Deploy an agent service with a hosted Studio
A production weft service is your Go program with five more pieces: provider credentials from the environment, a recording pipeline with destinations you name, a Studio other people reach behind a token (setup C), a durable session store if you keep conversations, and a shutdown that stops in order. CI runs the same code with model requests denied.
A hosted Studio over its own database, with an API token, a separate ingest token, the one origin whose pages load the panel, and 30 days of retention, in production/main.go:
srv := studio.New( studio.DB(db), // the hosted database (SQLite here; clickhouse.Open in a fleet) studio.Token(apiToken), // every /api route: Authorization: Bearer <apiToken> studio.IngestToken(ingestToken), // /v1/traces and /v1/logs: Authorization: Bearer <ingestToken> studio.AllowOrigins("https://app.example.com"), // the app page that loads the devtools panel studio.Retain(30*24*time.Hour), // delete runs not running, last seen 30 days ago)defer func() { _ = srv.Close() }() // stops the sweepermux := http.NewServeMux()mux.Handle("/studio/", http.StripPrefix("/studio", srv.Handler()))Your apps export to it with the ingest token; your backend reads it, and mints panel tokens, with the API token.
The pieces
Section titled “The pieces”| Piece | In production | Page |
|---|---|---|
| Provider credentials | the SDKs’ environment variables, or the adapters’ APIKey(k) | Providers |
| Recording | otel.Install(…) with explicit destinations and a content policy | Recording, Destinations, Content and privacy |
| Studio | setup C: studio.New behind Token and IngestToken | this page, Security |
| Studio’s database | SQLite for one host, ClickHouse for a fleet | Storage backends |
| Retention | studio.Retain(d) or a scheduled weft vacuum --retain d | Retention |
| Sessions | thread/jsonl or thread/sqlite, one writer per session | Operate sessions in production |
| CI | WEFT_MODEL_REQUESTS=deny | Never reach the network |
| Shutdown | HTTP, sessions, Studio, then the pipeline | Shut down in order |
| Limits | budgets, caps and queue sizes | Limits |
Provider credentials
Section titled “Provider credentials”The adapters read their keys from the environment when no option names one: OPENAI_API_KEY, ANTHROPIC_API_KEY, and GOOGLE_API_KEY or GEMINI_API_KEY, then application default credentials for Google. Put them in your secret store’s environment, not in code; APIKey(k) takes one you load yourself. Use a provider lists the endpoints and the other variables each SDK reads.
Record runs
Section titled “Record runs”With no options, otel.Install takes its destinations from the environment and from a running Studio’s discovery file, and writes the local sink ./.weft/weft.db only when they add none. In production, name them:
otel.Studio(url, ingestToken)to a hosted Studio, content on.otel.OTLP,otel.Datadogorotel.Langfuseto your existing backend, content off unless you passotel.WithContent().otel.Content(otel.ContentConfig{Redact: …})for what the content-on destinations store.otel.QueueSize(n)where bursts outrun a destination: a full queue refuses records rather than block your app.
Send records to Studio, Datadog, Langfuse or any OTLP backend covers each destination and the environment variables that add one. Leave WEFT_ENV unset in production. WEFT_ENV=dev lets an explicit otel.RawBodies(true), otel.DevDetail() or otel.Blocking() take effect, and lets runtime.Install open the playground’s runtime link (as runtime.Enabled(true) does).
Choose a Studio setup
Section titled “Choose a Studio setup”| Setup | Fits | Guard |
|---|---|---|
| A · embedded | one service, inspected from the same host | a loopback Host or an AllowOrigins host; no token |
B · weft studio | a developer machine | the dev token; ingest from loopback only |
| C · hosted | a team, several services, apps on other hosts | studio.Token, studio.IngestToken, panel tokens |
Setups A and B are for development. Setup A’s API answers a loopback Host, or one AllowOrigins names, and nothing else guards it. Setup B’s API answers its dev token, but the weft studio binary has no ingest-token option, so it takes OTLP from its own machine only. Run Studio covers all three; the rest of this page is setup C.
Setup C (hosted)
Section titled “Setup C (hosted)”Setup C is the same handler as setup A, built with studio.New and served by your own HTTP server, behind your TLS. studio.Token walls the JSON API: every request needs the server token, or a panel token your backend minted, as a bearer. studio.IngestToken guards OTLP ingest separately, so the apps that export never hold the token that reads. Secure Studio has the full rule set.
The devtools panel in your app’s pages never sees the server token. Your backend calls POST /api/panel-tokens with the server token and hands the page a panel token: HMAC-signed {public_id, tags, scope, exp}, scoped to one conversation’s public id. Every data route refuses anything outside that public id; child runs carrying another public id are counted as one hidden hole, never named. Since 0.20.0 a token can instead, or as well, be scoped to a batch of runs by their metadata: {"tags": {"arena.batch": "20261014-1606"}} (capability panel_token_tags). Every read is held to the tags, as a public id token’s is held to its public id. A request may narrow the tags but never widen them, and such a token is read-only. A child run is read by its own row: a Subagent child inherits its parent’s metadata and is in the batch, while a pool or thread child session’s turn carries only the tags its app gave it and is otherwise a counted hidden hole (Secure the devtools panel). A panel token is read-only unless minted with "playground": true, a read-scoped one does not see the agents’ system prompts, and experiments stay the server token’s. From a playground-scoped panel, “Open in Studio” asks GET /api/panel-handoff?to= and opens the hosted Studio on the run with a 5-minute read token for the same public id, no token pasted.
The example builds this server, exports one run to it, and checks the wall:
GET /api/runs without a token: 401 with it: 200 lists the run: trueretention: 720h0m0spanel token, its public id: 200 another: 403studio.New(…) needs Close on shutdown: it stops Retain’s sweeper and the playground’s link server. It closes the database only when New opened it; a DB(db) you passed stays yours to close. For a fleet, open the database with clickhouse.Open(dsn) instead of SQLite (Storage backends).
Export to the hosted Studio
Section titled “Export to the hosted Studio”Each app names the Studio and passes the ingest token, which otel.Studio sends as Authorization: Bearer:
WEFT_STUDIO_URL=https://studio.example/studio WEFT_STUDIO_TOKEN=$INGEST_TOKEN ./my-appThe environment form adds that destination to otel.Install unless the program passes otel.NoEnv(); in code it is otel.Studio("https://studio.example/studio", ingestToken). The URL’s path is kept, so a Studio mounted under /studio/ receives /studio/v1/traces and /studio/v1/logs. http:// to a host other than localhost, 127.0.0.1 and ::1 is refused unless you pass otel.Insecure(), because the destination carries a token.
Store sessions
Section titled “Store sessions”thread.Memory() holds sessions in a map that is gone when the process is. A service that keeps conversations opens jsonl.Open(dir) or sqlite.Open(path) from weft/thread’s backends. Each session has one writer at a time (thread rule T1): route a conversation’s requests to the process that holds it, or let ErrLocked tell you another does. Operate sessions in production covers stores, locks, backups and crashes.
Keep the network out of CI
Section titled “Keep the network out of CI”Set WEFT_MODEL_REQUESTS=deny in CI and in any suite that must stay offline. Every first-party adapter then refuses to call its provider with weft.ErrModelRequestsDenied; the switch is read on every call, so a test can flip it with t.Setenv. A client injected with an adapter’s Client(c) option is a test double by construction and stays reachable; wefttest models ignore the switch. Never reach the network shows it in a test.
Shut down in order
Section titled “Shut down in order”On SIGTERM, stop each piece before the one it feeds:
stopCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()err = errors.Join( httpSrv.Shutdown(stopCtx), // 1. stop taking requests; in-flight handlers finish s.Close(stopCtx), // 2. drain the running turn and the queue, give the writer lease up inspector.Close(), // 3. stop Retain's sweeper and the playground link)shutdownRecording() // 4. flush every destination (5 s budget), close the local sink lasthttp.Server.Shutdownstops new requests and lets in-flight handlers finish.s.Close(ctx)stops new sends (ErrClosed), drains the running turn and the queue, seals the session and gives the writer lease up (thread rule T2). Ifctxends first, it cancels the running turn and returnsctx.Err(); call it again to finish (Close and shutdown).Server.Closestops Studio’s sweeper and runtime link.- The function
otel.Installreturned shuts the pipeline down under a 5-second context: it restores the slog bridge, stops heartbeats, flushes every destination in parallel, shuts the providers down and closes the local database last. The flush is capped at 5 seconds whatever the context; records still queued after it are lost.Pipeline.Shutdown(ctx)fromotel.Starttakes your context, which gives the provider shutdowns more time but not the flush.
The pipeline goes last because the turns drained in step 2 still emit records, and in setup A Studio serves the database the pipeline closes. After the example’s shutdown the turn is in the store:
reply: Order 1234 has shipped.after shutdown the sink holds: support-bot succeeded turn 1Complete example
Section titled “Complete example”The Production pages share one example program; hostedStudio, gracefulShutdown and serve are this page’s:
// Command production runs the examples of the Production pages —// deploying, content and privacy, retention, limits, storage backends// and Studio operations:// go run ./production. Every Studio is a stand-in on a loopback port// over a fresh SQLite file and the model is scripted with wefttest, so// it runs offline.package main
import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "log" "net" "net/http" "net/http/httptest" "os" "os/signal" "path/filepath" "regexp" "strings" "syscall" "time"
"github.com/weftgo/weft" "github.com/weftgo/weft/obsdb" "github.com/weftgo/weft/obsdb/sqlite" "github.com/weftgo/weft/otel" "github.com/weftgo/weft/studio" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/wefttest")
// LookupInput is the lookup tool's argument.type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"`}
// lookup returns a customer's email address: the content the pages keep// out of the records.var lookup = weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, in LookupInput) (string, error) { return "order " + in.OrderID + " has shipped to jane@example.com", nil })
// script is a two-step dialogue: one tool call, then an answer.func script() *wefttest.Model { return wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), )}
func main() { dir, err := os.MkdirTemp("", "weft-production-") if err != nil { log.Fatal(err) } defer func() { _ = os.RemoveAll(dir) }() // The shutdown example waits for SIGINT or SIGTERM; here it stops // itself after one turn so the program ends. ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() if err := run(ctx, os.Stdout, dir); err != nil { log.Fatal(err) } if err := runOperations(ctx, os.Stdout, dir); err != nil { log.Fatal(err) }}
func run(ctx context.Context, w io.Writer, dir string) error { steps := []struct { name string fn func(context.Context, io.Writer, string) error }{ {"content policy", contentPolicy}, {"strip content", stripContent}, {"hosted studio", hostedStudio}, {"retention", retention}, {"tool limits", toolLimits}, {"graceful shutdown", gracefulShutdown}, } for _, s := range steps { fmt.Fprintln(w, "==", s.name) if err := s.fn(ctx, w, dir); err != nil { return fmt.Errorf("%s: %w", s.name, err) } } return nil}
// contentPolicy records one run twice: into the local sink with a// redactor and a cap, and into a third-party OTLP collector with// content off.func contentPolicy(ctx context.Context, w io.Writer, dir string) error { collectorURL, collectorDB, stopCollector, err := standInStudio(filepath.Join(dir, "collector.db")) if err != nil { return err } defer stopCollector() path := filepath.Join(dir, "redacted.db")
email := regexp.MustCompile(`[\w.+-]+@[\w-]+\.[\w.]+`) redact := func(kind weft.ContentKind, s string) string { return email.ReplaceAllString(s, "[email]") // every content field of every kind } p, err := otel.Start(ctx, otel.Local(path), // content on: the redactor and the cap apply otel.OTLP(collectorURL, otel.NoContent()), // a third party: shape only, no content otel.Content(otel.ContentConfig{ MaxBytes: 16 << 10, // one event field, delta, prompt or catalog body; never the transcript Redact: redact, }), otel.NoEnv(), ) if err != nil { return err } agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } if err := p.Shutdown(ctx); err != nil { return err }
local, err := sqlite.Open(path) if err != nil { return err } defer func() { _ = local.Close() }() stored, err := everything(ctx, local, res.ID) if err != nil { return err } fmt.Fprintln(w, "the model saw:", toolResult(res)) fmt.Fprintln(w, "local sink holds [email]:", strings.Contains(stored, "[email]"), "the address:", strings.Contains(stored, "jane@example.com"))
rec, err := collectorDB.Run(ctx, res.ID) if err != nil { return err } page, err := collectorDB.Events(ctx, res.ID, -1, 50) if err != nil { return err } stripped := 0 for _, e := range page.Events { if e.Content == "stripped" { stripped++ } } fmt.Fprintln(w, "collector:", rec.Status, "events:", rec.EventCount, "stripped:", stripped, "transcript batches:", rec.MessageCount) return nil}
// stripContent shows the core's content table and the agent-side veto.func stripContent(ctx context.Context, w io.Writer, dir string) error { path := filepath.Join(dir, "vetoed.db") p, err := otel.Start(ctx, otel.Local(path), otel.NoEnv(), otel.NoGlobal()) // Local: content on if err != nil { return err } tp, lp := p.TracerProvider(), p.LoggerProvider()
ev := weft.ToolFinish{Seq: 4, CallID: "call_1", Name: "lookup_order", Content: "order 1234 has shipped to jane@example.com"} out := weft.StripContent(ev).(weft.ToolFinish) // what a content-off destination receives fmt.Fprintf(w, "stripped: name=%s call=%s content=%q\n", out.Name, out.CallID, out.Content)
// This agent's records never carry content, whatever a destination asks for. payroll := weft.New(script(), weft.Name("payroll-bot"), lookup, weft.Content(false), weft.TracerProvider(tp), weft.LoggerProvider(lp))
res, err := payroll.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } if err := p.Shutdown(ctx); err != nil { return err } db, err := sqlite.Open(path) if err != nil { return err } defer func() { _ = db.Close() }() rec, err := db.Run(ctx, res.ID) if err != nil { return err } stored, err := everything(ctx, db, res.ID) if err != nil { return err } fmt.Fprintln(w, "content(false):", rec.Status, "events:", rec.EventCount, "transcript batches:", rec.MessageCount, "the address stored:", strings.Contains(stored, "jane@example.com")) return nil}
// hostedStudio is setup C: a Studio behind a Token, its own ingest// token, one allowed origin and a retention, and an app exporting to it.func hostedStudio(ctx context.Context, w io.Writer, dir string) error { db, err := sqlite.Open(filepath.Join(dir, "hosted.db")) if err != nil { return err } defer func() { _ = db.Close() }() apiToken, ingestToken := "api-secret", "ingest-secret" // in production: from your secret store
srv := studio.New( studio.DB(db), // the hosted database (SQLite here; clickhouse.Open in a fleet) studio.Token(apiToken), // every /api route: Authorization: Bearer <apiToken> studio.IngestToken(ingestToken), // /v1/traces and /v1/logs: Authorization: Bearer <ingestToken> studio.AllowOrigins("https://app.example.com"), // the app page that loads the devtools panel studio.Retain(30*24*time.Hour), // delete runs not running, last seen 30 days ago ) defer func() { _ = srv.Close() }() // stops the sweeper mux := http.NewServeMux() mux.Handle("/studio/", http.StripPrefix("/studio", srv.Handler())) ts := httptest.NewServer(mux) defer ts.Close() base := ts.URL + "/studio"
// The app's side: export to the hosted Studio with the ingest token. p, err := otel.Start(ctx, otel.Studio(base, ingestToken), otel.NoEnv(), otel.NoGlobal()) if err != nil { return err } agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), weft.Metadata(map[string]string{"weft.public_id": "pub_jane"})) if err != nil { return err } if err := p.Shutdown(ctx); err != nil { return err }
noToken, _ := get(base+"/api/runs", "") withToken, body := get(base+"/api/runs", apiToken) fmt.Fprintln(w, "GET /api/runs without a token:", noToken, "with it:", withToken, "lists the run:", strings.Contains(body, res.ID)) _, meta := get(base+"/api/meta", apiToken) var m struct { Retention string `json:"retention"` } _ = json.Unmarshal([]byte(meta), &m) fmt.Fprintln(w, "retention:", m.Retention)
// Your backend mints a panel token for one conversation's public id. tok, err := mintPanelToken(base, apiToken, "pub_jane") if err != nil { return err } own, _ := get(base+"/api/runs?public_id=pub_jane", tok) other, _ := get(base+"/api/runs?public_id=pub_other", tok) fmt.Fprintln(w, "panel token, its public id:", own, "another:", other) return nil}
// retention keeps runs 30 days and shows what a sweep 30 days later// deletes, then gives the space back.func retention(ctx context.Context, w io.Writer, dir string) error { path := filepath.Join(dir, "retained.db") p, err := otel.Start(ctx, otel.Local(path), otel.NoEnv(), otel.NoGlobal()) if err != nil { return err } agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) if _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil { return err } if err := p.Shutdown(ctx); err != nil { return err } db, err := sqlite.Open(path) if err != nil { return err } defer func() { _ = db.Close() }()
srv := studio.New(studio.DB(db), studio.Retain(30*24*time.Hour)) // sweeps at New, then hourly defer func() { _ = srv.Close() }() // Close stops the sweeper page, err := db.Runs(ctx, obsdb.RunQuery{}) if err != nil { return err } fmt.Fprintln(w, "kept under a 30-day retention:", len(page.Runs), "run") // a fresh run is never swept
later := time.Now().Add(30*24*time.Hour + time.Minute) // the clock, 30 days on n, err := sweepAndVacuum(ctx, db, later, 30*24*time.Hour) if err != nil { return err } page, err = db.Runs(ctx, obsdb.RunQuery{}) if err != nil { return err } fmt.Fprintln(w, "30 days later: swept", n, "runs; left:", len(page.Runs)) return nil}
// sweepAndVacuum is one sweep as Retain's sweeper runs it at now, then// VACUUM: what `weft vacuum --retain` does.func sweepAndVacuum(ctx context.Context, db obsdb.DB, now time.Time, retain time.Duration) (int, error) { cutoff := now.Add(-retain) // what Retain's sweeper computes each pass n, err := db.Sweep(ctx, cutoff) // runs not running, last seen before cutoff, with their children if err != nil { return n, err } err = db.Vacuum(ctx) // SQLite: VACUUM; ClickHouse: OPTIMIZE TABLE … FINAL return n, err}
// ReportInput is the report tool's argument.type ReportInput struct { Month string `json:"month" jsonschema:"the month, YYYY-MM"`}
// toolLimits runs two tools against their limits: a result past its cap// and a handler past its deadline.func toolLimits(ctx context.Context, w io.Writer, _ string) error { report := weft.Tool("monthly_report", "Export a month's orders as CSV.", func(_ context.Context, in ReportInput) (string, error) { return strings.Repeat("order,status\n", 5_000), nil // 65,000 bytes }, weft.MaxResultBytes(4<<10), // this tool's results are cut at 4 KiB, with a marker weft.Timeout(10*time.Second), ) slow := weft.Tool("carrier_status", "Ask the carrier where a parcel is.", func(ctx context.Context, in LookupInput) (string, error) { select { case <-ctx.Done(): // honour ctx: the deadline cancels it return "", ctx.Err() case <-time.After(time.Minute): return "in transit", nil } }, weft.Timeout(50*time.Millisecond), // past it: an error result, the run goes on ) agt := weft.New(model(), report, slow, weft.MaxSteps(5), // budget: ErrMaxSteps past 5 model calls weft.UsageLimit(weft.Usage{OutputTokens: 20_000}), // budget: ErrUsageLimit past 20,000 output tokens ) res, err := agt.Generate(ctx, weft.Prompt("Report for 2026-09, and where is parcel 1234?")) if err != nil { return err } for _, m := range res.Messages { for _, part := range m.Content { if r, ok := part.(weft.ToolResultPart); ok { if r.IsError { fmt.Fprintf(w, "%s (error): %s\n", r.Name, r.Content) continue } fmt.Fprintf(w, "%s (%d bytes): …%s\n", r.Name, len(r.Content), tail(r.Content, 28)) } } } return nil}
func model() *wefttest.Model { return wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "monthly_report", Args: `{"month":"2026-09"}`}, wefttest.Call{Name: "carrier_status", Args: `{"order_id":"1234"}`}, ), wefttest.Say("The report is partial; the carrier did not answer."), )}
// gracefulShutdown serves one agent over HTTP with a thread session and// an embedded Studio, then shuts every piece down in order once ctx ends.func gracefulShutdown(ctx context.Context, w io.Writer, dir string) error { path := filepath.Join(dir, "app.db") ctx, cancel := context.WithCancel(ctx) defer cancel() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return err } done := make(chan error, 1) go func() { done <- serve(ctx, ln, path) }()
// One request, then the signal. resp, err := http.Post("http://"+ln.Addr().String()+"/chat", "text/plain", strings.NewReader("Where is order 1234?")) if err != nil { return err } reply, _ := io.ReadAll(resp.Body) _ = resp.Body.Close() fmt.Fprintln(w, "reply:", string(reply)) cancel() if err := <-done; err != nil { return err }
db, err := sqlite.Open(path) if err != nil { return err } defer func() { _ = db.Close() }() page, err := db.Runs(context.Background(), obsdb.RunQuery{}) if err != nil { return err } for _, r := range page.Runs { fmt.Fprintln(w, "after shutdown the sink holds:", r.Agent, r.Status, "turn", r.Turn) } return nil}
// serve runs the app until ctx ends, then shuts down: HTTP first, then// the session, then Studio, then the recording pipeline.func serve(ctx context.Context, ln net.Listener, dbPath string) error { shutdownRecording := otel.Install(otel.Local(dbPath), otel.NoEnv()) agt := weft.New(script(), weft.Name("support-bot"), lookup) s, err := thread.Create(ctx, thread.Memory(), agt, thread.NoAutoCompact()) // in production: jsonl.Open or sqlite.Open if err != nil { shutdownRecording() return err } inspector := studio.New(studio.DB(otel.LocalDB())) mux := http.NewServeMux() mux.Handle("/studio/", http.StripPrefix("/studio", inspector.Handler())) mux.HandleFunc("POST /chat", func(rw http.ResponseWriter, r *http.Request) { var prompt bytes.Buffer _, _ = prompt.ReadFrom(r.Body) turn, err := s.Send(r.Context(), weft.User(prompt.String())) if err != nil { http.Error(rw, err.Error(), http.StatusServiceUnavailable) return } res, err := turn.Wait() if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } _, _ = io.WriteString(rw, res.Text()) }) httpSrv := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second} go func() { _ = httpSrv.Serve(ln) }()
<-ctx.Done() // SIGINT or SIGTERM in main stopCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() err = errors.Join( httpSrv.Shutdown(stopCtx), // 1. stop taking requests; in-flight handlers finish s.Close(stopCtx), // 2. drain the running turn and the queue, give the writer lease up inspector.Close(), // 3. stop Retain's sweeper and the playground link ) shutdownRecording() // 4. flush every destination (5 s budget), close the local sink last return err}
// standInStudio serves a Studio over a fresh SQLite file on a loopback// port: its OTLP ingest takes loopback peers without an ingest token.func standInStudio(path string) (url string, db obsdb.DB, stop func(), err error) { db, err = sqlite.Open(path) if err != nil { return "", nil, nil, err } srv := studio.New(studio.DB(db)) ts := httptest.NewServer(srv.Handler()) return ts.URL, db, func() { ts.Close(); _ = srv.Close(); _ = db.Close() }, nil}
// everything is every stored body of a run: its events and its// transcript, joined.func everything(ctx context.Context, db obsdb.DB, runID string) (string, error) { var sb strings.Builder page, err := db.Events(ctx, runID, -1, 500) if err != nil { return "", err } for _, e := range page.Events { b, _ := json.Marshal(e) sb.Write(b) } batches, err := db.Transcript(ctx, runID) if err != nil { return "", err } for _, b := range batches { sb.Write(b) } return sb.String(), nil}
func get(url, token string) (int, string) { req, _ := http.NewRequest(http.MethodGet, url, nil) if token != "" { req.Header.Set("Authorization", "Bearer "+token) } resp, err := http.DefaultClient.Do(req) if err != nil { return 0, err.Error() } defer func() { _ = resp.Body.Close() }() b, _ := io.ReadAll(resp.Body) return resp.StatusCode, string(b)}
func mintPanelToken(base, apiToken, publicID string) (string, error) { body := strings.NewReader(`{"public_id":"` + publicID + `","ttl":"15m"}`) req, _ := http.NewRequest(http.MethodPost, base+"/api/panel-tokens", body) req.Header.Set("Authorization", "Bearer "+apiToken) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { return "", err } defer func() { _ = resp.Body.Close() }() var out struct { Token string `json:"token"` } if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { return "", err } if out.Token == "" { return "", fmt.Errorf("panel-tokens: %s", resp.Status) } return out.Token, nil}
// toolResult is the text of the run's first tool result: what the model// read, never changed by a destination's redactor.func toolResult(res *weft.RunResult) string { for _, m := range res.Messages { for _, part := range m.Content { if r, ok := part.(weft.ToolResultPart); ok { return r.Content } } } return ""}
func tail(s string, n int) string { s = strings.ReplaceAll(s, "\n", `\n`) if len(s) <= n { return s } return s[len(s)-n:]}View on GitHub · run it from docs-site/examples:
go run ./productiongo test ./production== content policythe model saw: order 1234 has shipped to jane@example.comlocal sink holds [email]: true the address: falsecollector: succeeded events: 8 stripped: 8 transcript batches: 0== strip contentstripped: name=lookup_order call=call_1 content=""content(false): succeeded events: 8 transcript batches: 0 the address stored: false== hosted studioGET /api/runs without a token: 401 with it: 200 lists the run: trueretention: 720h0m0spanel token, its public id: 200 another: 403== retentionkept under a 30-day retention: 1 run30 days later: swept 1 runs; left: 0== tool limitsmonthly_report (4123 bytes): …\n…[truncated 60904 bytes]carrier_status (error): tool "carrier_status" timed out after 50ms== graceful shutdownreply: Order 1234 has shipped.after shutdown the sink holds: support-bot succeeded turn 1main_test.go pins this output and checks the token rules: ingest refuses a request without the ingest token even from loopback, the API token is not an ingest token, and ?token= is a 401.
Best practices & gotchas
Section titled “Best practices & gotchas”- Give apps the ingest token, never the server token. The server token reads every transcript and signs panel tokens; the ingest token only writes. (Source:
studio/studio.go:81-98) - Build a hosted Studio with
studio.New, andCloseit.studio.Handlerbuilds a server nothing can close, so aRetainsweeper under it stops only when the database closes. (Source:studio.Handlergodoc,studio/studio.go:304-316) - Name your destinations. A bare
otel.Install()takes whatever the environment adds, and falls back to the local sink only when it adds nothing that builds. (Source:otel/pipeline.go:332-370) - Flush last. Close sessions and Studio before the pipeline: a turn drained after shutdown would record into a closed pipeline. (Source:
otel/pipeline.go:146-153; thread rule T2) - Report the weft version with
version.Runtime(). It reads the build info, so it names the tag your binary was built against (areplaceto another version included). It falls back toversion.Versionfor(devel), a pseudo-version or+dirty. Studio’s/api/metaweft_versionandweft versionprint the same (Package version). (Source:version/version.go:27-76;studio/api.go:2948-2951) - Never set
WEFT_ENV=devon a production host, and never shipotel.DevMode(). Either letsotel.RawBodies,otel.DevDetailandotel.Blockingtake effect when the code passes them;WEFT_ENV=devalso opens the runtime linkruntime.Installwould start. A binary that setsDevModesays so at start, one INFO line per switch it opened (otel: raw bodies on by otel.DevMode()), and aWEFT_ENVset to anything butdevoverrules it. (Source:otel/pipeline.go:241-311, 931;runtime/options.go:270; AGENTS.md block 7a)
See also
Section titled “See also”- Secure Studio: tokens, loopback and origins
- Run Studio: embedded, local binary or hosted
- Control what content leaves the process
- Operate sessions in production
- Limits and performance
Symbols used: studio.New · studio.DB · studio.Token · studio.IngestToken · studio.AllowOrigins · studio.Retain · Server.Handler · Server.Close · otel.Install · otel.Studio · otel.Insecure · otel.LocalDB · Pipeline.Shutdown · thread.Create · thread.Memory · thread.NoAutoCompact · Session.Send · Session.Close · Turn.Wait · weft.ErrModelRequestsDenied · weft.Metadata · weft.User · RunResult.Text · sqlite.Open