Skip to content

How does the playground work?

View as Markdown

The playground re-runs your real agents from Studio. Studio sends a command; the package weft/runtime in your process runs it as an ordinary weft run of an agent you registered, with your tools, your model keys and your code. Studio never runs your agent. A replay keeps a recorded prefix, applies your changes, and runs the rest fresh, and a tool with side effects is never fired again silently: its call is answered from the record or parked, unless the tool’s code vouched it safe.

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

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

playground/main.go on GitHub

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

Your app dials Studio out over the runtime link; Studio never listens for it or calls into your process. In setup A the link is in-process; with weft studio it is HTTP to 127.0.0.1:7331. Connect your app has both.

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

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

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

The same commands drive two surfaces: Studio’s /playground page and the devtools panel’s experiment drawer. Each renders a control only for a capability Studio reports.

A replay re-runs model calls, and a model that called refund once will call it again. The command’s side_effects field says what happens to such a call. It is one of three modes, and the playground form’s select names them:

side_effectsThe form saysA never-class tool’s call
substitute (the default)substitute — recorded results, else parkanswered with the recorded result when the source made the same call; any other call parks
parkpark — every side-effect call waitsparks, every time: nothing is answered from the record
allowallow — runs the tools this app opted in (AllowSideEffects) for realthe tools named in runtime.AllowSideEffects run for real; the command is refused unless every tool it leaves on is opted in or vouched safe

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

Substitute matches by tool name and arguments, compared as canonical JSON. Repeated calls are answered in the order the source made them, and a recorded error stays an error. The runtime acts as the approval boundary’s resolver (ADR 0007): the run parks, and the runtime resumes it with weft.Resolve and the recorded content, as a new pg_ run; earlier legs read parked (gotcha). A miss stays parked for you to decide.

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

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

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

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

Two parks are never substituted, whatever the mode: a breakpoint and a command’s park_on.

weft.Replay sets a tool’s weft.ReplayPolicy, its side-effect class for re-runs. There are two values:

  • weft.ReplayNever is the default: an unannotated tool reports never through ToolDef.ReplayPolicy, as does any value other than safe. Nobody has vouched for it, so a re-run substitutes its call with the recorded result or parks it, and never fires it again silently.
  • weft.ReplaySafe says the call is idempotent and side-effect free. A re-run may execute it for real.

Like every tool option the last one wins: Replay(ReplayNever) after Replay(ReplaySafe) is never’s. ToolDef.ReplayPolicy reports the class; ExampleReplay prints lookup: safe and refund: never. The manifest writes replay_policy: "safe" only for a safe tool, so an unannotated agent’s weft.json does not change.

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

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

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

The playground form and both replay drawers mark each never-class tool with ⚠, titled “side-effect tool (ReplayPolicy never): substituted or parked, never re-fired silently — only side effects: allow runs it, if the app opted it in”. Beside the ⚠ of an approval tool they say needs approval, its hint that every live call waits for a decision and that never is the replay class. The other per-tool options are on Set per-tool policy.

Two more fields shape a command. The engine decides who answers the model calls:

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

Since 0.19.0 Studio’s forms choose the engine per command: scripted when the recording can answer, else live, and a form, link or saved experiment that names no engine means that choice, no longer live (Choose the engine).

The thread mode decides where the run lives:

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

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

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

Studio's playground over a recorded acme-support turn, on the acme-app runtime: variant A's source run, step, system prompt, tools, model, thinking, engine, side effects and where it writes, with the option fields below them and the experiment matrix beside the variantStudio's playground over a recorded acme-support turn, on the acme-app runtime: variant A's source run, step, system prompt, tools, model, thinking, engine, side effects and where it writes, with the option fields below them and the experiment matrix beside the variant
The playground over a recorded source run: one variant's prompt, tools, model, engine and side-effect mode, and the experiment matrix beside it.

The page holds:

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

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

studio.Playground(true) turns the routes and the runtime link server on. weft studio has it on by default (--no-playground turns it off). Server.Runtime returns the link server’s in-process side, a studio.RuntimeServer, which runtime.Local takes; it is nil without the option, and so are the routes.

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

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

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

  • It does not run your agent in Studio. No model call, tool call or prompt leaves Studio for a provider. Your process does all of it, and a stopped process runs nothing.
  • It does not widen your code. No tool, model or higher limit can be added from Studio.
  • It does not touch your app’s own runs, except through what you opt into: runtime.Breakpoints() on an agent, and runtime.Sessions for your thread turns (Approve and steer your app’s own turns). A budget breach rejects the next experiment command, never your own runs.
  • It does not make a model deterministic. A replay is exact up to the model’s input (ADR 0029): what a live model answers is new.

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

playground/main.go
// Command playground is the Playground pages' program: setup A with the
// playground on. It records every run into the local sink, serves Studio
// over the same handle with studio.Playground(true), registers one support
// agent through runtime.Local, and runs that agent once so the playground
// has a source run to replay.
//
// go run ./playground [-addr 127.0.0.1:8080]
//
// It prints Studio's URL and the source run's id, then serves until
// Ctrl-C. The other functions are the pages' variants: runtime.Studio for
// a weft studio binary, a model resolver, and an agent built with
// runtime.Breakpoints(). main_test.go runs each of them offline.
package main
import (
"context"
"errors"
"flag"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"strings"
"sync/atomic"
"github.com/weftgo/weft"
"github.com/weftgo/weft/otel"
"github.com/weftgo/weft/runtime"
"github.com/weftgo/weft/studio"
"github.com/weftgo/weft/wefttest"
)
// OrderInput is the input of every order tool.
type OrderInput struct {
OrderID string `json:"order_id" jsonschema:"the order to act on"`
}
// EmailInput is send_email's input.
type EmailInput struct {
To string `json:"to" jsonschema:"the recipient"`
Body string `json:"body" jsonschema:"the message"`
}
// refundsIssued and emailsSent count the handlers that really ran: the
// tests read them to prove a replay did or did not fire a side effect.
var refundsIssued, emailsSent atomic.Int64
// supportTools are the agent's three tools, one per side-effect class.
func supportTools() []weft.Option {
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
func(ctx context.Context, in OrderInput) (string, error) {
return `{"order_id":"` + in.OrderID + `","status":"shipped"}`, nil
},
weft.Replay(weft.ReplaySafe), // a read: a replay may run it for real, in every mode
)
refund := weft.Tool("refund", "Refund an order.",
func(ctx context.Context, in OrderInput) (string, error) {
refundsIssued.Add(1) // stands in for the payment provider's call
return "refunded order " + in.OrderID, nil
}) // unannotated: ReplayNever, so a replay never re-fires it
email := weft.Tool("send_email", "Email the customer.",
func(ctx context.Context, in EmailInput) (string, error) {
emailsSent.Add(1)
return "sent to " + in.To, nil
})
return []weft.Option{lookup, refund, email}
}
// newAgent is the support agent the runtime registers. extra adds
// options a variant needs (runtime.Breakpoints, below).
func newAgent(model weft.Model, extra ...weft.Option) *weft.Agent {
return weft.New(model,
weft.Name("acme-support"),
weft.Instructions("You are Acme's support agent."),
weft.MaxSteps(10),
weft.Options(supportTools()...),
weft.Options(extra...),
)
}
// newDebuggableAgent is the agent built with runtime.Breakpoints(): the
// breakpoints Studio sets park its own runs too, not only the runs the
// runtime starts.
func newDebuggableAgent(model weft.Model) *weft.Agent {
agt := weft.New(model,
weft.Name("acme-support"),
weft.Options(supportTools()...),
runtime.Breakpoints(), // Studio's breakpoints park this agent's own runs too
)
return agt
}
// resolveModel is the app's ModelResolver: a model a command names that
// runtime.Models does not list reaches it before the command is acked.
//
func resolveModel(ctx context.Context, name string) (weft.Model, error) {
model, ok := strings.CutPrefix(name, "acme/")
if !ok {
// The text is the rejected command's reason: no key, no URL.
return nil, errors.New("this app serves acme/* models only")
}
return newProviderModel(model), nil // build the client from the app's own credentials
}
// newProviderModel stands in for a provider adapter (anthropic.Model,
// openai.Model, …): a scripted model, so the program runs offline.
func newProviderModel(name string) weft.Model {
return wefttest.Script(wefttest.Say("(" + name + ") Your order shipped yesterday."))
}
// installStudio registers agt with a Studio reached over HTTP: the weft
// studio binary (setup B) or a hosted one (setup C). It opens the link
// only under WEFT_ENV=dev.
func installStudio(studioURL, token string, agt *weft.Agent, alt weft.Model) (shutdown func()) {
shutdown = runtime.Install(
runtime.Studio(studioURL, token), // the Studio to dial, and its token
runtime.Agents(agt), // the agents experiments may run
runtime.Models(map[string]weft.Model{"acme-small": alt}), // alternates, by display name
runtime.ModelResolver(resolveModel), // any other model name: the app decides
runtime.Limits(runtime.Budget{MaxTokensPerExperiment: 200_000, MaxRunsPerExperiment: 2}),
runtime.AllowSideEffects("send_email"), // runs for real only under side_effects "allow"
)
return shutdown
}
// installLocal is setup A: Studio embedded in the app over the local
// sink's handle, and the runtime link talking to it in-process.
func installLocal(agt *weft.Agent) (h http.Handler, stop func()) {
srv := studio.New(studio.DB(otel.LocalDB()), studio.Playground(true))
shutdown := runtime.Install(
runtime.Local(srv), // the embedded Studio, in-process: no socket
runtime.Agents(agt),
runtime.Enabled(true), // open the link without WEFT_ENV=dev
)
return srv.Handler(), func() { shutdown(); _ = srv.Close() }
}
// demoScript answers the source run (a lookup, then a reply) and a few
// experiments after it, so the playground can run them offline.
func demoScript() weft.Model {
turns := []wefttest.Turn{
wefttest.ToolCalls(wefttest.Call{ID: "c1", Name: "lookup_order", Args: `{"order_id":"4411"}`}),
wefttest.Say("Order 4411 shipped yesterday."),
}
for range 20 {
turns = append(turns, wefttest.Say("Order 4411 shipped yesterday. Track it at acme.example/t/4411."))
}
return wefttest.Script(turns...)
}
// start records the source run and returns Studio's handler with the
// runtime registered.
func start(ctx context.Context) (h http.Handler, sourceRun string, stop func(), err error) {
agt := newAgent(demoScript())
h, stopLink := installLocal(agt)
res, err := agt.Generate(ctx, weft.Prompt("Where is my order #4411?"))
if err != nil {
stopLink()
return nil, "", nil, err
}
return h, res.ID, stopLink, nil
}
func main() {
addr := flag.String("addr", "127.0.0.1:8080", "the loopback address to serve Studio on")
flag.Parse()
defer otel.Install(otel.Local(""))() // ./.weft/weft.db (or $WEFT_DB), content on
ctx := context.Background()
h, source, stop, err := start(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "playground:", err)
os.Exit(1)
}
defer stop()
ln, err := net.Listen("tcp", *addr)
if err != nil {
fmt.Fprintln(os.Stderr, "playground:", err)
os.Exit(1)
}
mux := http.NewServeMux()
mux.Handle("/studio/", http.StripPrefix("/studio", h))
fmt.Println("playground: http://" + ln.Addr().String() + "/studio/playground")
fmt.Println("source run:", source)
go func() { _ = http.Serve(ln, mux) }()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
}

View playground/main.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./playground
go test ./playground
playground: http://127.0.0.1:8080/studio/playground
source run: dd66354adfaac2b44848f0c1ed75516f

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

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

Symbols used: weft.Replay · weft.ReplayPolicy · weft.ReplayNever · weft.ReplaySafe · ToolDef.ReplayPolicy · weft.Tool · weft.ParkAllExcept · weft.ToolSource · weft.Subagent · runtime.Install · runtime.AllowSideEffects · runtime.Threads · runtime.Local · studio.Playground · studio.RuntimeServer · Server.Runtime · weft.Resolve · weft.ResumeOf