Limits and performance
These are the caps, budgets, queue sizes and timeouts that an operator meets, grouped by where they apply: the agent loop, the recording pipeline, the observability database, Studio, the playground link, the devtools panel, the weft command and sessions. “Fixed” means a constant in the code with no option. The model-visible ones (the tool-result cap, timeouts, budgets) are behaviour your agent depends on; the rest bound what Studio stores and reads.
Put a tool’s result cap and deadline beside the run’s budgets, in production/main.go:
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)monthly_report (4123 bytes): …\n…[truncated 60904 bytes]carrier_status (error): tool "carrier_status" timed out after 50msThe model reads the first 4,096 bytes and a marker that names the 60,904 bytes it did not get; the slow tool’s call becomes an error result and the run continues.
Agent loop
Section titled “Agent loop”Budgets are checked only when the loop would call the model again, so a step that ends the run succeeds even past one; a breach is a *RunError with the partial transcript (How does a run stop?).
| Limit | Value | Set by | When hit | Source |
|---|---|---|---|---|
| Steps | 10 model calls | weft.MaxSteps(n); per run lower only | ErrMaxSteps, stopped_by max_steps | core/agent.go:23 |
| Usage | none | weft.UsageLimit(u); subagent usage counts | ErrUsageLimit, stopped_by usage_limit | core/agent.go:125 |
| Model retries | 3 consecutive RETRY results per tool | weft.MaxModelRetries(n) | ErrModelRetriesExceeded | core/agent.go:25 |
| Loop detection | off | weft.DetectLoops(repeats) | ErrLoopDetected | core/agent.go:187 |
| Parallel tool calls | 4 | weft.Parallelism(n), weft.Sequential(); per run lower only | further calls wait | core/agent.go:24 |
| Tool result | 64 KiB of text | weft.MaxResultBytes(n) per agent or per tool; 0 = no cap | cut on a rune boundary, marker …[truncated N bytes] the model sees | core/agent.go:28, core/loop.go:2221 |
| Tool deadline | none | weft.Timeout(d) per agent or per tool | error result tool "X" timed out after d; the handler’s goroutine is abandoned | core/tool.go:508, core/loop.go:1980 |
| Output tokens per step | the provider’s; Anthropic 4096 | the adapter’s MaxTokens(n), weft.Params | max_tokens stop; tool calls in that step are not executed | anthropic/model.go:185 |
| Stream idle gap | 60 s between chunks | the adapter’s IdleTimeout(d); 0 disables | ErrStreamIdle | openai/model.go:165, core/errors.go:77 |
mw.Retry | 3 retries, 500 ms doubling, each wait capped at 8 s, ±25% jitter | mw.MaxRetries, mw.BaseDelay | the last error | core/mw/retry.go:26-28 |
| SDK transport retries | 2 (OpenAI, Anthropic), the SDKs’ default | the adapter’s MaxRetries(n) | — | openai/model.go:115, anthropic/model.go:107 |
mw.Retry provider wait | 60 s | mw.MaxWait(d); 0 = no cap | mw.ErrRetryAfterTooLong | core/mw/retry.go:29 |
| Metadata | 64 keys, 128-byte keys, 1,024-byte values | fixed | the entry is dropped, never truncated, and counted in weft.metadata.dropped | core/metadata.go:14-16 |
| Resumed calls on a span | 32 in weft.resume.calls | fixed | the rest written as ,…+k | core/loop.go:1519 |
Recording pipeline
Section titled “Recording pipeline”| Limit | Value | Set by | When hit | Source |
|---|---|---|---|---|
| Content field | 32 KiB per event field, delta, prompt or catalog body; never the transcript | otel.ContentConfig{MaxBytes}; negative = no cap | cut, weft.content.truncated_bytes set | otel/options.go:31 |
| Destination queue | 2,048 per chain (records and spans each); Studio 16,384; Local has no queue | otel.QueueSize(n) | refused by tier: deltas at ½, records at ⅞, run brackets and heartbeats when full; one WARN; weft.records.dropped | otel/admission.go:53-54, 119-121 |
| Blocking wait | 5 s per stall | otel.Blocking(), development gate only (WEFT_ENV=dev or otel.DevMode()) | refused until an export begins | otel/admission.go:60 |
| Heartbeat | every 10 s per open run | otel.Heartbeat(d); 0 disables | a run silent for a fixed 30 s reads interrupted (three default beats), whatever the interval | otel/pipeline.go:392, obsdb/db.go:998 |
| Studio batch interval | logs 200 ms, spans 1 s; others the SDK’s | otel.BatchDelay(d) | — | otel/config.go:129-136 |
| Raw body | 256 KiB per wire body | fixed (otel.RawBodies, dev only) | cut and counted in the body’s truncated_bytes | core/raw.go:40 |
| Raw batch to Studio | 16 records per batch, 12 MiB per export | fixed | the export is split | otel/pipeline.go:397, 407 |
| Bridged log attributes | 120 per line | fixed | dropped, counted in weft.log.attrs_dropped | otel/slog.go:51 |
| Shutdown flush | 5 s | fixed; Pipeline.Shutdown(ctx) flushes for at most 5 s within your ctx, which bounds the provider shutdowns after it | unflushed records are lost | otel/pipeline.go:177, 365 |
Control what content leaves the process and queue size and blocking explain the first three.
Observability database
Section titled “Observability database”| Limit | Value | Set by | When hit | Source |
|---|---|---|---|---|
| List page (runs, traces, sessions) | 50, at most 500 | the query’s Limit, ?limit= | clamped | obsdb/db.go:1056-1061 |
| Running → interrupted | 30 s since last seen | fixed (obsdb.InterruptedAfter) | status interrupted; also the 30 s settling window | obsdb/db.go:998 |
| Sweep pass | 500 root runs | fixed (obsdb.SweepBatch) | the next pass | obsdb/db.go:1006 |
| Span tree | 10,000 spans, 10,000 run rows | fixed (obsdb.TreeSpanCap, TreeRowCap) | truncated hole, cause response_cap | obsdb/tree.go:108, 127 |
| Derived run’s trace read | 50,000 spans | fixed | TraceTruncated | obsdb/tree.go:117 |
| Child runs per read | 10,000 | fixed (obsdb.ChildRunsCap) | ErrChildRunsCapped; cost reads unknown | obsdb/tree.go:133 |
| Search | 16 terms, 256 bytes a term, offset up to 100,000 | fixed | ErrInvalidSearch, Studio 400 | obsdb/search.go:74-76 |
| Prompt preview | 200 runes | fixed | cut | obsdb/search.go:156 |
| Live subscriber queue | 1,000 frames | obsdb.QueueSize(n) on a hub | the slow subscriber is dropped | obsdb/hub.go:114 |
| App log candidates per read | 10,000 records | fixed | LogPage.Truncated | obsdb/logs.go:120 |
| App log page | 100, at most 1,000 | ?limit= | clamped | obsdb/logs.go:31-40, studio/logs.go:28 |
| Requests page | at most 1,000 | ?limit= | clamped | studio/requests.go:28 |
| Event gaps listed per page | 1,000 | fixed (obsdb.MaxGaps) | the rest not listed | obsdb/db.go:674 |
| Same-timestamp rows past a page | 500 | fixed (obsdb.MaxTies) | the page ends there | obsdb/db.go:627 |
| Missing tree children named | 100, all counted | fixed (obsdb.TreeMissingCap) | the count only | obsdb/tree.go:121 |
| ClickHouse table TTLs | content 30 days, spans and runs 90 days | clickhouse.TTL(content, meta) | rows expire | obsdb/clickhouse/clickhouse.go:20-21 |
Studio
Section titled “Studio”| Limit | Value | Set by | When hit | Source |
|---|---|---|---|---|
| OTLP ingest body | 16 MiB after decompression | fixed | 413 request body exceeds 16 MiB after decompression | studio/ingest/ingest.go:40 |
| API request body | 4 MiB, every JSON body | fixed | 413 …: larger than the 4 MiB limit | studio/api.go:67-71 |
| Runtime link request body (register, acks) | 8 MiB | fixed | 413 | studio/runtime/http.go:44 |
| Events page | 500, at most 5,000 | ?limit= | clamped | studio/api.go:33-34 |
| Search by cost | the first 2,000 matches priced | fixed | cost_sort_cap in the answer | studio/search.go:146 |
| Diff | 500 steps | fixed | truncated hole, cause response_cap | studio/diff.go:66 |
Export with tree=1 | 200 subagent runs | fixed | truncated hole: the later ones were not exported | studio/export.go:167 |
| Trace list failed runs | 500 counted | fixed | failed_runs_capped | studio/traces.go:182 |
Live backfill, all=1 | the last hour or running, 500 runs | fixed | older runs not replayed | studio/live.go:710-711 |
| Instruction proposals | 64, in memory | fixed | the oldest evicted | studio/proposals.go:40 |
| Unpriced models named | 5, then (+n) | fixed | — | studio/pricing.go:521 |
| Experiments list | 50, at most 200 | ?limit= | clamped, total given | studio/experiments.go:189-190 |
| Panel token | 1 h | ttl in the mint request; no maximum | 401 bad or expired token | studio/auth.go:671 |
| Live grant | 60 s to open; never past a panel token’s expiry | fixed | 401; a panel token’s stream ends with event: expired | studio/livegrant.go:53 |
| Hand-off token | 5 min, never past the calling panel token’s expiry | fixed | the tab falls back to its stored token, if one is stored; with none, the 401 stands | studio/handoff.go:40 |
Hand-off to | 2,048 bytes | fixed | 400 | studio/handoff.go:43 |
| Retention | at least 1 h; sweeps every min(d/10, 1h), at least a minute apart | studio.Retain(d), --retain, WEFT_RETAIN | under 1 h: New panics, the CLI exits 2 | studio/delete.go:141-153 |
| Refused-ingest log lines | one a minute per remote, route and status, 1,024 keys tracked | fixed | the rest suppressed and counted; 5xx never limited | studio/internal/reqlog/reqlog.go:181, 185 |
| Live stream | a ping every 15 s; 30 s to write a frame; 65,536 deduplication keys per connection | fixed | a write past 30 s ends the stream; the dedup set evicts its oldest keys | studio/live.go:23, 30, 33 |
Playground and runtime link
Section titled “Playground and runtime link”| Limit | Value | Set by | When hit | Source |
|---|---|---|---|---|
| Command ack | 30 s from enqueue; the runtime validates within 25 s | fixed | the command is marked lost, no ack in time | studio/runtime/runtime.go:882, runtime/executor.go:363 |
| Accepted command without finish | max(10 min, 3 heartbeats); heartbeat every minute | fixed | marked lost | studio/runtime/runtime.go:2000-2001, runtime/link.go:913 |
| Commands in flight per runtime | 256 | fixed | rejected ack runtime busy: N commands in flight | runtime/link.go:38 |
| Concurrent runs per runtime | 16 | fixed | the rest wait, already acked | runtime/link.go:43 |
| Command frame | 8 MiB | fixed | the command is acked as rejected, the stream ends and the link reconnects | runtime/link.go:44-46, 364-374 |
| Source transcript fetched from Studio | 64 MiB | fixed | a rejected ack, studio transcript: larger than N bytes | runtime/transcript.go:151, 296, 379 |
| Finished commands and routes kept | 24 h | fixed | pruned | studio/runtime/runtime.go:885 |
| Command rows in memory | 10,000 | fixed | the oldest finished rows pruned | studio/runtime/runtime.go:2201 |
| Command stream | 30 s to write a frame; 256 frames queued per stream | fixed | the stream is dropped; the runtime reconnects | studio/runtime/runtime.go:886-887 |
| Command id | 1 to 128 characters of [A-Za-z0-9._:-] | fixed | 400 | studio/runtime/runtime.go:714 |
| Remembered manifests | 64 | fixed | the oldest unheld one forgotten | studio/runtime/manifests.go:23 |
| Command store failure | its queue held 30 s, then re-applied | fixed | — | studio/runtime/store.go:130 |
| Runtime: command ids remembered | 4,096 | fixed | — | runtime/link.go:35 |
| Runtime: HTTP timeouts | register 15 s, response headers 30 s, an ack post 10 s | fixed | — | runtime/link.go:51-52, 892 |
| Runtime: ack error text | 2 KiB | fixed | cut, … appended | runtime/link.go:56 |
| Runtime: resolvers | ModelResolver 10 s, runtime.Sessions resolver 10 s | fixed | — | runtime/executor.go:355, runtime/sessions.go:49 |
| Runtime: kept state | 64 forked sessions, 128 parked runs | fixed | the oldest forgotten; a fork’s park whose session is still held is rebuilt, any other evicted park answers no parked run … on this runtime | runtime/executor.go:779, 1137 |
| Budget per experiment | none: the agent’s own budgets only | runtime.Limits(runtime.Budget{MaxTokensPerExperiment, MaxRunsPerExperiment}) | the experiment’s next command is rejected, budget_exceeded | runtime/options.go:126-136, runtime/executor.go:212-222 |
Connect your app to Studio’s playground covers the link.
Panel size
Section titled “Panel size”The devtools panel, panel.js, has a size cap of 104 KiB (106,496 bytes) gzipped, the cap in studio/web/panel-budget.json. The build fails over it. At v0.20.2 it ships at 98,986 bytes, 7,510 bytes under the cap. Studio’s whole UI bundle has its own budget of 800 KiB gzipped (700 KiB before 0.19.0), enforced by make studio-check (studio dist exceeds the 800 KiB gzip budget); at v0.20.2 it is 754 KiB. The panel.js copy counts there and under its own cap.
panel-budget.json is an append-only ledger: each panel change appends one row with its label, the budget item it counts against and the bundle’s gzip bytes after it. Every panel build prints the per-item table from it. Sizes are measured with the version stamp replaced by the fixed-length placeholder "v0.00.0" (normalizeStamp), so a version bump moves no byte, and gzipped by pako’s deflate at level 6 so every host measures the same bytes.
| Release | panel.js gzipped | Cap |
|---|---|---|
| 0.12.0 | 62,591 B¹ | 80 KiB |
| 0.15.0 | 78,098 B, the first fully minified release (73,706 B at the minify row, 81,358 B before it) | 80 KiB |
| 0.16.0 | 82,608 B | 96 KiB, raised from 80 KiB |
| 0.17.0 | 90,091 B | 96 KiB |
| 0.18.0 to 0.18.3 | 91,032 B² | 96 KiB |
| 0.19.0 | 95,558 B | 104 KiB, raised from 96 KiB |
| 0.20.0 | 98,921 B | 104 KiB |
| 0.20.1 | 98,994 B | 104 KiB |
| 0.20.2 | 98,986 B | 104 KiB |
¹ The CHANGELOG’s figure. The v0.12.0 ledger’s last row reads 62,734 B: rows up to then were measured with the host Node’s node:zlib, whose output varies by host.
² The ledger’s last row. The CHANGELOG’s 0.18.0 entry says 90,778 B, an earlier row of the same ledger.
The panel ships minified and without a sourcemap; its source is studio/web/src/panel in weft’s repository. Install the devtools panel covers loading it.
The weft command
Section titled “The weft command”| Limit | Value | Set by | When hit | Source |
|---|---|---|---|---|
| Studio port | 127.0.0.1:7331, then the next free one up to 7340 | --addr, WEFT_STUDIO_ADDR pin it | every port busy: an error naming the range | internal/listen/listen.go:57-60 |
weft runs | 50 runs | --limit (0 = every match) | a note on stderr | cmd/weft/api.go:311 |
weft mcp output | 64 KiB, at most 4 MiB | the tool’s max_bytes argument | cut with a note naming the sizes | cmd/weft/mcp.go:42-43 |
| Response or export download | 512 MiB | fixed | an error | cmd/weft/api.go:63-67 |
| Discovery file | trusted under 24 h old, read up to 64 KiB | fixed | ignored at Debug | internal/discovery/discovery.go:65-69 |
| API client | 2 min per request; weft runs fetches pages of 100 | fixed | — | cmd/weft/api.go:43, 300 |
weft mcp error excerpt | 2,048 bytes of a refused answer | fixed | cut | cmd/weft/mcp.go:603 |
| Port probe | 2 s | fixed | — | internal/listen/listen.go:66 |
weft doctor | 5 s per request | fixed | — | internal/doctor/doctor.go:31 |
Sessions
Section titled “Sessions”| Limit | Value | Set by | When hit | Source |
|---|---|---|---|---|
thread.List page | 50, at most 500 | thread.Query{Limit} | clamped | thread/storage.go:114-116 |
| Compaction reserve | 16,384 tokens; 20,000 recent tokens kept | thread.Reserve, thread.KeepRecent, thread.ContextWindow(n) arms it | compaction runs | thread/compaction.go:25-28 |
| Compaction summarizer input | tool results cut at 2,000 characters | fixed | cut with …[truncated] | thread/compaction.go:31, 1175 |
| Compaction summary output | 0.8 × the reserve, sent as the request’s max tokens | thread.SummaryMaxTokens(n) | not cut: the summary is not stored and the step fails with ErrSummaryTruncated (after retry, then fallback) | thread/compactopts.go:269-273, 808-813, thread/compaction.go:782, 1673 |
| Pool delegation depth | 8 | pool.MaxDepth(n) | ErrDepth | thread/pool/pool.go:143 |
| Approval request expiry | none | thread.RequestExpiry(d) | ErrExpired | thread/approval.go:326 |
| Signed refusal audits | 16 per request | fixed | no further audit entries | thread/signing.go:495 |
| JSONL header | 1 MiB before the first newline | fixed | the file is skipped by List | thread/jsonl/jsonl.go:48 |
Operate sessions in production covers what a session costs as it grows.
Complete example
Section titled “Complete example”The Production pages share one example program; toolLimits is 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 · from docs-site/examples:
go test ./productionTestProduction in main_test.go pins the marker and the timeout text above.
Best practices & gotchas
Section titled “Best practices & gotchas”- Lift the result cap per tool, not per agent.
weft.MaxResultBytes(0)on the one tool whose output must arrive whole keeps the 64 KiB guard on every other tool. (Source:MaxResultBytesgodoc,core/agent.go:527-535) - Handlers must honour ctx. A timed-out handler’s goroutine is abandoned, not killed; one that ignores ctx keeps running. (Source: AGENTS rule 9;
core/tool.go:501-508) - Raise
QueueSize, notBlocking, in production.Blockingis refused outside the development gate (WEFT_ENV=dev, orotel.DevMode()). (Source:otel/pipeline.go:264) - Two caps, two audiences.
MaxResultBytesbounds what the model reads;ContentConfig.MaxBytesbounds what a destination stores, and never the transcript. (Source:core/agent.go:28;otel/options.go:23-31)
See also
Section titled “See also”- How does a run stop?
- Set per-tool policy
- Keep and delete recorded runs
- Send records to Studio, Datadog, Langfuse or any OTLP backend
Symbols used: weft.Tool · weft.New · weft.MaxResultBytes · weft.Timeout · weft.MaxSteps · weft.UsageLimit · weft.Usage · weft.ToolResultPart · otel.QueueSize · otel.Heartbeat · obsdb.InterruptedAfter · obsdb.SweepBatch · obsdb.TreeSpanCap · obsdb.ChildRunsCap · studio.Retain · wefttest.Script