Skip to content

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

View as Markdown

runtime.Install registers your agents with a Studio and opens the runtime link, the connection Studio’s playground sends commands over. It is one deferred call in main. It opens a link only under WEFT_ENV=dev or with runtime.Enabled(true), so a production binary exposes nothing unless it opts in.

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

playground/main.go
shutdown = runtime.Install(
runtime.Studio(studioURL, token), // the Studio to dial, and its token
runtime.Agents(agt), // the agents experiments may run
runtime.Models(map[string]weft.Model{"acme-small": alt}), // alternates, by display name
runtime.ModelResolver(resolveModel), // any other model name: the app decides
runtime.Limits(runtime.Budget{MaxTokensPerExperiment: 200_000, MaxRunsPerExperiment: 2}),
runtime.AllowSideEffects("send_email"), // runs for real only under side_effects "allow"
)

playground/main.go on GitHub

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

runtime.Install dials out and never listens, so it works behind NAT. It never panics and never fails the program. When it cannot build a runtime, it logs one WARN and opens nothing: no agents given, or no Studio to dial. Link log lines lists each line. Each runtime.Option:

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

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

  1. The pipeline’s own Studio destination, otel.StudioEndpoint(): the one otel.Studio(url, token) or WEFT_STUDIO_URL names, or the discovery file’s Studio when the pipeline itself joined it. With both set to different URLs, it reports the environment’s (Send runs to Studio).
  2. The discovery file a running weft studio or weft dev wrote. It is never read when WEFT_STUDIO_URL is set or WEFT_DISCOVERY=off, and a stale file is never trusted. One INFO line names the Studio it joined.
  3. None: a WARN, and no link.

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

ExampleInstall builds the whole call with runtime.Enabled(false), so it stays inert.

runtime.Agents names the agents a runtime exposes. An agent without a weft.Name cannot register, since its manifest would be nameless: it is skipped with a WARN. A duplicate name keeps the first.

runtime.Models maps display names to weft.Model values: the allow-list the playground’s model picker reads. A command that names any other model is refused unless the runtime has a resolver. Studio’s 400 says so:

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

runtime.ModelResolver lets a command name a model you did not list. The name reaches your function while the command is validated, before its ack. A model back runs the command, named on the run’s RunStart.Model and weft.override.model. An error rejects it with model <name>: <your error's text>. The example’s resolver serves acme/* names only:

playground/main.go
func resolveModel(ctx context.Context, name string) (weft.Model, error) {
model, ok := strings.CutPrefix(name, "acme/")
if !ok {
// The text is the rejected command's reason: no key, no URL.
return nil, errors.New("this app serves acme/* models only")
}
return newProviderModel(model), nil // build the client from the app's own credentials
}

playground/main.go on GitHub

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

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

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

runtime.AllowSideEffects opts tools in to running for real in a playground run, and only when the command asks for side_effects: "allow". Under substitute (the default) and park an opted-in tool is a side effect like any other. A tool marked weft.Replay(weft.ReplaySafe) needs no opt-in: it runs in every mode. "allow" runs this list for real; it does not widen it. A command that asks for it is refused unless every tool it leaves on is named here or vouched safe. The modes are explained on How does the playground work?.

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

runtime.Threads sets the thread.Storage the runtime reads a source run’s transcript through first. Readers never lock, so a session your app holds open is readable. Without it the runtime is ephemeral-only: it resolves transcripts from the local sink, then from Studio, and a "thread": "fork" command is refused:

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

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

In setup A Studio is embedded in your app. Build it with studio.Playground(true) and hand the server to runtime.Local:

playground/main.go
srv := studio.New(studio.DB(otel.LocalDB()), studio.Playground(true))
shutdown := runtime.Install(
runtime.Local(srv), // the embedded Studio, in-process: no socket
runtime.Agents(agt),
runtime.Enabled(true), // open the link without WEFT_ENV=dev
)

playground/main.go on GitHub

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

weft’s runtime/examples/local is the same in one process, drivable with curl. It serves Studio on 127.0.0.1:7331, runs the agent once, and prints the command to replay that run from step 1:

Terminal window
go run ./runtime/examples/local -addr 127.0.0.1:7331

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

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

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

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

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

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

Studio keeps the link’s state through obsdb.CommandStore, which both first-party databases implement and studio.New passes in. Commands, routes, breakpoint sets and registrations are written through one ordered writer off the request path, and a failed write holds its queue 30 s, then re-applies it. A restarted Studio lists the stored runtimes with "restored": true until they register again, decides lost from the stored state, and never re-sends an accepted command.

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

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

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

A command’s row moves through five states:

StateMeans
queuedStudio put it on the runtime’s stream
acceptedthe runtime validated it and will run it; run_id names the run (empty for a fork until its turn starts)
rejectedthe runtime refused it; error says why (budget_exceeded, a validation sentence, the resolver’s text)
finishedthe run ended; status is succeeded or failed, error a failed run’s text
lostStudio gave up waiting; error says what it waited for

Send one, here the replay Replay a run from any step starts with:

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

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

Terminal window
curl -s http://127.0.0.1:8080/studio/api/playground/commands/cmd_docs_1
{"command_id":"cmd_docs_1","state":"finished","run_id":"pg_01M5780D5BYHQNGQDWRXR84HAZ","status":"succeeded","error":null,"created":"2026-10-18T12:13:07.369713696+02:00","updated":"2026-10-18T12:13:07.376531416+02:00"}

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

The timing rules:

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

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

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

LevelMessageAttributesWhen
WARNweft/runtime: Install without agents: no link openedhint runtime.Agents(...) names the agents a runtime exposesInstall was given no runtime.Agents, or an empty one. Nothing opens
WARNweft/runtime: no Studio to dial: no link openedhint runtime.Studio(url, token), runtime.Local(srv), or a Studio destination in weft/otelNo Studio, no Local, no pipeline Studio destination and no trusted discovery file. Nothing opens
WARNweft/runtime: the pipeline records only into a Local store (otel.Local, or otel.Install's default) and names no Studio: no link openedhintThe installed weft/otel pipeline records into a Local store and names no Studio, and Install names none either. Nothing opens (weft dev)
INFOweft/runtime: joined the running Studiourl, pid, file, hintThe discovery file named the Studio to dial
WARNweft/runtime: the Studio token travels unencrypted over http to a non-loopback hosthint use an https Studio URLA token is set and the URL is http:// to a host other than localhost or a loopback IP (setup C). The link still opens
WARNweft/runtime: agent without core.Name is not playablehint core.Name names an agent in its manifestA nameless agent in runtime.Agents; it is skipped
WARNweft/runtime: link failed to starterrThe link could not start. Nothing opens. In v0.20.2 the link’s start returns no error, so this line is not expected
WARNweft/runtime: Studio refused the runtime link; the playground stays off until the token is rightstatus (401 Unauthorized or 403 Forbidden), hint runtime.Studio(url, token) carries the token — with runtime.Local(srv) too, when srv was built with studio.TokenThe register call was refused for its token. Logged once per link
DEBUGweft/runtime: register failed; retryingerr, such as weft/runtime: register: 401 UnauthorizedEvery failed register, the refused ones included. The link retries with backoff, so after the one WARN a wrong token is silent at the default level
DEBUGweft/runtime: command stream ended; reconnectingerrThe command stream broke; the link registers again

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

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

LevelMessageAttributesWhen
WARNweft/runtime: undecodable run commanderrA run frame that is not a command. The runtime rejects it with undecodable command when its id is usable
WARNweft/runtime: command frame without a usable id ignorednoneA frame with no id, or one Studio would refuse. It is neither run nor acked
WARNweft/runtime: the accepted ack was not taken; the command is not runcommand_idStudio refused the accepted ack or did not confirm it (above). Nothing runs
WARNweft/runtime: the accepted ack was not taken; the decision is not appliedcommand_idThe same for a decision on a parked playground run: the resume does not run, and the park keeps that call
WARNweft/runtime: the accepted ack was not taken; the decision is not heldcommand_idThe same for a decision that leaves other parked calls undecided: it is not held, so deciding again is not refused as already decided
WARNweft/runtime: the accepted ack was not taken; the session is not writtencommand_idThe same for a decision or steer on your app’s own turn (App-owned turns)
WARNweft/runtime: ack failedcommand_id, state, errPosting an ack failed in transport; it counts as unconfirmed
WARNweft/runtime: ack unconfirmedcommand_id, state, statusStudio answered an ack with a 5xx
WARNweft/runtime: ack refusedcommand_id, state, statusStudio answered an ack with any other non-200 status, such as 409 once it marked the command lost
WARNweft/runtime: playground run failedcommand_id, run_id, errA playground run ended in an error; its finished ack carries the text
WARNweft/runtime: fork command failedcommand_id, source, errA "thread": "fork" command could not fork or run its turn
WARNweft/runtime: fork resume failedsession, errA decision on a parked fork could not resume its session
WARNweft/runtime: forked session not releasedsession, errClosing a forked session failed, so its writer lease may still be held
WARNweft/runtime: session command failedcommand_id, session, verb, errA decision or steer on your app’s own turn failed after its ack; the finished ack says why
WARNweft/runtime: source transcript unresolved; running on the input alonerun_id, errA command with a fresh input whose source transcript could not be read runs on the input (Replay)
WARNweft/runtime: the source step's compaction view could not be read; it is unknown, the thread's messages are usedrun_id, step, errA replay from a thread turn’s step: the records or Studio could not say what the model saw, so the turn’s own messages are used
WARNweft/runtime: no request record places the source step's messages (derived); the replay uses the transcript cut at the step, no compaction view knownrun_id, stepNo request record places the source step’s messages: an older run, or a request recorded with content off
WARNweft/runtime: this Studio does not answer the transcript as of a step (ADR 0029); a compaction view of the source step is unknownrun_id, stepThe Studio is older than GET /api/runs/{id}/transcript?step=
WARNweft/runtime: manifest for agent failedagent, errBuilding a registered agent’s manifest failed; it registers without one. Not expected, since names are checked first
ERRORweft/runtime: command panickedcommand_id, panicA panic around a command, outside the agent’s own contained code. Before the runtime accepted the command, it is rejected with internal error in the runtime (see its log); after, it finishes failed with that error
ERRORweft/runtime: in-process Studio handler panickedpath, panicUnder runtime.Local, a Studio handler panicked. The call answers 500 and the app keeps running

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

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

The tests in main_test.go register the runtime both ways (TestRuntimeRegisters through runtime.Local, TestInstallStudioRegisters through runtime.Studio under WEFT_ENV=dev, and nothing connects without it), and check the stable rt_ id, each tool’s class, the alternate and the resolver.

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

Symbols used: otel.Install · runtime.Install · runtime.Option · runtime.Studio · runtime.Local · runtime.Agents · runtime.Models · runtime.ModelResolver · runtime.Limits · runtime.Budget · runtime.AllowSideEffects · runtime.Threads · runtime.Sessions · runtime.Enabled · weft.Model · weft.Name · thread.Storage · otel.StudioEndpoint · obsdb.CommandStore · studio.New · studio.Playground