---
title: How does the playground work?
description: 'The playground re-runs your real agents from Studio: Studio sends a command, weft/runtime in your process runs it with your tools and keys, and side effects are substituted or parked unless a tool is vouched safe.'
url: https://weftgo.dev/docs/observe/playground/overview/
type: concept
sources:
  - 'weft/runtime/doc.go:1-6 (the playground''s in-app side: Studio asks, the runtime answers), 21-60 (Safety: off unless WEFT_ENV=dev or Enabled(true); commands only narrow; side effects never re-fire silently; substitute, park, allow), 61-73 (default-deny ParkAllExcept; ToolSource and Subagent children; SUBAGENT_PENDING), 75-83 (re-validation; bounded link state), 84-101 (engines live and scripted; thread ephemeral and fork), 102-109 (run metadata; budgets never touch the app''s runs)'
  - 'weft/studio/README.md:1662-1667 (the playground: the app dials out; setup A five lines; runtime/examples/local), 1675-1695 (Studio''s side: GET /api/runtimes, POST /api/playground/runs and its validation table, GET /api/playground/commands/{id}, the runtime link''s routes, heartbeat_ms, safety), 1740-1755 (P1–P5 on one command: edits, scripted, fork, approvals, fixtures, experiments), 1813-1822 (both surfaces render them)'
  - 'weft/AGENTS.md:43-44 (block 1: weft.Replay(weft.ReplaySafe); unannotated counts as never), 477-478 (block 7a), 495-499 (side_effects substitute | park | allow), 515-518 (weft.playground, never weft.session.id; engines; thread modes), 529-538 (Studio side: studio.Playground(true) and its routes), 545-550 (the panel drawer and /playground; the option lab)'
  - 'weft/core/tool.go:719-766 (ReplayPolicy, ReplayNever, ReplaySafe, Replay: the last option wins; ToolDef.ReplayPolicy)'
  - weft/facade.go:1940-1959 (the root's ReplayPolicy, ReplayNever, ReplaySafe, Replay)
  - 'weft/example_test.go:1073 (ExampleReplay: lookup safe, refund never)'
  - 'weft/studio/studio.go:156-161 (Playground), 317-321 (Server.Runtime: nil without Playground)'
  - weft/studio/routes.go:329-336 (RuntimeServer, an alias of studio/runtime's)
  - 'weft/studio/playground.go:63-156 (registerPlayground: the routes and the capabilities playground, runtimes, preview, breakpoints, steer, cancel), 204-392 (servePlaygroundRun: the status table), 700-769 (checkRegistered: narrowing; allow refused unless every tool left on is opted in or safe)'
  - weft/studio/runtime/runtime.go:17-24 (the command lifecycle), 560-696 (RuntimeView, AgentView, ToolView)
  - 'weft/runtime/registry.go:266-274 (allowedTools: the except-list of the default-deny park rule)'
  - 'weft/studio/web/src/routes/playground.tsx:318-322 (the /playground route), 431 (no playground: the off line)'
  - weft/studio/web/src/components/studio/experiment-form.tsx:183-198 (the ⚠ on a never-class tool and its title), 205-205 (the side-effect select's labels)
  - 'weft/docs/adr/0029-replay-input.md (decision 1: the prefix is what the model saw; decision 5: a child run is its own source)'
  - 'weft/CHANGELOG.md:3219 (Replay: the last option wins), 3456 (allow accepts a ReplaySafe tool not opted in), 3507 (default-deny ParkAllExcept; ToolSource and child tools park; submit_output runs; weft.override.park_all_except), 3517 (fork mode), 3526 (scripted never runs live; breakpoints never substituted; the substitute chain), 3548 (fork sessions under the writer lease, the 64-fork bound), 3558 (AllowSideEffects only under allow), 4276 (ReplayPolicy; the manifest''s replay_policy), 4475 (the executor''s run options and labels; the source transcript order), 4498 (P1–P5 on both surfaces), 4509 (the /playground page), 4616 (studio/playground.go''s routes and validation table)'
  - docs-site/examples/playground/main_test.go:TestRuntimeRegisters (side_effects safe/never), TestNeverToolIsSubstitutedOrParked (substitute answers, park parks, refund never re-runs), TestAllowIsRefusedUnlessOptedIn, TestReplayFromStep (forked_from, no session id)
  - 'observed: the example program''s GET /api/runtimes and /playground at v0.17.0 (labels quoted below)'
  - 'weft/core/tool.go:761-766 (ReplayPolicy(): anything not safe reports never)'
  - 'weft/runtime/executor.go:637-647 (stepLimit: the command''s max_steps, else the agent''s cap, else 64), 980-999 (forkSession: approve grants revoked, deny grants kept), 1409-1471 (run options incl. ToolChoice and ParkOn; weft.playground.breakpoints, weft.replay.view, weft.edits)'
  - weft/studio/web/src/routes/playground.tsx:2172-2202 (save as test; keep as prompt copies and, under proposals, proposes)
  - docs-site/factcheck/playground.md (findings 4, 6-11)
  - 'weft/runtime/executor.go:676-740 (the substitute chain: each leg a fresh newID("pg_") run with Messages and Resolve/ResolveError, no ResumeOf; the command''s run is the last leg), 1317 (ResumeOf only on the human-decision path), 1441-1473 (every leg carries weft.playground.command and weft.experiment.id)'
  - 'weft/obsdb/db.go:430-432 (parked: succeeded, pending > 0, no run resumed it)'
  - weft/studio/experiments.go:72-75 (run_count counts the experiment's top-level runs)
  - 'weft/CHANGELOG.md:138, 157 (0.19.0: the engine per command; Breaking: no engine means the command''s own choice)'
  - 'weft v0.20.2: weft/studio/runtime/runtime.go:667-678 (ToolView: side_effects is the replay class; approval for a RequireApproval tool, omitempty); weft/studio/web/src/lib/drawer-spec.ts:62-71 (SIDE_EFFECT_TOOL, NEEDS_APPROVAL, NEEDS_APPROVAL_HINT), 74-75 (BREAKPOINTS_MOVED); weft/studio/web/src/components/studio/experiment-form.tsx:190-197 (needs approval beside the ⚠); weft/studio/web/src/components/studio/breakpoints.tsx:17-30 (BreakpointsPointer); weft/CHANGELOG.md:51 (0.20.0: approval: true, needs approval), 136 (0.19.0: Break on moved to /runtimes)'
---

# How does the playground work?

The [playground](https://weftgo.dev/docs/reference/glossary/#playground) re-runs your real agents from Studio. Studio sends a [command](https://weftgo.dev/docs/reference/glossary/#command); the package [`weft/runtime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime) in your process runs it as an ordinary weft run of an agent you registered, with your tools, your model keys and your code. Studio never runs your agent. A replay keeps a recorded prefix, applies your changes, and runs the rest fresh, and a tool with side effects is never fired again silently: its call is answered from the record or parked, unless the tool's code vouched it safe.

That vouching is one tool option. A read is marked safe; a refund is left unannotated, which counts as never, in `playground/main.go`:

```go title="playground/main.go"
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
	func(ctx context.Context, in OrderInput) (string, error) {
		return `{"order_id":"` + in.OrderID + `","status":"shipped"}`, nil
	},
	weft.Replay(weft.ReplaySafe), // a read: a replay may run it for real, in every mode
)
refund := weft.Tool("refund", "Refund an order.",
	func(ctx context.Context, in OrderInput) (string, error) {
		refundsIssued.Add(1) // stands in for the payment provider's call
		return "refunded order " + in.OrderID, nil
	}) // unannotated: ReplayNever, so a replay never re-fires it
```

[playground/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/playground/main.go)

`lookup_order` runs for real in every replay. `refund` never does unless you opt it in and ask for it.

## How it works

Your app dials Studio out over the [runtime link](https://weftgo.dev/docs/reference/glossary/#runtime-link); Studio never listens for it or calls into your process. In setup A the link is in-process; with `weft studio` it is HTTP to `127.0.0.1:7331`. [Connect your app](https://weftgo.dev/docs/observe/playground/connect/) has both.

| Step | Who | What happens |
|---|---|---|
| 1 | your app | `runtime.Install` registers each agent: its manifest, tools and their side-effect classes, the model alternates, the budget |
| 2 | you, in Studio | you pick a source run and a step, change the prompt, tools, model or a recorded result, and press Run |
| 3 | Studio | `POST /api/playground/runs` checks the command against the registration, then puts it on the runtime's stream |
| 4 | the runtime | it re-validates everything, acks the command, then runs it as a run of your agent |
| 5 | the pipeline | the run's events, transcript and spans reach Studio through `weft/otel`, like any other run, labelled `weft.playground` |

The runtime is the authority: whatever Studio checked, the runtime checks again against its own registration before the ack, and rejects anything it does not recognise rather than defaulting it. Commands can only narrow what the code allows. They can turn a tool off but never add one, choose a model only from the ones you registered or your resolver accepts, and lower `MaxSteps` and `Parallelism` but never raise them.

The link holds bounded state: at most 256 commands admitted and 16 runs executing at once, the newest 4,096 command ids for at-most-once, 128 parked runs and 64 forks. Stopping it cancels the runs it started.

The same commands drive two surfaces: Studio's [`/playground`](#the-playground-page) page and the devtools panel's experiment drawer. Each renders a control only for a capability Studio reports.

## Side effects

A [replay](https://weftgo.dev/docs/reference/glossary/#replay) re-runs model calls, and a model that called `refund` once will call it again. The command's `side_effects` field says what happens to such a call. It is one of three [modes](https://weftgo.dev/docs/reference/glossary/#side-effects-mode), and the playground form's select names them:

| `side_effects` | The form says | A never-class tool's call |
|---|---|---|
| `substitute` (the default) | substitute — recorded results, else park | answered with the recorded result when the source made the same call; any other call parks |
| `park` | park — every side-effect call waits | parks, every time: nothing is answered from the record |
| `allow` | allow — runs the tools this app opted in (AllowSideEffects) for real | the tools named in `runtime.AllowSideEffects` run for real; the command is refused unless every tool it leaves on is opted in or vouched safe |

A tool vouched with `weft.Replay(weft.ReplaySafe)` is no side effect: it runs in every mode, opted in or not. A tool opted in with `runtime.AllowSideEffects` runs for real only under `allow`; in `substitute` and `park` it is a side effect like any other.

**Substitute** matches by tool name and arguments, compared as canonical JSON. Repeated calls are answered in the order the source made them, and a recorded error stays an error. The runtime acts as the approval boundary's resolver ([ADR 0007](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0007-approval-boundary.md)): the run parks, and the runtime resumes it with `weft.Resolve` and the recorded content, as a new `pg_` run; earlier legs read `parked` ([gotcha](#best-practices--gotchas)). A miss stays parked for you to decide.

The chain's step budget is the command's `max_steps` override, else the agent's registered `MaxSteps`, else 64. The test `TestNeverToolIsSubstitutedOrParked` replays a run that refunded once: under `substitute` the replay finishes with the recorded result, under `park` it ends parked, and the refund handler runs zero more times.

The rule is default-deny. Each playground run lists the tools that may execute: the vouched-safe ones, an `Output` agent's `submit_output`, and under `allow` the opted-in names. Every other call parks, matched by name against each step's own tool set. The run carries that list as `weft.override.park_all_except`. So a tool that reaches the run only through `weft.ToolSource` parks like an unannotated one, and the rule follows a `weft.Subagent` delegation into the child run. A child's parked call is not yours to decide: the delegating call reads `SUBAGENT_PENDING` and the parent carries on, the side effect never having fired.

Studio checks `allow` before it sends: a tool left on that is neither opted in nor safe is a 403. From `TestAllowIsRefusedUnlessOptedIn`, where `refund` is on and only `send_email` is opted in:

```json
{"error":{"code":"forbidden","message":"tool refund is not opted in for real side effects"}}
```

Two parks are never substituted, whatever the mode: a [breakpoint](https://weftgo.dev/docs/observe/playground/breakpoints/) and a command's `park_on`.

## Mark tools replay safe

[`weft.Replay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Replay) sets a tool's [`weft.ReplayPolicy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplayPolicy), its side-effect class for re-runs. There are two values:

- [`weft.ReplayNever`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplayNever) is the default: an unannotated tool reports never through `ToolDef.ReplayPolicy`, as does any value other than safe. Nobody has vouched for it, so a re-run substitutes its call with the recorded result or parks it, and never fires it again silently.
- [`weft.ReplaySafe`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplaySafe) says the call is idempotent and side-effect free. A re-run may execute it for real.

Like every tool option the last one wins: `Replay(ReplayNever)` after `Replay(ReplaySafe)` is never's. [`ToolDef.ReplayPolicy`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.ReplayPolicy) reports the class; [`ExampleReplay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Replay) prints `lookup: safe` and `refund: never`. The manifest writes `replay_policy: "safe"` only for a safe tool, so an unannotated agent's `weft.json` does not change.

The runtime registers each tool's class, and `GET /api/runtimes` reports it with the tool's opt-in flag. For the example's agent:

```json
"tools":[{"name":"lookup_order","side_effects":"safe","allow":false},{"name":"refund","side_effects":"never","allow":false},{"name":"send_email","side_effects":"never","allow":false}]
```

`side_effects` is the replay class, not whether the tool has effects: `never` means a replay never re-runs it. Since 0.20.0 a tool built with `weft.RequireApproval` also carries `"approval": true` there (omitted otherwise), since every live call of it waits for a decision anyway.

The playground form and both replay drawers mark each never-class tool with ⚠, titled "side-effect tool (ReplayPolicy never): substituted or parked, never re-fired silently — only side effects: allow runs it, if the app opted it in". Beside the ⚠ of an approval tool they say **needs approval**, its hint that every live call waits for a decision and that `never` is the replay class. The other per-tool options are on [Set per-tool policy](https://weftgo.dev/docs/guides/tool-policy/#mark-a-tool-safe-to-re-run).

## Engines and threads

Two more fields shape a command. The [engine](https://weftgo.dev/docs/reference/glossary/#engine) decides who answers the model calls:

- **`live`** calls the agent's own model, or an alternate the command names.
- **`scripted`** answers each model call with the source run's recorded turn, at zero tokens. It is its own model over the source's transcript records, keyed like `wefttest` fixtures. When the input changed, a step misses loudly with "no recorded turn", so a prompt experiment is never answered with the old reply. An instructions or model override is refused with it outright, and so are transcript edits. A scripted command never runs on the live model. The run header reads "scripted · 0 tokens".

Since 0.19.0 Studio's forms choose the engine per command: `scripted` when the recording can answer, else `live`, and a form, link or saved experiment that names no engine means that choice, no longer `live` ([Choose the engine](https://weftgo.dev/docs/observe/playground/replay/#choose-the-engine)).

The `thread` mode decides where the run lives:

- **`ephemeral`** (the default) writes nothing to thread storage. The run is not a turn of any session: it never carries `weft.session.id`.
- **`fork`** needs `runtime.Threads(store)`. The source session is opened read-side and forked to a new session with lineage (`weft.session.forked_from`), and the command's input becomes the fork's next turn, so you keep chatting in it. The source's approve grants are revoked in the fork, so your app user's standing consent does not decide an experiment's call; standing denials stay. A later fork command naming the fork's latest turn continues it in place; one naming an earlier turn forks from there. A parked call in a fork is the fork session's own approval boundary, decided through it, and the record is never consulted there: every never-class call parks. Forking a source that is waiting on approval fails at once. The runtime holds each fork's `Session` and its writer lease until nothing needs it, then closes it, so another writer can continue that session.

Every run the runtime starts is an ordinary weft run through the `weft/otel` pipeline to every destination. It carries `weft.playground` (`true`), `weft.playground.command`, `weft.playground.actor`, `weft.experiment.id`, `weft.public_id` and `weft.forked_from` (`<source run>#<from_step>`). Its run options are plain ones: `weft.Instructions`, `weft.OnlyTools`, `weft.UseModel`, `weft.Thinking`, lower-only `weft.MaxSteps` and `weft.Parallelism`, `weft.Params`, `weft.ToolChoice`, `weft.ParkOn` (a command's `park_on` and the runtime's breakpoints), and the default-deny `weft.ParkAllExcept`. Some runs carry more metadata: `weft.playground.breakpoints` names which parks are the debugger's, and a replay carries `weft.replay.view` and, when edited, `weft.edits` ([Replay a run from any step](https://weftgo.dev/docs/observe/playground/replay/)). The source transcript is read from thread storage first, then the local sink, then Studio's `GET /api/runs/{id}/transcript`. A whole-turn re-run that sends no input reuses the source's own user message. The runtime's [breakpoints](https://weftgo.dev/docs/observe/playground/breakpoints/) park the runs it starts too.

## The playground page

Studio's `/playground` page is the playground's own surface. Open it from the sidebar's **Playground**, or with `?run=<id>&step=<n>` naming a source run and step. The devtools panel hands off into it with the run, the step and the current overrides as query parameters.

![Studio's playground over a recorded acme-support turn, on the acme-app runtime: variant A's source run, step, system prompt, tools, model, thinking, engine, side effects and where it writes, with the option fields below them and the experiment matrix beside the variant](https://weftgo.dev/docs/_astro/studio-playground.light.C_3iakPV.webp)

*The playground over a recorded source run: one variant's prompt, tools, model, engine and side-effect mode, and the experiment matrix beside it.*

The page holds:

- the agent and runtime picker, then **Variant A** with **+ variant**, **duplicate** and **remove**;
- **Source run**, **Continue from step**, and the **Transcript edits** of the kept steps;
- **System prompt**, **Tools**, **Model**, **Thinking**, **Engine**, **Side effects** and **Thread**;
- **Options**, the [option lab](https://weftgo.dev/docs/observe/playground/experiments/#the-option-lab): max steps, parallelism, temperature, top_p, max tokens, seed, stop, tool choice, only tools and park on, each showing the agent's default greyed;
- a link to the runtime's breakpoints on the [Runtimes page](https://weftgo.dev/docs/observe/playground/runtimes/#breakpoints), with the count in force ("breakpoints for the whole runtime live on Runtimes · 1 tool break on every run"); before 0.19.0 the form carried a **Break on** box;
- **Run A**, then a result card per run: its state, run id, tokens, latency, cost, reply, a diff against the source and a step-by-step compare;
- the **Experiment matrix** with **Run matrix**, and the experiment history.

A result card steers a run in flight and decides its parked calls ("approve", "deny", "resolve…"; "continue" and "skip" before 0.18.0). **save as test** downloads the run as a `wefttest` replay test, the run page's "save as test", and **keep as prompt** copies the variant's prompt text and, where Studio holds proposals (capability `proposals`), proposes it as the agent's prompt with `PUT /api/agents/{name}/proposal`. The panel's replay drawer carries the same approve, deny and resolve verbs for the runs it starts. A bare `/playground` over several agents asks you to pick one, or to paste a run id in Source run. A Studio without the playground says "This Studio has no playground and no debugger." The option lab is one form on both surfaces: a refusal is shown on its knob in the server's words and holds Run, and the server's 400 is still shown verbatim if it refuses anyway.

## The playground API

[`studio.Playground(true)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Playground) turns the routes and the runtime link server on. `weft studio` has it on by default (`--no-playground` turns it off). [`Server.Runtime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Server.Runtime) returns the link server's in-process side, a [`studio.RuntimeServer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#RuntimeServer), which `runtime.Local` takes; it is nil without the option, and so are the routes.

The routes fall into four groups, each behind a capability `GET /api/meta` reports:

- **commands** (`playground`): `GET /api/runtimes` lists what registered, `POST /api/playground/runs` sends one command, and `GET /api/playground/commands/{id}` follows its row. `POST /api/runs/{id}/approvals`, `POST /api/playground/fixtures` and the `/api/experiments` routes ride the same capability;
- **the preview** (`preview`): `POST /api/playground/preview`, the replay's first request without running it;
- **the debugger** (`breakpoints`, `steer`, `cancel`): `PUT /api/runtimes/{id}/breakpoints`, `POST /api/runs/{id}/steer`, `POST /api/runs/{id}/cancel`;
- **the runtime link** (`runtimes`): `POST /api/runtime/register`, `GET /api/runtime/commands` and `POST /api/runtime/acks`, server-to-server and refused to every panel token.

`POST /api/playground/runs` checks a command before it reaches your process and answers with a fixed set of statuses. It is 400 for an unknown name or a malformed command, 403 for a widening, 404 for an unknown runtime, agent or source run, 409 for a reused command id, and 503 when the runtime holds no command stream. Each how-to page shows the refusals its task meets. Every route, status and body is listed on [Studio's HTTP API](https://weftgo.dev/docs/reference/studio-api/).

## What it does not do

- **It does not run your agent in Studio.** No model call, tool call or prompt leaves Studio for a provider. Your process does all of it, and a stopped process runs nothing.
- **It does not widen your code.** No tool, model or higher limit can be added from Studio.
- **It does not touch your app's own runs**, except through what you opt into: [`runtime.Breakpoints()`](https://weftgo.dev/docs/observe/playground/breakpoints/) on an agent, and `runtime.Sessions` for your thread turns ([Approve and steer your app's own turns](https://weftgo.dev/docs/observe/devtools/app-turns/)). A budget breach rejects the next experiment command, never your own runs.
- **It does not make a model deterministic.** A replay is exact up to the model's input ([ADR 0029](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0029-replay-input.md)): what a live model answers is new.

## Complete example

The program records one run of the support agent in setup A and registers the agent with the embedded Studio's playground:

```go title="playground/main.go"
// Command playground is the Playground pages' program: setup A with the
// playground on. It records every run into the local sink, serves Studio
// over the same handle with studio.Playground(true), registers one support
// agent through runtime.Local, and runs that agent once so the playground
// has a source run to replay.
//
//	go run ./playground [-addr 127.0.0.1:8080]
//
// It prints Studio's URL and the source run's id, then serves until
// Ctrl-C. The other functions are the pages' variants: runtime.Studio for
// a weft studio binary, a model resolver, and an agent built with
// runtime.Breakpoints(). main_test.go runs each of them offline.
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"net"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"sync/atomic"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/runtime"
	"github.com/weftgo/weft/studio"
	"github.com/weftgo/weft/wefttest"
)

// OrderInput is the input of every order tool.
type OrderInput struct {
	OrderID string `json:"order_id" jsonschema:"the order to act on"`
}

// EmailInput is send_email's input.
type EmailInput struct {
	To   string `json:"to" jsonschema:"the recipient"`
	Body string `json:"body" jsonschema:"the message"`
}

// refundsIssued and emailsSent count the handlers that really ran: the
// tests read them to prove a replay did or did not fire a side effect.
var refundsIssued, emailsSent atomic.Int64

// supportTools are the agent's three tools, one per side-effect class.
func supportTools() []weft.Option {
	lookup := weft.Tool("lookup_order", "Look up an order by ID.",
		func(ctx context.Context, in OrderInput) (string, error) {
			return `{"order_id":"` + in.OrderID + `","status":"shipped"}`, nil
		},
		weft.Replay(weft.ReplaySafe), // a read: a replay may run it for real, in every mode
	)
	refund := weft.Tool("refund", "Refund an order.",
		func(ctx context.Context, in OrderInput) (string, error) {
			refundsIssued.Add(1) // stands in for the payment provider's call
			return "refunded order " + in.OrderID, nil
		}) // unannotated: ReplayNever, so a replay never re-fires it
	email := weft.Tool("send_email", "Email the customer.",
		func(ctx context.Context, in EmailInput) (string, error) {
			emailsSent.Add(1)
			return "sent to " + in.To, nil
		})
	return []weft.Option{lookup, refund, email}
}

// newAgent is the support agent the runtime registers. extra adds
// options a variant needs (runtime.Breakpoints, below).
func newAgent(model weft.Model, extra ...weft.Option) *weft.Agent {
	return weft.New(model,
		weft.Name("acme-support"),
		weft.Instructions("You are Acme's support agent."),
		weft.MaxSteps(10),
		weft.Options(supportTools()...),
		weft.Options(extra...),
	)
}

// newDebuggableAgent is the agent built with runtime.Breakpoints(): the
// breakpoints Studio sets park its own runs too, not only the runs the
// runtime starts.
func newDebuggableAgent(model weft.Model) *weft.Agent {
	agt := weft.New(model,
		weft.Name("acme-support"),
		weft.Options(supportTools()...),
		runtime.Breakpoints(), // Studio's breakpoints park this agent's own runs too
	)
	return agt
}

// resolveModel is the app's ModelResolver: a model a command names that
// runtime.Models does not list reaches it before the command is acked.
//
func resolveModel(ctx context.Context, name string) (weft.Model, error) {
	model, ok := strings.CutPrefix(name, "acme/")
	if !ok {
		// The text is the rejected command's reason: no key, no URL.
		return nil, errors.New("this app serves acme/* models only")
	}
	return newProviderModel(model), nil // build the client from the app's own credentials
}

// newProviderModel stands in for a provider adapter (anthropic.Model,
// openai.Model, …): a scripted model, so the program runs offline.
func newProviderModel(name string) weft.Model {
	return wefttest.Script(wefttest.Say("(" + name + ") Your order shipped yesterday."))
}

// installStudio registers agt with a Studio reached over HTTP: the weft
// studio binary (setup B) or a hosted one (setup C). It opens the link
// only under WEFT_ENV=dev.
func installStudio(studioURL, token string, agt *weft.Agent, alt weft.Model) (shutdown func()) {
	shutdown = runtime.Install(
		runtime.Studio(studioURL, token),                         // the Studio to dial, and its token
		runtime.Agents(agt),                                      // the agents experiments may run
		runtime.Models(map[string]weft.Model{"acme-small": alt}), // alternates, by display name
		runtime.ModelResolver(resolveModel),                      // any other model name: the app decides
		runtime.Limits(runtime.Budget{MaxTokensPerExperiment: 200_000, MaxRunsPerExperiment: 2}),
		runtime.AllowSideEffects("send_email"), // runs for real only under side_effects "allow"
	)
	return shutdown
}

// installLocal is setup A: Studio embedded in the app over the local
// sink's handle, and the runtime link talking to it in-process.
func installLocal(agt *weft.Agent) (h http.Handler, stop func()) {
	srv := studio.New(studio.DB(otel.LocalDB()), studio.Playground(true))
	shutdown := runtime.Install(
		runtime.Local(srv), // the embedded Studio, in-process: no socket
		runtime.Agents(agt),
		runtime.Enabled(true), // open the link without WEFT_ENV=dev
	)
	return srv.Handler(), func() { shutdown(); _ = srv.Close() }
}

// demoScript answers the source run (a lookup, then a reply) and a few
// experiments after it, so the playground can run them offline.
func demoScript() weft.Model {
	turns := []wefttest.Turn{
		wefttest.ToolCalls(wefttest.Call{ID: "c1", Name: "lookup_order", Args: `{"order_id":"4411"}`}),
		wefttest.Say("Order 4411 shipped yesterday."),
	}
	for range 20 {
		turns = append(turns, wefttest.Say("Order 4411 shipped yesterday. Track it at acme.example/t/4411."))
	}
	return wefttest.Script(turns...)
}

// start records the source run and returns Studio's handler with the
// runtime registered.
func start(ctx context.Context) (h http.Handler, sourceRun string, stop func(), err error) {
	agt := newAgent(demoScript())
	h, stopLink := installLocal(agt)
	res, err := agt.Generate(ctx, weft.Prompt("Where is my order #4411?"))
	if err != nil {
		stopLink()
		return nil, "", nil, err
	}
	return h, res.ID, stopLink, nil
}

func main() {
	addr := flag.String("addr", "127.0.0.1:8080", "the loopback address to serve Studio on")
	flag.Parse()
	defer otel.Install(otel.Local(""))() // ./.weft/weft.db (or $WEFT_DB), content on

	ctx := context.Background()
	h, source, stop, err := start(ctx)
	if err != nil {
		fmt.Fprintln(os.Stderr, "playground:", err)
		os.Exit(1)
	}
	defer stop()

	ln, err := net.Listen("tcp", *addr)
	if err != nil {
		fmt.Fprintln(os.Stderr, "playground:", err)
		os.Exit(1)
	}
	mux := http.NewServeMux()
	mux.Handle("/studio/", http.StripPrefix("/studio", h))
	fmt.Println("playground: http://" + ln.Addr().String() + "/studio/playground")
	fmt.Println("source run:", source)
	go func() { _ = http.Serve(ln, mux) }()

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	<-c
}
```

[playground/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/playground/main.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/playground) · run it from `docs-site/examples`:

```sh
go run ./playground
go test ./playground
```

```text
playground: http://127.0.0.1:8080/studio/playground
source run: dd66354adfaac2b44848f0c1ed75516f
```

Open the URL with `?run=` and the source run's id to replay it.

## Best practices & gotchas

- **Mark every read `weft.Replay(weft.ReplaySafe)`.** An unannotated read parks or is substituted like a refund, so a replay that changes its arguments stops at it. (Source: `weft.ReplayPolicy` godoc; `runtime/doc.go:31-33`)
- **Name a tool in `AllowSideEffects` only when re-running it is harmless.** Names match wherever the run reaches, a `ToolSource` tool or a subagent child's tool of the same name included. (Source: `runtime.AllowSideEffects` godoc)
- **Expect a replay to stop at a call the source did not make.** Substitute answers only the same tool with the same arguments; anything else parks for a decision. (Source: `runtime/doc.go:36-43`; the example's `TestNeverToolIsSubstitutedOrParked`)
- **Expect one substitute command to list as several runs.** Each leg of the substitute chain is its own `pg_` run with the command's labels, `weft.experiment.id` included. The legs before the last stay `parked`: `weft runs --status parked` and `/api/runs?status=parked` list them though nobody has to decide them, and an experiment's `run_count` counts each leg. The command's result names the last leg. (Source: `runtime/executor.go:676-740, 1317, 1441-1473`; `obsdb/db.go:430-432`)
- **A subagent's side effect is not yours to decide from the parent.** The child parks; the parent sees `SUBAGENT_PENDING` and continues. Replay the child as its own source instead. (Source: `runtime/doc.go:66-73`; ADR 0029 decision 5)

## See also

- [Connect your app to Studio's playground](https://weftgo.dev/docs/observe/playground/connect/)
- [Replay a run from any step, with edits](https://weftgo.dev/docs/observe/playground/replay/)
- [Run experiments with the option lab](https://weftgo.dev/docs/observe/playground/experiments/)
- [Pause runs at breakpoints, then steer or cancel them](https://weftgo.dev/docs/observe/playground/breakpoints/)
- [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/)

Symbols used: [`weft.Replay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Replay) · [`weft.ReplayPolicy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplayPolicy) · [`weft.ReplayNever`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplayNever) · [`weft.ReplaySafe`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplaySafe) · [`ToolDef.ReplayPolicy`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.ReplayPolicy) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.ParkAllExcept`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkAllExcept) · [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`runtime.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Install) · [`runtime.AllowSideEffects`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#AllowSideEffects) · [`runtime.Threads`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Threads) · [`runtime.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Local) · [`studio.Playground`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Playground) · [`studio.RuntimeServer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#RuntimeServer) · [`Server.Runtime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Server.Runtime) · [`weft.Resolve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Resolve) · [`weft.ResumeOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResumeOf)
