---
title: Studio HTTP API
description: Every route Studio serves — the JSON read API, deletion, the live stream and its grant, panel tokens and hand-off, the panel files, OTLP ingest, the playground and the runtime link — with parameters, auth, capability, response shape, status codes and caps.
url: https://weftgo.dev/docs/reference/studio-api/
type: reference
sources:
  - 'W11-auditB2-fix, v0.20.2: weft/studio/livegrant.go:104-133 (the stream: filter pairs, agent), 236-266, 283-330 (tag.<k>, flow in the body; the 400 text); weft/studio/live.go:254-264; weft/studio/api.go:1424-1448; weft/CHANGELOG.md:46, 63; git show v0.18.0:studio/api.go (delegated_sessions_cache)'
  - 'W11-factcheck4, v0.20.2: weft/studio/auth.go:103-105 (admits: the public id and every tag), 604-611 (agent alone: a tag-only token only); weft/studio/live.go:233-235 (agent= narrows beside another selector), 395-420 (scopeLiveFiltered)'
  - 'W11-fix3, v0.20.2: weft/studio/auth.go:120-145, 335-343 (the tag-scoped token; the scope refusal names public id and tags), 595-611 (a tag-only token''s agent= stream), 642-731 (POST /api/panel-tokens: tags, public_id or tags, strict body, the tag bounds and their 400s, tags in the answer); weft/studio/live.go:204-246 (the selector: agent alone or narrowing, a tag/flow filter alone), 250-330, 404-420 (the filter, scopeLiveFiltered); weft/studio/handoff.go:10-30, 85-104 (the server token rides the fragment); weft/studio/routes.go:150-232 (the 501 groups), 244-250 (scope_tags); weft/studio/stats.go:107-110, 185-262 (since durations, the 24 h default, parent *, playground false or all, flow via tagParams); weft/studio/api.go:285-296 (own_usage, delegated_usage), 1130-1210 (runs params: flow, error_class, turn_below, turn_above, oldest), 1424-1444 (tagParams: tag.<k>, flow), 2165-2177 (trace doc run_ids, not_run), 2262-2310 (sessions id_prefix, tag scope); weft/studio/traces.go:15-45, 200-210 (not_run, id_prefix, tags); weft/studio/search.go:20-95, 105-125 (error_class filter and facet, 501 without Aggregator); weft/studio/meta.go:200-215 (manifest_check.latest); weft/studio/playground.go:105-140, 133 (the commands route takes one segment), 226, 670-700 (cross_agent); weft/studio/preview.go:60-75, preview_scripted.go:20-45 (scripted_hit, scripted_key_match); weft/studio/runtime/runtime.go:70-175 (Registration studio_url, AgentRegistration manifest_hash, AgentDefaults thinking_budget), 540-560 (CommandStatus.Reason), 563-677 (RuntimeView studio_url, weft_version, breakpoints_set_at in the store, breakpoints_surface, breakpoints_by; AgentView manifest_hash, model_provider; ToolView approval); weft/studio/runtime/reason.go:25-55; weft/studio/cancel.go:52-110 (an app turn''s cancel refused at once, 409); weft/studio/debugger.go:23-35, 73-76 (surface), 131, 170-190 (an app turn''s steer: 409 when parked or finished); weft/studio/appturn.go:60-150 (the refusal cases in order)'
  - weft/studio/runtime/runtime.go:520-530 (AckReason), 625-640 (BreakpointsSurfaceAPI, BreakpointsBy*), 689-692 (ErrConnected, ErrRuntimeBusy), 1776-1790 (RunCommand, CommandsOn), 1841 (HoldsInstance), 2100-2112 (SetBreakpointsFrom), 2144 (Forget); weft/studio/runtime/reason.go:17-80 (Reason, ReasonOf, ScriptedMissReason); weft/studio/runtime/example_test.go:48-151; weft/studio/README.md:2941-2946 (the wire for future non-Go clients) — v0.20.2
  - weft/studio/meta.go:90-125 (runtime_link, discovery_file), 180-192 (content.latest started, weft_version, service); weft/studio/routes.go:245-275 (scope_tags, panel_token_tags); weft/studio/playground.go:105-140 (target_check, runtime_forget, run_commands), 1012-1052 (serveRunCommands); weft/studio/debugger.go:93-124 (serveForgetRuntime); weft/studio/stats.go:170-182 (the stats group); weft/AGENTS.md:236-244 (fields doctor does not check) — v0.20.2
  - 'weft/otel/options.go:104-123 (DevMode), 169-198 (DevDetail, dev-gated); weft/otel/pipeline.go:241-311, 931-960 (the gate, its WARNs and the DevMode INFO lines); weft/obsdb/request.go:93, 149, 167-168 (the gap and raw_off fixes name otel.DevMode()); weft/CHANGELOG.md:124 (0.19.0: DevMode), 35 (0.20.0: DevDetail)'
  - every path and line below is in the weft v0.17.0 tag (53bab77f), read from the weft-v0.17.0 worktree
  - 'studio/routes.go:12-32 (the route registry), 36-99 (routeGroup, addRunRoute, addRunItemRoute, capabilityList), 104-291 (registerGroups: every group and its condition), 293-327 (serveAPINotFound, registerReadAPI, registerIngest)'
  - studio/studio.go:110-130 (Base), 144-154 (Capabilities), 248 (default base /studio/), 288 (the / catch-all), 363-389 (ingestAuthorized), 397-420 (ServeHTTP headers, routed), 445-476 (serveUI)
  - studio/api.go:32-35 (events page sizes), 37-65 (writeJSON, writeError, request_id on 5xx), 71-104 (maxBody 4 MiB, decodeBody, 413), 122-134 (dbError), 140-301 (runRow), 306-361 (row), 375-386 (problem fields), 396-509 (runsPage, runDoc, compactions), 592-656 (events, transcript docs), 690-710 (spanDTO), 749-767 (spansFor), 1130-1241 (serveRuns), 1391-1463 (statusParam, parentParam, tagParams, limitParam), 1472-1496 (serveRunRoutes), 1501-1614 (run document), 1721-1795 (runHoles), 1841-1910 (events), 1929-1938 (refuseDerived), 1947-2029 (transcript), 2045-2166 (spans, tree, treeHole), 2219-2250 (traces/{id}), 2260-2472 (sessions), 2805-2922 (scoped sessions, public_id, public)
  - studio/meta.go:26-214 (metaDoc and its blocks), 240-293 (serveMeta), 299-309 (mayReadDBPath), 314-330 (dbFile), 334-364 (latestContent), 376-387 (runtimes), 395-445 (manifestCheck), 477-493 (the manifest document's weft and name keys)
  - studio/auth.go:26-165 (setups, identity, scopes), 169-226 (panel token format), 230-235 (bearer), 246-305 (the wall), 338-344 (forbidden), 354-428 (scope, hidden holes), 436-563 (scope checks), 574-614 (scopeLive), 622-632 (serverOnly), 634-734 (servePanelTokens), 736-792 (CORS, default origins), 794-866 (crossOriginWrite, hostAllowed)
  - studio/manifest.go:32-37 (capability off reasons), 46-65 (optionalCapabilities), 168-254 (withHash, serveManifest, withSources), 273-297 (capabilitiesOff)
  - studio/manifests.go:22-45 (group, off reason), 79-115 (the stored manifest route), 138-145 (manifest_available)
  - studio/proposals.go:38-141 (64 proposals, mayPropose, PUT), 166-205 (bodies, DELETE)
  - studio/delete.go:19-103 (group, the notes at 33-36, mayDelete, both DELETE routes)
  - studio/requests.go:27 (requests page 100), 40-202 (badgeFields, rows, raw, readsPrompts, mayReadPrompts), 197-274 (requests), 344-393 (tools)
  - studio/steps.go:41-156 (step document), 239-254 (stepHole), 426-436 (writeStepError), 542-598 (serveRunStep)
  - studio/export.go:88-93 (formats), 99-164 (serveRunExport), 167-261 (tree, cap 200), 297-306 (Content-Disposition), 325-419 (refuseHidden, conflict), 594-603 (exportDoc)
  - studio/logs.go:28 (logs page 100), 77-127 (logsPage, the read-token refusal), 132-232 (serveRunLogs, holes)
  - studio/diff.go:65-181 (500-step cap, the diff document), 204-364 (serveDiff)
  - studio/search.go:61-199 (searchPage, cost cap 2000, min_cost, sort), 200-367 (params, serveCostSearch)
  - studio/traces.go:58-198 (traceRow, root_run, failed_runs cap 500, rootMissing), 195-280 (serveTraces)
  - studio/pricing.go:426-480 (cost and delegated fields), 1015-1065 (usagePending, coster.row), 1306-1358 (meta pricing, pricingDoc, servePricing)
  - studio/live.go:23-33 (ping 15 s, write deadline 30 s, dedup 65,536), 125-202 (frame DTOs), 204-481 (selector, kinds, Last-Event-ID, HEAD), 493-565 (stream, expired, overflow), 598-633 (filter, dedup), 705-894 (backfill, 1 h, 500)
  - studio/livegrant.go:23-60 (window 60 s, reuse), 220-266 (sig use), 276-367 (serveLiveGrant)
  - studio/ingest/ingest.go:1-15 (package doc), 38-74 (MaxBody, Traces, Logs), 96-147 (content types, gzip, 413), 149-274 (pipeline, success, errors)
  - studio/ingesthealth.go:13-147 (meta.ingest, dropped, healthHub)
  - studio/internal/reqlog/reqlog.go:47-120 (X-Request-Id), 157-174 (ingest counters, last_error), 181-305 (rate limit, log lines)
  - 'studio/handoff.go:40-145 (hand-off: 5 minutes, 2048, the path rule)'
  - studio/panel.go:24-70 (/panel.js)
  - studio/panelconfig.go:18-93 (/panel-config.json and its guard)
  - studio/assets.go:39-131 (cache headers, CSP, the shell)
  - studio/playground.go:39-157 (the group and its capabilities), 168-206 (runtimes), 209-391 (runs), 421-550 (checkCommand), 633-959 (checkSource, checkRegistered, toolOverrides, checkNeutral), 989-1006 (commands/{id}), 1055-1237 (approvals)
  - studio/experiments.go:24-30, 49-50, 120-180 (checkExperiment), 188-355 (list 50/200, refusal of panel tokens, detail)
  - studio/preview.go:17-77 (previewDoc), 151-282 (servePlaygroundPreview)
  - 'studio/playground.go:916-926 (leavesOn: an empty tools_enabled leaves every tool on); studio/preview.go:692-702 (onlyTools: the same); runtime/executor.go:1376-1382 (an empty list adds no OnlyTools)'
  - studio/fixtures.go:523-625 (servePlaygroundFixture)
  - studio/debugger.go:23-226 (breakpoints, steer)
  - studio/cancel.go:28-144 (cancel)
  - studio/appturn.go:29-187 (app-owned turns)
  - studio/edits.go:156-213 (transcript edit kinds)
  - 'studio/runtime/runtime.go:325-329 (RegisterResponse), 331-348 (Command: Runtime json:"-"), 396-400 (SourceSpec), 540-558 (CommandStatus), 560-676 (RuntimeView, AgentView, ToolView), 1759 (RuntimeServer.Command returns CommandStatus), 1868-1926 (Snapshot: a ToolView per manifest tool, side_effects from the registration, allow from IsAllowed)'
  - 'studio/requests.go:122-140 (promptDoc: hash, text, segments omitempty, content "" | truncated | derived, truncated_bytes; catalogDoc)'
  - studio/runtime/runtime.go:72-180 (Registration), 326-345 (RegisterResponse, Command), 378-537 (frames, verbs, Ack, states), 541-678 (CommandStatus, RuntimeView), 683-721 (errors, ValidCommandID), 744-776 (RuntimeServer timers), 880-937 (New, Mount, MountGuarded, the three routes), 959-1450 (register, commands, acks), 1457-2198 (methods)
  - 'core/report.go:46-49 (AttemptInfo.Wait, weft.attempt.wait_ms: the wait before this attempt was sent)'
  - studio/runtime/runtime.go:2199-2201 (maxCommands 10,000)
  - 'studio/runtime/runtime.go:71-180 (Registration, AgentRegistration, AgentDefaults, AgentLimits, Budget, Registration.Agent), 182-325 (IsAllowed, ManifestToolNames, ManifestToolSchemas, ManifestModelName, ManifestInstructions), 331-347 (Command), 372-395 (ApprovalDecision, PublicID json:"-"), 455-499 (Breakpoints, SteerMessage, SessionCommand), 959-1023 (serveRegister: runtime_id is required, no agents), 1147-1156 (breakpoints frame before the backlog), 1218-1268 (writeRunFrame: id lines, the cancel frame''s data), 1451-1495 (Enqueue), 1537-1587 (CancelTarget, CancelRun), 1607-1655 (EnqueueApproval), 1711-1755 (EnqueueSession), 2178-2195 (Steer)'
  - 'studio/runtime/manifests.go:21 (maxManifests 64), 26-55 (ManifestSource, Version json:"-", ManifestAgent, Entry json:"-"), 128-131 (Manifests: live first)'
  - 'runtime/link.go:382-447 (the runtime''s frame switch: breakpoints and steer are not acked)'
  - 'runtime/registry.go:72 (side_effects: the tool''s ReplayPolicy), 194 (env: WEFT_ENV)'
  - 'runtime/sessions.go:30-37 (the six refusal texts), 60-99 (rejected before the accepted ack: body check, not set, cancel, resolve, signed, pending), 104-107 (steer decided after the ack), 136-150 (ErrLocked and ErrNotRunning as a failed finish), 158-180 (checkSessionCommand), 205-243 (resolveSession), 304-320 (checkPending), 251-252 and 276 (the resolver and claim timeout and panic texts)'
  - 'studio/runtime/runtime.go:473-480 (the SessionCommand godoc: four refusals, before any write)'
  - 'studio/runtime/runtime.go:1463-1473 (Enqueue: unknown runtime, command id, duplicate, not connected); studio/runtime/manifests.go:18-23 (64, a soft bound)'
  - core/tool.go:732-735 (ReplayNever never, ReplaySafe safe)
  - 'studio/playground.go:275-285 (command_id and experiment_id rule), 481-545 (trap: preview warns, runs refuse; the scripted engine and fork rules), 633-642 (checkSource: from_step negative, input with from_step > 0), 808-838 (checkNeutral: thinking, the closed options set), 841-850 (actorOf), 936-958 (paramsOverride)'
  - 'studio/api.go:1166-1174, 2268-2276 (before_id read only with before: runs, sessions)'
  - 'studio/traces.go:35-36, 235-237 (before_id without before is ignored: traces)'
  - studio/steps.go:121-249 (stepMessagesIn, stepToolCall, stepToolResult, stepSpan, stepChild, stepCompaction, stepHole)
  - studio/api.go:516-521 (posEvent)
  - 'studio/ingest/ingest.go:259-275 (writeIngestError: the API''s JSON error shape)'
  - studio/runtime/http.go:29-78 (link error shape, 8 MiB, cmd_ ids)
  - studio/runtime/store.go:111-121 (Option, WithStore), 581-590 (Close, Shutdown)
  - studio/runtime/manifests.go:131 (Manifests)
  - studio/runtime/example_test.go:13-43 (ExampleRuntimeServer)
  - studio/README.md:2824-2844 (runtimes, the wire for runtime clients), 2953-3552 (The API)
  - AGENTS.md:234-412 (block 7, the API)
  - CHANGELOG.md:567-568, 620-622, 1057-1070 (GET /api/traces, the trace list, 0.14.0), 2485-2487, 2503-2509, 2942-2946, 3400-3431, 4550-4573, 4610-4613, 4643-4647, 5383-5387
  - 'observed: weft studio built from the v0.17.0 worktree, on a scratch database seeded with three scripted runs, a token and the playground on, plus a scratch app holding the runtime link; every JSON block on this page is a captured response, trimmed where it says so'
  - 'W11-auditB1-fix, v0.20.2: studio/api.go:1027-1068 (sessionDoc: delegated, delegated_more, delegated_unknown, delegated_usage, delegated_holes; delegatedSessionsFields: cost_usd, cost_known, cost_reason, cache; delegatedCap 100, delegatedTreeCap 500), 2474-2619 (delegatedSessions: [] when none, delegated_unknown on a failed direct read, delegated_more past 100, the 500-session reason, zero cost when nothing delegated, cache exact or not_reported, the cache note); studio/timeline.go:39 (timelineMarkCap 2000), 84-120 (sessionEntry: at, fact_at), 122-143 (timelineTurn), 157-185 (timelineFork, timelineForkCap 20), 187-218 (timelineLane; timelineDoc: session_id, public_id, agent, status, turns, marks, lanes, marks_total, holes, forks, summarizer)'
  - 'weft v0.20.2: studio/api.go:155-175 (session_compactions, delegated_sessions, ended_by, ended_by_turn, ended_kind), 400-410 (turn_marks_capped), 1248-1253 (turnMarksSessions 50, turnMarksPages 10), 440-470 (decided, resumes, summarizer), 918-941 (the sessions row''s turn facts); studio/decisions.go:40-117 (the decided block: sources, the 32-call cap, outcomes, the content rules for a read token); studio/diff.go:170-180 (system_hidden); studio/steps.go:245-256 (count, count_floor); studio/timeline.go:46-52 (lanes), 90-125 (the mark: content_hidden, actor, actor_of); studio/session_export.go:300-322 (session_hole, session_end {turns_exported, marks_exported, bytes}); weft/AGENTS.md:256, 265, 312-343 (block 7: runs, runs/{id}, sessions, sessions/{id}, timeline, export); weft/CHANGELOG.md:227 (0.18.0: the timeline), 232 (0.18.0: decided)'
---

# Studio HTTP API

Studio serves one HTTP surface under its base path: a JSON API under `api/`, OTLP ingest under `v1/`, the devtools panel's two files, and the UI shell for every other path. This page lists every route weft v0.20.2 registers, with its parameters, who may call it, the [capability](#capabilities) that gates it, the response shape and the status codes. The how-to pages are [Run Studio](https://weftgo.dev/docs/observe/studio/setup/), [Secure Studio](https://weftgo.dev/docs/production/security/) and [Watch runs live](https://weftgo.dev/docs/observe/studio/live/); the Go side is [`weft/studio`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio).

```sh
curl -s -H "Authorization: Bearer $WEFT_STUDIO_TOKEN" http://127.0.0.1:7331/api/meta
```

The answer, from a `weft studio` with a token and the playground on (trimmed: `db.path` shortened):

```json
{
  "weft_version": "v0.20.2",
  "studio_version": "v0.20.2",
  "panel_version": "v0.20.2",
  "db": { "kind": "sqlite", "path": "…/weft.db", "size": 278528 },
  "title": "weft studio",
  "has_manifest": false,
  "ingest_open": true,
  "ingest": { "dropped": [], "accepted": 0, "refused": 0 },
  "interrupted_after_ms": 30000,
  "capabilities": ["requests", "steps", "export", "logs", "diff", "traces", "search", "manifests",
    "spans_tree", "timeline", "pricing", "delete", "proposals", "live", "ingest", "auth", "handoff",
    "panel-config", "runtimes", "preview", "breakpoints", "steer", "cancel", "playground"],
  "manifest_sources": 0,
  "auth_required": true,
  "live_all": true,
  "debug_scope": "runtime-started runs",
  "content": {
    "ingest": "as_received",
    "latest": { "run_id": "0284b9967cc95119e5e12416f9982fe9", "mark": "full", "note": "the latest run's content is stored in full" }
  },
  "pricing": { "source": "default", "dated": "2026-10-10", "models": 47 },
  "retention": null,
  "runtimes": 0,
  "manifest_check": null,
  "pid": 3015109
}
```

<span id="overview"></span>
## Conventions

These hold for every route unless its row says otherwise.

| Topic | Rule |
|---|---|
| Base path | Every path on this page is relative to Studio's base: `/` under `weft studio`, `/studio/` by default for an embedded `studio.Handler` ([`studio.Base`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Base)) |
| Format | JSON, `application/json; charset=utf-8`. Times are RFC 3339; every time parameter takes RFC 3339 only (`since=2026-10-17` is a 400), except `/api/stats`' `since`, which also takes a positive duration (`90m`, `24h`, `7d`) |
| Errors | `{"error": {"code", "message"}}`, plus `request_id` on a 5xx. Codes: `bad_request` (400, and 413 over a body cap), `unauthorized` (401), `forbidden` (403), `not_found` (404), `method_not_allowed` (405), `conflict` (409), `unsupported` (415, ingest only), `internal` (500), `not_implemented` (501: `spans?tree=1`, the session timeline and entries, or an `error_class` filter, on a database that cannot serve them), `unavailable` (503) |
| Badged errors | A refusal that is about a [hole](https://weftgo.dev/docs/reference/badges/) adds `badge`, `reason` and `fix` beside `error`: 403 `hidden` (a read-scoped token), 409 with the record's hole, 400 `derived` (a run built from stock spans) |
| Database errors | `obsdb.ErrNotFound` is 404 `no <noun> <id>`. Any other read error is 500 `read <noun> <id>: <err>`; a panel token gets `read <noun> <id> failed`, the cause only in the server log |
| Request bodies | At most 4 MiB on every `/api` route (413 `<what>: larger than the 4 MiB limit`); the runtime link's register and acks take 8 MiB; ingest takes 16 MiB after decompression |
| Headers on every response | `X-Request-Id` (yours when it is 1 to 64 characters of `[A-Za-z0-9._:-]`, else 16 generated hex digits), `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, and a `Content-Security-Policy` that loads nothing from another origin |
| Methods and unknown paths | A `GET` route also answers `HEAD`, without a body. A wrong method on a path under `api/` or `v1/`, and an unknown path there, is 404 `no such api route <path>` in the error shape, never the UI shell; under `api/` that answer comes after the token wall, so without a bearer it is the wall's 401. The UI shell answers 405 to a method other than `GET` or `HEAD` |
| Paging | Run, session and trace lists take `limit` (0 or absent: 50; above 500: clamped to 500; negative or not an integer: 400 `limit must be a non-negative integer`) and the cursor `before` (RFC 3339) plus `before_id` (an exact cursor inside a tie). They answer `total`, `next_before` and `next_before_id`, both `null` on the last page. `before_id` is read only beside `before`: sent alone, it is ignored. A group of rows with the same timestamp is never split: a page may hold up to 500 rows past `limit` |
| Run ids | A subagent's run id holds slashes (`<parent>/<step>/<call id>`), so on `GET` and `DELETE` everything after `/api/runs/` is the id. The `POST` verbs (`approvals`, `steer`, `cancel`) and `GET /api/runs/{id}/commands` take one path segment: send a child id with its slashes encoded as `%2F`. A trailing `events`, `transcript`, `spans`, `requests`, `tools`, `export` or `logs` segment, or `steps/<n>`, is a sub-route; a child id that ended in one of those words would be shadowed, and provider call ids never do |
| CORS | With a `Token` or an `AllowOrigins` list, every answer carries `Vary: Origin`. An allowed origin gets `Access-Control-Allow-Origin`, methods `GET, POST, PUT, DELETE, OPTIONS`, headers `Authorization, Content-Type, Last-Event-ID`, `Access-Control-Expose-Headers: X-Request-Id`; a preflight is 204 with `Max-Age: 600`. With a Token and no list, the allowed origins are `http` or `https` `localhost` and `127.0.0.1` on any port. The entry `"*"` admits every origin and, in setup A, every `Host` |

The route groups are registered in `studio/routes.go`; `/api/meta`'s `capabilities` is computed from them, never hard-coded, and the panel and playground files add their own groups through package hooks.

| Since | Change |
|---|---|
| 0.7.0 | The route groups; the read routes (`transcript`, `spans`, `traces/{id}`, `sessions`, `public/{public_id}`, `panel-tokens`); S4.3's run row with the identity chain in full (`parent_run_id`, `trace_id`, `service`, `session_id`, `public_id`, `turn`, `playground`, `experiment_id`, `forked_from`, `meta`, `last_seen`, `pending`, `stop_reason`, `message_count`) |
| 0.8.0 | The run and session lists take `before_id` and answer `next_before_id`; every `/api` body is capped at 4 MiB |
| 0.14.0 | The trace list, with the same cursor from the start |
| 0.18.0 | A session is grouped over its own turns, pool child sessions included; its `status` is the newest turn's outcome. Caller-linked runs leave `children`. The session timeline, entries and export routes |
| studio 0.1.0 | The read API is pinned by golden files on the Go side, and the web app mirrors their types against the same fixtures |

## Who may call what

Studio knows five callers. The [security page](https://weftgo.dev/docs/production/security/) explains the setups; this table is the rule each route below applies.

| Caller | How Studio knows it | Reads | Writes |
|---|---|---|---|
| Server token (the dev token under `weft studio`) | `Authorization: Bearer` equal to `studio.Token`, compared in constant time | Everything | Everything |
| Setup A | No `Token` configured, and the `Host` is loopback (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`) or an `AllowOrigins` host:port | Everything | Everything from its own origin; an unsafe method from another `Origin`, or with no `Origin` but `Sec-Fetch-Site: cross-site`, is 403 `cross-origin write refused (setup A): …` |
| Playground panel token | `weft_pt.<payload>.<signature>` minted with `"playground": true` | Its public id's runs, sessions, traces and stream, prompts included | Runs, decisions, steer and cancel inside its public id |
| Read panel token | A panel token minted without `playground` | Its public id's runs, sessions, traces and stream; no system prompt, tool catalog or app log | None: 403 `this token is read-only: mint it with "playground": true to act` |
| Tag-scoped panel token (0.20.0) | A panel token minted with `tags`, with or without a `public_id` | What a read token reads, held to the runs carrying every tag: across public ids for a tag-only token; a token with a `public_id` is also held to that public id. A tag-only token reads no run commands (403) | None: it is read-only |

The wall, in order: `?token=` on any `/api` route is 401 `a token in the URL is never accepted: …` in every setup. In setup A a non-loopback `Host` is 403 and a cross-origin write is 403. With a Token, no bearer is 401 `the API requires a token: Authorization: Bearer <token>`, and a bad or expired panel token is 401 `bad or expired token`. Studio sends no `WWW-Authenticate` header. A `sig` from [`POST /api/live-grant`](#post-api-live-grant) is the one credential a URL may carry, on `/api/live` only.

Four rules recur in the tables below:

| Rule | Who passes |
|---|---|
| Server or loopback | The server token, or no Token and a loopback `Host` (an `AllowOrigins` host does not count). It governs `db.path`, `db.size`, `pid`, `pricing.path`, `live_all` and `all=1`, deletion and proposals |
| Reads prompts | Everyone but a read panel token. A read token gets 403 with badge `hidden` where a route carries system prompts, catalogs or app logs, or the field replaced by a `hidden` badge inside a 200 |
| Scope | A panel token reads only its own public id, and a tagged one only runs carrying its tags. Another public id's run, session or trace, or another value of one of its tag keys, is 403 `this token is scoped to public id <pub>` (or `tags <k>=<v>`, or both). An unknown id is 404 as for anyone, so scope never reveals whether a run exists. Child runs outside the scope are one `hidden` hole with a `count` |
| Server to server | The server token or setup A; every panel token gets 403. The [runtime link](#runtime-link) (`this route speaks server-to-server: it needs the server token, not a panel token`) and [breakpoints](#put-api-runtimes-id-breakpoints) (`breakpoints park every future run of the runtime: the server token, not a panel token`) |

## Route index

| Method and path | Capability | Who |
|---|---|---|
| [`GET /api/meta`](#get-api-meta) | none | anyone past the token wall |
| [`GET /api/manifest`](#get-api-manifest) | none | reads prompts |
| [`GET /api/manifests/{hash}`](#get-api-manifests-hash) | `manifests` | reads prompts |
| [`PUT /api/agents/{name}/proposal`](#put-api-agents-name-proposal), [`DELETE`](#delete-api-agents-name-proposal) | `proposals` | server or loopback |
| [`GET /api/runs`](#get-api-runs) | none | scoped |
| [`GET /api/runs/{id}`](#get-api-runs-id) | none | scoped |
| [`GET /api/runs/{id}/events`](#get-api-runs-id-events) | none | scoped |
| [`GET /api/runs/{id}/transcript`](#get-api-runs-id-transcript) | none | scoped |
| [`GET /api/runs/{id}/spans`](#get-api-runs-id-spans) | none; `?tree=1` needs `spans_tree` | scoped |
| [`GET /api/runs/{id}/requests`](#get-api-runs-id-requests), [`/tools`](#get-api-runs-id-tools) | `requests` | reads prompts, scoped |
| [`GET /api/runs/{id}/steps/{n}`](#get-api-runs-id-steps-n) | `steps` | scoped |
| [`GET /api/runs/{id}/export`](#get-api-runs-id-export) | `export` | scoped |
| [`GET /api/runs/{id}/logs`](#get-api-runs-id-logs) | `logs` | reads prompts, scoped |
| [`DELETE /api/runs/{id}`](#delete-api-runs-id) | `delete` | server or loopback |
| [`GET /api/runs/{id}/commands`](#get-api-runs-id-commands) | `run_commands` | scoped |
| [`GET /api/stats`](#get-api-stats) | `stats` | scoped |
| [`GET /api/search`](#get-api-search) | `search` | scoped |
| [`GET /api/diff`](#get-api-diff) | `diff` | scoped |
| [`GET /api/traces`](#get-api-traces), [`GET /api/traces/{id}`](#get-api-traces-id) | `traces` / none | scoped |
| [`GET /api/sessions`](#get-api-sessions), [`GET /api/sessions/{id}`](#get-api-sessions-id) | none | scoped |
| [`GET /api/sessions/{id}/timeline`](#get-api-sessions-id-timeline), [`GET /api/sessions/{id}/entries`](#get-api-sessions-id-entries) | `timeline` | scoped |
| [`GET /api/sessions/{id}/export`](#get-api-sessions-id-export) | none | scoped |
| [`GET /api/sessions/{id}/public_id`](#get-api-sessions-id-public-id) | none | no panel token |
| [`GET /api/public/{id}`](#get-api-public-id) | none | scoped |
| [`DELETE /api/sessions/{id}`](#delete-api-sessions-id) | `delete` | server or loopback |
| [`GET /api/settings/pricing`](#get-api-settings-pricing) | `pricing` | anyone |
| [`GET /api/live`](#get-api-live), [`POST /api/live-grant`](#post-api-live-grant) | `live` | scoped |
| [`POST /api/panel-tokens`](#post-api-panel-tokens) | `auth` | server token |
| [`GET /api/panel-handoff`](#get-api-panel-handoff) | `handoff` | server or playground token |
| [`GET /panel.js`](#get-panel-js), [`GET /panel-config.json`](#get-panel-config-json), [`GET /`](#the-ui-shell) | none / `panel-config` / none | no auth |
| [`POST /v1/traces`, `POST /v1/logs`](#otlp-ingest) | `ingest` | ingest token or loopback |
| [`GET /api/runtimes`](#get-api-runtimes) and the other [playground routes](#playground-routes) | `playground`, `preview`, `breakpoints`, `steer`, `cancel` | see each |
| [`DELETE /api/runtimes/{id}`](#delete-api-runtimes-id) | `runtime_forget` | no panel token |
| [`POST /api/runtime/register`, `GET /api/runtime/commands`, `POST /api/runtime/acks`](#runtime-link) | `runtimes` | server to server |

<span id="capabilities"></span>
## Capabilities

`/api/meta`'s `capabilities` lists the registered route groups' names, in registration order, then any names a hosting wrapper declared with [`studio.Capabilities(...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Capabilities). The UIs gate each screen on these names. A capability that could be on and is not appears in `capabilities_off` with the reason below, or with the words a host gave [`studio.OffReason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#OffReason) (0.20.0; `weft studio --no-playground` uses it); `capabilities_off` is omitted when nothing is off, and a name a host declared is never both on and off. `/panel-config.json` serves the same list. The read API and `/panel.js` belong to groups that name no capability.

| Capability | Present when | Gates | `capabilities_off` reason |
|---|---|---|---|
| `requests` | always | `GET /api/runs/{id}/requests`, `/tools`; the Request pane (0.10.0) | — |
| `steps` | always | `GET /api/runs/{id}/steps/{n}` | — |
| `export` | always | `GET /api/runs/{id}/export` | — |
| `logs` | always | `GET /api/runs/{id}/logs` | — |
| `diff` | always | `GET /api/diff` | — |
| `traces` | always | `GET /api/traces` | — |
| `search` | the database implements `obsdb.Searcher` | `GET /api/search` | `the database cannot search: its obsdb.DB does not implement obsdb.Searcher (obsdb/sqlite and obsdb/clickhouse both do)` |
| `manifests` | the database implements `obsdb.ManifestStore` | `GET /api/manifests/{hash}` | `the database cannot store manifests: …` |
| `spans_tree` | the database implements `obsdb.TreeReader` | `?tree=1` on `GET /api/runs/{id}/spans` (no route of its own) | `the database cannot read a run tree: … GET /api/runs/{id}/spans?tree=1 answers 501` |
| `timeline` | the database implements `obsdb.SessionEventReader` | `GET /api/sessions/{id}/timeline`, `/entries` (0.18.0) | `the database cannot read a session's state log: … GET /api/sessions/{id}/timeline and /entries answer 501` |
| `pricing` | always | `GET /api/settings/pricing`; cost on the rows | — |
| `delete` | always | `DELETE /api/runs/{id}`, `DELETE /api/sessions/{id}` | — |
| `proposals` | always | `PUT` and `DELETE /api/agents/{name}/proposal` | — |
| `live` | always | `GET /api/live`, `POST /api/live-grant` | — |
| `ingest` | not `studio.NoIngest()` | `POST /v1/traces`, `POST /v1/logs` | `OTLP ingest is off: studio.NoIngest() turned it off` |
| `auth` | a `Token` is set | `POST /api/panel-tokens` | `no server token to sign panel tokens with: turn it on with studio.Token(tok); weft studio always sets one` |
| `handoff` | a `Token` is set | `GET /api/panel-handoff` | `no Token: panel tokens do not exist here, so there is none to hand off from: …` |
| `panel-config` | always | `GET /panel-config.json` | — |
| `playground` | `studio.Playground(true)` | `GET /api/runtimes`, `POST /api/playground/runs`, `GET /api/playground/commands/{id}`, `POST /api/runs/{id}/approvals`, `POST /api/playground/fixtures`, `GET` and `POST /api/experiments`, `GET /api/experiments/{id}` | `the playground is off: turn it on with studio.Playground(true); weft studio --no-playground turns it off` |
| `runtimes` | `Playground(true)` | the three [runtime link](#runtime-link) routes | the playground reason |
| `preview` | `Playground(true)` | `POST /api/playground/preview` | the playground reason |
| `breakpoints` | `Playground(true)` | `PUT /api/runtimes/{id}/breakpoints` | the playground reason |
| `steer` | `Playground(true)` | `POST /api/runs/{id}/steer` | the playground reason |
| `cancel` | `Playground(true)` | `POST /api/runs/{id}/cancel` | the playground reason |
| `target_check` | `Playground(true)` (0.19.0) | no route: `GET /api/runtimes`' per-agent `manifest_hash` and per-runtime `studio_url`, the preview's `scripted_hit` and `scripted_key_match`, the cross-agent refusal (`cross_agent: true` opts in) and a command's `reason` | the playground reason |
| `runtime_forget` | `Playground(true)` (0.19.0) | `DELETE /api/runtimes/{id}` | the playground reason |
| `run_commands` | `Playground(true)` (0.19.0) | `GET /api/runs/{id}/commands` | the playground reason |
| `stats` | the database implements `obsdb.Aggregator` (0.19.0) | `GET /api/stats`; the search `error_class` facet and filter | `the database cannot aggregate: its obsdb.DB does not implement obsdb.Aggregator …; GET /api/stats and the error_class facet and filter are off` |
| `scope_tags` | always (0.20.0) | no route: `tag.<k>=<v>` and `flow=` on `/api/runs`, `/api/sessions`, `/api/search`, `/api/traces`, `/api/stats` and `/api/live` | — |
| `panel_token_tags` | a `Token` is set (0.20.0) | `"tags"` in `POST /api/panel-tokens`, and every read route holding such a token to them | the `auth` reason |
| `Capabilities(...)` extra names | the host passed them | whatever the host serves | never listed off |

Without its condition a group registers nothing, so its routes answer 404 `no such api route …`. Three answers are 501 instead, on a database without the interface: `spans?tree=1` without `obsdb.TreeReader`, the session timeline and entries without `obsdb.SessionEventReader`, and an `error_class` filter without `obsdb.Aggregator`.

<span id="meta"></span>
## Server metadata

<span id="get-api-meta"></span>
### `GET /api/meta`

Versions, the database, what is on, and the state of ingest. Every identity may call it; with a `Token` set it still needs a bearer (401 without). It then always answers 200: a failed observation goes into a field, not the status. [`weft doctor`](https://weftgo.dev/docs/reference/cli/#weft-doctor) prints it line by line.

| Field | Meaning |
|---|---|
| `weft_version` | The weft that serves it |
| `studio_version` | `studio.Version` |
| `panel_version` | The version stamped into the embedded `/panel.js`; `""` when the bundle is missing. It differs from `studio_version` only when the committed bundle is stale |
| `db` | `{kind, path, size}`. `kind` is `memory`, `sqlite`, `clickhouse`, the bare type name or `unknown`. `path` and `size` (the file's bytes plus its `-wal`) only to the server-or-loopback rule, and absent for a database with no file |
| `title` | `studio.Title` (`weft studio` by default) |
| `has_manifest` | A `weft.json` is configured, or a runtime registered a manifest |
| `ingest_open` | Ingest is on and has no `IngestToken`: loopback peers may post |
| `ingest` | Omitted for a panel token. `dropped`: `[{service, records, last_heard}]`, never null, most records first: the largest `weft.records.dropped` each service's heartbeats, `run_start` and `run_finish` reported on `/v1/logs`, kept in memory. `accepted` and `refused`: the OTLP POSTs under `/v1/` answered below 400 and at 400 or above since start. `last_error` (`<status> <code>: <reason>`) and `last_at`: the last refusal, omitted before the first |
| `interrupted_after_ms` | 30000: a running run silent this long reads `interrupted` |
| `capabilities` | [The list above](#capabilities) |
| `capabilities_off` | `{capability: why}`, omitted when nothing is off |
| `manifest_sources` | How many sources `/api/manifest` lists |
| `auth_required` | A `Token` is set |
| `live_all` | This caller may open `/api/live?all=1` (the server-or-loopback rule); always present |
| `debug_scope` | `runtime-started runs`, or `own+runtime` while a connected runtime registered `runtime.Sessions` or `breakpoints_own`. Present only with the `breakpoints` capability |
| `content` | `ingest`: always `as_received` (Studio stores records as they arrive). `latest`: the newest top-level run in the caller's scope, or `null`. It carries the run's `run_id`, its `mark` (`full`, `stripped`, `none` or `unmarked`, from its first event's `weft.content`) and a `note`. When content was off, a `fix` names `otel.NoContent()` or `weft.Content(false)`. Since 0.20.0 it also carries the run's `started`, `weft_version` and `service` (the last two omitted for a non-weft exporter), which `weft doctor`'s `data` line reads. `error`: a failed read |
| `pricing` | `{source, path?, dated, models}`: `source` is `default`, `file` or `option`; `path` to the server-or-loopback rule; `models` the row count. [Cost](https://weftgo.dev/docs/observe/studio/cost/) |
| `retention` | `studio.Retain`'s duration as a Go string (`720h0m0s`), or `null` when off |
| `runtimes` | Runtimes holding a command stream now; 0 without the playground |
| `manifest_check` | `null` for a panel token or with no manifest. Else `source` (`file` or `runtime`), `agents` (how many agents the manifest names) and `checked` (how many of them have a latest run carrying a `manifest_hash`). `stale` lists the checked agents whose latest hash is no known version; it is never null. `differs` names those registered in more than one version, omitted when none. `latest` is each checked agent's latest run's manifest hash, by agent name, omitted when nothing was checked. `error` is the first read failure. The keys `weft` and `name` it parses are the manifest document's own |
| `pid` | The serving process, to the server-or-loopback rule only (0.11.0) |
| `runtime_link` | `{studio_url?, in_process}`: this process's own runtime links (0.19.0). `in_process` says a link talks to this server, `runtime.Local(srv)` or HTTP to this very Studio; `studio_url` names the Studio another link dialled instead. Omitted when no link of this process is open, and under `db.path`'s rule |
| `discovery_file` | The discovery file apps find this Studio through, while it names this process (0.20.0, `studio.DiscoveryFile`); omitted for setup A, under `WEFT_DISCOVERY=off`, and under `db.path`'s rule |

| Since | Change |
|---|---|
| 0.7.0 | `db`, `ingest_open`, `interrupted_after_ms` |
| 0.10.0 | The `requests` capability |
| 0.11.0 | `db` becomes `{kind, path, size}` (breaking); `content`, `pricing`, `retention`, `runtimes`, `panel_version`; `pid` under `db.path`'s rule |
| 0.19.0 | `runtime_link`; the `stats`, `target_check`, `runtime_forget` and `run_commands` capabilities |
| 0.20.0 | `discovery_file`; `content.latest`'s `started`, `weft_version`, `service`; the `scope_tags` and `panel_token_tags` capabilities |

**Request ids and server logs.**

| Signal | Behaviour |
|---|---|
| `X-Request-Id` | On every answer; a 5xx body also carries it as `error.request_id` |
| ERROR on `slog.Default` | Every 5xx (the real error, even when a panel token's body masks it) and every handler panic; never rate-limited |
| WARN on `slog.Default` | A refused ingest batch, at most one a minute per remote host, route class (`/v1/traces`, `/v1/logs` or `/v1/*`), code and status |
| Handler | `weft studio --log-level` and `--log-format` choose it |

`weft doctor` checks only the fields its lines name; read `retention`, `pricing`, `live_all`, `debug_scope` and `interrupted_after_ms` here, or with `weft mcp`'s `meta` tool.

<span id="get-api-manifest"></span>
### `GET /api/manifest`

| Aspect | Behaviour |
|---|---|
| Who | Reads prompts: a read token gets 403 `hidden`, `the manifest carries the agents' system prompts: a read-scoped panel token does not read it` |
| With a `weft.json` | The file verbatim, with `sources` added as its last key. An agent with a held proposal gains `proposed: {instructions, instructions_hash, since}` |
| Without one | `{weft, agents, sources}` from the manifests runtimes registered, each agent prefixed with its `manifest_hash`, one per service and name |
| `sources` | `[{source, manifest_hash, service?, live?, registered_at?, runtime_id?, agents: [{name, manifest_hash}]}]`: the file first, then registrations, live before remembered, newest first. Registrations are remembered in memory by service and manifest hash and forgotten on restart |
| 404 | `no manifest: no weft.json configured (studio.Manifest, or weft studio --manifest) and no runtime has registered` (with the playground reason when the playground is off) |

<span id="get-api-manifests-hash"></span>
### `GET /api/manifests/{hash}`

| Aspect | Behaviour |
|---|---|
| Capability | `manifests` |
| Who | Reads prompts (403 `hidden` for a read token) |
| 200 | `{manifest_hash, agent, source, first_seen, current_manifest_hash, manifest}`: the one-agent manifest a run's `manifest_hash` names; `source` is `file` or `runtime`; `current_manifest_hash` is `""` when the current manifest names no such agent |
| 404 | `no manifest <hash>: Studio stores a manifest when a runtime registers it or a weft.json it serves names it` |
| Storage | Written from the `weft.json` at `New` and from every runtime registration, content-addressed, first write kept, kept forever: deletion and `Retain` never touch it. A run document whose hash resolves carries `manifest_available: true` |

<span id="put-api-agents-name-proposal"></span>
### `PUT /api/agents/{name}/proposal`

| Aspect | Behaviour |
|---|---|
| Capability | `proposals` |
| Who | Server or loopback. A panel token: 403 `a proposed prompt is a system prompt: …`; setup A through an `AllowOrigins` host: 403 |
| Body | `{"instructions": "…"}`, required; `""` proposes no system prompt. A missing key: 400 `proposal body: instructions is required (…)` |
| 200 | `{agent, proposed: {instructions, instructions_hash, since}, note}`; `instructions_hash` is SHA-256 hex. `/api/manifest` shows it beside the registered prompt |
| 404 | `no agent <name> in the manifest file or any registered manifest` |
| 409 | A file is served and only a runtime names the agent: `the served manifest file does not name agent <name>; the proposal would not show` |
| Storage | In memory, at most 64, the oldest forgotten first; lost on restart |

<span id="delete-api-agents-name-proposal"></span>
### `DELETE /api/agents/{name}/proposal`

Same capability and rule as `PUT`. 200 `{agent, proposed: null, note: "the proposal is forgotten"}`; 404 `no proposal for agent <name>`.

## Runs

<span id="get-api-runs"></span>
### `GET /api/runs`

| Parameter | Values |
|---|---|
| `agent`, `session`, `public_id`, `experiment_id`, `error_type` | Exact match |
| `id_prefix` | Runs whose id starts with it, byte for byte (`obsdb.RunQuery.IDPrefix`; the ⌘K palette's short-id lookup) |
| `stopped_by` | Exact, or a prefix when it ends in `:` (`has_tool_call:`) |
| `status` | `running`, `succeeded`, `failed`, `interrupted`, `parked`, `cancelled`. `parked` and `cancelled` are read-time: succeeded with open pending calls and no resumer; failed with error type `cancelled`. Any other word: 400 `status must be running, succeeded, failed, interrupted, parked or cancelled ("bogus" given)` |
| `parent` | Absent: top-level runs only; `*`: every run; a run id: that run's children |
| `all` | `1`/`true`: child runs too (`parent=*`). Not a boolean: 400 |
| `playground` | `true`/`false`. Not a boolean: 400 `playground must be true or false` |
| `tag.<key>`, `flow` | Metadata match, `tag.tenant=acme`; `flow` matches `weft.flow` (0.20.0) |
| `error_class` | A failure class, exact: the `/api/search` facet's class string. Needs the `stats` capability; without it, 501 (0.19.0) |
| `turn_below`, `turn_above` | A positive turn number: runs whose `turn` is below or above it (`obsdb.RunQuery.TurnBelow`, `TurnAbove`). With `session` and `limit=1`, a turn's neighbour, `total` the count on that side: the turn stepper's one-row read (0.18.0) |
| `oldest` | `1`/`true`: oldest first, the cursor reading forward (`obsdb.RunQuery.Oldest`, 0.18.0) |
| `before`, `before_id`, `limit` | [Paging](#overview) |

A panel token is pinned to its own public id; another `public_id` is 403. Every parameter but `limit` is checked before scope, so a malformed one is a 400 before another `public_id`'s 403. The answer is `{total, runs, next_before, next_before_id}`; `total` counts the whole match. On a page narrowed by `public_id` or `session`, the turn marks above are read for at most 50 sessions and 10 pages of marks each; the turns left without them are counted in the answer's `turn_marks_capped`, a `truncated` hole with `cause` `response_cap`. Each run row:

| Field | Meaning |
|---|---|
| `id`, `parent_run_id`, `parent_call_id`, `trace_id`, `agent`, `model` `{provider, name}`, `manifest_hash`, `weft_version`, `service` | Identity |
| `caller_run_id`, `caller_call_id` | A caller-linked run: one started on a tool call's context that is no `Subagent` child, such as a `thread/pool` child session's turn (0.18.0). It has no `parent_run_id`; omitted when none |
| `session_id`, `public_id`, `turn`, `playground`, `experiment_id`, `forked_from`, `meta` | The identity chain; `meta` is the run's metadata pairs, never null |
| `started`, `finished` (null while running), `last_seen`, `status`, `err`, `steps`, `pending`, `stop_reason`, `usage` | Outcome |
| `stopped_by`, `cancel_cause` | What ended it (`final_answer`, `max_steps`, `parked`, `has_tool_call:<name>`, …) and a cancel's cause; omitted when none |
| `error_type` | A failed run's kind; a context error reads `cancelled` |
| `resumed_from`, `resumed_by` | The approval link: the parked run a resume names, and on the parked run the run that resumed it; read time, either ingest order; omitted when none |
| `attempts_retried`, `fallbacks`, `tool_errors`, `denied`, `truncated`, `repaired`, `tap_panics` | Problem counters, counted at ingest, each omitted when 0. `attempts_retried` counts a failed attempt a later one of its call followed; `fallbacks` the attempts `weft.attempt.layer` marks; `tool_errors` skips `RETRY` results |
| `children_count`, `children_failed`, `children_unknown` | The runs whose parent is this one, one level deep, read once for the whole page; omitted when 0. Since 0.18.0 a caller-linked run is not counted. `children_unknown: true` when that read failed (the UI's "⑂ ?") |
| `prompt_preview` | The turn's own prompt: the input record's last user text (a resume's new prompt when it has one), else its first; 200 runes; absent when content was off |
| `settling` | `true` while the run's root span is stored, its `run_finish` is not, and it was heard from within 30 s; never on a failed root. The UI treats such a run as live |
| `events_emitted`, `messages_emitted`, `event_count`, `message_count`, `delta_count` | What the root span says was emitted, and what was stored |
| `instructions_hash`, `catalog_hash`, `request_count` | The request record's summary (0.10.0). `requests_badge`: `not_recorded` for a run written before ADR 0028, `derived` for a run built from stock spans |
| `derived` | `true` for a run built from stock OTel GenAI spans |
| `cost_usd`, `cost_known`, `cost_badge`, `cost_reason`, `cache`, `unpriced_models` | Own cost at read time, never stored: `cost_usd` is `null` when not known, never a made-up 0; `cost_badge` is `unpriced`, `unknown` or `scripted`; `cache` is `exact` or `not_reported`; at most five models, then `(+n)`. [Cost](https://weftgo.dev/docs/observe/studio/cost/) and [the badges](https://weftgo.dev/docs/reference/badges/#cost-badges) |
| `delegated_cost_usd`, `delegated_cost_known`, `delegated_cost_reason`, `delegated_unpriced_models` | The descendants' own cost, never folded into `cost_usd` |
| `own_usage`, `delegated_usage` | The run's own model calls' usage, and its Subagent children's, read at request time (0.20.0). Omitted on a run with no Subagent child, a running run, a failed read, or where a panel token cannot see one of the children |
| `session_compactions`, `delegated_sessions` | A session turn's marks, only on a page the request narrowed by `public_id` or `session` (0.18.0): the session compaction markers filed under the turn, and the sessions its calls delegated. The devtools panel draws them as its ⌗ and ↳ chips without a fetch per turn. Read through the session events index ([`obsdb.SessionEventQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionEventQuery)'s `Kinds`); omitted when 0 or not read |
| `ended_by`, `ended_by_turn`, `ended_kind` | On the same pages, what ended a turn a busy policy felled: the `weft.thread.interrupt` record filed under it, its `by_run`, `by_turn` and policy (`interrupt` or `rollback`), drawn "✗ interrupted by t7" or "↶ rolled back by t9 · off path". Omitted when no such record was read |

One row as captured (trimmed: hashes and empty fields removed):

```json
{
  "id": "0284b9967cc95119e5e12416f9982fe9",
  "trace_id": "3bfe79976e96ecfb6c4516fd4fce747d",
  "agent": "support-bot",
  "model": { "provider": "wefttest", "name": "script" },
  "service": "refb1seed",
  "started": "2026-10-18T14:44:33.062103108Z",
  "finished": "2026-10-18T14:44:33.066851684Z",
  "status": "failed",
  "err": "weft: run failed at step 1: weft: run exceeded the maximum number of steps",
  "steps": 1,
  "stop_reason": "tool_calls",
  "stopped_by": "max_steps",
  "error_type": "max_steps",
  "usage": { "input_tokens": 10, "output_tokens": 5 },
  "cost_usd": 0,
  "cost_known": true,
  "cost_badge": "scripted",
  "cost_reason": "a scripted model: nothing bills it, an exact $0",
  "cache": "exact",
  "event_count": 5,
  "message_count": 3,
  "request_count": 1,
  "prompt_preview": "Where is order 43?"
}
```

<span id="get-api-runs-id"></span>
### `GET /api/runs/{id}`

The run document: the run row plus the fields below. Out of scope: 403; unknown: 404 `no run <id>`.

| Field | Meaning |
|---|---|
| `children` | Child rows, each with `holes` when it has any. A panel token sees only its own public id's children; the rest are one `hidden` hole with a `count`. Since 0.18.0 a caller-linked run is not a child: read it from `caller_linked` |
| `caller_linked`, `caller_linked_more`, `caller_linked_hidden`, `caller_linked_unknown` | The runs this run's calls started that are no `Subagent` children (their `caller_run_id` names it), the first 100 in start order; the other fields say more exist, some are hidden from a panel token, or the read failed |
| `holes` | Always a list of `{hole, reason, fix?, count?}`, from the [closed table](https://weftgo.dev/docs/reference/badges/#the-ten-holes) |
| `compactions` | `[{scope, index?, step?, from_seq?, to_seq?, hash, replaced, entries, tokens_before?, tokens_after?, reason?}]`: run-scope views first, then session markers, which carry no index, step or range |
| `manifest_available` | `true` when the run's `manifest_hash` resolves on [`manifests/{hash}`](#get-api-manifests-hash) |
| `log_warn`, `log_error`, `logs_capped` | App log counts at severity 13–16 and 17–24, read at request time through `obsdb.DB.CountLogs`; `logs_capped` when they are floors (the UI's "≥"). On the document only |
| `decided`, `resumes` | Since 0.18.0, on a parked run that a resume names (`resumed_by`), each parked call's decision as that resume applied it; on the resume (`resumed_from`), the same calls. `{run, at, actor?, source, calls, more?, hole?, notes?, error?}`: `run` the other side, `at` the resume's start, `actor` its `weft.approval.actor` (metadata: every token reads it), `source` where the calls come from: `resume_calls` (the resume's `weft.resume.calls`), `transcript` (its pre-step results), `spans` (its pre-step `execute_tool` spans) or `none` with `hole` `not_recorded`. At most 32 calls, `more` counting the rest. Each call: `call_id`, `name`, `outcome` (`approved`, `denied`, `resolved`, `expired` or `no_decision`), `derived` (read from a result text or a span, not a decision record), `via`, `key_id`, `grant_id`, `who`, `approved_by` (a split verdict's overruled approvers), `reason`, `result` and `at`. The thread decision records are read with `obsdb.SessionEventQuery`'s `RunIDs`. A read-scoped panel token gets no `who` (`who_hidden`), `reason` or `result` (`reason_badge`, `result_badge` `hidden`); content-off they read `not_recorded`. Omitted when the run is neither |
| `summarizer` | What the summarizer calls filed under this run cost: the compaction markers and `SummarizeLeft` branches under it, priced at the recorded summarizer model's rates, else the run's model's as an estimate. Never in the run's usage or `cost_usd`; omitted when none |

<span id="get-api-runs-id-events"></span>
### `GET /api/runs/{id}/events`

| Aspect | Behaviour |
|---|---|
| `after` | The first position to return, inclusive; `-1` or `0` from the start. Below -1 or not an integer: 400 |
| `limit` | Default 500. Studio passes at most 5,000 to the database; both first-party databases return at most 1,000 per page, a third-party `obsdb.DB` may return up to 5,000 |
| 200 | `{events: [{pos, time, event, attrs?}], next_after, done, gaps}`. `event` is the core event as recorded; `attrs` only when the content is not `full`. `next_after` is `null` when nothing follows; `done` is true once the run is terminal; `gaps` lists missing positions (at most 1,000). A derived run adds `badge`, `reason`, `fix` |
| Who | Scoped; a read token reads events |

<span id="get-api-runs-id-transcript"></span>
### `GET /api/runs/{id}/transcript`

| Aspect | Behaviour |
|---|---|
| Bare | `{batches: [{index, step, input, badge?, messages}]}`: every stored `messages` batch. A batch with no step stamped reads step `-1` and badge `not_recorded`; one whose `input` flag was inferred reads `derived` |
| `step=N` | Also `step`, `messages` (what step N's model call carried: the record's truth, the replay prefix for `from_step` N > 0; `from_step` 0 re-runs step 0's `PrepareStep` over the original input), and `compacted_at` (the run-scope view the request carried, else `null`). `derived` when no request record placed the messages. A read token over a compaction view gets `messages: null` with badge `hidden` (ADR 0029) |
| 400 | `step must be a non-negative integer ordinal` |
| 404 | `no step N of run <id>`: the run never reached it |
| 409 | The records do not rebuild the step: badge `gap` or `stripped`; a derived run with `step`: badge `derived` |

<span id="get-api-runs-id-spans"></span>
### `GET /api/runs/{id}/spans`

| Aspect | Behaviour |
|---|---|
| 200 | `{spans}`, each `{trace_id, span_id, parent_span_id, name, kind, start, end, status, status_message, service, attrs, events, run_id}`; `run_id` is the run asked for. `kind` is `internal`, `server`, `client`, `producer`, `consumer` or `unspecified`; `status` is `ok`, `error` or `unset` |
| `tree` | `1`/`true`: [the run tree](#get-api-runs-id-spans-tree-1). Not a boolean: 400 `tree must be true or false (1 or 0)` |
| Who | Scoped. A read token's spans lose `weft.override.tools`, `weft.override.park_on` and `weft.override.park_all_except`, and a named `weft.override.tool_choice` is cut to its mode |

The sub-routes of a run are `runs/{id}/events|transcript|spans|requests|tools`, plus `steps/{n}`, `export` and `logs` below.

<span id="get-api-runs-id-spans-tree-1"></span>
### `GET /api/runs/{id}/spans?tree=1`

The run's spans and every descendant run's, found by the `weft.parent.run.id` chain and core's id rule (`<parent>/<step>/<call>`) from the run rows and read by run id, never the whole trace. A caller-linked run is not a descendant (0.18.0). Capability `spans_tree` (`obsdb.TreeReader`); without it, 501 `not_implemented`, checked before scope.

| Case | Behaviour |
|---|---|
| 200 | `{spans, holes}`. Each span adds `run_id` and `parent_run_id` (absent for the root's spans); a span is keyed by `run_id` plus `span_id`. `holes` is always a list of `{hole, cause?, reason, fix?, runs?, count?}` |
| `truncated`, cause `response_cap` | Past 10,000 spans (`obsdb.TreeSpanCap`), or past a derived run's 50,000-span trace read |
| `not_recorded`, cause `no_spans` | Finished child runs with a row and no span: `runs` names the first 100, `count` counts all. A running child is not missing |
| `hidden` | A panel token's descendants with another public id, left out with their subtrees before the cap and counted (`obsdb.RunTree.HiddenCount`, `obsdb.TreeQuery.PublicID`); never a 403 |

Captured from a run with one subagent child (trimmed: one span):

```json
{
  "spans": [
    { "trace_id": "95722f4da1c2f6ef1595b77f15fba570", "span_id": "fc36bce8bc5c2035",
      "name": "invoke_agent support-bot", "kind": "internal", "status": "ok",
      "service": "refb1seed", "run_id": "c5c6be88c1cdb9e00b58780ccc1db0bd" }
  ],
  "holes": []
}
```

<span id="get-api-runs-id-requests"></span>
### `GET /api/runs/{id}/requests`

Every model-call attempt's request record (ADR 0028), with the prompt and catalog it named.

| Aspect | Behaviour |
|---|---|
| Capability | `requests` |
| Who | Reads prompts, then scoped. A read token: 403 `hidden`, `the request record carries the system prompt and the tool catalog: a read-scoped panel token does not read it` |
| `step` | One step's records; else 400 `step must be a non-negative integer` |
| `from`, `limit` | The first request index (else 400 `from must be a non-negative request index`), and the page size: 100 by default, at most 1,000 |
| `refs` | `1`: hashes only, no inline prompt or catalog; else 400 `refs must be 1 (hashes only) or 0` |
| 200 | `{requests, next_from?, badge?, reason?, fix?}`. Each row: `index, step, attempt, time, system_hash, catalog_hash, content, truncated_bytes, body, prompt, tools, raw`. `prompt` and `tools` are inline documents (below) or `{hash, badge}` when the record is missing. `raw` is the attempt's wire pair under `otel.RawBodies` (development gate: `WEFT_ENV=dev`, or `otel.DevMode()`), else `null` with `raw_badge: "not_recorded"`, `raw_reason` and `raw_fix` ("run under WEFT_ENV=dev (or otel.DevMode()) with otel.RawBodies(true) …") |
| Old or derived run | 200 with an empty list and the page `badge` (`not_recorded` or `derived`) |
| `prompt` document | `{hash, text, segments?, content, truncated_bytes}`: the composed system text; `segments` attributes it to the instructions and each tool's prompt snippet ([`PromptSegment`](https://weftgo.dev/docs/reference/obsdb-records/#promptsegment)), absent when the record carries none; `content` is `""`, `truncated` (`truncated_bytes` > 0) or `derived` (a body that did not parse) |
| `tools` document | `{hash, tools, content, truncated_bytes}`: the catalog of that hash, tools in name order; `content` as the prompt's |

<span id="get-api-runs-id-tools"></span>
### `GET /api/runs/{id}/tools`

Same capability and rule as `requests`. 200 `{catalogs: [{hash, tools, content, truncated_bytes}], badge?}`; the badge is `not_recorded`, `derived`, `stripped`, or `gap` when a request names a catalog that was not stored.

<span id="get-api-runs-id-steps-n"></span>
### `GET /api/runs/{id}/steps/{n}`

One step assembled on the server: capability `steps`, scoped.

| Aspect | Behaviour |
|---|---|
| `n` | A canonical non-negative integer; else 400 `the step must be a non-negative integer ordinal` |
| 200 | `run_id, step, status` (`ok`, `error`, `parked` or `running`), `reason, started, finished, latency_ms, ttft_ms, model {provider, requested, answered}, request, attempts, attempts_badge?, messages_in, events, tool_calls, children, usage`, cost fields, `compaction?`, `holes`. A read token's `request` is `{badge: "hidden", …}` inside the 200 |
| `attempts` | `[{attempt, model, provider, outcome, error_type?, retry_after_ms?, layer?, http_status?, wait_ms?, error?, started, finished, span_id, request_index, badge?}]`: `http_status` is `http.response.status_code`; `wait_ms` is `weft.attempt.wait_ms`, the wait before this attempt was sent (absent on a first try); `retry_after_ms` is the provider's ask |
| `tool_calls` | `[{call_id, name, seq, args, result {content, is_error, bytes, truncated?}, span, child_run_id?, pending?, badge?}]`. `result` is absent while the call runs or is parked; `bytes` is the span's `weft.tool.result_bytes` when content was stripped; `truncated` means the result cap cut it |
| `tool_calls[].span` | `{id, started, finished, status}`: the call's `execute_tool` span |
| `tool_calls[].badge` | `max_tokens`: the step hit the output token limit, so the call never ran (no span; its result is the "not executed" text). `stripped`: content-off dropped args and result. On a content-off `max_tokens` step the calls are known only by count and listed with `call_id` `""` |
| `messages_in` | `{index?, count, badge?, reason?, fix?}`: the messages record index the request's view ends at, and how many messages it carried. `badge` is `stripped`, `compacted` (the index names the step's compaction view) or `not_recorded` (no request record) |
| `events` | `[{pos, time, event, attrs?}]`: the step's durable events in `pos` order, from its `step_start` up to the next step's, a steer delivered after the step included |
| `children` | `[{id, call_id, agent, status, usage}]` plus the run row's cost and delegated fields (`cost_usd`, `cost_known`, `cost_badge?`, `cost_reason?`, `cache`, `delegated_cost_usd`, …): the child runs this step's calls started, own and delegated never folded |
| `compaction` | `{scope, index, from_seq, to_seq, hash, replaced, entries, badge?}`: the compaction view the request carried; transcript entries `[from_seq, to_seq)` replaced by `entries` messages |
| `holes` | `[{hole, reason, fix?, count?}]`, deduplicated; `count` only on a `hidden` hole, the child runs a panel token's scope left out |
| 404 | `no step N of run <id>`: nothing records the step |

The run cards' words built from this document live in `src/lib/cards.ts`, shared by the run page and the panel.

<span id="get-api-runs-id-export"></span>
### `GET /api/runs/{id}/export`

The whole run as one download: capability `export`, scoped. [Export a run](https://weftgo.dev/docs/observe/studio/export/) shows each format.

| Aspect | Behaviour |
|---|---|
| `format` | Required: `json` (`weft.run.export/1`: run, events, transcript, compactions, requests with prompts and catalogs, spans, holes), `jsonl` (one record per line), `otlp` (`{logs, traces}`, re-ingestable through `/v1/*`), `wefttest` (a zip: `<agent>_replay_test.go` and `testdata/TestReplay_<run>/` fixtures). Else 400 `format must be json, jsonl, otlp or wefttest` |
| `tree` | `1` on `json`, `jsonl` or `otlp`: every subagent run under it too, breadth first, at most 200, each its own export (`subagents`, `subagent_holes`; the file `<run>.tree.<ext>`). With `wefttest`: 400; not a boolean: 400 `tree must be true or false (1 or 0)` |
| Who | A read token: `otlp` and `wefttest` are 403 `hidden`; `json` and `jsonl` carry the request block as a `hidden` badge |
| 200 | `Content-Disposition: attachment; filename="<id>.<ext>"`, the extension `.json`, `.jsonl`, `.otlp.json` or `.zip`. In the name `/`, `\`, `"`, control characters and non-ASCII become `_`; a non-ASCII name also gets `filename*`. `Content-Length` is set |
| 409 | `wefttest` for a transcript that cannot be fixtured: the hole as `badge` (`stripped`, `gap` or `derived`); without a badge when the run recorded no assistant turn. A derived run: 400 `derived` |

<span id="get-api-runs-id-logs"></span>
### `GET /api/runs/{id}/logs`

The app's own log lines under the run's spans: capability `logs`; reads prompts, then scoped. A read token: 403 `hidden`, `a run's app logs may carry anything the app logged, prompts included: …`. [Read a run's app logs](https://weftgo.dev/docs/observe/app-logs/) shows the bridge.

| Aspect | Behaviour |
|---|---|
| `from`, `limit` | The first log index (else 400 `from must be a non-negative log index`); the page size, 100 by default, at most 1,000 |
| `severity` | `trace`, `debug`, `info`, `warn`, `error`, `fatal`, a severity text or 1–24: lines at or above it. Else 400 |
| 200 | `{logs: [{index, time, severity, severity_number, body, attrs, span_id?}], next_from?, partial?, partial_reason?, holes, badge?, reason?, fix?}`; the top-level badge repeats the first hole. A running run is `partial`: spans export when they end |
| Holes | `not_recorded` when the run stored no span; `truncated` past 10,000 candidate lines; `gap` for lines naming an unstored span; and the `not_recorded` hint for a run without the slog bridge, whose fix names `otel.Slog()` |

The captured hint for a run recorded without the bridge (trimmed: the reason shortened):

```json
{
  "logs": [],
  "holes": [{ "hole": "not_recorded", "reason": "no app logs: no weft slog bridge was recorded for this run …",
    "fix": "bridge slog: otel.Install(…, otel.Slog()), or log through slog.New(otel.SlogHandler(h))" }],
  "badge": "not_recorded",
  "reason": "no app logs: no weft slog bridge was recorded for this run …",
  "fix": "bridge slog: otel.Install(…, otel.Slog()), or log through slog.New(otel.SlogHandler(h))"
}
```

<span id="delete-api-runs-id"></span>
### `DELETE /api/runs/{id}`

| Aspect | Behaviour |
|---|---|
| Capability | `delete` (always on) |
| Who | Server or loopback. A panel token: 403 `deletion answers the dev token (or loopback in setup A) only, never a panel token`; setup A through an `AllowOrigins` host: 403 |
| What | The run with its subagent children and the runs derived from stock spans under its tools: rows, records, search index, spans, app logs, from obsdb's tables only (`obsdb.DB.DeleteRun`). The app's conversation store and a shared file's thread tables are untouched; stored manifests stay |
| Path | The whole rest of the path is the id; no sub-route |
| 200 | `{deleted: "run", run_id, note}` |
| 404 / 500 | `no run <id>`; `delete run <id>: <err>` |

<span id="get-api-runs-id-commands"></span>
### `GET /api/runs/{id}/commands`

The commands sent to one run, oldest first: `{"commands": [...]}`, never null. Each is [`GET /api/playground/commands/{id}`](#get-api-playground-commands-id)'s row plus its `verb` (`decide`, `steer` or `cancel`) and, for a decision, its `call_id` and `decision`. Lost and rejected commands are listed too, so the run page can mark a command that never landed after a reload or a Studio restart. A panel token reads a run inside its scope and only the commands its own public id sent; a tag-only token is refused with 403. With no command and no such run stored, 404. A child run's id goes in one path segment, its slashes as `%2F`. Capability `run_commands` (0.19.0).

<span id="get-api-stats"></span>
### `GET /api/stats`

Numbers across runs, grouped `by=agent`, `model`, `tool`, `error_type` or `step`, over the run filters: `since`, `until`, `agent`, `tag.<k>=<v>`, `flow`, `public_id`, `parent`, `playground`, `experiment_id` and `status`. `since` defaults to 24 hours before `until`, and also takes a duration. `parent` defaults to `*`, every run. `playground` defaults to `false`, or both kinds with `experiment_id`; `all` asks for both. Each group carries runs, failures, calls, tokens, the cost block priced at read time, latency percentiles and a 24-bucket series. Capability `stats`, present when the database implements `obsdb.Aggregator` (0.19.0). [Track agent health](https://weftgo.dev/docs/observe/studio/stats/) explains every field.

## Search and compare

<span id="get-api-search"></span>
### `GET /api/search`

Capability `search` (`obsdb.Searcher`: SQLite FTS5 trigram, ClickHouse one derivation per search). Scope is checked first, so another `public_id` is 403 before any 400. [Find runs](https://weftgo.dev/docs/observe/studio/runs/#search) covers the query language.

| Parameter | Values |
|---|---|
| `q` | Terms over prompt, answer, error and tool names: substrings, all must match, a `"quoted phrase"` is one term. A bad query: 400 with its message |
| `agent`, `tool`, `model` | Exact |
| `error` | Substring |
| `status`, `session`, `public_id`, `experiment_id`, `stopped_by`, `error_type`, `parent`, `all`, `playground`, `tag.<key>`, `flow` | As on [`/api/runs`](#get-api-runs); `id_prefix`, `before` and `before_id` are not read |
| `error_class` | A failure class, exact, from the `facets.error_class` list. Without the `stats` capability, 501 (0.19.0) |
| `since`, `until` | RFC 3339; else 400 |
| `min_tokens` | A non-negative integer |
| `min_cost` | USD, own plus delegated; an unpriced run never matches. Not a non-negative number: 400 |
| `sort` | `started` (default), `duration`, `tokens`, `cost` (most first, unpriced last); else 400 `sort must be started, duration, tokens or cost` |
| `limit`, `offset` | 50 by default, at most 500; `offset` 0 to 100,000 |

200 `{total, runs, sort, next_offset, cost_sort_cap?, facets?}`. `facets.error_class` is the match's failures by class, most runs first, at most 20, counted without the request's own `error_class`; `error_class_capped` says past 2,000 distinct texts the rarest were not read. `facets` is absent without the `stats` capability. `min_cost` and `sort=cost` are applied in Studio over the match's first 2,000 runs; `cost_sort_cap: 2000` says the match was larger and `total` counts the capped set.

<span id="get-api-diff"></span>
### `GET /api/diff`

Two runs aligned by step ordinal: capability `diff`; both runs scoped. [Compare runs](https://weftgo.dev/docs/observe/studio/compare/) draws it.

| Aspect | Behaviour |
|---|---|
| `a`, `b` | Both required; else 400 `a and b must both name a run: /api/diff?a=<run id>&b=<run id>` |
| 200 | `{a: {run_id, steps, status}, b, steps: [{step, changed, a, b, changes, unknown}], summary: {changed_steps, first_changed}, holes}`. Each side is reduced to `status, system_hash, system, tool_calls, tool_results, text, usage, marks, holes`; `changes` names `system`, `tool_calls`, `tool_results`, `text`, `usage` or `missing`. A column a side did not record is in `unknown`, never compared. Compaction and subagent are marks, never a change |
| Caps | 500 steps; past them a `truncated` hole with `response_cap`'s reason and fix (no `cause` key is sent) |
| Who | A read token gets `system: null`, `system_hidden: true` on the side (0.18.0) and a `hidden` hole. A `hidden` hole with a `count` is the child runs a panel token's scope left out, and may stand beside it |

## Traces

<span id="get-api-traces"></span>
### `GET /api/traces`

Capability `traces` (`obsdb.DB.Traces`). A panel token lists only the traces every span of which carries its public id; scope is checked first.

| Parameter | Values |
|---|---|
| `since`, `until` | RFC 3339, on the trace's earliest span (SQLite narrows on `spans_start`, migration 0019). A bare day: 400 `since must be RFC 3339: …` |
| `service` | Exact, any span of the trace |
| `public_id` | One public id |
| `tag.<key>`, `flow` | Traces holding a span that carries the pair (0.20.0) |
| `not_run` | `1`: the GenAI traces that make no run: a GenAI span, no weft run and no derived run (0.20.0). Not a boolean: 400 |
| `id_prefix` | Traces whose id starts with it, byte for byte (0.20.0) |
| `before`, `before_id`, `limit` | [Paging](#overview) |

200 `{total, traces, next_before, next_before_id}`. Each trace:

| Field | Meaning |
|---|---|
| `trace_id` | The join key with `run_ids` |
| `root` | `{span_id, name}`, or `null` with `badge: "gap"`, `reason` and `fix` when only child spans arrived |
| `service`, `start`, `end`, `duration_ms`, `span_count`, `error` | The root's service, else the earliest span's; the span window |
| `run_ids` | Every run id in the trace, never null |
| `root_run` | `{id, agent, prompt_preview, status}`: the first id without `/`, else the shortest; omitted when unread or out of scope |
| `failed_runs`, `failed_runs_capped` | Failed runs among the root run and its core children; `failed_runs_capped` when the count stopped at 500, a floor |

A trace can appear on two pages; dedupe on `trace_id`.

<span id="get-api-traces-id"></span>
### `GET /api/traces/{id}`

Any trace, weft or not: `{spans, run_ids, not_run?}`, the spans in the [span shape](#get-api-runs-id-spans) without `run_id` (`weft.run.id` is in `attrs`). `run_ids` lists the weft runs and the derived runs the trace makes; when it makes none, `not_run` is `{reason, fix}` (0.20.0). A panel token needs every span to carry its public id, else 403. 404 `no trace <id>`.

## Sessions

<span id="get-api-sessions"></span>
### `GET /api/sessions`

Sessions grouped over their own turns (runs whose id is `<session>-t<turn>`, or runs linked to no run), playground runs left out. Since 0.18.0 a `thread/pool` child session is a row of its own, counted in `total`, with its lineage `parent_session`, `parent_turn`, `parent_call` and `parent_run`; a client after top-level sessions only skips rows with a `parent_session`. A panel token is pinned to its public id.

| Parameter | Values |
|---|---|
| `q` | Every term must appear in the title, first turn's prompt, id, public id or agent (`obsdb.SessionQuery.Q`) |
| `agent`, `public_id` | Exact |
| `id_prefix` | Sessions whose id starts with it, byte for byte (0.20.0) |
| `awaiting`, `failed`, `compacted` | `1`: the newest turn is an open park; a turn failed; the session was compacted (0.18.0) |
| `status` | The newest turn's outcome: `succeeded`, `failed`, `running` or `interrupted`; the other outcome words are a 400 (0.18.0) |
| `lineage`, `since`, `tag.<key>`, `flow` | `child` or `fork`; sessions seen since an RFC 3339 time; turns carrying the pair (0.18.0). Since 0.20.0 a tag scopes the turns a session is grouped over, so a partly tagged session counts its tagged turns alone |
| `before`, `before_id`, `limit` | [Paging](#overview), on `last_seen` |

200 `{total, sessions, next_before, next_before_id}`. Each row has `id, public_id, agent, turns, first_seen, last_seen` and `status`. `status` is the newest turn's outcome: `succeeded`, `failed`, `running`, `interrupted`, `cancelled`, `ended`, `parked` or `resumed`. Before 0.18.0 a cancelled or busy-ended turn read `failed` and a parked one `succeeded`. The row also has `usage`, `title` (the newest turn's `weft.session.title`), `first_prompt` and `content_off` (the first turn stored no content). Its cost fields are the turns' own plus delegated. Since 0.18.0 each row also carries its turn facts ([`obsdb.SessionTurnFacts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionTurnFacts), both backends), each omitted when zero or empty. `pending` is the newest turn's pending calls when it is an open park. `failed_turns` counts failures; `ended_turns` (the turns a busy policy ended) and `cancelled_turns` (the other cancelled turns) are never failures. `resumes` counts the turns that resume a parked one. `outcomes` lists the newest 40 turns' outcome words, oldest first, and `forked_from_session` is a fork's `<origin>#<entry>`.

The filters map onto [`obsdb.SessionQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionQuery): `tag.<key>` is `Meta`, `awaiting`, `failed`, `compacted`, `status`, `lineage` and `since` its fields of the same names. Studio lists a page's delegated sessions with `SessionQuery.Parents`, one tree level per read, and reads a session's forks in one `SessionQuery.IDs` query. [Sessions and traces](https://weftgo.dev/docs/observe/studio/sessions-and-traces/).

<span id="get-api-sessions-id"></span>
### `GET /api/sessions/{id}`

The session row plus `runs`: its turns as run rows. A panel token sees its own public id's turns and a row recomputed from them. Since 0.18.0 it answers a `thread/pool` child session too, and adds `delegated` (each delegated session with its cost) and the delegated tree's `delegated_usage` and `delegated_sessions_cost_usd`, beside its own cost, never folded in. A session is priced up to 10,000 runs, a level's reads bounded at 20 pages; past either the figure is unknown with a reason. Delegated sessions at any depth that a panel token may not see are one `hidden` hole in `delegated_holes`, with a `count` (`count_floor: true` when the walk stopped past 500, the count then a floor), and the delegated cost is then unknown with a reason. A panel token reads an unknown session id as another public id's: 403, here and on the timeline, entries and export routes. 404 `no session <id>`.

The delegated block's fields, beside the session row and `runs` (0.18.0):

| Field | Meaning |
|---|---|
| `delegated` | The sessions this one delegated directly, each a session row with its lineage and its own cost, newest first; `[]` when none. At most 100 rows |
| `delegated_more` | `true` when more than 100 sessions were delegated directly, so `delegated` is cut. The figures below still read past the 100 |
| `delegated_unknown` | `true` when a read of the direct level failed: `delegated` is then empty or partial, never complete |
| `delegated_usage` | The whole delegated tree's usage, at any depth, own plus their subagents'; never folded into the session's `usage` |
| `delegated_sessions_cost_usd` | That tree's cost; `null` when not known, `0` when nothing was delegated |
| `delegated_sessions_cost_known` | Whether that figure is known. A failed read, more than 500 delegated sessions, an unpriced run or a hidden session makes it unknown |
| `delegated_sessions_cost_reason` | Why it is unknown, or why a known figure may overstate a cached prompt (a session reported no cache split); omitted otherwise |
| `delegated_sessions_cache` | `exact` when every delegated session's own cost reported its cache split exactly, else `not_reported`; omitted when nothing was delegated |
| `delegated_holes` | The `hidden` hole for sessions a panel token may not see, with `count` and `count_floor`; omitted when none |

A client tells a complete list from a cut or failed one by `delegated_more` and `delegated_unknown`. It tells a full bill from a partial one by `delegated_sessions_cost_known`.

<span id="get-api-sessions-id-timeline"></span>
### `GET /api/sessions/{id}/timeline`

The session's turns in order and its state-log marks in record-time order, at most 2,000; past the cap a `truncated` hole with `cause: "response_cap"`. The document's top level:

| Field | Meaning |
|---|---|
| `session_id`, `public_id`, `agent`, `status` | The session; `public_id` omitted when it has none |
| `turns` | Every turn in turn order: `run_id`, `turn`, `agent`, `status`, `started`, `finished`, `last_seen`, `steps`, `usage` and `marks`, the count filed under it. `pending`, `prompt_preview`, `resumed_from`, `resumed_by`, `stopped_by`, `error_type` and `summarizer` appear when set |
| `marks` | The marks read, in record-time order, at most 2,000 |
| `lanes` | `[{lane, marks}]`: each lane's count of the marks read. The six named lanes always, `other` only when a mark sits on it |
| `marks_total` | The session's whole mark count, beside the capped `marks` |
| `forks` | One per fork mark read: `{session_id, entry, run_id, turns, status}`, the forked session as Studio stored it (`turns` 0: it ran none yet). `hidden` for a panel token, `unknown` past 20 forks or on a failed read. Omitted when it forked none |
| `summarizer` | The session's whole summarizer bill: `usage` and its cost priced at read time. Omitted when it summarized nothing; never folded into a turn's usage |
| `holes` | `not_recorded`, `stripped`, `hidden` and `truncated`, as below |
 Capability `timeline`; without it, 501 (0.18.0). The marks come from [`obsdb.SessionEventReader`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionEventReader) over the session events index (SQLite's `session_events`, ClickHouse's `weft_session_events`): every [`thread` record](https://weftgo.dev/docs/reference/record-contract/#thread) and compaction marker of the session, those filed under no run included.

A mark's `at` is the record's time, which orders the marks; `fact_at` is the body's own time on the session's clock, absent on a compaction marker. Each mark carries `at`, `fact_at`, `record`, `kind`, `event`, `lane` (`approvals`, `grants`, `compaction`, `steer_queue`, `branch_fork`, `pool` or `other`), `run_id` and `turn` (both `null` for a session-level mark), `entry`, `content_mark` and `fields`, the body's fields. `content` is the body's content object; to a read-scoped panel token it is withheld and `content_hidden: true` says so. A decision mark carries `actor`: the `weft.approval.actor` of the turn that resumed the run the mark is filed under. It is never that run's own `actor`, which names who decided the run before it. When the resume names several deciders, `actor` is narrowed to the call's own by `key_id`, else by a content reader's `who`. Otherwise it is the resume's whole list, with `actor_of: "resume"`. It is metadata, so every token reads it; absent while no stored turn resumed the run. The holes: `not_recorded` (only where a turn parked or resumed, since a plain send writes no record), `stripped`, `hidden` (a panel token's counts are exact) and `truncated`.

<span id="get-api-sessions-id-entries"></span>
### `GET /api/sessions/{id}/entries`

The same marks paged: `offset`, `limit` (at most 1,000) and `next_offset`; `run` narrows them to one run's. Capability `timeline` (0.18.0).

<span id="get-api-sessions-id-export"></span>
### `GET /api/sessions/{id}/export`

`?format=jsonl` downloads the conversation as `<session>.session.jsonl`, streamed (0.18.0): a `session` line `{format, session_id, public_id, agent, turns, marks}`, every turn's run export in turn order (at most 200), the state log's `session_mark` lines (at most 2,000), `session_hole` lines, and a closing `session_end` line `{turns_exported, marks_exported, bytes}`. Past 64 MiB, counting every line before the holes, the export stops with a `truncated` hole, cause `response_cap`; a read that fails mid-stream is a plain `truncated` hole. A read-scoped panel token's marks are `content_hidden` and its requests hidden.

<span id="get-api-sessions-id-public-id"></span>
### `GET /api/sessions/{id}/public_id`

The reverse of `public/{public_id}`. Every panel token, read or playground: 403 `the session-to-public-id lookup answers the dev token only, never a panel token`, with badge `hidden` and the `dev_token_only` reason and fix. 200 `{session_id, public_id}`; an empty `public_id` carries badge `not_recorded` with the `no_public_id` reason and fix. No `cause` key is sent. 404 for an unknown session.

<span id="get-api-public-id"></span>
### `GET /api/public/{id}`

Resolves a public id to its newest session: 200 `{session_id}`. A panel token for another public id: 403. 404 `no public id <id>`.

<span id="delete-api-sessions-id"></span>
### `DELETE /api/sessions/{id}`

A session's runs, by [`DELETE /api/runs/{id}`](#delete-api-runs-id)'s rule and scope of deletion (`obsdb.DB.DeleteSession`). 200 `{deleted: "session", session_id, note}`; 404 `no session <id>`. The session page's **delete session…** calls it.

## Settings

<span id="get-api-settings-pricing"></span>
### `GET /api/settings/pricing`

The effective pricing table: capability `pricing`, every identity. 200 `{source, path?, dated, note?, models}` in the file's own shape, so the answer saves as a `WEFT_PRICING` file; `path` to the server-or-loopback rule. [Cost](https://weftgo.dev/docs/observe/studio/cost/).

## The live stream

<span id="get-api-live"></span>
### `GET /api/live`

Server-sent events: capability `live`. [Watch runs live](https://weftgo.dev/docs/observe/studio/live/) walks through a stream.

| Aspect | Behaviour |
|---|---|
| Selector | Exactly one of `run`, `session`, `public_id`, `all` (`all=1` or `all=true`), or `agent` alone. Since 0.20.0 a `tag.<k>=<v>` or `flow=` filter alone is valid too: the stream is every run (a panel token's public id), filtered. Beside another selector, `agent=` narrows it. None, or two: 400 `exactly one of run, session, public_id, agent or all is required, or a tag.<k>=<v> / flow= filter alone (2 given)` |
| Filters | `tag.<k>=<v>` and `flow=` (0.20.0): a run frame passes when the run's metadata carries every pair; a record or attempt frame when its run passed, or its own attributes carry every pair |
| `kinds` | A comma list of `event`, `delta`, `messages`, `run`, `attempt`; default `event,run`, also for an empty value (`kinds=`). An unknown kind, or a list naming none (`kinds=,`), is 400. Heartbeat records are never forwarded, nor a `messages` record that is a compaction view |
| Resume | `Last-Event-ID` only. Not a non-negative integer: 400. With the header present, any value, Studio first replays the selector's stored `event` and `messages` records, then the live frames, deduplicated on run, kind and position per connection |
| `sig` | A [live grant](#post-api-live-grant), for `EventSource`, which cannot send headers. Bad, expired, or for another stream: 401 `bad or expired live grant for this stream: request a new one with POST /api/live-grant` |
| Who | `all=1`: server or loopback, else 403 `the all selector streams every run: it needs the server token, or setup A on a loopback Host` (`live_all` in `/api/meta`). A panel token: its own `public_id`, runs and sessions only, and every frame is checked against its public id. `agent` alone is 403 for a public id's token (beside its `public_id` it narrows); a tag-only token may use it alone, its tags then filter the stream. A filter naming another value of one of the token's tag keys is 403; its stream ends at the token's expiry with `event: expired` |
| 200 | `text/event-stream`, `Cache-Control: no-cache`, `X-Accel-Buffering: no`. `HEAD` answers the headers only (without `X-Accel-Buffering`) and subscribes to nothing |
| Caps | A 30 s deadline on each frame write; a ping every 15 s. An `all=1` resume replays runs running or last seen in the past hour, newest 500 (`obsdb.RunQuery.LastSeenAfter`); `session`, `public_id` and `agent` resumes page through every run they cover, 500 a page |

| `event:` | `id:` | `data` |
|---|---|---|
| `record` | the hub's frame sequence, the resume cursor (none when backfilled) | `{run_id, session_id, public_id, kind, pos, time, trace_id, span_id, event, attrs?}`; `kind` is `event`, `delta` or `messages`; `event` is the record body |
| `run` | sequence | `{run: <run row, cost included>}` |
| `attempt` | sequence | One try of a model call, from its `attempt` span as it lands: `{run_id, session_id, public_id, step, attempt, layer?, status, error_type?, provider?, model?, start, end, wait_ms?, retry_after_ms?, trace_id, span_id}`. `wait_ms` is `weft.attempt.wait_ms`, the wait before this attempt was sent (absent on a first try); `retry_after_ms` is the provider's ask. Live only, never backfilled |
| `ping` | none | `{}` every 15 s |
| `overflow` | none | `{}`: the subscriber's queue overflowed; Studio closes the stream |
| `backfill_error` | none | `{run_id, kind}`: a resume could not read one run's stored records |
| `expired` | none | `{}`: a panel token's expiry |

A backfilled frame, captured (`Last-Event-ID: 0`, trimmed: one frame, the hash cut):

```text
event: record
data: {"run_id":"c5c6be88c1cdb9e00b58780ccc1db0bd","session_id":"","public_id":"","kind":"event","pos":0,"time":"2026-10-18T14:44:33.045661597Z","trace_id":"95722f4da1c2f6ef1595b77f15fba570","span_id":"","event":{"type":"run_start","id":"c5c6be88c1cdb9e00b58780ccc1db0bd","model":{"provider":"wefttest","name":"script"},"agent":"support-bot","instructions_hash":"57e8f4…"}}
```

<span id="post-api-live-grant"></span>
### `POST /api/live-grant`

| Aspect | Behaviour |
|---|---|
| Body | `{"run"\|"session"\|"public_id"\|"agent": "…", "all": true, "kinds": "event,run"}`, or the same in the query, not both (400 `name the stream in the body or in the query, not both`). Since 0.20.0 the stream parameters also take `/api/live`'s filters, `"tag.<k>": "…"` and `"flow": "…"`, alone or beside a selector, and `agent` beside another selector narrows it. Each member is a string but `all`, a boolean; any other member is ignored. A body that is not that JSON is 400 `body must be JSON: {"run"\|"session"\|"public_id"\|"agent": "…" or "all": true, "tag.<k>"\|"flow": "…", "kinds": "event,run"}` |
| Who | The caller's own bearer, or setup A with none; the same scope rules as `/api/live`, checked at minting |
| 200 | `{"sig": "weft_lg.…", "exp": "…"}`, `Cache-Control: no-store` |
| Window | 60 s, never past a panel token's own expiry. Reusable within the window, since `EventSource` reconnects with the same URL; each stream opened in time runs until it is closed |
| Binding | HMAC over the identity, the selector and the sorted kinds (`all=1` and `all=true` are the same stream), then, since 0.20.0, each filter pair in key order (`flow` is the `weft.flow` pair) and a narrowing `agent`. A grant opens only the stream with that exact filter: `/api/live` with another filter, or none, is 401. Keyed by the `Token`; without one, a random key per process |
| Status | 200, 400, 401, 403, 413, 500 |

Captured: `{"sig":"weft_lg.…","exp":"2026-10-18T14:46:50.581848302Z"}` (the signature cut). Then open `/api/live?run=<id>&kinds=event,run&sig=<sig>`.

## Panel tokens, hand-off and the panel files

<span id="post-api-panel-tokens"></span>
### `POST /api/panel-tokens`

| Aspect | Behaviour |
|---|---|
| Capability | `auth`: registered only with a `Token`; without one, 404 |
| Who | The server token only; anyone else: 401 `minting a panel token requires the server token` |
| Body | `{public_id?, tags?, ttl?, playground?}`: `public_id` or `tags` required. `tags` (0.20.0) is a run metadata map: at most 16 pairs, keys and values 1 to 256 bytes, no `weft.*` key but `weft.flow`. `ttl` is a positive Go duration, default `1h`, no maximum. `playground: true` asks for the playground scope, with a public id alone |
| 200 | `{token, public_id, tags?, scope, exp}`; `scope` is `read` or `playground`; the token is `weft_pt.<base64url claims>.<base64url HMAC-SHA256 under the Token>` |
| 400 | An unknown field (0.20.0): `body must be JSON with public_id, tags, ttl and playground ("playground": true mints a playground token)`. No scope: `public_id or tags is required`. A bad tag: `tags: at most 16 pairs (N given)`, `tags: every key and value must be non-empty …`, `tags: "k": a key or value is at most 256 bytes`, `tags: "weft.x" is a weft record attribute, not run metadata: …`. Tags with the playground: `a token with tags is read-only: "playground": true takes a public id alone`. A bad TTL: `ttl must be a positive duration (e.g. "1h")` |

Captured (the token cut): `{"token":"weft_pt.eyJw…","public_id":"pub_jane","scope":"read","exp":"2026-10-18T15:00:50.53471257Z"}`. [Secure the devtools panel](https://weftgo.dev/docs/observe/devtools/security/).

<span id="get-api-panel-handoff"></span>
### `GET /api/panel-handoff`

| Aspect | Behaviour |
|---|---|
| Capability | `handoff`, with a `Token` only |
| `to` | A path under Studio's base, at most 2,048 bytes: one leading `/`, no scheme, host, fragment, backslash, white space or `.`/`..` segment. Else 400 |
| Playground token | 303 to `<base><to>#token=<read token>`: a fresh read token for the same public id, valid 5 minutes, never past the caller's own expiry |
| Server token | 303 to `<base><to>#token=<the server token>`: since 0.20.0 the dev token lands signed in, as `weft open --with-token` does. No read token is minted |
| Read token | 403 `a read-scoped token cannot widen: …`, checked before `to` |
| JSON | With `Accept: application/json`: 200 `{location, exp?}` instead of the redirect |
| Headers | Every answer, refusals included: `Cache-Control: no-store`, `Referrer-Policy: no-referrer` |

<span id="get-panel-js"></span>
### `GET /panel.js`

The devtools panel's script, embedded from `dist/panel/panel.js`. No auth, no host check: it is static and sits outside `/api`. 200 `text/javascript; charset=utf-8`, `Cache-Control: no-cache`; 500 when the bundle is missing from the build. Its group names no capability. [Install the panel](https://weftgo.dev/docs/observe/devtools/install/).

<span id="get-panel-config-json"></span>
### `GET /panel-config.json`

Capability `panel-config`, always on, unauthenticated. 200 `{endpoint, version, capabilities}`, `Cache-Control: no-store`: `endpoint` is the scheme (https only on a TLS connection; proxy headers are not read), the request's `Host` and the base. Served only when the `Host` passes the setup A host rule and any `Origin` is the same host, a loopback origin or an `AllowOrigins` entry; otherwise 404, not 403, so a panel that cannot use it removes itself. Captured:

```json
{"endpoint":"http://127.0.0.1:7331/","version":"v0.20.2","capabilities":["requests","steps","export","logs","diff","traces","search","stats","manifests","spans_tree","timeline","pricing","delete","proposals","live","scope_tags","ingest","auth","panel_token_tags","handoff","panel-config","runtimes","preview","target_check","runtime_forget","run_commands","breakpoints","steer","cancel","playground"]}
```

<span id="the-ui-shell"></span>
### `GET /` (the UI shell)

Every path no route claims. Files under `assets/` are `Cache-Control: public, max-age=31536000, immutable` (a missing one is 404 `no asset <path>`); a path naming another embedded file (`favicon.svg`) serves that file with `no-cache`; every other path answers the single-page shell, `text/html`, `no-cache`, with `<base href>` set to Studio's base and `studio.Title` as its title. No auth and no host check: the API behind it is what is walled. A method other than `GET` or `HEAD` is 405 `the studio UI is static: GET only`. [Studio's pages](https://weftgo.dev/docs/reference/studio-urls/) lists the paths the shell routes.

<span id="otlp-ingest"></span>
## OTLP ingest

`POST /v1/traces` and `POST /v1/logs` are an OTLP/HTTP receiver ([`ingest.Traces`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/ingest#Traces) and [`ingest.Logs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/ingest#Logs) in package `studio/ingest`, 0.7.0), capability `ingest` unless `studio.NoIngest()`. They sit outside `/api`, so the API's `Token` does not apply. [Send records from any language](https://weftgo.dev/docs/observe/other-languages/).

| Aspect | Behaviour |
|---|---|
| Content-Type | `application/x-protobuf` or `application/json` (protojson). Else 415 `Content-Type must be application/x-protobuf or application/json` |
| Content-Encoding | none, `identity` or `gzip`. Else 415; a bad gzip stream: 400 |
| Size | [`ingest.MaxBody`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/ingest#MaxBody): 16 MiB after decompression; above it 413 `request body exceeds 16 MiB after decompression` |
| Who | With `studio.IngestToken(tok)`: `Authorization: Bearer <tok>` on every POST, loopback included. Without one: a loopback socket peer only, refused when the request carries `Forwarded`, `X-Forwarded-For`, `X-Real-Ip`, or an `Origin` that is not allowed. Every refusal: 401 `ingest requires Authorization: Bearer <ingest token>`. `/api/meta`'s `ingest_open` says which applies |
| Pipeline | Decode, publish every record to the live hub (deltas and attempt frames included), then write. A write failure: 503 `unavailable`, so the exporter retries. On a database that publishes no run frames of its own (ClickHouse), the receiver also publishes a run frame for every run the batch touched, derived runs included (0.15.0) |
| 200 | An empty export response in the request's format: zero bytes of protobuf, or `{}` as JSON; `partial_success` is never set |
| Error body | Every refusal is Studio's JSON error, `{"error": {"code", "message"}}` as `application/json`, even to an `application/x-protobuf` request: never an OTLP `google.rpc.Status`. A protobuf-only exporter cannot decode it; act on the status code |
| Other | 400 for an undecodable body; a 4xx is counted in `/api/meta`'s `ingest.refused` and logged as a rate-limited WARN; an unknown path under `v1/` is 404 |

```sh
curl -s -w ' %{http_code}\n' -X POST -H 'Content-Type: application/json' \
  --data '{"resourceSpans":[]}' http://127.0.0.1:7331/v1/traces
```

```text
{} 200
```

<span id="playground-routes"></span>
## Playground routes

Registered only under `studio.Playground(true)` (`weft studio` turns it on; `--no-playground` turns it off). Studio enqueues each command for a connected runtime, which runs it in the app: [The playground](https://weftgo.dev/docs/observe/playground/overview/). Bodies are capped at 4 MiB.

<span id="get-api-runtimes"></span>
### `GET /api/runtimes`

Capability `playground`; any identity. 200 `{runtimes}`, newest `last_seen` first:

| Field | Meaning |
|---|---|
| `id`, `host`, `pid`, `cwd`, `service`, `env` | The runtime. `cwd` only to the server-or-loopback rule, never to a panel token |
| `studio_url`, `weft_version` | The Studio the runtime's link dialled, under `cwd`'s rule, absent in process (0.19.0); the weft the runtime was built with |
| `connected_since`, `last_seen`, `connected` | `connected`: a live command stream now; a dropped runtime stays listed with `false` until pruned |
| `restored` | Listed from the store after a Studio restart and not registered since |
| `sessions`, `breakpoints_own` | It registered `runtime.Sessions`; its breakpoints also park the app's own runs (built with `runtime.Breakpoints()`) |
| `agents` | `[{name, manifest_hash, model_provider?, models, resolver, defaults, tools: [{name, side_effects, allow, approval?}], instructions}]`. `manifest_hash` is the registered agent's `weft.manifest.hash` (0.19.0); `model_provider` its own model's provider (`wefttest` for a test script); `approval` marks a tool built with `RequireApproval`. `defaults` is absent for a runtime older than the option lab. A read token gets no `instructions`, no `defaults.tool_choice.name` and no `defaults.stop` |
| `breakpoints`, `breakpoints_set_at`, `breakpoints_surface`, `breakpoints_by` | The breakpoint set (never null); when Studio set it and through which surface (`runtimes`, or `api` for a `PUT` that named none), kept in the command store across restarts (0.20.0); and where a non-empty set came from: `studio`, `runtime` (its registration carried it) or `store` (restored after a restart) |

Captured from a scratch app holding the link (trimmed: `cwd` and times removed):

```json
{
  "runtimes": [{
    "id": "rt_4bccd920952a6381", "host": "build-01", "pid": 3019082, "service": "refb1app", "env": "",
    "connected": true, "sessions": false, "breakpoints_own": false,
    "agents": [{
      "name": "support-bot", "models": [], "resolver": false,
      "defaults": { "max_steps": 10, "parallelism": 4, "thinking": "", "tool_choice": { "mode": "auto" } },
      "tools": [{ "name": "lookup_order", "side_effects": "safe", "allow": false }],
      "instructions": "You are a support agent."
    }],
    "breakpoints": []
  }]
}
```

<span id="post-api-playground-runs"></span>
### `POST /api/playground/runs`

Starts a run or a replay on a runtime: capability `playground`. [Run experiments](https://weftgo.dev/docs/observe/playground/experiments/) and [Replay a run](https://weftgo.dev/docs/observe/playground/replay/).

| Field | Values |
|---|---|
| `runtime` | Required: a registered runtime id |
| `agent` | An agent the runtime registered |
| `command_id` | Optional idempotency key, `[A-Za-z0-9._:-]{1,128}`; Studio mints `cmd_` plus a ULID |
| `input` | The turn's user message (with `from_step` 0 only) |
| `source` | `{run_id, from_step}`: the run to replay and the step to re-run from |
| `transcript_edits` | `[{kind, step, call_id?, tool_result?, content?, args?, index?}]`; `kind` is `tool_result`, `reply`, `user`, `tool_args` (checked against the step's catalog schema) or `insert`; no kind is the pre-F2 reading. They need a source and `from_step` > 0 |
| `overrides` | `instructions`, `tools_enabled`, `model`, `thinking` (`off`, `low`, `medium`, `high`), `options {max_steps, parallelism, temperature}`, `params {top_p, max_tokens, stop, seed}`, `tool_choice {mode, name}`, `park_on`, `only_tools`: narrowing or neutral only. `only_tools` applies when non-empty, else `tools_enabled`; when both are empty (`[]`) or absent the run gets every tool, so a command cannot turn every tool off |
| `engine` | `live` (default) or `scripted` (the source run's recorded turns, zero tokens) |
| `side_effects` | `substitute` (default), `park` or `allow` |
| `thread` | `ephemeral` (default) or `fork` (a new session with lineage; needs `runtime.Threads` on the runtime) |
| `cross_agent` | `true` replays a source run recorded by another agent on this one (0.19.0). Without it that is a 400: `source run R is agent A; this command targets agent B: send agent "A" to replay it as recorded, or cross_agent: true to replay it as B anyway` |
| `experiment_id`, `public_id` | The experiment the run joins: any id of `[A-Za-z0-9._:-]{1,128}`, saved or not; the public id a panel token must send as its own |

| Status | When |
|---|---|
| 202 | `{"command_id": "cmd_…", "state": "queued"}`; poll [`commands/{id}`](#get-api-playground-commands-id) |
| 400 | A refusal naming its rule: `unknown engine warp`, a scripted engine with an instructions or model override, edits without a source. Also `temperature must be between 0 and 2`, a tool not in the manifest, a derived source run (badge `derived`). A runtime too old for the request is refused too: `runtime predates the option lab: upgrade weft/runtime to use params, tool_choice, park_on, only_tools`, `runtime predates transcript edit kinds: upgrade weft/runtime to use user, tool_args, insert edits`, `runtime predates replay across a compaction: …; upgrade weft/runtime`, … |
| 403 | A read token (`this token is read-only: …`); a playground token outside its public id, or with `experiment_id`; a widening override (`max_steps may only lower the agent's cap`, `only_tools may only narrow tools_enabled: …`, `tool X is not opted in for real side effects`) |
| 404 | `unknown runtime <id>`, `unknown agent <name>`, `unknown source run <id>` |
| 409 | `command id X was already used` |
| 503 | `runtime <id> is not connected` |

The 400 rules a hand-written body meets, by field (`POST /api/playground/preview` turns the scripted engine's override, edit and step-count refusals into `warnings`; a missing source stays a 400 there too):

| Field | Refused with |
|---|---|
| `command_id`, `experiment_id` | `command_id must be 1 to 128 characters of [A-Za-z0-9._:-]`, `experiment_id must be 1 to 128 characters of [A-Za-z0-9._:-]` |
| `source.from_step` | Negative: `source.from_step must be 0 or more`. An `input` with `from_step` > 0: `input replaces the turn's user message only when from_step is 0: …` (edit step 0's message with a `user` edit instead) |
| `engine: "scripted"` | No source: `the scripted engine replays a source run's recorded turns: a source run is required`. An instructions or model override: `scripted engine with an instructions override would silently replay the old answer (WEFT-PLAYGROUND §5.5)` (and the `model` form). Transcript edits: `… transcript edits need engine live`. `from_step` equal to the source's step count: `the scripted engine has no recorded turn for step N: the source never answered it (use engine live)` |
| `thread: "fork"` | No source: `fork mode forks a source turn's session: a source run is required`. No or empty `input`: `fork mode continues the conversation: an input is required`. `from_step` > 0: `fork mode re-runs no steps (from_step is the ephemeral verb); send an input instead`. Any other mode: `unknown thread mode X` |
| `overrides.options` | A closed set: `max_steps`, `parallelism`, `temperature`; any other key is `unknown option <key>`. `max_steps` and `parallelism` must be whole numbers from 1 to 1,000,000 (`<key> must be a whole number from 1`); `temperature` 0 to 2 |
| `overrides.params` | `top_p must be between 0 and 1`, `max_tokens must be positive`, `stop takes at most 4 sequences, got N`, `stop sequences must be non-empty`; any `seed` |
| `overrides.thinking` | `unknown thinking level X` |

<span id="get-api-playground-commands-id"></span>
### `GET /api/playground/commands/{id}`

Capability `playground`. 200 `{command_id, state, run_id, status?, error, reason?, created, updated}`: `state` is `queued`, `accepted`, `rejected`, `finished` or `lost`; `status` is `succeeded` or `failed` once finished; `error` is the run's error, a rejection's reason or why the command was lost, else `null`. `reason` (0.19.0) reads a scripted engine's miss out of `error`: `{kind: "scripted_miss", step, components, message}`; absent for any other error. A panel token reads only its own public id's commands, a read token included. 404 `unknown command <id>`. Captured:

```json
{"command_id":"cmd_01M57QNZ1KYYPGTDH17SDAEV4C","state":"finished","run_id":"pg_01M57QNZ1KRRJ82F3TMR6C9VG4","status":"failed","error":"weft: run failed at step 0: model stream: wefttest: model script exhausted (agent made more model calls than the script provides)","created":"2026-10-18T16:47:02.451313998+02:00","updated":"2026-10-18T16:47:02.452318302+02:00"}
```

<span id="post-api-runs-id-approvals"></span>
### `POST /api/runs/{id}/approvals`

A parked run's decision: capability `playground`. Body `{call_id, decision, reason?, content?}`; `decision` is `approve` (the handler runs), `deny` (with the reason) or `resolve` (`content` is the result). [Breakpoints and decisions](https://weftgo.dev/docs/observe/playground/breakpoints/).

| Status | When |
|---|---|
| 202 | `{command_id, state: "queued"}` for a runtime-started run; for an app-owned turn under `runtime.Sessions`, `{command_id, state, run_id, runtime_id}` |
| 400 | `unknown decision X`, `an approval needs a call_id`, `run <id> is not parked: …`, `call C is not pending on run R (pending: …)` |
| 403 | A read token; out of scope; an [app-owned turn](#app-owned-turns) |
| 404 | `unknown run <id>` |
| 503 | The runtime is not connected. Studio mints the approval's command id, so there is no reused-id 409 |

<span id="post-api-runs-id-steer"></span>
### `POST /api/runs/{id}/steer`

Capability `steer`. Body `{"message": "…"}`; without it, 400 `steer body: message is required`. A runtime-started run: 202 `{"steered": true}`, best effort, no command row, and no state check: a run that already finished still gets the 202. An app-owned turn under `runtime.Sessions`: 202 `{command_id, state, run_id, runtime_id}`; without it, 403 [app-owned turn](#app-owned-turns). A parked app turn is refused at once with 409: `no running turn to steer: run R is parked: decide its pending calls (approve/deny) instead`. So is one whose row reads `succeeded` or `failed`: `… already finished (succeeded)`. 403 for a read token or out of scope; 404 `unknown run <id>`; 503 when the runtime is not connected.

<span id="post-api-runs-id-cancel"></span>
### `POST /api/runs/{id}/cancel`

Capability `cancel`; no body; the same auth as steer. Best effort: the link's cancel frame for the command holding the run.

| Status | When |
|---|---|
| 202 | `{run_id, command_id, runtime_id, state: "cancelling"}` |
| 403 | A read token; out of scope; an app-owned turn without a `runtime.Sessions` runtime ([app-owned turns](#app-owned-turns)) |
| 404 | `unknown run <id>` |
| 409 | Parked (`run R is parked: decide its pending calls (approve/deny) instead`), or finished (`run R already finished …`). An app-owned turn under `runtime.Sessions` is never cancelled from here: `cancel is not supported on an app turn: run R is the app's own turn` |
| 503 | `runtime X is not connected` |

<span id="put-api-runtimes-id-breakpoints"></span>
### `PUT /api/runtimes/{id}/breakpoints`

Capability `breakpoints`. Body `{"tools": [...], "surface"?: "runtimes"}`; an empty list clears. `surface` (0.20.0) names the page that sent the set, read back as `breakpoints_surface`; it must match `[a-z][a-z0-9_-]{0,31}`, else 400 `surface must be a short lowercase word ([a-z][a-z0-9_-]{0,31}), e.g. runtimes`. Server or setup A only: every panel token gets 403 `breakpoints park every future run of the runtime: the server token, not a panel token`. 200 `{"tools": [...]}`: the set is delivered to the runtime and stored. The runtime parks those tools on every run it starts and, with `breakpoints_own`, on the app's own runs built with `runtime.Breakpoints()`. A clear answers `{"tools": null}` (captured). 400 for a tool no agent of the runtime registered; 404 `unknown runtime <id>`; 503 when not connected, and nothing is stored.

<span id="delete-api-runtimes-id"></span>
### `DELETE /api/runtimes/{id}`

Forgets a runtime that is gone: its row and its breakpoint set leave the list and the command store, and its commands and routes stay as history. 204 once it is gone. 409 `runtime <id> is connected: only a runtime that is gone is forgotten`, or `… still has queued or accepted commands: forget it once they resolve`. 404 for an id nothing registered. Runtime-wide, so a panel token gets 403. Capability `runtime_forget` (0.19.0). [Forget a runtime](https://weftgo.dev/docs/observe/playground/runtimes/#forget-a-runtime).

<span id="post-api-playground-preview"></span>
### `POST /api/playground/preview`

The replay's exact first request beside the recorded step's, and their diff: pure assembly, no model call and no runtime needed.

| Aspect | Behaviour |
|---|---|
| Capability | `preview` |
| Body | The body of [`POST /api/playground/runs`](#post-api-playground-runs), with a `source` |
| Who | Scoped. A read token may preview its own public id; its system prompt, tools and view messages read `hidden` |
| 200 | `{source, agent, engine, runtime, will_send, was_sent, diff, compacted_at, warnings, unchecked, scripted_hit, scripted_key_match}` |
| `scripted_hit`, `scripted_key_match` | Whatever the engine (0.19.0): per step from `from_step` through the first miss, `{step, hit, because}`, whether the scripted engine holds a recorded answer. `scripted_key_match` sums it up: `{ok, because, step, message?}`, the first missing step and the sentence a failed scripted run's command reads too |
| `will_send`, `was_sent` | `{system, messages, tools, model, params, thinking, tool_choice}`, with `system_source`, `tools_source` and `params_source` (`override`, `agent` or `recorded`), and `system_badge`, `messages_badge` and `tools_badge` where a block is a hole; a side may carry `badge`, `reason`, `fix` for the request as a whole |
| `warnings`, `unchecked` | `[{kind, message}]`; the overrides only a registered agent could check |
| 400 | No source (`a preview needs a source run: …`), `thread: "fork"`, `from_step` past the last step, a derived source (badge `derived`) |
| 409 | The source transcript does not rebuild; the message only, no badge |

<span id="post-api-playground-fixtures"></span>
### `POST /api/playground/fixtures`

`wefttest` replay fixtures rebuilt from the run's records, returned, never written by Studio.

| Aspect | Behaviour |
|---|---|
| Capability | `playground` |
| Body | `{run_id, tools?}`; `tools` keys a run recorded before request records |
| 200 | `{run_id, agent, files: [{name, body}]}` |
| 400 | `fixture body: run_id is required`; a derived run (badge `derived`) |
| 403 | A read token (badge `hidden`), checked before the body; out of scope |
| 404 | `unknown run <id>` |
| 409 | The transcript cannot be fixtured: the hole as `badge` (`stripped`, `gap` or `derived`). Without a badge: `the run recorded no assistant turns to fixture` |

<span id="get-api-experiments"></span>
### `GET /api/experiments`

Capability `playground`; the server token or setup A only: every panel token gets 403, reads included. `limit`: 50 by default, at most 200. 200 `{experiments, total}`, most recently updated first; each saved with its whole command (`engine`, `side_effects`, `thread`, `from_step`, `source_run_id`, `transcript_edits`, variants with their overrides and modes, inputs) plus `created`, `updated`, `run_count`, `succeeded`, `last_run` and cost. `/api/runs` and `/api/search` filter its runs by `experiment_id`.

<span id="post-api-experiments"></span>
### `POST /api/experiments`

Creates or replaces a saved experiment by `id` (`[A-Za-z0-9._:-]{1,128}`, the `weft.experiment.id` its runs carry); fields left out are cleared. At least one variant and one input. 200: the experiment's detail document, with `runs: null`; 400 naming the rule (`engine must be live or scripted`, …); 403 for any panel token.

<span id="get-api-experiments-id"></span>
### `GET /api/experiments/{id}`

The experiment and `runs`: its top-level runs as run rows, oldest first, read 20 pages of 500, so at most 10,000. 404 `unknown experiment <id>`; 403 for any panel token.

<span id="app-owned-turns"></span>
### App-owned turns

A run the app started itself, not a playground command, is an app-owned turn. Approvals, steer and cancel on it go through the app's `runtime.Sessions` when a connected runtime of the run's service registered it; otherwise they are 403 with a `fix` beside the error. The cases, in the order Studio checks them:

| Case | Message | `fix` |
|---|---|---|
| The service's `Sessions` runtime disconnected | `app-owned turn · read-only: the app's runtime <rt> of service <svc> disconnected — last seen <time>` | `restart the app: its runtime link registers again` |
| A runtime, no `Sessions` | `app-owned turn · read-only: run <id> is the app's own, and no connected runtime of its service <svc> acts on the app's sessions` | `set runtime.Sessions(resolver) at runtime.Install in the app (service <svc>): …` |
| None here; this process's link dialled another Studio (server or loopback only) | `app-owned turn · read-only: no runtime of service <svc> is connected here — the app's link dialled <url>` | `open the panel there (data-endpoint), or link in-process: runtime.Local(srv)` |
| No runtime of the service connected | `app-owned turn · read-only: no runtime of service <svc> is connected` | `open the runtime link in the app: WEFT_ENV=dev (or runtime.Enabled(true)) at runtime.Install, with runtime.Sessions(resolver)` |
| A `Sessions` runtime, but not a session turn with a public id | `app-owned turn · read-only: run <id> is not a turn of a session with a public id` | A plain `Generate`'s park: `resume it in your app; to decide here, run it as a session turn with thread.PublicID(...) (weft/thread)`. A session turn without a public id: `run the agent through weft/thread with thread.PublicID(...): runtime.Sessions resolves a session by its public id` |

[Decide an app's own turns](https://weftgo.dev/docs/observe/devtools/app-turns/) covers the setup.

<span id="runtime-link"></span>
## The runtime link

Three routes the app's [`weft/runtime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime) calls to hold the playground link: not for browsers or scripts. Capability `runtimes`; server to server (every panel token: 403). Bodies are capped at 8 MiB, since a registration carries one manifest per agent. [Connect your app to the playground](https://weftgo.dev/docs/observe/playground/connect/).

`weft/runtime` (Go) is the only runtime-link client today. The wire below is documented for future clients in other languages; none ships yet.

| Route | Body | Answer |
|---|---|---|
| `POST /api/runtime/register` | `{runtime_id, host, pid, cwd?, instance?, service, env, weft_version, budget, threads, sessions, breakpoints_own, breakpoints, agents, heartbeat_ms}`; each agent `{name, manifest, models, resolver, limits, defaults, side_effects, allow}` | 200 `{runtime_id, commands_url}`. 400 without `runtime_id` or agents. An id another process holds (a live stream, or queued or accepted work) is answered `<id>-<pid>`, which the client adopts. Without `instance`, Studio WARNs once: a client must send it to keep at-most-once across restarts |
| `GET /api/runtime/commands?runtime=<id>` | — | SSE. On open: `ping`, the stored breakpoint set, then queued commands after `Last-Event-ID` (a `cmd_` id Studio never minted re-sends nothing). Frames `run`, `approve`, `breakpoints`, `steer`, `session`, `cancel` (no `id:` line), `ping` every 15 s. A new stream replaces the old. 400 without `runtime`, 404 for an unregistered id, 405 for `HEAD` |
| `POST /api/runtime/acks` | `{command_id, state, run_id?, status?, error?, reason?}` (`reason`, 0.19.0: `{kind, step, components}`, what the runtime knows of why its run failed, such as `scripted_miss`); `state` is `accepted`, `rejected` or `finished` | 200, empty. A repeated `accepted` ack is the heartbeat, every minute. In order: 400 `ack body: command_id is required`; 404 `unknown command <id>`; 400 `ack body: unknown state X`; 409 `command <id> was marked lost before this accepted ack (…): it must not run` |

### The registration body

What a runtime client sends to `POST /api/runtime/register`. Go types `Registration`, `AgentRegistration`, `AgentLimits`, `AgentDefaults` and `Budget`; `weft/runtime` mirrors them, with the JSON pinned by tests.

| Key | Type | Meaning |
|---|---|---|
| `runtime_id` | string | Required (400 `register body: runtime_id is required`). Studio may answer another id, which the client adopts |
| `host`, `pid`, `cwd?` | string, int, string | The process; `cwd` is one input of the stable id |
| `instance?` | string | Random per link, kept across its reconnects; with `host` and `pid` it tells a reconnect of the same process from a second process |
| `studio_url?` | string | The Studio the link dialled, credentials stripped; `""` in process (0.19.0). `/api/runtimes` serves it |
| `service`, `env`, `weft_version` | string | The app's service name, its `WEFT_ENV`, its weft version |
| `budget` | `{max_tokens_per_experiment, max_runs_per_experiment}` | The runtime's per-experiment caps, both int64 |
| `threads`, `sessions`, `breakpoints_own` | bool | `runtime.Threads` set (fork mode works); `runtime.Sessions` set (app-owned turns route to it); an agent built with `runtime.Breakpoints()`. An older runtime sends `false` |
| `breakpoints` | string list | The breakpoint set the runtime holds now; a Studio that holds none for this id adopts it |
| `agents` | list, at least one | 400 `register body: no agents` when empty. One object per exposed agent, below |
| `heartbeat_ms` | int64 | The cadence of the repeated `accepted` ack; 0 (an older runtime) gets the finish watch only when its stream ends |

Each `agents` entry:

| Key | Type | Meaning |
|---|---|---|
| `name` | string | The agent's name |
| `manifest` | string | The agent's one-agent `weft.Manifest` document, as JSON text. Its tool names, input schemas, model name and instructions are read from it; a manifest that does not parse leaves the agent out of the remembered manifests |
| `manifest_hash?` | string | SHA-256 (lowercase hex) of `manifest` as registered: the `weft.manifest.hash` the agent's runs carry (0.19.0). Without it Studio hashes `manifest` itself |
| `models` | string list | The alternate models a command's `model` override may name |
| `resolver` | bool | The runtime holds a `runtime.ModelResolver`, so a model outside `models` is the runtime's to decide |
| `limits` | `{max_steps, parallelism}` | The agent's own lower-only bounds |
| `defaults` | `{max_steps, parallelism, thinking, thinking_budget?, temperature?, top_p?, max_tokens?, seed?, stop?, tool_choice {mode, name?}}` | The agent's run defaults in the override vocabulary; `thinking` `""` is the provider default; `thinking_budget` the default budget in tokens, absent when none; `tool_choice.mode` `auto` when none was set. A runtime older than the option lab sends the zero value |
| `side_effects` | object, tool name → `"safe"` or `"never"` | Each tool's replay class (`weft.Replay`); unannotated is `never` |
| `allow` | string list | The tools opted in with `runtime.AllowSideEffects` |

### Frames on the command stream

Each SSE frame's `data` is one JSON object. Frames that carry an `id:` line use the command id there; the runtime acks `run`, `approve` and `session` frames by that id. Studio keeps no command row for `breakpoints` or `steer`, and the runtime acks neither.

| Event | `id:` | `data` (Go type) |
|---|---|---|
| `run` | the command id | `Command`: `{command_id, agent, source, input, overrides, transcript_edits, engine, side_effects, thread, experiment_id, actor, public_id}`. `source` is `{run_id, from_step}` or `null`; `input` a string or `null`; `overrides` and `transcript_edits` the [`POST /api/playground/runs`](#post-api-playground-runs) shapes; `actor` is `local`, `server` or `panel:<public id>` |
| `approve` | the command id | `ApprovalDecision`: `{command_id, run_id, call_id, decision, reason?, content?, actor?}`; `decision` is `approve`, `deny` or `resolve` |
| `session` | the command id | `SessionCommand`: `{command_id, verb, public_id, session_id, run_id, call_id?, decision?, reason?, content?, message?, actor?}`; `verb` `decide` carries `call_id`, `decision`, `reason`, `content`; `steer` carries `message`; `cancel` nothing more |
| `breakpoints` | a fresh id | `Breakpoints`: `{tools}`; an empty list clears. Sent on every stream open, before the backlog |
| `steer` | a fresh id | `SteerMessage`: `{run_id, message}` |
| `cancel` | none | `{command_id}`: the command whose run to cancel |
| `ping` | none | `{}`, every 15 s |

How a runtime answers a `session` frame it does not carry out. In the cases listed, nothing is written to the session:

| Ack | Reason |
|---|---|
| `rejected`, before the accepted ack | The runtime's refusals: `this runtime does not act on the app's sessions: runtime.Sessions(...) is not set`; `cancel is not supported on an app turn`; `no session for this public id`; `the session resolver answered session S for public id P, not the run's session S2`. The session's own: `the app is writing this session; fork instead` (the writer lease is taken); `this session requires signed decisions: decide it in the app (thread.DecideSigned)`. A body check: `unknown session verb …`, `a session command needs public_id, session_id and run_id`, `unknown decision …`, `a decision needs a call_id`, `a steer needs a message`. A pending check: `call … is not pending on session …`, `session … has no parked call: …`, `call … was parked by run …, not …`. The resolver's or the lease claim's own error, as its text: `session resolver timed out`, `session claim timed out`, `session resolver panicked: …`. An `ErrStale` on the second open, or any other error the resolver returned, reads the same way |
| `finished` with `status: "failed"`, after the accepted ack | `no running turn to steer for run <id> (…)`: whether a turn runs is known only under the session's lock. `the app is writing this session; fork instead`: the lease was lost between the claim and the write. Any other error `Decide` or `Steer` returns, as its own text |

**Contract and code.** The godoc of `SessionCommand` (studio/runtime/runtime.go:473-480) lists four refusals, all "before any write", including `no running turn to steer`. The code holds six refusal texts (runtime/sessions.go:30-37), and it sends `no running turn to steer`, and sometimes the locked reason, as a failed finish after the accepted ack (runtime/sessions.go:104-107, 139-145).

Command states and timers:

| Transition | Rule |
|---|---|
| `queued` → `accepted` | The runtime acks within Studio's 30 s window (it validates, fetches the source and resolves the model within 25 s); no ack in time is `lost`, and a stream that ends loses its queued commands at once (`runtime disconnected before the ack`) |
| `accepted` → `finished` | A `finished` ack. Silent for `max(10 min, 3 beats)` after its stream ended or its last beat: `lost`. An accepted ack Studio did not take runs nothing |
| `rejected` | The runtime refused it, with its reason |
| Restart | Commands, routes, breakpoints and registrations persist through `obsdb.CommandStore`; a restarted Studio decides lost from the stored state and never re-sends an accepted command |
| Ids | Stable per service, cwd and agents: `rt_` plus 16 hex digits of SHA-256 |

### The Go side: `studio/runtime`

The Go side is package [`studio/runtime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/runtime), the server these routes run on. `studio.Server.Runtime` returns its server under `Playground(true)`, and `runtime.Local(srv)` drives it in process.

| Symbol | What it is |
|---|---|
| [`New(opts ...Option)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/runtime#New) | Builds a `RuntimeServer` with the default timers (0.15.0: it took no options before, the framework module's breaking line) |
| [`Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/runtime#Option), [`WithStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/runtime#WithStore) | Options; `WithStore(obsdb.CommandStore)` writes through and loads at `New` |
| [`RuntimeServer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/runtime#RuntimeServer) | The registry of runtimes. Fields `AckDeadline` (30 s: queued without an ack), `FinishDeadline` (10 min: accepted without word), `PingEvery` (15 s), `Retention` (24 h: terminal commands, run routes, a gone runtime holding breakpoints), `WriteTimeout` (30 s per frame). At most 10,000 command rows are kept in memory, the oldest terminal ones dropped first |
| `RuntimeServer.Mount`, `RuntimeServer.MountGuarded` | Mount the three routes, bare or each wrapped in a guard; Studio passes its server-to-server guard |
| `RuntimeServer.Enqueue(runtimeID, Command) (Command, error)` | Queue a `run` frame. It validates the command id, its uniqueness and the connection (`ErrInvalidCommandID`, `ErrDuplicateCommand`, `ErrUnknownRuntime`, `ErrNotConnected`), not the command body: the playground route does that; it mints `command_id` when empty and returns the command as queued |
| `RuntimeServer.EnqueueApproval(runtimeID, ApprovalDecision) (ApprovalDecision, error)` | Queue an `approve` frame, minting `command_id`. `ApprovalDecision.PublicID` is `json:"-"`: never on the wire, it is the scope the command row and the resumed run carry, so a panel token can poll its own decision; empty takes the run's recorded scope |
| `RuntimeServer.EnqueueSession(runtimeID, SessionCommand) (SessionCommand, error)` | Queue a `session` frame for a runtime that registered `Sessions`, minting `command_id`; the row carries `PublicID` |
| `RuntimeServer.Steer(runtimeID, runID, message) error`, `RuntimeServer.Cancel(runtimeID, commandID)`, `RuntimeServer.CancelRun(runID) (CancelTarget, error)` | Best-effort steer and cancel frames. `CancelRun` finds the accepted command holding the run and returns a `CancelTarget {run_id, command_id, runtime_id}` |
| `RuntimeServer.SetBreakpoints`, `RuntimeServer.BreakpointsOf` | Deliver and store a breakpoint set (not connected: nothing stored); read it |
| `RuntimeServer.Command`, `RuntimeServer.CommandOf` | A command's lifecycle row; the command as enqueued |
| `RuntimeServer.Registration`, `RuntimeServer.Connected`, `RuntimeServer.Snapshot` | A runtime's registration; whether it holds a stream; the `/api/runtimes` rows |
| `RuntimeServer.RuntimeOf`, `RuntimeServer.PublicOf` | The runtime that started a run, from its acks; the public id it was scoped to |
| `RuntimeServer.SessionsRuntime`, `RuntimeServer.AnySessions`, `RuntimeServer.AnyOwnRuns` | The runtime acting on a service's sessions; whether any does; whether any parks the app's own runs (`/api/meta`'s `debug_scope`) |
| `RuntimeServer.Manifests() []ManifestSource` | The registrations' manifests, live first, then the most recently registered; about 64 are remembered, in memory. The bound is soft: past it the oldest manifest no connected runtime holds is dropped, one per registration, and a held one never is |
| `Registration.Agent(name)` | The named `AgentRegistration` of a registration, and whether it is there |
| `AgentRegistration` | One `agents` entry (above). Methods `IsAllowed(tool)` (on `allow`), `ManifestToolNames`, `ManifestToolSchemas`, `ManifestModelName`, `ManifestInstructions` (read from `manifest`) |
| `AgentLimits`, `AgentDefaults`, `Budget` | The `limits`, `defaults` and `budget` objects |
| `ApprovalDecision`, `SessionCommand`, `SteerMessage`, `Breakpoints`, `CancelTarget` | The frame payloads (above) and `CancelRun`'s answer |
| `RegisterResponse` | `{runtime_id, commands_url}`: the answer to `POST /api/runtime/register`; `runtime_id` is the id the client adopts |
| `Command`, `SourceSpec` | The `run` frame's payload (above). `SourceSpec` is its `source`, `{run_id, from_step}`: the run to re-run and the step to replay from. `Command.Runtime`, the runtime it was enqueued to, is `json:"-"` |
| `CommandStatus` | `{command_id, state, run_id, status?, error, created, updated}`: what `RuntimeServer.Command` returns and [`GET /api/playground/commands/{id}`](#get-api-playground-commands-id) serves. `status` is the finished run's `succeeded` or `failed`, absent until finished; `error` a failed run's error, a rejection's reason or what made the command lost, else `null` |
| `RuntimeView`, `AgentView`, `ToolView` | The rows of [`GET /api/runtimes`](#get-api-runtimes) that `RuntimeServer.Snapshot` returns. `ToolView` is one tool of a runtime's agent: `{name, side_effects, allow}`, one per tool of the agent's manifest: its replay class from the registration's `side_effects` (`safe` or `never`) and whether `runtime.AllowSideEffects` opted it in |
| `ManifestSource` | `{service, manifest_hash, live, registered_at, runtime_id, agents}`: one remembered registration manifest, a `sources[]` entry of [`GET /api/manifest`](#get-api-manifest). `Version`, the manifest documents' `weft` format version, is `json:"-"` and so never on the wire |
| `ManifestAgent` | `{name, manifest_hash}`: one agent of it, `manifest_hash` the `weft.manifest.hash` its runs carry. `Entry`, its object in the manifest, is `json:"-"` |
| `RuntimeServer.Close`, `RuntimeServer.Shutdown` | Stop timers and streams, drain the store (`Close`: a 5 s drain) |
| `VerbDecide`, `VerbSteer`, `VerbCancel` | A session command's verb: `decide`, `steer`, `cancel` |
| `StateQueued`, `StateAccepted`, `StateRejected`, `StateFinished`, `StateLost` | The command states |
| `ErrUnknownRuntime`, `ErrNotConnected`, `ErrDuplicateCommand`, `ErrInvalidCommandID` | Mapped to 404, 503, 409 and 400 |
| `ErrUnknownCommand`, `ErrUnknownRun`, `ErrRunFinished` | No such command; no runtime started the run; its command is no longer in flight |
| `ValidCommandID` | The `[A-Za-z0-9._:-]{1,128}` rule (0.8.0: a line break in a caller's id could forge frames on the stream) |

[`ExampleRuntimeServer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/runtime#example-RuntimeServer) mounts a server on a test mux, posts one registration and reads it back with `Snapshot`.

| Since | Change |
|---|---|
| 0.7.0 | The link: register, the SSE command stream, acks, the lost-command timers |
| 0.8.0 | `ValidCommandID`, `ErrInvalidCommandID`, `Retention`, `WriteTimeout`, `RuntimeView.Breakpoints`; command rows' `status` and `error`; a panel token may poll its own approval and steer the resumed run |
| 0.15.0 | Stable runtime ids; `cwd` and `instance` in the registration; approvals, steer and cancel on an app-owned turn answer 202 or 403; `New` takes options |

The package's 0.19.0 and 0.20.0 additions:

| Name | What it is |
|---|---|
| `RuntimeServer.CommandsOn(runID)` → `[]RunCommand` | The commands acting on one run, oldest first: `GET /api/runs/{id}/commands`. A `RunCommand` is a command's status plus `Verb` (`decide`, `steer`, `cancel`), `CallID`, `Decision` and `PublicID` |
| `RuntimeServer.Forget(id)` | `DELETE /api/runtimes/{id}`; `ErrConnected` for a runtime holding a live stream, `ErrRuntimeBusy` for one with queued or accepted commands |
| `RuntimeServer.HoldsInstance(instance)` | Whether a link with that registration instance registered here, connected or not |
| `RuntimeServer.SetBreakpointsFrom(id, tools, surface)` | `SetBreakpoints` naming the surface the set came through (0.20.0); `""` reads `BreakpointsSurfaceAPI`, `api` |
| `BreakpointsByStudio`, `BreakpointsByRuntime`, `BreakpointsByStore` | Where a runtime's breakpoint set came from, `RuntimeView.BreakpointsBy` |
| `Reason`, `ReasonOf(text)`, `ScriptedMissReason(step, components)`, `ReasonScriptedMiss` | A command's structured why: `{kind, step, components, message}`. `ReasonOf` reads a scripted miss out of an error text; `ScriptedMissReason` writes the same sentence for a miss predicted before Run |
| `AckReason` | `Ack.Reason`: `Reason` without Studio's sentence |

The package examples `ExampleReasonOf`, `ExampleScriptedMissReason`, `ExampleRuntimeServer_CommandsOn`, `ExampleRuntimeServer_Forget`, `ExampleRuntimeServer_HoldsInstance` and `ExampleAgentRegistration_ManifestModelProvider` show each.

## See also

- [Run Studio](https://weftgo.dev/docs/observe/studio/setup/)
- [Secure Studio](https://weftgo.dev/docs/production/security/)
- [Badges and holes](https://weftgo.dev/docs/reference/badges/)
- [The record contract](https://weftgo.dev/docs/reference/record-contract/)
- [weft CLI reference](https://weftgo.dev/docs/reference/cli/)

Packages: [`weft/studio`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio) · [`weft/studio/ingest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/ingest) · [`weft/studio/runtime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/runtime) · [`weft/obsdb`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb)
