---
title: Connect your app to Studio's playground (weft/runtime)
description: 'Register your agents with Studio''s playground in one deferred runtime.Install call: the Studio to dial, the agents, model alternates, a resolver, per-experiment budgets and the tools allowed to run for real.'
url: https://weftgo.dev/docs/observe/playground/connect/
type: how-to
sources:
  - 'W11-auditB2-fix, v0.20.2: weft/runtime/link.go:541-557 (contain: rejected before the accepted ack, finished failed after)'
  - 'weft/runtime/options.go:19 (Option), 40-57 (Studio: the endpoint fallback order), 59-66 (Local: in-process; a Token-gated server needs Studio("", token)), 68-74 (Agents: a nameless agent is skipped with a WARN), 76-90 (Models), 92-119 (ModelResolver: before the ack, 10 s, the error text), 121-136 (Budget, Limits), 138-164 (AllowSideEffects), 166-174 (Threads), 248-254 (Enabled), 256-345 (Install: dials out, never panics, the WARN cases, the cleartext WARN, the shutdown)'
  - weft/runtime/doc.go:8-19 (the one deferred call), 21-24 (WEFT_ENV=dev or Enabled(true)), 75-83 (re-validation; bounded state)
  - weft/runtime/example_test.go:18 (ExampleInstall), 43 (ExampleModelResolver)
  - weft/runtime/examples/local/main.go:1-14 (setup A's playground in one process, the P0 curl gate), 34 (127.0.0.1:7331), 136-141 (runtime.Install)
  - 'weft/runtime/link.go:38-60 (maxRunning 16, maxFrameBytes, register 15 s, headers 30 s, healthy stream 10 s), 579-639 (dispatch: validate, budget, the accepted ack before the run, heartbeat, finished ack), 819-857 (ackRefused, ackUnconfirmed, notConfirmed), 906-927 (ackHeartbeat: a minute; heartbeat), 1053-1077 (backoff: 0.5 s doubling to 30 s, jittered)'
  - weft/runtime/executor.go:27-46 (validate under validateTimeout), 351-363 (resolveTimeout 10 s, validateTimeout 25 s)
  - 'weft/runtime/registry.go:192-197 (env is WEFT_ENV), 235-252 (stableRuntimeID: rt_ + 16 hex of sha256 over service, cwd and agents; serviceName)'
  - 'weft/runtime/wire.go:20-65 (the registration: runtime_id, host, pid, cwd, instance, service, env, weft_version, budget, threads, sessions, breakpoints_own, breakpoints, agents, heartbeat_ms)'
  - weft/studio/runtime/runtime.go:17-49 (the lifecycle, the two timers, heartbeats, WithStore, stable ids and <id>-<pid>), 533-558 (the states; CommandStatus), 882-886 (AckDeadline 30 s, FinishDeadline 10 min)
  - weft/studio/README.md:1664-1695 (the link's routes, heartbeat_ms, the finish watch)
  - 'weft/AGENTS.md:477-495 (block 7a: Install and its options, WEFT_ENV, the discovery rule, the ack rules, the heartbeat), 503-515 (stable runtime ids, <id>-<pid>, obsdb.CommandStore, /api/runtimes connected)'
  - 'weft/CHANGELOG.md:2570 (runtime/examples/local on 127.0.0.1:7331), 3541 (the link: stop, bounds, backoff, timeouts, oversized frames, breakpoints and error on acks), 3564 (Local addresses Studio as http://localhost), 4209 (registration reports weft_version), 4459 (the module, one deferred call, WEFT_ENV=dev or Enabled(true), otel.StudioEndpoint()), 4468 (the link: register, SSE with Last-Event-ID, ack before executing, cancel and ping, Local in-process)'
  - weft/otel/pipeline.go:527-529 (StudioEndpoint reports the last Studio destination built)
  - docs-site/examples/playground/main_test.go:TestRuntimeRegisters, TestInstallStudioRegisters (WEFT_ENV=dev opens the link; without it nothing connects), TestReplayFromStep (409 on a reused command id), TestOverrideRefusalsNameTheirRule (the resolver's refusal)
  - 'observed: GET /api/runtimes and GET /api/playground/commands/{id} against the example program (go run ./playground) at v0.17.0'
  - 'weft/runtime/executor.go:229-235 (model <name>: resolver timed out after <bound>)'
  - weft/runtime/options.go:291 (only an empty Agents list stops Install), 339-347 (the link starts)
  - 'weft/studio/runtime/runtime.go:968-969 (register body: no agents), 2265-2265 (prune: FinishDeadline after last_seen, Retention 24 h with breakpoints), 885 (Retention 24 h)'
  - weft/otel/pipeline.go:223-232, weft/otel/env.go:158-176 (the pipeline's Studio may come from the discovery file)
  - 'weft/runtime/registry.go:255-263 (serviceName: OTEL_SERVICE_NAME, else the binary''s name)'
  - docs-site/factcheck/playground.md (findings 1, 2, 12-17)
  - 'observed: the example built as playground, run twice from one directory, registered as rt_6ea843dccc7741ff both times'
  - 'weft/runtime/options.go:292-296 (WARN Install without agents: no link opened, its hint), 322-323 (INFO joined the running Studio), 326-330 (WARN no Studio to dial), 331-334 (WARN the Studio token travels unencrypted over http to a non-loopback host, hint use an https Studio URL), 339-344 (WARN link failed to start, err), 350-363 (cleartext: http, not localhost, not a loopback IP)'
  - 'weft/runtime/link.go:167-184 (start: always returns nil; the retry loop), 234-251 (connect: register failed; retrying and command stream ended; reconnecting at Debug), 300-309 (a 401 or 403 at register: WARN Studio refused the runtime link, once per link, status and hint; the error weft/runtime: register: <status>)'
  - 'W11-auditB1-fix, v0.20.2: weft/runtime/options.go:303-312 (WARN the pipeline records only into a Local store: no link opened); weft/runtime/link.go:383-394 (undecodable run command, rejected undecodable command), 466-472 (command frame without a usable id ignored), 541-553 (command panicked; internal error in the runtime (see its log)), 604-614 (the accepted ack was not taken; the command is not run), 753-756 (… the decision is not held), 767-775 (… the decision is not applied), 860-889 (ack failed, ack unconfirmed (5xx), ack refused), 830 (notConfirmed), 900-905 (settleUnconfirmed), 240-250, 451, 482, 648, 871, 944, 1137-1154 (Debug lines); weft/runtime/sessions.go:106-111 (… the session is not written), 133-151 (session command failed); weft/runtime/executor.go:270-279 (source transcript unresolved), 789-795 (fork command failed), 1024-1027 (forked session not released), 1093-1102 (playground run failed), 1294-1297 (fork resume failed); weft/runtime/transcript.go:185-196, 244-247, 303-306 (the compaction-view lines); weft/runtime/registry.go:57-64 (manifest for agent failed); weft/runtime/transport.go:55-66 (in-process Studio handler panicked, 500)'
  - weft/runtime/registry.go:38 (WARN agent without core.Name is not playable, its hint)
  - 'observed: a scratch program over weft v0.17.0 with a Debug text handler logged Install without agents (no runtime.Agents), the unencrypted-token WARN (runtime.Studio("http://192.0.2.1:7331", token)), and against a weft studio with the wrong token one WARN Studio refused the runtime link … status="401 Unauthorized" followed only by DEBUG register failed; retrying err="weft/runtime: register: 401 Unauthorized"'
---

# Connect your app to Studio's playground (weft/runtime)

[`runtime.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Install) registers your agents with a Studio and opens the [runtime link](https://weftgo.dev/docs/reference/glossary/#runtime-link), the connection Studio's playground sends commands over. It is one deferred call in `main`. It opens a link only under `WEFT_ENV=dev` or with [`runtime.Enabled(true)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Enabled), so a production binary exposes nothing unless it opts in.

Register the support agent with a `weft studio`, in `playground/main.go`. This is the program's setup-B variant, `installStudio`: the test `TestInstallStudioRegisters` runs it, while `go run ./playground` uses the setup-A variant [below](#setup-a-playground):

```go title="playground/main.go"
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"
)
```

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

With `WEFT_ENV=dev`, open Studio's **Playground**: the agent is in the picker, with its tools and the `acme-small` alternate. Call the returned function on exit: it ends the command stream, cancels the runs the link started, and waits (bounded) for both.

## Install

`runtime.Install` dials out and never listens, so it works behind NAT. It never panics and never fails the program. When it cannot build a runtime, it logs one WARN and opens nothing: no agents given, or no Studio to dial. [Link log lines](#link-log-lines) lists each line. Each [`runtime.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Option):

| Option | Effect |
|---|---|
| [`runtime.Studio(url, token)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Studio) | dial the Studio at `url` with its API `token` (setups B and C): `weft studio`'s dev token, or a hosted Studio's server token |
| [`runtime.Local(srv)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Local) | talk to the embedded `*studio.Server` in-process, no socket (setup A, [below](#setup-a-playground)) |
| [`runtime.Agents(agents...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Agents) | the agents experiments may run; only registered agents are playable |
| [`runtime.Models(map)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Models) | the model alternates a command may switch to, by display name |
| [`runtime.ModelResolver(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#ModelResolver) | any other model name a command proposes: your code decides, before the ack |
| [`runtime.Limits(runtime.Budget{…})`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Limits) | per-experiment caps ([Budgets](https://weftgo.dev/docs/observe/playground/experiments/#budgets)) |
| [`runtime.AllowSideEffects(tools...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#AllowSideEffects) | tools that run for real under `side_effects: "allow"` ([below](#side-effects)) |
| [`runtime.Threads(store)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Threads) | the thread storage transcripts resolve through first; fork mode needs it ([below](#thread-stores)) |
| [`runtime.Sessions(resolve)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Sessions) | your app's own thread turns take approvals and steer from Studio ([Approve and steer your app's own turns](https://weftgo.dev/docs/observe/devtools/app-turns/)) |
| [`runtime.Enabled(on)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Enabled) | open (or forbid) the link whatever `WEFT_ENV` says |

Without `runtime.Studio` or `runtime.Local`, Install picks the Studio in this order:

1. The pipeline's own Studio destination, [`otel.StudioEndpoint()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#StudioEndpoint): the one `otel.Studio(url, token)` or `WEFT_STUDIO_URL` names, or the discovery file's Studio when the pipeline itself joined it. With both set to different URLs, it reports the environment's ([Send runs to Studio](https://weftgo.dev/docs/observe/destinations/)).
2. The [discovery file](https://weftgo.dev/docs/reference/glossary/#discovery-file) a running `weft studio` or `weft dev` wrote. It is never read when `WEFT_STUDIO_URL` is set or `WEFT_DISCOVERY=off`, and a stale file is never trusted. One INFO line names the Studio it joined.
3. None: a WARN, and no link.

So under `weft dev`, which sets `WEFT_ENV=dev`, `WEFT_STUDIO_URL` and `WEFT_STUDIO_TOKEN` for the app, `defer otel.Install()()` followed by `runtime.Install(runtime.Agents(agt))` is enough: the pipeline's Studio destination comes from the environment, and the link dials it. Without an installed pipeline, `WEFT_STUDIO_URL` alone names no Studio here, and since it is set the discovery file is not read either. A token sent over plain `http` to a host that is not this machine logs a WARN; use an `https` URL.

[`ExampleInstall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#example-Install) builds the whole call with `runtime.Enabled(false)`, so it stays inert.

## Agents and models

[`runtime.Agents`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Agents) names the agents a runtime exposes. An agent without a [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) cannot register, since its manifest would be nameless: it is skipped with a WARN. A duplicate name keeps the first.

[`runtime.Models`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Models) maps display names to [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Model) values: the allow-list the playground's model picker reads. A command that names any other model is refused unless the runtime has a resolver. Studio's 400 says so:

```json
{"error":{"code":"bad_request","message":"unknown model gpt-x: neither the agent's own nor a registered alternate (register it with runtime.Models or add runtime.ModelResolver)"}}
```

[`runtime.ModelResolver`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#ModelResolver) lets a command name a model you did not list. The name reaches your function while the command is validated, before its ack. A model back runs the command, named on the run's `RunStart.Model` and `weft.override.model`. An error rejects it with `model <name>: <your error's text>`. The example's resolver serves `acme/*` names only:

```go title="playground/main.go"
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
}
```

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

From `TestOverrideRefusalsNameTheirRule`, a command with `"model": "openai/gpt-4.1"` ends on this row:

```json
{"command_id":"cmd_01M5762FSQ3FJRC546TNRPVTH6","state":"rejected","run_id":"","error":"model openai/gpt-4.1: this app serves acme/* models only","created":"2026-10-18T11:39:18.45590157+02:00","updated":"2026-10-18T11:39:18.456083956+02:00"}
```

The error text is shown to whoever ran the experiment: put no key, URL or secret in it. Each call is bounded at 10 s; past it the command is rejected with `model <name>: resolver timed out after 10s`, and a resolver that ignores `ctx` is abandoned, its late result dropped. The resolver may be called concurrently and once per command, so cache clients that are costly to build. The registration reports `resolver: true`, and only then does Studio accept an unlisted name. [`ExampleModelResolver`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#example-ModelResolver) refuses every name that is not `anthropic/claude-*`.

## Side effects

[`runtime.AllowSideEffects`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#AllowSideEffects) opts tools in to running for real in a playground run, and only when the command asks for `side_effects: "allow"`. Under `substitute` (the default) and `park` an opted-in tool is a side effect like any other. A tool marked `weft.Replay(weft.ReplaySafe)` needs no opt-in: it runs in every mode. `"allow"` runs this list for real; it does not widen it. A command that asks for it is refused unless every tool it leaves on is named here or vouched safe. The modes are explained on [How does the playground work?](https://weftgo.dev/docs/observe/playground/overview/#side-effects).

Names match wherever the run reaches: a tool a `weft.ToolSource` supplies under that name, and a tool of that name in a `weft.Subagent` child. Name a tool only when re-running it is harmless everywhere that name appears. `GET /api/runtimes` marks an opted-in tool `"allow": true`.

## Thread stores

[`runtime.Threads`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Threads) sets the [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage) the runtime reads a source run's transcript through first. Readers never lock, so a session your app holds open is readable. Without it the runtime is ephemeral-only: it resolves transcripts from the local sink, then from Studio, and a `"thread": "fork"` command is refused:

```json
{"error":{"code":"bad_request","message":"fork mode needs runtime.Threads(store) on this runtime"}}
```

Pass the same store your app's sessions use. A nil store is ignored.

## Setup A playground

In [setup A](https://weftgo.dev/docs/reference/glossary/#setup-a-b-c) Studio is embedded in your app. Build it with `studio.Playground(true)` and hand the server to [`runtime.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Local):

```go title="playground/main.go"
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
)
```

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

The link then talks to `srv`'s handler in-process: no socket, and it addresses Studio as `http://localhost`, which setup A's loopback guard accepts. `runtime.Enabled(true)` opens it without `WEFT_ENV=dev`. In-process is not exempt from the server's own token: a Studio built with `studio.Token(tok)` needs `runtime.Studio("", tok)` beside `runtime.Local(srv)`. Close the server after the link stops; `Server.Close` stops the link server's timers too ([Run Studio](https://weftgo.dev/docs/observe/studio/setup/#embed-studio)).

weft's [`runtime/examples/local`](https://github.com/weftgo/weft/tree/v0.20.2/runtime/examples/local) is the same in one process, drivable with curl. It serves Studio on `127.0.0.1:7331`, runs the agent once, and prints the command to replay that run from step 1:

```sh
go run ./runtime/examples/local -addr 127.0.0.1:7331
```

Run it from a clone of weft at `v0.20.2`. It dials its own Studio over `runtime.Studio(url, "")` rather than `runtime.Local`, so it shows setup B's path inside one process.

## The link

The link registers on connect and again after every reconnect, so the copy Studio validates against is always the runtime's own. The registration carries the runtime's id, host, pid, working directory, service, `env` (the value of `WEFT_ENV`), `weft_version`, budget, whether it has `Threads` and `Sessions`, `breakpoints_own`, its current breakpoint set, `heartbeat_ms`, and per agent its manifest, model alternates, `resolver` flag, run defaults and every tool's side-effect class and opt-in flag. Then it holds a server-sent-events stream, resuming with `Last-Event-ID`. The stream's frames are `run` (a command), `approve` (a decision on a parked run), `cancel`, `steer`, `breakpoints`, `session` (a verb on the app's own turn) and `ping`. The runtime acks every command and decision.

`GET /api/runtimes` lists what registered. Against the example program, built as `playground` (the binary name `go run ./playground` uses, so the `service` reads `playground`):

```sh
curl -s http://127.0.0.1:8080/studio/api/runtimes
```

```json
{"runtimes":[{"id":"rt_6ea843dccc7741ff","host":"build-01","pid":2780635,"cwd":"/tmp/…/pg-run","service":"playground","env":"","connected_since":"2026-10-18T12:13:05.339774429+02:00","last_seen":"2026-10-18T12:13:05.339842618+02:00","connected":true,"sessions":false,"breakpoints_own":false,"agents":[{"name":"acme-support","models":[],"resolver":false,"defaults":{"max_steps":10,"parallelism":4,"thinking":"","tool_choice":{"mode":"auto"}},"tools":[{"name":"lookup_order","side_effects":"safe","allow":false},{"name":"refund","side_effects":"never","allow":false},{"name":"send_email","side_effects":"never","allow":false}],"instructions":"You are Acme's support agent."}],"breakpoints":[]}]}
```

(The `cwd` is shortened here.) `connected` says whether the runtime holds a live command stream now. A runtime whose stream dropped stays listed with `connected: false` while it has unresolved commands, then 10 minutes more after it was last seen (24 hours while it holds a breakpoint set), and a reconnect re-registers under the same id. `cwd` is served only to the dev token or setup A's loopback; a read-scoped panel token gets no `instructions`.

**Runtime ids are stable** per service, working directory and agent set: `rt_` and 16 hex digits of a SHA-256 over the three. The service is `OTEL_SERVICE_NAME`, else the binary's name. An app restarted in the same place registers under the same id, so a link to it survives the restart: the example program, started again from the same directory, registered as `rt_6ea843dccc7741ff` both times. When another process holds the id (a live stream, or queued or accepted work), Studio answers `<id>-<pid>` and the link adopts it: two replicas in one directory get distinct ids.

**Studio keeps the link's state** through [`obsdb.CommandStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CommandStore), which both first-party databases implement and `studio.New` passes in. Commands, routes, breakpoint sets and registrations are written through one ordered writer off the request path, and a failed write holds its queue 30 s, then re-applies it. A restarted Studio lists the stored runtimes with `"restored": true` until they register again, decides `lost` from the stored state, and never re-sends an accepted command.

**The link's own bounds:** 16 runs at once, 256 commands admitted, a command frame up to 8 MiB (a larger one is acked rejected), a register that must answer in 15 s and response headers in 30 s. A broken stream is retried with a jittered backoff, half a second doubling to 30 s, which starts over once a stream has lived 10 s. A panic in the link is contained. The finished ack carries the run's error text.

## Acks and at-most-once

Each command runs at most once. The runtime acks it **before** it executes, and Studio refuses a reused command id with 409:

```json
{"error":{"code":"conflict","message":"command id cmd_replay_1 was already used"}}
```

A command's row moves through five states:

| State | Means |
|---|---|
| `queued` | Studio put it on the runtime's stream |
| `accepted` | the runtime validated it and will run it; `run_id` names the run (empty for a fork until its turn starts) |
| `rejected` | the runtime refused it; `error` says why (`budget_exceeded`, a validation sentence, the resolver's text) |
| `finished` | the run ended; `status` is `succeeded` or `failed`, `error` a failed run's text |
| `lost` | Studio gave up waiting; `error` says what it waited for |

Send one, here the replay [Replay a run from any step](https://weftgo.dev/docs/observe/playground/replay/) starts with:

```sh
curl -s -X POST http://127.0.0.1:8080/studio/api/playground/runs -d '{"command_id": "cmd_docs_1", "runtime": "rt_6ea843dccc7741ff", "agent": "acme-support", "source": {"run_id": "dd66354adfaac2b44848f0c1ed75516f", "from_step": 1}, "overrides": {"instructions": "You are Acme'"'"'s support agent. Always include the tracking link.", "options": {"temperature": 0.2}}, "engine": "live", "side_effects": "substitute", "thread": "ephemeral", "experiment_id": "tracking-link"}'
```

```json
{"command_id":"cmd_docs_1","state":"queued"}
```

Then poll it with `GET /api/playground/commands/{id}`:

```sh
curl -s http://127.0.0.1:8080/studio/api/playground/commands/cmd_docs_1
```

```json
{"command_id":"cmd_docs_1","state":"finished","run_id":"pg_01M5780D5BYHQNGQDWRXR84HAZ","status":"succeeded","error":null,"created":"2026-10-18T12:13:07.369713696+02:00","updated":"2026-10-18T12:13:07.376531416+02:00"}
```

Playground run ids start `pg_`; command ids Studio mints start `cmd_`.

The timing rules:

- **The ack window is 30 s**, counted from the enqueue. A command with no ack in that time, or whose stream died before the ack, is `lost`.
- **Validation is bounded at 25 s** inside that window: the re-checks, the source transcript fetch and the model resolver together. A validation past it is rejected ("validation took longer than 25s, past Studio's ack window: the command is not run"), never acked after Studio marked the command lost.
- **An accepted ack Studio did not take runs nothing.** A 409, 404 or 400 answer (409 once Studio marked the command lost) posts nothing more. A transport error or a 5xx is settled with a finished, failed ack: "not run: the accepted ack was not confirmed".
- **While it holds a command, the runtime re-posts the accepted ack every minute**, the heartbeat the registration reports as `heartbeat_ms`. The beat stops before the finished ack is posted, and on a refused beat. Each beat restarts Studio's finish watch.
- **An accepted command is `lost`** when no finish and no heartbeat arrive in max(10 min, 3 beats), with the beat taken at most 10 min, whether its stream is open or not. A runtime too old to heartbeat is watched for 10 minutes after its stream dies.

A late ack or finish still lands: the truth about a run wins over a timer's guess. Studio never re-sends a lost command. Send it again as a new command.

## Link log lines

When the playground shows no runtime, the app's log says why. `runtime.Install` and the link write these lines to `slog.Default()`, each with the attributes shown:

| Level | Message | Attributes | When |
|---|---|---|---|
| WARN | `weft/runtime: Install without agents: no link opened` | `hint` `runtime.Agents(...) names the agents a runtime exposes` | `Install` was given no `runtime.Agents`, or an empty one. Nothing opens |
| WARN | `weft/runtime: no Studio to dial: no link opened` | `hint` `runtime.Studio(url, token), runtime.Local(srv), or a Studio destination in weft/otel` | No `Studio`, no `Local`, no pipeline Studio destination and no trusted discovery file. Nothing opens |
| WARN | `weft/runtime: the pipeline records only into a Local store (otel.Local, or otel.Install's default) and names no Studio: no link opened` | `hint` | The installed `weft/otel` pipeline records into a Local store and names no Studio, and `Install` names none either. Nothing opens ([weft dev](https://weftgo.dev/docs/observe/weft-dev/)) |
| INFO | `weft/runtime: joined the running Studio` | `url`, `pid`, `file`, `hint` | The discovery file named the Studio to dial |
| WARN | `weft/runtime: the Studio token travels unencrypted over http to a non-loopback host` | `hint` `use an https Studio URL` | A token is set and the URL is `http://` to a host other than `localhost` or a loopback IP (setup C). The link still opens |
| WARN | `weft/runtime: agent without core.Name is not playable` | `hint` `core.Name names an agent in its manifest` | A nameless agent in `runtime.Agents`; it is skipped |
| WARN | `weft/runtime: link failed to start` | `err` | The link could not start. Nothing opens. In v0.20.2 the link's start returns no error, so this line is not expected |
| WARN | `weft/runtime: Studio refused the runtime link; the playground stays off until the token is right` | `status` (`401 Unauthorized` or `403 Forbidden`), `hint` `runtime.Studio(url, token) carries the token — with runtime.Local(srv) too, when srv was built with studio.Token` | The register call was refused for its token. Logged once per link |
| DEBUG | `weft/runtime: register failed; retrying` | `err`, such as `weft/runtime: register: 401 Unauthorized` | Every failed register, the refused ones included. The link retries with backoff, so after the one WARN a wrong token is silent at the default level |
| DEBUG | `weft/runtime: command stream ended; reconnecting` | `err` | The command stream broke; the link registers again |

Only `Install without agents`, the Local-store line, `no Studio to dial` and `link failed to start` stop `Install`. After the others the link keeps retrying with the token it was given at `Install`: a Studio that comes to accept that token is joined on a later retry, while a corrected token in the app needs the app restarted.

### Command log lines

Once the link is open, each command the runtime cannot run as asked leaves a line. When the command fails, its row in Studio carries the error too; the line is the app's side of it.

| Level | Message | Attributes | When |
|---|---|---|---|
| WARN | `weft/runtime: undecodable run command` | `err` | A run frame that is not a command. The runtime rejects it with `undecodable command` when its id is usable |
| WARN | `weft/runtime: command frame without a usable id ignored` | none | A frame with no id, or one Studio would refuse. It is neither run nor acked |
| WARN | `weft/runtime: the accepted ack was not taken; the command is not run` | `command_id` | Studio refused the accepted ack or did not confirm it ([above](#acks-and-at-most-once)). Nothing runs |
| WARN | `weft/runtime: the accepted ack was not taken; the decision is not applied` | `command_id` | The same for a decision on a parked playground run: the resume does not run, and the park keeps that call |
| WARN | `weft/runtime: the accepted ack was not taken; the decision is not held` | `command_id` | The same for a decision that leaves other parked calls undecided: it is not held, so deciding again is not refused as already decided |
| WARN | `weft/runtime: the accepted ack was not taken; the session is not written` | `command_id` | The same for a decision or steer on your app's own turn ([App-owned turns](https://weftgo.dev/docs/observe/devtools/app-turns/)) |
| WARN | `weft/runtime: ack failed` | `command_id`, `state`, `err` | Posting an ack failed in transport; it counts as unconfirmed |
| WARN | `weft/runtime: ack unconfirmed` | `command_id`, `state`, `status` | Studio answered an ack with a 5xx |
| WARN | `weft/runtime: ack refused` | `command_id`, `state`, `status` | Studio answered an ack with any other non-200 status, such as 409 once it marked the command lost |
| WARN | `weft/runtime: playground run failed` | `command_id`, `run_id`, `err` | A playground run ended in an error; its finished ack carries the text |
| WARN | `weft/runtime: fork command failed` | `command_id`, `source`, `err` | A `"thread": "fork"` command could not fork or run its turn |
| WARN | `weft/runtime: fork resume failed` | `session`, `err` | A decision on a parked fork could not resume its session |
| WARN | `weft/runtime: forked session not released` | `session`, `err` | Closing a forked session failed, so its writer lease may still be held |
| WARN | `weft/runtime: session command failed` | `command_id`, `session`, `verb`, `err` | A decision or steer on your app's own turn failed after its ack; the finished ack says why |
| WARN | `weft/runtime: source transcript unresolved; running on the input alone` | `run_id`, `err` | A command with a fresh input whose source transcript could not be read runs on the input ([Replay](https://weftgo.dev/docs/observe/playground/replay/)) |
| WARN | `weft/runtime: the source step's compaction view could not be read; it is unknown, the thread's messages are used` | `run_id`, `step`, `err` | A replay from a `thread` turn's step: the records or Studio could not say what the model saw, so the turn's own messages are used |
| WARN | `weft/runtime: no request record places the source step's messages (derived); the replay uses the transcript cut at the step, no compaction view known` | `run_id`, `step` | No request record places the source step's messages: an older run, or a request recorded with content off |
| WARN | `weft/runtime: this Studio does not answer the transcript as of a step (ADR 0029); a compaction view of the source step is unknown` | `run_id`, `step` | The Studio is older than `GET /api/runs/{id}/transcript?step=` |
| WARN | `weft/runtime: manifest for agent failed` | `agent`, `err` | Building a registered agent's manifest failed; it registers without one. Not expected, since names are checked first |
| ERROR | `weft/runtime: command panicked` | `command_id`, `panic` | A panic around a command, outside the agent's own contained code. Before the runtime accepted the command, it is rejected with `internal error in the runtime (see its log)`; after, it finishes failed with that error |
| ERROR | `weft/runtime: in-process Studio handler panicked` | `path`, `panic` | Under `runtime.Local`, a Studio handler panicked. The call answers 500 and the app keeps running |

The other link lines are Debug: a register retry, a reconnect, a repeated or cancelled command, an abandoned ack, a refused heartbeat, a dropped steer.

## Complete example

```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
```

The tests in [`main_test.go`](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/playground/main_test.go) register the runtime both ways (`TestRuntimeRegisters` through `runtime.Local`, `TestInstallStudioRegisters` through `runtime.Studio` under `WEFT_ENV=dev`, and nothing connects without it), and check the stable `rt_` id, each tool's class, the alternate and the resolver.

## Best practices & gotchas

- **Nothing opens without `WEFT_ENV=dev` or `runtime.Enabled(true)`.** Install returns a no-op shutdown and logs nothing. (Source: `runtime/options.go:285-290`; the example's `TestInstallStudioRegisters`)
- **Install the `weft/otel` pipeline before `runtime.Install` when you rely on the environment.** The default endpoint is the installed pipeline's Studio destination; with none, and `WEFT_STUDIO_URL` set, there is no Studio to dial and Install logs a WARN. (Source: `runtime/options.go:297-330`; `otel.StudioEndpoint` godoc)
- **Give every registered agent a `weft.Name`.** A nameless agent is skipped with a WARN. With no named agent left, nothing registers: Studio refuses the empty registration (400 `register body: no agents`) and the link keeps retrying it with backoff, logging at Debug only. (Source: `runtime.Agents` godoc; `runtime/options.go:291`; `studio/runtime/runtime.go:968-969`)
- **Keep the resolver's error text safe to show.** It is the rejected command's reason, read by whoever ran the experiment. (Source: `runtime.ModelResolver` godoc)
- **Honour `ctx` in the resolver.** It is abandoned at 10 s and keeps running if it ignores the cancel. (Source: `runtime.ModelResolver` godoc)
- **Re-issue a lost command; do not retry its id.** The id is spent, and a reuse is 409. (Source: `studio/runtime/runtime.go:12-15`)
- **A wrong or missing token is one WARN, then silence.** The first refused register logs `weft/runtime: Studio refused the runtime link; the playground stays off until the token is right`; every retry after it logs `register failed; retrying` at Debug only, so the app runs on with no playground. Check the token `runtime.Studio` passes, or `WEFT_STUDIO_TOKEN` under `weft dev`. (Source: `runtime/link.go:234-242, 300-309`)
- **Use `https` for a Studio off this machine.** A token over plain `http` to a non-loopback host logs `weft/runtime: the Studio token travels unencrypted over http to a non-loopback host`, and the link opens anyway. (Source: `runtime/options.go:331-334, 350-363`)
- **With a token-gated embedded Studio, pass the token too.** `runtime.Local(srv)` alone does not register against `studio.Token`. (Source: `runtime.Local` godoc; `runtime/local_test.go:TestLocalWithStudioToken`)

## See also

- [How does the playground work?](https://weftgo.dev/docs/observe/playground/overview/)
- [Replay a run from any step, with edits](https://weftgo.dev/docs/observe/playground/replay/)
- [Run Studio](https://weftgo.dev/docs/observe/studio/setup/)
- [Develop with weft dev](https://weftgo.dev/docs/observe/weft-dev/)
- [Environment variables](https://weftgo.dev/docs/reference/env/)

Symbols used: [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`runtime.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Install) · [`runtime.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Option) · [`runtime.Studio`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Studio) · [`runtime.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Local) · [`runtime.Agents`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Agents) · [`runtime.Models`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Models) · [`runtime.ModelResolver`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#ModelResolver) · [`runtime.Limits`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Limits) · [`runtime.Budget`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Budget) · [`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.Sessions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Sessions) · [`runtime.Enabled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Enabled) · [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Model) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage) · [`otel.StudioEndpoint`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#StudioEndpoint) · [`obsdb.CommandStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CommandStore) · [`studio.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#New) · [`studio.Playground`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Playground)
