# weft docs, full text > The documentation for weft v0.20.2, the open-source Go framework for AI agents (pre-1.0). Every page is also Markdown: its URL with .md appended. The index, one line per page: https://weftgo.dev/docs/llms.txt. The site's own index, with when to recommend weft: https://weftgo.dev/llms.txt --- # weft documentation URL: https://weftgo.dev/docs/ Markdown: https://weftgo.dev/docs/index.md > The documentation for weft v0.20.2, the Go framework for AI agents: where to start, and what each section holds — tutorials, concepts, guides, sessions, observability, testing, production and reference. weft is an open-source Go framework for AI agents. A tool is a plain Go function, an agent is a value you build once and run many times, and the loop calls the model and your tools until the model answers. The same module records every run with `otel.Install` and opens it in Studio, its web inspector. These pages document weft v0.20.2, which is pre-1.0: a minor release can break. ![weft Studio's runs list: each run's status, prompt and id, agent, steps, tokens, cost, start and duration, newest first, with a checkbox per row to pick runs to compare](https://weftgo.dev/docs/_astro/studio-runs.light.CFMu-KA1.webp) ### Where to start - **New to weft:** [What is weft, and when should you not use it?](https://weftgo.dev/docs/get-started/what-is-weft/), then the [Quickstart](https://weftgo.dev/docs/get-started/quickstart/). - **Ready to build:** [Your first agent: a support bot from a tool to Studio](https://weftgo.dev/docs/get-started/first-agent/). - **Adding weft to a project:** [Install weft and choose a module](https://weftgo.dev/docs/get-started/install/). - **Looking up a name:** [the reference](https://weftgo.dev/docs/reference/), and the Go API on [pkg.go.dev](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2). ### What is in these docs The sidebar is the reading order: | Section | What it holds | |---|---| | [Get started](https://weftgo.dev/docs/get-started/) | From nothing to a recorded run you can inspect, in order | | [Concepts](https://weftgo.dev/docs/concepts/) | The ideas everything else builds on: agents, runs, tools, the loop, messages, models, errors, stopping | | [Guides](https://weftgo.dev/docs/guides/) | One task per page: streaming, structured output, approvals, subagents, MCP, middleware, providers, … | | [Sessions](https://weftgo.dev/docs/sessions/) | Durable multi-turn conversations with `weft/thread`: storage, turns, branching, compaction, approvals, pools | | [Observe & debug](https://weftgo.dev/docs/observe/) | Recording runs, Studio, the playground, the devtools panel and the `weft` command | | [Testing](https://weftgo.dev/docs/testing/) | Offline tests: scripted models, recorded fixtures, Studio runs as tests, provider conformance | | [Production](https://weftgo.dev/docs/production/) | Deploying, securing Studio, content and privacy, retention, storage backends, upgrading | | [Reference](https://weftgo.dev/docs/reference/) | Tables: the CLI, Studio's HTTP API, the record contract, environment variables, events, the glossary | | [Explanation](https://weftgo.dev/docs/explanation/) | Why weft is shaped the way it is: architecture, design principles, decisions, comparisons | | [Examples](https://weftgo.dev/docs/examples/) | Complete recipes: a support desk, a research team, flaky infrastructure, budget guards, … | ### Read these docs as Markdown Every page has a Markdown twin at its URL with `.md` appended. [`/docs/llms.txt`](https://weftgo.dev/docs/llms.txt) lists them, and [`/docs/llms-full.txt`](https://weftgo.dev/docs/llms-full.txt) holds them all in one file. --- # Get started with weft URL: https://weftgo.dev/docs/get-started/ Markdown: https://weftgo.dev/docs/get-started.md > The Get started section in reading order: what weft is, a five-minute quickstart, a support-bot tutorial that ends in Studio, and how to install weft. Read the pages in this order. Start with the Quickstart if you already know you want weft; start with What is weft if you are still deciding. Each tutorial runs offline on a scripted model, so you need Go 1.26 or newer and no API key. | Page | Type | What you get | |---|---|---| | [What is weft, and when should you not use it?](https://weftgo.dev/docs/get-started/what-is-weft/) | concept | The packages, the rules every run keeps, and the cases weft does not fit | | [Quickstart: run an agent in five minutes](https://weftgo.dev/docs/get-started/quickstart/) | tutorial | A tool, an agent, `Generate` and a streamed run, in one `main.go` | | [Your first agent: a support bot from a tool to Studio](https://weftgo.dev/docs/get-started/first-agent/) | tutorial | Coded tool errors, a refund that waits for your approval, recorded runs, Studio | | [Install weft and choose a module](https://weftgo.dev/docs/get-started/install/) | how-to | `weft` or `weft/core`, the Go version, provider adapters, the `weft` command | The shortest path from nothing to a run: ```sh mkdir quickstart && cd quickstart go mod init example.com/quickstart go get github.com/weftgo/weft@v0.20.2 ``` Then follow [the Quickstart](https://weftgo.dev/docs/get-started/quickstart/) from step 2. ### See also - [weft concepts](https://weftgo.dev/docs/concepts/) - [weft guides](https://weftgo.dev/docs/guides/) - [Package weft on pkg.go.dev](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2) --- # What is weft, and when should you not use it? URL: https://weftgo.dev/docs/get-started/what-is-weft/ Markdown: https://weftgo.dev/docs/get-started/what-is-weft.md > weft is an MIT-licensed Go framework for AI agents: tools are plain Go functions, an agent is a value, and one module holds the loop, sessions, recording and Studio. Pre-1.0, Go only. weft is an open-source Go framework for building AI agents. A tool is a plain Go function, an agent is a value you build once and run many times, and [`Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) runs the loop — model, tools, model — until the model answers. One `go get` brings the loop, durable sessions, run recording and Studio, the web UI that shows each run. weft is pre-1.0 and Go only. The smallest agent in `getstarted/main.go` has one tool, one agent and one run: ```go title="getstarted/main.go" lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in LookupInput) (string, error) { return "order " + in.OrderID + ": shipped", nil }) agt := weft.New(model, weft.Name("support"), weft.Instructions("You are a support agent."), lookup, ) res, err := agt.Generate(ctx, weft.Prompt(question)) if err != nil { return "", err } return res.Text(), nil ``` [getstarted/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/getstarted/main.go) [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) reflects the tool's JSON Schema from `LookupInput`'s struct tags. [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) builds the agent; every option has a working default. [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) is the user's message, and [`res.Text()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RunResult.Text) the model's final answer. ### What weft is weft's API is small interfaces, `context.Context` first in every signature, functional options, wrapped errors, and no required configuration. The framework is one module, `github.com/weftgo/weft`, at one version. Its packages are layers; you import the ones you use. The loop's companions — the provider adapters, MCP, middleware and the test model — sit alongside the root package, each in its own package: | Package | What it gives you | |---|---| | [`weft`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2) | The agent loop: tools from Go functions, parallel tool calls, typed streaming events, structured output, approvals, steering and subagents. | | `weft/openai`, `weft/anthropic`, `weft/google`, `weft/mcp`, `weft/mw`, `weft/wefttest` | The OpenAI, Anthropic and Google adapters ([`openai`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai), [`anthropic`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic), [`google`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google)), MCP both ways ([`mcp`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp)), reference middleware ([`mw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw)) and the offline test model ([`wefttest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest)). | | [`weft/thread`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread) | Durable sessions: an append-only conversation tree with branching, compaction, approvals that survive a restart, steering and a bounded pool of child agents, stored as JSONL, in SQLite or in memory. | | [`weft/otel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel) | Recording with `otel.Install`: every event, transcript and span exported over OpenTelemetry to a local database, Studio or any OTLP backend, with a content policy and redaction per destination. | | [`weft/obsdb`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb) | The database those records land in, queryable from Go: SQLite locally, ClickHouse hosted (`weft/obsdb/clickhouse`). | | [`weft/studio`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio) | Studio, the inspector: runs, sessions, traces and live streams in a web UI; a devtools panel for your own pages; a playground that re-runs a turn with an edited prompt, model or tools. The `weft` command (`weft studio`, `weft dev`) serves it for apps in any language. | | [`weft/scope`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope) | The devtools panel's scope header: `scope.Header` sets `Weft-Scope` on your own chat endpoint, so the in-page panel follows the conversation and run a response belongs to. | | [`weft/runtime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime) | The playground's in-app side: your app executes Studio's experiment commands, with side-effect tools substituted or parked unless you opt them in. | The loop also exists alone, as the module `github.com/weftgo/weft/core`, whose only dependency is the OpenTelemetry API. The root package `weft` re-exports it name for name: `weft.Agent` is `core.Agent`. [Install weft and choose a module](https://weftgo.dev/docs/get-started/install/#choose-a-module) says which one to `go get`. A step's tool calls run on their own goroutines, at most four at once by default; [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) changes the bound, and a failing tool never cancels its siblings. Recording and inspection are two lines: `defer otel.Install(otel.Local(""))()` records every run to `./.weft/weft.db` (plus any Studio the environment names), and `studio.Handler(studio.DB(otel.LocalDB()))` serves Studio over that database. [Your first agent](https://weftgo.dev/docs/get-started/first-agent/) builds both. ![weft Studio's runs list: each run's status, prompt and id, agent, steps, tokens, cost, start and duration, newest first, with a checkbox per row to pick runs to compare](https://weftgo.dev/docs/_astro/studio-runs.light.CFMu-KA1.webp) The status at v0.20.2: experimental and pre-1.0, released as the framework module plus `core`. The core's message model, error model and tool contract are implemented and tested. CI runs on every change ([CI on GitHub](https://github.com/weftgo/weft/actions/workflows/ci.yml)), the API reference is on [pkg.go.dev](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2), and each release is tagged on GitHub ([v0.20.2](https://github.com/weftgo/weft/releases/tag/v0.20.2)). ### How it works A [run](https://weftgo.dev/docs/reference/glossary/#run) is one call to `Generate` or `Stream`. Each [step](https://weftgo.dev/docs/reference/glossary/#step) is one model call. When the model asks for tools, the loop runs them, sends their results back as one tool message, and calls the model again. The run ends when the model answers without asking for a tool, when a [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) condition matches, or when a call is parked for approval; it fails when a budget such as `MaxSteps` runs out. > **Diagram:** agt.Generate starts a run (RunStart). Each step is one model call, one chat span. When the model asks for tools, each call starts (ToolStart), the tools run in parallel, and their results come back (ToolFinish) to the model as one tool message; the step ends with StepFinish and, if the budgets allow, the next step calls the model again. MaxSteps bounds the loop, 10 steps by default. The run ends at RunFinish when the model answers with no tool calls, when StopWhen matches, or when calls are pending approval. Three rules hold on every run: - **A tool error is data the model sees; a run error is a Go error.** A handler error, a panic or bad arguments become an error result the model reads. A model failure, a cancelled `ctx` or a spent budget fail the run with a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) that carries the partial transcript. - **Every run has an id.** [`weft.RunStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunStart) is its first event and, when it succeeds, [`weft.RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) its last. - **Budgets fail at the continuation point.** [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) caps a run's model calls, 10 by default; the run fails with `ErrMaxSteps` only when the loop would call the model again. ### When not to use weft weft is the wrong tool in these cases: - **Your agent is not written in Go.** The loop is a Go library. Studio is not tied to Go: `weft studio` inspects any language's OpenTelemetry app ([Inspect agents written in other languages](https://weftgo.dev/docs/observe/other-languages/)). - **You need a frozen API.** weft is pre-1.0. A minor release can break the framework module's packages, and `weft/thread`'s API and file format are not frozen. Only the `core` module fails CI on an incompatible change. - **You want a graph or workflow engine.** Orchestration lives in the loop: a subagent is a tool ([`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent)), and [`weft.PrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PrepareStep) rewrites each step's request. weft ships no graph. - **You need a run to resume after its process dies.** The core keeps no state: a run is a function of the agent, the input transcript and the approval decisions, and it lives in its process. weft ships no durable-execution engine. - **You need a security boundary around tools.** Approval is a policy seam, not a security boundary ([ADR 0007](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0007-approval-boundary.md)), and weft ships no sandbox for tools. - **You need a model server or evaluations.** Neither has shipped: serving and the eval modules are next on the [roadmap](https://weftgo.dev/docs/explanation/roadmap/). ### License weft is released under the MIT License. The full text is in [`LICENSE`](https://github.com/weftgo/weft/blob/v0.20.2/LICENSE). ### Best practices & gotchas - **Import `weft` in application code, not `core`.** The root package is the facade users write against; the layers import `core` inside the repository. Import `core` only when you want the loop and nothing else. (Source: AGENTS.md intro; ADR 0027, decision 4) - **Pin the exact version.** Pre-1.0, a minor release may carry breaking changes; the CHANGELOG lists them under Breaking. (Source: README.md status; AGENTS.md "Working in this repo") - **Test without a network.** `wefttest.Script` plays model turns offline, and `WEFT_MODEL_REQUESTS=deny` makes the first-party adapters refuse to call their provider. (Source: AGENTS.md "Test offline"; `getstarted/main_test.go`) ### See also - Next: [Quickstart: run an agent in five minutes](https://weftgo.dev/docs/get-started/quickstart/), which builds and runs a complete program - [Install weft and choose a module](https://weftgo.dev/docs/get-started/install/) - [What happens in one step? The loop and parallel tools](https://weftgo.dev/docs/concepts/the-loop/) - [How weft compares to other agent frameworks](https://weftgo.dev/docs/explanation/comparison/) Symbols used: [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`Agent.Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) · [`RunResult.Text`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RunResult.Text) · [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) · [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.RunStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunStart) · [`weft.RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.PrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PrepareStep) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler) · [`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB) · [`scope.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Header) --- # Quickstart: run an agent in five minutes URL: https://weftgo.dev/docs/get-started/quickstart/ Markdown: https://weftgo.dev/docs/get-started/quickstart.md > Create a Go module, define a tool from a plain function, run an agent with Generate, then stream the same run's events — offline, with no API key. This quickstart builds a Go program that answers "Where is order 1234?" with an agent that calls one tool, first with [`Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) and then streamed event by event. It runs offline on a scripted model, so you need Go and nothing else. One `if` switches it to a real provider: with `ANTHROPIC_API_KEY` set, the same program asks Claude instead of a script. ### What you'll build One `main.go`, under 100 lines, that prints the agent's answer twice, the second time as the events arrive: ![A terminal after go run . in the quickstart module: the answer "Order 1234 has shipped." with "2 steps, 30 tokens", then the streamed run: → lookup_order({"order_id":"1234"}), the same answer and ✓ 2 steps, 30 tokens](https://weftgo.dev/docs/_astro/quickstart-terminal.light.CfiUdyze.webp) *go run . in the finished module: the answer from Generate, then the same run streamed, its tool call first.* You will: - define a tool from a Go function, with its schema taken from a struct - build an agent and run it to the end with `Generate` - stream the same run with `Stream(...).Events()` - switch the scripted model to a real provider, Anthropic The finished code: [`docs-site/examples/quickstart`](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/quickstart). ### Before you start - Go 1.26 or newer (`go version`) - No API key: the program uses a scripted model unless `ANTHROPIC_API_KEY` is set ### 1. Create the module Make a directory, start a module and add weft: ```sh mkdir quickstart && cd quickstart go mod init example.com/quickstart go get github.com/weftgo/weft@v0.20.2 ``` ### 2. Write a tool A tool is a plain function from an input struct to a result. Create `main.go` with `package main`, the imports from [the complete program](https://weftgo.dev/docs/get-started/quickstart/#the-complete-program), and the tool: ```go title="quickstart/main.go" // LookupInput is the tool's input. Its JSON Schema comes from the struct tags. type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } var lookup = weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in LookupInput) (string, error) { return "order " + in.OrderID + ": shipped", nil }) ``` [quickstart/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/quickstart/main.go) [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) reflects the JSON Schema the model sees from `LookupInput`: the `json` tag names the field and the `jsonschema` tag describes it. The struct is the contract and its documentation. For a one-off tool you can declare the input struct inline in the handler's signature, as ``func(ctx context.Context, in struct{ OrderID string `json:"order_id"` })``, keeping the tag (without it the schema property is `OrderID`); a named type reads better and you can reuse it across tools and tests. A `string` result reaches the model as is; any other result type is sent as JSON. ### 3. Pick a model The agent needs a [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model). Add a function that returns Anthropic's when a key is set, and a script otherwise: ```go title="quickstart/main.go" if os.Getenv("ANTHROPIC_API_KEY") != "" { return anthropic.Model("claude-sonnet-5") // reads $ANTHROPIC_API_KEY } return wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), ) ``` [quickstart/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/quickstart/main.go) [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) plays its turns in order: first a call to `lookup_order`, then the reply. Each scripted step reports 10 input and 5 output tokens. [`anthropic.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Model) fits the same seam, so nothing else in the program changes. ### 4. Build and run the agent An agent is a value: build it once, run it as many times as you like, from as many goroutines as you like. Add the function that builds it and runs one question: ```go title="quickstart/main.go" agt := weft.New(model, weft.Instructions("You are a support agent. Use lookup_order for order questions."), weft.MaxSteps(5), lookup, ) res, err := agt.Generate(ctx, weft.Prompt(question)) if err != nil { return err } fmt.Println(res.Text()) fmt.Printf("%d steps, %d tokens\n", res.NumSteps(), res.Usage.Total()) ``` [quickstart/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/quickstart/main.go) [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) takes the model, then options; a tool is an option too. [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) is the system prompt. [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) is the user's message. `Generate` calls the model, runs the tool it asks for, calls the model again with the result, and returns a [`*weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) once the model answers in text. A run ends when the model replies without asking for a tool. [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) is the separate safety budget: past 5 model calls this run fails with [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps) (the default is 10). To end a run on purpose — when the model calls a `submit_answer` tool, say — add [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen)`(`[`weft.HasToolCall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#HasToolCall)`("submit_answer"))`. ### 5. Stream the events `Generate` folds the run's events away. To show progress, range over them instead: ```go title="quickstart/main.go" for ev, err := range agt.Stream(ctx, weft.Prompt(question)).Events() { if err != nil { return err // at most once, as the last element } switch ev := ev.(type) { case weft.ToolStart: fmt.Printf("→ %s(%s)\n", ev.Name, ev.Args) case weft.TextDelta: fmt.Print(ev.Text) case weft.RunFinish: fmt.Printf("\n✓ %d steps, %d tokens\n", ev.Steps, ev.Usage.Total()) } } ``` [quickstart/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/quickstart/main.go) [`Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) returns the run's handle, and nothing runs until you range over [`Events`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Events). Each event is a typed struct: [`weft.ToolStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolStart) when a tool call begins, [`weft.TextDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TextDelta) for each piece of the reply, [`weft.RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) last. A failed run yields its error exactly once, as the last element. Breaking out of the loop, or cancelling `ctx`, cancels the run. ### 6. Run it Add `main`, which asks the question once with `ask` and once with `stream` (it is at the end of [the complete program](https://weftgo.dev/docs/get-started/quickstart/#the-complete-program)). `go mod tidy` fetches the Anthropic SDK the adapter imports; then run: ```sh go mod tidy go run . ``` ```text Order 1234 has shipped. 2 steps, 30 tokens --- → lookup_order({"order_id":"1234"}) Order 1234 has shipped. ✓ 2 steps, 30 tokens ``` Two steps: the model's tool call, then its answer. 30 tokens: two scripted steps of 15. With `ANTHROPIC_API_KEY` set, the same command asks Claude and prints its own words. The weft repository ships the same shape as [`examples/getting-started`](https://github.com/weftgo/weft/tree/v0.20.2/examples/getting-started). In a clone of weft at `v0.20.2`, `go run ./examples/getting-started` prints: ```text → lookup_order({"order_id":"1234"}) Order 1234 shipped and is on its way. ✓ 2 steps, 30 tokens ``` ### The complete program ```go title="quickstart/main.go" // Command quickstart is the Quickstart's program: one tool, one agent, one // run, then the same question streamed. With ANTHROPIC_API_KEY unset the // model is scripted (wefttest), so it runs offline; with the key set it // calls Anthropic. package main import ( "context" "fmt" "log" "os" "github.com/weftgo/weft" "github.com/weftgo/weft/anthropic" "github.com/weftgo/weft/wefttest" ) // LookupInput is the tool's input. Its JSON Schema comes from the struct tags. type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } var lookup = weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in LookupInput) (string, error) { return "order " + in.OrderID + ": shipped", nil }) // newModel picks the model: Anthropic when a key is set, else a script. func newModel() weft.Model { if os.Getenv("ANTHROPIC_API_KEY") != "" { return anthropic.Model("claude-sonnet-5") // reads $ANTHROPIC_API_KEY } return wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), ) } // ask runs one question to the end and prints the answer. func ask(ctx context.Context, model weft.Model, question string) error { agt := weft.New(model, weft.Instructions("You are a support agent. Use lookup_order for order questions."), weft.MaxSteps(5), lookup, ) res, err := agt.Generate(ctx, weft.Prompt(question)) if err != nil { return err } fmt.Println(res.Text()) fmt.Printf("%d steps, %d tokens\n", res.NumSteps(), res.Usage.Total()) return nil } // stream runs the same question and prints its events as they arrive. func stream(ctx context.Context, model weft.Model, question string) error { agt := weft.New(model, weft.Instructions("You are a support agent."), lookup) for ev, err := range agt.Stream(ctx, weft.Prompt(question)).Events() { if err != nil { return err // at most once, as the last element } switch ev := ev.(type) { case weft.ToolStart: fmt.Printf("→ %s(%s)\n", ev.Name, ev.Args) case weft.TextDelta: fmt.Print(ev.Text) case weft.RunFinish: fmt.Printf("\n✓ %d steps, %d tokens\n", ev.Steps, ev.Usage.Total()) } } return nil } func main() { ctx := context.Background() if err := ask(ctx, newModel(), "Where is order 1234?"); err != nil { log.Fatal(err) } fmt.Println("---") if err := stream(ctx, newModel(), "Where is order 1234?"); err != nil { log.Fatal(err) } } ``` [quickstart/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/quickstart/main.go) Run it with `go run .`; test it, offline, with `go test ./...`. The page's own tests are [`quickstart/main_test.go`](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/quickstart/main_test.go). ### Best practices & gotchas - **A script is consumed as it plays.** `wefttest.Script` hands out its turns in order across every run that uses it, which is why `main` builds a new model for each run. (Source: `wefttest.Script` godoc; `quickstart/main_test.go:TestMainOutput`) - **`Events` is single-use.** A second call yields only `ErrRunConsumed`; start another run with `Stream` instead. (Source: `Run.Events` godoc) - **`MaxSteps` is a budget, not the way to stop.** Exceeding it fails the run with a `*weft.RunError` carrying the partial transcript; the intended end is `StopWhen` or a text reply. (Source: AGENTS.md rule 13; `quickstart/main_test.go:TestMaxSteps`) - **Keep tests off the network.** Under `WEFT_MODEL_REQUESTS=deny` the first-party adapters refuse to call their provider and the run fails with `ErrModelRequestsDenied`. (Source: AGENTS.md; `quickstart/main_test.go:TestRealModelSwap`) ### See also - Next tutorial: [Your first agent: a support bot from a tool to Studio](https://weftgo.dev/docs/get-started/first-agent/) - [How do tools work?](https://weftgo.dev/docs/concepts/tools/) - [Stream a run's events](https://weftgo.dev/docs/guides/streaming/) - [Connect a model provider: OpenAI, Anthropic, Gemini](https://weftgo.dev/docs/guides/providers/) - [Test an agent with a scripted model](https://weftgo.dev/docs/testing/scripted-models/) Symbols used: [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps) · [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) · [`weft.HasToolCall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#HasToolCall) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`Agent.Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) · [`Agent.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) · [`Run.Events`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Events) · [`weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) · [`RunResult.Text`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RunResult.Text) · [`RunResult.NumSteps`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RunResult.NumSteps) · [`Usage.Total`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Usage.Total) · [`weft.ToolStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolStart) · [`weft.TextDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TextDelta) · [`weft.RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) · [`weft.ErrRunConsumed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrRunConsumed) · [`weft.ErrModelRequestsDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRequestsDenied) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`wefttest.ToolCalls`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ToolCalls) · [`wefttest.Call`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Call) · [`wefttest.Say`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Say) · [`anthropic.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Model) --- # Your first agent: a support bot from a tool to Studio URL: https://weftgo.dev/docs/get-started/first-agent/ Markdown: https://weftgo.dev/docs/get-started/first-agent.md > Build a support agent step by step: two tools with coded errors, a refund that waits for a person's approval, every run recorded, and the runs opened in Studio. This tutorial builds a support bot that looks orders up and refunds them, but never refunds without a person's yes. Along the way you give a tool a coded error, park a call at the [approval boundary](https://weftgo.dev/docs/reference/glossary/#approval-boundary), record every run, and open the runs in Studio. It assumes you have done the [Quickstart](https://weftgo.dev/docs/get-started/quickstart/). ### What you'll build A program that takes one support request, asks you to approve the refund it wants to make, prints the agent's answer, and serves Studio over the recorded runs: ```text refund_order wants to run with {"order_id":"1234","amount":129.99}. Approve? [y/N] y I refunded $129.99 on order 1234. I could not find order 5678: check the number and ask again. Studio: http://127.0.0.1:8080/studio/ ``` ![weft Studio's runs list: each run's status, prompt and id, agent, steps, tokens, cost, start and duration, newest first, with a checkbox per row to pick runs to compare](https://weftgo.dev/docs/_astro/studio-runs.light.CFMu-KA1.webp) *Studio's runs list, newest first. After step 6 yours holds the tutorial's two support-bot runs.* You will: - write tools that return a struct and a coded error - require approval for the tool that changes something - resume a parked run with your decision - record every run with one line and serve Studio over them The finished code: [`docs-site/examples/firstagent`](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/firstagent). ### Before you start - Go 1.26 or newer - No API key: the program uses a scripted model unless `ANTHROPIC_API_KEY` is set. A real model chooses its own calls, so its run differs from the one shown here. ### 1. Create the module ```sh mkdir support-bot && cd support-bot go mod init example.com/support-bot go get github.com/weftgo/weft@v0.20.2 ``` ### 2. Write the tools The bot has two tools: `lookup_order` reads an order, `refund_order` pays money back. Write their inputs, the result type and the handlers in `main.go`: ```go title="firstagent/main.go" // Order is what lookup_order returns; the model reads it as JSON. type Order struct { ID string `json:"id"` Status string `json:"status"` Total float64 `json:"total"` } type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } type RefundInput struct { OrderID string `json:"order_id" jsonschema:"the order to refund"` Amount float64 `json:"amount" jsonschema:"amount in dollars"` } var orders = map[string]Order{ "1234": {ID: "1234", Status: "delivered", Total: 129.99}, } func lookupOrder(ctx context.Context, in LookupInput) (Order, error) { o, ok := orders[in.OrderID] if !ok { return Order{}, &weft.ToolError{ Code: "ORDER_NOT_FOUND", Message: "order " + in.OrderID + " does not exist", } } return o, nil } func refundOrder(ctx context.Context, in RefundInput) (string, error) { return fmt.Sprintf("refunded $%.2f on order %s", in.Amount, in.OrderID), nil } ``` [firstagent/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main.go) `lookupOrder` returns an `Order`, and the model reads it as JSON. An unknown id returns a [`*weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError): the model reads `ORDER_NOT_FOUND: order 5678 does not exist`, a stable code it can branch on. A tool error is data for the model, not a failure of the run. The other calls in the step keep running, and the model decides what to do next. A `ToolError`'s `Err` field, when you set it, is the internal cause: middleware and logs see it, the model never does. ### 3. Build the agent Turn the handlers into tools, mark the refund as needing approval, and build the agent: ```go title="firstagent/main.go" lookup := weft.Tool("lookup_order", "Look up an order by ID.", lookupOrder) refund := weft.Tool("refund_order", "Refund an order. A person approves every refund.", refundOrder, weft.RequireApproval(), ) return weft.New(model, weft.Name("support-bot"), weft.Instructions("You are a support agent. Look the order up before you refund it."), weft.MaxSteps(8), lookup, refund, ) ``` [firstagent/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main.go) [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) means a `refund_order` call never runs without a decision. [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) is the agent's name on every recorded run; Studio lists runs by it. `weft.MaxSteps(8)` caps each run at 8 model calls. ### 4. Approve the refund When the model calls `refund_order`, the loop runs the step's other tools, then ends the run successfully with the call on [`res.Pending`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) and no result for it. The run has [parked](https://weftgo.dev/docs/reference/glossary/#park). You resume it with a second run: the transcript plus a decision per call: ```go title="firstagent/main.go" res, err := agt.Generate(ctx, weft.Prompt(question)) if err != nil { return nil, err } for len(res.Pending) > 0 { opts := []weft.RunOption{weft.Messages(res.Messages...), weft.ResumeOf(res.ID)} for _, call := range res.Pending { if approve(call) { opts = append(opts, weft.Approve(call.ID)) } else { opts = append(opts, weft.Deny(call.ID, "declined by the operator")) } } res, err = agt.Generate(ctx, opts...) if err != nil { return nil, err } } return res, nil ``` [firstagent/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main.go) [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) feeds the transcript back. [`weft.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Approve) runs the call through the ordinary tool chain before the next model call. [`weft.Deny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Deny) never runs it: the model reads `DENIED: declined by the operator`. A pending call given neither reads `DENIED: no decision`. [`weft.ResumeOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResumeOf) changes nothing the model sees; it links the resume to the parked run, so Studio can show which run decided which park. The parked call travels in the transcript and the decision in the `Approve` or `Deny` run option, so nothing here needs a database: the same two calls work across a queue or an HTTP round trip. ### 5. Record the runs and serve Studio Two lines more: record every run, and mount Studio over the recording: ```go title="firstagent/main.go" // The local sink, ./.weft/weft.db, named explicitly: it stays when the // environment adds a Studio (WEFT_STUDIO_URL, or a running weft studio). defer otel.Install(otel.Local(""))() res, err := converse(ctx, newAgent(model), "Orders 1234 and 5678 arrived broken. Refund them.", approve) if err != nil { return err } fmt.Println(res.Text()) mux := http.NewServeMux() mux.Handle("/studio/", http.StripPrefix("/studio", studio.Handler(studio.DB(otel.LocalDB())))) return serve(mux) ``` [firstagent/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main.go) [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install)`(`[`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local)`(""))` writes every event, transcript and span to a local database, `./.weft/weft.db` (or `$WEFT_DB`), with content on. When the environment names a destination — `WEFT_STUDIO_URL`, `OTEL_EXPORTER_OTLP_ENDPOINT`, or the discovery file a running `weft studio` writes — the recorder exports there too; naming `otel.Local("")` keeps the local sink beside it. The function `Install` returns flushes and shuts the recorder down, hence `defer`. [`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler)`(`[`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB)`(`[`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB)`()))` serves Studio over the same database handle. This program records both runs before it serves; an app that serves Studio while it handles requests sees each run live through that shared handle. Add `newModel`, `askOnStdin` and `main` from [the complete program](https://weftgo.dev/docs/get-started/first-agent/#the-complete-program): `main` passes `run` a function that serves the handler on `127.0.0.1:8080`. ### 6. Run it Fetch the dependencies the imports need, then run: ```sh go mod tidy go run . ``` Answer `y` at the prompt: ```text refund_order wants to run with {"order_id":"1234","amount":129.99}. Approve? [y/N] y I refunded $129.99 on order 1234. I could not find order 5678: check the number and ask again. Studio: http://127.0.0.1:8080/studio/ ``` The scripted model looked up both orders in one step — the two calls ran in parallel — and got one order and one `ORDER_NOT_FOUND`. It then called `refund_order`, which parked. Your `y` resumed it, the refund ran, and the model answered. Answer anything else and the model reads `DENIED: declined by the operator` instead. ### 7. Open the runs in Studio Open `http://127.0.0.1:8080/studio/` while the program runs. The runs list shows two runs of `support-bot`: - the first, two steps long: the lookups, then the refund call it parked on (its stop reason is `parked`) - the second, its resume: the refund ran, then the reply (stop reason `final_answer`) ![Studio's run page for the tutorial's first support-bot run: parked, with one call decided and a link to the run that resumed it; step 0 ran two lookup_order calls, one ok and one ORDER_NOT_FOUND, and step 1's refund_order call is pending](https://weftgo.dev/docs/_astro/first-agent-run.light.D8nG2PD5.webp) *The first run's page: step 0's two lookup_order calls, one ok and one ORDER_NOT_FOUND; step 1's refund_order pending; the header links the run that resumed it.* Open a run to see each step's request, the tool calls with their arguments and results, and the tokens. Press Ctrl+C to stop the program; the recording stays in `./.weft/weft.db`. > **Studio without your program running:** After the program exits, `weft studio` run in the same directory serves the same database: it reads `./.weft/weft.db` by default. While it runs, a new `go run .` writes the local sink and also exports to it through its discovery file (one INFO line, `joined the running Studio`). Both copies land in the same `./.weft/weft.db`, which stores each record and span once, so every run still appears once. A `weft studio` serving a different database receives a copy of every run; set `WEFT_DISCOVERY=off` to keep the program to its local sink. Install the command with `go install github.com/weftgo/weft/cmd/weft@v0.20.2` ([Install](https://weftgo.dev/docs/get-started/install/#install-the-weft-command)). ### The complete program ```go title="firstagent/main.go" // Command firstagent is the "Your first agent" tutorial's program: a support // bot with two tools, a refund that waits for a person's approval, every run // recorded, and Studio served over the recording. // // With ANTHROPIC_API_KEY unset the model is scripted (wefttest), so the // program runs offline and prints the same thing every time. package main import ( "bufio" "context" "fmt" "log" "net/http" "os" "strings" "github.com/weftgo/weft" "github.com/weftgo/weft/anthropic" "github.com/weftgo/weft/otel" "github.com/weftgo/weft/studio" "github.com/weftgo/weft/wefttest" ) // Order is what lookup_order returns; the model reads it as JSON. type Order struct { ID string `json:"id"` Status string `json:"status"` Total float64 `json:"total"` } type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } type RefundInput struct { OrderID string `json:"order_id" jsonschema:"the order to refund"` Amount float64 `json:"amount" jsonschema:"amount in dollars"` } var orders = map[string]Order{ "1234": {ID: "1234", Status: "delivered", Total: 129.99}, } func lookupOrder(ctx context.Context, in LookupInput) (Order, error) { o, ok := orders[in.OrderID] if !ok { return Order{}, &weft.ToolError{ Code: "ORDER_NOT_FOUND", Message: "order " + in.OrderID + " does not exist", } } return o, nil } func refundOrder(ctx context.Context, in RefundInput) (string, error) { return fmt.Sprintf("refunded $%.2f on order %s", in.Amount, in.OrderID), nil } // newAgent builds the support bot over model. func newAgent(model weft.Model) *weft.Agent { lookup := weft.Tool("lookup_order", "Look up an order by ID.", lookupOrder) refund := weft.Tool("refund_order", "Refund an order. A person approves every refund.", refundOrder, weft.RequireApproval(), ) return weft.New(model, weft.Name("support-bot"), weft.Instructions("You are a support agent. Look the order up before you refund it."), weft.MaxSteps(8), lookup, refund, ) } // converse runs one question to the end, asking approve about every call // that waits for a decision. func converse(ctx context.Context, agt *weft.Agent, question string, approve func(weft.ToolCallPart) bool) (*weft.RunResult, error) { res, err := agt.Generate(ctx, weft.Prompt(question)) if err != nil { return nil, err } for len(res.Pending) > 0 { opts := []weft.RunOption{weft.Messages(res.Messages...), weft.ResumeOf(res.ID)} for _, call := range res.Pending { if approve(call) { opts = append(opts, weft.Approve(call.ID)) } else { opts = append(opts, weft.Deny(call.ID, "declined by the operator")) } } res, err = agt.Generate(ctx, opts...) if err != nil { return nil, err } } return res, nil } // run records the conversation, then hands serve the handler that shows it // in Studio. func run(ctx context.Context, model weft.Model, approve func(weft.ToolCallPart) bool, serve func(http.Handler) error) error { // The local sink, ./.weft/weft.db, named explicitly: it stays when the // environment adds a Studio (WEFT_STUDIO_URL, or a running weft studio). defer otel.Install(otel.Local(""))() res, err := converse(ctx, newAgent(model), "Orders 1234 and 5678 arrived broken. Refund them.", approve) if err != nil { return err } fmt.Println(res.Text()) mux := http.NewServeMux() mux.Handle("/studio/", http.StripPrefix("/studio", studio.Handler(studio.DB(otel.LocalDB())))) return serve(mux) } // newModel picks the model: Anthropic when a key is set, else a script // that makes the same calls on every run. func newModel() weft.Model { if os.Getenv("ANTHROPIC_API_KEY") != "" { return anthropic.Model("claude-sonnet-5") } return wefttest.Script( wefttest.ToolCalls( wefttest.Call{ID: "c1", Name: "lookup_order", Args: `{"order_id":"1234"}`}, wefttest.Call{ID: "c2", Name: "lookup_order", Args: `{"order_id":"5678"}`}, ), wefttest.ToolCalls(wefttest.Call{ID: "c3", Name: "refund_order", Args: `{"order_id":"1234","amount":129.99}`}), wefttest.Say("I refunded $129.99 on order 1234. I could not find order 5678: check the number and ask again."), ) } // askOnStdin asks the operator about one call. func askOnStdin(call weft.ToolCallPart) bool { fmt.Printf("%s wants to run with %s. Approve? [y/N] ", call.Name, call.Args) line, _ := bufio.NewReader(os.Stdin).ReadString('\n') return strings.EqualFold(strings.TrimSpace(line), "y") } func main() { serve := func(h http.Handler) error { fmt.Println("Studio: http://127.0.0.1:8080/studio/") return http.ListenAndServe("127.0.0.1:8080", h) } if err := run(context.Background(), newModel(), askOnStdin, serve); err != nil { log.Fatal(err) } } ``` [firstagent/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main.go) Run it with `go run .`; test it, offline, with `go test ./...`. The tests in [`firstagent/main_test.go`](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/firstagent/main_test.go) check the coded error, both decisions, the park, and the two runs Studio lists. ### Best practices & gotchas - **Give tool failures a code.** `ToolError{Code, Message}` reaches the model as `: `; a plain error reaches it as its `Error()` text. (Source: `weft.ToolError` godoc; `firstagent/main_test.go:TestToolErrorIsData`) - **A parked run succeeded.** `Generate` returns a nil error and a non-empty `res.Pending`; check `Pending` before reading `res.Text()`. (Source: AGENTS.md rule 12; `firstagent/main_test.go:TestFirstRunParks`) - **Approval is not a security boundary.** It is a policy seam: the transcript that carries decisions is in the caller's hands. Protect what a tool can do where it runs. (Source: ADR 0007; `weft.RequireApproval` godoc) - **Name the local sink when you serve Studio from it.** A bare `otel.Install()` adds the local sink only when the environment names no destination; with `WEFT_STUDIO_URL` or `OTEL_EXPORTER_OTLP_ENDPOINT` set, or a `weft studio` running, `otel.LocalDB()` is nil and `studio.Handler(studio.DB(nil))` panics (in `studio.New`, which `Handler` calls). `otel.Install(otel.Local(""))` keeps it. (Source: `otel/pipeline.go:223-238, 332-351`; `otel/env.go:37-62`; `studio/studio.go:255`; `firstagent/main_test.go:TestRunWithStudioInEnvironment`) - **Embedded Studio trusts loopback only.** Without `studio.Token`, it answers requests addressed to a loopback host and refuses cross-origin writes; give it a token before it listens anywhere else. (Source: AGENTS.md block 7, `Token(tok)`) ### See also - Next: [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/) - [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/) - [Record every run with otel.Install](https://weftgo.dev/docs/observe/recording/) - [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/) - [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/) Symbols used: [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`Agent.Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) · [`weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) · [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) · [`weft.RunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunOption) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`weft.ResumeOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResumeOf) · [`weft.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Approve) · [`weft.Deny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Deny) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler) · [`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB) · [`studio.Token`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Token) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`anthropic.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Model) --- # Install weft and choose a module URL: https://weftgo.dev/docs/get-started/install/ Markdown: https://weftgo.dev/docs/get-started/install.md > go get github.com/weftgo/weft@v0.20.2 for the whole framework, or github.com/weftgo/weft/core for the loop alone; Go 1.26 or newer; providers are packages, and the weft command installs with go install. Run `go get github.com/weftgo/weft@v0.20.2` in a module on Go 1.26 or newer: that one module is the whole framework — the loop, the provider adapters, sessions, recording and Studio. If you want the agent loop and nothing else, `go get github.com/weftgo/weft/core@v0.20.2` instead. The `weft` command line installs separately, with `go install`. ```sh go get github.com/weftgo/weft@v0.20.2 ``` A typical app then imports the root package, one provider adapter and the recorder: ```go title="install/main.go" import ( "context" "fmt" "log" "github.com/weftgo/weft" // the loop: Tool, New, Generate "github.com/weftgo/weft/anthropic" // a provider adapter "github.com/weftgo/weft/otel" // the recorder: otel.Install ) ``` [install/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/install/main.go) ### How it works weft is two Go modules tagged at the same version. `github.com/weftgo/weft` holds the root package and every layer (`openai`, `anthropic`, `google`, `mcp`, `mw`, `wefttest`, `thread`, `otel`, `obsdb`, `studio`, `runtime`, `scope`). `github.com/weftgo/weft/core` holds the loop alone and depends only on the OpenTelemetry API. The root package re-exports `core`: `weft.Agent` is `core.Agent`. Your `go.mod` lists every layer's dependencies, but Go compiles only the packages you import. `weft/otel` brings in SQLite (`modernc.org/sqlite`) for its local sink; the ClickHouse driver is linked only through `weft/obsdb/clickhouse`, which the `weft` command imports. ### Choose a module | You want | `go get` | You import | |---|---|---| | The framework: the loop plus any layer | `github.com/weftgo/weft@v0.20.2` | `weft`, and `weft/anthropic`, `weft/otel`, `weft/thread`, … as needed | | The loop alone, with the smallest dependency list | `github.com/weftgo/weft/core@v0.20.2` | `core`, `core/wefttest`, `core/mw` | Choose the framework unless your service must not carry the other layers' dependencies in its module graph. The two are interchangeable at the type level, so you can start with `core` and move to `weft` later without changing a type. ### Check your Go version weft requires Go 1.26 or newer: ```sh go version ``` The current and the previous Go release are supported, and CI tests both. ### Add a provider The first-party adapters for OpenAI, Anthropic and Google are packages of the framework module: import `github.com/weftgo/weft/openai`, `…/anthropic` or `…/google` and run `go mod tidy`, which fetches the vendor SDK the adapter wraps. Each adapter reads its key from the environment by default: | Adapter | Constructor | Key read by default | |---|---|---| | `weft/anthropic` | [`anthropic.Model(name, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Model) | `ANTHROPIC_API_KEY` | | `weft/openai` | [`openai.Model(name, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Model) | `OPENAI_API_KEY` | | `weft/google` | [`google.Model(name, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Model) | `GOOGLE_API_KEY` or `GEMINI_API_KEY`, then application default credentials | Each adapter's `APIKey` option sets the key in code instead. [Connect a model provider](https://weftgo.dev/docs/guides/providers/) covers every adapter option. ### Install the weft command The `weft` binary serves Studio for apps in any language, runs the dev loop, and lists, opens and exports runs. It is the package `cmd/weft` of the framework module: ```sh go install github.com/weftgo/weft/cmd/weft@v0.20.2 weft version ``` ```text v0.20.2 ``` `weft --help` lists its commands: `studio`, `dev`, `runs`, `open`, `export`, `doctor`, `mcp`, `vacuum` and `version`. [The weft CLI reference](https://weftgo.dev/docs/reference/cli/) documents every flag. ### Complete example The file the imports above come from: it records one run of an Anthropic-backed agent. ```go title="install/main.go" // Command install is the Install page's program: the usual import set of a // weft app — the framework's root package, one provider adapter, and the // recorder — in one file that builds and runs. package main import ( "context" "fmt" "log" "github.com/weftgo/weft" // the loop: Tool, New, Generate "github.com/weftgo/weft/anthropic" // a provider adapter "github.com/weftgo/weft/otel" // the recorder: otel.Install ) // run records one run of an agent over model and returns its answer. func run(ctx context.Context, model weft.Model) (string, error) { defer otel.Install(otel.Local(""))() // ./.weft/weft.db, plus any Studio the environment names agt := weft.New(model, weft.Instructions("Answer in one sentence.")) res, err := agt.Generate(ctx, weft.Prompt("What is a goroutine?")) if err != nil { return "", err } return res.Text(), nil } func main() { // Reads $ANTHROPIC_API_KEY. text, err := run(context.Background(), anthropic.Model("claude-sonnet-5")) if err != nil { log.Fatal(err) } fmt.Println(text) } ``` [install/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/install/main.go) ```sh export ANTHROPIC_API_KEY=… # your key go mod tidy go run . go test ./... ``` The page's test runs the same `run` function on a scripted model and reads the recorded run back from the local database ([`install/main_test.go`](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/install/main_test.go)). ### Best practices & gotchas - **Run `go mod tidy` after adding an adapter import.** `go get github.com/weftgo/weft` does not record the vendor SDK's checksums; until `go mod tidy` runs, the build fails with `missing go.sum entry`. (Source: observed with `go run .` in a fresh module) - **Do not mix the retired per-layer modules with 0.9.0 or later.** Before 0.9.0 each layer (`thread`, `otel`, …) was its own module. A `go.mod` that requires one of those paths and the framework fails with an ambiguous-import error; `MIGRATION-0.9.md` in the weft repository is the fix. (Source: ADR 0027, Consequences) - **Keep test suites off the network.** Set `WEFT_MODEL_REQUESTS=deny` and every first-party adapter that built its own client refuses to call its provider, failing with `ErrModelRequestsDenied`. (Source: AGENTS.md; `install/main_test.go:TestAnthropicDenied`) ### See also - [What is weft, and when should you not use it?](https://weftgo.dev/docs/get-started/what-is-weft/) - [How weft is put together](https://weftgo.dev/docs/explanation/architecture/) - [Connect a model provider: OpenAI, Anthropic, Gemini](https://weftgo.dev/docs/guides/providers/) - [Use the weft command](https://weftgo.dev/docs/observe/cli/) - [Upgrade weft](https://weftgo.dev/docs/production/upgrading/) Symbols used: [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.Agent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Agent) · [`core.Agent`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`weft.ErrModelRequestsDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRequestsDenied) · [`anthropic.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Model) · [`anthropic.APIKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#APIKey) · [`openai.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Model) · [`google.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Model) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) --- # weft concepts URL: https://weftgo.dev/docs/concepts/ Markdown: https://weftgo.dev/docs/concepts.md > The ideas the rest of weft builds on — agents, runs, tools, the loop, messages, models, errors and stopping — in the order to learn them. These pages explain what weft's core pieces are and how they behave, one idea per page. Read them in order: each one uses only the ideas of the pages before it. The how-to guides apply them; the [reference](https://weftgo.dev/docs/reference/) holds the tables. 1. [What is an agent in weft?](https://weftgo.dev/docs/concepts/agents/) — an agent is an immutable value: a model, instructions, tools and policy, built once with `weft.New` and run concurrently. 2. [What does a run return?](https://weftgo.dev/docs/concepts/runs/) — `Generate` returns a `RunResult`: the run's id, the transcript, one record per step, the usage. 3. [How do tools work?](https://weftgo.dev/docs/concepts/tools/) — a tool is a Go function; its input struct's tags are the schema the model sees. 4. [What happens in one step?](https://weftgo.dev/docs/concepts/the-loop/) — one model call, then one batch of tool calls that start in call order, run in parallel and land in call order. 5. [Messages, parts and the transcript](https://weftgo.dev/docs/concepts/messages/) — a message is a role plus typed parts; transcripts round-trip through JSON and `weft.Repair` keeps them valid. 6. [What is a Model?](https://weftgo.dev/docs/concepts/models/) — the provider seam: one `Stream` method and a contract the loop enforces. 7. [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/) — a failed tool call is a result the model reads; a failed run is a `*RunError` you handle. 8. [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/) — the intended end succeeds; a budget or a cancellation fails the run with a named error. Two ideas build on these and have their own sections: approval as a run boundary ([Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/)) and durable conversations ([What is a session?](https://weftgo.dev/docs/sessions/overview/)). Why the core is shaped this way is in [Explanation](https://weftgo.dev/docs/explanation/). ### See also - [Quickstart: run an agent in five minutes](https://weftgo.dev/docs/get-started/quickstart/) - [The agent loop, from first principles](https://weftgo.dev/docs/explanation/agent-loop/) - [Glossary](https://weftgo.dev/docs/reference/glossary/) - [Package weft on pkg.go.dev](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2) --- # What is an agent in weft? URL: https://weftgo.dev/docs/concepts/agents/ Markdown: https://weftgo.dev/docs/concepts/agents.md > A weft.Agent is an immutable value — a model, instructions, tools and policy — that weft.New builds once and every run reuses, concurrently. An agent in weft is a [`weft.Agent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Agent): an immutable value that holds a model, a system instruction, a tool set and an execution policy. You build it once with [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) and run it as many times as you need, from as many goroutines as you need; the [runs](https://weftgo.dev/docs/reference/glossary/#run) share no state. The support agent in `concepts/agents.go` is a name, an instruction and a plugin that brings its tools: ```go title="concepts/agents.go" // Orders is a plugin: the order tools and their policy, closed over the // store they need, returned as one weft.Option. func Orders(store *OrderStore) weft.Option { return weft.Options( weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in OrderLookup) (string, error) { return "order " + in.OrderID + ": " + store.Status[in.OrderID], nil }), weft.MaxResultBytes(4096), ) } func newSupportAgent(model weft.Model, store *OrderStore) *weft.Agent { return weft.New(model, weft.Name("support-bot"), weft.Instructions("You are a support agent."), Orders(store), ) } ``` [concepts/agents.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/agents.go) Every argument after the model is a [`weft.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Option). `Orders(store)` is one option that carries a tool and a policy. The `weft.MaxResultBytes(4096)` inside it is an agent option, so it caps every tool on the agent, not only `lookup_order`; passed to `weft.Tool` instead, it would cap that tool alone. The next sections explain each part. ### How it works `weft.New` applies its options in order to a fresh `Agent`, then freezes it: the tool set is deep-copied, the [`WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) chain is built, and nothing about the value changes again. Running it is a separate call, `agt.Generate` or `agt.Stream`, covered in [What does a run return?](https://weftgo.dev/docs/concepts/runs/). ### An agent is a value `weft.New(m, opts...)` takes any [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model): a provider adapter (`weft/openai`, `weft/anthropic`, `weft/google`) or a test double such as [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script). A nil model panics, including a typed nil such as `var m *myModel`. Every other setting has a working default: | Setting | Default | Option | |---|---|---| | Steps per run | 10 | [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) | | Tool calls executing at once | 4 | [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) | | `RETRY` results per tool since its last success | 3 | [`weft.MaxModelRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries) | | One tool result's size | 64 KiB | [`weft.MaxResultBytes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxResultBytes) | `Option` is a sealed interface: you get options from weft's constructors, never by implementing one. Tools are options too. [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) returns a `*weft.ToolDef`, and passing it to `New` registers a deep copy of it. A second tool with the same name, or a nil `*ToolDef`, panics at `New`. Because the value never changes, one agent serves concurrent runs. This loop runs three questions at once on the same `agt`: ```go title="concepts/agents.go" answers := make([]string, len(questions)) errs := make([]error, len(questions)) var wg sync.WaitGroup for i, q := range questions { wg.Go(func() { // one agent value, many runs at once: runs share no state res, err := agt.Generate(ctx, weft.Prompt(q)) if err != nil { errs[i] = err return } answers[i] = res.Text() }) } wg.Wait() ``` [concepts/agents.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/agents.go) Each run gets its own transcript, step count and usage. A conversation's history lives in the messages you pass to the next run, never in the agent: see [Continue a conversation](https://weftgo.dev/docs/guides/conversations/). ### Name and instructions [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) names the agent. The name appears on every run's `RunStart.Agent` event and in the manifest; [`weft.Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Manifest) returns an error for an unnamed agent. An empty name is ignored. A named agent's runs also carry a hash of its manifest, so a recorded run says which version of the agent ran. [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) sets the system prompt. There is no system role in a weft transcript: the instruction is agent configuration and reaches the model on each request's `ModelRequest.System`, followed by the `PromptSnippet` text of the tools that step advertises. Passed to `Generate` instead of `New`, `weft.Instructions` replaces the prompt for that one run; the manifest keeps reporting the agent's own. [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/) covers every option that works at both levels. ### Compose options [`weft.Options`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Options) composes several options into one, applied in order. That is how you package a family of tools with its policy: a **plugin** is a function `func(deps) weft.Option`, like `Orders(store)` above. Its dependencies are parameters, never globals. Nothing registers itself, so there is no registry, no scope and no deduplication: - Nil entries are ignored. - A tool name that appears twice still panics at `New`, wherever the two tools came from. - An `Options` value may hold other `Options` values; nesting composes. [`weft.ToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOptions) is the per-tool counterpart: a named bundle of `Timeout`, `MaxResultBytes` and similar options for one tool. [Set per-tool policy](https://weftgo.dev/docs/guides/tool-policy/) shows it. The package example [`ExampleOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Options) is the same plugin shape. ### Read an agent's configuration The agent reports its configuration through accessors, so code that receives an `*Agent` can inspect it without the options it was built from: ```go title="concepts/agents.go" temp := 0.2 agt := weft.New(model, weft.Name("support-bot"), weft.Thinking(weft.ThinkingConfig{Level: weft.ThinkLow}), weft.Params(weft.RequestParams{Temperature: &temp}), Orders(store), ) fmt.Fprintln(w, "name:", agt.Name()) fmt.Fprintln(w, "model:", weft.InfoOf(agt.Model())) for _, t := range agt.Tools() { fmt.Fprintln(w, "tool:", t.Name) } fmt.Fprintln(w, "thinking low:", agt.Thinking().Level == weft.ThinkLow) fmt.Fprintln(w, "tool choice auto:", agt.ToolChoice().Mode == weft.ToolChoiceAuto) p := agt.Params() // a copy: changing it does not reach the agent *p.Temperature = 0.9 fmt.Fprintln(w, "temperature:", *agt.Params().Temperature) ``` [concepts/agents.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/agents.go) | Accessor | Returns | |---|---| | [`agt.Name()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Name) | The `Name` option's value; empty when unnamed. | | [`agt.Model()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Model) | The model as the loop calls it: the model `New` was given, wrapped by the `WrapModel` middleware, outermost first. `weft/thread` summarizes with it. | | [`agt.Tools()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Tools) | Copies of the registered tools in registration order. Changing a copy does not reach the agent. | | [`agt.Params()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Params) | The default sampling knobs, as a copy with fresh pointers; the zero value leaves every knob to the adapter. | | [`agt.Thinking()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Thinking) | The default reasoning level; the zero value, `ThinkUnset`, keeps the provider default. | | [`agt.ToolChoice()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.ToolChoice) | The default tool choice; the zero value is `ToolChoiceAuto`. | The core package's examples [`ExampleAgent_Model`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Agent.Model), [`ExampleAgent_Params`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Agent.Params), [`ExampleAgent_Thinking`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Agent.Thinking) and [`ExampleAgent_ToolChoice`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Agent.ToolChoice) pin each accessor. Walking `agt.Model()` through its middleware with `weft.Unwrap` is shown on [What is a Model?](https://weftgo.dev/docs/concepts/models/#unwrap). ### What it does not do - **An agent holds no conversation.** Every run starts from the messages you give it; the agent remembers nothing between runs. Durable multi-turn state is [`weft/thread`](https://weftgo.dev/docs/sessions/overview/). - **An agent cannot be reconfigured after `New`.** There is no setter, and middleware cannot be added to the model chain later. Per-run changes are run options, which leave the agent untouched. - **`agt.Tools()` reports the static tool set.** Tools a [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) supplies at run time are not in it, nor in the manifest: both describe the code, not a live registry. ### Complete example `concepts/agents.go` builds the support agent once, runs it for three questions at once, and reads its configuration back: ```go title="concepts/agents.go" package main import ( "context" "fmt" "io" "sync" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // OrderStore is the dependency the Orders plugin closes over. type OrderStore struct { Status map[string]string } // OrderLookup is the lookup_order tool's input. type OrderLookup struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } // Orders is a plugin: the order tools and their policy, closed over the // store they need, returned as one weft.Option. func Orders(store *OrderStore) weft.Option { return weft.Options( weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in OrderLookup) (string, error) { return "order " + in.OrderID + ": " + store.Status[in.OrderID], nil }), weft.MaxResultBytes(4096), ) } func newSupportAgent(model weft.Model, store *OrderStore) *weft.Agent { return weft.New(model, weft.Name("support-bot"), weft.Instructions("You are a support agent."), Orders(store), ) } // askConcurrently runs one agent value for several questions at once and // returns the answers in question order. func askConcurrently(ctx context.Context, agt *weft.Agent, questions []string) ([]string, error) { answers := make([]string, len(questions)) errs := make([]error, len(questions)) var wg sync.WaitGroup for i, q := range questions { wg.Go(func() { // one agent value, many runs at once: runs share no state res, err := agt.Generate(ctx, weft.Prompt(q)) if err != nil { errs[i] = err return } answers[i] = res.Text() }) } wg.Wait() for _, err := range errs { if err != nil { return nil, err } } return answers, nil } // describeAgent prints what an agent value reports about its own // configuration. func describeAgent(w io.Writer, model weft.Model, store *OrderStore) { temp := 0.2 agt := weft.New(model, weft.Name("support-bot"), weft.Thinking(weft.ThinkingConfig{Level: weft.ThinkLow}), weft.Params(weft.RequestParams{Temperature: &temp}), Orders(store), ) fmt.Fprintln(w, "name:", agt.Name()) fmt.Fprintln(w, "model:", weft.InfoOf(agt.Model())) for _, t := range agt.Tools() { fmt.Fprintln(w, "tool:", t.Name) } fmt.Fprintln(w, "thinking low:", agt.Thinking().Level == weft.ThinkLow) fmt.Fprintln(w, "tool choice auto:", agt.ToolChoice().Mode == weft.ToolChoiceAuto) p := agt.Params() // a copy: changing it does not reach the agent *p.Temperature = 0.9 fmt.Fprintln(w, "temperature:", *agt.Params().Temperature) } // demoAgents builds the support agent once, runs it for three questions at // once, and reads its configuration back. func demoAgents(ctx context.Context, w io.Writer) error { store := &OrderStore{Status: map[string]string{"1234": "shipped"}} model := wefttest.Script( wefttest.Say("Your order has shipped."), wefttest.Say("Your order has shipped."), wefttest.Say("Your order has shipped."), ) agt := newSupportAgent(model, store) answers, err := askConcurrently(ctx, agt, []string{ "Where is order 1234?", "Has order 1234 left?", "Is order 1234 on its way?", }) if err != nil { return err } for _, a := range answers { fmt.Fprintln(w, "answer:", a) } describeAgent(w, wefttest.Script(), store) return nil } ``` [concepts/agents.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/agents.go) Run it from `docs-site/examples`: ```sh go run ./concepts agents go test ./concepts ``` ```text answer: Your order has shipped. answer: Your order has shipped. answer: Your order has shipped. name: support-bot model: {wefttest script} tool: lookup_order thinking low: true tool choice auto: true temperature: 0.2 ``` ### Best practices & gotchas - **Build the agent once, at startup.** `New` computes the manifest hash and builds the model chain once, and every run reuses them; building an agent per request repeats that work. (Source: `weft/core/agent.go:747-760`) - **Pass dependencies into plugins as parameters.** A plugin that reads a global cannot be tested with a second store, and nothing in weft registers plugins for you. (Source: `weft/core/agent.go:49-55`, `ExampleOptions`) - **Expect a panic, not an error, for a construction mistake.** A nil model, a nil tool and a duplicate tool name all panic at `New`, so a wrong agent never starts. (Source: `weft/core/agent.go:678-684`, `weft/core/tool.go:481-497`) - **Start a per-run `Params` override from `agt.Params()`.** A run-level `weft.Params` replaces the agent's struct whole, so a run that sets only `Temperature` loses the agent's `MaxTokens`. (Source: `weft/core/agent.go:384-399`, `ExampleAgent_Params`) ### See also - [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/) - [What does a run return?](https://weftgo.dev/docs/concepts/runs/) - [How do tools work?](https://weftgo.dev/docs/concepts/tools/) - [Describe your agents in weft.json (the manifest)](https://weftgo.dev/docs/guides/manifest/) - [Glossary: run](https://weftgo.dev/docs/reference/glossary/#run) Symbols used: [`weft.Agent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Agent) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Option) · [`weft.Options`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Options) · [`weft.ToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOptions) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.MaxResultBytes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxResultBytes) · [`weft.Thinking`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Thinking) · [`weft.Params`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Params) · [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) · [`weft.Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Manifest) · [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # What does a run return? URL: https://weftgo.dev/docs/concepts/runs/ Markdown: https://weftgo.dev/docs/concepts/runs.md > A run is one Generate or Stream call; it returns a RunResult with the run's id, the full transcript, one StepRecord per model call and the summed Usage. A run is one execution of an agent: [`agt.Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) calls the model and the tools until the run ends, then returns a [`*weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult). The result holds the run's id, the full transcript, one [`weft.StepRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepRecord) per model call, and the summed [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage). `concepts/runs.go` runs a one-tool agent and prints what the result holds: ```go title="concepts/runs.go" res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return nil, err } fmt.Fprintln(w, "id length:", len(res.ID)) fmt.Fprintln(w, "text:", res.Text()) fmt.Fprintln(w, "steps:", res.NumSteps(), "last stop reason:", res.StopReason) fmt.Fprintln(w, "messages:", len(res.Messages)) fmt.Fprintln(w, "usage:", res.Usage.InputTokens, "in,", res.Usage.OutputTokens, "out") fmt.Fprintln(w, "pending:", len(res.Pending)) ``` [concepts/runs.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/runs.go) ```text id length: 32 text: Order 1234 has shipped. steps: 2 last stop reason: stop messages: 4 usage: 20 in, 10 out pending: 0 ``` Two [steps](https://weftgo.dev/docs/reference/glossary/#step): the model asked for `lookup_order`, then answered. Four messages: the prompt, the assistant's tool call, the tool result, the answer. ### How it works A run starts with a `RunStart` event, makes one model call per step, and ends either successfully, with a `RunFinish` event, or with an error. Every run has an id, fixed before it executes. What happens inside one step is on [What happens in one step?](https://weftgo.dev/docs/concepts/the-loop/); how a run decides to end is on [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/). ### Generate `agt.Generate(ctx, opts...)` runs the agent to completion and returns `(*RunResult, error)`. Its options are [`weft.RunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunOption) values: they configure this run alone and are applied in the order given. - [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) adds a user message to the run's input. - [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) adds existing messages: an earlier transcript, few-shot examples. `weft.Messages(res.Messages...)` followed by `weft.Prompt(...)` continues a conversation. - [`weft.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunID) sets the run's id instead of generating one, for replays, idempotent retries, or an id from an outer system; an empty value is ignored, and a generated id is 128 random bits as 32 hex characters. For an idempotent retry, keep the outer system's key stable across attempts, not the run id. A recorded run needs a fresh id for each attempt ([gotcha](https://weftgo.dev/docs/concepts/runs/#best-practices--gotchas)). `Generate` is [`agt.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) with the events folded away. `Stream` returns a [`*weft.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Run), a handle that does nothing until you consume it. Its id is fixed when `Stream` returns, so [`run.ID()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.ID) can go into a log line or a response header before the first event: ```go title="concepts/runs.go" run := agt.Stream(ctx, weft.RunID("order-1234-attempt-1"), weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, "id before the run starts:", run.ID()) res, err := run.Wait() // runs to the end, discarding the events if err != nil { return err } fmt.Fprintln(w, "result id:", res.ID) ``` [concepts/runs.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/runs.go) `run.Wait()` runs the agent itself when nobody ranges over `run.Events()`, discarding the events; [Stream a run's events](https://weftgo.dev/docs/guides/streaming/) covers the event side. The package example [`ExampleAgent_generate`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#pkg-examples) is the same call in its shortest form. Some options exist at both levels. `weft.Instructions`, `weft.MaxSteps`, `weft.Parallelism`, `weft.Thinking`, `weft.ToolChoice` and `weft.Params` are accepted by `New` as the agent's default and by `Generate` as a one-run override. A run may only lower `MaxSteps` and `Parallelism`: a raise fails the run with `ErrInvalidRunOption` before any model call. A one-run override stays with the run it was given to: a `weft.Subagent` child runs on its own agent's defaults, and only context-carried state such as `weft.Metadata` reaches it ([what reaches the child run](https://weftgo.dev/docs/guides/subagents/#what-reaches-the-child-run)). [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/) lists them all. ### The result | Field or method | What it holds | |---|---| | [`res.ID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) | The run's id: the `RunID` option's value, else a generated one. | | `res.Messages` | The full transcript, the input messages included, as the loop repaired and extended it. Feed it back with `weft.Messages` to continue. | | `res.Steps` | One `StepRecord` per model call, in order. | | `res.Usage` | Token usage summed over every step, subagent runs included. | | `res.StopReason` | The last step's finish reason. `StopMaxTokens` here means the final reply was cut off; the run still succeeds and the caller decides what the truncated text means. | | `res.Pending` | Tool calls of the last step waiting for an approval decision. The run ended successfully without running them, and the transcript has no result for them. See [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/). | | [`res.NumSteps()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RunResult.NumSteps) | How many model calls the run made: `len(res.Steps)`. | | [`res.Text()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RunResult.Text) | The text parts of the last assistant message: the answer when the run ended on a text reply. After a `StopWhen(HasToolCall(...))` stop it is only the text the model wrote beside the call, often `""`; the answer is the call's arguments, on the last step's `ToolCalls`. | ### Steps A [`StepRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepRecord) captures what one model call produced and what its tool calls returned: | Field | What it holds | |---|---| | `Index` | The step's zero-based number. | | `StopReason` | Why the model call ended, mapped to `stop`, `tool_calls` or `max_tokens`. | | `RawStopReason` | The provider's own reason when the mapping was approximate (`refusal`, `content_filter`, …); empty when it was exact. | | `Usage` | This step's own model call only. | | `Text` | The assistant text the step streamed. | | `ToolCalls` | The calls the model requested, as [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) values. | | `Results` | Their results, in call order, as [`weft.ToolResultPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolResultPart) values. | | `SubagentUsage` | The usage of each child run the step started, keyed by the parent's call id, a failed child's partial usage included. Nil when the step ran no subagent. | Calls an approval resumed run before the first step and belong to no step, so they have no `StepRecord`. ### Usage A [`Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage) counts tokens for one step or one run. `InputTokens` and `OutputTokens` are inclusive totals; the other three fields are subsets of them, reported when the provider gives them: | Field | Subset of | Counts | |---|---|---| | `InputTokens` | — | Every token billed as input. | | `OutputTokens` | — | Every token billed as output. | | `CachedInputTokens` | `InputTokens` | Input read from a provider prompt cache. | | `CacheWriteTokens` | `InputTokens` | Input written to a prompt cache (Anthropic). | | `ReasoningTokens` | `OutputTokens` | Output the model spent on provider-side reasoning. | All three adapters fill the splits. They are reporting, not budget bases: [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) and [`Usage.Total`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Usage.Total) read the two totals, so a run served from cache budgets the same as one that was not. `Total()` returns input plus output; [`Usage.Add`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Usage.Add) returns the element-wise sum. The steps' own usage adds up to the run's when no subagent ran: ```go title="concepts/runs.go" var sum weft.Usage for _, st := range res.Steps { fmt.Fprintf(w, "step %d: %s, %d call(s), %d result(s), %d tokens\n", st.Index, st.StopReason, len(st.ToolCalls), len(st.Results), st.Usage.Total()) sum = sum.Add(st.Usage) } fmt.Fprintln(w, "sum of steps:", sum.Total(), "run total:", res.Usage.Total()) ``` [concepts/runs.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/runs.go) ```text step 0: tool_calls, 1 call(s), 1 result(s), 15 tokens step 1: stop, 0 call(s), 0 result(s), 15 tokens sum of steps: 30 run total: 30 ``` With a [subagent](https://weftgo.dev/docs/reference/glossary/#subagent), `res.Usage` is larger than the sum of the steps' own `Usage`: the child runs' usage is in `res.Usage` and in each step's `SubagentUsage`, never in the step's own `Usage`. ### Run results A run ends one of two ways, and the return values say which: - **Success:** `res` is the result and `err` is nil. The run's last event was `RunFinish`. - **Failure:** `res` is nil and `err` is a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError). Its `Result` field holds the partial transcript, steps and usage up to the failure. See [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/#run-errors). The terminal `RunFinish` decides the outcome. A run that delivered `RunFinish` returns success; a cancellation that lands between the loop's last context check and that event fails the run with the cancellation error instead, the resumable result on the `RunError`. A run never returns success without its `RunFinish`, and never delivers `RunFinish` and then fails. ### Complete example `concepts/runs.go` runs the agent, reads the result and its steps, and starts a run with an id the caller chose: ```go title="concepts/runs.go" package main import ( "context" "fmt" "io" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // runOrderAgent builds a one-tool agent over model: lookup_order answers // "shipped" for any order. func runOrderAgent(model weft.Model) *weft.Agent { return weft.New(model, weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in OrderLookup) (string, error) { return "order " + in.OrderID + ": shipped", nil }), ) } // orderScript plays two model turns: call lookup_order, then answer. func orderScript() *wefttest.Model { return wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), ) } // readResult runs the agent once and prints what the RunResult holds. func readResult(ctx context.Context, w io.Writer, agt *weft.Agent) (*weft.RunResult, error) { res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return nil, err } fmt.Fprintln(w, "id length:", len(res.ID)) fmt.Fprintln(w, "text:", res.Text()) fmt.Fprintln(w, "steps:", res.NumSteps(), "last stop reason:", res.StopReason) fmt.Fprintln(w, "messages:", len(res.Messages)) fmt.Fprintln(w, "usage:", res.Usage.InputTokens, "in,", res.Usage.OutputTokens, "out") fmt.Fprintln(w, "pending:", len(res.Pending)) return res, nil } // readSteps prints one line per step and checks the steps add up to the // run's usage. func readSteps(w io.Writer, res *weft.RunResult) { var sum weft.Usage for _, st := range res.Steps { fmt.Fprintf(w, "step %d: %s, %d call(s), %d result(s), %d tokens\n", st.Index, st.StopReason, len(st.ToolCalls), len(st.Results), st.Usage.Total()) sum = sum.Add(st.Usage) } fmt.Fprintln(w, "sum of steps:", sum.Total(), "run total:", res.Usage.Total()) } // namedRun starts a run with an id the caller chose and reads the id // before the run executes. func namedRun(ctx context.Context, w io.Writer, agt *weft.Agent) error { run := agt.Stream(ctx, weft.RunID("order-1234-attempt-1"), weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, "id before the run starts:", run.ID()) res, err := run.Wait() // runs to the end, discarding the events if err != nil { return err } fmt.Fprintln(w, "result id:", res.ID) return nil } // demoRuns runs the order agent and reads its result, its steps, and a // run whose id the caller set. func demoRuns(ctx context.Context, w io.Writer) error { res, err := readResult(ctx, w, runOrderAgent(orderScript())) if err != nil { return err } readSteps(w, res) return namedRun(ctx, w, runOrderAgent(orderScript())) } ``` [concepts/runs.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/runs.go) Run it from `docs-site/examples`: ```sh go run ./concepts runs go test ./concepts ``` ```text id length: 32 text: Order 1234 has shipped. steps: 2 last stop reason: stop messages: 4 usage: 20 in, 10 out pending: 0 step 0: tool_calls, 1 call(s), 1 result(s), 15 tokens step 1: stop, 0 call(s), 0 result(s), 15 tokens sum of steps: 30 run total: 30 id before the run starts: order-1234-attempt-1 result id: order-1234-attempt-1 ``` ### Best practices & gotchas - **Read a failed run's work from the error, not from `res`.** `Generate` returns a nil result with a `*RunError`; the partial transcript is on `RunError.Result`. (Source: `weft/core/loop.go:264-274`, AGENTS.md rule 1) - **Check `res.Pending` after every successful run that has approval-gated tools.** A parked call ends the run successfully, so `err == nil` does not mean every call ran. (Source: `weft/core/run.go:701-706`, AGENTS.md rule 12) - **Check `res.StopReason` before trusting the answer.** `StopMaxTokens` on a successful run means the final text was cut off. (Source: `weft/core/run.go:693-697`, AGENTS.md rule 8) - **Read a final-answer tool's answer from the last step, not from `res.Text()`.** A run that `StopWhen(HasToolCall("submit_answer"))` ended has the call's message as its last assistant message and the tool message after it, so `res.Text()` is `""` unless the model also wrote text. Read `res.Steps[len(res.Steps)-1].ToolCalls` (the arguments) or `.Results` (what the handler returned), or use `weft.Output[T]` with `weft.GenerateAs`. (Source: `weft/core/run.go:714-721`, `weft/core/agent.go:577-588`; scratch proof in `sources`) - **Budget on `res.Usage`, not on the steps.** Only `res.Usage` includes subagent runs. (Source: `weft/core/run.go:682-686`) - **Give every attempt its own `weft.RunID`, and correlate attempts with `weft.Metadata`.** Under a reused id, the store keeps the first run's events and transcript and drops the later run's, its subagent children (`//`) included. The later run's spans and metadata are still added, so the run row and the span and trace views blend both runs. Use ids like `order-1234-attempt-2`, with `weft.Metadata(map[string]string{"request_key": "order-1234"})` on each attempt. (Source: `weft/core/run.go:225-232`; `weft/obsdb/db.go:27-28`; `weft/obsdb/sqlite/write.go:19-21`; `weft/core/subagent.go:166-174`; scratch proof in `sources`) ### See also - [Stream a run's events](https://weftgo.dev/docs/guides/streaming/) - [Continue a conversation](https://weftgo.dev/docs/guides/conversations/) - [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/) - [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/) - [Event types](https://weftgo.dev/docs/reference/events/) Symbols used: [`Agent.Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) · [`Agent.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) · [`weft.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Run) · [`Run.ID`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.ID) · [`Run.Wait`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Wait) · [`weft.RunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunOption) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`weft.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunID) · [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) · [`weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) · [`weft.StepRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepRecord) · [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # How do tools work? URL: https://weftgo.dev/docs/concepts/tools/ Markdown: https://weftgo.dev/docs/concepts/tools.md > weft.Tool turns a Go function into a tool: the input struct's tags become its JSON Schema, and the return value becomes the result the model sees. [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) turns a Go function into a tool the model can call. The input struct's `json` and `jsonschema` tags become the tool's JSON Schema; the function's return value becomes the result the model sees, a string as it is and anything else as JSON. Two tools in `concepts/tools.go` take the same input and return different types: ```go title="concepts/tools.go" status = weft.Tool("order_status", "Report an order's status in words.", func(ctx context.Context, in OrderQuery) (string, error) { return "order " + in.OrderID + " has shipped", nil // a string is sent verbatim }) lookup = weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in OrderQuery) (Order, error) { return Order{ID: in.OrderID, Status: "shipped"}, nil // anything else is sent as JSON }) ``` [concepts/tools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/tools.go) The model reads `order 1234 has shipped` from the first and `{"id":"1234","status":"shipped"}` from the second. ### How it works A tool is a [`*weft.ToolDef`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolDef). Each step, the loop advertises the agent's tools to the model by name, description and input schema. When the model calls one, the loop decodes the call's JSON arguments into the input struct, runs the handler with a context that identifies the call, and puts the rendered result on the step's tool message. A failure in decoding or running a call is a result too, not a run error: see [Tool errors are data](https://weftgo.dev/docs/concepts/errors/). The exceptions are malformed calls and tool sets: an empty or repeated call id or an empty tool name fails the run with `ErrModelContract` (see the edge cases below), and a `ToolSource` snapshot with a nil tool or a duplicate name fails it with `ErrNilTool` or `ErrDuplicateTool`. ### Define a tool `weft.Tool(name, description, fn, opts...)` infers its two type parameters from `fn`'s signature, `func(ctx context.Context, in In) (Out, error)`, so the compiler checks the handler's shape and nothing is written twice. The shape mirrors the official Go MCP SDK's `AddTool[In, Out]`, so a weft tool can be served over MCP without an adapter layer ([Use MCP both ways](https://weftgo.dev/docs/guides/mcp/)). What the model sees as the result depends on `Out`: - **A `string`** is sent verbatim. The tool has no output schema. - **Any other type** is sent as its `json.Marshal` encoding, and the tool's `OutputSchema` is reflected from that type. The model never sees `OutputSchema`: no first-party provider adapter sends it, and the request record's tool catalog (and its hash) covers the name, description and input schema only. Two readers outside the loop use it. [`weft.Manifest`](https://weftgo.dev/docs/guides/manifest/) writes it as the tool's `output_schema` in `weft.json`. [`mcp.AddTools` and `mcp.Serve`](https://weftgo.dev/docs/guides/mcp/#serve-an-agent) list it as the MCP tool's `outputSchema` and return the result's JSON as `structuredContent` too; a result that is not JSON is then an `isError` result. In the other direction, `mcp.Tools` records an object output schema the server sends. `In` must be a struct or a pointer to one, because providers and MCP require an object at the top of a tool schema. An empty name, a nil function or a non-struct input panics when `Tool` is called. The [`ToolDef`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolDef) it returns has four exported fields: `Name`, `Description`, `InputSchema` and `OutputSchema`. A `ToolDef` can be changed until it is registered. Tools are options: passing one to `weft.New` registers a deep copy, so later changes to your value never reach the agent. Options after the handler set that tool's policy: `weft.Timeout`, `weft.MaxResultBytes`, `weft.StrictInput`, `weft.Sequential`, `weft.RequireApproval` and more, covered in [Set per-tool policy](https://weftgo.dev/docs/guides/tool-policy/). [`weft.ToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOptions) composes several of them into one named value, applied in order, with nil entries ignored. [`toolDef.Invoke(ctx, args)`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.Invoke) runs a tool directly with raw JSON arguments: it decodes them into the input type, calls the handler and returns the text the model would see. A decode failure returns an error wrapping `ErrInvalidToolInput`. `Invoke` applies the tool's own `StrictInput` setting; timeouts and result caps are run policy, applied only by the loop. The package example [`ExampleTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Tool) prints a derived schema. Tools defined outside Go source, with an explicit schema, use `weft.RawTool`: see [Define tools at runtime](https://weftgo.dev/docs/guides/dynamic-tools/). ### The schema A [`weft.Schema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Schema) is the subset of JSON Schema (draft 2020-12) weft derives from an input struct. Its shape tracks what the Go MCP SDK derives through Google's `jsonschema-go`, so tools cross to MCP without conversion. Its fields are `Type`, `Format`, `Description`, `Properties`, `AdditionalProperties`, `Required` and `Items`. The derivation, field by field: - The `json` tag names the property; a field tagged `"-"` is skipped; an untagged field uses its Go name. - The `jsonschema` tag is the property's description. - A field is required unless it is a pointer or tagged `omitempty`. - The `,string` tag option types a scalar field as `string`, its quoted wire form. Types map like this: | Go type | Schema | |---|---| | `string`, `[]byte` | `string` | | `bool` | `boolean` | | any integer type | `integer` | | `float32`, `float64` | `number` | | slice, array | `array`, with `Items` | | `map[K]V` | `object`, with `AdditionalProperties` typing the values; `map[string]any` stays a bare `object` | | struct | `object`, with `Properties` and `Required` | | `time.Time` | `string` with `format: date-time` | | pointer | the pointed-to type's schema; the field becomes optional | | interface, func, chan | unconstrained (an empty schema) | The `RefundRequest` struct in `concepts/tools.go` uses most of these: ```go title="concepts/tools.go" refund := weft.Tool("refund_order", "Refund an order.", func(ctx context.Context, in RefundRequest) (string, error) { return "refunded", nil }) b, err := json.MarshalIndent(refund.InputSchema, "", " ") if err != nil { return err } fmt.Fprintln(w, string(b)) ``` [concepts/tools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/tools.go) ```text { "type": "object", "properties": { "credits": { "type": "object", "additionalProperties": { "type": "integer" } }, "lines": { "type": "array", "description": "line numbers to refund; all when empty", "items": { "type": "integer" } }, "order_id": { "type": "string", "description": "the order to refund" }, "reason": { "type": "string", "description": "why the customer wants a refund" } }, "required": [ "order_id" ] } ``` `reason` is a `*string`, so it is optional without `omitempty`. `credits` is a `map[string]int`, so its values are typed. The OpenAI and Anthropic adapters send `additionalProperties`; the Google adapter drops it, because Gemini's schema subset has no such field. The boolean form `additionalProperties: false` cannot be expressed. [`Schema.MarshalJSON`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Schema.MarshalJSON) emits a schema that came from [`weft.ParseSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParseSchema) (an MCP server's input schema, a plugin manifest) byte for byte, so keywords the struct cannot hold, such as `enum` or `oneOf`, still reach the model on the openai and anthropic adapters. The google adapter drops every keyword Gemini's schema type lacks, `oneOf` and `$ref` among them; [Use MCP both ways](https://weftgo.dev/docs/guides/mcp/#import-tools) has the table of what it keeps. A reflected schema marshals as the plain struct. ### Edge cases in schemas and arguments The derivation follows `encoding/json`, so the schema never advertises a field the decoder will not fill: - **Embedded structs** contribute their fields to the enclosing object with `encoding/json`'s dominance rules. A name claimed at a shallower embedding depth wins over a deeper one. At equal depth, exactly one `json`-tagged claim wins over untagged ones; any other tie cancels the name, which `encoding/json` also drops. - **Two fields of one struct claiming one JSON name** panic when the tool is built, at any named nesting depth: one of them could never receive a value. Inside an embedded struct the same collision drops the name instead, as `encoding/json` does. - **An embedded pointer to an unexported struct type** panics: `encoding/json` cannot decode into it, so its fields would be advertised and unreachable. - **Recursive types** are cut at the recursion: the nested occurrence is an unconstrained value. - **`time.Duration`** is an integer counting nanoseconds, as `encoding/json` encodes it. Prefer a string field for durations a model writes. The loop is as strict with what the model sends: - **Arguments must be exactly one JSON value.** Trailing data after the arguments object (`{"a":1} {"a":2}`) is an `INVALID_INPUT` result, with or without `StrictInput`. Empty or `null` arguments decode as `{}`. - **A tool-call id repeated within one step fails the run** with `ErrModelContract`, like an empty id: results and approval decisions key on the id. Ids may repeat across steps. - **A required field may be absent.** The loop checks types, not presence: nothing compares the arguments with the schema's `required` list, and no adapter asks the provider to enforce the schema. A field the model leaves out decodes to its zero value (`""`, `0`, `false`, `nil`), and the handler runs. `StrictInput` does not change this: it refuses fields the struct does not declare, never missing ones. Where absent and zero mean different things, as with a refund `amount` or a `bool` decision, make the field a pointer and check it in the handler. Return [`weft.ModelRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRetry) so the model repairs the call. The model reads `RETRY: amount is required` and calls again; the retries count against `MaxModelRetries`. A pointer field is also optional in the schema, so say in its `jsonschema` description that the model must send it. `weft.Output[T]`'s `submit_output` decodes the same way: see [Get structured output](https://weftgo.dev/docs/guides/structured-output/#how-it-works). ### The call context Inside a handler, [`weft.CallFromContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) reports which call is running, as a [`weft.Call`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Call): | Field | What it holds | |---|---| | `RunID` | The run the call belongs to. | | `Step` | The zero-based index of the step that requested it. | | `CallID` | The provider's call identifier. | | `Name` | The tool name. | | `Approved` | True when the call was parked at the approval boundary and now runs under an `Approve` decision. | Use it for audit lines, progress that must name its call, or the call's part of an idempotency key. The call id alone is not a key: a later turn may reuse it, so add the session and what the call acts on ([Make an approved tool idempotent](https://weftgo.dev/docs/sessions/pools/#make-an-approved-tool-idempotent)): ```go title="concepts/tools.go" return weft.Tool("who_calls", "Report which call this is.", func(ctx context.Context, in OrderQuery) (string, error) { call, ok := weft.CallFromContext(ctx) if !ok { return "", errors.New("who_calls: not called by the agent loop") } return fmt.Sprintf("run=%s step=%d call=%s tool=%s", call.RunID, call.Step, call.CallID, call.Name), nil }) ``` [concepts/tools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/tools.go) In the complete example this tool prints `run=run-1 step=0 call=call_3 tool=who_calls`. The second return value is false when the context did not come from the agent loop, for example under a direct `Invoke`. Tool middleware passes verified values to a handler the same way, on the context: see [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/). ### Call a tool by hand [`agt.CallTool(ctx, call)`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) dispatches one tool call by name the way the loop does, through the agent's `WrapTools` chain and the tool's own, with `StrictInput` applied at both levels. It returns the text the model would see. It is the seam for code that dispatches calls itself: ```go title="concepts/tools.go" out, err := agt.CallTool(ctx, weft.ToolCallPart{ ID: "manual-1", Name: "lookup_order", Args: json.RawMessage(`{"order_id":"1234"}`), }) fmt.Fprintln(w, "CallTool:", out, err) _, err = agt.CallTool(ctx, weft.ToolCallPart{ID: "manual-2", Name: "refund_order"}) fmt.Fprintln(w, "unknown tool is ErrNoSuchTool:", errors.Is(err, weft.ErrNoSuchTool)) out, err = lookup.Invoke(ctx, json.RawMessage(`{"order_id":"5678"}`)) fmt.Fprintln(w, "Invoke:", out, err) ``` [concepts/tools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/tools.go) Unlike the loop, `CallTool` does not turn failures into results or apply run policy: - An unknown name returns an error wrapping `ErrNoSuchTool`; arguments that do not decode, one wrapping `ErrInvalidToolInput`; a `RequireApproval` tool, one wrapping `ErrApprovalRequired`. - Handler errors, middleware errors and panics come back to the caller as they are. - `Timeout` and `MaxResultBytes` are not applied. Those are the run policies the package example [`ExampleToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolOptions) bundles with `weft.ToolOptions`; only the loop enforces them. Called from inside a tool handler, the dispatched call is a call of its own. Its handler's `CallFromContext` reports its own id and name, in the dispatching call's run and step. An approval the outer call ran under does not carry over: a `RequireApproval` tool still returns `ErrApprovalRequired`. > **CallTool outside a run records nothing:** `CallTool` produces no span and no log line. Called outside a run it leaves no trace at all: no run, no event, no span, so Studio has nothing to show for it. Record your own line around it if the call matters. ### Complete example `concepts/tools.go` runs the three tools in one step, prints the derived schema, and dispatches calls by hand: ```go title="concepts/tools.go" package main import ( "context" "encoding/json" "errors" "fmt" "io" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // OrderQuery is the input of the order tools below. type OrderQuery struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } // Order is lookup_order's result; a non-string result reaches the model // as JSON. type Order struct { ID string `json:"id"` Status string `json:"status"` } // RefundRequest shows how Go types map onto the derived schema. type RefundRequest struct { OrderID string `json:"order_id" jsonschema:"the order to refund"` Lines []int `json:"lines,omitempty" jsonschema:"line numbers to refund; all when empty"` Reason *string `json:"reason" jsonschema:"why the customer wants a refund"` Credits map[string]int `json:"credits,omitempty"` } // orderTools defines two tools with one input type and two result types. func orderTools() (status, lookup *weft.ToolDef) { status = weft.Tool("order_status", "Report an order's status in words.", func(ctx context.Context, in OrderQuery) (string, error) { return "order " + in.OrderID + " has shipped", nil // a string is sent verbatim }) lookup = weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in OrderQuery) (Order, error) { return Order{ID: in.OrderID, Status: "shipped"}, nil // anything else is sent as JSON }) return status, lookup } // printSchema prints the input schema weft derives for RefundRequest. func printSchema(w io.Writer) error { refund := weft.Tool("refund_order", "Refund an order.", func(ctx context.Context, in RefundRequest) (string, error) { return "refunded", nil }) b, err := json.MarshalIndent(refund.InputSchema, "", " ") if err != nil { return err } fmt.Fprintln(w, string(b)) return nil } // whoCalls is a tool that reports the call it is serving. func whoCalls() *weft.ToolDef { return weft.Tool("who_calls", "Report which call this is.", func(ctx context.Context, in OrderQuery) (string, error) { call, ok := weft.CallFromContext(ctx) if !ok { return "", errors.New("who_calls: not called by the agent loop") } return fmt.Sprintf("run=%s step=%d call=%s tool=%s", call.RunID, call.Step, call.CallID, call.Name), nil }) } // callByHand dispatches tool calls without a run. func callByHand(ctx context.Context, w io.Writer, agt *weft.Agent, lookup *weft.ToolDef) error { out, err := agt.CallTool(ctx, weft.ToolCallPart{ ID: "manual-1", Name: "lookup_order", Args: json.RawMessage(`{"order_id":"1234"}`), }) fmt.Fprintln(w, "CallTool:", out, err) _, err = agt.CallTool(ctx, weft.ToolCallPart{ID: "manual-2", Name: "refund_order"}) fmt.Fprintln(w, "unknown tool is ErrNoSuchTool:", errors.Is(err, weft.ErrNoSuchTool)) out, err = lookup.Invoke(ctx, json.RawMessage(`{"order_id":"5678"}`)) fmt.Fprintln(w, "Invoke:", out, err) return nil } // demoTools runs the three tools in one step, prints the schema, and // dispatches calls by hand. func demoTools(ctx context.Context, w io.Writer) error { status, lookup := orderTools() model := wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "order_status", Args: `{"order_id":"1234"}`}, wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}, wefttest.Call{Name: "who_calls", Args: `{"order_id":"1234"}`}, ), wefttest.Say("Order 1234 has shipped."), ) agt := weft.New(model, status, lookup, whoCalls()) res, err := agt.Generate(ctx, weft.RunID("run-1"), weft.Prompt("Where is order 1234?")) if err != nil { return err } for _, r := range res.Steps[0].Results { fmt.Fprintf(w, "%s → %s\n", r.Name, r.Content) } fmt.Fprintln(w, "order_status has an output schema:", status.OutputSchema != nil) fmt.Fprintln(w, "lookup_order has an output schema:", lookup.OutputSchema != nil) if err := printSchema(w); err != nil { return err } return callByHand(ctx, w, agt, lookup) } ``` [concepts/tools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/tools.go) Run it from `docs-site/examples`: ```sh go run ./concepts tools go test ./concepts ``` ```text order_status → order 1234 has shipped lookup_order → {"id":"1234","status":"shipped"} who_calls → run=run-1 step=0 call=call_3 tool=who_calls order_status has an output schema: false lookup_order has an output schema: true { … the schema above … } CallTool: {"id":"1234","status":"shipped"} unknown tool is ErrNoSuchTool: true Invoke: {"id":"5678","status":"shipped"} ``` ### Best practices & gotchas - **Return a string when the result is prose.** A string reaches the model without JSON quotes; a struct is marshalled. (Source: `weft/docs/adr/0003-tool-contract.md`, `weft/core/tool.go:174-181`) - **Write a `jsonschema` description on every field the model fills.** It is the only per-field guidance the model gets. (Source: `weft/core/schema.go:366-368`) - **Make optional fields pointers or `omitempty`.** Every other field is required in the schema the model sees. (Source: `weft/core/schema.go:188-190`) - **Do not rely on `required` to reject a call.** It is advertised to the model, not checked: an omitted field reaches the handler as its zero value. Use a pointer field and return `weft.ModelRetry` when it is nil. (Source: `weft/core/tool.go:192-221`; `weft/core/errors.go:203-214`) - **Honour `ctx` in handlers.** A timed-out handler's goroutine is abandoned, not stopped; only `ctx` tells it to give up. (Source: AGENTS.md rule 9, `weft/core/tool.go:499-508`) - **Do not expect `CallTool` to be recorded.** It never produces a span; outside a run nothing records it. (Source: `weft/core/loop.go:1686-1705`, CHANGELOG 0.8.0) ### See also - [Set per-tool policy: timeouts, caps, ordering and strict input](https://weftgo.dev/docs/guides/tool-policy/) - [Define tools at runtime: RawTool and ToolSource](https://weftgo.dev/docs/guides/dynamic-tools/) - [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/) - [What happens in one step?](https://weftgo.dev/docs/concepts/the-loop/) - [Use MCP both ways](https://weftgo.dev/docs/guides/mcp/) Symbols used: [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.ToolDef`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolDef) · [`ToolDef.Invoke`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.Invoke) · [`weft.Schema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Schema) · [`Schema.MarshalJSON`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Schema.MarshalJSON) · [`weft.ParseSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParseSchema) · [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) · [`weft.Call`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Call) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) · [`weft.ToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOptions) · [`weft.ErrNoSuchTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNoSuchTool) · [`weft.ErrInvalidToolInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidToolInput) · [`weft.ErrApprovalRequired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalRequired) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunID) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # What happens in one step? The loop and parallel tools URL: https://weftgo.dev/docs/concepts/the-loop/ Markdown: https://weftgo.dev/docs/concepts/the-loop.md > Each step is one model call followed by one batch of tool calls; the calls start in call order, run up to Parallelism at once, and their results land in call order. A [step](https://weftgo.dev/docs/reference/glossary/#step) is one model call followed by one batch of tool calls. The loop sends the model a request, records the assistant message it streams back, runs every tool call in that message, puts the results on one tool message, and then either ends the run or starts the next step. Within a batch, calls start in call order, up to [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) of them run at once (4 by default), and their results land in call order. Three calls in one step, two at a time, in `concepts/loop.go`: ```go title="concepts/loop.go" agt := weft.New(model, weft.Parallelism(2), // at most two of a step's calls execute at once slowTool("inventory", 200*time.Millisecond, false), slowTool("pricing", 20*time.Millisecond, false), slowTool("shipping", 20*time.Millisecond, true), ) run := agt.Stream(ctx, weft.Prompt("Quote order 1234.")) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.StepStart: fmt.Fprintf(w, "step %d starts\n", ev.Index) case weft.ToolStart: fmt.Fprintf(w, " seq %d start %s\n", ev.Seq, ev.Name) case weft.ToolFinish: fmt.Fprintf(w, " seq %d finish %s (error: %v)\n", ev.Seq, ev.Name, ev.IsError) case weft.RunFinish: fmt.Fprintf(w, "run finishes: %s\n", ev.StoppedBy) } } res, err := run.Wait() if err != nil { return err } for _, r := range res.Steps[0].Results { // call order, whatever order they finished in fmt.Fprintf(w, "result %s: %s\n", r.Name, r.Content) } ``` [concepts/loop.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/loop.go) ```text step 0 starts seq 1 start inventory seq 2 start pricing seq 3 finish pricing (error: false) seq 4 start shipping seq 5 finish shipping (error: true) seq 6 finish inventory (error: false) step 1 starts run finishes: final_answer result inventory: inventory ok result pricing: pricing ok result shipping: shipping: carrier unavailable ``` `shipping` waited for a free slot, started when `pricing` finished, and failed; `inventory` kept running and finished last. The results are still in call order, and the failed call is a result like the others. ### How it works > **Diagram:** agt.Generate starts a run (RunStart). Each step is one model call, one chat span. When the model asks for tools, each call starts (ToolStart), the tools run in parallel, and their results come back (ToolFinish) to the model as one tool message; the step ends with StepFinish and, if the budgets allow, the next step calls the model again. MaxSteps bounds the loop, 10 steps by default. The run ends at RunFinish when the model answers with no tool calls, when StopWhen matches, or when calls are pending approval. The run repeats steps until one of three things happens after a step: the model made no tool calls, a `StopWhen` condition matched, or calls are waiting for approval. One exception: when a steering source delivers a message at what would be the final step, the run takes one more step instead of ending ([Steer a running turn](https://weftgo.dev/docs/guides/steering/)). Before each further model call, the loop checks the budgets; `MaxSteps` bounds the number of steps. [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/) covers every exit. ### Life of a call `docs/life-of-a-call.md` in the weft repository lists where every phase of a step and of a tool call sits. Phases are documentation, not hooks: behaviour attaches at the two middleware [seams](https://weftgo.dev/docs/reference/glossary/#seam), `WrapModel` and `WrapTools`, and observation at the [tap](https://weftgo.dev/docs/reference/glossary/#tap) and in the loop's own spans and log lines. **A step**, in order: 1. The loop builds a [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest): the instructions, the transcript so far, the step's tools (a `ToolSource`'s snapshot, else the static list), the thinking level, `SequentialTools`. 2. [`weft.PrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PrepareStep) functions may rewrite it. What they return is what the step advertises and dispatches against. 3. The system prompt becomes the instructions plus the `PromptSnippet` text of the advertised tools. 4. A `chat` span begins and the request goes through the `WrapModel` chain (first listed is outermost) to the adapter and the provider. 5. The loop enforces the stream contract: exactly one `ModelFinish`, nothing after it. A violation fails the run with `ErrModelContract` (see [What is a Model?](https://weftgo.dev/docs/concepts/models/#the-model-contract)). 6. The step's output joins the transcript as one assistant message: reasoning parts, text, tool calls. 7. The tool calls run as one batch, below. A `max_tokens` finish with calls runs none of them: each gets an error result instead. 8. `StepFinish` is emitted. Pending approvals, no calls, or a matching `StopWhen` end the run with `RunFinish`. 9. Otherwise the run reaches the continuation point: `MaxModelRetries`, `UsageLimit` and `DetectLoops` are checked, first breach wins, and the next step begins. **A tool call**, in order: 1. The dispatcher acquires a slot (`Parallelism(n)`; `Sequential()` is one at a time; a `Sequential` tool is a barrier). 2. `ToolStart` is emitted with its `Seq`. 3. Inside the containment boundary, an `execute_tool` span begins, and the call goes through the agent's `WrapTools` chain, then the tool's own chain, then the base: resolve the name (unknown is `NO_SUCH_TOOL`), park a `RequireApproval` call that is not approved, decode the arguments (failure is `INVALID_INPUT`), run the handler. 4. At the containment boundary a panic becomes `tool "X" panicked: …` and a `Timeout` becomes `tool "X" timed out after 10s` (with the configured duration); neither fails the run. 5. The result is rendered (`*ToolError` as `CODE: message`, any other error as its text) and capped at `MaxResultBytes` with a visible marker. 6. The span ends, then `ToolFinish` is emitted, and the result joins the step's tool message in call order. A parked call gets no `ToolFinish`. A [subagent's](https://weftgo.dev/docs/reference/glossary/#subagent) child run sits inside the handler line: it holds a slot like any tool, and its events arrive wrapped in `Nested` between the delegating call's `ToolStart` and `ToolFinish`. **The two conventions** the same document fixes: - **Context decoration.** Middleware that verifies something (a user, a tenant, a quota) puts it on `ctx` before calling `next`; the handler reads it through a typed accessor, as it reads [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext). Decorate only with what the middleware verified. - **Error shaping.** Handlers return `*weft.ToolError` when the model should branch on a code; `mw.MapErrors` codes everything else centrally. The cause in `ToolError.Err` is for audit logs and `errors.As`, never for the model. [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) applies both. ### Parallel tools > **Diagram:** The model asks for three tools in one step: lookup_order, track_shipment and get_customer. With Parallelism(4), the default, each call runs on its own goroutine at the same time. lookup_order finishes in 140 ms and get_customer in 90 ms; track_shipment times out after 5 seconds and becomes an error result (IsError) instead of failing the run. The results join one tool message in call order, 1, 2, 3, whatever order they finished in, and the model sees all three. Sequential() runs them one at a time instead. A step's tool calls fan out over goroutines. `weft.Parallelism(n)` sets how many execute at once, 4 by default; values below 1 are ignored. As a run option it may only lower the agent's value. [`weft.Sequential()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Sequential) on the agent runs calls one at a time, each finishing before the next starts. Three orders are kept separately, and each is fixed: - **Start order is call order.** The slot is acquired on the dispatching goroutine, in call order, before the call's goroutine is spawned, and `ToolStart` is emitted there. - **Result order is call order.** Results are collected by index and land on the tool message in the order the model requested them, whatever order they finished in. - **Event order is `Seq` order.** `ToolStart`, `ToolFinish` and `Nested` events take their `Seq` and are emitted under one lock, so the observed order never contradicts the numbers and a stream replays exactly. A tool built with `weft.Sequential()` is a barrier: the dispatcher lets every call in flight finish, runs that call alone, then resumes parallel dispatch for the calls after it. Other tools keep their parallelism. Failure and cancellation follow fixed rules: - **A failing tool never cancels its siblings.** An error, a panic or a timeout is that call's result; only the run's `ctx` cancels other calls. - **No tool starts after the run is canceled.** A call that never got a slot gets the result `run canceled before the tool started` and no events, so every `ToolFinish` follows its `ToolStart`. - **A hung tool never hangs the run.** With [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) on the tool or the agent, an expired call is recorded as an error result and its goroutine is abandoned. Without a timeout, only the run's `ctx` bounds a call. Under `Sequential()` or `Parallelism(1)` the loop also sets `ModelRequest.SequentialTools`. The OpenAI and Anthropic adapters then ask the provider not to emit parallel batches at all; Gemini has no such switch, so with the Google adapter the loop's single slot is what serializes the calls. ### What it does not do - **No phase is a hook.** You cannot attach code "after decode" or "before render"; behaviour goes in middleware around the whole call, and observation in a tap. Adding a third seam needs an ADR. - **No automatic waiting for approval-gated tools.** A `RequireApproval` call parks, and its siblings in the same step still run before the run ends. `Sequential()` does not change that: it is an execution barrier, and a parked call returns at once. If siblings must wait for the decision, park them too (`weft.ParkOn`, or middleware returning `ErrApprovalRequired`) or deny them in middleware such as `mw.Allow`. - **No per-run timeout option.** A run's deadline is its `ctx`; `weft.Timeout` bounds single tool calls. ### Complete example `concepts/loop.go` defines three tools of different speeds, one failing, and streams one step of them two at a time: ```go title="concepts/loop.go" package main import ( "context" "errors" "fmt" "io" "time" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // QuoteInput is the input of the three quote tools. type QuoteInput struct { OrderID string `json:"order_id"` } // slowTool is a tool that takes d to answer; fail makes it return an error // instead. func slowTool(name string, d time.Duration, fail bool) *weft.ToolDef { return weft.Tool(name, "Quote one part of an order.", func(ctx context.Context, in QuoteInput) (string, error) { select { case <-time.After(d): case <-ctx.Done(): return "", ctx.Err() } if fail { return "", errors.New(name + ": carrier unavailable") } return name + " ok", nil }) } // quoteScript asks for the three quote tools in one step, then answers. func quoteScript() *wefttest.Model { return wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "inventory", Args: `{"order_id":"1234"}`}, wefttest.Call{Name: "pricing", Args: `{"order_id":"1234"}`}, wefttest.Call{Name: "shipping", Args: `{"order_id":"1234"}`}, ), wefttest.Say("Order 1234: in stock and priced; no shipping quote yet."), ) } // demoLoop runs one step's three tool calls two at a time and prints the // events in Seq order, then the results in call order. func demoLoop(ctx context.Context, w io.Writer) error { model := quoteScript() agt := weft.New(model, weft.Parallelism(2), // at most two of a step's calls execute at once slowTool("inventory", 200*time.Millisecond, false), slowTool("pricing", 20*time.Millisecond, false), slowTool("shipping", 20*time.Millisecond, true), ) run := agt.Stream(ctx, weft.Prompt("Quote order 1234.")) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.StepStart: fmt.Fprintf(w, "step %d starts\n", ev.Index) case weft.ToolStart: fmt.Fprintf(w, " seq %d start %s\n", ev.Seq, ev.Name) case weft.ToolFinish: fmt.Fprintf(w, " seq %d finish %s (error: %v)\n", ev.Seq, ev.Name, ev.IsError) case weft.RunFinish: fmt.Fprintf(w, "run finishes: %s\n", ev.StoppedBy) } } res, err := run.Wait() if err != nil { return err } for _, r := range res.Steps[0].Results { // call order, whatever order they finished in fmt.Fprintf(w, "result %s: %s\n", r.Name, r.Content) } return nil } ``` [concepts/loop.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/loop.go) Run it from `docs-site/examples`: ```sh go run ./concepts loop go test ./concepts ``` ```text step 0 starts seq 1 start inventory seq 2 start pricing seq 3 finish pricing (error: false) seq 4 start shipping seq 5 finish shipping (error: true) seq 6 finish inventory (error: false) step 1 starts run finishes: final_answer result inventory: inventory ok result pricing: pricing ok result shipping: shipping: carrier unavailable ``` ### Best practices & gotchas - **Mark tools that share state `Sequential()`.** Parallel calls of the same step run at the same time; a barrier tool runs alone. (Source: `weft/core/agent.go:233-244`, deep dive §6) - **Honour `ctx` in every handler.** A timed-out handler is abandoned, not stopped; a write after the timeout is lost, and side effects must check `ctx` first. (Source: AGENTS.md rule 9, deep dive §6 edge cases) - **Consume `Events()` promptly or use `Generate`.** Tool events are emitted under the step's ordering lock, so a slow consumer delays the step's later tools. (Source: `weft/core/run.go:757-771`) - **Read results in call order, events in `Seq` order.** Completion order is visible only in the events. (Source: AGENTS.md rule 3, `weft/core/loop.go:1188-1206`) ### See also - [Set per-tool policy: timeouts, caps, ordering and strict input](https://weftgo.dev/docs/guides/tool-policy/) - [Stream a run's events](https://weftgo.dev/docs/guides/streaming/) - [Add behaviour with middleware (the two seams)](https://weftgo.dev/docs/guides/middleware/) - [The agent loop, from first principles](https://weftgo.dev/docs/explanation/agent-loop/) - [Fan out many tool calls safely](https://weftgo.dev/docs/examples/tool-storm/) Symbols used: [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) · [`weft.Sequential`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Sequential) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.PrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PrepareStep) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`weft.ToolStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolStart) · [`weft.ToolFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolFinish) · [`weft.StepStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepStart) · [`weft.RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) · [`Agent.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Messages, parts and the transcript URL: https://weftgo.dev/docs/concepts/messages/ Markdown: https://weftgo.dev/docs/concepts/messages.md > A weft.Message is a role plus typed parts; a transcript round-trips through JSON losslessly, and weft.Repair makes any transcript valid model input. A [`weft.Message`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Message) is one turn of a conversation: a [`weft.Role`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Role) plus an ordered list of typed parts. A transcript is a `[]weft.Message`; it round-trips through `encoding/json` without loss, and [`weft.Repair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Repair) turns any transcript into valid model input. One support turn, written by hand in `concepts/messages.go`, in the same shape the loop produces: ```go title="concepts/messages.go" transcript := []weft.Message{ weft.User("Where is order 1234?"), {Role: weft.RoleAssistant, Content: []weft.Part{ weft.TextPart{Text: "Let me check."}, weft.ToolCallPart{ID: "call_1", Name: "lookup_order", Args: json.RawMessage(`{"order_id":"1234"}`)}, }}, {Role: weft.RoleTool, Content: []weft.Part{ // one tool message per step, a result per call weft.ToolResultPart{CallID: "call_1", Name: "lookup_order", Content: "order 1234: shipped"}, }}, weft.Assistant("Order 1234 has shipped."), } for _, m := range transcript { fmt.Fprintf(w, "%-9s %d part(s), text %q\n", m.Role, len(m.Content), m.Text()) } ``` [concepts/messages.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/messages.go) ```text user 1 part(s), text "Where is order 1234?" assistant 2 part(s), text "Let me check." tool 1 part(s), text "" assistant 1 part(s), text "Order 1234 has shipped." ``` ### How it works The loop appends to the transcript as a run goes: each step adds one assistant message (its reasoning, text and tool calls) and, when the step called tools, one tool message holding a result for every call that ran. Two exceptions: a step that produced no text, reasoning or calls adds no assistant message, and a call parked at the approval boundary has no result until the run that decides it, so a step whose every call parked adds no tool message. `RunResult.Messages` is that transcript, the run's input included. Pass it back with `weft.Messages(res.Messages...)` and the next run continues where this one ended. ### Roles and parts There are three roles: | Role | Constant | Carries | |---|---|---| | `user` | [`weft.RoleUser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RoleUser) | The person's input: text, and files. | | `assistant` | [`weft.RoleAssistant`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RoleAssistant) | The model's output: reasoning, text and tool calls. | | `tool` | [`weft.RoleTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RoleTool) | The results of one step's tool calls, one result per call. | There is no system role. The system instruction is agent configuration (`weft.Instructions`) and travels on `ModelRequest.System`, so a transcript never carries it and adapters never merge it in. The role of a message you pass in is not checked. That covers a message given to `weft.Messages` and a transcript decoded from JSON: `Message.UnmarshalJSON` rejects an unknown part type but takes any `role` string, the loop does not look, and `weft.Repair` passes such a message through unchanged. Steering is the exception: a steered message that is not `user` fails with `ErrInvalidSteer`. Each adapter converts only `user`, `assistant` and `tool`, so a message with any other role, such as a `"system"` message imported from an OpenAI-format transcript, stays in `res.Messages` and is never sent to the provider. The run gets no error and no log line. A [`weft.Part`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Part) is a sealed interface: the set of part types is closed, and only weft adds to it. The three every tool-using conversation has: - [`weft.TextPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TextPart): `Text`, a span of user or assistant text. - [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart): a call the model requested. `ID` is the provider's call id, unique within its step, and `Name` is the tool. `Args` is the raw JSON the model produced, decoded into the tool's input type only when the call runs. `Signature` is a provider's opaque token on the call itself (Gemini's thought signatures), empty for providers without one. - [`weft.ToolResultPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolResultPart): the outcome of one call. `CallID` matches the call's `ID`; `Name` is the tool; `Content` is the result text (the output, or the failure message); `IsError` marks a failure. A tool failure is a result the model reads, never a run error. Two more part types exist: [`weft.ReasoningPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReasoningPart), a provider reasoning block weft keeps and sends back with its signature but never acts on; and [`weft.FilePart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#FilePart), an image, PDF or audio file in a user message ([Send images and files to a model](https://weftgo.dev/docs/guides/multimodal/)). ### Build messages The constructors cover the common shapes: - [`weft.User(text)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#User) and [`weft.Assistant(text)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Assistant) return a message with one `TextPart`. - [`weft.UserParts(parts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UserParts) returns a user message with several parts, for text beside files. - Any other shape is a literal: `weft.Message{Role: …, Content: []weft.Part{…}}`, as the assistant and tool messages above. `Message` has two fields, `Role` and `Content`. [`m.Text()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Message.Text) returns the concatenation of its text parts, so a tool message's text is empty. On the wire every part carries a `"type"` discriminator (`text`, `tool_call`, `tool_result`, `reasoning`, `file`). Encoding is plain `json.Marshal`; decoding goes through [`Message.UnmarshalJSON`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Message.UnmarshalJSON), which restores each part as its own Go type and rejects a part type it does not know: ```go title="concepts/messages.go" b, err := json.Marshal(transcript[1]) // the assistant message with the tool call if err != nil { return err } fmt.Fprintln(w, string(b)) var back []weft.Message all, _ := json.Marshal(transcript) if err := json.Unmarshal(all, &back); err != nil { return err } call := back[1].Content[1].(weft.ToolCallPart) // parts come back as their own types fmt.Fprintln(w, "decoded:", call.Name, string(call.Args)) var m weft.Message err = json.Unmarshal([]byte(`{"role":"user","content":[{"type":"sticker"}]}`), &m) fmt.Fprintln(w, "unknown part:", err) ``` [concepts/messages.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/messages.go) ```text {"role":"assistant","content":[{"type":"text","text":"Let me check."},{"type":"tool_call","id":"call_1","name":"lookup_order","args":{"order_id":"1234"}}]} decoded: lookup_order {"order_id":"1234"} unknown part: weft: message content[0]: unknown part type "sticker" ``` An unknown type is an error, never a dropped part: silently losing content would corrupt the transcript. The wire format is versioned by [`weft.SchemaVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SchemaVersion), currently 1; within a version, fields change only by addition. ### Repair A valid transcript pairs every tool call with exactly one result. `weft.Repair(msgs)` restores that from anything: a transcript cut off mid-step, one assembled by hand, one loaded from storage. Every run's input goes through it before the first model call, so you only call it yourself to persist or inspect a transcript. What it changes: - A tool call with no result gets a visible error result: `no result recorded: the call was interrupted`. - A result whose `CallID` names no call of the assistant message before it is dropped, as is a second result for the same call. - Only the first tool message after an assistant message is kept; a later one is non-canonical and dropped whole. - A tool message that does not follow an assistant message with calls is dropped, and so is any part in a tool message that is not a `ToolResultPart`. - Everything outside tool messages is untouched. Here the only result answers a call nobody made, so it is dropped, and the real call gets a synthesized result: ```go title="concepts/messages.go" interrupted := []weft.Message{ weft.User("Where is order 1234?"), {Role: weft.RoleAssistant, Content: []weft.Part{ weft.ToolCallPart{ID: "call_1", Name: "lookup_order", Args: json.RawMessage(`{"order_id":"1234"}`)}, }}, {Role: weft.RoleTool, Content: []weft.Part{ // answers a call no message made weft.ToolResultPart{CallID: "call_9", Name: "lookup_order", Content: "order 9: shipped"}, }}, } for _, m := range weft.Repair(interrupted) { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok { fmt.Fprintf(w, "%s %s (error: %v): %s\n", m.Role, r.CallID, r.IsError, r.Content) } } } ``` [concepts/messages.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/messages.go) ```text tool call_1 (error: true): no result recorded: the call was interrupted ``` `Repair` is pure, never changing its input, and idempotent: `Repair(Repair(m))` equals `Repair(m)`. A dropped part leaves no marker; a synthesized one is always visible to the model. The package example [`ExampleRepair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Repair) shows the same repair on a transcript that stops after the call. Studio marks a synthesized result where it can see one: on the run page's Request pane, a message line holding that text is prefixed `[synthesised by Repair]`. The record carries no other sign, so Studio matches the text ([Badges and holes](https://weftgo.dev/docs/reference/badges/#other-words)). ### Complete example `concepts/messages.go` builds a transcript, round-trips it through JSON and repairs a broken one: ```go title="concepts/messages.go" package main import ( "context" "encoding/json" "fmt" "io" "github.com/weftgo/weft" ) // buildTranscript writes one turn of a support conversation by hand: the // shape the loop itself produces. func buildTranscript(w io.Writer) []weft.Message { transcript := []weft.Message{ weft.User("Where is order 1234?"), {Role: weft.RoleAssistant, Content: []weft.Part{ weft.TextPart{Text: "Let me check."}, weft.ToolCallPart{ID: "call_1", Name: "lookup_order", Args: json.RawMessage(`{"order_id":"1234"}`)}, }}, {Role: weft.RoleTool, Content: []weft.Part{ // one tool message per step, a result per call weft.ToolResultPart{CallID: "call_1", Name: "lookup_order", Content: "order 1234: shipped"}, }}, weft.Assistant("Order 1234 has shipped."), } for _, m := range transcript { fmt.Fprintf(w, "%-9s %d part(s), text %q\n", m.Role, len(m.Content), m.Text()) } return transcript } // roundTrip encodes the transcript as JSON and decodes it back. func roundTrip(w io.Writer, transcript []weft.Message) error { b, err := json.Marshal(transcript[1]) // the assistant message with the tool call if err != nil { return err } fmt.Fprintln(w, string(b)) var back []weft.Message all, _ := json.Marshal(transcript) if err := json.Unmarshal(all, &back); err != nil { return err } call := back[1].Content[1].(weft.ToolCallPart) // parts come back as their own types fmt.Fprintln(w, "decoded:", call.Name, string(call.Args)) var m weft.Message err = json.Unmarshal([]byte(`{"role":"user","content":[{"type":"sticker"}]}`), &m) fmt.Fprintln(w, "unknown part:", err) return nil } // repairTranscript repairs a transcript cut off mid-step. func repairTranscript(w io.Writer) { interrupted := []weft.Message{ weft.User("Where is order 1234?"), {Role: weft.RoleAssistant, Content: []weft.Part{ weft.ToolCallPart{ID: "call_1", Name: "lookup_order", Args: json.RawMessage(`{"order_id":"1234"}`)}, }}, {Role: weft.RoleTool, Content: []weft.Part{ // answers a call no message made weft.ToolResultPart{CallID: "call_9", Name: "lookup_order", Content: "order 9: shipped"}, }}, } for _, m := range weft.Repair(interrupted) { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok { fmt.Fprintf(w, "%s %s (error: %v): %s\n", m.Role, r.CallID, r.IsError, r.Content) } } } } // demoMessages builds a transcript, round-trips it through JSON and // repairs a broken one. func demoMessages(ctx context.Context, w io.Writer) error { transcript := buildTranscript(w) if err := roundTrip(w, transcript); err != nil { return err } repairTranscript(w) return nil } ``` [concepts/messages.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/messages.go) Run it from `docs-site/examples`: ```sh go run ./concepts messages go test ./concepts ``` ```text user 1 part(s), text "Where is order 1234?" assistant 2 part(s), text "Let me check." tool 1 part(s), text "" assistant 1 part(s), text "Order 1234 has shipped." {"role":"assistant","content":[{"type":"text","text":"Let me check."},{"type":"tool_call","id":"call_1","name":"lookup_order","args":{"order_id":"1234"}}]} decoded: lookup_order {"order_id":"1234"} unknown part: weft: message content[0]: unknown part type "sticker" tool call_1 (error: true): no result recorded: the call was interrupted ``` ### Best practices & gotchas - **Store transcripts as JSON of `[]weft.Message`.** The encoding is lossless, signatures included, and versioned; rebuilding messages from events loses signatures and block boundaries. (Source: `weft/core/message.go:30-41`, `weft/core/run.go:551-574`) - **Put every result of one step on one tool message.** `Repair` keeps only the first tool message after an assistant message. (Source: `weft/core/repair.go:21-36`) - **Branch on part types with a type switch, and keep a default case.** The set is closed, so a switch over `TextPart`, `ToolCallPart`, `ToolResultPart`, `ReasoningPart` and `FilePart` is complete for v0.20.2; weft plans to add part types (approval parts), and only weft can. (Source: `weft/core/message.go:95-100`) - **Keep the system prompt out of the transcript.** There is no system role; use `weft.Instructions`. (Source: ADR 0001, AGENTS.md rule 2) - **Move a foreign system message into `weft.Instructions` before the run.** A transcript imported from another framework may hold `{"role":"system",…}`. It decodes, but all three adapters drop it from the request without an error, so the model never sees that text. Take its text out of the slice and pass it with `weft.Instructions`. (Source: `weft/core/message.go:77-83`, `weft/openai/convert.go:34-73`, `weft/anthropic/convert.go:118-145`, `weft/google/convert.go:20-50`) ### See also - [Continue a conversation](https://weftgo.dev/docs/guides/conversations/) - [Send images and files to a model](https://weftgo.dev/docs/guides/multimodal/) - [What does a run return?](https://weftgo.dev/docs/concepts/runs/) - [What is a session?](https://weftgo.dev/docs/sessions/overview/) Symbols used: [`weft.Message`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Message) · [`weft.Role`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Role) · [`weft.Part`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Part) · [`weft.TextPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TextPart) · [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) · [`weft.ToolResultPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolResultPart) · [`weft.ReasoningPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReasoningPart) · [`weft.FilePart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#FilePart) · [`weft.User`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#User) · [`weft.UserParts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UserParts) · [`weft.Assistant`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Assistant) · [`weft.Repair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Repair) · [`weft.SchemaVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SchemaVersion) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) --- # What is a Model? The provider contract URL: https://weftgo.dev/docs/concepts/models/ Markdown: https://weftgo.dev/docs/concepts/models.md > A weft.Model is one method, Stream, that turns a ModelRequest into a stream of model events ending in exactly one ModelFinish; the loop enforces that contract. A [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) is the provider seam: one method, `Stream(ctx, req)`, that takes one step's [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) and yields that step's output as model events, ending in exactly one `ModelFinish`. The provider adapters implement it over the vendors' official Go SDKs; `wefttest.Script` implements it for tests; so can you. The loop checks every stream against the contract, so a broken model fails the run instead of corrupting the transcript. A complete model, in `concepts/models.go`: ```go title="concepts/models.go" // echoModel is a complete weft.Model: it streams one text delta that // repeats the last message, then exactly one ModelFinish. type echoModel struct{} func (echoModel) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { return func(yield func(weft.ModelEvent, error) bool) { if err := ctx.Err(); err != nil { yield(nil, err) // a failure is one terminal (nil, err) return } last := req.Messages[len(req.Messages)-1].Text() if !yield(weft.ModelTextDelta{Text: "you said: " + last}, nil) { return } yield(weft.ModelFinish{Reason: weft.StopEndTurn, Usage: weft.Usage{InputTokens: 4, OutputTokens: 3}}, nil) } } // Info names the model on RunStart.Model and in the manifest (optional). func (echoModel) Info() weft.ModelInfo { return weft.ModelInfo{Provider: "docs", Name: "echo-1"} } ``` [concepts/models.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/models.go) `weft.New(echoModel{})` is a working agent; asked "hello", it answers `you said: hello`. ### How it works Each step, the loop builds a request, passes it through the `WrapModel` middleware chain, and ranges over the stream the innermost model returns. Text deltas become `TextDelta` events and the assistant message's text; tool calls are collected for the step's tool batch; `ModelFinish` closes the step with its stop reason and usage. The adapter's job is translation in both directions: the request into the vendor's wire format, the vendor's stream into these events. ### The model contract [`Model.Stream`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) returns an `iter.Seq2[ModelEvent, error]` that must: 1. Yield any number of `ModelTextDelta`, `ModelReasoningDelta` and `ModelToolCall` values, optionally interleaved with `ModelToolCallDelta` progress, then exactly one `ModelFinish`. 2. Report a failure as a single terminal `(nil, err)`, with nothing after it. 3. Honour `ctx`: when it is done, yield `(nil, ctx.Err())` if the stream has not finished. The loop enforces it. A stream that ends without `ModelFinish`, yields an event after it, yields a tool call with an empty id or name, yields two tool calls with the same id in one step, or panics fails the run with an error wrapping [`weft.ErrModelContract`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelContract): ```go title="concepts/models.go" noFinish := wefttest.Raw(weft.ModelTextDelta{Text: "hello"}) // a stream with no ModelFinish agt := weft.New(wefttest.Script(noFinish)) _, err := agt.Generate(ctx, weft.Prompt("hi")) fmt.Fprintln(w, "ErrModelContract:", errors.Is(err, weft.ErrModelContract)) fmt.Fprintln(w, err) ``` [concepts/models.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/models.go) ```text ErrModelContract: true weft: run failed at step 0: weft: model violated the stream contract: stream ended without ModelFinish ``` An error yielded after `ModelFinish` fails the run as that stream error, `model stream: `, not as `ErrModelContract`. `ErrModelContract` means an adapter bug, not an outage: a provider's own errors reach the caller unwrapped, as `model stream: `. Two sentinels adapters wrap on purpose: - [`weft.ErrUnsupported`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUnsupported): the request uses something the model cannot carry, such as a `FilePart` of a media type the provider does not accept. It is a run error, so a caller can `errors.Is` on it and fall back to another model. - [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow): the request exceeds the model's context window. See [run errors](https://weftgo.dev/docs/concepts/errors/#context-overflow). The loop also protects adapters from each other and from themselves: - **Each request gets fresh copies** of the `Messages` and `Tools` slices, of each message's `Content` slice, and of `Params`' values (the pointer knobs and `Stop`). A model or middleware may append, reassign a message or part, or write `*req.Params.Temperature`. Nothing reaches the transcript, the agent, the run option, the caller's variables or a later step. Only the bytes inside parts (a tool call's `Args`, a file's `Data`) and the `ToolDef` fields stay shared. Never modify them, and clone what you keep past the call. - **Empty assistant turns never reach the transcript.** A step that streamed no text, no reasoning and no calls appends nothing, because providers reject empty content. All three adapters also skip an assistant message with nothing sendable (reasoning-only, say: openai drops all reasoning, anthropic and google drop unsigned reasoning) and drop empty text parts when they build the wire request; Google skips a content entry left with no parts. - **Tool definitions are converted per request** by the adapters, so a `ToolSource` that rebuilds its list every step costs a conversion, not a growing cache. ### The request A `ModelRequest` is everything one step needs, read-only for the model: | Field | What it holds | |---|---| | `System` | The instructions plus the advertised tools' `PromptSnippet` text. | | `Messages` | The transcript so far, as a fresh slice. | | `Tools` | The tools this step advertises and will dispatch against, as a fresh slice. | | `Thinking` | The reasoning level for this step; the zero value keeps the provider default. | | `SequentialTools` | True under `Sequential()` or `Parallelism(1)`: ask the provider not to emit parallel tool-call batches. | | `ToolChoice` | Whether the step must call some tool, a named tool, or none; the zero value is the provider default. | | `Params` | Sampling overrides (`Temperature`, `TopP`, `MaxTokens`, `Stop`, `Seed`) for this request; nil fields keep the adapter's defaults. | `PrepareStep` functions can rewrite any of these before the model sees them ([Rewrite the request each step](https://weftgo.dev/docs/guides/prepare-step/)). ### Stream events [`weft.ModelEvent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelEvent) is a sealed interface with five types: | Event | Fields | Meaning | |---|---|---| | [`ModelTextDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelTextDelta) | `Text` | An increment of assistant text. | | [`ModelReasoningDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelReasoningDelta) | `Text`, `Signature` | An increment of provider reasoning. A delta with a non-empty `Signature` closes the current reasoning block, so one `ReasoningPart` per provider block survives the round trip. | | [`ModelToolCall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelToolCall) | `ID`, `Name`, `Args`, `Signature` | One complete tool call. `ID` is echoed on the matching result and must be unique within the step; `Signature` is a token some providers attach to the call itself. | | [`ModelToolCallDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelToolCallDelta) | `Index`, `Name`, `Args` | Progress while the model writes a call's arguments: `Index` is the provider's fragment key, `Name` the best-known name so far, `Args` the fragment. The whole call still arrives as a `ModelToolCall`. | | [`ModelFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelFinish) | `Reason`, `Usage`, `Raw` | Closes the step: the mapped `StopReason`, the step's token `Usage`, and the provider's own stop reason in `Raw` when the mapping was approximate (`refusal`, `content_filter`, …). | Tool calls arrive whole: assembling a provider's streamed argument fragments is the adapter's job, which keeps the loop identical across providers. Adapters whose providers send calls whole, such as Google's, yield no `ModelToolCallDelta` at all. ### Model identity A model can name itself by implementing the optional method `Info() weft.ModelInfo`. A [`weft.ModelInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelInfo) has two fields: `Provider` (`"openai"`, `"anthropic"`, `"wefttest"`) and `Name`, the vendor's model id. The loop puts it on `RunStart.Model`, the spans and the manifest. `Model` itself stays one method. [`weft.InfoOf(m)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) returns `m`'s `ModelInfo`, or the zero value when `m` does not implement `Info`. Model middleware forwards identity with it, so a wrapped model still reports the model underneath. The `countingModel` middleware in `concepts/models.go` forwards both optional methods: ```go title="concepts/models.go" func (m countingModel) Info() weft.ModelInfo { return weft.InfoOf(m.next) } func (m countingModel) Unwrap() weft.Model { return m.next } ``` [concepts/models.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/models.go) ### Unwrap Middleware also declares the model it wraps with the optional method `Unwrap() weft.Model`. [`weft.Unwrap(m)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Unwrap) walks one level and returns nil for a model that is not a wrapper, so a caller walks a chain without knowing the wrapper types: ```go title="concepts/models.go" counting := func(next weft.Model) weft.Model { return countingModel{next: next, calls: &calls} } agt := weft.New(echoModel{}, weft.WrapModel(counting)) for m := agt.Model(); m != nil; m = weft.Unwrap(m) { fmt.Fprintf(w, "%T %v\n", m, weft.InfoOf(m)) } ``` [concepts/models.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/models.go) ```text main.countingModel {docs echo-1} main.echoModel {docs echo-1} ``` `agt.Model()` is the chain as the loop calls it, outermost first. `mw.Retry`, `mw.Fallback` (unwrapping to its primary, the model its `Info` names), `mw.Log` and `mw.RepairJSON` all implement `Unwrap`. The walk ends at the first model that is not a wrapper. `weft/thread` walks the chain this way to find provider-native compaction under an agent's middleware. The core example [`ExampleAgent_Model`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Agent.Model) pins the walk. ### Raw wire bodies Code inside the model chain can report each provider request's raw wire exchange to the run's record. [`weft.ReportFromContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReportFromContext) returns the [`weft.Reporter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Reporter) of the model call `ctx` belongs to; outside a run's model call it is a no-op reporter, never nil. Reporting is not a seam: no report changes a step, a retry or a result. - [`rep.WantsRaw()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.WantsRaw) reports whether a raw report would be recorded now. It is true only inside a run's model call, with content capture on, and with a destination that asked for raw bodies (`otel.RawBodies(true)`, development only). An adapter asks first and buffers no body when the answer is false. - [`rep.Raw(pair)`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Raw) reports one attempt's exchange as a `weft.raw` record, attributed to the step and to the attempt in flight. A layer that reports both an attempt and its body reports `Raw` first. A [`weft.RawPair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawPair) holds what the reporter knows; zero fields are left out of the record: | Field | What it holds | |---|---| | `Request`, `Response` | The request as sent and the response as received; a streamed response is the raw stream bytes. | | `MediaType`, `ResponseMediaType` | The two sides' media types, e.g. `application/json`, `text/event-stream`. | | `Method`, `URL` | The request line. The record drops the URL's userinfo and credential query values. | | `Status` | The HTTP status; 0 when no response arrived. | | `RequestHeaders`, `ResponseHeaders` | The headers. The record never carries a credential header (`Authorization`, `X-Api-Key`, `Cookie`, …) or a Bearer or Basic value. | | `RedactedHeaders` | Headers the reporter stripped itself, listed so the record says what is missing. | | `RequestTruncated`, `ResponseTruncated` | Bytes the reporter did not keep past its own cap, counted into the record's cut. Each body is also capped at 256 KiB by the record. | | `ResponseIncomplete` | The response body was not read to its end (closed unread, timed out, read error); the record marks that side incomplete. | The bytes are content: the request carries the prompt. [Control what content leaves the process](https://weftgo.dev/docs/production/content-and-privacy/) covers the policy. ### What it does not do - **A model does not run tools or keep history.** It sees one request and streams one step; the loop owns the transcript and the tool batch. - **The loop does not retry.** A stream error fails the step; retries and fallbacks are model middleware, `mw.Retry` and `mw.Fallback` ([Retry and fall back](https://weftgo.dev/docs/guides/retries-and-fallback/)). - **The core reads no reasoning.** Reasoning text and signatures are stored and sent back, never interpreted. ### Complete example `concepts/models.go` runs the echo model, a stream that breaks the contract, and a middleware chain: ```go title="concepts/models.go" package main import ( "context" "errors" "fmt" "io" "iter" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // echoModel is a complete weft.Model: it streams one text delta that // repeats the last message, then exactly one ModelFinish. type echoModel struct{} func (echoModel) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { return func(yield func(weft.ModelEvent, error) bool) { if err := ctx.Err(); err != nil { yield(nil, err) // a failure is one terminal (nil, err) return } last := req.Messages[len(req.Messages)-1].Text() if !yield(weft.ModelTextDelta{Text: "you said: " + last}, nil) { return } yield(weft.ModelFinish{Reason: weft.StopEndTurn, Usage: weft.Usage{InputTokens: 4, OutputTokens: 3}}, nil) } } // Info names the model on RunStart.Model and in the manifest (optional). func (echoModel) Info() weft.ModelInfo { return weft.ModelInfo{Provider: "docs", Name: "echo-1"} } // countingModel is model middleware: it counts calls and forwards the // rest, identity included. type countingModel struct { next weft.Model calls *int } func (m countingModel) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { *m.calls++ return m.next.Stream(ctx, req) } func (m countingModel) Info() weft.ModelInfo { return weft.InfoOf(m.next) } func (m countingModel) Unwrap() weft.Model { return m.next } // brokenModel shows the loop refusing a stream that never finishes. func brokenModel(ctx context.Context, w io.Writer) error { noFinish := wefttest.Raw(weft.ModelTextDelta{Text: "hello"}) // a stream with no ModelFinish agt := weft.New(wefttest.Script(noFinish)) _, err := agt.Generate(ctx, weft.Prompt("hi")) fmt.Fprintln(w, "ErrModelContract:", errors.Is(err, weft.ErrModelContract)) fmt.Fprintln(w, err) return nil } // walkChain walks a wrapped model one middleware at a time. func walkChain(w io.Writer) { var calls int counting := func(next weft.Model) weft.Model { return countingModel{next: next, calls: &calls} } agt := weft.New(echoModel{}, weft.WrapModel(counting)) for m := agt.Model(); m != nil; m = weft.Unwrap(m) { fmt.Fprintf(w, "%T %v\n", m, weft.InfoOf(m)) } } // demoModels runs the echo model, a contract-breaking model, and walks a // middleware chain. func demoModels(ctx context.Context, w io.Writer) error { res, err := weft.New(echoModel{}).Generate(ctx, weft.Prompt("hello")) if err != nil { return err } fmt.Fprintln(w, res.Text(), "|", res.Usage.Total(), "tokens") if err := brokenModel(ctx, w); err != nil { return err } walkChain(w) return nil } ``` [concepts/models.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/models.go) Run it from `docs-site/examples`: ```sh go run ./concepts models go test ./concepts ``` ```text you said: hello | 7 tokens ErrModelContract: true weft: run failed at step 0: weft: model violated the stream contract: stream ended without ModelFinish main.countingModel {docs echo-1} main.echoModel {docs echo-1} ``` ### Best practices & gotchas - **Forward `Info` and `Unwrap` in every model middleware.** Without `Info`, runs report a zero model; without `Unwrap`, the chain walk stops at your wrapper. `wefttest.ConformInfo` checks the first. (Source: `weft/core/agent.go:246-253`) - **Return when `yield` returns false.** The loop stops ranging when it fails the step, for example on an event after `ModelFinish`. Calling `yield` again makes Go panic, and the loop's recover turns that into an `ErrModelContract` run error. (Source: `weft/core/loop.go:617-628`) - **Never modify a request's messages or tools.** The slices are copies, the values inside are not. (Source: `weft/core/model.go:149-157`) - **Wrap `ErrUnsupported` rather than dropping a part.** A silently dropped file changes what the model sees; the error lets the caller fall back. (Source: AGENTS.md rule 2, `weft/core/errors.go:64-69`) - **Ask `WantsRaw` before buffering a body.** Raw records exist only in development with a destination that wants them. (Source: `weft/core/report.go:202-215`) ### See also - [Connect a model provider: OpenAI, Anthropic, Gemini](https://weftgo.dev/docs/guides/providers/) - [Prove a provider adapter with the conformance suite](https://weftgo.dev/docs/testing/conformance/) - [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/) - [Test an agent with a scripted model](https://weftgo.dev/docs/testing/scripted-models/) Symbols used: [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.ModelEvent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelEvent) · [`weft.ModelTextDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelTextDelta) · [`weft.ModelReasoningDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelReasoningDelta) · [`weft.ModelToolCall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelToolCall) · [`weft.ModelToolCallDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelToolCallDelta) · [`weft.ModelFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelFinish) · [`weft.ModelInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelInfo) · [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) · [`weft.Unwrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Unwrap) · [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.ErrModelContract`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelContract) · [`weft.ErrUnsupported`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUnsupported) · [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow) · [`weft.ReportFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReportFromContext) · [`weft.Reporter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Reporter) · [`weft.RawPair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawPair) · [`wefttest.Raw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Raw) --- # Tool errors are data, run errors are yours URL: https://weftgo.dev/docs/concepts/errors/ Markdown: https://weftgo.dev/docs/concepts/errors.md > A failing tool call becomes an error result the model reads and the run continues; a model failure, cancellation or budget breach returns a *weft.RunError to the caller. weft has one error rule: a tool error is data the model sees, a run error is a Go error the caller sees. When a tool call fails (the handler returns an error or panics, the tool does not exist, the arguments do not decode, the call times out) the loop records an error result, the model reads it on its next step, and the call's siblings keep running. When the run itself cannot go on (the model call fails, `ctx` is canceled, a budget runs out) `Generate` returns a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) carrying the partial transcript. A handler gives the model a code to branch on with a [`*weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError), from `concepts/errors.go`: ```go title="concepts/errors.go" return weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in OrderLookup) (string, error) { if in.OrderID != "1234" { return "", &weft.ToolError{ Code: "ORDER_NOT_FOUND", Message: "order " + in.OrderID + " does not exist", Err: errNoRows, // for middleware and logs; the model never sees it } } return "order 1234: shipped", nil }) ``` [concepts/errors.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/errors.go) For order 42 the model reads `ORDER_NOT_FOUND: order 42 does not exist`. The database error in `Err` stays out of the model's sight. ### How it works Every tool call ends in a [`weft.ToolResultPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolResultPart). A failure sets `IsError: true` and puts the failure's text in `Content`, so the model can correct course: retry with other arguments, try another tool, or tell the user. The run fails only for conditions the model cannot fix by itself, and then the caller decides. | Failure | Becomes | The run | |---|---|---| | Handler returns an error, or panics | An error result | continues | | Unknown tool, undecodable arguments | An error result with a code | continues | | Tool `Timeout` expires | An error result | continues | | A step hit `max_tokens` with tool calls | An error result per call | continues | | Model stream fails or breaks its contract | `*RunError` | fails | | `ctx` canceled or past its deadline | `*RunError` | fails | | `MaxSteps`, `UsageLimit`, `MaxModelRetries`, `DetectLoops` breached | `*RunError` | fails | | A `ToolSource` snapshot with a nil tool or a duplicate name | `*RunError` | fails | ![The ops-probe run of rw.flaky-infra on the waterfall: inventory_api marked retry 1/3, tax_service RATE_LIMITED, shipping_quote timed out at 300 ms and legacy_billing panicked, with the selected call's details in the drawer](https://weftgo.dev/docs/_astro/studio-run-flaky.light.esXYYcMg.webp) *Studio's run page for a run whose tools fail four ways — a retry, a coded error, a timeout and a panic — each recorded as that call's result.* ### Tool errors A handler that returns a plain error produces a result whose text is `err.Error()`. A handler that returns a `*weft.ToolError` produces `CODE: Message`: | Field | Role | |---|---| | `Code` | A stable code the model can branch on, `SCREAMING_SNAKE` by convention (`ORDER_NOT_FOUND`). Not validated. | | `Message` | What the model reads after the code. With no message the result is the code alone. | | `Err` | The internal cause, for middleware and logs through `errors.Is`, `errors.As` and [`Unwrap`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolError.Unwrap). Never shown to the model. | [`ToolError.Error`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolError.Error) returns that model-visible text. [`weft.Errorf(code, format, args...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Errorf) builds one with a formatted message: a `%w` verb sets `Err` as `fmt.Errorf` would, and several `%w` verbs keep every cause reachable. The wrapped error's text is part of the formatted message, so wrap only what the model may read. `mw.MapErrors` codes plain errors centrally instead of in each handler ([Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/)). The loop renders its own failures in the same shape. One step of `concepts/errors.go` fails three ways next to a call that succeeds: ```go title="concepts/errors.go" model := wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "lookup_order", Args: `{"order_id":"42"}`}, // the handler's ToolError wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}, // succeeds wefttest.Call{Name: "lookup_order", Args: `{"order_id":1234}`}, // a number, not a string wefttest.Call{Name: "refund_order", Args: `{}`}, // no such tool ), wefttest.Say("Order 1234 has shipped; order 42 does not exist."), ) res, err := weft.New(model, lookup).Generate(ctx, weft.Prompt("Where are orders 42 and 1234?")) if err != nil { return err // never reached: tool failures are results, the run succeeds } for _, r := range res.Steps[0].Results { fmt.Fprintf(w, "error=%-5v %s\n", r.IsError, r.Content) } ``` [concepts/errors.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/errors.go) ```text error=true ORDER_NOT_FOUND: order 42 does not exist error=false order 1234: shipped error=true INVALID_INPUT: tool "lookup_order": field "order_id": expected string, got number error=true NO_SUCH_TOOL: no tool named "refund_order" ``` Under the code, the loop's failures still match their sentinels: an unknown tool wraps [`weft.ErrNoSuchTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNoSuchTool) and bad arguments wrap [`weft.ErrInvalidToolInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidToolInput), so middleware branches with `errors.Is`. `agt.CallTool` returns the same errors to its caller instead of rendering them. Containment produces two more texts, neither of them coded: a panic becomes `tool "X" panicked: ` and an expired [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) becomes `tool "X" timed out after 10s`, with the configured duration. A result longer than `MaxResultBytes` (64 KiB by default) is cut on a rune boundary and ends with `…[truncated N bytes]`, where N is the number of bytes the model did not receive. The package example [`ExampleToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolError) shows a coded error and an invalid-input result side by side. ### Result codes The codes the loop writes are exported constants, so policy middleware produces the same strings without copying them: | Constant | Text | Written for | |---|---|---| | [`weft.CodeInvalidInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeInvalidInput) | `INVALID_INPUT` | Arguments that do not decode into the tool's input struct. | | [`weft.CodeNoSuchTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeNoSuchTool) | `NO_SUCH_TOOL` | A call naming a tool the agent does not have. | | [`weft.CodeDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeDenied) | `DENIED` | A call refused at the approval boundary (`DENIED: `, or `DENIED: no decision`) or by a policy middleware such as `mw.Allow`. A refused call carries the same `DENIED` code whoever refused it; the message after it differs. | | [`weft.CodeRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeRetry) | `RETRY` | `weft.ModelRetry`: an instruction to try again, not a failure report. | The package examples [`ExampleCodeDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-CodeDenied) and [`ExampleCodeNoSuchTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-CodeNoSuchTool) print the exact strings. ### Invalid arguments Bad arguments come back in the schema's own words: `INVALID_INPUT: tool "lookup_order": field "order_id": expected string, got number`. The expected type is read from the schema the tool advertised, walked along the field's path, so the message never names a Go type the model was not shown: a `[]byte` field says `expected string`, and an integer tagged `,string` says `expected string, got number`. Other decode failures name their rule: - Malformed JSON: `invalid JSON at offset N: …`, or `invalid JSON: unexpected end of input` for cut-off arguments. - Anything after the first JSON value: `trailing data after the JSON arguments`. - Valid JSON that is not an object, such as `[1]` or `"x"`: `expected object at the top level, got `, where `` is `array`, `string`, `number` or `bool`. So `[1]` reads `INVALID_INPUT: tool "lookup_order": expected object at the top level, got array`. Empty or `null` arguments are not refused: they decode as `{}`. - An undeclared field under [`weft.StrictInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StrictInput): `unknown field "x": not in the schema`. Undeclared fields are ignored by default, as `encoding/json` ignores them, because models add stray keys and a rejection costs a round trip. Turn on `StrictInput` where an ignored field would be a silent misreading of the call. ### Ask the model to retry [`weft.ModelRetry(hint)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRetry) is a tool error that asks the model to call again with the hint applied. It renders `RETRY: `. Return it when the arguments decode but are wrong in a way the model can fix: an ambiguous date, an id missing its prefix. ```go title="concepts/errors.go" return weft.Tool("track_shipment", "Track a shipment by its ship date.", func(ctx context.Context, in TrackInput) (string, error) { if _, err := time.Parse(time.DateOnly, in.Date); err != nil { return "", weft.ModelRetry("date must be ISO-8601, like 2026-10-18") } return "in transit", nil }) ``` [concepts/errors.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/errors.go) Given `18/10/2026`, the model reads `RETRY: date must be ISO-8601, like 2026-10-18`; the corrected call returns `in transit`. The loop counts `RETRY` results per tool name since that tool's last successful result: a success resets the count, and other error results neither count nor reset it. When a tool's count passes [`weft.MaxModelRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries) (3 by default), the run fails with `ErrModelRetriesExceeded` at the next continuation point: with the default, the fourth `RETRY` since the tool last succeeded. Two parallel calls to the same tool that both retry count as two, and a `RETRY` from middleware counts like a handler's. [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/#model-retries) has the budget side. ### Run errors Every run failure is a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError), and `Generate` returns a nil result beside it: | Field | What it holds | |---|---| | `Step` | The step at which the run failed. For `ErrMaxSteps` it is the step that would have come next: `n` for `MaxSteps(n)`, one past the last step's index. | | `Err` | The cause. `RunError` unwraps to it, so `errors.Is(err, weft.ErrMaxSteps)` works on the returned error. | | `Result` | The `RunResult` up to the failure: transcript, steps, usage, and any calls still pending. Partial work is never lost. | ```go title="concepts/errors.go" _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) var re *weft.RunError if errors.As(err, &re) { fmt.Fprintln(w, err) fmt.Fprintln(w, "the provider's error:", errors.Is(err, errProviderDown)) fmt.Fprintln(w, "kept:", len(re.Result.Messages), "messages,", re.Result.NumSteps(), "step(s)") } ``` [concepts/errors.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/errors.go) ```text weft: run failed at step 1: model stream: provider unavailable the provider's error: true kept: 3 messages, 1 step(s) ``` The first step's tool call and its result survive on `re.Result`. Branch on the cause with `errors.Is` against the sentinels (`ErrMaxSteps`, `ErrUsageLimit`, `ErrModelContract`, `context.Canceled`, …), never by matching the text. ### Context overflow [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow) is the run error for a request that exceeds the model's context window. The OpenAI, Anthropic and Google adapters all wrap their provider's overflow error in it, keeping both links: `errors.Is` finds the sentinel and `errors.As` still reaches the vendor SDK's error. The same bytes can never succeed, so `mw.Retry` never retries it; `weft/thread` answers it by compacting the session and re-running once ([Keep long sessions inside the context window](https://weftgo.dev/docs/sessions/compaction/)). ### What it does not do - **A tool error never fails the run by itself.** Only the budgets above turn repeated tool failures into a run failure; otherwise the model decides what a failure means. - **The cause never reaches the model.** `ToolError.Err` and a plain error's wrapped chain are for your logs; only the rendered text is sent. - **A run error is not retried.** Retrying a failed model call is `mw.Retry`'s job, inside the model chain, before the step fails. ### Complete example `concepts/errors.go` runs the four tool outcomes, a corrected and an uncorrected retry, and a run whose model fails: ```go title="concepts/errors.go" package main import ( "context" "errors" "fmt" "io" "time" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // errNoRows stands in for a database's not-found error. var errNoRows = errors.New("pg: no rows in result set") // errProviderDown stands in for a provider outage. var errProviderDown = errors.New("provider unavailable") // TrackInput is track_shipment's input. type TrackInput struct { Date string `json:"date" jsonschema:"the ship date, YYYY-MM-DD"` } // failingLookup is lookup_order with a coded failure for unknown orders. func failingLookup() *weft.ToolDef { return weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in OrderLookup) (string, error) { if in.OrderID != "1234" { return "", &weft.ToolError{ Code: "ORDER_NOT_FOUND", Message: "order " + in.OrderID + " does not exist", Err: errNoRows, // for middleware and logs; the model never sees it } } return "order 1234: shipped", nil }) } // toolFailures runs one step with three failing calls beside one success. func toolFailures(ctx context.Context, w io.Writer) error { lookup := failingLookup() model := wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "lookup_order", Args: `{"order_id":"42"}`}, // the handler's ToolError wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}, // succeeds wefttest.Call{Name: "lookup_order", Args: `{"order_id":1234}`}, // a number, not a string wefttest.Call{Name: "refund_order", Args: `{}`}, // no such tool ), wefttest.Say("Order 1234 has shipped; order 42 does not exist."), ) res, err := weft.New(model, lookup).Generate(ctx, weft.Prompt("Where are orders 42 and 1234?")) if err != nil { return err // never reached: tool failures are results, the run succeeds } for _, r := range res.Steps[0].Results { fmt.Fprintf(w, "error=%-5v %s\n", r.IsError, r.Content) } return nil } // trackShipment is a tool that asks the model to fix its arguments. func trackShipment() *weft.ToolDef { return weft.Tool("track_shipment", "Track a shipment by its ship date.", func(ctx context.Context, in TrackInput) (string, error) { if _, err := time.Parse(time.DateOnly, in.Date); err != nil { return "", weft.ModelRetry("date must be ISO-8601, like 2026-10-18") } return "in transit", nil }) } // retries shows a corrected retry, then a model that never corrects itself. func retries(ctx context.Context, w io.Writer) error { fixes := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "track_shipment", Args: `{"date":"18/10/2026"}`}), wefttest.ToolCalls(wefttest.Call{Name: "track_shipment", Args: `{"date":"2026-10-18"}`}), wefttest.Say("Your shipment is in transit."), ) res, err := weft.New(fixes, trackShipment()).Generate(ctx, weft.Prompt("Where is my parcel?")) if err != nil { return err } fmt.Fprintln(w, res.Steps[0].Results[0].Content) fmt.Fprintln(w, res.Steps[1].Results[0].Content) stuck := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "track_shipment", Args: `{"date":"yesterday"}`}), wefttest.ToolCalls(wefttest.Call{Name: "track_shipment", Args: `{"date":"last week"}`}), wefttest.ToolCalls(wefttest.Call{Name: "track_shipment", Args: `{"date":"soon"}`}), wefttest.Say("never reached"), ) _, err = weft.New(stuck, trackShipment(), weft.MaxModelRetries(2)).Generate(ctx, weft.Prompt("Where is my parcel?")) fmt.Fprintln(w, "ErrModelRetriesExceeded:", errors.Is(err, weft.ErrModelRetriesExceeded)) return nil } // runFailure shows a run error and the partial transcript it carries. func runFailure(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Fail(errProviderDown), // the second model call fails ) agt := weft.New(model, failingLookup()) _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) var re *weft.RunError if errors.As(err, &re) { fmt.Fprintln(w, err) fmt.Fprintln(w, "the provider's error:", errors.Is(err, errProviderDown)) fmt.Fprintln(w, "kept:", len(re.Result.Messages), "messages,", re.Result.NumSteps(), "step(s)") } return nil } // demoErrors runs the tool failures, the retries and a failed run. func demoErrors(ctx context.Context, w io.Writer) error { if err := toolFailures(ctx, w); err != nil { return err } if err := retries(ctx, w); err != nil { return err } return runFailure(ctx, w) } ``` [concepts/errors.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/errors.go) Run it from `docs-site/examples`: ```sh go run ./concepts errors go test ./concepts ``` ```text error=true ORDER_NOT_FOUND: order 42 does not exist error=false order 1234: shipped error=true INVALID_INPUT: tool "lookup_order": field "order_id": expected string, got number error=true NO_SUCH_TOOL: no tool named "refund_order" RETRY: date must be ISO-8601, like 2026-10-18 in transit ErrModelRetriesExceeded: true weft: run failed at step 1: model stream: provider unavailable the provider's error: true kept: 3 messages, 1 step(s) ``` ### Best practices & gotchas - **Give the model a code for every failure it should handle.** A `ToolError` code is a stable string to branch on; a plain error's text may change with a library upgrade. (Source: `weft/core/errors.go:135-148`) - **Keep secrets out of `Message` and out of `%w` causes in `weft.Errorf`.** Both become model-visible text; only `Err` set directly stays hidden. (Source: `weft/core/errors.go:163-180`) - **Use `ModelRetry` for fixable arguments, a coded error for facts.** `RETRY` counts toward `MaxModelRetries`; `ORDER_NOT_FOUND` does not. (Source: `weft/core/errors.go:198-214`) - **Read `RunError.Result`, not the nil `res`.** The partial transcript is only on the error. (Source: `weft/core/loop.go:264-274`) - **Use the exported codes in policy middleware.** `weft.CodeDenied` keeps a refusal identical to the approval boundary's. (Source: CHANGELOG 0.2.0, `weft/core/tool.go:266-283`) ### See also - [Add behaviour with middleware (the two seams)](https://weftgo.dev/docs/guides/middleware/) - [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/) - [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/) - [Survive flaky infrastructure](https://weftgo.dev/docs/examples/flaky-infrastructure/) Symbols used: [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`weft.Errorf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Errorf) · [`weft.ModelRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRetry) · [`weft.MaxModelRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.ToolResultPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolResultPart) · [`weft.CodeInvalidInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeInvalidInput) · [`weft.CodeNoSuchTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeNoSuchTool) · [`weft.CodeDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeDenied) · [`weft.CodeRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeRetry) · [`weft.ErrNoSuchTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNoSuchTool) · [`weft.ErrInvalidToolInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidToolInput) · [`weft.ErrModelRetriesExceeded`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRetriesExceeded) · [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow) · [`weft.StrictInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StrictInput) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`wefttest.Fail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Fail) --- # How does a run stop? URL: https://weftgo.dev/docs/concepts/budgets-and-stopping/ Markdown: https://weftgo.dev/docs/concepts/budgets-and-stopping.md > A run ends successfully at its intended end — a final answer, a StopWhen condition, or pending approvals — and fails with a sentinel error when a safety budget runs out or its context is canceled. A run stops in one of two ways. It **ends successfully** at its intended end: the model answers without calling a tool, a [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) condition matches, or calls are waiting for approval. It **fails** with a sentinel error, such as `ErrMaxSteps`, when a safety budget runs out ([`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps), [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit), [`weft.MaxModelRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries), [`weft.DetectLoops`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#DetectLoops)) or its context is canceled. Reaching a budget is never a quiet success. The intended end, from `concepts/budgets.go`: the run is over once the model calls `submit`: ```go title="concepts/budgets.go" submit := weft.Tool("submit", "Submit the final answer.", func(ctx context.Context, in SubmitInput) (string, error) { return "recorded", nil }) agt := weft.New(model, submit, weft.StopWhen(weft.HasToolCall("submit"))) for ev, err := range agt.Stream(ctx, weft.Prompt("Answer, then submit.")).Events() { if err != nil { return err } if fin, ok := ev.(weft.RunFinish); ok { fmt.Fprintln(w, "stopped by:", fin.StoppedBy, "after", fin.Steps, "step(s)") } } ``` [concepts/budgets.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/budgets.go) ```text stopped by: has_tool_call:submit after 1 step(s) ``` The step that called `submit` runs its tools, then the run ends without another model call. ### How it works After each step's tool calls have run, the loop asks, in order: are calls pending approval? Does a `StopWhen` condition match? Did the model make no tool calls? Any yes ends the run with `RunFinish`, so a final answer that also matches a condition reports the condition. One exception: when a steering source delivers a message at what would be the final step, the run takes one more step instead of ending ([Steer a running turn](https://weftgo.dev/docs/guides/steering/)); pending approvals and `StopWhen` ends are never redirected. Otherwise the loop has reached the continuation point, where it would spend more, and checks the budgets there: `MaxModelRetries`, then `UsageLimit`, then `DetectLoops`, first breach wins. `MaxSteps` bounds the loop itself. Budgets fail only at the continuation point. A step that ends the run succeeds even if it overshot a budget, because a budget's job is to stop further spend, not to discard finished work. ### What stopped a run Every run records what ended it. [`RunFinish.StoppedBy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) and the `invoke_agent` span's `weft.run.stopped_by` attribute carry the same value: | Value | Ended by | Outcome | |---|---|---| | `final_answer` | A step with no tool calls | success | | `has_tool_call:`, `step_count_is:`, `output_submitted` | That `StopWhen` condition | success | | a custom condition's `String()`, else `custom` | A custom `StopWhen` condition | success | | `parked` | Calls pending approval | success | | `max_steps`, `usage_limit`, `loop_detected`, `model_retries_exceeded` | That budget | failure (span only) | | `canceled` | The run's `ctx` | failure (span only) | A failed run has no `RunFinish`, so the failure values exist only on the span. A run that failed for another reason, such as a model error, has no `stopped_by`; its span's `error.type` names the cause. ### Stop when [`weft.StopWhen(conds...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) adds stop conditions; the run ends when any one matches. Without it, a run ends when the model replies without requesting tools. A [`weft.StopCondition`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopCondition) is one method, `Stop(steps []StepRecord) bool`, called after a step's tool calls have run with every step so far; the last element is the step just finished. - [`weft.HasToolCall(names...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#HasToolCall) matches once the step just finished called any named tool: the final-answer-tool pattern. It checks only the call, not its result, so a `submit` call that failed (bad arguments, a handler error) ends the run too, successfully, with the `INVALID_INPUT` or error result as the last message and no step left for the model to repair it. `weft.Output[T]` ends only on a valid submission. After such a stop, `res.Text()` holds only text the model wrote beside the call, often `""`: the answer is the call's arguments on `res.Steps[len(res.Steps)-1].ToolCalls`, and the handler's return on that step's `Results`. - [`weft.StepCountIs(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepCountIs) matches after `n` steps, successfully, where reaching `MaxSteps` is a failure. - [`weft.StopFunc`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopFunc) adapts an ordinary `func([]StepRecord) bool`, the `http.HandlerFunc` shape; its `Stop` method calls the function. Conditions see `StepRecord.Results`, so a custom one can wait for a tool's result. The built-ins implement `fmt.Stringer`, which is how the manifest and `StoppedBy` name them; give a custom condition a `String()` method to name it too. `weft.Output[T]` registers its own condition, `output_submitted` ([Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/)). ### Max steps [`weft.MaxSteps(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) is the safety budget behind `ErrMaxSteps`: the most model calls a run may make, 10 by default. When the model still requests tools after the last allowed step, the run fails with [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps), the whole transcript (the last step's tool results included) on the `RunError`: ```go title="concepts/budgets.go" agt := weft.New(model, checkOrder(), weft.MaxSteps(3)) _, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships.")) var re *weft.RunError if errors.As(err, &re) && errors.Is(err, weft.ErrMaxSteps) { fmt.Fprintln(w, err) fmt.Fprintln(w, "kept:", re.Result.NumSteps(), "steps,", len(re.Result.Messages), "messages") } ``` [concepts/budgets.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/budgets.go) ```text weft: run failed at step 3: weft: run exceeded the maximum number of steps kept: 3 steps, 7 messages ``` Use `StopWhen` for the end you intend and `MaxSteps` for the one you do not. Values below 1 are ignored. As a run option `weft.MaxSteps` may only lower the agent's value; a raise fails with `ErrInvalidRunOption` before any model call. If the run is canceled during its last step's tools, it fails with the cancellation, not `ErrMaxSteps`: the cause wins over the budget. ### Usage limit `weft.UsageLimit(max)` bounds a run's total tokens: its own model calls plus every [subagent's](https://weftgo.dev/docs/reference/glossary/#subagent), as `RunResult.Usage` sums them. A field left zero is unlimited, and there is no default limit. Past the limit, the run fails with [`weft.ErrUsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUsageLimit), wrapped with the numbers: ```go title="concepts/budgets.go" researcher := weft.New(researchModel, weft.Name("researcher")) lead := weft.New(leadModel, weft.Subagent("research", "Research a topic in depth.", researcher), weft.UsageLimit(weft.Usage{OutputTokens: 8}), // the run's own calls plus every subagent's ) _, err := lead.Generate(ctx, weft.Prompt("Why are shipments late?")) var re *weft.RunError if errors.As(err, &re) && errors.Is(err, weft.ErrUsageLimit) { fmt.Fprintln(w, err) fmt.Fprintln(w, "own step:", re.Result.Steps[0].Usage.OutputTokens, "output tokens; with the subagent:", re.Result.Usage.OutputTokens) } ``` [concepts/budgets.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/budgets.go) ```text weft: run failed at step 0: weft: run exceeded its usage limit (input 20/0, output 10/8) own step: 5 output tokens; with the subagent: 10 ``` The lead's own model call spent 5 output tokens, under the limit; the research subagent's 5 more pushed the run over. The limit counts a child's usage but cannot stop a running child. A delegation is one tool call in one of the lead's steps, and the lead checks its limit only before its next model call. The child runs to its own end first, bounded by its own agent's `MaxSteps` and `UsageLimit`, and every delegation of that step runs. A lead with `UsageLimit{OutputTokens: 6}` delegated once to a child that made 7 model calls; only then did the lead fail with `output 40/6`. The same child with its own `UsageLimit{OutputTokens: 6}` stopped after 2 calls. `Usage.Total()` is not a separate limit: to bound the total, set both fields. A `thread/pool` child is a session, not a tool-call child: its usage is not on the parent run's `Usage`, so `UsageLimit` does not cover it ([Run bounded child sessions with a pool](https://weftgo.dev/docs/sessions/pools/)). ### Model retries [`weft.MaxModelRetries(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries) bounds how many `RETRY` results one tool may produce in a run since its last successful result, 3 by default. Past it, the run fails with [`weft.ErrModelRetriesExceeded`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRetriesExceeded): a model that cannot correct itself is a failure, not an endless loop. The count is per tool name; a successful result for the tool resets it, other error results neither count nor reset it, and calls resumed under `Approve` do not count. [Ask the model to retry](https://weftgo.dev/docs/concepts/errors/#ask-the-model-to-retry) shows the `RETRY` side. ### Detect loops `weft.DetectLoops(repeats)` fails a run with [`weft.ErrLoopDetected`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrLoopDetected) when `repeats` consecutive steps request the same set of tool calls: the same names with the same raw argument bytes, in any order. It is off by default, and values below 2 are ignored. ```go title="concepts/budgets.go" agt := weft.New(model, checkOrder(), weft.DetectLoops(3)) _, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships.")) fmt.Fprintln(w, err) ``` [concepts/budgets.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/budgets.go) ```text weft: run failed at step 2: weft: the model repeated the same tool calls too many times: 3 identical steps in a row ``` Results are not part of the comparison, so a tool whose output carries a timestamp cannot hide a loop. Different arguments are not a loop: a corrected retry has a different signature. ### Stop reasons Each model call ends with a [`weft.StopReason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopReason), recorded on `StepRecord.StopReason`, on `StepFinish.Reason`, and for the last step on `RunResult.StopReason`: | Constant | Value | Meaning | |---|---|---| | [`weft.StopEndTurn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopEndTurn) | `stop` | The model finished its turn. | | [`weft.StopToolCalls`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopToolCalls) | `tool_calls` | The model stopped to call tools. | | [`weft.StopMaxTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopMaxTokens) | `max_tokens` | The output hit the token limit. | When the provider's own reason did not map exactly (`refusal`, `content_filter`, …), it is kept beside the mapped one in `StepRecord.RawStopReason`. ### Truncation is visible A `max_tokens` finish never passes silently: - **Text only:** the run succeeds with `RunResult.StopReason` set to `StopMaxTokens`. The caller decides what truncated text means. - **With tool calls:** none of the calls runs, because an intact-looking call may be the first of several the model never finished. Each gets the error result `tool call was not executed: the response hit the output token limit`, and the loop continues so the model retries with a full budget. ```go title="concepts/budgets.go" cut := wefttest.Raw( // the response hit max_tokens after one tool call weft.ModelToolCall{ID: "call_1", Name: "check_order", Args: json.RawMessage(`{"order_id":"1234"}`)}, weft.ModelFinish{Reason: weft.StopMaxTokens}, ) agt := weft.New(wefttest.Script(cut, wefttest.Say("Order 1234 is still processing.")), checkOrder()) res, err := agt.Generate(ctx, weft.Prompt("Is order 1234 ready?")) if err != nil { return err } fmt.Fprintln(w, res.Steps[0].Results[0].Content) fmt.Fprintln(w, "steps:", res.NumSteps(), "final stop reason:", res.StopReason) ``` [concepts/budgets.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/budgets.go) ```text tool call check_order was not executed: the response hit the output token limit steps: 2 final stop reason: stop ``` The same rule makes long tool results visible: a result past `MaxResultBytes` ends with a marker naming the bytes cut. ### Cancel with a cause A canceled `ctx` fails the run with a `*RunError` matching `context.Canceled` (or `context.DeadlineExceeded`). No event follows the cancellation, and the partial transcript is on `RunError.Result`. To say *why* the run was canceled, cancel through `context.WithCancelCause` with a [`weft.CancelCause`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CancelCause): ```go title="concepts/budgets.go" ctx, cancel := context.WithCancelCause(ctx) cancel(weft.CancelCause("app.shutdown")) // e.g. on SIGTERM _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, "context.Canceled:", errors.Is(err, context.Canceled)) fmt.Fprintln(w, "cause:", context.Cause(ctx)) ``` [concepts/budgets.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/budgets.go) ```text context.Canceled: true cause: context canceled: app.shutdown ``` The run's error is unchanged, still the context's. Its `invoke_agent` span records `weft.cancel.cause` = `app.shutdown` beside `weft.run.stopped_by` = `canceled`, so Studio shows who canceled it. The loop records any cause with a `Kind() string` method, so a layer may bring its own type; a deadline reads `deadline`, and a cancel with no cause records none. `CancelCause` is a string type, a short, low-cardinality dotted name. [`Kind()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#CancelCause.Kind) returns it, [`Error()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#CancelCause.Error) returns `context canceled: `, and [`Is`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#CancelCause.Is) reports it as `context.Canceled`. weft's own layers pass theirs: `weft/thread` cancels a turn with `thread.interrupted` or `thread.closed`, and `weft/runtime` with `studio.cancel` or `app.shutdown`. The core example [`ExampleCancelCause`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-CancelCause) is this snippet. Cancellation wins everywhere, at the approval boundary too: a run canceled while calls are parked fails with the cancellation error, and the parked calls stay resumable on `RunError.Result.Pending`. ### Complete example `concepts/budgets.go` runs each way a run stops: ```go title="concepts/budgets.go" package main import ( "context" "encoding/json" "errors" "fmt" "io" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // SubmitInput is the submit tool's input. type SubmitInput struct { Answer string `json:"answer" jsonschema:"the final answer"` } // CheckInput is the check_order tool's input. type CheckInput struct { OrderID string `json:"order_id"` } // checkOrder is a tool the scripted models below call again and again. func checkOrder() *weft.ToolDef { return weft.Tool("check_order", "Check an order's status.", func(ctx context.Context, in CheckInput) (string, error) { return "still processing", nil }) } // stopOnSubmit ends the run on its intended end: the submit call. func stopOnSubmit(ctx context.Context, w io.Writer, model weft.Model) error { submit := weft.Tool("submit", "Submit the final answer.", func(ctx context.Context, in SubmitInput) (string, error) { return "recorded", nil }) agt := weft.New(model, submit, weft.StopWhen(weft.HasToolCall("submit"))) for ev, err := range agt.Stream(ctx, weft.Prompt("Answer, then submit.")).Events() { if err != nil { return err } if fin, ok := ev.(weft.RunFinish); ok { fmt.Fprintln(w, "stopped by:", fin.StoppedBy, "after", fin.Steps, "step(s)") } } return nil } // exhaustSteps runs into the step budget. func exhaustSteps(ctx context.Context, w io.Writer, model weft.Model) error { agt := weft.New(model, checkOrder(), weft.MaxSteps(3)) _, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships.")) var re *weft.RunError if errors.As(err, &re) && errors.Is(err, weft.ErrMaxSteps) { fmt.Fprintln(w, err) fmt.Fprintln(w, "kept:", re.Result.NumSteps(), "steps,", len(re.Result.Messages), "messages") } return nil } // overBudget runs a lead agent whose subagent pushes the run past its // token budget. func overBudget(ctx context.Context, w io.Writer, leadModel, researchModel weft.Model) error { researcher := weft.New(researchModel, weft.Name("researcher")) lead := weft.New(leadModel, weft.Subagent("research", "Research a topic in depth.", researcher), weft.UsageLimit(weft.Usage{OutputTokens: 8}), // the run's own calls plus every subagent's ) _, err := lead.Generate(ctx, weft.Prompt("Why are shipments late?")) var re *weft.RunError if errors.As(err, &re) && errors.Is(err, weft.ErrUsageLimit) { fmt.Fprintln(w, err) fmt.Fprintln(w, "own step:", re.Result.Steps[0].Usage.OutputTokens, "output tokens; with the subagent:", re.Result.Usage.OutputTokens) } return nil } // repeating runs a model that asks for the same call every step. func repeating(ctx context.Context, w io.Writer, model weft.Model) error { agt := weft.New(model, checkOrder(), weft.DetectLoops(3)) _, err := agt.Generate(ctx, weft.Prompt("Tell me when order 1234 ships.")) fmt.Fprintln(w, err) return nil } // truncated runs a step whose tool call was cut off by the output-token // limit. func truncated(ctx context.Context, w io.Writer) error { cut := wefttest.Raw( // the response hit max_tokens after one tool call weft.ModelToolCall{ID: "call_1", Name: "check_order", Args: json.RawMessage(`{"order_id":"1234"}`)}, weft.ModelFinish{Reason: weft.StopMaxTokens}, ) agt := weft.New(wefttest.Script(cut, wefttest.Say("Order 1234 is still processing.")), checkOrder()) res, err := agt.Generate(ctx, weft.Prompt("Is order 1234 ready?")) if err != nil { return err } fmt.Fprintln(w, res.Steps[0].Results[0].Content) fmt.Fprintln(w, "steps:", res.NumSteps(), "final stop reason:", res.StopReason) return nil } // cancelled runs an agent under a context cancelled with a cause. opts // are added to the agent (the test passes a recording TracerProvider). func cancelled(ctx context.Context, w io.Writer, opts ...weft.Option) error { agt := weft.New(wefttest.Script(wefttest.Say("never sent")), opts...) ctx, cancel := context.WithCancelCause(ctx) cancel(weft.CancelCause("app.shutdown")) // e.g. on SIGTERM _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, "context.Canceled:", errors.Is(err, context.Canceled)) fmt.Fprintln(w, "cause:", context.Cause(ctx)) return nil } // checking scripts n steps that each call check_order; distinct makes the // arguments differ from step to step. func checking(n int, distinct bool) *wefttest.Model { turns := make([]wefttest.Turn, 0, n+1) for i := range n { id := "1234" if distinct { id = fmt.Sprintf("1234-%d", i) } turns = append(turns, wefttest.ToolCalls(wefttest.Call{Name: "check_order", Args: `{"order_id":"` + id + `"}`})) } turns = append(turns, wefttest.Say("Order 1234 shipped.")) return wefttest.Script(turns...) } // demoBudgets runs each way a run stops. func demoBudgets(ctx context.Context, w io.Writer) error { submit := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "submit", Args: `{"answer":"Order 1234 shipped."}`}), wefttest.Say("never reached: StopWhen ended the run"), ) if err := stopOnSubmit(ctx, w, submit); err != nil { return err } if err := exhaustSteps(ctx, w, checking(3, true)); err != nil { return err } lead := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"shipping delays this week"}`}), wefttest.Say("never reached: the budget stopped the run"), ) research := wefttest.Script(wefttest.Say("Port congestion.")) if err := overBudget(ctx, w, lead, research); err != nil { return err } if err := repeating(ctx, w, checking(3, false)); err != nil { return err } if err := truncated(ctx, w); err != nil { return err } return cancelled(ctx, w) } ``` [concepts/budgets.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/budgets.go) Run it from `docs-site/examples`: ```sh go run ./concepts budgets go test ./concepts ``` ```text stopped by: has_tool_call:submit after 1 step(s) weft: run failed at step 3: weft: run exceeded the maximum number of steps kept: 3 steps, 7 messages weft: run failed at step 0: weft: run exceeded its usage limit (input 20/0, output 10/8) own step: 5 output tokens; with the subagent: 10 weft: run failed at step 2: weft: the model repeated the same tool calls too many times: 3 identical steps in a row tool call check_order was not executed: the response hit the output token limit steps: 2 final stop reason: stop context.Canceled: true cause: context canceled: app.shutdown ``` ### Best practices & gotchas - **Give every agent an intended end.** A final-answer tool with `StopWhen(HasToolCall(...))` ends on purpose; relying on `MaxSteps` turns the end into an error. (Source: deep dive §4, `weft/core/agent.go:100-108`) - **Check the final tool's result, or use `weft.Output[T]`.** `HasToolCall("submit")` fires on a `submit` call with bad arguments: `err` is nil, the run took one step, and the last message is `INVALID_INPUT: tool "submit": field …`. When the final answer must be valid, use `weft.Output[T]`, whose `output_submitted` condition waits for a submission without an error and lets the model repair a bad one first. Otherwise check the last result's `IsError` yourself. Valid means it decodes: a field the submission leaves out arrives as its zero value, so check required fields after `GenerateAs` ([structured output](https://weftgo.dev/docs/guides/structured-output/#best-practices--gotchas)). (Source: `weft/core/agent.go:577-588`, `weft/core/output.go:101-112`) - **Do not read a final-answer tool's answer with `res.Text()`.** The run ends on the tool message, so `res.Text()` is the text beside the call, usually `""`. Read the last step's `ToolCalls` or `Results`, or use `weft.Output[T]` with `weft.GenerateAs`. (Source: `weft/core/run.go:714-721`, `weft/core/agent.go:577-588`) - **Expect a budget to overshoot by one step, and a step to hold whole child runs.** Limits are checked after a step, so the run that breaches `UsageLimit` has already spent the step that breached it. A step that delegates includes each child's whole run, so the overshoot can be several child runs. Bound each child with its own `UsageLimit` and `MaxSteps`. (Source: AGENTS.md rule 13, `weft/core/agent.go:114-125`; `weft/core/loop.go:849, 1102-1116`) - **Set both `UsageLimit` fields to bound the total.** `Total()` is not a limit of its own. (Source: `weft/core/agent.go:122-124`) - **Consider `DetectLoops` where a model may repeat itself.** It is off by default, so a model stuck on the same calls spends steps until `MaxSteps`. (Source: `weft/core/agent.go:180-187`) - **Check `res.StopReason` on success.** `StopMaxTokens` there means the answer was cut off, and the run still returned nil. (Source: AGENTS.md rule 8) - **Cancel with a `CancelCause` in your own shutdown paths.** A plain `cancel()` leaves the record without a reason. (Source: `weft/core/observe.go:845-859`) ### See also - [Guard against runaway agents](https://weftgo.dev/docs/examples/budget-guards/) - [Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/) - [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/) - [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/) - [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/) Symbols used: [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) · [`weft.StopCondition`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopCondition) · [`weft.StopFunc`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopFunc) · [`weft.HasToolCall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#HasToolCall) · [`weft.StepCountIs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepCountIs) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) · [`weft.MaxModelRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries) · [`weft.DetectLoops`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#DetectLoops) · [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps) · [`weft.ErrUsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUsageLimit) · [`weft.ErrModelRetriesExceeded`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRetriesExceeded) · [`weft.ErrLoopDetected`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrLoopDetected) · [`weft.StopReason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopReason) · [`weft.CancelCause`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CancelCause) · [`weft.RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`wefttest.Raw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Raw) --- # weft guides URL: https://weftgo.dev/docs/guides/ Markdown: https://weftgo.dev/docs/guides.md > How-to guides for weft, one task per page: streaming, structured output, conversations, per-step and per-run configuration, steering, approvals, tools, providers, middleware, observers, metadata and the manifest. Each guide does one task with weft and ends with a complete program that runs offline, against a scripted model or (for providers) a local test server. The guides assume you have built an agent once ([Quickstart](https://weftgo.dev/docs/get-started/quickstart/)) and know what a run and a tool are ([Concepts](https://weftgo.dev/docs/concepts/)). Pick a guide by what you need to do. ### Run an agent and read the result - [Stream a run's events](https://weftgo.dev/docs/guides/streaming/): range over `Events()` to show progress, read the terminal error, stop early. - [Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/): constrain the final answer to a Go struct with `weft.Output`. - [Continue a conversation](https://weftgo.dev/docs/guides/conversations/): feed the transcript back with `weft.Messages` and store it between requests. ### Shape what a run does - [Rewrite the request each step (PrepareStep)](https://weftgo.dev/docs/guides/prepare-step/): trim messages, change the tools, the system prompt or sampling for each model call. - [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/): override instructions, narrow tools, switch the model, sample differently or force a tool call for a single run. - [Steer a running turn](https://weftgo.dev/docs/guides/steering/): deliver a user message into a run that is already going. - [Control reasoning (thinking)](https://weftgo.dev/docs/guides/thinking/): set a reasoning level for every run or for one. - [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/): park a call, end the run, resume it with a decision. ### Give an agent tools - [Set per-tool policy: timeouts, caps, ordering and strict input](https://weftgo.dev/docs/guides/tool-policy/): one tool's own deadline, result cap, barrier, input rule or prompt snippet. - [Define tools at runtime: RawTool and ToolSource](https://weftgo.dev/docs/guides/dynamic-tools/): a tool with an explicit schema, or a catalogue that changes during a run. - [Delegate to another agent (subagents)](https://weftgo.dev/docs/guides/subagents/): run an agent as another agent's tool. - [Use MCP both ways](https://weftgo.dev/docs/guides/mcp/): import an MCP server's tools, or serve an agent as an MCP server. ### Work with models and providers - [Connect a model provider: OpenAI, Anthropic, Gemini](https://weftgo.dev/docs/guides/providers/): construct and configure the first-party adapters. - [Send images and files to a model](https://weftgo.dev/docs/guides/multimodal/): mix text and files in one prompt. - [Add behaviour with middleware (the two seams)](https://weftgo.dev/docs/guides/middleware/): wrap the model and every tool call. - [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/): retry transient errors and switch to a backup model. ### Observe and describe your agents - [Observe a run without changing it: Tap, OnRunEnd, OnMessages](https://weftgo.dev/docs/guides/observers/): see every event, the outcome, or each batch of messages as it joins the transcript. - [Tag runs with metadata](https://weftgo.dev/docs/guides/metadata/): put tenant, user or request ids on every span and record of a run. - [Describe your agents in weft.json (the manifest)](https://weftgo.dev/docs/guides/manifest/): generate and golden-gate the manifest that Studio's Agents page reads. ### See also - [Concepts](https://weftgo.dev/docs/concepts/): what the core pieces are and how they behave - [Sessions](https://weftgo.dev/docs/sessions/): durable conversations with `weft/thread` - [Testing](https://weftgo.dev/docs/testing/): scripted models, record and replay - [Package weft on pkg.go.dev](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2) --- # Stream a run's events URL: https://weftgo.dev/docs/guides/streaming/ Markdown: https://weftgo.dev/docs/guides/streaming.md > Range over agt.Stream(...).Events() to handle a run's events as they happen, read the terminal error, and stop early without leaking the run. [`agt.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) starts a run and returns a [`*weft.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Run); ranging over [`run.Events()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Events) yields each event as the loop emits it. A failed run yields its error once, as the last element; a successful run ends with `RunFinish`. Use it when a UI or log must show progress; use `agt.Generate` when only the result matters. The range in `streaming/main.go`, with a type switch over the events it handles: ```go title="streaming/main.go" run := agt.Stream(ctx, weft.Prompt("Where is order 1234?")) for ev, err := range run.Events() { if err != nil { return err // a failed run: non-nil at most once, as the last element } switch ev := ev.(type) { case weft.RunStart: fmt.Fprintln(w, "run started:", ev.Agent) case weft.StepStart: fmt.Fprintln(w, "step", ev.Index) case weft.ToolStart: fmt.Fprintf(w, " seq %d: %s %s\n", ev.Seq, ev.Name, ev.Args) case weft.ToolFinish: fmt.Fprintf(w, " seq %d: %s → %s (error: %t)\n", ev.Seq, ev.Name, ev.Content, ev.IsError) case weft.TextDelta: fmt.Fprintln(w, " text:", ev.Text) case weft.StepFinish: fmt.Fprintln(w, " finished:", ev.Reason) case weft.RunFinish: fmt.Fprintf(w, "run finished: %d steps, %d output tokens, stopped by %s\n", ev.Steps, ev.Usage.OutputTokens, ev.StoppedBy) } } ``` [streaming/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/streaming/main.go) The switch needs no `default`: an event type you do not name is skipped. The package example [`ExampleAgent_stream`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Agent-Stream) is the same loop over a dice-rolling tool. ### How it works `Stream` is lazy. Nothing runs until you range over `Events`, so you can read [`run.ID()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.ID) first and hand it to a client. Each `Events` call hands events over an unbuffered channel from the goroutine that runs the loop. Every run's first event is `RunStart`; a successful run's last is `RunFinish`. Tool events carry `Seq`, a per-run counter assigned under the same lock that emits them, so the order you observe is the order of `Seq`. Pair `ToolStart` and `ToolFinish` by `CallID` when tools run in parallel ([ADR 0004](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0004-event-ordering.md)). A `weft.Tap` on the agent sees the same events in the same order ([rule 3](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). Events are snapshots: you may keep them or write into them without touching the run's transcript. ### Stream events [`weft.Event`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Event) is a sealed interface. These are its types, in the order a run emits them: | Event | Fields | When | |---|---|---| | [`RunStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunStart) | `ID`, `Model`, `Agent`, `InstructionsHash` | First event of every run | | [`StepStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepStart) | `Index` | The model is being called for a step | | [`ReasoningDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReasoningDelta) | `Text` | Provider reasoning, in order with the text | | [`TextDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TextDelta) | `Text` | An increment of assistant text | | [`ToolArgsDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolArgsDelta) | `Name`, `Args` | The model is still writing a tool call; progress only | | [`ToolStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolStart) | `Seq`, `CallID`, `Name`, `Args` | A tool call began | | [`Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested) | `Seq`, `CallID`, `Event` | One event of a subagent's child run | | [`ToolFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolFinish) | `Seq`, `CallID`, `Name`, `Content`, `IsError` | A tool call completed; `Content` is what the model sees | | [`StepFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepFinish) | `Index`, `Reason`, `Usage`, `Raw`, `LatencyMS`, `TTFTMS` | The step's model call and tools are done | | [`Steered`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Steered) | `Seq`, `Step`, `Messages` | The run's steering source delivered messages | | [`RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) | `Usage`, `Steps`, `Pending`, `StoppedBy` | Last event of a successful run | Every event except `RunStart` also carries `RunID`. `ToolArgsDelta` arrives only from adapters that stream arguments: the OpenAI and Anthropic adapters emit it, and Gemini calls arrive whole. The assembled call still arrives as `ToolStart` when it executes. The `err` element is non-nil at most once, as the last element. It is the run error `agt.Generate` would return: a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) with the partial transcript on `.Result`. A failed run has no `RunFinish`. The [events reference](https://weftgo.dev/docs/reference/events/) lists every field. ### Close and wait [`run.Wait()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Wait) returns the run's `*RunResult` and error. After the range it returns at once; called on a run nobody ranged over, it runs the agent itself and discards the events. It is safe from another goroutine while the range runs: ```go title="streaming/main.go" run := agt.Stream(ctx, weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, "run id known before the first event:", run.ID() != "") for _, err := range run.Events() { if err != nil { return err } } res, err := run.Wait() // the stream is consumed; Wait returns its result if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text()) ``` [streaming/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/streaming/main.go) Breaking out of the range cancels the run. `Wait` then reports an error matching `context.Canceled`. A run you create with `Stream` and never consume holds a context; [`run.Close()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Close) cancels it and releases it: ```go title="streaming/main.go" run := agt.Stream(ctx, weft.Prompt("Where is order 1234?")) for ev, err := range run.Events() { if err != nil { return err } if _, ok := ev.(weft.ToolStart); ok { break // stopping the range cancels the run } } _, err := run.Wait() fmt.Fprintln(w, "stopped early, canceled:", errors.Is(err, context.Canceled)) // A run you start but never consume: Close releases it. abandoned := agt.Stream(ctx, weft.Prompt("Where is order 5678?")) defer abandoned.Close() ``` [streaming/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/streaming/main.go) `Close` is for abandoned runs only. A run you range over or `Wait` on needs no `Close`: `Events` and `Wait` release everything themselves. `Close` is safe to call any number of times, before or after consumption. ### Range over events once `Events` is single-use. A second call yields one element, [`weft.ErrRunConsumed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrRunConsumed), and nothing else: ```go title="streaming/main.go" run := agt.Stream(ctx, weft.Prompt("Where is order 1234?")) for range run.Events() { } for _, err := range run.Events() { // a second range yields only ErrRunConsumed fmt.Fprintln(w, "second range:", errors.Is(err, weft.ErrRunConsumed)) } ``` [streaming/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/streaming/main.go) To fan events out to several consumers, use one range and forward each event, or register a `weft.Tap` on the agent. ### Consume events promptly The hand-off is unbuffered, and tool events are emitted while the loop holds the step's ordering lock. A slow consumer does not only receive late: it delays emission and gates the start of the step's next tools. For parallel tools where latency matters, range in a dedicated goroutine that buffers, or use `Generate`, which needs no consumer. The package example [`ExampleTap_async`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Tap-Async) shows the same queue pattern for a slow tap. ### Complete example `streaming/main.go` runs each region against a scripted model that calls `lookup_order` once and then answers: ```go title="streaming/main.go" // Command streaming runs the examples of the guide "Stream a run's // events": go run ./streaming. The model is scripted with wefttest, so it // runs offline; swap in a provider adapter for a real one. package main import ( "context" "errors" "fmt" "io" "os" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } // newAgent returns an agent whose scripted model calls lookup_order once, // then answers. func newAgent() *weft.Agent { lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, in LookupInput) (string, error) { return "order " + in.OrderID + " has shipped", nil }) model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), ) return weft.New(model, weft.Name("support-bot"), lookup) } // streamEvents ranges over a run's events and prints each kind it handles. func streamEvents(ctx context.Context, w io.Writer, agt *weft.Agent) error { run := agt.Stream(ctx, weft.Prompt("Where is order 1234?")) for ev, err := range run.Events() { if err != nil { return err // a failed run: non-nil at most once, as the last element } switch ev := ev.(type) { case weft.RunStart: fmt.Fprintln(w, "run started:", ev.Agent) case weft.StepStart: fmt.Fprintln(w, "step", ev.Index) case weft.ToolStart: fmt.Fprintf(w, " seq %d: %s %s\n", ev.Seq, ev.Name, ev.Args) case weft.ToolFinish: fmt.Fprintf(w, " seq %d: %s → %s (error: %t)\n", ev.Seq, ev.Name, ev.Content, ev.IsError) case weft.TextDelta: fmt.Fprintln(w, " text:", ev.Text) case weft.StepFinish: fmt.Fprintln(w, " finished:", ev.Reason) case weft.RunFinish: fmt.Fprintf(w, "run finished: %d steps, %d output tokens, stopped by %s\n", ev.Steps, ev.Usage.OutputTokens, ev.StoppedBy) } } return nil } // streamThenWait consumes the events, then reads the result with Wait. func streamThenWait(ctx context.Context, w io.Writer, agt *weft.Agent) error { run := agt.Stream(ctx, weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, "run id known before the first event:", run.ID() != "") for _, err := range run.Events() { if err != nil { return err } } res, err := run.Wait() // the stream is consumed; Wait returns its result if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text()) return nil } // streamStopEarly breaks out of the range at the first tool call and // shows what the run reports. func streamStopEarly(ctx context.Context, w io.Writer, agt *weft.Agent) error { run := agt.Stream(ctx, weft.Prompt("Where is order 1234?")) for ev, err := range run.Events() { if err != nil { return err } if _, ok := ev.(weft.ToolStart); ok { break // stopping the range cancels the run } } _, err := run.Wait() fmt.Fprintln(w, "stopped early, canceled:", errors.Is(err, context.Canceled)) // A run you start but never consume: Close releases it. abandoned := agt.Stream(ctx, weft.Prompt("Where is order 5678?")) defer abandoned.Close() return nil } // streamTwice ranges over one run's events a second time. func streamTwice(ctx context.Context, w io.Writer, agt *weft.Agent) error { run := agt.Stream(ctx, weft.Prompt("Where is order 1234?")) for range run.Events() { } for _, err := range run.Events() { // a second range yields only ErrRunConsumed fmt.Fprintln(w, "second range:", errors.Is(err, weft.ErrRunConsumed)) } return nil } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer, *weft.Agent) error }{ {"events", streamEvents}, {"wait", streamThenWait}, {"stop early", streamStopEarly}, {"consume once", streamTwice}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w, newAgent()); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [streaming/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/streaming/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/streaming) · run it from `docs-site/examples`: ```sh go run ./streaming go test ./streaming ``` ```text == events run started: support-bot step 0 seq 1: lookup_order {"order_id":"1234"} seq 2: lookup_order → order 1234 has shipped (error: false) finished: tool_calls step 1 text: Order 1234 has shipped. finished: stop run finished: 2 steps, 10 output tokens, stopped by final_answer == wait run id known before the first event: true answer: Order 1234 has shipped. == stop early stopped early, canceled: true == consume once second range: true ``` ### Best practices & gotchas - **Check `err` on every element.** The error arrives as the last element of the range, at most once; a range that ignores it treats a failed run as finished. (Source: `weft/core/run.go:766-771`, AGENTS.md block 3b) - **Pair tool events by `CallID`, order them by `Seq`.** Parallel tools interleave; `Seq` is the total order. (Source: ADR 0004, `weft/core/events.go:66-70`) - **After a cancel, render tool outcomes from `RunError.Result`, not from events.** Delivery stops at cancellation, so a started tool may have no `ToolFinish`; the transcript on `RunError.Result` is the source of truth. (Source: ADR 0004, amendment 2026-09-09) - **Call `Close` on a run you abandon unconsumed.** Otherwise its context stays live until the parent context ends. (Source: `weft/core/run.go:822-826`, CHANGELOG 0.2.0) - **Keep the consumer fast.** A slow range gates the start of the step's later tools. (Source: `weft/core/run.go:760-768`, CHANGELOG 0.2.0) ### See also - [What does a run return?](https://weftgo.dev/docs/concepts/runs/) - [Event types](https://weftgo.dev/docs/reference/events/) - [Observe a run without changing it](https://weftgo.dev/docs/guides/observers/) - [Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/): partial values while a run streams - [Delegate to another agent](https://weftgo.dev/docs/guides/subagents/): `Nested` events Symbols used: [`Agent.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) · [`weft.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Run) · [`Run.Events`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Events) · [`Run.Wait`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Wait) · [`Run.Close`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Close) · [`Run.ID`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.ID) · [`weft.Event`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Event) · [`weft.ErrRunConsumed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrRunConsumed) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExampleAgent_stream`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Agent-Stream) --- # Get structured output from a run URL: https://weftgo.dev/docs/guides/structured-output/ Markdown: https://weftgo.dev/docs/guides/structured-output.md > Constrain a run's final answer to a Go struct with weft.Output, read it with GenerateAs or OutputOf, and render partial values with an OutputDecoder while it streams. [`weft.Output[T]()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Output) constrains a run's final answer to the struct `T`, and [`weft.GenerateAs[T]`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#GenerateAs) runs the agent and returns that answer decoded. It works on every provider, because the answer is a tool call: the model calls `submit_output` with `T`'s fields as arguments. In `output/main.go`, `Verdict` has two fields, `approved` (a `bool`) and `reason` (a `string` tagged `jsonschema:"one sentence"`): ```go title="output/main.go" agt := weft.New(model, weft.Instructions("Review refund requests."), weft.Output[Verdict]()) v, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?")) if err != nil { return err } fmt.Fprintln(w, "approved:", v.Approved, "reason:", v.Reason) ``` [output/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/output/main.go) `v` is a `Verdict`. `res` is the ordinary `*RunResult`, with the transcript and usage. ### How it works `Output[T]` registers a tool named `submit_output`. Its input schema is reflected from `T` the way [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) reflects a handler's input, and its description is model-visible contract text: `Submit your final answer. Call this exactly once, when you are done: the run ends with it.` A valid call's result is `recorded`. `Output` also adds the stop condition `output_submitted`. The run ends after the step in which a `submit_output` call produced a non-error result ([ADR 0008](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0008-structured-output.md)). An invalid submission is an ordinary tool error. Arguments that do not decode come back to the model as an `ErrInvalidToolInput` result naming the field, and the model calls again. In the example the model first sends `"approved":"yes"` and reads: ```text INVALID_INPUT: tool "submit_output": field "approved": expected boolean, got string ``` Its second call decodes, so the run takes two steps. Because repair is the tool-error loop, it needs no special handling and counts against `weft.MaxSteps` like any step. What is refused is a wrong type, malformed JSON or trailing data, and an undeclared field under `StrictInput`; a missing field is not. A field the submission leaves out decodes to its zero value and the run ends on it, `required` in the schema or not: `{"reason":"x"}` gives `Verdict{Approved: false, Reason: "x"}` with a nil error after one step ([How do tools work?](https://weftgo.dev/docs/concepts/tools/#edge-cases-in-schemas-and-arguments)). `T` must be a struct or a pointer to one: providers require an object schema at the top level. `Output` panics otherwise. Other tools still work beside it; `weft.New(model, weft.Output[Verdict](), lookup)` lets the model call `lookup` before it submits. ### Decode the output with GenerateAs `GenerateAs` calls `agt.Generate` and decodes the last `submit_output` call that had a non-error result. A run that ends without one, because the model answered in text, returns [`weft.ErrNoOutput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNoOutput) with the `*RunResult` still set, so the transcript is inspectable: ```go title="output/main.go" _, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?")) if errors.Is(err, weft.ErrNoOutput) { fmt.Fprintln(w, "no structured output; the model said:", res.Text()) } ``` [output/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/output/main.go) A run error, such as a model failure, is returned as `*RunError` the way `Generate` returns it, and the `*RunResult` return is nil; the partial transcript is on the error's `.Result`. A step-budget breach is such a run error: a model that still calls tools at `weft.MaxSteps` fails the run with a `*RunError` wrapping `weft.ErrMaxSteps`, not `ErrNoOutput`. The package example [`ExampleGenerateAs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-GenerateAs) is the one-step version. ### Read the output after a stream [`weft.OutputOf[T](res)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OutputOf) does the decode alone, for a run you streamed. Range over the events, take the result from `run.Wait()`, then decode: ```go title="output/main.go" run := agt.Stream(ctx, weft.Prompt("Refund order 7?")) for _, err := range run.Events() { if err != nil { return err } } res, err := run.Wait() if err != nil { return err } v, err := weft.OutputOf[Verdict](res) if err != nil { return err } fmt.Fprintln(w, "approved:", v.Approved, "reason:", v.Reason) ``` [output/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/output/main.go) `OutputOf` follows the same rule as `GenerateAs`: the newest `submit_output` call with a non-error result. It returns `ErrNoOutput` when there is none, or when the bytes do not decode into the type you pass, which means it differs from the type given to `Output`. ### Show partial output while it streams An [`OutputDecoder`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OutputDecoder) turns `submit_output`'s argument deltas into a filling-in `T`, for a UI that renders a form as the model writes it. Create one with [`weft.NewOutputDecoder[T]()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#NewOutputDecoder), pass it every event you already consume, and draw what [`Feed`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#OutputDecoder.Feed) returns: ```go title="output/main.go" run := agt.Stream(ctx, weft.Prompt("Refund order 42?")) dec := weft.NewOutputDecoder[Verdict]() for ev, err := range run.Events() { if err != nil { return err } if partial, ok := dec.Feed(ev); ok { fmt.Fprintf(w, "partial: approved=%t reason=%q\n", partial.Approved, partial.Reason) } } v, err := dec.Result() if err != nil { return err } fmt.Fprintf(w, "final: approved=%t reason=%q\n", v.Approved, v.Reason) ``` [output/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/output/main.go) ```text partial: approved=true reason="" partial: approved=true reason="within pol" partial: approved=true reason="within policy" final: approved=true reason="within policy" ``` `Feed` returns `ok == true` only when the partial changed. After each delta it decodes the longest closed prefix of the arguments so far: fields not yet written stay at their zero value, and a prefix that does not decode keeps the last good partial. Partials only grow. A later partial never holds fewer fields or array elements than an earlier one. A cut number shows its longest valid prefix (`12e` reads `12`), so a partial number can still change as digits arrive. A cut `true`, `false` or `null` is dropped and its key reads `null`, so the field holds its zero value. An array element still being written drops back to where it began. A string grows only by appending. A dangling escape, a cut rune or a high surrogate awaiting its pair is held back until it completes. It is never shown as a backslash or U+FFFD. It ignores every event except this run's `StepStart` and `submit_output`'s `ToolStart`, `ToolArgsDelta` and `ToolFinish`; `Nested` events from subagents are skipped. [`Result`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#OutputDecoder.Result) returns the completed submission by the `OutputOf` rule, or `ErrNoOutput` when no valid call finished. Errors surface only there. A second `submit_output` call within a step starts the buffer over, so `Result` follows the last call. Partials come from `ToolArgsDelta` events, which the OpenAI and Anthropic adapters stream. Gemini's calls arrive whole, so with the Google adapter the decoder reports one value, at `ToolStart`. The decoder is never model-visible: it reads the stream and writes nothing back. The package example is [`ExampleOutputDecoder`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-OutputDecoder). ### Repair malformed JSON arguments [`mw.RepairJSON`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RepairJSON) is model middleware that re-encodes a tool call's arguments once when they are not valid JSON. It strips a Markdown fence, with any language tag (` ```json `, ` ```JSON `, ` ```javascript `), and closes unterminated strings, objects and arrays; a run of trailing commas before the close is dropped. When the result parses, it replaces the original: ```go title="output/main.go" agt := weft.New(model, weft.Output[Verdict](), weft.WrapModel(mw.RepairJSON()), // strip fences, close cut-off JSON, once ) v, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?")) ``` [output/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/output/main.go) The scripted model in the example wraps its arguments in a ` ```json ` fence; with `RepairJSON` the run ends in one step. Arguments it cannot repair pass through unchanged, so the model still sees an `INVALID_INPUT` result. It touches tool-call events only, every tool's, not only `submit_output`'s. See [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) for where it sits in the chain. ### Complete example `output/main.go` runs every region against scripted models: ````go title="output/main.go" // Command output runs the examples of the guide "Get structured output // from a run": go run ./output. Every model is scripted with wefttest, so // it runs offline; swap in a provider adapter for a real one. package main import ( "context" "encoding/json" "errors" "fmt" "io" "os" "github.com/weftgo/weft" "github.com/weftgo/weft/mw" "github.com/weftgo/weft/wefttest" ) // Verdict is the run's final answer. Its tags become submit_output's schema. type Verdict struct { Approved bool `json:"approved"` Reason string `json:"reason" jsonschema:"one sentence"` } // generateAs: the first submission is invalid, the model repairs it, and // GenerateAs returns the decoded value. func generateAs(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "submit_output", Args: `{"approved":"yes","reason":"within policy"}`}), wefttest.ToolCalls(wefttest.Call{Name: "submit_output", Args: `{"approved":true,"reason":"within policy"}`}), ) agt := weft.New(model, weft.Instructions("Review refund requests."), weft.Output[Verdict]()) v, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?")) if err != nil { return err } fmt.Fprintln(w, "approved:", v.Approved, "reason:", v.Reason) fmt.Fprintln(w, "steps:", res.NumSteps()) fmt.Fprintln(w, "the model first read:", res.Steps[0].Results[0].Content) return nil } // noOutput: a run that ends in text returns ErrNoOutput with the result. func noOutput(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("Looks fine to me.")) agt := weft.New(model, weft.Output[Verdict]()) _, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?")) if errors.Is(err, weft.ErrNoOutput) { fmt.Fprintln(w, "no structured output; the model said:", res.Text()) } return nil } // outputOf: stream the run, then decode the output from its result. func outputOf(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "submit_output", Args: `{"approved":false,"reason":"past the refund window"}`}), ) agt := weft.New(model, weft.Output[Verdict]()) run := agt.Stream(ctx, weft.Prompt("Refund order 7?")) for _, err := range run.Events() { if err != nil { return err } } res, err := run.Wait() if err != nil { return err } v, err := weft.OutputOf[Verdict](res) if err != nil { return err } fmt.Fprintln(w, "approved:", v.Approved, "reason:", v.Reason) return nil } // decoder: render partial values while submit_output's arguments stream. func decoder(ctx context.Context, w io.Writer) error { turn := wefttest.Raw( weft.ModelToolCallDelta{Index: 0, Name: "submit_output", Args: `{"approved":true,`}, weft.ModelToolCallDelta{Index: 0, Name: "submit_output", Args: `"reason":"within pol`}, weft.ModelToolCallDelta{Index: 0, Name: "submit_output", Args: `icy"}`}, weft.ModelToolCall{ID: "c1", Name: "submit_output", Args: json.RawMessage(`{"approved":true,"reason":"within policy"}`)}, weft.ModelFinish{Reason: weft.StopToolCalls}, ) agt := weft.New(wefttest.Script(turn), weft.Output[Verdict]()) run := agt.Stream(ctx, weft.Prompt("Refund order 42?")) dec := weft.NewOutputDecoder[Verdict]() for ev, err := range run.Events() { if err != nil { return err } if partial, ok := dec.Feed(ev); ok { fmt.Fprintf(w, "partial: approved=%t reason=%q\n", partial.Approved, partial.Reason) } } v, err := dec.Result() if err != nil { return err } fmt.Fprintf(w, "final: approved=%t reason=%q\n", v.Approved, v.Reason) return nil } // repairJSON: a model that wraps its arguments in a Markdown fence. func repairJSON(ctx context.Context, w io.Writer) error { fenced := wefttest.Raw( weft.ModelToolCall{ID: "c1", Name: "submit_output", Args: json.RawMessage("```json\n{\"approved\":true,\"reason\":\"within policy\"}\n```")}, weft.ModelFinish{Reason: weft.StopToolCalls}, ) model := wefttest.Script(fenced) agt := weft.New(model, weft.Output[Verdict](), weft.WrapModel(mw.RepairJSON()), // strip fences, close cut-off JSON, once ) v, res, err := weft.GenerateAs[Verdict](ctx, agt, weft.Prompt("Refund order 42?")) if err != nil { return err } fmt.Fprintln(w, "approved:", v.Approved, "reason:", v.Reason, "steps:", res.NumSteps()) return nil } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"GenerateAs", generateAs}, {"ErrNoOutput", noOutput}, {"OutputOf", outputOf}, {"OutputDecoder", decoder}, {"RepairJSON", repairJSON}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ```` [output/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/output/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/output) · run it from `docs-site/examples`: ```sh go run ./output go test ./output ``` ```text == GenerateAs approved: true reason: within policy steps: 2 the model first read: INVALID_INPUT: tool "submit_output": field "approved": expected boolean, got string == ErrNoOutput no structured output; the model said: Looks fine to me. == OutputOf approved: false reason: past the refund window == OutputDecoder partial: approved=true reason="" partial: approved=true reason="within pol" partial: approved=true reason="within policy" final: approved=true reason="within policy" == RepairJSON approved: true reason: within policy steps: 1 ``` ### Best practices & gotchas - **Check for `ErrNoOutput` with `errors.Is`, and read the result.** A model that answers in text ends the run successfully; the error is how you learn there is no value, and `res` still holds what it said. (Source: `weft/core/output.go:20-24`, ADR 0008) - **Describe a field whose name does not say what goes in it.** A `jsonschema:"…"` tag becomes the field's description in `submit_output`'s schema, as for any tool's input. (Source: `weft/core/output.go:26-32`, `weft/core/tool.go:115`) - **Do not register your own `submit_output` tool.** The name is reserved; a duplicate panics as any duplicate tool does. (Source: ADR 0008, Consequences) - **Feed the decoder every event; throttle the rendering instead.** `Feed` appends each delta's bytes to its buffer, so a delta you skip is lost and later partials can show wrong values until the call's `ToolStart` re-seeds the buffer. Each `Feed` rescans the buffer, so cost grows with the square of the submission's size: for large submissions, render less often, not feed less often. (Source: `weft/core/output.go:213-219`, 225-230) - **Keep `submit_output` in a `ToolSource` list and in `OnlyTools`.** To both, it is an ordinary tool. A source advertises only the list it returns, and `OnlyTools("lookup")` keeps only the tools it names, so either one drops `submit_output`. The model's submission then reads `NO_SUCH_TOOL: no tool named "submit_output"` and `GenerateAs` returns `ErrNoOutput`. `weft.ParkAllExcept` is different: it never parks the submission. Name it in the narrowing, as in `OnlyTools("lookup", "submit_output")`. In a source, append the agent's own definition: the entry of `agt.Tools()` named `submit_output`, which `Agent.Tools` reports even beside a source. The playground's `tools_enabled` and `only_tools` overrides are `OnlyTools` too. (Source: `weft/core/agent.go:802-809`, 949-964; `weft/core/run.go:483-488`; `weft/core/loop.go:1752`; `weft/runtime/executor.go:1374-1382`) - **Check required fields yourself.** An omitted field is not an invalid submission: `GenerateAs` returns its zero value with a nil error, so a missing `approved` reads as `false`. Check the value after `GenerateAs`, or refuse the call before it ends the run: a `weft.WrapTools` middleware sees `submit_output` like any tool, with the raw arguments in the `ToolCallPart`'s `Args`, before they are decoded. When it returns `weft.ModelRetry("approved is required: true or false")`, the model reads `RETRY: approved is required: true or false`, the run goes on, and the model submits again. Those retries count against `MaxModelRetries` (default 3). A pointer field (`*bool`) tells absent from `false` after the decode. (Source: `weft/core/tool.go:192-221`; `weft/core/output.go:45-112`; `weft/core/loop.go:1783-1797`, 1650-1657) - **A subagent built with `Output` returns its submission's JSON.** The parent's tool result is the child's last valid `submit_output` arguments, byte for byte. (Source: `weft/core/subagent.go:265-276`) ### See also - [How do tools work?](https://weftgo.dev/docs/concepts/tools/): the schema `T` is reflected into - [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/) - [Stream a run's events](https://weftgo.dev/docs/guides/streaming/) - [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) Symbols used: [`weft.Output`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Output) · [`weft.GenerateAs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#GenerateAs) · [`weft.OutputOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OutputOf) · [`weft.ErrNoOutput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNoOutput) · [`weft.OutputDecoder`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OutputDecoder) · [`weft.NewOutputDecoder`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#NewOutputDecoder) · [`OutputDecoder.Feed`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#OutputDecoder.Feed) · [`OutputDecoder.Result`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#OutputDecoder.Result) · [`mw.RepairJSON`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RepairJSON) · [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps) · [`weft.ErrInvalidToolInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidToolInput) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`weft.ModelToolCallDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelToolCallDelta) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`wefttest.Raw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Raw) --- # Require human approval for a tool URL: https://weftgo.dev/docs/guides/approvals/ Markdown: https://weftgo.dev/docs/guides/approvals.md > Park a tool call with weft.RequireApproval, ParkOn or middleware, end the run with the call pending, and resume with Approve, Deny or Resolve. [`weft.RequireApproval()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) marks a tool whose calls never run without a decision. When the model calls it, the run ends successfully with the call on `res.Pending`; you resume with a second run that carries the transcript and [`weft.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Approve) or [`weft.Deny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Deny). Nothing blocks in between, so the decision can arrive over any transport, hours later. The refund tool in `approvals/main.go`: ```go title="approvals/main.go" refund := weft.Tool("refund_order", "Refund an order. Requires a human decision.", refundHandler, weft.RequireApproval(), // calls park until someone decides ) agt := weft.New(model, weft.Name("refund-desk"), lookupTool(), refund) ``` [approvals/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/approvals/main.go) ### How it works Approval is a run boundary ([rule 12](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them), [ADR 0007](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0007-approval-boundary.md)). A call that needs a decision is [parked](https://weftgo.dev/docs/reference/glossary/#park): it is not executed, and the step's other calls run normally. After they finish, the run ends successfully with the parked calls on [`RunResult.Pending`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) and `RunFinish.Pending`. > **Diagram:** The model calls refund_order, a tool built with RequireApproval(). The call gets a ToolStart but is not executed and gets no ToolFinish; the step's other calls run. The run then ends successfully, err is nil, with the parked call on res.Pending and RunFinish.Pending. Later, over any transport, a decision arrives and a new run resumes: agt.Generate(ctx, weft.Messages(res.Messages...), weft.Approve(id)). An approved call runs with Call.Approved set; weft.Deny(id, why) gives the model the result DENIED: why; a call with no decision gets DENIED: no decision. The results complete the earlier tool message and the loop continues with the next model call. The next run resumes with the transcript and a decision per call. The transcript is the only state, so the core needs no persistence: store `res.Messages` wherever the decision waits. If the run's context is canceled while calls are parked, cancellation wins: the run fails with the context error and the parked calls ride on `RunError.Result.Pending`, still resumable. Approval is a policy and UX seam, not a security boundary. A per-call prompt does not contain a compromised prompt or a malicious tool; a sandbox around the tool does. ### Require approval `RequireApproval` is a tool option. [`ToolDef.RequiresApproval()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.RequiresApproval) reports whether a tool has it. Run the agent, then read what parked: ```go title="approvals/main.go" res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234: $40, then $900.")) if err != nil { return nil, err } for _, pc := range res.Pending { // the run ended successfully, with work parked fmt.Fprintf(w, "pending %s: %s %s\n", pc.ID, pc.Name, pc.Args) } ``` [approvals/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/approvals/main.go) ```text pending c2: refund_order {"order_id":"1234","amount":40} pending c3: refund_order {"order_id":"1234","amount":900} lookup ran: order 1234 was delivered ``` `lookup_order` ran in the same step; its result is already in the transcript. A parked call emits a `ToolStart` and no `ToolFinish`, and `RunFinish.StoppedBy` reads `parked`. Each pending entry is a [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) with `ID`, `Name` and `Args` to show the person deciding. ### Approve and deny Resume by passing the parked transcript back with [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) and one decision per call: ```go title="approvals/main.go" res, err := agt.Generate(ctx, weft.Messages(parked.Messages...), // the transcript is the only state weft.Approve("c2"), weft.Deny("c3", "over the refund limit"), weft.ResumeOf(parked.ID), // links this run to the parked one in the record weft.Metadata(map[string]string{"weft.approval.actor": "ops-7"}), ) if err != nil { return err } ``` [approvals/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/approvals/main.go) ```text c2 refund_order → refunded $40.00 on order 1234 (approved: true) c3 refund_order → DENIED: over the refund limit ``` Before its first model call the resuming run settles every parked call: - **Approved** calls run through the ordinary tool chain. The handler's [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) reports `Call.Approved == true`. They emit `ToolStart` and `ToolFinish` in the new run. - **Denied** calls never run and emit no event. The model sees the error result `DENIED: `. - **Undecided** calls are denied with the reason `no decision`: the model sees `DENIED: no decision`. The cause on a denied call's error result is [`weft.ErrApprovalDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalDenied). It is a tool error, data for the model, never a run error. `Approve` and `Deny` ignore ids that are not pending, so a stale id in a decision list is harmless. #### Resume an approval The resume path, from [`docs/life-of-a-call.md`](https://github.com/weftgo/weft/blob/v0.20.2/docs/life-of-a-call.md#resuming-an-approval): ```text Generate(Messages(res.Messages...), Approve(id), Deny(id, reason)) │ ▼ repair, exempting the last assistant message's unresolved calls │ ▼ approved → the tool-call chain, Call.Approved = true denied → DENIED: ; undecided → DENIED: no decision │ ▼ results complete the earlier tool message → first model call of this run ``` The results complete the earlier step's tool message in the assistant's call order, even when a new `weft.Prompt` follows the transcript. Order matters for Gemini, which matches function responses by name and position. A transcript fed back with no decision at all is repaired like any other: each unresolved call gets `no result recorded: the call was interrupted`. Resumed calls belong to no step of the new run: they are not a `StepRecord`, and their `Call.Step` is `0`. Key audit lines on `CallID`. A resume is not idempotent. The core keeps no record of decisions, so resuming the same parked transcript twice with `Approve(id)` runs the approved call twice, and both runs succeed. A retried HTTP request or a double-click is enough ([gotcha](https://weftgo.dev/docs/guides/approvals/#best-practices--gotchas)). ### Resolve [`weft.Resolve(id, content)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Resolve) resumes a parked call with a result computed outside the process: a person runs the query in production and pastes what happened. The handler never runs: ```go title="approvals/main.go" res, err := agt.Generate(ctx, weft.Messages(parked.Messages...), weft.Resolve("q1", "count: 42"), // the handler never runs; this is the result weft.ResumeOf(parked.ID), ) ``` [approvals/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/approvals/main.go) The model reads `count: 42` as `run_sql`'s result. The content becomes the call's `ToolResultPart` verbatim, capped by `MaxResultBytes` as any result is. [`weft.ResolveError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResolveError) does the same with the result marked as an error. A resolved call follows the denied path: no `ToolStart` or `ToolFinish`, no `execute_tool` span, and `Call.Approved` is never set. `Resolve` composes with `Approve` and `Deny` in one resuming call; the last option for an id wins. Unlike `Approve` and `Deny`, `Resolve` on a call that is not pending fails the run at step 0 with `resolve: call "" is not pending in this run's transcript`. It carries a result the caller expects the model to see, and dropping it silently is what the error model forbids. ### Link the resume to the parked run [`weft.ResumeOf(res.ID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResumeOf) names the run a resume continues. A transcript carries no run id, so the core cannot infer it. It changes nothing the model sees and nothing the loop does: the decisions resume the calls with or without it. What it changes is the record. The resuming run's `invoke_agent` span and `run_start` record carry `weft.resumed_from`, and every run fed decisions carries `weft.resume.calls`: each parked call as `=approved|denied|resolved|no_decision`, in call order. Studio's run row shows `resumed_from`, and the parked run shows `resumed_by`. `weft/thread` and `weft/runtime` pass it on every resume; an app resuming a plain `Generate` passes it itself. Empty values are ignored, the last `ResumeOf` wins, and a subagent's child run does not inherit it. The package example is [`ExampleResumeOf`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-ResumeOf). ![An incident run parked in Studio: the header reads parked, three calls decided, resumed in the next run; step 0 read the metrics and step 1's restart_service, delete_logs and scale_service calls are pending](https://weftgo.dev/docs/_astro/studio-run-parked.light.Dmtk6MhA.webp) *A parked run in Studio: three calls decided, and "resumed in" linking the run that carried the decisions.* ### Name the decider Pass the approver as run metadata under the key `weft.approval.actor`, as the resume region does with [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata). It rides on every span and record of the resuming run, like any caller pair. To name what decided, rather than who, resume with [`weft.ApproveBy(callID, by, grantID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ApproveBy) instead of `Approve`. `by` is the decider's class (`weft/thread` uses `user`, `grant`, `approver`, `quorum` and `policy`) and `grantID` the standing permission that decided, if one did. It is reporting only: the call resumes exactly as with `Approve`, and its `execute_tool` span carries `weft.tool.approved_by` and `weft.grant.id`, each absent when empty. Both are ids and enums, never a person's name, so put an opaque class in `by`. [`weft.DenyBy(callID, reason, by, grantID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#DenyBy) is `Deny` naming what refused: with `by` `grant` the span reads `weft.tool.denied_by` `grant` and `weft.grant.id`, and any other `by`, or a plain `Deny`, reads `approval`. The last decision for an id wins, as with `Approve`. `weft/thread` passes `ApproveBy` on every resume it runs, and `DenyBy` when a deny grant matched. The package examples [`ExampleApproveBy`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-ApproveBy) (approved by a grant, `g_refunds`) and [`ExampleDenyBy`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-DenyBy) (`DENIED: refunds are closed`) show both. A denied call, by `Deny` or by no decision, gets a zero-length `execute_tool` span marked `weft.tool.denied` with `weft.tool.denied_kind` `denied` or `no_decision`. The span never carries the reason: that is the transcript's. The run's `invoke_agent` span counts denied calls in `weft.run.denied`. See [Tag runs with metadata](https://weftgo.dev/docs/guides/metadata/). ### Park calls for one run [`weft.ParkOn(names...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkOn) is a run option that parks calls to the named tools exactly as if they were built with `RequireApproval`. It reaches a run without touching the agent, which is immutable after `weft.New`: ```go title="approvals/main.go" // This run alone: park refund_order as if it were built with RequireApproval. res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234."), weft.ParkOn("refund_order")) ``` [approvals/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/approvals/main.go) Names are not validated: a name no tool carries parks nothing. With no names nothing parks. The set covers this run only; a subagent's child run does not inherit it. The package example is [`ExampleParkOn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ParkOn). #### Park all except [`weft.ParkAllExcept(names...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkAllExcept) turns `ParkOn` around: you list what may run, and every other call parks. Use it where a list of tools to park cannot be complete: ```go title="approvals/main.go" // Default-deny: only lookup_order runs unasked; every other call parks. res, err = agt.Generate(ctx, weft.Prompt("Refund order 1234."), weft.ParkAllExcept("lookup_order")) ``` [approvals/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/approvals/main.go) - The rule applies by name to the tool each call resolves to in its step's dispatch snapshot, so a tool only a `weft.ToolSource` supplies parks like any other. - It reaches runs started inside this run: a subagent's child applies the same rule to its own tools. A child that parks makes the delegating call's result `SUBAGENT_PENDING`; the parent does not park. - Park rules only add up. A `RequireApproval` tool or a `ParkOn` name parks whether or not it is listed here, and several `ParkAllExcept` options let through only the names all of them list. - With no names every call parks, except the agent's own `weft.Output` submission, `submit_output`: it is the run's answer, not a side effect. - An approved call runs once even when the resume carries the rule again; the next call to the tool parks again. The package example is [`ExampleParkAllExcept`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ParkAllExcept). Both options change the run's override fingerprint (`weft.override.*` on its span). ### Park from a source [`weft.ParkSource(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkSource) gives the agent a park set that can change between runs ([ADR 0030](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0030-a-dynamic-park-source.md)). The loop calls `fn` once per run, at its start, and merges the names it returns as a `ParkOn` would: ```go title="approvals/main.go" var mu sync.Mutex breakpoints := []string{"refund_order"} // changed elsewhere, e.g. by an admin page agt = weft.New(script(), lookupTool(), refund, weft.ParkSource(func(context.Context) []string { // read once per run, at its start mu.Lock() defer mu.Unlock() return slices.Clone(breakpoints) // answer from memory, never the network }), ) ``` [approvals/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/approvals/main.go) `fn` runs on the loop's goroutine before the first model call, so it must return promptly: read a cached set, never the network. A nil or empty answer parks nothing. A panic is contained, parks nothing and is reported as one Debug line. Several `ParkSource` options add up. A resume is its own run, so the loop reads the sources again, before the decided calls run. A call you approve still runs once, as under `ParkOn`: the approved calls skip the park check, and only later calls are matched against the new answer. The answer is behaviour, not configuration: it adds no `weft.override.*` attribute, and a source that answers nothing leaves the run byte-identical to one without it. A subagent's child run reads its own agent's sources. [`agt.ParkSources()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.ParkSources) returns the agent's sources in order. The playground's `runtime.Breakpoints()` is one ([Breakpoints](https://weftgo.dev/docs/observe/playground/breakpoints/)); the package example is [`ExampleParkSource`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-ParkSource). ### Park from middleware Tool middleware parks any call by returning an error that wraps [`weft.ErrApprovalRequired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalRequired). Read `Call.Approved` to let the approved call through on resume: ```go title="approvals/main.go" // parkLargeRefunds parks any refund over $100 until a person approves it. // An approved call comes back through the chain with Call.Approved set. func parkLargeRefunds(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, tc weft.ToolCallPart) (string, error) { if info, _ := weft.CallFromContext(ctx); tc.Name == "refund_order" && !info.Approved { var in RefundInput if err := json.Unmarshal(tc.Args, &in); err == nil && in.Amount > 100 { return "", fmt.Errorf("refund of $%.2f: %w", in.Amount, weft.ErrApprovalRequired) } } return next(ctx, tc) } } ``` [approvals/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/approvals/main.go) Registered with `weft.WrapTools(parkLargeRefunds)`, the $40 refund runs and the $900 one parks; after `Approve`, it runs with `approved: true`. The `RequireApproval`, `ParkOn` and `ParkAllExcept` check sits at the base of the chain, inside every middleware, so an outer `mw.Allow` can deny first and `mw.Audit` sees the attempt. A parking middleware such as `parkLargeRefunds` parks at its own position in `WrapTools` order: middleware listed inside it never sees the parked call. See [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/). `agt.CallTool` on a `RequireApproval` tool returns an error wrapping `ErrApprovalRequired` instead of parking: outside the loop there is no run to end. ### Complete example `approvals/main.go` parks, approves, denies, resolves, and parks per run and from middleware, all against scripted models: ```go title="approvals/main.go" // Command approvals runs the examples of the guide "Require human approval // for a tool": go run ./approvals. Every model is scripted with wefttest, // so it runs offline; swap in a provider adapter for a real one. package main import ( "context" "encoding/json" "fmt" "io" "os" "slices" "sync" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) type RefundInput struct { OrderID string `json:"order_id" jsonschema:"the order to refund"` Amount float64 `json:"amount" jsonschema:"amount in dollars"` } type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } func lookupTool() *weft.ToolDef { return weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, in LookupInput) (string, error) { return "order " + in.OrderID + " was delivered", nil }) } func refundHandler(ctx context.Context, in RefundInput) (string, error) { call, _ := weft.CallFromContext(ctx) return fmt.Sprintf("refunded $%.2f on order %s (approved: %t)", in.Amount, in.OrderID, call.Approved), nil } // refundAgent: the model looks order 1234 up and asks for two refunds in // one step, then answers once it sees the results. func refundAgent() *weft.Agent { model := wefttest.Script( wefttest.ToolCalls( wefttest.Call{ID: "c1", Name: "lookup_order", Args: `{"order_id":"1234"}`}, wefttest.Call{ID: "c2", Name: "refund_order", Args: `{"order_id":"1234","amount":40}`}, wefttest.Call{ID: "c3", Name: "refund_order", Args: `{"order_id":"1234","amount":900}`}, ), wefttest.Say("I refunded $40; the $900 refund was declined."), ) refund := weft.Tool("refund_order", "Refund an order. Requires a human decision.", refundHandler, weft.RequireApproval(), // calls park until someone decides ) agt := weft.New(model, weft.Name("refund-desk"), lookupTool(), refund) return agt } // park runs the first turn and prints what parked. func park(ctx context.Context, w io.Writer, agt *weft.Agent) (*weft.RunResult, error) { res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234: $40, then $900.")) if err != nil { return nil, err } for _, pc := range res.Pending { // the run ended successfully, with work parked fmt.Fprintf(w, "pending %s: %s %s\n", pc.ID, pc.Name, pc.Args) } fmt.Fprintln(w, "lookup ran:", res.Steps[0].Results[0].Content) return res, nil } // resume decides both parked calls and resumes the run. func resume(ctx context.Context, w io.Writer, agt *weft.Agent, parked *weft.RunResult) error { res, err := agt.Generate(ctx, weft.Messages(parked.Messages...), // the transcript is the only state weft.Approve("c2"), weft.Deny("c3", "over the refund limit"), weft.ResumeOf(parked.ID), // links this run to the parked one in the record weft.Metadata(map[string]string{"weft.approval.actor": "ops-7"}), ) if err != nil { return err } printResults(w, res, "refund_order") fmt.Fprintln(w, "answer:", res.Text()) return nil } // printResults prints every result of the named tool in the transcript. func printResults(w io.Writer, res *weft.RunResult, name string) { for _, m := range res.Messages { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok && r.Name == name { fmt.Fprintf(w, "%s %s → %s\n", r.CallID, r.Name, r.Content) } } } } // resolve: a human runs the query and pastes what happened. func resolve(ctx context.Context, w io.Writer) error { runSQL := weft.Tool("run_sql", "Run a read-only SQL query. A human executes it.", func(_ context.Context, in struct { SQL string `json:"sql"` }) (string, error) { return "", &weft.ToolError{Code: "NOT_EXECUTED", Message: "this tool only runs through a human"} }, weft.RequireApproval(), ) model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{ID: "q1", Name: "run_sql", Args: `{"sql":"SELECT COUNT(*) FROM orders"}`}), wefttest.Say("There are 42 orders."), ) agt := weft.New(model, weft.Name("sql-desk"), runSQL) parked, err := agt.Generate(ctx, weft.Prompt("How many orders are there?")) if err != nil { return err } res, err := agt.Generate(ctx, weft.Messages(parked.Messages...), weft.Resolve("q1", "count: 42"), // the handler never runs; this is the result weft.ResumeOf(parked.ID), ) if err != nil { return err } printResults(w, res, "run_sql") fmt.Fprintln(w, "answer:", res.Text()) return nil } // parkPerRun: tools without RequireApproval, parked by run options and by // a ParkSource. func parkPerRun(ctx context.Context, w io.Writer) error { refund := weft.Tool("refund_order", "Refund an order.", refundHandler) script := func() *wefttest.Model { return wefttest.Script( wefttest.ToolCalls( wefttest.Call{ID: "c1", Name: "lookup_order", Args: `{"order_id":"1234"}`}, wefttest.Call{ID: "c2", Name: "refund_order", Args: `{"order_id":"1234","amount":40}`}, ), wefttest.Say("Refunded."), ) } agt := weft.New(script(), lookupTool(), refund) // This run alone: park refund_order as if it were built with RequireApproval. res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234."), weft.ParkOn("refund_order")) if err != nil { return err } fmt.Fprintln(w, "ParkOn pending:", names(res.Pending)) agt = weft.New(script(), lookupTool(), refund) // Default-deny: only lookup_order runs unasked; every other call parks. res, err = agt.Generate(ctx, weft.Prompt("Refund order 1234."), weft.ParkAllExcept("lookup_order")) if err != nil { return err } fmt.Fprintln(w, "ParkAllExcept pending:", names(res.Pending)) var mu sync.Mutex breakpoints := []string{"refund_order"} // changed elsewhere, e.g. by an admin page agt = weft.New(script(), lookupTool(), refund, weft.ParkSource(func(context.Context) []string { // read once per run, at its start mu.Lock() defer mu.Unlock() return slices.Clone(breakpoints) // answer from memory, never the network }), ) res, err = agt.Generate(ctx, weft.Prompt("Refund order 1234.")) if err != nil { return err } fmt.Fprintln(w, "ParkSource pending:", names(res.Pending), "sources:", len(agt.ParkSources())) return nil } // parkLargeRefunds parks any refund over $100 until a person approves it. // An approved call comes back through the chain with Call.Approved set. func parkLargeRefunds(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, tc weft.ToolCallPart) (string, error) { if info, _ := weft.CallFromContext(ctx); tc.Name == "refund_order" && !info.Approved { var in RefundInput if err := json.Unmarshal(tc.Args, &in); err == nil && in.Amount > 100 { return "", fmt.Errorf("refund of $%.2f: %w", in.Amount, weft.ErrApprovalRequired) } } return next(ctx, tc) } } // parkFromMiddleware: the small refund runs, the large one parks. func parkFromMiddleware(ctx context.Context, w io.Writer) error { refund := weft.Tool("refund_order", "Refund an order.", refundHandler) model := wefttest.Script( wefttest.ToolCalls( wefttest.Call{ID: "c1", Name: "refund_order", Args: `{"order_id":"1234","amount":40}`}, wefttest.Call{ID: "c2", Name: "refund_order", Args: `{"order_id":"5678","amount":900}`}, ), wefttest.Say("Both refunds are done."), ) agt := weft.New(model, refund, weft.WrapTools(parkLargeRefunds)) res, err := agt.Generate(ctx, weft.Prompt("Refund both orders.")) if err != nil { return err } fmt.Fprintln(w, "ran:", res.Steps[0].Results[0].Content) fmt.Fprintln(w, "pending:", names(res.Pending)) res, err = agt.Generate(ctx, weft.Messages(res.Messages...), weft.Approve("c2"), weft.ResumeOf(res.ID)) if err != nil { return err } printResults(w, res, "refund_order") return nil } func names(calls []weft.ToolCallPart) []string { out := make([]string, len(calls)) for i, c := range calls { out[i] = c.ID + " " + c.Name } return out } func run(ctx context.Context, w io.Writer) error { fmt.Fprintln(w, "== park and resume") agt := refundAgent() parked, err := park(ctx, w, agt) if err != nil { return err } if err := resume(ctx, w, agt, parked); err != nil { return err } fmt.Fprintln(w, "== resolve") if err := resolve(ctx, w); err != nil { return err } fmt.Fprintln(w, "== park per run") if err := parkPerRun(ctx, w); err != nil { return err } fmt.Fprintln(w, "== park from middleware") return parkFromMiddleware(ctx, w) } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [approvals/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/approvals/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/approvals) · run it from `docs-site/examples`: ```sh go run ./approvals go test ./approvals ``` ```text == park and resume pending c2: refund_order {"order_id":"1234","amount":40} pending c3: refund_order {"order_id":"1234","amount":900} lookup ran: order 1234 was delivered c2 refund_order → refunded $40.00 on order 1234 (approved: true) c3 refund_order → DENIED: over the refund limit answer: I refunded $40; the $900 refund was declined. == resolve q1 run_sql → count: 42 answer: There are 42 orders. == park per run ParkOn pending: [c2 refund_order] ParkAllExcept pending: [c2 refund_order] ParkSource pending: [c2 refund_order] sources: 1 == park from middleware ran: refunded $40.00 on order 1234 (approved: false) pending: [c2 refund_order] c1 refund_order → refunded $40.00 on order 1234 (approved: false) c2 refund_order → refunded $900.00 on order 5678 (approved: true) ``` The tests in `approvals/main_test.go` also pin `DENIED: no decision`, the parked call's events, and `Resolve` failing on an id that is not pending. weft's own [`examples/approval`](https://github.com/weftgo/weft/tree/v0.20.2/examples/approval) asks for the decision on standard input. ### Best practices & gotchas - **Decide every pending call.** An undecided call is denied with `DENIED: no decision`, and the model reads it. (Source: ADR 0007 §3, `weft/core/run.go:139-152`) - **Resume each park once.** The core does not remember that a park was decided, so a second resume of the same transcript runs the approved call again. Record the decision before you resume, for example a row keyed on `res.ID` and the call id that only the first request can claim. Make side-effecting handlers idempotent too, or use `weft/thread`, which records each decision and spends it on the resume that applies it ([Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/#how-it-works)). (Source: `weft/core/run.go:118-123`, ADR 0007; scratch test) - **Pass `ResumeOf(res.ID)` on every resume.** The core cannot infer the link, and without it Studio cannot show which run decided which park. (Source: `weft/core/run.go:209-223`, CHANGELOG 0.16.0) - **Put an opaque id in `weft.approval.actor`, never an email.** It is metadata, so it survives a content-off destination. (Source: CHANGELOG.md:338) - **Treat approval as policy, not security.** A malicious tool or a compromised prompt is contained by a sandbox, not by a prompt to a person. (Source: ADR 0007, "Not a security boundary") - **Do not stop a run on an approval-gated tool's result.** Stop conditions do not see resumed calls; `HasToolCall` fires on the step that issued the call. (Source: ADR 0007, Consequences) - **Return promptly from a `ParkSource`.** It runs before the first model call on the loop's goroutine. (Source: `weft/core/run.go:395-400`, ADR 0030) ### See also - [What does a run return?](https://weftgo.dev/docs/concepts/runs/): `Pending` on the result - [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/): `thread` adds persistence, grants and signed decisions - [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) - [Continue a conversation](https://weftgo.dev/docs/guides/conversations/) Symbols used: [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`ToolDef.RequiresApproval`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.RequiresApproval) · [`weft.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Approve) · [`weft.Deny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Deny) · [`weft.Resolve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Resolve) · [`weft.ResolveError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResolveError) · [`weft.ResumeOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResumeOf) · [`weft.ParkOn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkOn) · [`weft.ParkAllExcept`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkAllExcept) · [`weft.ParkSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkSource) · [`Agent.ParkSources`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.ParkSources) · [`weft.ErrApprovalRequired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalRequired) · [`weft.ErrApprovalDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalDenied) · [`weft.Call`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Call) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) · [`weft.RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) · [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) · [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) · [`weft.ToolCaller`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCaller) · [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) · [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Delegate to another agent (subagents) URL: https://weftgo.dev/docs/guides/subagents/ Markdown: https://weftgo.dev/docs/guides/subagents.md > weft.Subagent turns an agent into a tool another agent calls: the child runs on the prompt alone, its events arrive wrapped in Nested, its usage rolls into the parent's, and its failure is a tool result. [`weft.Subagent(name, description, child, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) returns a tool whose handler runs another agent. The parent model calls it with one argument, `prompt`; the child runs on a fresh transcript holding only that prompt, and the tool's result is the child's final text. Use it when an orchestrator should hand a self-contained task to a specialist and read its answer. `subagents/main.go` gives an orchestrator a researcher: ```go title="subagents/main.go" researcher := weft.New(childModel, weft.Name("researcher"), weft.Instructions("You research one question and answer briefly."), deepSearch, ) orchestrator := weft.New(parentModel, weft.Name("orchestrator"), weft.Subagent("research", "Research a topic in depth.", researcher, weft.Timeout(2*time.Minute), // bounds the child run ), ) ``` [subagents/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/subagents/main.go) The tool's description is all the parent model knows about the child, so write it as you would any tool's. The package example is [`ExampleSubagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Subagent). ### How it works A subagent is an ordinary tool ([ADR 0014](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0014-subagents-as-tools.md)). Its handler runs the child through the same loop `Generate` and `Stream` use, on the parent call's context. There is no second loop and no graph: it is the orchestrator-worker pattern built from the tool contract. The child sees nothing of the parent's conversation, only the prompt the parent model wrote and its own instructions. The prompt argument's schema says so to the parent model: `The task, stated in full: the agent sees only this prompt, not the conversation.` The child's run is observable from the parent. Its events arrive in the parent's stream, its usage is added to the parent's, and Studio draws the delegation as an edge: ![A run on the graph scale: the director agent delegating to its ops-manager subagent, with step 0's details in the drawer](https://weftgo.dev/docs/_astro/studio-run-graph.light.DS67UvLU.webp) *A run on Studio's graph scale: the director agent delegating to its ops-manager subagent.* ### Delegate Every tool option applies to the delegation: - `weft.Timeout` bounds the child run. At the deadline the result is the ordinary `tool "research" timed out after 2m0s`, and the child stops at its next context check. - `weft.MaxResultBytes` caps the child's answer. - `weft.RequireApproval` gates the act of delegating: the call parks, and `Approve` runs the child. - `weft.Sequential` makes the delegation a barrier, and the parent's `weft.Parallelism` bounds concurrent delegations: with the default `Parallelism(4)`, four research calls in one step run their four children at once, and a fifth waits for a slot. - The parent's `weft.WrapTools` wraps the delegation once; the child's own seams govern inside it. A child built with [`weft.Output`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Output) returns its last valid `submit_output` arguments, byte for byte, instead of its text. If it never made a valid submission, the tool's result is its final text, and no error is raised. Canceling the parent's context cancels the child. #### What reaches the child run The child runs on its own agent's configuration. Its run is built from the delegating call alone: the call's context, a run id derived from the call, and the prompt argument. A parent's run options reach the child only when they ride that context: | Parent run option | Reaches the child? | What the child does | |---|---|---| | `weft.Metadata`, and `weft.WithMetadata` on the context | Yes | Reads the merged pairs with `weft.MetadataFromContext`. | | `weft.ParkAllExcept` | Yes | Applies the rule to its own tools; a call it parks ends the delegation `SUBAGENT_PENDING`. | | Cancellation and deadline, `weft.Timeout` on the delegation included | Yes | Stops at its next context check. | | `weft.Thinking`, `weft.Instructions`, `weft.Params`, `weft.ToolChoice` | No | Sends its own agent's defaults. | | `weft.UseModel` | No | Calls its own agent's model. | | `weft.OnlyTools` | No | Is offered all of its own tools. | | `weft.MaxSteps`, `weft.Parallelism` (lowered) | No | Keeps its own agent's limits. | | `weft.ParkOn` | No | Runs the named tools unasked. | | `weft.Approve`, `weft.Deny`, `weft.Resolve`, `weft.ResolveError`, `weft.ResumeOf` | No | Decides nothing of the parent's. A child that parks ends `SUBAGENT_PENDING`. | | `weft.Steering`, `weft.OnMessages` | No | Gets no steering source and no transcript observer. | | `weft.RunID`, `weft.Prompt`, `weft.Messages` | No | Gets the id `//` and a transcript holding only the `prompt` argument. | No error is raised. A parent run with `Thinking(ThinkHigh)`, `Instructions("run sys")`, `Params{Temperature: 0.9}`, `UseModel(alt)`, `OnlyTools`, `MaxSteps(2)` and `ParkOn` sent all of these on its own two model calls. Its child's three requests, one more than the parent's `MaxSteps(2)`, carried the child's system prompt, no thinking level, no temperature and both of the child's tools; the parked tool ran ([gotcha](https://weftgo.dev/docs/guides/subagents/#best-practices--gotchas)). #### See the child's events Each event of the child run arrives in the parent's stream wrapped in a [`weft.Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested): `CallID` is the parent call that owns the child, `Event` is the child's event. Switch on the inner event as you would on the parent's: ```go title="subagents/main.go" run := orchestrator.Stream(ctx, weft.Prompt("What is new in tool-use evaluation?"), weft.RunID("run-1")) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.ToolStart: fmt.Fprintf(w, "parent tool %s: %s\n", ev.CallID, ev.Name) case weft.Nested: // one event of the child run, owned by parent call ev.CallID switch inner := ev.Event.(type) { case weft.RunStart: fmt.Fprintf(w, " child %s started: %s\n", inner.ID, inner.Agent) case weft.ToolFinish: fmt.Fprintf(w, " child tool %s → %s\n", inner.Name, inner.Content) case weft.RunFinish: fmt.Fprintf(w, " child %s finished in %d steps\n", inner.RunID, inner.Steps) } case weft.ToolFinish: fmt.Fprintf(w, "parent tool %s → %s\n", ev.CallID, ev.Content) } } ``` [subagents/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/subagents/main.go) ```text parent tool c1: research child run-1/0/c1 started: researcher child tool deep_search → 3 papers on tool-use evaluation child run-1/0/c1 finished in 2 steps parent tool c1 → I found 3 papers on tool-use evaluation. ``` The child's whole run, `RunStart` through `RunFinish`, sits inside the delegating call's `ToolStart` and `ToolFinish`. No `Nested` event for a call is delivered after that call's `ToolFinish`, even when a timeout abandoned the child (the late-event rule, an amendment to ADR 0004). A `Nested` event's `Seq` comes from the parent's counter, so the parent stream stays totally ordered with the child's events in place. The inner event keeps its own `RunID` and `Seq`. A grandchild's event is a `Nested` inside a `Nested`. [`wefttest.Flatten`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Flatten) unwraps them all for a test. A child run's id is `//`: `run-1/0/c1` is call `c1` of step 0 of run `run-1`. A call executed under `Approve` gets `/resume/`. The id is on the nested `RunStart` (`ID`) and `RunFinish` (`RunID`), and on `weft.CallFromContext` inside the child's tools; the parent's tool result does not carry it. #### Count the child's usage The child's total usage is added to the parent's `RunResult.Usage` and recorded per call on `StepRecord.SubagentUsage`. The step's own `Usage` stays the model call's numbers: ```go title="subagents/main.go" res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?")) if err != nil { return err } step := res.Steps[0] fmt.Fprintf(w, "step 0 model call: %d in, %d out\n", step.Usage.InputTokens, step.Usage.OutputTokens) for callID, u := range step.SubagentUsage { // the child's total, keyed by the delegating call fmt.Fprintf(w, "subagent %s: %d in, %d out\n", callID, u.InputTokens, u.OutputTokens) } fmt.Fprintf(w, "run total: %d in, %d out\n", res.Usage.InputTokens, res.Usage.OutputTokens) ``` [subagents/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/subagents/main.go) ```text step 0 model call: 10 in, 5 out subagent c1: 20 in, 10 out run total: 40 in, 20 out ``` A failed child's partial usage counts too, as long as the child returns before its call finishes. A child abandoned by `weft.Timeout` is the exception: its usage is recorded only when the child run returns, after the timed-out call has finished, so none of it reaches `RunResult.Usage`, `SubagentUsage` or the parent's `UsageLimit`, including the steps it ran before the deadline. Because the child's usage is otherwise the parent's, `weft.UsageLimit` on the parent counts delegated work ([rule 13](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). It counts it once the delegating call returns: the parent checks its limit only between its own steps, so it cannot stop a child that is running ([How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/#usage-limit)). A `weft/thread` pool child is the exception: it is a session, its usage is on its receipt, never on the parent run's `Usage` ([Run bounded child sessions with a pool](https://weftgo.dev/docs/sessions/pools/)). ### Read the failure codes A child that fails never fails the parent run. Its failure is a coded tool error the parent model reads and reacts to: ```go title="subagents/main.go" res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?")) if err != nil { return err // the child's failure is not a parent run error } r := res.Steps[0].Results[0] fmt.Fprintf(w, "error result: %t\n%s\n", r.IsError, r.Content) ``` [subagents/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/subagents/main.go) ```text error result: true SUBAGENT_FAILED: agent "research" failed at step 0: model stream: provider down ``` The three codes are exported constants, so policy middleware can branch on them without parsing text: | Constant | Result text | When | |---|---|---| | [`weft.CodeSubagentFailed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeSubagentFailed) | `SUBAGENT_FAILED: agent "" failed at step N: ` | The child run returned an error. Its `*RunError` is on `ToolError.Err`, reachable with `errors.As` in middleware. | | [`weft.CodeSubagentPending`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeSubagentPending) | `SUBAGENT_PENDING: agent "" ended awaiting approval of N call(s)` | The child parked a call. The parent's transcript has nowhere to carry it. | | [`weft.CodeSubagentCycle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeSubagentCycle) | `SUBAGENT_CYCLE: agent "" is already running in this call chain` | The child is already running above this call; refused before any model call. | The messages name the tool, not the child agent's `Name`: the tool name is what the parent model called. The child's own name is on the nested `RunStart.Agent`. Agents are immutable, so a cycle cannot be built at construction; a `weft.ToolSource` can close one at run time, and the guard compares `*Agent` pointers. ### Complete example `subagents/main.go` streams a delegation, reads its usage, and fails a child: ```go title="subagents/main.go" // Command subagents runs the examples of the guide "Delegate to another // agent (subagents)": go run ./subagents. Every model is scripted with // wefttest, so it runs offline; swap in a provider adapter for a real one. package main import ( "context" "errors" "fmt" "io" "os" "time" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) type SearchInput struct { Query string `json:"query" jsonschema:"what to search for"` } // newOrchestrator builds a researcher child and an orchestrator that // delegates to it. childModel scripts the child; the parent calls the // research tool once and then answers. func newOrchestrator(childModel weft.Model) *weft.Agent { deepSearch := weft.Tool("deep_search", "Search the paper index.", func(_ context.Context, in SearchInput) (string, error) { return "3 papers on " + in.Query, nil }) parentModel := wefttest.Script( wefttest.ToolCalls(wefttest.Call{ID: "c1", Name: "research", Args: `{"prompt":"Find recent work on tool-use evaluation."}`}), wefttest.Say("Research found three papers."), ) researcher := weft.New(childModel, weft.Name("researcher"), weft.Instructions("You research one question and answer briefly."), deepSearch, ) orchestrator := weft.New(parentModel, weft.Name("orchestrator"), weft.Subagent("research", "Research a topic in depth.", researcher, weft.Timeout(2*time.Minute), // bounds the child run ), ) return orchestrator } func researchScript() weft.Model { return wefttest.Script( wefttest.ToolCalls(wefttest.Call{ID: "c1", Name: "deep_search", Args: `{"query":"tool-use evaluation"}`}), wefttest.Say("I found 3 papers on tool-use evaluation."), ) } // nested streams the orchestrator and prints the child's events. func nested(ctx context.Context, w io.Writer) error { orchestrator := newOrchestrator(researchScript()) run := orchestrator.Stream(ctx, weft.Prompt("What is new in tool-use evaluation?"), weft.RunID("run-1")) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.ToolStart: fmt.Fprintf(w, "parent tool %s: %s\n", ev.CallID, ev.Name) case weft.Nested: // one event of the child run, owned by parent call ev.CallID switch inner := ev.Event.(type) { case weft.RunStart: fmt.Fprintf(w, " child %s started: %s\n", inner.ID, inner.Agent) case weft.ToolFinish: fmt.Fprintf(w, " child tool %s → %s\n", inner.Name, inner.Content) case weft.RunFinish: fmt.Fprintf(w, " child %s finished in %d steps\n", inner.RunID, inner.Steps) } case weft.ToolFinish: fmt.Fprintf(w, "parent tool %s → %s\n", ev.CallID, ev.Content) } } return nil } // usage shows the child's usage rolled into the parent's result. func usage(ctx context.Context, w io.Writer) error { orchestrator := newOrchestrator(researchScript()) res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?")) if err != nil { return err } step := res.Steps[0] fmt.Fprintf(w, "step 0 model call: %d in, %d out\n", step.Usage.InputTokens, step.Usage.OutputTokens) for callID, u := range step.SubagentUsage { // the child's total, keyed by the delegating call fmt.Fprintf(w, "subagent %s: %d in, %d out\n", callID, u.InputTokens, u.OutputTokens) } fmt.Fprintf(w, "run total: %d in, %d out\n", res.Usage.InputTokens, res.Usage.OutputTokens) return nil } // failure: the child's model fails; the parent model reads it as data. func failure(ctx context.Context, w io.Writer) error { orchestrator := newOrchestrator(wefttest.Script(wefttest.Fail(errors.New("provider down")))) res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?")) if err != nil { return err // the child's failure is not a parent run error } r := res.Steps[0].Results[0] fmt.Fprintf(w, "error result: %t\n%s\n", r.IsError, r.Content) fmt.Fprintln(w, "answer:", res.Text()) return nil } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"nested events", nested}, {"usage", usage}, {"failure", failure}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [subagents/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/subagents/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/subagents) · run it from `docs-site/examples`: ```sh go run ./subagents go test ./subagents ``` ```text == nested events parent tool c1: research child run-1/0/c1 started: researcher child tool deep_search → 3 papers on tool-use evaluation child run-1/0/c1 finished in 2 steps parent tool c1 → I found 3 papers on tool-use evaluation. == usage step 0 model call: 10 in, 5 out subagent c1: 20 in, 10 out run total: 40 in, 20 out == failure error result: true SUBAGENT_FAILED: agent "research" failed at step 0: model stream: provider down answer: Research found three papers. ``` ### Best practices & gotchas - **Keep approval-gated tools in the orchestrator.** A child that parks returns `SUBAGENT_PENDING` and its call cannot be decided from the parent; put `RequireApproval` on the subagent tool instead. (Source: ADR 0014, `weft/core/subagent.go:23-28`) - **Pass a built agent.** `weft.Subagent` panics when `child` is nil, with `weft: Subagent "research" called with a nil agent` for a tool named `research`, at construction rather than on the first call. (Source: `weft/core/subagent.go:304-308`) - **Do not count on an `Output` child failing when it never submits.** Without a valid `submit_output` call the result falls back to the child's final text, with no error and no code, so the parent model reads prose where it expected JSON. (Source: `weft/core/subagent.go:264-270, 331-336`; `weft/core/output.go:135-153`) - **Write the delegation's description for the parent model.** It is the parent's entire routing surface for the child. (Source: `weft/core/subagent.go:279-282`) - **Set a `Timeout` on long children, and bound what it leaves uncounted.** The child runs on the call's deadline context, so at the deadline its in-flight model request is cancelled and it calls the model no more. The steps it ran before the deadline are not counted: none of their usage reaches the parent, so the parent's `UsageLimit` cannot cover them. Bound the child itself with its own `MaxSteps` or `UsageLimit`. (Source: ADR 0014, "Cancellation and timeouts" and the late-event rule; `weft/core/subagent.go:318-319`; `weft/core/loop.go:1265-1272, 1381, 2156`) - **Configure the child agent, not the parent's run.** A per-run `Thinking`, `UseModel`, `Params`, `Instructions`, `ToolChoice`, `OnlyTools` or lowered `MaxSteps` changes the parent's model calls only. Build the child with the setting it needs, or build a second child agent for the variant. To vary a child per run, give it a `weft.PrepareStep` that reads the inherited `weft.MetadataFromContext(ctx)`: a child whose `PrepareStep` set `ThinkHigh` on `think=high` sent level 4 under a parent run with `Metadata{"think": "high"}`. (Source: `weft/core/subagent.go:316`; `weft/core/loop.go:63`; `weft/core/agent.go:176`) - **Budget with `UsageLimit` on the parent, and bound each child itself.** Delegated usage counts toward the parent's limit, and there is no depth cap. The parent checks the limit only before its next model call, so every child of the step runs to its own end first. Give each child agent its own `UsageLimit` and `MaxSteps` to bound one delegation. (Source: ADR 0014, "The cycle guard"; AGENTS.md rule 13; `weft/core/loop.go:849, 1102-1116`) - **Read `SubagentUsage` for attribution, not `StepRecord.Usage`.** The step's usage is its own model call only. (Source: ADR 0014, "Usage") ### See also - [How do tools work?](https://weftgo.dev/docs/concepts/tools/): a subagent is one - [Stream a run's events](https://weftgo.dev/docs/guides/streaming/) - [Run bounded child sessions with a pool](https://weftgo.dev/docs/sessions/pools/) - [The agent loop, from first principles](https://weftgo.dev/docs/explanation/agent-loop/) Symbols used: [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested) · [`weft.CodeSubagentFailed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeSubagentFailed) · [`weft.CodeSubagentPending`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeSubagentPending) · [`weft.CodeSubagentCycle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CodeSubagentCycle) · [`weft.StepRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepRecord) · [`weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) · [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`weft.MaxResultBytes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxResultBytes) · [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) · [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) · [`weft.Output`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Output) · [`weft.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunID) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`ExampleSubagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Subagent) · [`wefttest.Flatten`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Flatten) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Use MCP both ways URL: https://weftgo.dev/docs/guides/mcp/ Markdown: https://weftgo.dev/docs/guides/mcp.md > Import an MCP server's tools into a weft agent with mcp.Tools, and serve weft tools or a whole agent as an MCP server with mcp.AddTools and mcp.Serve. Package [`weft/mcp`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp) bridges weft and the Model Context Protocol in both directions, over the official Go MCP SDK. [`mcp.Tools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Tools) turns a connected server's tools into ordinary weft tools; [`mcp.AddTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#AddTools) and [`mcp.Serve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Serve) register weft tools, or a whole agent, on an MCP server. Import a server's tools and give them to an agent, in `mcpx/mcpx.go`: ```go title="mcpx/mcpx.go" tools, err := mcp.Tools(ctx, sess, mcp.Prefix("gh_"), // search_issues → gh_search_issues mcp.Policy(weft.Timeout(10*time.Second)), // per-tool policy on every imported tool ) var skipped *mcp.ImportError if errors.As(err, &skipped) { fmt.Fprintln(w, "skipped:", skipped) // some tools were left out; the rest are in tools } else if err != nil { return err // the listing itself failed } opts := []weft.Option{weft.Name("triage")} for _, t := range tools { opts = append(opts, t) // an imported tool is an ordinary *weft.ToolDef } model := wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "gh_search_issues", Args: `{"q":"crash","state":"open"}`}, wefttest.Call{Name: "gh_close_issue", Args: `{"id":12}`}, ), wefttest.Say("Two issues are open; #12 is locked."), ) agt := weft.New(model, opts...) res, err := agt.Generate(ctx, weft.Prompt("Triage the crash reports.")) ``` [mcpx/mcpx.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/mcpx.go) The tools `Tools` returns are `*weft.ToolDef` values, so they register on `weft.New` like any tool. The model calls `gh_search_issues`; the bridge forwards the call to the server's `search_issues`. ### How it works The bridge has no adapter layer of its own: weft's tool contract and MCP's are the same shape, so each direction is a field-for-field mapping ([ADR 0015](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0015-mcp-interop.md)). The package imports the SDK as `sdk` in examples and keeps the name `mcp` for itself. Both directions take an SDK value you set up: `Tools` takes a connected `*sdk.ClientSession`, and `AddTools` and `Serve` take an `*sdk.Server`. Transports, OAuth and connection pools stay the SDK's job. The examples on this page connect a client to a server in memory, the way weft's own tests do: ```go title="mcpx/mcpx.go" // connect runs srv over an in-memory transport and returns a client // session connected to it. A real client dials the server instead: // sdk.CommandTransport for a subprocess, sdk.StreamableClientTransport // for HTTP. func connect(ctx context.Context, srv *sdk.Server) (*sdk.ClientSession, error) { serverSide, clientSide := sdk.NewInMemoryTransports() go func() { _ = srv.Run(ctx, serverSide) }() client := sdk.NewClient(&sdk.Implementation{Name: "support-app", Version: "1"}, nil) return client.Connect(ctx, clientSide, nil) } ``` [mcpx/mcpx.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/mcpx.go) The loop, the two seams, the manifest and `wefttest` treat an imported tool like any other: it is a [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool). `TestRoundTripIsLossless` pins the property both directions rest on: a tool exported with `AddTools` and imported back with `Tools` keeps its schema and answers the same. More examples for both directions live in [`mcp/examples/`](https://github.com/weftgo/weft/tree/v0.20.2/mcp/examples) and run offline over in-memory transports. ### Import tools `mcp.Tools(ctx, sess, opts...)` lists the session's tools, every page of the listing, and returns one weft tool per server tool. Each keeps the server's name and description. Its input schema is the document the server sent, kept whole through [`weft.ParseSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParseSchema), so keywords weft's `Schema` type cannot hold, such as `enum` or `oneOf`, reach the openai and anthropic adapters whole. An object output schema, when the server sends one, is recorded on the tool too. The google adapter cannot send the document whole. It decodes the schema into the Gemini SDK's `genai.Schema` type, which keeps the keywords it has a field for and silently drops the rest: | Gemini receives | Keywords | |---|---| | Kept | `type`, `format`, `title`, `description`, `enum` (string values), `default`, `example`, `nullable`, `properties`, `required`, `propertyOrdering`, `minProperties`, `maxProperties`, `items`, `minItems`, `maxItems`, `minLength`, `maxLength`, `pattern`, `minimum`, `maximum`, `anyOf` | | Dropped | everything else, including `oneOf`, `allOf`, `not`, `const`, `$ref`, `$defs`, `additionalProperties`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf` and `uniqueItems` | | Kept when the document does not decode | `type`, `format`, `description`, `required`, `items` and `properties`, recursively; a node whose `type` was an array keeps no type | The third row is the fallback for a document with a value `genai.Schema` cannot hold, such as a numeric `enum` value or a `type` given as an array. One such value anywhere puts the whole document on the fallback, so every other keyword is dropped from every node, not only from the one that failed. A property described only by `oneOf` reaches Gemini as an unconstrained node rather than disappearing. These options shape the import, all of type [`mcp.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Option); [`mcp.Server`, `mcp.Transport`](https://weftgo.dev/docs/guides/mcp/#mcp-identity) and [`mcp.CallerMeta`](https://weftgo.dev/docs/guides/mcp/#link-a-served-run-to-its-caller) only change what is recorded (and, for `CallerMeta`, what the server is told): | Option | Effect | |---|---| | [`mcp.Server(name)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Server), [`mcp.Transport(kind)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Transport) | Name the server and how it is reached, for the record ([MCP identity](https://weftgo.dev/docs/guides/mcp/#mcp-identity)) | | [`mcp.CallerMeta()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#CallerMeta) | Sends each call's caller in `params._meta` ([Link a served run to its caller](https://weftgo.dev/docs/guides/mcp/#link-a-served-run-to-its-caller)) | | [`mcp.Prefix(p)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Prefix) | Prepends `p` to every imported name (`search` becomes `gh_search`), so two servers' tools can share one agent. The remote call still uses the server's name. | | [`mcp.Policy(opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Policy) | Applies tool options to every imported tool: `weft.Timeout`, `weft.MaxResultBytes`, `weft.RequireApproval` and `weft.WrapTools` work as on any tool. `weft.StrictInput` has no effect: a raw tool gets the model's arguments as sent, and validation is the server's. | A call forwards the model's argument bytes to `tools/call` unchanged; empty or `null` arguments go as `{}`. The result comes back as text: the JSON of `structuredContent` when the server sends it, otherwise the text items joined by newlines. Images, audio and resources become one-line markers such as `[image image/png, 2048 bytes]`, because a weft transcript carries no binary tool results. Every remote failure is data the model sees, never a run error. The `execute_tool` span tells the three kinds apart by `error.type`: | `error.type` | The call | What the model sees | |---|---|---| | `mcp_tool_error` | the server answered with an `isError` result: its tool failed | the server's text verbatim, matching [`mcp.ErrToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ErrToolError) with `errors.Is`; an empty one reads `mcp: tool returned an error` | | `mcp_rpc_error` | the server answered with a JSON-RPC error: its handler failed, the tool is not listed, the arguments were refused | `mcp: ` | | `mcp_transport` | no answer: a closed session, a stdio stream at EOF, a refused or dropped connection, a 5xx or 429 with no JSON-RPC body | `mcp: `, the cause unwrapped. A cancelled call's `error.type` is the context error's name, not `mcp_transport` | Before 0.20.0 a JSON-RPC error answer read `mcp_transport` too. Studio says the three as "MCP tool error", "MCP refused the call" and "MCP unreachable", and its call graph counts them per server. A server's annotations set one default. A tool the server does not mark `readOnlyHint` is `Sequential`: foreign tools run one at a time unless the server says parallel is safe. `Policy` runs after that default, so it cannot undo it, and it can add `RequireApproval` but never remove it. `Tools` does not own the session and never closes it. For a server whose list changes, set the SDK's `ToolListChangedHandler` to call `Tools` again into a slice under a mutex, and serve the slice through [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource): the package example [`ExampleTools_toolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-Tools-ToolSource) shows the shape. [`ExampleTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-Tools) is the minimal import. `WEFT_MODEL_REQUESTS=deny` governs model requests only. A `tools/call` is not one, so imported tools still run under deny, like any handler that makes a network call. ### MCP identity Name the server when you import its tools: ```go title="mcpx/identity.go" tools, err := mcp.Tools(ctx, sess, mcp.Server("github"), // origin mcp:github: the tools record, weft.tool.origin, the call graph mcp.Transport("memory"), // how the session reaches it: stdio, http, sse, your word mcp.CallerMeta(), // send this run and call in params._meta (servers you run only) ) ``` [mcpx/identity.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/identity.go) [`mcp.Server(name)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Server) names the server an import comes from, for the record only. Every imported tool's `Origin` reads `mcp:`. That is the tools record's `source`, the `execute_tool` span's `weft.tool.origin` and the node Studio's call graph draws. [`mcp.Transport(kind)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Transport) says how the session reaches it: `stdio`, `http`, `sse`, `memory` or your own word, since the SDK's session does not say. Without `Server` the origin is plain `mcp` and no server is named. weft never names a node after the server's own `initialize` answer, which is untrusted. Neither option changes what the model sees. The tools record carries each tool's origin in parts as `source_detail`, [`weft.SourceDetail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SourceDetail): `Server`, `Transport`, `Prefix` and `RemoteName`, the tool's name on the server. Its `Skipped` field holds the tools the importer left out of the same source, each a [`weft.SkippedImport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SkippedImport) with a `Name` and a `Reason`. The record lists them once per source in `skipped[]`, as `{name, reason, source}`. It keeps at most 64, with `skipped_more` counting the rest, and cuts names at 128 bytes. Neither `source_detail` nor `skipped[]` is part of the catalog hash. A tool you build yourself sets its parts with [`weft.OriginDetail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OriginDetail). The package examples [`ExampleServer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-Server) and [`ExampleOriginDetail`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-OriginDetail) show both. Studio's Request pane names each tool's origin in parts and lists the skipped tools greyed; the call graph draws `mcp:` with its calls, its slowest call and its failures by kind ("1 unreachable · 1 refused · 1 tool error"). ![The agents level of the graph scale for a run whose tools come from an MCP server: billing-desk calling an mcp:billing node, 3 calls, 3 failed (1 unreachable, 1 refused, 1 tool error), with the get_invoice call's MCP tool error in the drawer](https://weftgo.dev/docs/_astro/studio-mcp-graph.light.DiKum4Eo.webp) *The agents level of the graph scale: billing-desk calling the mcp:billing node, its three calls unreachable, refused and a tool error.* ### Handle tools that cannot be imported A tool the bridge cannot import fails that tool, not the listing. `Tools` returns every importable tool and, beside them, an [`*mcp.ImportError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ImportError) naming each one it left out. Read it with `errors.As`: ```go title="mcpx/mcpx.go" tools, err := mcp.Tools(ctx, sess) var skipped *mcp.ImportError if errors.As(err, &skipped) { // the importable tools are in tools; these are not for _, s := range skipped.Skipped { fmt.Fprintf(w, "skipped %q (listing entry %d): %v\n", s.Name, s.Index, s.Err) } err = nil // a warning here; return it to make it a stop } if err != nil { // a listing failure: transport, ctx return err } ``` [mcpx/mcpx.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/mcpx.go) [`ImportError.Skipped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ImportError) is a list of [`mcp.SkippedTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#SkippedTool): `Name` (the server-side name, empty when the name was the problem), `Index` (the position in the listing) and `Err` (why). [`ImportError.Unwrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ImportError.Unwrap) returns each tool's cause, so `errors.Is` against a `ParseSchema` failure works through the report. A tool is skipped for: - an input schema weft cannot key on: a non-object root, a `$ref` root, or no schema; - an empty name; - a name repeated in the listing (the first importable occurrence stands); - a nil entry. `ImportError.Source` is the imported tools' origin (`mcp:`, or `mcp`). An imported tool carries its server's skipped tools into the tools record, so a partial import records them on its own. When every tool was skipped, no imported tool can: pass [`ImportError.Option()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ImportError.Option) to `weft.New` and the agent records the skips itself, through [`weft.SkippedImports`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SkippedImports). It is harmless beside importable tools; the record lists each skip once ([`ExampleImportError_Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-ImportError.Option), and [`ExampleSkippedImports`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-SkippedImports) for a tool source of your own). The slice is usable whether or not the error is set; you decide whether a skipped tool is a warning to log or a reason to stop. Any other error is a listing failure (the transport, or `ctx` ending, which returns the `ctx` error unchanged) and comes with no tools. ### Serve an agent `mcp.Serve(srv, agent, description)` exposes an agent as one MCP tool named after the agent, plus each of the agent's registered tools. `mcp.AddTools(srv, tools...)` exposes tools alone: ```go title="mcpx/mcpx.go" lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, in struct { OrderID string `json:"order_id"` }) (string, error) { return "order " + in.OrderID + " has shipped", nil }) refund := weft.Tool("refund", "Refund an order.", func(_ context.Context, _ struct{}) (string, error) { return "refunded", nil }, weft.RequireApproval()) support := weft.New( wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), ), weft.Name("support"), // Serve names the agent tool after the agent lookup, refund, ) srv := sdk.NewServer(&sdk.Implementation{Name: "support-server", Version: "1"}, nil) mcp.Serve(srv, support, "Answer a customer's question about an order.") tools := sdk.NewServer(&sdk.Implementation{Name: "tools-only", Version: "1"}, nil) mcp.AddTools(tools, lookup) // tools alone, no agent; AddTools panics on refund ``` [mcpx/mcpx.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/mcpx.go) The agent tool is [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) under the agent's name: it takes `{"prompt": string}` and returns the run's final text or submitted output. The `description` is all a client's model reads to decide when to call the agent, so write it for routing. `Serve` requires a name set with [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name). The two differ in how a call is dispatched: | | `AddTools` | `Serve` | |---|---|---| | Dispatch | [`ToolDef.Invoke`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.Invoke): the tool alone | the agent's own tools: [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool), through the agent's `WrapTools` chain, so `mw.Allow` and `mw.Audit` see each call; the agent tool: the `weft.Subagent`'s own `ToolDef.Invoke`, outside that chain, while its child run's tool calls go through the chain | | A `RequireApproval` tool | Panics at registration: MCP has no approval channel | Called directly, answers `weft: tool call requires approval: tool "refund"` with `isError`, without running; reached by the agent tool, see the gotcha on parking below | | `Timeout`, `MaxResultBytes` | Not applied | Not applied; the SDK's request handling bounds the call | | Tools from a `ToolSource` | — | Not listed; they still run inside the agent tool's own steps | | Recorded by `weft/otel` | No: a call outside a run | the agent's own tools: no, since `CallTool` outside a run leaves no run, event or span; the agent tool: yes, its child run is recorded like any run | Every failure on the serving side is an MCP tool result with `isError`, carrying the text weft's own model would see: undecodable arguments, a handler error, a panic. A tool with an output schema also returns its JSON as `structuredContent`; if its result text is not valid JSON, the call is an `isError` result instead, reading `tool "" advertised an output schema, so its result must be JSON; got non-JSON text`, never `structuredContent`. `AddTools` panics on a nil tool or a name repeated within one call, but a name an earlier `AddTools` or `Serve` call registered on the same server is replaced without an error: the MCP SDK replaces same-named tools and offers no lookup. So an `AddTools` after `Serve` can silently shadow one of the agent's tools, and the replacement runs outside the agent's `WrapTools` chain. `Serve` panics on a nil or unnamed agent and on a tool whose name collides with the agent's. The package examples [`ExampleAddTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-AddTools) and [`ExampleServe`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-Serve) call each from a client. ### Link a served run to its caller When one of your agents calls another you serve with `mcp.Serve`, the served run can record the call that made it. Opt in on the client with [`mcp.CallerMeta()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#CallerMeta) beside `mcp.Tools`' other options, as in [MCP identity](https://weftgo.dev/docs/guides/mcp/#mcp-identity). Every call the imported tools make then sends two things in `params._meta`: - the W3C `traceparent` (and `tracestate`) of its `execute_tool` span; - [`mcp.MetaCaller`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#MetaCaller), `"dev.weftgo/caller"`, holding `{"run_id", "call_id"}`. `mcp.Serve` and `AddTools`' tools read it back. The served run's `invoke_agent` span starts its own trace with an OpenTelemetry link to the caller's span, never as the caller's child. So the client's sampling flag never decides whether the server records the run. The run records `weft.caller.run.id`, `weft.caller.call.id` and `weft.caller.remote` `"true"`: a link, never `weft.parent.*`. A remote caller is the caller's own statement, so readers never place a run by it. The run stays top-level, and Studio says "started over MCP by run … in another process (not linked)". A missing or malformed `_meta` links nothing and refuses nothing. `CallerMeta` is off by default: the run and call ids and the trace state name your runs to the server. Send them to servers you run, not to a third party's. Code that is not an MCP server, such as a queue consumer or an RPC handler, links its runs the same way with [`weft.WithCaller`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WithCaller): ```go title="mcpx/identity.go" ctx = weft.WithCaller(ctx, weft.Caller{RunID: job.RunID, CallID: job.CallID}) res, err := worker.Generate(ctx, weft.Prompt(job.Prompt)) // records weft.caller.* and weft.caller.remote ``` [mcpx/identity.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/identity.go) Every run started directly on that context, not inside a tool call, records the caller. A `Caller`'s `Span` adds the OpenTelemetry link. No run started inside such a run inherits the caller. The examples [`ExampleCallerMeta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-CallerMeta), [`ExampleServe (callerLink)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#example-Serve-CallerLink) and [`ExampleWithCaller`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-WithCaller) show each side. ### Limits What the bridge does not do, by decision: - **Resources, prompts and sampling** are not bridged; only tools are. - **Progress notifications** are not surfaced. The calling step's `ToolStart` and `ToolFinish` bracket the remote call. - **Elicitation** is not answered. A server that asks fails the call, as a tool error. - **Schema bytes are re-encoded.** The SDK's client decodes the listed schema before `Tools` sees it, so the kept document has keys in canonical order, and an integer above 2^53 is rounded through `float64`. - **A non-object output schema** has no weft form and is not recorded; the result text is the tool's output either way. - **An unconstrained schema node** reaches OpenAI and Anthropic as `{}`. Before the tag `mcp` v0.1.4 (2026-09-27, when `weft/mcp` was its own module), one unparseable input schema failed the whole import. Since then it fails that tool alone, as the previous section describes. ### Complete example `mcpx/mcpx.go` imports a stand-in GitHub server's tools into an agent, imports from a server with one bad tool, and serves an agent and a tool, all in memory: ```go title="mcpx/mcpx.go" package main import ( "context" "encoding/json" "errors" "fmt" "io" "time" sdk "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/weftgo/weft" "github.com/weftgo/weft/mcp" "github.com/weftgo/weft/wefttest" ) // connect runs srv over an in-memory transport and returns a client // session connected to it. A real client dials the server instead: // sdk.CommandTransport for a subprocess, sdk.StreamableClientTransport // for HTTP. func connect(ctx context.Context, srv *sdk.Server) (*sdk.ClientSession, error) { serverSide, clientSide := sdk.NewInMemoryTransports() go func() { _ = srv.Run(ctx, serverSide) }() client := sdk.NewClient(&sdk.Implementation{Name: "support-app", Version: "1"}, nil) return client.Connect(ctx, clientSide, nil) } // githubServer stands in for a remote MCP server with three tools: a // read-only search whose schema carries an enum, a write the server does // not mark read-only, and one that always answers isError. func githubServer() *sdk.Server { srv := sdk.NewServer(&sdk.Implementation{Name: "github", Version: "0"}, nil) srv.AddTool(&sdk.Tool{ Name: "search_issues", Description: "Search issues by state.", InputSchema: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"},"state":{"type":"string","enum":["open","closed"]}},"required":["q"]}`), Annotations: &sdk.ToolAnnotations{ReadOnlyHint: true}, }, func(_ context.Context, req *sdk.CallToolRequest) (*sdk.CallToolResult, error) { return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "2 open issues match: #12, #31"}}}, nil }) srv.AddTool(&sdk.Tool{ Name: "create_issue", Description: "Open an issue.", InputSchema: json.RawMessage(`{"type":"object","properties":{"title":{"type":"string"}},"required":["title"]}`), }, func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) { return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "opened #40"}}}, nil }) srv.AddTool(&sdk.Tool{ Name: "close_issue", Description: "Close an issue.", InputSchema: json.RawMessage(`{"type":"object","properties":{"id":{"type":"integer"}},"required":["id"]}`), }, func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) { return &sdk.CallToolResult{IsError: true, Content: []sdk.Content{&sdk.TextContent{Text: "issue #12 is locked"}}}, nil }) return srv } // importTools imports the server's tools into an agent and runs one step // that calls two of them. func importTools(ctx context.Context, w io.Writer) error { sess, err := connect(ctx, githubServer()) if err != nil { return err } defer sess.Close() tools, err := mcp.Tools(ctx, sess, mcp.Prefix("gh_"), // search_issues → gh_search_issues mcp.Policy(weft.Timeout(10*time.Second)), // per-tool policy on every imported tool ) var skipped *mcp.ImportError if errors.As(err, &skipped) { fmt.Fprintln(w, "skipped:", skipped) // some tools were left out; the rest are in tools } else if err != nil { return err // the listing itself failed } opts := []weft.Option{weft.Name("triage")} for _, t := range tools { opts = append(opts, t) // an imported tool is an ordinary *weft.ToolDef } model := wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "gh_search_issues", Args: `{"q":"crash","state":"open"}`}, wefttest.Call{Name: "gh_close_issue", Args: `{"id":12}`}, ), wefttest.Say("Two issues are open; #12 is locked."), ) agt := weft.New(model, opts...) res, err := agt.Generate(ctx, weft.Prompt("Triage the crash reports.")) if err != nil { return err } for _, t := range tools { schema, _ := json.Marshal(t.InputSchema) fmt.Fprintf(w, "imported %s %s\n", t.Name, schema) } for _, r := range res.Steps[0].Results { fmt.Fprintf(w, "%s → %q error=%v\n", r.Name, r.Content, r.IsError) } fmt.Fprintln(w, "answer:", res.Text()) // The isError result is a tool error the model sees; middleware and // your own code match it with errors.Is. close := tools[0] // gh_close_issue: Tools keeps the server's listing order _, err = close.Invoke(ctx, json.RawMessage(`{"id":12}`)) fmt.Fprintf(w, "%s: errors.Is(err, mcp.ErrToolError) = %v\n", close.Name, errors.Is(err, mcp.ErrToolError)) return nil } // importWithSkips imports from a server whose listing holds one tool the // bridge cannot import. func importWithSkips(ctx context.Context, w io.Writer) error { srv := sdk.NewServer(&sdk.Implementation{Name: "mixed", Version: "0"}, nil) ok := func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) { return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: "ok"}}}, nil } srv.AddTool(&sdk.Tool{Name: "ping", InputSchema: json.RawMessage(`{"type":"object"}`)}, ok) // The Go SDK refuses a non-object root at AddTool; a server written in // another language can list one, so the example swaps it in afterwards. odd := &sdk.Tool{Name: "nullable", InputSchema: json.RawMessage(`{"type":"object"}`)} srv.AddTool(odd, ok) odd.InputSchema = json.RawMessage(`{"type":["object","null"]}`) sess, err := connect(ctx, srv) if err != nil { return err } defer sess.Close() tools, err := mcp.Tools(ctx, sess) var skipped *mcp.ImportError if errors.As(err, &skipped) { // the importable tools are in tools; these are not for _, s := range skipped.Skipped { fmt.Fprintf(w, "skipped %q (listing entry %d): %v\n", s.Name, s.Index, s.Err) } err = nil // a warning here; return it to make it a stop } if err != nil { // a listing failure: transport, ctx return err } for _, t := range tools { fmt.Fprintln(w, "imported", t.Name) } return nil } // serveAgent exposes a tool and an agent on an MCP server and calls them // as an MCP client would. func serveAgent(ctx context.Context, w io.Writer) error { lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, in struct { OrderID string `json:"order_id"` }) (string, error) { return "order " + in.OrderID + " has shipped", nil }) refund := weft.Tool("refund", "Refund an order.", func(_ context.Context, _ struct{}) (string, error) { return "refunded", nil }, weft.RequireApproval()) support := weft.New( wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), ), weft.Name("support"), // Serve names the agent tool after the agent lookup, refund, ) srv := sdk.NewServer(&sdk.Implementation{Name: "support-server", Version: "1"}, nil) mcp.Serve(srv, support, "Answer a customer's question about an order.") tools := sdk.NewServer(&sdk.Implementation{Name: "tools-only", Version: "1"}, nil) mcp.AddTools(tools, lookup) // tools alone, no agent; AddTools panics on refund sess, err := connect(ctx, srv) if err != nil { return err } defer sess.Close() for t, err := range sess.Tools(ctx, nil) { if err != nil { return err } fmt.Fprintln(w, "listed", t.Name) } for _, c := range []struct { name string args map[string]any }{ {"support", map[string]any{"prompt": "Where is order 1234?"}}, {"lookup_order", map[string]any{"order_id": "5678"}}, {"refund", map[string]any{}}, } { out, err := sess.CallTool(ctx, &sdk.CallToolParams{Name: c.name, Arguments: c.args}) if err != nil { return err } fmt.Fprintf(w, "%s → %q isError=%v\n", c.name, out.Content[0].(*sdk.TextContent).Text, out.IsError) } sess2, err := connect(ctx, tools) if err != nil { return err } defer sess2.Close() out, err := sess2.CallTool(ctx, &sdk.CallToolParams{Name: "lookup_order", Arguments: map[string]any{"order_id": "42"}}) if err != nil { return err } fmt.Fprintf(w, "tools-only lookup_order → %q\n", out.Content[0].(*sdk.TextContent).Text) return nil } // run is the page's complete example. func run(ctx context.Context, w io.Writer) error { ctx, cancel := context.WithCancel(ctx) defer cancel() // stops the in-memory servers for _, demo := range []func(context.Context, io.Writer) error{importTools, importWithSkips, serveAgent} { if err := demo(ctx, w); err != nil { return err } } return nil } ``` [mcpx/mcpx.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/mcpx/mcpx.go) Run it from `docs-site/examples`: ```sh go run ./mcpx go test ./mcpx ``` ```text imported gh_close_issue {"properties":{"id":{"type":"integer"}},"required":["id"],"type":"object"} imported gh_create_issue {"properties":{"title":{"type":"string"}},"required":["title"],"type":"object"} imported gh_search_issues {"properties":{"q":{"type":"string"},"state":{"enum":["open","closed"],"type":"string"}},"required":["q"],"type":"object"} gh_search_issues → "2 open issues match: #12, #31" error=false gh_close_issue → "issue #12 is locked" error=true answer: Two issues are open; #12 is locked. gh_close_issue: errors.Is(err, mcp.ErrToolError) = true skipped "nullable" (listing entry 0): weft: ParseSchema: top-level type must be "object", got "" imported ping listed lookup_order listed refund listed support support → "Order 1234 has shipped." isError=false lookup_order → "order 5678 has shipped" isError=false refund → "weft: tool call requires approval: tool \"refund\"" isError=true tools-only lookup_order → "order 42 has shipped" ``` The `enum` on `state` survived the import. The locked issue came back as an error result the model read, and the run went on. ### Best practices & gotchas - **Treat a server's tool descriptions as untrusted input.** They land in your model's tool list, text you did not write. Read what `Tools` returns before registering it, or filter calls with `mw.Allow`. (Source: `weft/README.md:862-867`) - **Expect foreign tools to run one at a time.** A tool without `readOnlyHint` is `Sequential`, the conservative reading of an untrusted hint. (Source: `weft/mcp/client.go:54-57`, `weft/mcp/client.go:164-190`) - **Do not return on every error from `Tools`.** An `*mcp.ImportError` comes with the good tools; check for it with `errors.As` first. (Source: `weft/mcp/client.go:89-110`, `weft/CHANGELOG.md:5718`) - **Keep a schema'd tool's output JSON.** Under `AddTools` and `Serve`, a tool with an `OutputSchema` whose result is not JSON becomes an `isError` result. That bites a `RawTool` given an output schema that returns plain text, and tool middleware that rewrites a typed tool's output into prose. (Source: `weft/mcp/server.go:195-214`) - **Check an imported schema against Gemini's subset.** On the google adapter, `oneOf`, `$ref` and the other keywords `genai.Schema` lacks are dropped without an error, so the model sees a looser schema than the server declared. Validate the arguments in the server, or keep such tools on openai or anthropic. (Source: `weft/google/convert.go:354-381`, `weft/google/model_test.go:278-306`) - **Keep tool names unique across every registration on one server.** A later `AddTools` or `Serve` replaces an earlier tool of the same name without an error, so check names yourself, or use `mcp.Prefix` on imported tools you re-export. (Source: `weft/mcp/server.go:26-29`, `weft/mcp/server.go:151-163`) - **Use `Serve`, not `AddTools`, for an approval-gated tool.** `AddTools` panics on it; `Serve` answers with the approval error instead of running it. (Source: `weft/mcp/server.go:26-30`, `weft/mcp/server.go:172-177`) - **Do not serve an agent whose run can park.** The agent tool is a `weft.Subagent`. When its child run parks, on a `RequireApproval` tool, a `weft.ParkSource` or middleware returning `ErrApprovalRequired`, the client gets an `isError` result: `SUBAGENT_PENDING: agent "support" ended awaiting approval of 1 call(s)`. Nothing can approve it over MCP, so the call never runs. (Source: `weft/mcp/server.go:150`, `weft/core/subagent.go:327-330`, `weft/core/loop.go:412`) - **Keep gated actions in your own app.** The `support` agent above has a gated `refund`; its scripted run never calls it, but a real model routing a refund to it would park. Serve an agent built without gated tools, and resume parked runs in your app with `weft.Approve` or a session's `Decide` ([Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/)). (Source: `docs-site/examples/mcpx/mcpx.go:164-177`) - **Expect no Studio record of direct served calls.** `Serve` dispatches the agent's own tools through `Agent.CallTool` on the MCP request's context, outside any run, so with `otel.Install` on they leave no run, event or span. Only calls to the agent tool show up in Studio, as the child run it starts. To keep a record of direct calls in your own logs, add `mw.Audit` to the agent's `WrapTools`. Its lines do not reach Studio either: `otel.Slog()` bridges only lines logged on a span-carrying context, and these calls have none. (Source: `weft/mcp/server.go:172-191`; `weft/core/loop.go:1691-1701`) - **Bound imported calls with `mcp.Policy(weft.Timeout(d))`.** A remote call is a network call; the run's tool timeout is what stops a hung server. (Source: `weft/README.md:842`, AGENTS.md rule 9) ### See also - [How do tools work?](https://weftgo.dev/docs/concepts/tools/) - [Define tools at runtime: RawTool and ToolSource](https://weftgo.dev/docs/guides/dynamic-tools/) - [Delegate to another agent (subagents)](https://weftgo.dev/docs/guides/subagents/) - [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) - [Let Claude Code or Cursor read your runs (weft mcp)](https://weftgo.dev/docs/observe/weft-mcp/): a different thing, the CLI that serves Studio's read routes over MCP Symbols used: [`mcp.Tools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Tools) · [`mcp.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Option) · [`mcp.Prefix`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Prefix) · [`mcp.Policy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Policy) · [`mcp.ErrToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ErrToolError) · [`mcp.ImportError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ImportError) · [`ImportError.Unwrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#ImportError.Unwrap) · [`mcp.SkippedTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#SkippedTool) · [`mcp.AddTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#AddTools) · [`mcp.Serve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Serve) · [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) · [`weft.ParseSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParseSchema) · [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`ToolDef.Invoke`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.Invoke) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [Go MCP SDK `mcp` package](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk@v1.8.0/mcp) --- # Add behaviour with middleware (the two seams) URL: https://weftgo.dev/docs/guides/middleware/ Markdown: https://weftgo.dev/docs/guides/middleware.md > Wrap the model with weft.WrapModel and every tool call with weft.WrapTools; the first middleware listed is the outermost, and package mw holds the reference set. Behaviour you add to a run attaches at two seams. [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) wraps the agent's model, so middleware sees every request the loop sends; [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) wraps every tool call the loop dispatches. In both, the first middleware listed is the outermost, and package [`mw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw) ships the reference set. Both seams on one agent, in `middleware/seams.go`: ```go title="middleware/seams.go" lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, _ struct{}) (string, error) { fmt.Fprintln(w, "handler: lookup_order") return "shipped", nil }, weft.WrapTools(trace(w, "tool")), // this tool only, inside the agent's chain ) agt := weft.New( wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order"}), wefttest.Say("It has shipped."), ), weft.WrapModel(logRequests(w)), weft.WrapTools(trace(w, "outer"), trace(w, "inner")), // first listed = outermost lookup, ) _, err := agt.Generate(ctx, weft.Prompt("Where is my order?")) ``` [middleware/seams.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/seams.go) `logRequests` prints a line per model request. The three `trace` middleware print before and after the rest of the chain, which shows the order a call takes: ```text model request: 1 messages, 1 tools outer: before lookup_order inner: before lookup_order tool: before lookup_order handler: lookup_order tool: after lookup_order inner: after lookup_order outer: after lookup_order model request: 3 messages, 1 tools ``` ### The two seams Each seam is a function from the next link to a new one, the shape `net/http` routers such as chi use: | Seam | Option | Middleware type | Wraps | |---|---|---|---| | Model | `weft.WrapModel(mw...)` | [`weft.ModelMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelMiddleware): `func(next weft.Model) weft.Model` | every model call the loop makes | | Tool | `weft.WrapTools(mw...)` | [`weft.ToolMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolMiddleware): `func(next weft.ToolCaller) weft.ToolCaller` | every tool call the loop and [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) dispatch | `WrapModel(a, b)` calls `a(b(model))`; `WrapTools(a, b)` runs `a(b(call))`. A later `WrapModel` or `WrapTools` option appends inward. Nil entries are ignored. The model chain is built once, at `weft.New`. `WrapTools` works on a tool too: passed to `weft.Tool`, it wraps that tool alone, inside the agent's chain. A tool call goes through, in order: the agent's middleware, the tool's own middleware, then the base, which resolves the tool, checks `RequireApproval`, decodes the arguments and runs the handler. Two seams is the whole set. Observation is a third thing, [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap), which sees every event and changes nothing. A third seam needs an ADR. To see where each phase of a step and a tool call sits around the seams, read [`docs/life-of-a-call.md`](https://github.com/weftgo/weft/blob/v0.20.2/docs/life-of-a-call.md). ### Model middleware A `ModelMiddleware` returns a `weft.Model` that wraps `next`. It sees each [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) as the loop built it, after `PrepareStep`, and every event the inner model yields. It may log, retry, substitute or rewrite: ```go title="middleware/seams.go" // logRequests is a ModelMiddleware: it prints a line for every request // the loop sends, then streams the inner model's reply unchanged. func logRequests(w io.Writer) weft.ModelMiddleware { return func(next weft.Model) weft.Model { return requestLogger{next: next, w: w} } } type requestLogger struct { next weft.Model w io.Writer } func (m requestLogger) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { fmt.Fprintf(m.w, "model request: %d messages, %d tools\n", len(req.Messages), len(req.Tools)) return m.next.Stream(ctx, req) } // Info and Unwrap forward the inner model's identity and declare it. func (m requestLogger) Info() weft.ModelInfo { return weft.InfoOf(m.next) } func (m requestLogger) Unwrap() weft.Model { return m.next } ``` [middleware/seams.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/seams.go) **A middleware may rewrite its own request.** Each request carries its own copies of the slices, of each message's `Content`, and of `Params`' values. `mw.Retry` and `mw.Fallback` hand each attempt a fresh copy. So a write such as `*req.Params.Temperature` holds for that attempt alone. Nothing leaks to the agent, the run option, the caller's variable, a later step or the next attempt: ```go title="middleware/params.go" // capTemperature is a ModelMiddleware that writes the request's own // temperature: since 0.18.1 each request, and each mw.Retry or // mw.Fallback attempt, carries its own copy of Params' values, so the // write reaches neither the agent, the run option, the caller's // variable, a later step nor the next attempt. func capTemperature(limit float64) weft.ModelMiddleware { return func(next weft.Model) weft.Model { return tempCap{next: next, limit: limit} } } type tempCap struct { next weft.Model limit float64 } func (m tempCap) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { if t := req.Params.Temperature; t != nil && *t > m.limit { *t = m.limit // this request's copy; the bytes inside parts stay read-only } return m.next.Stream(ctx, req) } func (m tempCap) Info() weft.ModelInfo { return weft.InfoOf(m.next) } func (m tempCap) Unwrap() weft.Model { return m.next } ``` [middleware/params.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/params.go) `TestCapTemperature` runs it inside `mw.Retry` with a temperature of 0.9: both tries are sent 0.5, and the caller's variable still reads 0.9. The bytes inside parts (`Args`, `Data`) stay shared and read-only. Forward the inner model's identity with [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf), so `RunStart.Model` and the manifest still name the provider. Declare the wrapped model with an `Unwrap` method, so a caller can walk the chain with [`weft.Unwrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Unwrap). A middleware that returns a nil `Model` panics at `New`. The package example [`ExampleWrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-WrapModel) is the same shape. ### Tool middleware A [`weft.ToolCaller`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCaller) takes a call and returns the result text the model will see, or an error. A `ToolMiddleware` wraps one and may act before `next` (deny, decorate `ctx`, log), after it (map errors, audit), or instead of it: ```go title="middleware/seams.go" // trace is a ToolMiddleware that prints before and after the rest of the // chain runs. func trace(w io.Writer, name string) weft.ToolMiddleware { return func(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { fmt.Fprintf(w, "%s: before %s\n", name, call.Name) out, err := next(ctx, call) fmt.Fprintf(w, "%s: after %s\n", name, call.Name) return out, err } } } ``` [middleware/seams.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/seams.go) What the middleware returns decides what the model sees: - **A string and nil** is the result. - **A `*weft.ToolError`** gives the model a code: `&weft.ToolError{Code: "DENIED", Message: "this agent is read-only"}` reads `DENIED: this agent is read-only`. - **Any other error** is rendered as its text, exactly as a handler error would be. - **An error wrapping `weft.ErrApprovalRequired`** is the one non-result: the call parks on `RunResult.Pending`. See [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/). A middleware panic is a `tool "x" panicked: …` result, never a run error: panic containment sits outside the chain. So does `weft.Timeout`, which bounds the whole chain. An unknown tool still runs the agent's chain, so `mw.Allow` and `mw.Audit` see the attempt, before the base returns `NO_SUCH_TOOL`. The package example [`ExampleWrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-WrapTools) denies every `delete_` tool. ### Pass facts on the context Middleware that verifies something (a user, a tenant, a quota) puts it on `ctx` before calling `next`. The handler reads it back through a typed accessor, the same shape as [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext): ```go title="middleware/seams.go" // The accessor pair: only this package can put a user on a context. type user struct{ Name string } type userKey struct{} func withUser(ctx context.Context, u user) context.Context { return context.WithValue(ctx, userKey{}, u) } func userFrom(ctx context.Context) (user, bool) { u, ok := ctx.Value(userKey{}).(user) return u, ok } // authenticate verifies the caller before next and puts the user on ctx. func authenticate(lookup func(ctx context.Context) (user, error)) weft.ToolMiddleware { return func(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { u, err := lookup(ctx) if err != nil { return "", &weft.ToolError{Code: "UNAUTHENTICATED", Message: "sign in first", Err: err} } return next(withUser(ctx, u), call) } } } // myOrders reads the verified user back; it never trusts the arguments // for who is calling. var myOrders = weft.Tool("my_orders", "List the caller's orders.", func(ctx context.Context, _ struct{}) (string, error) { u, ok := userFrom(ctx) if !ok { return "", weft.Errorf("UNAUTHENTICATED", "no user on the call") } return "orders for " + u.Name + ": 1234, 5678", nil }) ``` [middleware/seams.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/seams.go) With a verified user, `my_orders` returns `orders for ada: 1234, 5678`. When the lookup fails, the middleware never calls `next` and the model reads `UNAUTHENTICATED: sign in first`; the cause stays on `ToolError.Err` for logs. Put only verified data on the context, and derive business values in the handler after decoding. The package example is [`ExampleWrapTools_context`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-WrapTools-Context). ### Reference middleware Package `mw` holds small, dependency-free middleware for both seams. Copy one, compose them, or write your own: | Middleware | Seam | What it does | |---|---|---| | [`mw.Allow(permit)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Allow) | tool | Runs a call only when `permit(call)` is true | | [`mw.Audit(logger)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Audit) | tool | One Info line per call | | [`mw.MapErrors(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MapErrors) | tool | Shapes handler errors before the model sees them | | [`mw.Log(logger)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Log) | model | One Debug line before and one after each model call | | [`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry), [`mw.Fallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Fallback), [`mw.FallbackWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#FallbackWhen) | model | Retry with backoff, then fail over: [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/) | | [`mw.RepairJSON`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RepairJSON) | model | Closes a truncated or fenced tool-call argument object once: [Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/) | The tool trio together, with `mw.Log` on the model: ```go title="middleware/seams.go" permit := func(c weft.Call) bool { return !strings.HasPrefix(c.Name, "delete_") } agt := weft.New(model, weft.WrapModel(mw.Log(logger)), // Debug: one line before and one after each model call weft.WrapTools( mw.Audit(logger), // observation: one Info line per call, with the cause mw.Allow(permit), // decision: DENIED: tool "x" is not allowed mw.MapErrors(nil), // shaping: plain errors → INTERNAL: tool "x" failed ), lookup, query, deleteOrder, ) res, err := agt.Generate(ctx, weft.RunID("run-1"), weft.Prompt("Status, report, then delete 1234.")) ``` [middleware/seams.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/seams.go) The order follows the godoc's: observation outermost, then the decision, then shaping. `mw.Audit` outside `mw.Allow` logs denied calls too. On the model seam the godoc's order is `mw.Log`, `mw.Fallback`, `mw.Retry`, `mw.RepairJSON`, outermost first. `mw` ships no rate limiter, because `golang.org/x/time` would be its first dependency; [`Example_rateLimitMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-package-RateLimitMiddleware) builds one from the standard library. #### Allow `mw.Allow(permit)` gates every call on a predicate over its [`weft.Call`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Call). A denied call never runs: the model reads `DENIED: tool "delete_order" is not allowed` and the loop moves on, with no retry and no prompt. A nil `permit` allows every call. Outside the loop (`Agent.CallTool` with a bare `ctx`) the `Call` is built from the call part alone. `Allow` is a fixed policy; a decision deferred to a person is [approval](https://weftgo.dev/docs/guides/approvals/). Package example: [`ExampleAllow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-Allow). #### Audit `mw.Audit(logger)` logs one line per call at Info level, on `slog.Default` when `logger` is nil: run, step, call id, tool, duration, and the outcome. A failed call's line carries the model-visible text as `err` and, for a `*weft.ToolError` with a cause, the cause as `cause`. Under the agent's `weft.Content(false)` neither text is logged, only `err_bytes` (the text's length) and the `ToolError` code. Audit changes nothing. Package example: [`ExampleAudit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-Audit). #### Log `mw.Log(logger)` writes a Debug line before each model call (provider, model, message and tool counts) and one after it (stop reason, usage, tool-call count, duration). Placed outermost it sees the outcome of retries and fallbacks; placed innermost, each attempt. A nil `logger` means `slog.Default`. Package example: [`ExampleLog`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-Log). #### Map errors `mw.MapErrors(fn)` shapes handler errors in one place. A `*weft.ToolError`, a context error and `ErrApprovalRequired` pass through untouched; every other error goes through `fn`. With a nil `fn`, the default hides the text (database messages, stack fragments) behind `INTERNAL: tool "query" failed` and keeps the original as the `ToolError`'s cause, where `mw.Audit` and `errors.As` still find it. When `fn` returns nil, the original error stands. Package example: [`ExampleMapErrors`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-MapErrors). ### Check middleware keeps model info [`wefttest.ConformInfo(m)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfo) returns nil when model middleware `m` forwards the inner model's identity unchanged, and an error otherwise, showing the `Info` it got and the one it wanted. The error names the function's Go type, `core.ModelMiddleware`, not which middleware failed, so call it once per middleware. [`wefttest.ConformInfoT`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfoT) is the test-helper form. Add one line to your middleware's tests, from `middleware/middleware_test.go`: ```go title="middleware/middleware_test.go" // The convention, checked: logRequests forwards the inner model's // identity, so RunStart.Model and the manifest still name the provider. func TestLogRequestsKeepsModelInfo(t *testing.T) { wefttest.ConformInfoT(t, logRequests(&bytes.Buffer{})) } ``` [middleware/middleware_test.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/middleware_test.go) ### The onion in the record Since 0.20.0 the record says which middleware wrapped a call and what each layer decided, at three levels. All of it reports only: nothing here changes a call, a retry, a denial or a result. **The manifest lists the chain.** Each agent's manifest names its `model_middleware` and `tool_middleware` outer to inner, with a tool's own middleware under the tool. It also lists the hooks the agent has: `prepare_step`, `tap`, `on_run_end` and `tool_source`. Each entry is `{name, params?, source?, opaque?}`, a [`weft.MiddlewareInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MiddlewareInfo). A model layer may describe itself with an optional `Describe() weft.MiddlewareInfo` method. `mw.Retry` reports its budget and delays, `mw.Fallback` its backups, `mw.Log` and `mw.RepairJSON` their names. Any other model layer is named by its type, and the walk goes inward through `Unwrap`. A layer without `Unwrap` ends the walk and is marked `opaque`, so the chain never reads shorter than it is without saying so. Put only configuration in `Describe()`'s `Params`: counts, durations, model names. Never put a secret or a closure's captured value there. The manifest is hashed into every run's `weft.manifest.hash`, and Studio serves it whole at `GET /api/manifests/{hash}`. A tool middleware is a function, so it is named by what the function is: ```go title="middleware/onion.go" agt := weft.New(wefttest.Script(), weft.Name("payments"), weft.WrapTools( mw.Allow(func(weft.Call) bool { return true }), // "mw.Allow", no source budget, // ".budget" ("main.budget" in a command), source "/onion.go:17" func(next weft.ToolCaller) weft.ToolCaller { return next }, // "func@middleware/onion.go:38", that place its source )) b, err := weft.Manifest(agt) ``` [middleware/onion.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/onion.go) | Tool middleware | `name` | `source` | |---|---|---| | weft's own (`mw.Allow`, `mw.Audit`, `mw.MapErrors`) | its name, registered with [`weft.NameToolMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#NameToolMiddleware) | none | | a named function or method | its package-qualified name, such as `main.budget` in a command | its position, such as `github.com/x/app/budget.go:17` | | a closure | `func@/:`, where it is written, such as `func@app/main.go:42`; Studio's layer drawer shows it as `main.go:42` | the same place, `app/main.go:42` | Wrap your own constructor's closure in `weft.NameToolMiddleware(name, mw)` to give it a name instead. The name belongs to the function literal, not to one closure of it: every closure of that literal shares it, and a later call for the same literal replaces it, in agents already built too. A constructor that names each closure from its argument (`"limit:"+name`) leaves every agent's manifest with the last name it was called with. `weft.manifest.hash` is computed once, at `New`, so an agent built before that last call keeps its old hash on every run while `weft.Manifest(a)` now holds the new name and hashes differently: its runs no longer match its own manifest, and they read stale against a registration or `weft.json` made later. Give each distinct name its own literal, or keep the name constant. The names do not depend on what the compiler inlined or on the Go version. A named function's `source` is one form on every machine: the defining package's import path, the file's base name and the line, never an absolute path. A closure's is its directory's name and file. Because the manifest lists the onion, adding or removing middleware changes `weft.manifest.hash` ([The manifest hash](https://weftgo.dev/docs/guides/manifest/#the-manifest-hash)). [`ExampleMiddlewareInfo`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-MiddlewareInfo) prints one. **The spans say what a layer decided.** A tool middleware tells the call's `execute_tool` span through [`weft.ToolReportFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolReportFromContext)`(ctx)`, a [`ToolReporter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolReporter): ```go title="middleware/onion.go" // budget refuses wire_money and says so on the call's execute_tool span // (weft.tool.denied_by "budget"). Reporting changes nothing the model sees. func budget(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { if call.Name == "wire_money" { weft.ToolReportFromContext(ctx).Denied("budget") return "", &weft.ToolError{Code: weft.CodeDenied, Message: "over budget"} } return next(ctx, call) } } ``` [middleware/onion.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/onion.go) | Reporter call | Span attribute | Set by | |---|---|---| | `Denied(by)` | `weft.tool.denied_by` | `mw.Allow` reports `allow`; a deny grant on a resume `grant` (with `weft.grant.id`), else `approval` | | `Masked(original)` | `weft.tool.error_masked` | `mw.MapErrors`: the hidden error's kind, never its text. The kind is the first of: an `ErrorKind() string` method, a context error's name, an `ErrorType()` method, a `ToolError`'s code, a standard sentinel through `errors.Is` (`io.EOF`, `fs.ErrNotExist`), else the error's Go type. Studio and the devtools panel read a plain error's type (`*errors.errorString`) as "plain error" and an `errors.Join` or two-`%w` error's as "joined errors"; the attribute keeps the type. A mapping that only wraps reports nothing | Three rules bound these reports. `Denied(by)` reaches the span only when the call then ends in an error. The last report of a kind wins. Outside a loop-dispatched call, `Agent.CallTool` included, `ToolReportFromContext` returns a reporter that discards every report. A model middleware that rewrites a call's arguments reports it with [`Reporter.Repair`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Repair) and a [`weft.RepairInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RepairInfo) (`CallID`, `Kind`, `Original`, `Repaired`): the step's `chat` span gets a `weft.repair` event and the call `weft.tool.args_repaired`. `mw.RepairJSON` does this, with the kinds `fence`, `unterminated`, `fence+unterminated` and `trim`. `mw.Retry` marks the requests it sent again with `weft.attempt.layer` `retry` ([Report attempts](https://weftgo.dev/docs/guides/retries-and-fallback/#report-attempts)). The examples [`ExampleToolReportFromContext`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-ToolReportFromContext) and [`ExampleReporter_Repair`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Reporter.Repair) show both. **Development detail shows every layer.** [`otel.DevDetail()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#DevDetail) adds one `layer ` span per `WrapModel` or `WrapTools` layer per call, named as the manifest names the layer. The spans nest outer to inner under the call's `chat` or `execute_tool` span. Each carries `weft.layer.name`, `weft.layer.kind` (`model` or `tool`), `weft.layer.index` (0 the outermost) and `error.type` where the layer returned an error. The `weft.repair` event then carries the original arguments, capped at 4 KiB. A contained tool or middleware panic's stack rides its `execute_tool` span as a `weft.panic` event, capped at 16 KiB. It is off by default: a span per layer is 2 to 6 more spans per call. Like `RawBodies` it takes effect only behind the development gate (`WEFT_ENV=dev`, or `otel.DevMode()`); otherwise `Start` logs `otel: DevDetail ignored: …`. Only the Local and Studio destinations with content on receive it ([Record provider wire bodies](https://weftgo.dev/docs/observe/destinations/#record-provider-wire-bodies-development-only)). Pass the pipeline's logger provider to the agent with `weft.LoggerProvider(p.LoggerProvider())`, or rely on `Install`'s global registration. With the option the agent knows the level at `New` and builds the layer boundaries into its one model chain. Through the global provider it cannot: the first run builds a second chain, so your `WrapModel` constructors run twice and a stateful middleware holds two states. [`ExampleDevDetail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#example-DevDetail) shows it. Studio draws all three in the run page's "what wrapped this call" ([Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/#what-wrapped-this-call)). ### Complete example `middleware/seams.go` runs the chain-order demo, the context accessor with a good and a failed lookup, and the reference middleware on three parallel calls: ```go title="middleware/seams.go" package main import ( "context" "errors" "fmt" "io" "iter" "log/slog" "slices" "strings" "github.com/weftgo/weft" "github.com/weftgo/weft/mw" "github.com/weftgo/weft/wefttest" ) // logRequests is a ModelMiddleware: it prints a line for every request // the loop sends, then streams the inner model's reply unchanged. func logRequests(w io.Writer) weft.ModelMiddleware { return func(next weft.Model) weft.Model { return requestLogger{next: next, w: w} } } type requestLogger struct { next weft.Model w io.Writer } func (m requestLogger) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { fmt.Fprintf(m.w, "model request: %d messages, %d tools\n", len(req.Messages), len(req.Tools)) return m.next.Stream(ctx, req) } // Info and Unwrap forward the inner model's identity and declare it. func (m requestLogger) Info() weft.ModelInfo { return weft.InfoOf(m.next) } func (m requestLogger) Unwrap() weft.Model { return m.next } // trace is a ToolMiddleware that prints before and after the rest of the // chain runs. func trace(w io.Writer, name string) weft.ToolMiddleware { return func(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { fmt.Fprintf(w, "%s: before %s\n", name, call.Name) out, err := next(ctx, call) fmt.Fprintf(w, "%s: after %s\n", name, call.Name) return out, err } } } // seamOrder runs one tool call through two agent middleware and one tool // middleware, and one model call through logRequests. func seamOrder(ctx context.Context, w io.Writer) error { lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, _ struct{}) (string, error) { fmt.Fprintln(w, "handler: lookup_order") return "shipped", nil }, weft.WrapTools(trace(w, "tool")), // this tool only, inside the agent's chain ) agt := weft.New( wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order"}), wefttest.Say("It has shipped."), ), weft.WrapModel(logRequests(w)), weft.WrapTools(trace(w, "outer"), trace(w, "inner")), // first listed = outermost lookup, ) _, err := agt.Generate(ctx, weft.Prompt("Where is my order?")) return err } // The accessor pair: only this package can put a user on a context. type user struct{ Name string } type userKey struct{} func withUser(ctx context.Context, u user) context.Context { return context.WithValue(ctx, userKey{}, u) } func userFrom(ctx context.Context) (user, bool) { u, ok := ctx.Value(userKey{}).(user) return u, ok } // authenticate verifies the caller before next and puts the user on ctx. func authenticate(lookup func(ctx context.Context) (user, error)) weft.ToolMiddleware { return func(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { u, err := lookup(ctx) if err != nil { return "", &weft.ToolError{Code: "UNAUTHENTICATED", Message: "sign in first", Err: err} } return next(withUser(ctx, u), call) } } } // myOrders reads the verified user back; it never trusts the arguments // for who is calling. var myOrders = weft.Tool("my_orders", "List the caller's orders.", func(ctx context.Context, _ struct{}) (string, error) { u, ok := userFrom(ctx) if !ok { return "", weft.Errorf("UNAUTHENTICATED", "no user on the call") } return "orders for " + u.Name + ": 1234, 5678", nil }) // contextFacts runs my_orders once with a verified user and once with a // failed lookup. func contextFacts(ctx context.Context, w io.Writer) error { for _, lookup := range []func(context.Context) (user, error){ func(context.Context) (user, error) { return user{Name: "ada"}, nil }, func(context.Context) (user, error) { return user{}, errors.New("session expired") }, } { agt := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "my_orders"}), wefttest.Say("Done."), ), myOrders, weft.WrapTools(authenticate(lookup))) res, err := agt.Generate(ctx, weft.Prompt("Show my orders.")) if err != nil { return err } fmt.Fprintln(w, "my_orders →", res.Steps[0].Results[0].Content) } return nil } // referenceSet runs the reference tool middleware together. func referenceSet(ctx context.Context, w io.Writer) error { // Drop the time and duration attributes so the output is stable. stable := func(_ []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey || a.Key == "dur" { return slog.Attr{} } return a } var logs strings.Builder logger := slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: stable})) lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, _ struct{}) (string, error) { return "shipped", nil }) query := weft.Tool("query", "Run a report query.", func(_ context.Context, _ struct{}) (string, error) { return "", errors.New("pq: SSL is not enabled on the server") }) deleteOrder := weft.Tool("delete_order", "Delete an order.", func(_ context.Context, _ struct{}) (string, error) { return "deleted", nil }) model := wefttest.Script( wefttest.ToolCalls( wefttest.Call{ID: "c1", Name: "lookup_order"}, wefttest.Call{ID: "c2", Name: "query"}, wefttest.Call{ID: "c3", Name: "delete_order"}, ), wefttest.Say("Order shipped; the report and the delete failed."), ) permit := func(c weft.Call) bool { return !strings.HasPrefix(c.Name, "delete_") } agt := weft.New(model, weft.WrapModel(mw.Log(logger)), // Debug: one line before and one after each model call weft.WrapTools( mw.Audit(logger), // observation: one Info line per call, with the cause mw.Allow(permit), // decision: DENIED: tool "x" is not allowed mw.MapErrors(nil), // shaping: plain errors → INTERNAL: tool "x" failed ), lookup, query, deleteOrder, ) res, err := agt.Generate(ctx, weft.RunID("run-1"), weft.Prompt("Status, report, then delete 1234.")) if err != nil { return err } for _, r := range res.Steps[0].Results { fmt.Fprintf(w, "%s → %s\n", r.Name, r.Content) } // The calls ran in parallel, so their audit lines are sorted by call id. var audit []string for _, line := range strings.Split(strings.TrimSpace(logs.String()), "\n") { if strings.Contains(line, `msg="tool call"`) { audit = append(audit, line[strings.Index(line, "run="):]) } } slices.Sort(audit) for _, line := range audit { fmt.Fprintln(w, "audit:", line) } return nil } // demoSeams is the middleware page's complete example. func demoSeams(ctx context.Context, w io.Writer) error { for _, demo := range []func(context.Context, io.Writer) error{seamOrder, contextFacts, referenceSet} { if err := demo(ctx, w); err != nil { return err } } return nil } ``` [middleware/seams.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/seams.go) Run it from `docs-site/examples`: ```sh go run ./middleware seams go test ./middleware ``` ```text model request: 1 messages, 1 tools outer: before lookup_order inner: before lookup_order tool: before lookup_order handler: lookup_order tool: after lookup_order inner: after lookup_order outer: after lookup_order model request: 3 messages, 1 tools my_orders → orders for ada: 1234, 5678 my_orders → UNAUTHENTICATED: sign in first lookup_order → shipped query → INTERNAL: tool "query" failed delete_order → DENIED: tool "delete_order" is not allowed audit: run=run-1 step=0 call=c1 tool=lookup_order result_bytes=7 audit: run=run-1 step=0 call=c2 tool=query err="INTERNAL: tool \"query\" failed" cause="pq: SSL is not enabled on the server" audit: run=run-1 step=0 call=c3 tool=delete_order err="DENIED: tool \"delete_order\" is not allowed" ``` ### Best practices & gotchas - **List the outermost middleware first.** `WrapModel(a, b)` is `a(b(model))`; a later option appends inward. (Source: `weft/core/agent.go:265-271`, `weft/core/tool.go:569-580`) - **Put `mw.Fallback` outside `mw.Retry`.** Then the primary is retried to exhaustion before the backup is tried; the reverse retries the whole fallback chain. (Source: `weft/core/mw/doc.go:15-19`) - **Forward `Info` and declare `Unwrap` in model middleware.** Without `Info`, `RunStart.Model` and the manifest lose the provider; `wefttest.ConformInfoT` catches it. (Source: `weft/core/agent.go:246-253`, `weft/core/wefttest/conform.go:15-22`) - **Decorate `ctx` only with what the middleware verified.** Handlers trust what an accessor returns; arguments come from the model. (Source: `weft/docs/adr/0006-seams.md:59-64`) - **Observe events with `weft.Tap`; reach for observing middleware only at the seam.** A tap sees every event and changes nothing. Use `mw.Audit` or `mw.Log` when you need the call's context or its outcome where the call is made. (Source: AGENTS.md rule 10, `weft/core/mw/doc.go:23`, `weft/core/mw/tool.go:45-53`, `weft/core/mw/model.go:297-302`) - **Expect parallel calls to log out of order.** Tool calls in one step run concurrently, so `mw.Audit` lines arrive in completion order; sort by call id when the order matters. (Source: `docs-site/examples/middleware/seams.go` referenceSet, AGENTS.md rule 3) ### See also - [How do tools work?](https://weftgo.dev/docs/concepts/tools/) - [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/) - [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/) - [Observe a run without changing it: Tap, OnRunEnd, OnMessages](https://weftgo.dev/docs/guides/observers/) - [What is a Model? The provider contract](https://weftgo.dev/docs/concepts/models/) Symbols used: [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) · [`weft.ModelMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelMiddleware) · [`weft.ToolMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolMiddleware) · [`weft.ToolCaller`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCaller) · [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) · [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) · [`weft.Unwrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Unwrap) · [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`weft.Errorf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Errorf) · [`weft.ErrApprovalRequired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalRequired) · [`weft.Call`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Call) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.Content`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Content) · [`weft.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunID) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`mw.Allow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Allow) · [`mw.Audit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Audit) · [`mw.MapErrors`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MapErrors) · [`mw.Log`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Log) · [`wefttest.ConformInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfo) · [`wefttest.ConformInfoT`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfoT) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Retry and fall back when a provider fails URL: https://weftgo.dev/docs/guides/retries-and-fallback/ Markdown: https://weftgo.dev/docs/guides/retries-and-fallback.md > Wrap the model with mw.Retry to retry rate limits, overload and transport errors with backoff and the provider's retry-after, add mw.Fallback for a backup model, and see each attempt on the run's record. [`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry) is model middleware that retries a model call which failed before yielding any event: rate limits, overload, transport errors, an idle stream. It backs off between tries and honours the provider's retry-after. [`mw.Fallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Fallback) tries a backup model when the primary still fails. Both report every attempt on the run's record. Retry the model, in `middleware/retries.go`: ```go title="middleware/retries.go" agt := weft.New(primary, weft.WrapModel(mw.Retry( mw.MaxRetries(3), // retries after the first try (default 3) mw.BaseDelay(10*time.Millisecond), // first backoff (default 500ms), doubling, capped at 8s mw.MaxWait(30*time.Second), // a longer retry-after fails at once (default 60s) mw.Classifier(func(err error) bool { return mw.Retryable(err) || errors.Is(err, errWarmingUp) }), )), attempts(w), // print each reported attempt ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) ``` [middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go) The scripted model fails twice, then answers. The agent's `weft.Logger` prints each reported attempt: ```text attempt attempt=1 model=large err=model is warming up attempt attempt=2 model=large retry_after=5ms layer=retry wait=10ms status=429 err=provider: 429 Too Many Requests attempt attempt=3 model=large layer=retry wait=5ms retry: "Order 1234 has shipped." after 3 requests ``` The first failure is retried because the custom classifier accepts it, after a backoff of about 10 ms (between 7.5 and 12.5 ms: ±25% jitter). The second is a 429 that asked for 5 ms, and Retry waited exactly that. ### How it works The loop never retries a model call itself. Retries are model-seam middleware, installed with [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) like any other: see [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/). `Retry` and `Fallback` act only on a call that failed **before any event reached the loop**. Once part of a reply has been consumed, no middleware can take it back, so a failure after the first event is the run's error. With the default classifier and fallback predicate, context cancellation and the `WEFT_MODEL_REQUESTS=deny` kill switch never retry and never fall through; a custom `mw.Classifier` or `mw.FallbackWhen` predicate replaces those rules and can change that. `Retry` itself never retries once the run's context is done. Each attempt gets its own copy of the request's slices and `Params` values. What a failed attempt's model, or a middleware inside `Retry`, wrote into its request never reaches the next attempt ([rewrite a request](https://weftgo.dev/docs/guides/middleware/#model-middleware)). The vendor SDKs have transport retries of their own, below the adapter. `mw.Retry` is the layer above them that you can see: its backoff shows in the attempt records and in `mw.Log`. ### Retry `mw.Retry(opts...)` takes [`mw.RetryOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RetryOption) values: | Option | Default | Effect | |---|---|---| | [`mw.MaxRetries(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MaxRetries) | 3 | Retries after the first try. `0` disables retrying; the retry-after rule and the classifier still apply. A negative `n` is ignored. | | [`mw.BaseDelay(d)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#BaseDelay) | 500ms | The first backoff. Delays double per retry (0.5s, 1s, 2s, …), capped at 8s; ±25% jitter is applied after the cap, so a capped delay lands between 6s and 10s. `0` means no delay. | | [`mw.MaxWait(d)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MaxWait) | 60s | The longest retry-after ask Retry sleeps on. A longer ask fails at once. `0` removes the cap. | | [`mw.Classifier(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Classifier) | `mw.Retryable` | Replaces the test that decides whether an error is retried. | A retry-after the provider sends wins over the backoff. Retry reads the `retry-after-ms` header, then `retry-after` (seconds, or an HTTP date), and an `x-should-retry` header overrides the status rule. When the retries run out, the last error comes back wrapped as `mw: giving up after 3 retries: …`, so `errors.As` on the SDK's error type still works. The package example is [`ExampleRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-Retry). #### Fail at once on a long retry-after A provider that asks for longer than `MaxWait` gets no sleep. The call fails at once wrapping [`mw.ErrRetryAfterTooLong`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#ErrRetryAfterTooLong), with the provider's own error underneath, so a queue or a person can decide: ```go title="middleware/retries.go" _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) var apiErr *apiError fmt.Fprintln(w, "too long:", errors.Is(err, mw.ErrRetryAfterTooLong), errors.As(err, &apiErr)) ``` [middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go) Here the provider asked for two minutes against the 60-second default; the output is `too long: true true` after one request. This check outranks the retry budget, so even `MaxRetries(0)` reports `ErrRetryAfterTooLong` rather than the raw error. #### Choose what is retried The default classifier is [`mw.Retryable`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retryable): - **Retried:** `weft.ErrStreamIdle`, any `net.Error`, and HTTP 408, 409, 429 and 5xx. - **Never retried:** context errors, the kill switch, `weft.ErrUnsupported`, `weft.ErrModelContract`, every other 4xx (quota, billing, a bad request), and a context-window overflow. `mw` imports no vendor SDK. It finds the status and headers on the error chain by shape, which the helpers expose for your own classifier: ```go title="middleware/retries.go" err := providerError(429, "250") status, _ := mw.HTTPStatus(err) // 429, from the StatusCode field ask, _ := mw.RetryAfter(err, time.Now()) // 250ms, from retry-after-ms fmt.Fprintln(w, "helpers:", status, ask, mw.Retryable(err)) overflow := errors.New("400: prompt is too long: 210000 tokens > 200000 maximum") fmt.Fprintln(w, "overflow:", mw.IsContextOverflow(overflow), mw.Retryable(overflow)) ``` [middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go) - [`mw.HTTPStatus(err)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#HTTPStatus) reads an exported integer `StatusCode` field (openai-go, anthropic-sdk-go) or `Code` field (genai) on any error in the chain. - [`mw.RetryAfter(err, now)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RetryAfter) reads the retry-after headers from a `Response` field on the chain. It reports false for a missing header and for a value that cannot become a duration (unparseable, negative, or too large). The example prints `helpers: 429 250ms true` and `overflow: true false`. #### Context overflow [`mw.IsContextOverflow(err)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#IsContextOverflow) reports whether the error's text names a context-window overflow, such as `context_length_exceeded` or `prompt is too long`. `Retryable` treats such an error, and `weft.ErrContextOverflow` that the first-party adapters wrap, as terminal: the same request cannot succeed again. Route it to compaction instead; see [Keep long sessions inside the context window](https://weftgo.dev/docs/sessions/compaction/). #### Pair Retry with the adapter's `MaxRetries(0)` The OpenAI and Anthropic SDKs retry twice by default, and they sleep on the provider's retry-after inside the adapter's idle timer. A long ask then fails as `ErrStreamIdle` with the 429 and its header discarded. Pass `openai.MaxRetries(0)` or `anthropic.MaxRetries(0)` to switch the SDK's retries off, so `mw.Retry` owns every retry, honours the ask under `MaxWait` and records it. See [Connect a model provider](https://weftgo.dev/docs/guides/providers/). ### Fallback `mw.Fallback(models...)` tries the given models in order when the wrapped model fails before yielding any event, for example an outage or a capability gap (`weft.ErrUnsupported`). Put it outside `mw.Retry` so the primary is retried first: ```go title="middleware/retries.go" agt := weft.New(primary, weft.WrapModel( mw.Fallback(backup), // outer: switch models once Retry gives up mw.Retry(mw.MaxRetries(1), mw.BaseDelay(10*time.Millisecond)), // inner: retry the primary ), attempts(w), ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) ``` [middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go) ```text attempt attempt=1 model=large retry_after=5ms status=503 err=provider: 503 Service Unavailable attempt attempt=2 model=large retry_after=5ms layer=retry wait=5ms status=503 err=provider: 503 Service Unavailable attempt attempt=3 model=small layer=fallback fallback: "Order 1234 has shipped.", backup requests 1 ``` Retry spent its one retry on the primary, gave up, and Fallback sent the request to `small`, marked `layer=fallback`. A `max_tokens` finish is a successful stream, so Fallback does not switch on it. A failure after events were yielded is not retried anywhere. The agent's `Info` still reports the primary. The package example is [`ExampleFallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-Fallback). When every model in the chain fails, the run error is the last model's error alone. The earlier models' errors are not on its chain; they are on the `attempt` spans, one per request, and in Studio's attempts. The order matters. With `Retry` outside `Fallback`, Retry retries the fallback chain as a whole: the primary gets one try per retry cycle, each followed by the backup, and Retry never sees the primary's transient failures. #### Fall back only for some errors [`mw.FallbackWhen(when, models...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#FallbackWhen) tries the next model only for errors `when` accepts. A nil `when` is `Fallback`'s default: anything but cancellation and the kill switch. ```go title="middleware/retries.go" onlyUnsupported := func(err error) bool { return errors.Is(err, weft.ErrUnsupported) } agt := weft.New(primary, weft.WrapModel(mw.FallbackWhen(onlyUnsupported, backup))) res, err := agt.Generate(ctx, weft.Prompt("Read the attached invoice.")) ``` [middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go) The `ErrUnsupported` failure (a PDF the primary cannot read) goes to the `vision` backup; a 503 is not accepted, so the run fails with it. The predicate receives each failed model's error before the next model is tried, so it is the place to classify the primary's failure: count a 429 or log the outage there. ### Report attempts Inside the model chain, [`weft.ReportFromContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReportFromContext) returns the current model call's [`weft.Reporter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Reporter). [`Reporter.Attempt`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Attempt) records one provider request: an `attempt` span under the step's `chat` span and, with the agent's logger at Debug, a `model attempt` line. `mw.Retry` and `mw.Fallback` report every try this way; your own middleware can too: ```go title="middleware/retries.go" // reportAttempts reports every call through it as one attempt on the // run's record: an attempt span under the step's chat span, and a // "model attempt" Debug line on the agent's Logger. func reportAttempts(next weft.Model) weft.Model { return attemptReporter{next} } type attemptReporter struct{ next weft.Model } func (m attemptReporter) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { return func(yield func(weft.ModelEvent, error) bool) { info, start := weft.InfoOf(m.next), time.Now() var failed error for ev, err := range m.next.Stream(ctx, req) { failed = err if !yield(ev, err) || err != nil { break } } status, _ := mw.HTTPStatus(failed) weft.ReportFromContext(ctx).Attempt(weft.AttemptInfo{ Model: info.Name, Provider: info.Provider, Start: start, End: time.Now(), Err: failed, HTTPStatus: status, }) } } func (m attemptReporter) Info() weft.ModelInfo { return weft.InfoOf(m.next) } func (m attemptReporter) Unwrap() weft.Model { return m.next } // ReportsAttempts tells a reporting layer above (mw.Retry, mw.Fallback) // that this one reports, so each request is reported once. func (m attemptReporter) ReportsAttempts() bool { return true } ``` [middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go) Install it like any model middleware. Its `ReportsAttempts` method tells the `mw.Retry` above it to stay silent, so each request is reported once: ```go title="middleware/retries.go" agt := weft.New(primary, weft.WrapModel(mw.Retry(mw.BaseDelay(0)), reportAttempts), // Retry stays silent: reportAttempts reports attempts(w), ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) ``` [middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go) ```text attempt attempt=1 model=large status=500 err=provider: 500 Internal Server Error attempt attempt=2 model=large ``` ![A run whose model call was retried: the header counts one model attempt retried, and the waterfall's model row holds attempt 1, marked model_error, and attempt 2, which answered](https://weftgo.dev/docs/_astro/studio-attempts.light.CjIZR-GH.webp) *A run page with a retried model call: the model row holds attempt 1, which failed, and attempt 2, which answered.* The reporter numbers the attempts 1, 2, … itself, per model call. An [`weft.AttemptInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptInfo) carries what the reporting code saw; a field it does not know stays zero: | Field | Meaning | On the `attempt` span | |---|---|---| | `Model`, `Provider` | The model id requested and its provider | `gen_ai.request.model`, `gen_ai.provider.name` | | `Start`, `End` | When the attempt ran; both or neither, else ignored | the span's times | | `Err` | The failure, nil on success | `error.type` (classified, below), status `Error` | | `RetryAfter` | The wait the provider asked for | `weft.attempt.retry_after_ms` | | `Layer` | `weft.AttemptLayerFallback` (`"fallback"`) on a request `mw.Fallback` sent to a backup, [`weft.AttemptLayerRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptLayerRetry) (`"retry"`) on one `mw.Retry` sent again after a failure; empty on a first try | `weft.attempt.layer` | | `Wait` | How long the layer waited before sending it | `weft.attempt.wait_ms` | | `HTTPStatus` | The provider's HTTP status, when known; `mw.Retry` and `mw.Fallback` read it with `mw.HTTPStatus` | `http.response.status_code` | | `GiveUp` | Why the reporting layer stopped after this failed attempt: [`weft.AttemptGiveUpBudget`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptGiveUpBudget) (`budget`, its retries spent), `AttemptGiveUpNotRetryable` (`not_retryable`, a failure it does not retry), `AttemptGiveUpRetryAfter` (`retry_after_too_long`, a retry-after past `MaxWait`) | `weft.attempt.giveup_reason` | `mw.Retry` fills `Wait`, `HTTPStatus` and `GiveUp`. `GiveUp` is that layer's stop, not always the call's: a `Retry` under a `Fallback` marks where it stopped, and the call may go on to the backup. It is empty on an attempt the layer followed with another and on a success. It is also empty when the run was cancelled (the run names its own cause), when the failed attempt had already streamed output (`Retry` stops once output was yielded, without a give-up reason), and when a model that reports its own attempts sits under the layer. The package example [`ExampleAttemptInfo (giveUp)`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-AttemptInfo-GiveUp) shows it. A failed attempt's `error.type` is a closed set, finer than the run's: the context errors and weft's own failures as the run reads them (`stream_idle`, …), `context_overflow`, then by the provider's HTTP status `rate_limit` (429), `overloaded` (503, 529), `timeout` (408, 504, or a transport timeout), `auth` (401, 403), `server_error` (any other 5xx), and `model_error` for the rest. Before 0.20.0 every provider failure read `model_error`; the run's own `error.type` keeps its table. Studio words each cause in the attempts list ("rate limited (429)"), ends a failed call with "gave up: retries spent (2 attempts)", and draws an attempt's `weft.attempt.wait_ms` as a hatch before its bar. From the second attempt on, each report also adds its own `request` record. A layer that holds the attempt's wire bytes can report them with [`Reporter.Raw`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Raw) before its `Attempt`; they are recorded only when a destination asks for raw bodies (`otel.RawBodies`, development only), and dropped otherwise. Reporting is not a seam: no report changes a step, a retry or the model chosen. A report never returns an error, never blocks, and a panicking tracer or log handler is contained and counted in `Agent.TapPanics`. Outside a run's model call the reporter is a no-op, never nil: in a tool handler, on a bare `Model.Stream`, or on a context the loop did not hand the chain. [`AttemptLayerFallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptLayerFallback) is what Studio's `fallbacks` counter keys on, never a comparison of model names; a reader that took any non-empty layer for a fallback must compare with `fallback` since 0.20.0 added `retry`. A backup under its own `mw.Retry` beneath `mw.Fallback` marks every request it sends `fallback`, its retries included, so the counter counts the run it answered. The run row also counts `attempts_retried`: failed attempts a later attempt of the same call followed. The package example [`ExampleReportFromContext`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-ReportFromContext) wraps a model the same way. To see the attempts on a run, open it in Studio: [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/). ### Complete example `middleware/retries.go` runs every snippet on this page. Its `apiError` type stands in for a vendor SDK's error, which `mw` reads by shape: ```go title="middleware/retries.go" package main import ( "context" "errors" "fmt" "io" "iter" "log/slog" "net/http" "strings" "time" "github.com/weftgo/weft" "github.com/weftgo/weft/mw" "github.com/weftgo/weft/wefttest" ) // apiError stands in for a vendor SDK's error type. mw reads it the way // it reads openai-go's and anthropic-sdk-go's: structurally, an int // StatusCode field and a Response whose Header carries retry-after. type apiError struct { StatusCode int Response *http.Response } func (e *apiError) Error() string { return fmt.Sprintf("provider: %d %s", e.StatusCode, http.StatusText(e.StatusCode)) } // providerError is a failed response; retryAfterMS, when set, is the // provider's retry-after-ms header. func providerError(status int, retryAfterMS string) error { h := http.Header{} if retryAfterMS != "" { h.Set("retry-after-ms", retryAfterMS) } return &apiError{StatusCode: status, Response: &http.Response{StatusCode: status, Header: h}} } // named gives a scripted model a provider and model name, as an adapter // reports them. type named struct { weft.Model info weft.ModelInfo } func (n named) Info() weft.ModelInfo { return n.info } func model(provider, name string, turns ...wefttest.Turn) (*wefttest.Model, weft.Model) { s := wefttest.Script(turns...) return s, named{Model: s, info: weft.ModelInfo{Provider: provider, Name: name}} } // attemptLog is a slog handler that prints the loop's "model attempt" // Debug lines, the log form of each reported attempt, and drops the rest. type attemptLog struct{ w io.Writer } func (h attemptLog) Enabled(context.Context, slog.Level) bool { return true } func (h attemptLog) WithAttrs([]slog.Attr) slog.Handler { return h } func (h attemptLog) WithGroup(string) slog.Handler { return h } func (h attemptLog) Handle(_ context.Context, r slog.Record) error { if r.Message != "model attempt" { return nil } var b strings.Builder r.Attrs(func(a slog.Attr) bool { switch a.Key { case "wait": // rounded to 5 ms: a backoff carries ±25% jitter fmt.Fprintf(&b, " wait=%v", a.Value.Duration().Round(5*time.Millisecond)) case "attempt", "model", "layer", "retry_after", "status", "err": fmt.Fprintf(&b, " %s=%v", a.Key, a.Value) } return true }) fmt.Fprintln(h.w, " attempt"+b.String()) return nil } func attempts(w io.Writer) weft.Option { return weft.Logger(slog.New(attemptLog{w})) } // errWarmingUp is an application error a custom classifier retries. var errWarmingUp = errors.New("model is warming up") func retryDemo(ctx context.Context, w io.Writer) error { script, primary := model("acme", "large", wefttest.Fail(errWarmingUp), // retried by the custom classifier, after a backoff wefttest.Fail(providerError(429, "5")), // rate limited: asks for 5 ms wefttest.Say("Order 1234 has shipped."), ) agt := weft.New(primary, weft.WrapModel(mw.Retry( mw.MaxRetries(3), // retries after the first try (default 3) mw.BaseDelay(10*time.Millisecond), // first backoff (default 500ms), doubling, capped at 8s mw.MaxWait(30*time.Second), // a longer retry-after fails at once (default 60s) mw.Classifier(func(err error) bool { return mw.Retryable(err) || errors.Is(err, errWarmingUp) }), )), attempts(w), // print each reported attempt ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } fmt.Fprintf(w, "retry: %q after %d requests\n", res.Text(), len(script.Requests())) return nil } func retryAfterTooLong(ctx context.Context, w io.Writer) error { script, primary := model("acme", "large", wefttest.Fail(providerError(429, "120000"))) // asks for 2 minutes agt := weft.New(primary, weft.WrapModel(mw.Retry())) _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) var apiErr *apiError fmt.Fprintln(w, "too long:", errors.Is(err, mw.ErrRetryAfterTooLong), errors.As(err, &apiErr)) fmt.Fprintf(w, "too long: %d request\n", len(script.Requests())) return nil } func retryHelpers(w io.Writer) { err := providerError(429, "250") status, _ := mw.HTTPStatus(err) // 429, from the StatusCode field ask, _ := mw.RetryAfter(err, time.Now()) // 250ms, from retry-after-ms fmt.Fprintln(w, "helpers:", status, ask, mw.Retryable(err)) overflow := errors.New("400: prompt is too long: 210000 tokens > 200000 maximum") fmt.Fprintln(w, "overflow:", mw.IsContextOverflow(overflow), mw.Retryable(overflow)) } func fallbackDemo(ctx context.Context, w io.Writer) error { _, primary := model("acme", "large", wefttest.Fail(providerError(503, "5")), wefttest.Fail(providerError(503, "5")), ) backupScript, backup := model("other", "small", wefttest.Say("Order 1234 has shipped.")) agt := weft.New(primary, weft.WrapModel( mw.Fallback(backup), // outer: switch models once Retry gives up mw.Retry(mw.MaxRetries(1), mw.BaseDelay(10*time.Millisecond)), // inner: retry the primary ), attempts(w), ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } fmt.Fprintf(w, "fallback: %q, backup requests %d\n", res.Text(), len(backupScript.Requests())) return nil } func fallbackWhenDemo(ctx context.Context, w io.Writer) error { for _, failure := range []error{ fmt.Errorf("%w: pdf input", weft.ErrUnsupported), providerError(503, ""), } { _, primary := model("acme", "large", wefttest.Fail(failure)) _, backup := model("other", "vision", wefttest.Say("The invoice total is 120 EUR.")) onlyUnsupported := func(err error) bool { return errors.Is(err, weft.ErrUnsupported) } agt := weft.New(primary, weft.WrapModel(mw.FallbackWhen(onlyUnsupported, backup))) res, err := agt.Generate(ctx, weft.Prompt("Read the attached invoice.")) if err != nil { fmt.Fprintln(w, "fallback-when:", err) // a 503 is not ErrUnsupported: no fallback continue } fmt.Fprintf(w, "fallback-when: %q\n", res.Text()) } return nil } // reportAttempts reports every call through it as one attempt on the // run's record: an attempt span under the step's chat span, and a // "model attempt" Debug line on the agent's Logger. func reportAttempts(next weft.Model) weft.Model { return attemptReporter{next} } type attemptReporter struct{ next weft.Model } func (m attemptReporter) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { return func(yield func(weft.ModelEvent, error) bool) { info, start := weft.InfoOf(m.next), time.Now() var failed error for ev, err := range m.next.Stream(ctx, req) { failed = err if !yield(ev, err) || err != nil { break } } status, _ := mw.HTTPStatus(failed) weft.ReportFromContext(ctx).Attempt(weft.AttemptInfo{ Model: info.Name, Provider: info.Provider, Start: start, End: time.Now(), Err: failed, HTTPStatus: status, }) } } func (m attemptReporter) Info() weft.ModelInfo { return weft.InfoOf(m.next) } func (m attemptReporter) Unwrap() weft.Model { return m.next } // ReportsAttempts tells a reporting layer above (mw.Retry, mw.Fallback) // that this one reports, so each request is reported once. func (m attemptReporter) ReportsAttempts() bool { return true } func reportDemo(ctx context.Context, w io.Writer) error { _, primary := model("acme", "large", wefttest.Fail(providerError(500, "")), wefttest.Say("Order 1234 has shipped."), ) agt := weft.New(primary, weft.WrapModel(mw.Retry(mw.BaseDelay(0)), reportAttempts), // Retry stays silent: reportAttempts reports attempts(w), ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } // Outside a run's model call the reporter is a no-op: nothing prints. weft.ReportFromContext(ctx).Attempt(weft.AttemptInfo{Model: "ignored"}) fmt.Fprintf(w, "report: %q\n", res.Text()) return nil } // demoRetries is the retries-and-fallback page's complete example. func demoRetries(ctx context.Context, w io.Writer) error { if err := retryDemo(ctx, w); err != nil { return err } if err := retryAfterTooLong(ctx, w); err != nil { return err } retryHelpers(w) for _, demo := range []func(context.Context, io.Writer) error{fallbackDemo, fallbackWhenDemo, reportDemo} { if err := demo(ctx, w); err != nil { return err } } return nil } ``` [middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go) Run it from `docs-site/examples`: ```sh go run ./middleware retries go test ./middleware ``` ```text attempt attempt=1 model=large err=model is warming up attempt attempt=2 model=large retry_after=5ms layer=retry wait=10ms status=429 err=provider: 429 Too Many Requests attempt attempt=3 model=large layer=retry wait=5ms retry: "Order 1234 has shipped." after 3 requests too long: true true too long: 1 request helpers: 429 250ms true overflow: true false attempt attempt=1 model=large retry_after=5ms status=503 err=provider: 503 Service Unavailable attempt attempt=2 model=large retry_after=5ms layer=retry wait=5ms status=503 err=provider: 503 Service Unavailable attempt attempt=3 model=small layer=fallback fallback: "Order 1234 has shipped.", backup requests 1 fallback-when: "The invoice total is 120 EUR." fallback-when: weft: run failed at step 0: model stream: provider: 503 Service Unavailable attempt attempt=1 model=large status=500 err=provider: 500 Internal Server Error attempt attempt=2 model=large report: "Order 1234 has shipped." ``` The `attemptLog` handler rounds `wait` to 5 ms, because a backoff carries jitter. ### Best practices & gotchas - **Put `mw.Fallback` outside `mw.Retry`.** The primary is retried to exhaustion before the backup is tried. (Source: `weft/core/mw/doc.go:15-19`) - **Switch the SDK's retries off when you use `mw.Retry`.** `openai.MaxRetries(0)` and `anthropic.MaxRetries(0)` stop the SDK sleeping on a retry-after inside the idle timer. (Source: `weft/core/mw/retry.go:93-108`, `weft/CHANGELOG.md:5660`) - **Expect nothing to be retried after the first event.** Part of the reply has reached the loop; the failure is the run's error. (Source: `weft/docs/adr/0006-seams.md:93-96`) - **Do not retry a context overflow.** The same bytes cannot fit; compact or shorten the request. (Source: `weft/core/mw/retry.go:283-291`, `weft/core/mw/retry.go:467-473`) - **Use `BaseDelay(0)` only in tests.** The default is 500ms doubling to 8s; zero removes the spacing a rate-limited provider needs. (Source: `weft/mw/example_test.go:28`) - **Expect the backup's error when the backup fails too.** `errors.Is(err, weft.ErrUnsupported)`, an `mw.HTTPStatus` check for a 429, or a log line on the run error all see the last model's error, so a misconfigured backup (no key, a wrong model id) hides the primary's real failure. Read the primary's error on the `attempt` spans or in Studio's attempts, or classify it in a `FallbackWhen` predicate before the backup runs. (Source: `weft/core/mw/model.go:118-125`, `weft/core/mw/model.go:38-44`) - **Declare `ReportsAttempts` when your layer reports.** Without it, a `mw.Retry` above reports the same requests again. (Source: `weft/core/report.go:151-157`, `weft/core/mw/model.go:253-283`) ### See also - [Add behaviour with middleware (the two seams)](https://weftgo.dev/docs/guides/middleware/) - [Connect a model provider: OpenAI, Anthropic, Gemini](https://weftgo.dev/docs/guides/providers/) - [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/) - [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/) - [The record contract](https://weftgo.dev/docs/reference/record-contract/) Symbols used: [`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry) · [`mw.RetryOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RetryOption) · [`mw.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MaxRetries) · [`mw.BaseDelay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#BaseDelay) · [`mw.MaxWait`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MaxWait) · [`mw.Classifier`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Classifier) · [`mw.Retryable`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retryable) · [`mw.RetryAfter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RetryAfter) · [`mw.HTTPStatus`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#HTTPStatus) · [`mw.IsContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#IsContextOverflow) · [`mw.ErrRetryAfterTooLong`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#ErrRetryAfterTooLong) · [`mw.Fallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Fallback) · [`mw.FallbackWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#FallbackWhen) · [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.ReportFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReportFromContext) · [`weft.Reporter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Reporter) · [`Reporter.Attempt`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Attempt) · [`Reporter.Raw`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Raw) · [`weft.AttemptInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptInfo) · [`weft.AttemptLayerFallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptLayerFallback) · [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) · [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger) · [`weft.ErrStreamIdle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrStreamIdle) · [`weft.ErrUnsupported`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUnsupported) · [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow) · [`openai.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#MaxRetries) · [`anthropic.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#MaxRetries) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Connect a model provider: OpenAI, Anthropic, Gemini URL: https://weftgo.dev/docs/guides/providers/ Markdown: https://weftgo.dev/docs/guides/providers.md > Construct weft's first-party adapters — openai.Model, anthropic.Model, google.Model — point them at a compatible server, and set their sampling, retry, timeout and escape-hatch options. Each provider is one constructor that returns a [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model): [`openai.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Model) for the OpenAI Chat Completions API and every compatible server, [`anthropic.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Model) for the Anthropic Messages API, and [`google.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Model) for the Gemini API. Pass the result to `weft.New`; swapping providers is swapping that one line. In `providers/main.go`, the official OpenAI API and a local compatible server: ```go title="providers/main.go" official = openai.Model("gpt-4o-mini") // reads $OPENAI_API_KEY and $OPENAI_BASE_URL local = openai.Model("llama3.2", openai.BaseURL("http://localhost:11434/v1"), // any Chat Completions server openai.APIKey("unused"), openai.MaxTokens(1024), openai.Temperature(0.2), openai.MaxRetries(0), // the SDK retries nothing; mw.Retry owns retries ) ``` [providers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/providers/main.go) Constructing a model performs no I/O. `openai.Model` and `anthropic.Model` build their SDK client then, so they read the key from the environment when the model is built; `google.Model` defers its client, and credential discovery, to the first run. ### The adapters The three adapters wrap the vendors' official Go SDKs (`openai-go`, `anthropic-sdk-go`, `google.golang.org/genai`): weft never owns an HTTP client, and every request goes through the SDK's client. They are packages of the framework module, so `go get github.com/weftgo/weft@v0.20.2` brings all three, and Go compiles only the ones you import. Every adapter takes the same kind of functional options, each package's own `Option` type. A model is immutable and safe for concurrent runs. | Option | `openai` | `anthropic` | `google` | Effect | |---|---|---|---|---| | `APIKey(k)` | ✓ | ✓ | ✓ | The key; default from the environment (below) | | `BaseURL(u)` | ✓ | ✓ | ✓ | A gateway, proxy or compatible server | | `Client(c)` | ✓ | ✓ | ✓ | Your configured SDK client; overrides `BaseURL`, `APIKey`, `MaxRetries` | | `MaxTokens(n)` | ✓ | ✓ (default 4096) | ✓ | Per-step output-token cap; zero keeps the provider default | | `Temperature(t)`, `TopP(p)`, `Stop(s...)` | ✓ | ✓ | ✓ | Sampling; not sent unless given | | `Seed(s)` | ✓ | — | ✓ | A best-effort determinism hint | | `IdleTimeout(d)` | ✓ | ✓ | ✓ | Longest gap between stream chunks; default 60s, 0 disables | | `MaxRetries(n)` | ✓ (SDK default 2) | ✓ (SDK default 2) | ✓ (off unless asked) | The SDK's transport retries on 429, 5xx and connection errors | | `ExtraBody(m)`, `ExtraHeaders(h)` | ✓ | ✓ | ✓ | [The escape hatch](https://weftgo.dev/docs/guides/providers/#escape-hatch) | | `Dialect(d)` | ✓ | — | — | [How thinking reaches a compatible server](https://weftgo.dev/docs/guides/providers/#openai) | | `Thinking(on)` | — | ✓ | — | Adaptive thinking when the run sets no level | | `PromptCache()` | — | ✓ | — | [Prompt caching](https://weftgo.dev/docs/guides/providers/#prompt-caching) | The sampling options are construction defaults. A per-run or per-step `weft.Params(weft.RequestParams{…})` overrides them for one call: see [Configure one run](https://weftgo.dev/docs/guides/run-options/). Credentials and endpoints come from the environment when no option names them: | Adapter | Key | Endpoint | |---|---|---| | `openai` | `OPENAI_API_KEY` | `OPENAI_BASE_URL` | | `anthropic` | `ANTHROPIC_API_KEY` (the SDK also accepts `ANTHROPIC_AUTH_TOKEN`, a bearer token) | `ANTHROPIC_BASE_URL` | | `google` | `GOOGLE_API_KEY` (wins when both are set) or `GEMINI_API_KEY`; on the Vertex AI backend (`GOOGLE_GENAI_USE_VERTEXAI=true`), application default credentials | the SDK's own `GOOGLE_GEMINI_BASE_URL` | ### OpenAI `openai.Model(name, opts...)` speaks the Chat Completions API. With [`openai.BaseURL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#BaseURL) it reaches any compatible server: a gateway, Ollama, vLLM, a hosted open-weights provider. That is the region above. The model's `Info()` reports provider `openai` whatever the base URL, so a host name never becomes a telemetry dimension. [`openai.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Client) takes an `openai-go` client you configured yourself, for Azure endpoints, a custom transport or a test double. The package example [`ExampleModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#example-Model) builds an agent with the default configuration. Chat Completions has two ways to express reasoning. The official API takes `reasoning_effort`; the z.ai and Moonshot gateways take a `thinking` object the SDK's typed request has no field for. A [`openai.ThinkingDialect`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#ThinkingDialect) picks one: | Dialect | Sends | |---|---| | [`DialectAuto`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectAuto) (default) | Detected from the base URL: the object for hosts ending `.z.ai`, `.bigmodel.cn`, `.moonshot.ai`, `.moonshot.cn`; effort for everything else | | [`DialectEffort`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectEffort) | `reasoning_effort`: `low`, `medium` or `high` | | [`DialectObject`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectObject) | `thinking: {"type": "enabled"}` or `{"type": "disabled"}`, injected into the body | | [`DialectNone`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectNone) | Nothing, for strict servers that reject unknown fields | Pin one with [`openai.Dialect`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Dialect) when the host does not tell, as in [`ExampleDialect`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#example-Dialect): ```go title="providers/main.go" // z.ai is a known gateway host: thinking goes out as a thinking object. detected = openai.Model("glm-4.6", openai.BaseURL("https://api.z.ai/api/paas/v4")) // An unrecognized host would get reasoning_effort; pin the object form. pinned = openai.Model("kimi-k2.7", openai.BaseURL("https://gw.internal/v1"), openai.Dialect(openai.DialectObject)) ``` [providers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/providers/main.go) A client passed through `Client(c)` hides its endpoint; `DialectAuto` then reads `OPENAI_BASE_URL`, and with none assumes the official API. What else the adapter does on the wire: - **Reasoning is output only.** DeepSeek-style `reasoning_content` streams as reasoning; assistant `ReasoningPart`s are dropped on the way back, because Chat Completions has no reasoning input. - **Empty tool-call arguments become `{}`** when a transcript is sent back, matching its stream side and the other adapters. - **`parallel_tool_calls` is sent only with a tool catalog**, since several compatible servers reject the hint without one. `weft.Sequential()` sets it to `false`. - **Missing call ids are synthesised** as `call_`, skipping ids the server already used in the same step. - **A function name streamed in repeated fragments** is overwritten, not concatenated. ### Anthropic `anthropic.Model(name, opts...)` speaks the Messages API. [`anthropic.Thinking(true)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Thinking) sends `thinking: {"type": "adaptive"}` and streams thinking blocks, with their signatures, as reasoning; without it nothing is sent and the model's default applies. `redacted_thinking` blocks are dropped: they never reach the transcript or the next request ([Control reasoning (thinking)](https://weftgo.dev/docs/guides/thinking/#read-reasoning-parts)). A run's own `weft.Thinking` level overrides it ([Thinking](https://weftgo.dev/docs/guides/providers/#thinking)). ```go title="providers/main.go" m := anthropic.Model("claude-sonnet-5", // reads $ANTHROPIC_API_KEY and $ANTHROPIC_BASE_URL anthropic.Thinking(true), // adaptive thinking unless a run sets a level anthropic.PromptCache(), // cache_control on the stable prefix edges anthropic.MaxTokens(8192), // required by the API; 4096 when unset ) ``` [providers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/providers/main.go) `max_tokens` is required by the API, so [`anthropic.MaxTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#MaxTokens) defaults to 4096. The Messages API has no seed: the adapter has no `Seed` option, and a `RequestParams.Seed` is dropped. [`anthropic.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Client) is the way in for Vertex AI and Bedrock clients. The package example is [`ExampleModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#example-Model). #### Prompt caching [`anthropic.PromptCache()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#PromptCache) marks three stable prefix edges with `cache_control: {"type": "ephemeral"}`: the system block, the final tool definition, and the last content block of the last message. That spends three of Anthropic's four breakpoints and leaves one free. Without the option, no `cache_control` appears anywhere. Cache writes bill 1.25× and cache reads 0.1× the base input price, so a transcript whose prefix repeats across steps saves from the second step on. `Usage.CachedInputTokens` and `Usage.CacheWriteTokens` show the effect. Keeping the prefix stable is your job. A `PrepareStep` that trims messages invalidates the trailing breakpoint. To stop tool calls on a step without removing the tool definitions, and the cached prefix they anchor, use `weft.ToolChoiceNone` instead of dropping the tools. It is a request, not a filter: a call the server emits anyway runs ([Enforce a choice](https://weftgo.dev/docs/guides/run-options/#enforce-a-choice)). ### Google `google.Model(name, opts...)` speaks the Gemini API through `google.golang.org/genai`. The SDK client is created on the first run, because credential discovery needs a context; a failed attempt is not cached, so the next run tries again. ```go title="providers/main.go" m := google.Model("gemini-2.5-flash", // $GOOGLE_API_KEY / $GEMINI_API_KEY, then application default google.Temperature(0.2), google.Seed(7), google.MaxRetries(2), // the SDK retries nothing unless asked ) ``` [providers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/providers/main.go) Unlike the other two, the Gemini SDK retries nothing unless [`google.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#MaxRetries) asks. [`google.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Client) takes a `genai.Client` you configured, for Vertex AI projects and regions. The package example is [`ExampleModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#example-Model). What else the adapter does on the wire: - **Integer limits fail loudly.** `MaxTokens`, `Seed` and `ThinkingConfig.Budget` are int32 on the wire; a larger value fails the call wrapping `weft.ErrUnsupported` instead of wrapping around. Options carry no error, so the check happens when the request is built. - **Thought signatures round-trip**, including one riding an empty non-thought text part: Gemini validates its return on the next request. - **Function calls arrive whole**, so there are no argument deltas. Missing call ids are synthesised as `call_`, skipping ids the API populated. - **`weft.Sequential()` has no Gemini switch**; function calling stays `AUTO`. - **An injected client records no raw wire pair.** genai has no per-request middleware, so for [`otel.RawBodies`](https://weftgo.dev/docs/observe/destinations/#record-provider-wire-bodies-development-only) the adapter wraps the transport of the HTTP client it built for its own SDK client. A `genai.Client` passed through `Client(c)` is yours and is never touched, so its runs record no raw pair; Studio shows `not_recorded` for them. openai and anthropic capture through the SDK's innermost per-request middleware, so they record one pair per HTTP call with or without `Client(c)`, and an SDK transport retry shows as a pair of its own. ### Escape hatch `ExtraBody(map[string]any)` adds fields to every request's JSON body, and `ExtraHeaders(http.Header)` adds headers verbatim. They are for vendor parameters weft has no option for: ```go title="providers/main.go" client := openaisdk.NewClient(option.WithBaseURL(baseURL), option.WithAPIKey("test")) m := openai.Model("gpt-4o-mini", openai.Client(&client), // an SDK client you configured: Azure, a proxy, a test server openai.ExtraBody(map[string]any{ "service_tier": "flex", // a new key is added "stream_options": map[string]any{"include_obfuscation": false}, // maps deep-merge }), openai.ExtraHeaders(http.Header{"X-Request-Source": {"docs"}}), ) ``` [providers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/providers/main.go) The body is deep-merged into what weft built: nested maps merge, every other value replaces, and your key wins on a conflict. Both options are construction-time snapshots, so changing the map afterwards never reaches the model. They apply through an injected `Client(c)` too. In the complete example, `stream_options` reaches the server as `{"include_obfuscation":false,"include_usage":true}`: weft's `include_usage` and your key, merged. #### What the run record names Each request record carries a `wire` object, names only: the endpoint and the escape hatches' keys ([`RequestWire`](https://weftgo.dev/docs/reference/obsdb-records/#requestwire)). A model declares them with the optional method `WireFacts() (serverAddress string, extraBodyKeys, extraHeaderNames []string)`. All three adapters implement it, as they implement `ThinkingWire`. - **The core walks the `Unwrap` chain** from the agent's model and asks the first model that has the method. Your own model, or a wrapping middleware, may declare it too. A layer without `Unwrap` hides the adapter below it, and the record then has no `wire`. A model with no such method along the chain, such as a `wefttest` model, records none. - **`server_address`** is the adapter's `BaseURL`, else the SDK's `OPENAI_BASE_URL` or `ANTHROPIC_BASE_URL`, else `api.openai.com` or `api.anthropic.com`. `google` names a `BaseURL` alone. An injected `Client(c)` names none. - **The core sanitises what the method returns.** It keeps `host[:port]` and drops a URL's scheme, userinfo, path, query and fragment. It names no host when the URL is ambiguous about where the credentials end. Keys are top-level `ExtraBody` keys; headers are names, lowercased, never values. Each list keeps at most 32 names of at most 128 bytes, and `dropped` counts the names left out for length or past the 32; a duplicate or an empty name is dropped without being counted. An address over 128 bytes reads empty. - **Behind `mw.Fallback` the facts are always the primary's.** `Fallback`'s `Unwrap` is its primary, so a backup's endpoint is never recorded. A fallback attempt's record names the primary's wire; its `attempt` span's `gen_ai.request.model` names the model that served it. ### What the adapters do not wrap Tools the provider runs itself have no weft mapping: a `weft.Tool` or `weft.RawTool` is executed in your process, and nothing in the process executes these. ADR 0013 records this as a stance, not an oversight. None of the three adapters wraps them: | Adapter | Not wrapped | |---|---| | `anthropic` | Server tools such as `web_search` and `code_execution` | | `google` | Grounding, search and code-execution tools | | `openai` | The Responses API, with its reasoning items and built-in tools; the adapter speaks Chat Completions only | Turning one on through `ExtraBody` does not make its output part of the run. The anthropic stream skips `server_tool_use` blocks and every other block that is not text, thinking or `tool_use`, and drops a server tool's argument fragments, so the transcript gets none of the tool's calls or results. The google stream reads only function calls, thought parts, text and thought signatures from a candidate's parts. A `tools` key in `ExtraBody` also replaces weft's own tool list rather than merging with it, because arrays replace in the merge. ### Idle timeout `IdleTimeout(d)` is the longest gap between two stream chunks. When it passes, the call fails with an error wrapping [`weft.ErrStreamIdle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrStreamIdle), the same error from every adapter. The default is 60 seconds; zero disables it. ```go title="providers/main.go" m := openai.Model("gpt-4o-mini", openai.Client(&client), openai.IdleTimeout(200*time.Millisecond), // default 60s; 0 disables it ) _, err := weft.New(m).Generate(ctx, weft.Prompt("hi")) if errors.Is(err, weft.ErrStreamIdle) { fmt.Fprintln(w, "the stream stalled:", err) } ``` [providers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/providers/main.go) The `ctx` deadline stays the hard limit on the whole call; the idle timer only catches a stalled stream, so a slow response that keeps streaming is never killed. ### Retries The weft loop never retries a model call. Transport retries on 429, 5xx and connection errors belong to the SDK, set by `MaxRetries(n)`: - **openai and anthropic** inherit the SDK default of 2 retries when the option is absent. `MaxRetries(0)` switches them off; a negative n is 0. - **google** retries nothing unless `MaxRetries(n)` is given. The wait for response headers is the idle timer's first gap, and it contains the SDK's retries and their sleeps. A rate-limited call whose `retry-after` the SDK sleeps on can therefore fail as `ErrStreamIdle`, with the 429 discarded. Pair `MaxRetries(0)` with `mw.Retry`, which then owns every retry and reads the provider's `retry-after` itself: see [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/). ### Thinking [`weft.Thinking`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Thinking) asks for a reasoning depth on a provider-neutral scale; each adapter writes it in its own field. Each adapter declares the field with the optional method `ThinkingWire(weft.ThinkingConfig) string`, which Studio shows as the request's thinking wire. The complete example prints it for every adapter: | `weft.ThinkingConfig` | `openai` (effort) | `openai` (object) | `anthropic` | `google` | |---|---|---|---|---| | zero value (`ThinkUnset`) | `none` | `none` | `none` | `none` | | `Level: ThinkOff` | `none` (no off switch) | `thinking` (`disabled`) | `thinking.disabled` | `thinking_budget` (zeroed) | | `Level: ThinkLow`, `ThinkMedium`, `ThinkHigh` | `reasoning_effort` | `thinking` (`enabled`) | `thinking.adaptive` | `thinking_level` | | `Budget: 2048` | `none` (dropped) | `none` | `thinking.budget_tokens` | `thinking_budget` | The table shows `ThinkingWire`'s label, not always what is sent. A run that sets no level keeps the adapter's construction default: with `anthropic.Thinking(true)` an unset level still sends `thinking.adaptive`, which the label reports as `none`. Setting levels per agent and per run is on [Control reasoning (thinking)](https://weftgo.dev/docs/guides/thinking/). ### Capabilities What each adapter carries, as its conformance run declares it, with the details from the adapter code (`openai/stream.go`, `openai/convert.go`, `anthropic/convert.go`, `google/convert.go`): | | `openai` | `anthropic` | `google` | |---|---|---|---| | Tools and streaming | ✓ | ✓ | ✓ | | Tool-argument deltas | ✓ | ✓ | — (calls arrive whole) | | Sequential tools hint | ✓ | ✓ | — | | Tool choice | ✓ | ✓ | ✓ | | Reasoning in and out | out only, via `reasoning_content` | ✓ | ✓ | | File input | images | images (PNG, JPEG, GIF, WebP) and PDF | inline data or a file URI, any media type | | Usage reported | ✓ | ✓ | ✓ | | `retry-after` readable by `mw.Retry` | ✓ | ✓ | — (backs off instead) | | Raw wire pairs under `otel.RawBodies` | ✓ one per HTTP call | ✓ one per HTTP call | ✓ only for a client the adapter built, not `Client(c)` | Structured output is not a row: `weft.Output` registers an ordinary tool, `submit_output`, so every adapter that carries tools carries it ([Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/)). A file an adapter cannot carry fails the call wrapping `weft.ErrUnsupported`: see [Send images and files to a model](https://weftgo.dev/docs/guides/multimodal/). ### How the transcript is sent Each adapter rewrites weft's messages into its provider's shape, and some content changes on the way. The placeholders are text the model reads: | In the transcript | `openai` | `anthropic` | `google` | |---|---|---|---| | A tool result | a `tool` message per result, the text as `content` | a `tool_result` block per result, all on one user message | a `functionResponse` per result with `{"output": }` | | A tool error result (`IsError`) | the same `tool` message: Chat Completions has no error flag, so only the text says it failed | the `tool_result` block with `is_error` set | `{"error": }` in place of `{"output": …}`: Gemini has no flag either | | An empty tool result | passed unchanged | `(empty tool output)` | `{"output": ""}` | | A user message whose every part is empty text | `(empty message)` | `(empty message)` | dropped | | An assistant message with nothing sendable | skipped | skipped | skipped | A tool error's text is the loop's, such as `INVALID_INPUT: …` or a `ToolError`'s code and message, so an OpenAI model reads the failure from the text alone. What each adapter sends back for a signed or unsigned `ReasoningPart` is on [Control reasoning (thinking)](https://weftgo.dev/docs/guides/thinking/#read-reasoning-parts), with how to [switch providers](https://weftgo.dev/docs/guides/thinking/#switch-providers) without sending one provider's signatures to another. ### Stop reasons Each adapter maps the provider's finish reason onto one of three [`weft.StopReason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopReason) values: `stop` (`StopEndTurn`), `tool_calls` (`StopToolCalls`) or `max_tokens` (`StopMaxTokens`). When the mapping is approximate, the provider's own word is kept beside it: on `StepRecord.RawStopReason` (in `res.Steps`) and on the `StepFinish` event's `Raw`. An exact mapping leaves it empty. | Adapter | Provider value | `StopReason` | `RawStopReason` | |---|---|---|---| | `openai` | `stop` | `stop` | empty | | | `tool_calls` | `tool_calls` | empty | | | `length` | `max_tokens` | empty | | | none sent (some compatible servers) | `tool_calls` if the step has calls, else `stop` | empty | | | `content_filter`, anything else | `stop` | the value, e.g. `content_filter` | | `anthropic` | `end_turn` | `stop` | empty | | | `tool_use` | `tool_calls` | empty | | | `max_tokens` | `max_tokens` | empty | | | `refusal` | `stop` | `refusal`, or `refusal:` when the API names `stop_details.category` | | | `stop_sequence`, `pause_turn`, anything newer | `stop` | the value | | `google` | `STOP` | `tool_calls` if the step has calls (Gemini reports `STOP` either way), else `stop` | empty | | | `MAX_TOKENS` | `max_tokens` | empty | | | none sent | `tool_calls` if the step has calls, else `stop` | empty | | | `SAFETY`, `RECITATION`, anything else | `stop` | the value, e.g. `SAFETY` | A safety-blocked Gemini reply, an OpenAI `content_filter` and an Anthropic refusal all read `stop`, like a normal answer. To tell them apart, check the last step's `RawStopReason` (or `StepFinish.Raw` on a stream); `res.StopReason` carries the mapped value only. An OpenAI safety refusal streams its message in `delta.refusal`, and the adapter passes it on as ordinary text: the refusal is the answer in `res.Text()`, and the step's `RawStopReason` is `content_filter`. A prompt Gemini blocks before writing any candidate is not caught by `RawStopReason`. The adapter never reads the response's `promptFeedback`, so such a stream ends the run successfully with `stop`, an empty `RawStopReason` and empty text. ### Token usage Every adapter fills [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage) from the provider's own usage fields. `InputTokens` and `OutputTokens` are the billed totals; `CachedInputTokens` and `CacheWriteTokens` are parts of `InputTokens`, and `ReasoningTokens` is part of `OutputTokens`, never added on top. | `weft.Usage` field | `openai` (the final chunk's `usage`) | `anthropic` (`message_start` and `message_delta`) | `google` (`usageMetadata`) | |---|---|---|---| | `InputTokens` | `prompt_tokens` | `input_tokens` + `cache_read_input_tokens` + `cache_creation_input_tokens` | `promptTokenCount` + `toolUsePromptTokenCount` | | `OutputTokens` | `completion_tokens` | `output_tokens` | `candidatesTokenCount` + `thoughtsTokenCount` | | `CachedInputTokens` | `prompt_tokens_details.cached_tokens` | `cache_read_input_tokens` | `cachedContentTokenCount` | | `CacheWriteTokens` | not reported (0) | `cache_creation_input_tokens` | not reported (0) | | `ReasoningTokens` | `completion_tokens_details.reasoning_tokens` | `output_tokens_details.thinking_tokens` | `thoughtsTokenCount` | The openai adapter asks for usage with `stream_options.include_usage`. A compatible server that never sends it reports zero usage rather than an estimate. Gemini's thought tokens count as output because they are billed as output, so a `UsageLimit` on `OutputTokens` includes them. ### Test without the network Set `WEFT_MODEL_REQUESTS=deny` and every adapter that built its own client fails its first call with [`weft.ErrModelRequestsDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRequestsDenied), before any I/O. [`weft.ModelRequestsAllowed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequestsAllowed) reads the variable on every call, so a test can toggle it with `t.Setenv`. A client injected through `Client(c)` stays reachable under deny: it is a test double by construction, and where it sends requests is your responsibility. The complete example relies on that to point the escape-hatch and idle-timeout demos at a local `httptest` server. The adapters' own parsing is proven by the shared conformance suite, `wefttest/conformance`, offline against recorded fixtures and live behind `-tags live`: see [Prove a provider adapter with the conformance suite](https://weftgo.dev/docs/testing/conformance/). ### Complete example `providers/main.go` builds every model above, shows each refusing under the kill switch, prints the thinking wire table, and runs the escape hatch and the idle timeout against local servers: ```go title="providers/main.go" // Command providers builds the three first-party adapters (weft/openai, // weft/anthropic, weft/google) and shows what each would send, without // reaching a provider: WEFT_MODEL_REQUESTS=deny stops every adapter that // built its own client, and the two wire demos talk to a local // httptest server through an injected SDK client. package main import ( "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/http/httptest" "os" "strings" "sync" "time" openaisdk "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/weftgo/weft" "github.com/weftgo/weft/anthropic" "github.com/weftgo/weft/google" "github.com/weftgo/weft/openai" ) func main() { // This demo never reaches a provider: the kill switch makes every // adapter that built its own client refuse before any I/O. os.Setenv("WEFT_MODEL_REQUESTS", "deny") if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } // openaiModels returns the official API and an OpenAI-compatible // local server. func openaiModels() (official, local weft.Model) { official = openai.Model("gpt-4o-mini") // reads $OPENAI_API_KEY and $OPENAI_BASE_URL local = openai.Model("llama3.2", openai.BaseURL("http://localhost:11434/v1"), // any Chat Completions server openai.APIKey("unused"), openai.MaxTokens(1024), openai.Temperature(0.2), openai.MaxRetries(0), // the SDK retries nothing; mw.Retry owns retries ) return official, local } // gatewayModels returns two gateway models: one whose thinking wire // form is detected from its host, one pinned with Dialect. func gatewayModels() (detected, pinned weft.Model) { // z.ai is a known gateway host: thinking goes out as a thinking object. detected = openai.Model("glm-4.6", openai.BaseURL("https://api.z.ai/api/paas/v4")) // An unrecognized host would get reasoning_effort; pin the object form. pinned = openai.Model("kimi-k2.7", openai.BaseURL("https://gw.internal/v1"), openai.Dialect(openai.DialectObject)) return detected, pinned } func anthropicModel() weft.Model { m := anthropic.Model("claude-sonnet-5", // reads $ANTHROPIC_API_KEY and $ANTHROPIC_BASE_URL anthropic.Thinking(true), // adaptive thinking unless a run sets a level anthropic.PromptCache(), // cache_control on the stable prefix edges anthropic.MaxTokens(8192), // required by the API; 4096 when unset ) return m } func googleModel() weft.Model { m := google.Model("gemini-2.5-flash", // $GOOGLE_API_KEY / $GEMINI_API_KEY, then application default google.Temperature(0.2), google.Seed(7), google.MaxRetries(2), // the SDK retries nothing unless asked ) return m } // extrasModel is an openai model whose requests carry fields and // headers weft has no option for. func extrasModel(baseURL string) weft.Model { client := openaisdk.NewClient(option.WithBaseURL(baseURL), option.WithAPIKey("test")) m := openai.Model("gpt-4o-mini", openai.Client(&client), // an SDK client you configured: Azure, a proxy, a test server openai.ExtraBody(map[string]any{ "service_tier": "flex", // a new key is added "stream_options": map[string]any{"include_obfuscation": false}, // maps deep-merge }), openai.ExtraHeaders(http.Header{"X-Request-Source": {"docs"}}), ) return m } // stallModel talks to a server that sends one chunk and then goes quiet. func stallModel(ctx context.Context, w io.Writer, baseURL string) error { client := openaisdk.NewClient(option.WithBaseURL(baseURL), option.WithAPIKey("test")) m := openai.Model("gpt-4o-mini", openai.Client(&client), openai.IdleTimeout(200*time.Millisecond), // default 60s; 0 disables it ) _, err := weft.New(m).Generate(ctx, weft.Prompt("hi")) if errors.Is(err, weft.ErrStreamIdle) { fmt.Fprintln(w, "the stream stalled:", err) } return err } // thinkingWire is the optional method an adapter declares to name the // provider field a thinking configuration is written to. type thinkingWire interface { ThinkingWire(weft.ThinkingConfig) string } func run(ctx context.Context, w io.Writer) error { official, local := openaiModels() detected, pinned := gatewayModels() claude, gemini := anthropicModel(), googleModel() // Constructing a model performs no I/O (openai and anthropic read the key // then; google on its first run). // Under WEFT_MODEL_REQUESTS=deny the first run fails before any request. for _, m := range []weft.Model{official, local, claude, gemini} { info := weft.InfoOf(m) _, err := weft.New(m).Generate(ctx, weft.Prompt("hi")) fmt.Fprintf(w, "%s/%s: denied=%v\n", info.Provider, info.Name, errors.Is(err, weft.ErrModelRequestsDenied)) } // What each adapter writes for each thinking configuration. configs := []struct { name string cfg weft.ThinkingConfig }{ {"unset", weft.ThinkingConfig{}}, {"off", weft.ThinkingConfig{Level: weft.ThinkOff}}, {"high", weft.ThinkingConfig{Level: weft.ThinkHigh}}, {"budget 2048", weft.ThinkingConfig{Budget: 2048}}, } fmt.Fprintf(w, "\n%-12s %-17s %-12s %-23s %s\n", "thinking", "openai", "z.ai", "anthropic", "google") for _, c := range configs { fmt.Fprintf(w, "%-12s %-17s %-12s %-23s %s\n", c.name, official.(thinkingWire).ThinkingWire(c.cfg), detected.(thinkingWire).ThinkingWire(c.cfg), claude.(thinkingWire).ThinkingWire(c.cfg), gemini.(thinkingWire).ThinkingWire(c.cfg)) } fmt.Fprintf(w, "pinned DialectObject, high: %s\n", pinned.(thinkingWire).ThinkingWire(weft.ThinkingConfig{Level: weft.ThinkHigh})) // The escape hatch, against a local server that records the request. srv := newFakeOpenAI() defer srv.Close() extras := weft.New(extrasModel(srv.URL)) res, err := extras.Generate(ctx, weft.Prompt("hi")) if err != nil { return err } body, header := srv.last() var payload map[string]any if err := json.Unmarshal(body, &payload); err != nil { return err } so, _ := json.Marshal(payload["stream_options"]) fmt.Fprintf(w, "\nanswer: %s\n", res.Text()) fmt.Fprintf(w, "service_tier: %v\n", payload["service_tier"]) fmt.Fprintf(w, "stream_options: %s\n", so) fmt.Fprintf(w, "X-Request-Source: %s\n", header.Get("X-Request-Source")) // The idle timeout, against a server that stalls after one chunk. stall := newStallServer() defer stall.Close() if err := stallModel(ctx, w, stall.URL); !errors.Is(err, weft.ErrStreamIdle) { return fmt.Errorf("want ErrStreamIdle, got %v", err) } return nil } // textOnly is a recorded Chat Completions stream: one text answer. const textOnly = `data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello from the model."},"finish_reason":null}]} data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]} data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":5,"total_tokens":14}} data: [DONE] ` type fakeOpenAI struct { *httptest.Server mu sync.Mutex body []byte header http.Header } func newFakeOpenAI() *fakeOpenAI { f := &fakeOpenAI{} f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { b, _ := io.ReadAll(r.Body) f.mu.Lock() f.body, f.header = b, r.Header.Clone() f.mu.Unlock() w.Header().Set("Content-Type", "text/event-stream") _, _ = io.WriteString(w, textOnly) })) return f } func (f *fakeOpenAI) last() ([]byte, http.Header) { f.mu.Lock() defer f.mu.Unlock() return f.body, f.header } // newStallServer sends the first chunk of an answer, then nothing until // the client goes away. func newStallServer() *httptest.Server { first, _, _ := strings.Cut(textOnly, "\n\n") return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/event-stream") _, _ = io.WriteString(w, first+"\n\n") w.(http.Flusher).Flush() <-r.Context().Done() })) } ``` [providers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/providers/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/providers) · from `docs-site/examples`: ```sh go run ./providers go test ./providers ``` ```text openai/gpt-4o-mini: denied=true openai/llama3.2: denied=true anthropic/claude-sonnet-5: denied=true google/gemini-2.5-flash: denied=true thinking openai z.ai anthropic google unset none none none none off none thinking thinking.disabled thinking_budget high reasoning_effort thinking thinking.adaptive thinking_level budget 2048 none none thinking.budget_tokens thinking_budget pinned DialectObject, high: thinking answer: Hello from the model. service_tier: flex stream_options: {"include_obfuscation":false,"include_usage":true} X-Request-Source: docs the stream stalled: weft: run failed at step 0: model stream: weft: model stream idle timeout after 200ms ``` ### Best practices & gotchas - **Set `MaxRetries(0)` when you use `mw.Retry`.** Otherwise the SDK sleeps on `retry-after` inside the idle timer and the call can fail as `ErrStreamIdle` with the 429 lost. (Source: `weft/openai/model.go:101-124`, CHANGELOG 0.3.4 `weft/CHANGELOG.md:5660`) - **Pin `openai.Dialect` behind an unrecognized gateway.** Detection knows four host suffixes; anything else gets `reasoning_effort`. (Source: `weft/openai/thinking.go:44-75`) - **Do not expect `ThinkOff` to stop OpenAI reasoning.** Chat Completions has no off switch, so nothing is sent under the effort dialect. (Source: `weft/openai/thinking.go:77-92`) - **Keep the prefix stable under `PromptCache`.** Trimming messages invalidates the trailing breakpoint; `weft.ToolChoiceNone` keeps the tool definitions in the request. (Source: `weft/anthropic/model.go:124-144`) - **`ExtraBody` keys win over weft's.** The bytes you add are yours: weft's default-bytes tests do not cover them. (Source: `weft/openai/model.go:126-147`, `weft/openai/extrabody_test.go:TestExtraBodyAndHeaders`) - **Do not set `Authorization` or `Content-Type` with `ExtraHeaders`.** The SDK sets them and the option does not check. (Source: `weft/openai/model.go:149-161`) - **An injected client ignores `WEFT_MODEL_REQUESTS=deny`.** Only clients the adapter built from credentials are guarded. (Source: `weft/core/env.go:5-20`, ADR 0013) - **Check `RawStopReason`, not only `StopReason`.** Gemini `SAFETY` and `RECITATION`, OpenAI `content_filter` and Anthropic `refusal` all map to `stop`. An OpenAI refusal's message is also the run's text. A prompt Gemini blocks outright is the exception: it reads `stop` with an empty `RawStopReason` and no text, so treat an empty answer from Gemini as a possible block. (Source: `weft/google/convert.go:438-458`, `weft/google/stream.go:80-84, 172-173`, `weft/openai/convert.go:256-279`, `weft/openai/stream.go:95-100`, `weft/anthropic/convert.go:343-366`) - **Do not turn on a provider-run tool with `ExtraBody`.** The anthropic adapter drops the blocks of `web_search`, `code_execution` and other server tools, so their calls and results never reach the transcript; the google adapter keeps only function calls, text and thought parts. A `tools` array in `ExtraBody` also replaces weft's tool list. Write a `weft.Tool` that calls the service instead. (Source: `weft/docs/adr/0013-adapter-contract.md:484-496`, `weft/anthropic/stream.go:99-103, 122-126`, `weft/google/stream.go:98-136`, `weft/internal/adapterkit/adapterkit.go:108-114`) - **Put the failure in an OpenAI tool error's text.** Chat Completions carries no error flag, so a `ToolError`'s `Code` and `Message` are all the model sees. (Source: `weft/openai/convert.go:56-71`, ADR 0013) - **Strip reasoning before another provider reads the transcript.** Anthropic and Gemini parts are signed, and each adapter sends a signed part as it is: anthropic as a `thinking` block with Gemini's signature, google as a `thoughtSignature` carrying Anthropic's. Neither signature is that provider's, so a `weft.UseModel` switch or a cross-provider `mw.Fallback` with reasoning on is expected to fail at the other provider. Only unsigned parts are dropped, and openai sends no reasoning back at all. Filter the parts out first ([Switch providers](https://weftgo.dev/docs/guides/thinking/#switch-providers)). (Source: `weft/anthropic/convert.go:278-281`, `weft/google/convert.go:278-322`, `weft/openai/convert.go:203-208`; scratch httptest capture) - **Check that a compatible server reports usage.** Without `include_usage` support the openai adapter reports zero input tokens, and a `weft/thread` session's automatic compaction, which reads the reported input, then in practice never fires, and nothing is logged ([compaction](https://weftgo.dev/docs/sessions/compaction/#best-practices--gotchas)). (Source: `weft/thread/turn.go:1661-1671`, `weft/thread/compaction.go:1332-1338, 1424-1428`) - **An injected `google.Client(c)` records no raw bodies.** Under `otel.RawBodies` only a client the google adapter built itself is captured; openai and anthropic capture either way. (Source: `weft/google/model.go:255-262`, `CHANGELOG.md:986-992`) ### See also - [What is a Model? The provider contract](https://weftgo.dev/docs/concepts/models/) - [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/) - [Control reasoning (thinking)](https://weftgo.dev/docs/guides/thinking/) - [Send images and files to a model](https://weftgo.dev/docs/guides/multimodal/) - [Prove a provider adapter with the conformance suite](https://weftgo.dev/docs/testing/conformance/) Symbols used: [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) · [`weft.Params`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Params) · [`weft.RequestParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequestParams) · [`weft.Thinking`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Thinking) · [`weft.ThinkingConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkingConfig) · [`weft.ToolChoiceNone`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceNone) · [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage) · [`weft.ErrStreamIdle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrStreamIdle) · [`weft.ErrUnsupported`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUnsupported) · [`weft.ErrModelRequestsDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRequestsDenied) · [`weft.ModelRequestsAllowed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequestsAllowed) · [`openai.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Model) · [`openai.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Option) · [`openai.APIKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#APIKey) · [`openai.BaseURL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#BaseURL) · [`openai.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Client) · [`openai.MaxTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#MaxTokens) · [`openai.Temperature`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Temperature) · [`openai.TopP`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#TopP) · [`openai.Stop`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Stop) · [`openai.Seed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Seed) · [`openai.IdleTimeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#IdleTimeout) · [`openai.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#MaxRetries) · [`openai.ExtraBody`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#ExtraBody) · [`openai.ExtraHeaders`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#ExtraHeaders) · [`openai.Dialect`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Dialect) · [`openai.ThinkingDialect`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#ThinkingDialect) · [`openai.DialectAuto`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectAuto) · [`openai.DialectEffort`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectEffort) · [`openai.DialectObject`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectObject) · [`openai.DialectNone`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectNone) · [`anthropic.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Model) · [`anthropic.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Option) · [`anthropic.APIKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#APIKey) · [`anthropic.BaseURL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#BaseURL) · [`anthropic.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Client) · [`anthropic.MaxTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#MaxTokens) · [`anthropic.Temperature`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Temperature) · [`anthropic.TopP`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#TopP) · [`anthropic.Stop`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Stop) · [`anthropic.IdleTimeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#IdleTimeout) · [`anthropic.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#MaxRetries) · [`anthropic.Thinking`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Thinking) · [`anthropic.PromptCache`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#PromptCache) · [`anthropic.ExtraBody`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#ExtraBody) · [`anthropic.ExtraHeaders`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#ExtraHeaders) · [`google.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Model) · [`google.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Option) · [`google.APIKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#APIKey) · [`google.BaseURL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#BaseURL) · [`google.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Client) · [`google.MaxTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#MaxTokens) · [`google.Temperature`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Temperature) · [`google.TopP`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#TopP) · [`google.Stop`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Stop) · [`google.Seed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Seed) · [`google.IdleTimeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#IdleTimeout) · [`google.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#MaxRetries) · [`google.ExtraBody`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#ExtraBody) · [`google.ExtraHeaders`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#ExtraHeaders) · [`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry) · [`mw.Fallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Fallback) · [`weft.UseModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UseModel) · [`weft.ReasoningPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReasoningPart) · [`conformance.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest/conformance#Run) --- # Control reasoning (thinking) URL: https://weftgo.dev/docs/guides/thinking/ Markdown: https://weftgo.dev/docs/guides/thinking.md > Set a reasoning level with weft.Thinking, as every run's default on the agent or for one run, and read the reasoning the provider returns as ReasoningDelta events and ReasoningPart blocks. [`weft.Thinking(weft.ThinkingConfig{…})`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Thinking) sets how hard the model reasons, on a provider-neutral scale. Passed to `weft.New` it is every run's default; passed to `Generate` or `Stream` it overrides that default for one run. Each adapter writes the level in its provider's own form. An agent that does not reason unless asked, in `thinking/main.go`: ```go title="thinking/main.go" agt := weft.New(model, weft.Thinking(weft.ThinkingConfig{Level: weft.ThinkOff}), // every run's default ) ``` [thinking/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/thinking/main.go) ### How it works The loop puts the run's configuration on every model request as `ModelRequest.Thinking`. The adapter maps it to the provider: `reasoning_effort` for OpenAI, a `thinking` object for Anthropic and the OpenAI-compatible gateways that take one, a thinking budget or level for Gemini. What a provider cannot express, the adapter drops and documents. Two examples: the Google adapter also asks Gemini to return thought summaries (`IncludeThoughts`) when a level or budget is set (not for `ThinkOff`), and the OpenAI adapter's `reasoning_effort` form has no off switch and no budget, so it drops `ThinkOff` and `Budget`. The full per-adapter mapping is on [Connect a model provider](https://weftgo.dev/docs/guides/providers/#thinking). Reasoning the provider returns comes back as [`weft.ReasoningDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReasoningDelta) events while the step streams and as [`weft.ReasoningPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReasoningPart) blocks in the transcript. weft keeps them and does not act on them. ### Choose a level [`weft.ThinkingConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkingConfig) has two fields: `Level`, a [`weft.ThinkingLevel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkingLevel), and `Budget`, a token count for providers whose depth control is a cap. | Level | Meaning | |---|---| | [`weft.ThinkUnset`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkUnset) | The zero value. Nothing is sent; the provider default applies. | | [`weft.ThinkOff`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkOff) | Suppress reasoning where the provider allows it. | | [`weft.ThinkLow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkLow) | Low effort. | | [`weft.ThinkMedium`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkMedium) | Medium effort. | | [`weft.ThinkHigh`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkHigh) | High effort. | `Level` and `Budget` combine: - **A level without a budget** leaves the depth to the provider: Anthropic's adaptive thinking, Gemini's own level mapping. - **A budget without a level** pins the depth to that many tokens: Anthropic's `budget_tokens`, Gemini's thinking budget. - **`ThinkOff` with a budget**: off wins. `weft.Thinking` returns a [`weft.ThinkingOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkingOption), an interface that is both an `Option` and a `RunOption`, which is why one call works in both places. ### Set the agent default The option on `weft.New` sets every run's default, as in the snippet above. [`agt.Thinking()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Thinking) returns it; the zero value means the provider default. An adapter declares how it sends a configuration with the optional method `ThinkingWire(weft.ThinkingConfig) string`: the provider field it writes, or `none`. The loop finds it along the model's `Unwrap` chain, so it survives middleware such as `mw.Retry`, and records it on each request record as `thinking.wire`; Studio shows it on the step. The method never calls the provider. The first-party adapters implement it; a custom adapter may. weft exports no interface for it: it is a convention, like `Info`. ### Override it for one run Pass `weft.Thinking` beside the prompt to change one run without rebuilding the agent: fast by default, think on demand: ```go title="thinking/main.go" deep := weft.Thinking(weft.ThinkingConfig{Level: weft.ThinkHigh, Budget: 2048}) if _, err := agt.Generate(ctx, deep, weft.Prompt("Plan the migration.")); err != nil { return err } if _, err := agt.Generate(ctx, weft.Prompt("What time is it in UTC?")); err != nil { return err } ``` [thinking/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/thinking/main.go) ```text run 1 asked for: level=high budget=2048 run 2 asked for: level=off budget=0 ``` The run option replaces the agent's configuration whole for that run; the second run, with no option, falls back to the agent's `ThinkOff`. A `weft.PrepareStep` function can also change `Thinking` per step, and the request record lists `thinking` among the fields it rewrote. The package example is [`ExampleThinking`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Thinking); per-run options in general are on [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/). ### Read reasoning parts While a step streams, reasoning arrives as `ReasoningDelta` events in the order the model produced it relative to `TextDelta`. After the run, the assistant message holds one `ReasoningPart` per provider block, before the `TextPart` of the same message: ```go title="thinking/main.go" run := agt.Stream(ctx, weft.Prompt("Hi.")) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.ReasoningDelta: fmt.Fprintln(w, "reasoning:", ev.Text) case weft.TextDelta: fmt.Fprintln(w, "text:", ev.Text) } } res, err := run.Wait() if err != nil { return err } for _, p := range res.Messages[1].Content { // the assistant message switch p := p.(type) { case weft.ReasoningPart: fmt.Fprintf(w, "part: reasoning %q, signed: %t\n", p.Text, p.Signature != "") case weft.TextPart: fmt.Fprintf(w, "part: text %q\n", p.Text) } } ``` [thinking/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/thinking/main.go) ```text reasoning: The user greets; reply in kind. text: Hello! part: reasoning "The user greets; reply in kind.", signed: false part: text "Hello!" ``` A `ReasoningPart` has two fields. `Text` is the reasoning. `Signature` is the provider's opaque token for the block: Anthropic rejects thinking sent back without it, and Gemini validates its own on the next request. Signatures are not streamed; they are only on the part. The anthropic and google adapters send them back unchanged, so a transcript you feed back with `weft.Messages` keeps them; the openai adapter sends no reasoning back. The complete example scripts a signed block and checks the signature reaches the next request. What each adapter does with a `ReasoningPart` it is given: | Part | `openai` | `anthropic` | `google` | |---|---|---|---| | Signed | dropped: Chat Completions takes no reasoning input | sent as a `thinking` block with its signature, whichever provider signed it | sent as a thought part with its signature, whichever provider signed it; on a step with tool calls, only the signatures go back, on the function-call parts | | Unsigned | dropped | dropped, with no error | dropped, with no error | One kind of Anthropic block does not round-trip at all. A `redacted_thinking` block, reasoning the provider returns encrypted, is skipped by the anthropic stream like any block that is not text, thinking or `tool_use`. It never becomes a `ReasoningPart`, so it is not in `res.Messages` and is never sent back. ADR 0013 lists redacted thinking blocks as a known gap of the anthropic adapter. A part is unsigned when it came from the openai adapter (a server's DeepSeek-style `reasoning_content`), from `wefttest.Think`, or from Gemini thought text on a step with tool calls, whose signature rides the function call instead. Anthropic's thinking blocks and Gemini's thoughts on a step without calls are signed, and neither adapter can tell whose signature a part carries: after a [provider switch](https://weftgo.dev/docs/guides/thinking/#switch-providers) each sends the other's signature as if it were its own. On Gemini, a step with tool calls returns each call's own signature on that call; when no call has one (a transcript recorded before per-call signatures), the reasoning's signature goes back on the first call. A step yields one part per provider block: a delta that carries a signature closes the block, and the next reasoning delta opens a new one. Reasoning without any signature accumulates into a single block. The package example is [`ExampleReasoningPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ReasoningPart). ### Switch providers Strip `ReasoningPart`s from a transcript before a different provider reads it. A signed part is sent as it is, so Anthropic would get a `thinking` block carrying Gemini's signature, and Gemini would get Anthropic's signature as a `thoughtSignature`. Neither is that provider's own signature, so the request is expected to be rejected (Gemini validates the signatures it gets back). weft has no helper for this; a plain filter, in `thinking/main.go`: ```go title="thinking/main.go" // withoutReasoning returns msgs with every ReasoningPart dropped, for a // transcript another provider is about to read. func withoutReasoning(msgs []weft.Message) []weft.Message { out := make([]weft.Message, 0, len(msgs)) for _, m := range msgs { parts := make([]weft.Part, 0, len(m.Content)) for _, p := range m.Content { if _, ok := p.(weft.ReasoningPart); !ok { parts = append(parts, p) } } out = append(out, weft.Message{Role: m.Role, Content: parts}) } return out } // noReasoning wraps a backup model so it never receives reasoning. type noReasoning struct{ weft.Model } func (m noReasoning) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { req.Messages = withoutReasoning(req.Messages) return m.Model.Stream(ctx, req) } // Info names the wrapped adapter in mw.Fallback's attempt report. func (m noReasoning) Info() weft.ModelInfo { return weft.InfoOf(m.Model) } // Unwrap lets mw.Fallback find a self-reporting model inside, such as // one wrapped in mw.Retry, so its attempts are not reported twice. func (m noReasoning) Unwrap() weft.Model { return m.Model } ``` [thinking/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/thinking/main.go) Wrap a cross-provider `mw.Fallback` backup in the filter, and filter `res.Messages` before you continue the conversation on another model with `weft.UseModel`: ```go title="thinking/main.go" agt := weft.New(primary, lookup, weft.WrapModel(mw.Fallback(noReasoning{backup})), // the backup gets no reasoning ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } // Continue on another provider: filter the transcript first. if _, err := agt.Generate(ctx, weft.Messages(withoutReasoning(res.Messages)...), weft.Prompt("Thanks."), weft.UseModel(other)); err != nil { return err } ``` [thinking/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/thinking/main.go) ```text transcript keeps: 1 reasoning part backup received: 0 reasoning parts other model received: 0 reasoning parts ``` The filter changes only what the other provider reads; `res.Messages` keeps every part. Wrap only the backup: the primary still needs its own signatures ([gotcha](https://weftgo.dev/docs/guides/thinking/#best-practices--gotchas)). A step the backup answered leaves the backup's signed parts in the transcript, and the primary's next request carries them. With reasoning on at both ends, filter the primary's requests too, and accept that the primary then loses its own signatures. `Info` forwards the adapter's identity, so `mw.Fallback`'s attempt report names the backup. `Unwrap` lets `mw.Fallback` find a backup that reports its own attempts, such as one wrapped in `mw.Retry`, so those attempts are not reported twice. ### Complete example `thinking/main.go` sets a default, overrides it per run, streams reasoning, round-trips a signed block, and strips reasoning before a provider switch: ```go title="thinking/main.go" // Command thinking runs the examples of the guide "Control reasoning // (thinking)": go run ./thinking. Every model is scripted with wefttest, // so it runs offline; swap in a provider adapter for a real one. package main import ( "context" "encoding/json" "errors" "fmt" "io" "iter" "os" "github.com/weftgo/weft" "github.com/weftgo/weft/mw" "github.com/weftgo/weft/wefttest" ) // levels names the neutral scale for printing. var levels = map[weft.ThinkingLevel]string{ weft.ThinkUnset: "unset", weft.ThinkOff: "off", weft.ThinkLow: "low", weft.ThinkMedium: "medium", weft.ThinkHigh: "high", } // perRun: the agent thinks off by default; one run asks for high. func perRun(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("ok"), wefttest.Say("ok")) agt := weft.New(model, weft.Thinking(weft.ThinkingConfig{Level: weft.ThinkOff}), // every run's default ) deep := weft.Thinking(weft.ThinkingConfig{Level: weft.ThinkHigh, Budget: 2048}) if _, err := agt.Generate(ctx, deep, weft.Prompt("Plan the migration.")); err != nil { return err } if _, err := agt.Generate(ctx, weft.Prompt("What time is it in UTC?")); err != nil { return err } for i, req := range model.Requests() { // the scripted model records what each run asked for fmt.Fprintf(w, "run %d asked for: level=%s budget=%d\n", i+1, levels[req.Thinking.Level], req.Thinking.Budget) } return nil } // parts streams a reasoning step and reads its parts back. func parts(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.Think("The user greets; reply in kind.", wefttest.Say("Hello!")), ) agt := weft.New(model) run := agt.Stream(ctx, weft.Prompt("Hi.")) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.ReasoningDelta: fmt.Fprintln(w, "reasoning:", ev.Text) case weft.TextDelta: fmt.Fprintln(w, "text:", ev.Text) } } res, err := run.Wait() if err != nil { return err } for _, p := range res.Messages[1].Content { // the assistant message switch p := p.(type) { case weft.ReasoningPart: fmt.Fprintf(w, "part: reasoning %q, signed: %t\n", p.Text, p.Signature != "") case weft.TextPart: fmt.Fprintf(w, "part: text %q\n", p.Text) } } return nil } // signed scripts a provider block that carries a signature, the way // Anthropic and Gemini send theirs. func signed(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.Raw( weft.ModelReasoningDelta{Text: "Check the order first."}, weft.ModelReasoningDelta{Signature: "sig-abc"}, // closes the block weft.ModelTextDelta{Text: "Order 1234 has shipped."}, weft.ModelFinish{Reason: weft.StopEndTurn}, ), wefttest.Say("You are welcome."), ) agt := weft.New(model) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } for _, p := range res.Messages[1].Content { if r, ok := p.(weft.ReasoningPart); ok { fmt.Fprintf(w, "signed block: %q signature=%s\n", r.Text, r.Signature) } } // The transcript goes back to the model with the signature intact. if _, err := agt.Generate(ctx, weft.Messages(res.Messages...), weft.Prompt("Thanks.")); err != nil { return err } for _, p := range model.LastRequest().Messages[1].Content { if r, ok := p.(weft.ReasoningPart); ok { fmt.Fprintf(w, "sent back: signature=%s\n", r.Signature) } } return nil } // withoutReasoning returns msgs with every ReasoningPart dropped, for a // transcript another provider is about to read. func withoutReasoning(msgs []weft.Message) []weft.Message { out := make([]weft.Message, 0, len(msgs)) for _, m := range msgs { parts := make([]weft.Part, 0, len(m.Content)) for _, p := range m.Content { if _, ok := p.(weft.ReasoningPart); !ok { parts = append(parts, p) } } out = append(out, weft.Message{Role: m.Role, Content: parts}) } return out } // noReasoning wraps a backup model so it never receives reasoning. type noReasoning struct{ weft.Model } func (m noReasoning) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { req.Messages = withoutReasoning(req.Messages) return m.Model.Stream(ctx, req) } // Info names the wrapped adapter in mw.Fallback's attempt report. func (m noReasoning) Info() weft.ModelInfo { return weft.InfoOf(m.Model) } // Unwrap lets mw.Fallback find a self-reporting model inside, such as // one wrapped in mw.Retry, so its attempts are not reported twice. func (m noReasoning) Unwrap() weft.Model { return m.Model } // countReasoning counts the ReasoningParts in msgs. func countReasoning(msgs []weft.Message) int { n := 0 for _, m := range msgs { for _, p := range m.Content { if _, ok := p.(weft.ReasoningPart); ok { n++ } } } return n } // switchProviders sends a transcript with a signed block to a backup // and to another model, without the block. func switchProviders(ctx context.Context, w io.Writer) error { type lookupInput struct { OrderID string `json:"order_id"` } lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in lookupInput) (string, error) { return "shipped", nil }) primary := wefttest.Script( wefttest.Raw( weft.ModelReasoningDelta{Text: "Look the order up.", Signature: "sig-primary"}, weft.ModelToolCall{ID: "c1", Name: "lookup_order", Args: json.RawMessage(`{"order_id":"1234"}`)}, weft.ModelFinish{Reason: weft.StopToolCalls}, ), wefttest.Fail(errors.New("primary down")), ) backup := wefttest.Script(wefttest.Say("Order 1234 has shipped.")) other := wefttest.Script(wefttest.Say("You are welcome.")) agt := weft.New(primary, lookup, weft.WrapModel(mw.Fallback(noReasoning{backup})), // the backup gets no reasoning ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } // Continue on another provider: filter the transcript first. if _, err := agt.Generate(ctx, weft.Messages(withoutReasoning(res.Messages)...), weft.Prompt("Thanks."), weft.UseModel(other)); err != nil { return err } fmt.Fprintf(w, "transcript keeps: %d reasoning part\n", countReasoning(res.Messages)) fmt.Fprintf(w, "backup received: %d reasoning parts\n", countReasoning(backup.LastRequest().Messages)) fmt.Fprintf(w, "other model received: %d reasoning parts\n", countReasoning(other.LastRequest().Messages)) return nil } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"per run", perRun}, {"parts", parts}, {"signed", signed}, {"switch providers", switchProviders}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [thinking/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/thinking/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/thinking) · run it from `docs-site/examples`: ```sh go run ./thinking go test ./thinking ``` ```text == per run run 1 asked for: level=high budget=2048 run 2 asked for: level=off budget=0 == parts reasoning: The user greets; reply in kind. text: Hello! part: reasoning "The user greets; reply in kind.", signed: false part: text "Hello!" == signed signed block: "Check the order first." signature=sig-abc sent back: signature=sig-abc == switch providers transcript keeps: 1 reasoning part backup received: 0 reasoning parts other model received: 0 reasoning parts ``` ### Best practices & gotchas - **Leave the level unset to keep the provider's default.** `ThinkUnset` sends nothing, so an adapter's construction setting, such as `anthropic.Thinking(true)`, applies. (Source: `weft/core/model.go:64-78`) - **Do not strip `ReasoningPart`s from a transcript you send back to the same provider.** They carry the signatures the anthropic adapter returns as `thinking` blocks and the google adapter returns on the turn's thought or function-call parts; strip them and the provider gets its own reasoning back without them. (Source: `weft/anthropic/convert.go:270-285`, `weft/google/convert.go:259-327`) - **Do not count on Anthropic's redacted thinking reaching the next request.** The anthropic adapter drops `redacted_thinking` blocks when it reads the stream, so a step that returned one goes back to the API without it, and nothing in the transcript or the events shows it was there. (Source: `weft/anthropic/stream.go:90-103`, ADR 0013 `docs/adr/0013-adapter-contract.md:159`) - **Strip reasoning before a provider switch.** After `weft.UseModel` or a cross-provider `mw.Fallback`, anthropic and google send a signed part from the other provider as their own, and the request is expected to be rejected. An unsigned part is dropped silently, and openai drops every part. Filter the transcript the other provider reads ([Switch providers](https://weftgo.dev/docs/guides/thinking/#switch-providers)). (Source: `weft/anthropic/convert.go:278-281`, `weft/google/convert.go:278-322`, `weft/openai/convert.go:203-208`; scratch httptest capture) - **Expect a level to be dropped where a provider has no form for it.** Adapters map what the provider can express and document what they drop; check the request's `thinking.wire` in Studio. (Source: `weft/core/agent.go:328-329`, ADR 0013) - **Use `wefttest.Think` to test reasoning offline.** It prefixes a scripted turn with an unsigned reasoning delta; script signed blocks with `wefttest.Raw`. (Source: `wefttest.Think` godoc) ### See also - [Connect a model provider](https://weftgo.dev/docs/guides/providers/#thinking): what each adapter sends - [What is a Model? The provider contract](https://weftgo.dev/docs/concepts/models/) - [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/) - [Stream a run's events](https://weftgo.dev/docs/guides/streaming/) Symbols used: [`weft.Thinking`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Thinking) · [`weft.ThinkingOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkingOption) · [`weft.ThinkingConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkingConfig) · [`weft.ThinkingLevel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkingLevel) · [`weft.ThinkUnset`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkUnset) · [`weft.ThinkOff`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkOff) · [`weft.ThinkLow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkLow) · [`weft.ThinkMedium`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkMedium) · [`weft.ThinkHigh`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkHigh) · [`Agent.Thinking`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Thinking) · [`weft.ReasoningPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReasoningPart) · [`weft.ReasoningDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReasoningDelta) · [`weft.ModelReasoningDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelReasoningDelta) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.Unwrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Unwrap) · [`weft.UseModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UseModel) · [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) · [`mw.Fallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Fallback) · [`weft.PrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PrepareStep) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`wefttest.Think`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Think) · [`wefttest.Raw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Raw) --- # Send images and files to a model URL: https://weftgo.dev/docs/guides/multimodal/ Markdown: https://weftgo.dev/docs/guides/multimodal.md > Build a prompt that mixes text and files with weft.UserParts and weft.FilePart; an adapter that cannot carry a file fails the model call with an error wrapping weft.ErrUnsupported. A file goes into a prompt as a part. [`weft.UserParts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UserParts) builds a user message from parts, and a [`weft.FilePart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#FilePart) carries an image, a PDF or audio, inline or by URL. The adapter maps it to the provider's image or document block; one that cannot carry the file fails the model call with an error wrapping [`weft.ErrUnsupported`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUnsupported). An image beside a question, in `multimodal/main.go`: ```go title="multimodal/main.go" msg := weft.UserParts( weft.TextPart{Text: "What is the total on this receipt?"}, weft.FilePart{MediaType: "image/png", Data: receiptPNG}, // or URL: "https://…" ) res, err := agt.Generate(ctx, weft.Messages(msg)) ``` [multimodal/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/multimodal/main.go) `weft.Prompt` takes text only, so a message with parts goes in through [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages). ### How it works A message is a role plus typed parts ([rule 2](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). `UserParts` copies the parts you give it into a `user` message; your slice is not retained. The core never reads a file's bytes: it carries the part to the model, and the adapter decides how to send it. On the wire the part has the type `file`, and inline bytes are base64-encoded, as `[]byte` is in `encoding/json`: ```json {"role":"user","content":[{"type":"text","text":"hi"},{"type":"file","media_type":"image/png","data":"YWJj"}]} ``` The transcript keeps the part, so a run you continue with `weft.Messages(res.Messages...)` sends the file again on every model call. See [Messages, parts and the transcript](https://weftgo.dev/docs/concepts/messages/). ### Send an image A `FilePart` has three fields. Set `MediaType` and exactly one of the other two: | Field | Type | Holds | |---|---|---| | `MediaType` | `string` | The file's MIME type: `image/png`, `application/pdf`, … | | `Data` | `[]byte` | The file inline. | | `URL` | `string` | A URL the provider fetches, or Gemini's file URI. | The exactly-one rule is checked by the adapter, not the core: a part with both or neither set fails the model call with `ErrUnsupported`. The package example [`ExampleUserParts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-UserParts) prints a message with a URL part. What each first-party adapter carries: | Adapter | Carries | Sent as | |---|---|---| | [`openai`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai) | images only (`image/*`) | an `image_url` part: the URL, or a `data:` URL for inline bytes | | [`anthropic`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic) | `image/png`, `image/jpeg`, `image/gif`, `image/webp`, `application/pdf` | an image or document block, base64 or URL | | [`google`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google) | every media type: the adapter does not filter, and Gemini carries images, audio and video natively | inline data, or file data for a URL | ### Handle a file the adapter cannot carry An adapter refuses a part it cannot send before any request leaves the process. The run fails at that step with a `*RunError` that matches `weft.ErrUnsupported`: ```go title="multimodal/main.go" msg := weft.UserParts( weft.TextPart{Text: "Summarise this contract."}, weft.FilePart{MediaType: "application/pdf", URL: "https://example.com/contract.pdf"}, ) _, err := agt.Generate(ctx, weft.Messages(msg)) if errors.Is(err, weft.ErrUnsupported) { fmt.Fprintln(w, "unsupported:", err) } ``` [multimodal/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/multimodal/main.go) ```text unsupported: weft: run failed at step 0: model stream: weft: request uses a feature the model does not support: chat completions accept image files, got "application/pdf" requests sent: 0 ``` The OpenAI adapter speaks Chat Completions, which accepts images only, so the PDF fails there; the Anthropic adapter would send it as a document block. Because the failure is a run error, you can match it with `errors.Is` and send the request to another model, for example with `mw.FallbackWhen` ([Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/)). Once a backup has been tried, the run error is the backup's: if it fails too, `errors.Is(err, weft.ErrUnsupported)` is false. ### Complete example `multimodal/main.go` sends an image to a scripted model and a PDF to the OpenAI adapter, pointed at a local test server that counts requests: ```go title="multimodal/main.go" // Command multimodal runs the examples of the guide "Send images and // files to a model": go run ./multimodal. The model is scripted with // wefttest, and the adapter demo talks to a local test server, so it runs // offline. package main import ( "context" "errors" "fmt" "io" "net/http" "net/http/httptest" "os" "sync/atomic" openaisdk "github.com/openai/openai-go" "github.com/openai/openai-go/option" "github.com/weftgo/weft" "github.com/weftgo/weft/openai" "github.com/weftgo/weft/wefttest" ) // receiptPNG stands in for an image read from disk or an upload. var receiptPNG = []byte("\x89PNG\r\n\x1a\n…") // sendImage puts an image beside a question and shows what the model got. func sendImage(ctx context.Context, w io.Writer) error { scripted := wefttest.Script(wefttest.Say("The receipt is for $42.10.")) agt := weft.New(scripted) msg := weft.UserParts( weft.TextPart{Text: "What is the total on this receipt?"}, weft.FilePart{MediaType: "image/png", Data: receiptPNG}, // or URL: "https://…" ) res, err := agt.Generate(ctx, weft.Messages(msg)) if err != nil { return err } for _, p := range scripted.LastRequest().Messages[0].Content { switch p := p.(type) { case weft.TextPart: fmt.Fprintf(w, "model received text: %q\n", p.Text) case weft.FilePart: fmt.Fprintf(w, "model received file: %s, %d bytes\n", p.MediaType, len(p.Data)) } } fmt.Fprintln(w, "answer:", res.Text()) return nil } // unsupported sends a PDF through the OpenAI adapter, whose Chat // Completions API takes images only. The test server counts requests. func unsupported(ctx context.Context, w io.Writer) error { var hits atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { hits.Add(1) http.Error(rw, "not reached", http.StatusTeapot) })) defer srv.Close() client := openaisdk.NewClient(option.WithBaseURL(srv.URL), option.WithAPIKey("test")) model := openai.Model("gpt-5-mini", openai.Client(&client)) agt := weft.New(model) msg := weft.UserParts( weft.TextPart{Text: "Summarise this contract."}, weft.FilePart{MediaType: "application/pdf", URL: "https://example.com/contract.pdf"}, ) _, err := agt.Generate(ctx, weft.Messages(msg)) if errors.Is(err, weft.ErrUnsupported) { fmt.Fprintln(w, "unsupported:", err) } fmt.Fprintln(w, "requests sent:", hits.Load()) return nil } func run(ctx context.Context, w io.Writer) error { fmt.Fprintln(w, "== image") if err := sendImage(ctx, w); err != nil { return err } fmt.Fprintln(w, "== unsupported") return unsupported(ctx, w) } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [multimodal/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/multimodal/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/multimodal) · run it from `docs-site/examples`: ```sh go run ./multimodal go test ./multimodal ``` ```text == image model received text: "What is the total on this receipt?" model received file: image/png, 11 bytes answer: The receipt is for $42.10. == unsupported unsupported: weft: run failed at step 0: model stream: weft: request uses a feature the model does not support: chat completions accept image files, got "application/pdf" requests sent: 0 ``` ### Best practices & gotchas - **Set exactly one of `Data` and `URL`.** The adapter refuses a part with both or neither, wrapping `ErrUnsupported`. (Source: `weft/core/message.go:192-199`, `weft/internal/adapterkit/adapterkit.go:101-106`) - **Check `errors.Is(err, weft.ErrUnsupported)` to fall back.** The refusal is a run error, raised before the request is sent. Under `mw.FallbackWhen` the check belongs in the predicate: when the backup fails too, the run error is the backup's alone. (Source: `weft/core/errors.go:64-69`, `weft/core/mw/model.go:118-125`) - **Send PDFs to the Anthropic or Google adapter.** The OpenAI adapter's Chat Completions API takes images only. (Source: `weft/openai/convert.go:157-160`, ADR 0013 Appendix A) - **Mind the transcript's size.** A continued conversation carries every earlier file part on every model call. (Source: rule 2; `weft/core/message.go:48-54`) ### See also - [Messages, parts and the transcript](https://weftgo.dev/docs/concepts/messages/) - [Connect a model provider](https://weftgo.dev/docs/guides/providers/) - [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/) Symbols used: [`weft.UserParts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UserParts) · [`weft.FilePart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#FilePart) · [`weft.TextPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TextPart) · [`weft.ErrUnsupported`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUnsupported) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`openai.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Model) · [`openai.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Client) · [`mw.FallbackWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#FallbackWhen) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Rewrite the request each step (PrepareStep) URL: https://weftgo.dev/docs/guides/prepare-step/ Markdown: https://weftgo.dev/docs/guides/prepare-step.md > Install weft.PrepareStep to trim messages, change the tools, the system prompt, tool choice or sampling for each model call, without touching the transcript. [`weft.PrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PrepareStep) installs a function the loop calls before every model call, with the [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) it built for that step. The request your function returns is what the step sends: trimmed messages, a subset of tools, a rewritten system prompt, a different tool choice or sampling. The transcript in the run's result is never changed. A function that sends the model at most the last `n` messages, from `preparestep/main.go`: ```go title="preparestep/main.go" // keepLast returns a PrepareStep function that sends the model at most the // last n messages. The cut moves forward to a user message, so the window // never opens on a tool result whose call was cut away. func keepLast(n int) func(context.Context, int, weft.ModelRequest) (weft.ModelRequest, error) { return func(_ context.Context, _ int, req weft.ModelRequest) (weft.ModelRequest, error) { if len(req.Messages) <= n { return req, nil } window := req.Messages[len(req.Messages)-n:] for len(window) > 1 && window[0].Role != weft.RoleUser { window = window[1:] } req.Messages = window return req, nil } } ``` [preparestep/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/preparestep/main.go) Install it on the agent: ```go title="preparestep/main.go" agt := weft.New(model, weft.Instructions("You are a support agent."), weft.PrepareStep(keepLast(3)), ) ``` [preparestep/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/preparestep/main.go) With four messages of history and a new prompt, the model sees the last three; `res.Messages` still holds all six. The cut moves forward to a `user` message so the window never opens on a tool result whose call was cut away ([rule 2](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them): every tool call is paired with its result). ### How it works The loop builds each step's request from the agent's instructions, the transcript so far, the step's tool snapshot, and the run's thinking, tool choice and sampling. Then it runs the `PrepareStep` chain: 1. The request your function receives is a copy. Message parts, tool-call argument bytes and tool definitions are deep-copied before the chain runs, so writing into them in place reaches neither the transcript nor the agent's registered tools (`TestPrepareStepCopiesDefendTheRun`). 2. Several `PrepareStep` options run in the order you passed them, each receiving the previous one's result. A nil function is ignored. 3. The tools the chain returns become the step's snapshot: what the step advertises and what it dispatches against. They are validated like a `ToolSource` snapshot, so a duplicate name fails the run with [`weft.ErrDuplicateTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrDuplicateTool) and a nil entry with [`weft.ErrNilTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNilTool). 4. The tool choice and the sampling params are validated against that snapshot. A named choice for a tool the function removed fails the run; so does a negative `MaxTokens`. 5. [Prompt snippets](https://weftgo.dev/docs/guides/tool-policy/) are composed into the system prompt after the chain, from the tools it returned. Your function sees the raw instructions, never the composed text. 6. The request goes through the [`WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) chain to the model, so model middleware sees the prepared request. `PrepareStep` is a loop knob, in the same category as `StopWhen`, not a third seam ([ADR 0006, amendment](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0006-seams.md)). Model middleware can rewrite a request too, but it cannot make the loop dispatch against the tools it removed; `PrepareStep` runs before the snapshot is fixed, so the two always agree. The package example [`ExamplePrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-PrepareStep) shows phased tool exposure. ### Offer a tool only from a later step The `step` argument is the zero-based step index. Remove a tool from `req.Tools` on the steps where the model must not call it: ```go title="preparestep/main.go" investigateFirst := func(_ context.Context, step int, req weft.ModelRequest) (weft.ModelRequest, error) { if step == 0 { req.Tools = slices.DeleteFunc(req.Tools, func(t *weft.ToolDef) bool { return t.Name == "refund" }) } return req, nil } agt := weft.New(model, weft.Instructions("You are a support agent."), lookup, refund, weft.PrepareStep(investigateFirst)) ``` [preparestep/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/preparestep/main.go) The scripted model calls `refund` on step 0 anyway. That call fails as an unknown tool, `NO_SUCH_TOOL: no tool named "refund"`, because the step did not offer it; on step 1 the same call runs. The refund tool's snippet, `Refund only after a lookup.`, is absent from step 0's system prompt and present from step 1: removing a tool removes its snippet. ### Change the system prompt, tool choice or sampling per step Every field of the request is yours to rewrite: [`System`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.System), [`Messages`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.Messages), [`Tools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.Tools), [`ToolChoice`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.ToolChoice), [`Params`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.Params), [`Thinking`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.Thinking) and [`SequentialTools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.SequentialTools). Two package examples use it this way: [`ExampleToolChoice`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolChoice) forces a `classify` call on step 0 only, and [`ExampleParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Params) sets the temperature to 0 for the classifying step. The agent-wide and per-run forms of those knobs are in [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/). The request record of each step names what the chain changed (`prepared`: `system`, `messages`, `tools`, `tool_choice`, `params`, `thinking`, `sequential_tools`), names only, so a reader can see a rewrite even with content off ([record contract](https://weftgo.dev/docs/reference/record-contract/)). ### Fail the run from PrepareStep Return an error to stop the run before the step's model call. The run fails with a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) that wraps your error, so `errors.Is` finds your sentinel: ```go title="preparestep/main.go" var errNoTenant = errors.New("no tenant on the request") func requireTenant(ctx context.Context, _ int, req weft.ModelRequest) (weft.ModelRequest, error) { if weft.MetadataFromContext(ctx)["tenant"] == "" { return req, errNoTenant // fails the run before the model is called } return req, nil } ``` [preparestep/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/preparestep/main.go) The function receives the run's context, so it can read the run's [metadata](https://weftgo.dev/docs/guides/metadata/) as this one does. A panic is different from an error: the loop closes the run's span and re-panics. Under `agt.Generate` the run is on your goroutine, so the panic reaches your caller. Under `agt.Stream` the run has its own goroutine, so the panic crashes the program and no caller can recover it. ### Complete example `preparestep/main.go` runs the three cases against scripted models: ```go title="preparestep/main.go" // Command preparestep runs the examples of the guide "Rewrite the request // each step (PrepareStep)": go run ./preparestep. Every model is scripted // with wefttest, so it runs offline; swap in a provider adapter for a real // one. package main import ( "context" "errors" "fmt" "io" "os" "slices" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // keepLast returns a PrepareStep function that sends the model at most the // last n messages. The cut moves forward to a user message, so the window // never opens on a tool result whose call was cut away. func keepLast(n int) func(context.Context, int, weft.ModelRequest) (weft.ModelRequest, error) { return func(_ context.Context, _ int, req weft.ModelRequest) (weft.ModelRequest, error) { if len(req.Messages) <= n { return req, nil } window := req.Messages[len(req.Messages)-n:] for len(window) > 1 && window[0].Role != weft.RoleUser { window = window[1:] } req.Messages = window return req, nil } } // trim feeds a long history back and trims what each step sends. func trim(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("Order 9012 is out for delivery.")) agt := weft.New(model, weft.Instructions("You are a support agent."), weft.PrepareStep(keepLast(3)), ) history := []weft.Message{ weft.User("Where is order 1234?"), weft.Assistant("Order 1234 shipped yesterday."), weft.User("And order 5678?"), weft.Assistant("Order 5678 is still pending."), } res, err := agt.Generate(ctx, weft.Messages(history...), weft.Prompt("And order 9012?")) if err != nil { return err } req := model.LastRequest() fmt.Fprintf(w, "the model saw %d of %d messages, starting with %q\n", len(req.Messages), len(history)+1, req.Messages[0].Text()) fmt.Fprintf(w, "the transcript keeps all %d messages\n", len(res.Messages)) return nil } // phased offers refund only after the first step, and shows that the // returned tools are what the step advertises, dispatches and composes // snippets from. func phased(ctx context.Context, w io.Writer) error { lookup := weft.Tool("lookup", "Look up an order.", func(_ context.Context, _ struct{}) (string, error) { return "order 1234: broken item", nil }) refund := weft.Tool("refund", "Refund an order.", func(_ context.Context, _ struct{}) (string, error) { return "refunded", nil }, weft.PromptSnippet("Refund only after a lookup.")) model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "refund"}), // not advertised in step 0 wefttest.ToolCalls(wefttest.Call{Name: "refund"}), // advertised from step 1 wefttest.Say("Refunded order 1234."), ) investigateFirst := func(_ context.Context, step int, req weft.ModelRequest) (weft.ModelRequest, error) { if step == 0 { req.Tools = slices.DeleteFunc(req.Tools, func(t *weft.ToolDef) bool { return t.Name == "refund" }) } return req, nil } agt := weft.New(model, weft.Instructions("You are a support agent."), lookup, refund, weft.PrepareStep(investigateFirst)) res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234.")) if err != nil { return err } for i, req := range model.Requests() { var names []string for _, t := range req.Tools { names = append(names, t.Name) } fmt.Fprintf(w, "step %d: tools %v, system %q\n", i, names, req.System) } for _, s := range res.Steps[:2] { fmt.Fprintf(w, "step %d result: %s\n", s.Index, s.Results[0].Content) } return nil } var errNoTenant = errors.New("no tenant on the request") func requireTenant(ctx context.Context, _ int, req weft.ModelRequest) (weft.ModelRequest, error) { if weft.MetadataFromContext(ctx)["tenant"] == "" { return req, errNoTenant // fails the run before the model is called } return req, nil } // failing shows that a PrepareStep error fails the run with the caller's // sentinel reachable through errors.Is, before any model call. func failing(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("unused")) agt := weft.New(model, weft.PrepareStep(requireTenant)) _, err := agt.Generate(ctx, weft.Prompt("hi")) var runErr *weft.RunError fmt.Fprintf(w, "errors.Is(err, errNoTenant): %t\n", errors.Is(err, errNoTenant)) fmt.Fprintf(w, "a *RunError: %t, model calls: %d\n", errors.As(err, &runErr), len(model.Requests())) return nil } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"trim", trim}, {"phased tools", phased}, {"error", failing}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [preparestep/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/preparestep/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/preparestep) · run it from `docs-site/examples`: ```sh go run ./preparestep go test ./preparestep ``` ```text == trim the model saw 3 of 5 messages, starting with "And order 5678?" the transcript keeps all 6 messages == phased tools step 0: tools [lookup], system "You are a support agent." step 1: tools [lookup refund], system "You are a support agent.\n\nRefund only after a lookup." step 2: tools [lookup refund], system "You are a support agent.\n\nRefund only after a lookup." step 0 result: NO_SUCH_TOOL: no tool named "refund" step 1 result: refunded == error errors.Is(err, errNoTenant): true a *RunError: true, model calls: 0 ``` ### Best practices & gotchas - **Trim deliberately: a rewrite can break a prompt-cache prefix.** `PrepareStep` and `ToolSource` are the two knobs that can change the bytes a provider caches. (Source: `weft/core/agent.go:174-175`) - **Rewrite the request, not the transcript.** What you send is not what the run keeps; the transcript, the record's messages and the next turn see every message. To add a user message mid-run, use [steering](https://weftgo.dev/docs/guides/steering/), whose messages join the transcript before the next step's chain runs. (Source: ADR 0019 "Rejected", `weft/core/steer.go:33-36`) - **Keep the tool choice consistent with the tools you return.** A `ToolChoiceNamed` for a tool your function dropped fails the run at that step. (Source: `weft/core/loop.go:554-563`) - **Do not expect the manifest to describe it.** `PrepareStep` is code, like middleware; `weft.json` does not mention it. (Source: ADR 0012, amendment 2026-09-19) - **Order several functions on purpose.** They chain in option order, each seeing the previous one's output. (Source: `TestPrepareStepChainsInOrder`) ### See also - [What happens in one step?](https://weftgo.dev/docs/concepts/the-loop/) - [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/) - [Define tools at runtime: RawTool and ToolSource](https://weftgo.dev/docs/guides/dynamic-tools/) - [Steer a running turn](https://weftgo.dev/docs/guides/steering/) - [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) Symbols used: [`weft.PrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PrepareStep) · [`Agent.Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) · [`Agent.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) · [`ModelRequest.SequentialTools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ModelRequest.SequentialTools) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.ErrDuplicateTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrDuplicateTool) · [`weft.ErrNilTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNilTool) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.PromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PromptSnippet) · [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExamplePrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-PrepareStep) --- # Steer a running turn URL: https://weftgo.dev/docs/guides/steering/ Markdown: https://weftgo.dev/docs/guides/steering.md > Deliver a user message into a run that is already going with weft.Steering; the loop drains it after the tool batch or at the final step, and the message joins the transcript. [`weft.Steering`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Steering) installs a steering source on one run: a function the loop calls at two fixed points to collect user messages typed while the run works. A delivered message joins the transcript as an ordinary `user` message, so the next model call, the run's result and the next turn all see it. Use it when a user corrects or adds to a request while the agent is still running. A source that drains an inbox without blocking, from `steering/main.go`: ```go title="steering/main.go" // inbox holds what the user typed while the run was working. Its // SteerFunc drains it without blocking: the loop calls it between steps, // so a source that waited would stall the run. type inbox chan weft.Message func (in inbox) steer(_ context.Context, at weft.SteerPoint) []weft.Message { var out []weft.Message for { select { case m := <-in: out = append(out, m) default: return out // nil when nothing arrived: the run goes on unchanged } } } ``` [steering/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/steering/main.go) Pass it as a run option: ```go title="steering/main.go" run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"), weft.Steering(typed.steer)) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.StepStart: fmt.Fprintf(w, "step %d starts\n", ev.Index) case weft.ToolFinish: fmt.Fprintf(w, " seq %d: %s → %s\n", ev.Seq, ev.Name, ev.Content) case weft.StepFinish: fmt.Fprintf(w, "step %d finished: %s\n", ev.Index, ev.Reason) case weft.Steered: fmt.Fprintf(w, " seq %d: steered after step %d: %q\n", ev.Seq, ev.Step, ev.Messages[0].Text()) } } ``` [steering/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/steering/main.go) The `lookup` tool stands in for the user: while it runs, a message lands in the inbox. The loop drains it after step 0's tool batch, emits a [`weft.Steered`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Steered) event, and step 1's model call sees the correction. ### Steer a run A source is a [`weft.SteerFunc`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SteerFunc): `func(ctx context.Context, at weft.SteerPoint) []weft.Message`. It returns the messages to deliver, or nil. It must not block: the loop calls it between steps, so a source that waits on a queue stalls the run. Drain what is there and return. `Steering` is a run option only, with no agent-level form: the run it steers is the one its queue belongs to. A child run started by a [`Subagent`](https://weftgo.dev/docs/guides/subagents/) tool does not inherit it; forwarding a steer to a child is your decision, made explicitly. [`weft.SteerPoint`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SteerPoint) tells the source where the run is: | Field | Meaning | |---|---| | [`RunID`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#SteerPoint.RunID) | The run being steered | | [`Step`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#SteerPoint.Step) | The step that has finished | | [`Final`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#SteerPoint.Final) | `true` when the run would otherwise end here; a non-empty return redirects it into one more step | The loop checks a step's possible ends in a fixed order after `StepFinish` ([ADR 0019 §2](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0019-steering-hook.md)): | The step… | Drained? | What happens | |---|---|---| | left calls pending approval | no | The run ends at the [approval boundary](https://weftgo.dev/docs/guides/approvals/); a steer cannot resolve a parked call | | met a `StopWhen` condition | no | The intended end stays an end | | made tool calls (`Final: false`) | yes | Every call of the batch already has its result, so the call/result pairing cannot be split | | made no tool calls (`Final: true`) | yes | A delivery redirects the run into one more step instead of ending it | When the drain is skipped, the source keeps its messages. Delivering them later, as a follow-up turn, is the caller's decision. A `max_tokens` step with tool calls is not final: its calls all get error results and the loop continues, so it is an ordinary drain point (`TestSteeringMaxTokensStepIsADrainPoint`). Delivered messages are appended to the transcript before the next step's [`PrepareStep`](https://weftgo.dev/docs/guides/prepare-step/) chain runs, so request rewrites see them. The `Steered` event carries `Seq`, `Step` and a copy of the messages, and sits between that step's `StepFinish` and the next `StepStart`, numbered from the run's `Seq` counter like a tool event. `Nested` wraps a child run's `Steered` like any other child event. On the wire its type is `steered`, and recorded runs store it as the `steered` record. A message with any role other than `user` fails the run with [`weft.ErrInvalidSteer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidSteer): the model's own turns come from the model. Nothing from that drain is appended; earlier steers stay on the partial transcript of the [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError). The complete example prints the error text. The package example [`ExampleSteering`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Steering) steers after a tool batch with a scripted source. ### Redirect a run that would end At a final point the model answered without calling a tool. A source that returns a message there gives the run one more step: ```go title="steering/main.go" sent := false followUp := func(_ context.Context, at weft.SteerPoint) []weft.Message { if at.Final && !sent { // the run would end here sent = true return []weft.Message{weft.User("And order 5678?")} } return nil } res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), weft.Steering(followUp)) ``` [steering/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/steering/main.go) The run takes two steps and `res.Text()` is the second answer. A redirect consumes a step and passes the same continuation checks as any continuation: `MaxSteps`, `UsageLimit` and `DetectLoops`. When a check fails, the run fails with its usual error, and the steer is on `RunError.Result.Messages`, delivered but unanswered. The complete example redirects a run built with `weft.MaxSteps(1)`; it fails with [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps) and the steer is the last message. ### Steer deterministically in tests [`wefttest.NewSteers`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#NewSteers) returns a [`*wefttest.Steers`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Steers), a source keyed by step rather than by time or channel state. [`At(step, msgs...)`](https://pkg.go.dev/github.com/weftgo/weft/core/wefttest@v0.20.2#Steers.At) registers the messages delivered at that step's drain point and returns the source, so calls chain; registering no messages clears the step. [`Option()`](https://pkg.go.dev/github.com/weftgo/weft/core/wefttest@v0.20.2#Steers.Option) is the run option, `weft.Steering` over [`Steer`](https://pkg.go.dev/github.com/weftgo/weft/core/wefttest@v0.20.2#Steers.Steer). In `steering/main_test.go`: ```go title="steering/main_test.go" // TestSteerRedirectsFinalStep steers a scripted run at step 0's drain // point. NewSteers is keyed by step, so the schedule is the same on every // run and under wefttest.Replay. func TestSteerRedirectsFinalStep(t *testing.T) { model := wefttest.Script( wefttest.Say("Order 1234 shipped yesterday."), wefttest.Say("Order 5678 is still pending."), ) agt := weft.New(model) src := wefttest.NewSteers().At(0, weft.User("And order 5678?")) res, err := agt.Generate(context.Background(), weft.Prompt("Where is order 1234?"), src.Option()) if err != nil { t.Fatal(err) } if res.NumSteps() != 2 { t.Fatalf("steps = %d, want 2: the steer redirects the final step", res.NumSteps()) } if got := model.LastRequest().LastText(); got != "And order 5678?" { t.Fatalf("step 1 was asked %q, want the steered message", got) } } ``` [steering/main_test.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/steering/main_test.go) The schedule the test ran is the schedule the file shows. Under [`wefttest.Replay`](https://weftgo.dev/docs/testing/record-replay/) a delivered steer is part of the next request's transcript, so a steer that differs from the recording misses its fixture loudly instead of drifting. ### Complete example `steering/main.go` runs five cases against scripted models: ```go title="steering/main.go" // Command steering runs the examples of the guide "Steer a running turn": // go run ./steering. Every model is scripted with wefttest, so it runs // offline; swap in a provider adapter for a real one. package main import ( "context" "errors" "fmt" "io" "os" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // inbox holds what the user typed while the run was working. Its // SteerFunc drains it without blocking: the loop calls it between steps, // so a source that waited would stall the run. type inbox chan weft.Message func (in inbox) steer(_ context.Context, at weft.SteerPoint) []weft.Message { var out []weft.Message for { select { case m := <-in: out = append(out, m) default: return out // nil when nothing arrived: the run goes on unchanged } } } // steerAfterTools delivers a message the user typed while a tool ran. func steerAfterTools(ctx context.Context, w io.Writer) error { typed := make(inbox, 8) lookup := weft.Tool("lookup", "Look up an order.", func(_ context.Context, _ struct{}) (string, error) { typed <- weft.User("Sorry, I meant order 5678.") // the user types while the tool runs return "order 1234 shipped yesterday", nil }) model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup"}), wefttest.Say("Order 5678 is still pending."), ) agt := weft.New(model, lookup) run := agt.Stream(ctx, weft.Prompt("Where is order 1234?"), weft.Steering(typed.steer)) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.StepStart: fmt.Fprintf(w, "step %d starts\n", ev.Index) case weft.ToolFinish: fmt.Fprintf(w, " seq %d: %s → %s\n", ev.Seq, ev.Name, ev.Content) case weft.StepFinish: fmt.Fprintf(w, "step %d finished: %s\n", ev.Index, ev.Reason) case weft.Steered: fmt.Fprintf(w, " seq %d: steered after step %d: %q\n", ev.Seq, ev.Step, ev.Messages[0].Text()) } } res, err := run.Wait() if err != nil { return err } for _, m := range res.Messages { fmt.Fprintf(w, "%-9s %s\n", m.Role, describe(m)) } return nil } // describe renders one transcript message on a line. func describe(m weft.Message) string { if t := m.Text(); t != "" { return t } for _, p := range m.Content { switch p := p.(type) { case weft.ToolCallPart: return "calls " + p.Name case weft.ToolResultPart: return "result: " + p.Content } } return "" } // redirect steers at the final point: the run would end, the steer gives // it one more step. func redirect(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.Say("Order 1234 shipped yesterday."), wefttest.Say("Order 5678 is still pending."), ) agt := weft.New(model) sent := false followUp := func(_ context.Context, at weft.SteerPoint) []weft.Message { if at.Final && !sent { // the run would end here sent = true return []weft.Message{weft.User("And order 5678?")} } return nil } res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), weft.Steering(followUp)) if err != nil { return err } fmt.Fprintf(w, "%d steps, answer: %s\n", res.NumSteps(), res.Text()) return nil } // stopWhen shows a drain point that never comes: an intended end stays an // end, and the source keeps its message. func stopWhen(ctx context.Context, w io.Writer) error { submit := weft.Tool("submit", "Submit the answer.", func(_ context.Context, _ struct{}) (string, error) { return "submitted", nil }) model := wefttest.Script(wefttest.ToolCalls(wefttest.Call{Name: "submit"})) agt := weft.New(model, submit, weft.StopWhen(weft.HasToolCall("submit"))) typed := make(inbox, 1) typed <- weft.User("One more thing…") if _, err := agt.Generate(ctx, weft.Prompt("Answer and submit."), weft.Steering(typed.steer)); err != nil { return err } fmt.Fprintf(w, "messages left in the inbox: %d\n", len(typed)) return nil } // invalid delivers an assistant message, which fails the run. func invalid(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("Hello.")) agt := weft.New(model) fake := func(context.Context, weft.SteerPoint) []weft.Message { return []weft.Message{weft.Assistant("I already answered.")} } _, err := agt.Generate(ctx, weft.Prompt("Hi."), weft.Steering(fake)) fmt.Fprintf(w, "errors.Is(err, weft.ErrInvalidSteer): %t\n", errors.Is(err, weft.ErrInvalidSteer)) fmt.Fprintln(w, err) return nil } // budget redirects on the last allowed step: the steer is delivered but // unanswered, on the partial transcript of the run error. func budget(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("Order 1234 shipped yesterday.")) agt := weft.New(model, weft.MaxSteps(1)) src := wefttest.NewSteers().At(0, weft.User("And order 5678?")) _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), src.Option()) var runErr *weft.RunError if !errors.As(err, &runErr) { return fmt.Errorf("want a *RunError, got %v", err) } msgs := runErr.Result.Messages last := msgs[len(msgs)-1] fmt.Fprintf(w, "errors.Is(err, weft.ErrMaxSteps): %t\n", errors.Is(err, weft.ErrMaxSteps)) fmt.Fprintf(w, "last message: %s %q\n", last.Role, last.Text()) return nil } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"steer after the tool batch", steerAfterTools}, {"redirect a final step", redirect}, {"StopWhen is not a drain point", stopWhen}, {"non-user role", invalid}, {"redirect past MaxSteps", budget}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [steering/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/steering/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/steering) · run it from `docs-site/examples`: ```sh go run ./steering go test ./steering ``` ```text == steer after the tool batch step 0 starts seq 2: lookup → order 1234 shipped yesterday step 0 finished: tool_calls seq 3: steered after step 0: "Sorry, I meant order 5678." step 1 starts step 1 finished: stop user Where is order 1234? assistant calls lookup tool result: order 1234 shipped yesterday user Sorry, I meant order 5678. assistant Order 5678 is still pending. == redirect a final step 2 steps, answer: Order 5678 is still pending. == StopWhen is not a drain point messages left in the inbox: 1 == non-user role errors.Is(err, weft.ErrInvalidSteer): true weft: run failed at step 0: weft: steering delivered a message with a role other than user: role "assistant" at step 0 == redirect past MaxSteps errors.Is(err, weft.ErrMaxSteps): true last message: user "And order 5678?" ``` ### Best practices & gotchas - **Never block in the source.** It runs on the loop's goroutine between steps; drain a queue, do not wait on one. (Source: `weft/core/steer.go:5-7`) - **Treat a panic in the source as a crash.** It fails the run like a panic in a `PrepareStep` function: the run's span ends and the loop re-panics. Under `Generate` the panic reaches your caller; under `Stream` it panics the run's own goroutine, which crashes the program. (Source: `weft/core/steer.go:8-10`, `weft/core/run.go:784`, `TestSteeringPanicReachesCaller`) - **Do not reuse delivered messages.** Ownership passes to the run, as with `weft.Messages`; build fresh values for each delivery. (Source: `weft/core/steer.go:12-15`) - **Forward steers to subagents yourself.** `Steering` is a run option only, and a child run started by a `Subagent` tool does not inherit it. (Source: ADR 0019 §7, `TestSteeringChildRunsDoNotInherit`) - **Steer through the message, not through `PrepareStep`.** A message added in `PrepareStep` reaches the model but not `RunResult.Messages`, the record or the next turn. (Source: ADR 0019 "Rejected") - **Use sessions for queue policy.** The core only drains; who may steer, queued follow-ups and receipts belong to `weft/thread` (`thread.BusyPolicy`, `s.Steer`). (Source: ADR 0019 Context, `weft/thread/doc.go:96`) ### See also - [What happens when you send while a turn runs?](https://weftgo.dev/docs/sessions/busy-and-steering/) - [What happens in one step?](https://weftgo.dev/docs/concepts/the-loop/) - [Stream a run's events](https://weftgo.dev/docs/guides/streaming/) - [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/) - [Record a real conversation once, replay it forever](https://weftgo.dev/docs/testing/record-replay/) Symbols used: [`weft.Steering`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Steering) · [`weft.SteerFunc`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SteerFunc) · [`weft.SteerPoint`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SteerPoint) · [`weft.Steered`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Steered) · [`weft.ErrInvalidSteer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidSteer) · [`weft.ErrMaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrMaxSteps) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) · [`weft.HasToolCall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#HasToolCall) · [`weft.User`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#User) · [`Agent.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) · [`wefttest.NewSteers`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#NewSteers) · [`wefttest.Steers`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Steers) · [`Steers.At`](https://pkg.go.dev/github.com/weftgo/weft/core/wefttest@v0.20.2#Steers.At) · [`Steers.Option`](https://pkg.go.dev/github.com/weftgo/weft/core/wefttest@v0.20.2#Steers.Option) · [`Steers.Steer`](https://pkg.go.dev/github.com/weftgo/weft/core/wefttest@v0.20.2#Steers.Steer) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExampleSteering`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Steering) --- # Change an agent's configuration for one run URL: https://weftgo.dev/docs/guides/run-options/ Markdown: https://weftgo.dev/docs/guides/run-options.md > Pass Instructions, MaxSteps, Parallelism, OnlyTools, UseModel, Params or ToolChoice to Generate to change one run of an immutable agent, without building a second one. An agent is an immutable value, so to change one run you pass the change to `Generate` or `Stream` as a run option. [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions), [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps), [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism), [`weft.Params`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Params) and [`weft.ToolChoice`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoice) work on `weft.New` and on a run; [`weft.OnlyTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnlyTools) and [`weft.UseModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UseModel) work on a run only. The agent's own values are unchanged for every other run. One run with its own prompt and a smaller budget, in `runoptions/main.go`: ```go title="runoptions/main.go" agt := weft.New(model, weft.Instructions("You are a support agent."), // every run's default weft.MaxSteps(10), weft.Parallelism(4), ) // One run, its own prompt and a smaller budget; the agent is unchanged. _, err := agt.Generate(ctx, weft.Instructions("Answer in one word."), weft.MaxSteps(3), weft.Parallelism(1), weft.Prompt("Where is order 1234?"), ) if err != nil { return err } fmt.Fprintf(w, "system sent: %q\n", model.LastRequest().System) // A raise is refused before any model call. _, err = agt.Generate(ctx, weft.MaxSteps(20), weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, "invalid run option:", errors.Is(err, weft.ErrInvalidRunOption)) fmt.Fprintln(w, err) ``` [runoptions/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/runoptions/main.go) The second `Generate` asks for 20 steps on an agent built with 10, and fails before any model call. ### How it works Each option sets a value on the run's configuration; the loop resolves the run's effective values once, before step 0, and reads those instead of the agent's fields. A value given to the run replaces the agent's; a value not given keeps it. Nothing is merged and nothing is written back to the agent, so concurrent runs of one agent can each carry different options. | Option | On `New` | On a run | Rule per run | |---|---|---|---| | `Instructions(text)` | default system prompt | replaces it | any text | | `MaxSteps(n)` | budget, default 10 | lowers it | a raise is `ErrInvalidRunOption` | | `Parallelism(n)` | width, default 4 | lowers it | a raise is `ErrInvalidRunOption` | | `OnlyTools(names...)` | — | narrows the tools | an unknown name is `ErrInvalidRunOption` | | `UseModel(m)` | — | replaces the model | a nil model is ignored | | `Params(p)` | default sampling | replaces the struct whole | a negative `MaxTokens` fails the run | | `ToolChoice(cfg)` | default choice | replaces it | an unsatisfiable choice fails the run | | `Thinking(cfg)` | default level | replaces it | see [Control reasoning](https://weftgo.dev/docs/guides/thinking/) | `ParkOn` and `ParkAllExcept` are run options too; they park calls at the approval boundary and are covered in [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/). The agent's [`Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Manifest), [`Agent.Tools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Tools) and [`Agent.Model`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Model) keep describing the agent as built: they describe the code, not one run. ### Change instructions and budgets for one run `Instructions`, `MaxSteps` and `Parallelism` return [`weft.InstructionsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InstructionsOption), [`weft.MaxStepsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxStepsOption) and [`weft.ParallelismOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParallelismOption). Each of these interfaces is both an `Option` and a `RunOption`, so one constructor works in both places. This is the shape `weft.Thinking` already had. A run may replace the instructions with any text. The two limits may only go down: per run they are safety knobs, and a raise would be the budget escaping. A raise fails with `ErrInvalidRunOption` at step 0, before any model call and before any resumed call runs. Values below 1 are ignored, as on `New`. ### Narrow the tools `OnlyTools` keeps the named tools among the agent's registered ones and drops the rest for this run. The step advertises and dispatches against the same narrowed list, so what the model was shown is exactly what runs: ```go title="runoptions/main.go" _, err := agt.Generate(ctx, weft.OnlyTools("lookup"), weft.Prompt("Where is order 1234?")) if err != nil { return err } fmt.Fprintln(w, "advertised:", model.LastRequest().ToolNames()) _, err = agt.Generate(ctx, weft.OnlyTools("cancel"), weft.Prompt("Cancel order 1234.")) fmt.Fprintln(w, err) res, err := agt.Generate(ctx, weft.UseModel(alt), weft.Prompt("Where is order 1234?")) if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text()) ``` [runoptions/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/runoptions/main.go) `OnlyTools` narrows; it cannot add, because a new tool is code. A name the agent does not have fails the run before any model call, as the second `Generate` shows. With a `ToolSource`, the names are checked against the step-0 snapshot and the narrowing applies to each step's fresh snapshot; a narrowed tool the source later drops fails as unknown when called. Several `OnlyTools` options add up: the run keeps every tool any of them names. An `Output[T]` agent's `submit_output` is narrowed like any tool, so name it too: `OnlyTools("lookup")` alone drops it, the model's submission reads `NO_SUCH_TOOL: no tool named "submit_output"`, and `GenerateAs` returns `ErrNoOutput` ([structured output](https://weftgo.dev/docs/guides/structured-output/#best-practices--gotchas)). The package example is [`ExampleOnlyTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-OnlyTools). ### Swap the model `UseModel(m)` replaces the agent's model for this run and rebuilds the `WrapModel` chain over it, first registered outermost, as `New` does. The run's model calls go through the same middleware, over `m`. `RunStart.Model` and the chat spans name the run's model, because middleware forwards `Info`; `Agent.Model` and the manifest keep naming the agent's own. In the example above, the third run answers from `alt`. A nil model is ignored. ### Set sampling parameters `Params` sets the sampling knobs of a [`weft.RequestParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequestParams): [`Temperature`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RequestParams.Temperature), [`TopP`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RequestParams.TopP), [`MaxTokens`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RequestParams.MaxTokens), [`Stop`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RequestParams.Stop) and [`Seed`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RequestParams.Seed). It returns a [`weft.ParamsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParamsOption), accepted by `New` and by a run: ```go title="runoptions/main.go" agt := weft.New(model, weft.Params(weft.RequestParams{ Temperature: ptr(0.2), MaxTokens: ptr(512), })) if _, err := agt.Generate(ctx, weft.Prompt("Classify this ticket.")); err != nil { return err } // The run's Params replaces the agent's struct: MaxTokens is not kept. creative := weft.Params(weft.RequestParams{Temperature: ptr(0.9), Seed: ptr(int64(7))}) if _, err := agt.Generate(ctx, creative, weft.Prompt("Draft a reply.")); err != nil { return err } for i, req := range model.Requests() { fmt.Fprintf(w, "run %d: %s\n", i+1, describe(req.Params)) } _, err := agt.Generate(ctx, weft.Params(weft.RequestParams{MaxTokens: ptr(-1)}), weft.Prompt("x")) fmt.Fprintln(w, err) ``` [runoptions/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/runoptions/main.go) `TopP` is a `*float64` like `Temperature`: nil keeps the adapter's `TopP` option, a set value overrides it for one call. `Stop` is a `[]string` of stop sequences: an empty slice keeps the adapter's `Stop` option. Every field is a pointer or a slice, so three states stay apart. Nil or empty keeps the adapter's construction default (its own `Temperature` option, and so on). A set value overrides it for this request. A set pointer to 0 is a value: a temperature of exactly 0 is sent. `MaxTokens` is the exception on two adapters. On anthropic a `MaxTokens` of 0 falls to the adapter's construction value, else its default, because the API requires a positive value. On google a 0 keeps the construction value, and with none set the field is left out, so Gemini's own default applies. Only openai sends a `MaxTokens` of 0 as a value. A run's `Params` replaces the agent's struct whole; it does not merge field by field. In the output, run 2 loses the agent's `max_tokens=512` because its struct does not set it. Start from [`agt.Params()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Params), a copy, when an override should keep the other knobs. A negative `MaxTokens` fails the run at the step that carries it, with the text shown in the output. Adapters drop knobs their provider lacks: anthropic has no seed. google sends `MaxTokens` and `Seed` as int32 and fails with `ErrUnsupported` past that ceiling. For a vendor knob weft has no field for, every adapter has `ExtraBody` and `ExtraHeaders` ([Connect a model provider](https://weftgo.dev/docs/guides/providers/)). To change sampling per step, edit `req.Params` in a [`PrepareStep`](https://weftgo.dev/docs/guides/prepare-step/) function; the package example [`ExampleParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Params) runs the classifying step cold and the drafting step at 0.9. ### Force or forbid tool calls `ToolChoice` takes a [`weft.ToolChoiceConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceConfig) with a [`Mode`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolChoiceConfig.Mode) and a [`Name`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolChoiceConfig.Name), and returns a [`weft.ToolChoiceOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceOption). The [`weft.ToolChoiceMode`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceMode) values: | Mode | Value | Effect | openai | anthropic | google | |---|---|---|---|---|---| | [`ToolChoiceAuto`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceAuto) | `""` | provider default; nothing is sent | — | — | — | | [`ToolChoiceAny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceAny) | `"any"` | the provider is asked to call some tool | `required` | `any` | `ANY` | | [`ToolChoiceNamed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceNamed) | `"tool"` | the provider is asked to call the tool `Name` | named function | `tool` | `ANY` + `allowedFunctionNames` | | [`ToolChoiceNone`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceNone) | `"none"` | the provider is asked for no call; the catalogue stays advertised | `none` | `none` | `NONE` | The adapter columns are what each one sends; the shared conformance case `tool_choice_forcing` checks the request bytes carry the provider's field ([Run the adapter conformance suite](https://weftgo.dev/docs/testing/conformance/)). Every mode is a request to the provider, not a rule the loop enforces. The loop validates the choice, but it never filters the calls that come back: a call the model emits anyway runs, under `ToolChoiceNone` too, because the model was shown the tool. The first-party adapters send the field; an OpenAI-compatible server that ignores `tool_choice` may not. [Enforce a choice](https://weftgo.dev/docs/guides/run-options/#enforce-a-choice) shows how to make sure a call does not run. ```go title="runoptions/main.go" agt := weft.New(model, lookupTool(), refundTool()) // Every step of this run must call lookup. named := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNamed, Name: "lookup"}) if _, err := agt.Generate(ctx, named, weft.Prompt("Where is order 1234?")); err != nil { return err } // None forbids calls and keeps the catalogue advertised. none := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNone}) if _, err := agt.Generate(ctx, none, weft.Prompt("Summarise our refund policy.")); err != nil { return err } last := model.LastRequest() fmt.Fprintf(w, "mode=%s tools=%v\n", last.ToolChoice.Mode, last.ToolNames()) // A choice the step's tools cannot satisfy fails the run. bad := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNamed, Name: "cancel"}) _, err := agt.Generate(ctx, bad, weft.Prompt("Cancel order 1234.")) fmt.Fprintln(w, err) ``` [runoptions/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/runoptions/main.go) A run-level choice applies to every step of the run: in the output, requests 1 and 2 of the first run both carry `mode="tool"`. A scripted model ignores it; a real one forced to call `lookup` on every step keeps calling it until the step budget ends the run. To force only the first step, set `req.ToolChoice` on step 0 in a `PrepareStep` function, as the package example [`ExampleToolChoice`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolChoice) does with a `classify` router. `ToolChoiceNone` exists for prompt caching. Removing tools from the request to stop calls changes the cached prefix; `none` keeps the tool definitions in the request and asks the provider not to call them. The loop checks the choice at each step, after `PrepareStep`, against the tools that step advertises. `Name` is required under `ToolChoiceNamed` and must be empty under every other mode. A named tool the step does not advertise, any forced mode with no tools, or an unknown mode fails the run with a descriptive error. Those failures are programming errors, reported in the text, with no sentinel. #### Enforce a choice Where a call must not run, whatever the provider does, pair the choice with a rule the loop applies to the calls that come back. `OnlyTools` and `ParkOn` are run options; `mw.Allow` is tool middleware, given to `weft.New`: | Add | What happens to a call it rules out | Catalogue | |---|---|---| | [`weft.OnlyTools(names...)`](https://weftgo.dev/docs/guides/run-options/#narrow-the-tools) | The tools not named are dropped for the run; a call to one reads `NO_SUCH_TOOL: no tool named "refund"` | Narrowed, so the cached prefix changes | | [`weft.WrapTools(mw.Allow(permit))`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Allow) | A call `permit` rejects never runs; the model sees `DENIED: tool "refund" is not allowed` | Kept | | [`weft.ParkOn(names...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkOn) | The call parks at the [approval boundary](https://weftgo.dev/docs/guides/approvals/) on `res.Pending`, for `Approve` or `Deny` | Kept | Each one rules calls out. Nothing makes a model call a tool it chose not to call: under `ToolChoiceAny` or `ToolChoiceNamed`, a reply with no call still ends the step as a plain answer. ### Read the override fingerprint A run that a run option changed carries the change on its `invoke_agent` span. `weft.override.hash` is a sha256 over the canonical JSON of every changed value, and one `weft.override.*` attribute names each knob: `instructions` (`true`; the text itself is content and never on a span), `tools`, `model`, `thinking`, `tool_choice`, `params`, `max_steps`, `parallelism`, `park_on` and `park_all_except`. A plain run carries none of them. "Changed" means a run option was applied, even when its value equals the agent's: the fingerprint records what the run carried, not a diff. Tool names in `tools`, `park_on` and `park_all_except` are a sorted, de-duplicated set, so equal experiments hash equal whatever order the names came in. `TestOverrideFingerprint` in the example package pins three of these rules against a recording tracer: no attribute on a plain run, the order-independent tool set, and the `instructions` flag with its own hash; the rest are in `core/run.go:878-978`. The hash is an experiment's fingerprint: two sibling runs with equal changes carry equal hashes, which is how a reader groups them ([Run experiments in the playground](https://weftgo.dev/docs/observe/playground/experiments/)). ### Handle a refused run option [`weft.ErrInvalidRunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidRunOption) marks a per-run configuration the agent refuses: an unknown name in `OnlyTools`, or a `MaxSteps` or `Parallelism` raise. It comes wrapped in a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) before any model call, so a run that would misconfigure itself does not start. Branch on it with `errors.Is(err, weft.ErrInvalidRunOption)`. The `Params` and `ToolChoice` failures are not this sentinel. They are checked per step, because `PrepareStep` can change both, and an agent default, a run option and a `PrepareStep` edit fail alike. ### Complete example `runoptions/main.go` runs each region against scripted models: ```go title="runoptions/main.go" // Command runoptions runs the examples of the guide "Change an agent's // configuration for one run": go run ./runoptions. Every model is // scripted with wefttest, so it runs offline. package main import ( "context" "errors" "fmt" "io" "os" "strings" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) func ptr[T any](v T) *T { return &v } type lookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } func lookupTool() *weft.ToolDef { return weft.Tool("lookup", "Look up an order.", func(_ context.Context, in lookupInput) (string, error) { return "order " + in.OrderID + " has shipped", nil }) } func refundTool() *weft.ToolDef { return weft.Tool("refund", "Refund an order.", func(_ context.Context, in lookupInput) (string, error) { return "refunded " + in.OrderID, nil }) } // dual: Instructions, MaxSteps and Parallelism per run. func dual(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("Shipped.")) agt := weft.New(model, weft.Instructions("You are a support agent."), // every run's default weft.MaxSteps(10), weft.Parallelism(4), ) // One run, its own prompt and a smaller budget; the agent is unchanged. _, err := agt.Generate(ctx, weft.Instructions("Answer in one word."), weft.MaxSteps(3), weft.Parallelism(1), weft.Prompt("Where is order 1234?"), ) if err != nil { return err } fmt.Fprintf(w, "system sent: %q\n", model.LastRequest().System) // A raise is refused before any model call. _, err = agt.Generate(ctx, weft.MaxSteps(20), weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, "invalid run option:", errors.Is(err, weft.ErrInvalidRunOption)) fmt.Fprintln(w, err) fmt.Fprintln(w, "model calls:", len(model.Requests())) return nil } // onlyTools narrows the catalogue and swaps the model for one run. func onlyTools(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("from the agent's model")) alt := wefttest.Script(wefttest.Say("from the alternate model")) agt := weft.New(model, lookupTool(), refundTool()) _, err := agt.Generate(ctx, weft.OnlyTools("lookup"), weft.Prompt("Where is order 1234?")) if err != nil { return err } fmt.Fprintln(w, "advertised:", model.LastRequest().ToolNames()) _, err = agt.Generate(ctx, weft.OnlyTools("cancel"), weft.Prompt("Cancel order 1234.")) fmt.Fprintln(w, err) res, err := agt.Generate(ctx, weft.UseModel(alt), weft.Prompt("Where is order 1234?")) if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text()) fmt.Fprintln(w, "agent's tools:", len(agt.Tools())) return nil } // params sets sampling for the agent, overrides it for a run, and shows // that the run's struct replaces the agent's whole. func params(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("a"), wefttest.Say("b"), wefttest.Say("c")) agt := weft.New(model, weft.Params(weft.RequestParams{ Temperature: ptr(0.2), MaxTokens: ptr(512), })) if _, err := agt.Generate(ctx, weft.Prompt("Classify this ticket.")); err != nil { return err } // The run's Params replaces the agent's struct: MaxTokens is not kept. creative := weft.Params(weft.RequestParams{Temperature: ptr(0.9), Seed: ptr(int64(7))}) if _, err := agt.Generate(ctx, creative, weft.Prompt("Draft a reply.")); err != nil { return err } for i, req := range model.Requests() { fmt.Fprintf(w, "run %d: %s\n", i+1, describe(req.Params)) } _, err := agt.Generate(ctx, weft.Params(weft.RequestParams{MaxTokens: ptr(-1)}), weft.Prompt("x")) fmt.Fprintln(w, err) return nil } // describe prints the set knobs of a RequestParams. func describe(rp weft.RequestParams) string { var parts []string if rp.Temperature != nil { parts = append(parts, fmt.Sprintf("temperature=%g", *rp.Temperature)) } if rp.TopP != nil { parts = append(parts, fmt.Sprintf("top_p=%g", *rp.TopP)) } if rp.MaxTokens != nil { parts = append(parts, fmt.Sprintf("max_tokens=%d", *rp.MaxTokens)) } if len(rp.Stop) > 0 { parts = append(parts, fmt.Sprintf("stop=%q", rp.Stop)) } if rp.Seed != nil { parts = append(parts, fmt.Sprintf("seed=%d", *rp.Seed)) } return strings.Join(parts, " ") } // toolChoice forces, names and forbids tool calls. func toolChoice(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), wefttest.Say("I can answer without tools."), ) agt := weft.New(model, lookupTool(), refundTool()) // Every step of this run must call lookup. named := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNamed, Name: "lookup"}) if _, err := agt.Generate(ctx, named, weft.Prompt("Where is order 1234?")); err != nil { return err } // None forbids calls and keeps the catalogue advertised. none := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNone}) if _, err := agt.Generate(ctx, none, weft.Prompt("Summarise our refund policy.")); err != nil { return err } last := model.LastRequest() fmt.Fprintf(w, "mode=%s tools=%v\n", last.ToolChoice.Mode, last.ToolNames()) // A choice the step's tools cannot satisfy fails the run. bad := weft.ToolChoice(weft.ToolChoiceConfig{Mode: weft.ToolChoiceNamed, Name: "cancel"}) _, err := agt.Generate(ctx, bad, weft.Prompt("Cancel order 1234.")) fmt.Fprintln(w, err) for i, req := range model.Requests() { fmt.Fprintf(w, "request %d: mode=%q name=%q\n", i+1, req.ToolChoice.Mode, req.ToolChoice.Name) } return nil } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"dual options", dual}, {"only tools and use model", onlyTools}, {"params", params}, {"tool choice", toolChoice}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [runoptions/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/runoptions/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/runoptions) · run it from `docs-site/examples`: ```sh go run ./runoptions go test ./runoptions ``` ```text == dual options system sent: "Answer in one word." invalid run option: true weft: run failed at step 0: weft: invalid run option: max_steps 20 raises the agent's 10; per run it may only lower model calls: 1 == only tools and use model advertised: [lookup] weft: run failed at step 0: weft: invalid run option: tool "cancel" is not registered on this agent; OnlyTools narrows, it cannot add answer: from the alternate model agent's tools: 2 == params run 1: temperature=0.2 max_tokens=512 run 2: temperature=0.9 seed=7 weft: run failed at step 0: params: MaxTokens -1 is negative; a token budget cannot be == tool choice mode=none tools=[lookup refund] weft: run failed at step 0: tool_choice names "cancel" but the step advertises no such tool request 1: mode="tool" name="lookup" request 2: mode="tool" name="lookup" request 3: mode="none" name="" ``` ### Best practices & gotchas - **Set every knob a `Params` override should carry.** A run's struct replaces the agent's whole; start from `agt.Params()` to keep the rest. (Source: `weft/core/run.go:611-620`, `weft/core/agent.go:970-984`) - **`RequestParams` has no TopK.** Its knobs are `Temperature`, `TopP`, `MaxTokens`, `Stop` and `Seed`; weft leaves TopK out because Chat Completions has none. Send it at construction with the adapter's `ExtraBody`, under the provider's own name (`top_k` on the Anthropic Messages API, `topK` inside `generationConfig` for Gemini); it then applies to every call, not per run. (Source: `weft/core/model.go:141-147`, `weft/anthropic/doc.go:25-32`, ADR 0013 `docs/adr/0013-adapter-contract.md:426`) - **Do not use a run option to raise a budget.** `MaxSteps` and `Parallelism` only lower per run; build an agent with the larger value instead. (Source: `weft/core/loop.go:356-366`, ADR 0024 D5) - **Force one step with `PrepareStep`, not a run-level `ToolChoice`.** A run-level choice forces every step. (Source: `weft/core/agent.go:357-365`, `ExampleToolChoice`) - **Prefer `ToolChoiceNone` to removing tools on a final step.** It keeps the cached prompt prefix. (Source: `weft/core/model.go:106-112`) - **Do not rely on `ToolChoice` alone to stop a call.** A call the provider emits anyway runs, whatever the mode, and a compatible server that ignores `tool_choice` emits them. Where a call must not run, add `OnlyTools`, `mw.Allow` or `ParkOn` ([Enforce a choice](https://weftgo.dev/docs/guides/run-options/#enforce-a-choice)). (Source: `weft/core/model.go:185-192`; scratch proof in `sources`) - **Expect `RunStart.Model` to name the `UseModel` model.** `Agent.Model` and the manifest still name the agent's. (Source: `weft/core/run.go:289-296`) ### See also - [What is an agent in weft?](https://weftgo.dev/docs/concepts/agents/) - [Rewrite the request each step (PrepareStep)](https://weftgo.dev/docs/guides/prepare-step/) - [Control reasoning (thinking)](https://weftgo.dev/docs/guides/thinking/) - [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/): `ParkOn`, `ParkAllExcept` - [Run experiments in the playground](https://weftgo.dev/docs/observe/playground/experiments/) Symbols used: [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.InstructionsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InstructionsOption) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.MaxStepsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxStepsOption) · [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) · [`weft.ParallelismOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParallelismOption) · [`weft.OnlyTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnlyTools) · [`weft.UseModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UseModel) · [`weft.Params`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Params) · [`weft.ParamsOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParamsOption) · [`weft.RequestParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequestParams) · [`weft.ToolChoice`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoice) · [`weft.ToolChoiceOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceOption) · [`weft.ToolChoiceConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceConfig) · [`weft.ToolChoiceMode`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceMode) · [`weft.ParkOn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkOn) · [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) · [`mw.Allow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Allow) · [`weft.ErrInvalidRunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidRunOption) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`Agent.Params`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Params) · [`Agent.Tools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Tools) · [`Agent.Model`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Model) · [`weft.Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Manifest) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExampleOnlyTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-OnlyTools) · [`ExampleParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Params) · [`ExampleToolChoice`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolChoice) --- # Set per-tool policy: timeouts, caps, ordering and strict input URL: https://weftgo.dev/docs/guides/tool-policy/ Markdown: https://weftgo.dev/docs/guides/tool-policy.md > Give one tool its own deadline, result cap, sequential barrier, strict argument check, prompt snippet or middleware with trailing options on weft.Tool. Trailing options on [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) set policy for that tool alone. [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout), [`weft.MaxResultBytes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxResultBytes), [`weft.StrictInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StrictInput), [`weft.Sequential`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Sequential) and [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) also work on `weft.New`, where they set the default for every tool; on a tool they override that default. Use them when one tool is slower, larger, riskier or more order-sensitive than the rest. A tool with its own deadline, and one that lifts the agent's, in `toolpolicy/main.go`: ```go title="toolpolicy/main.go" slow := weft.Tool("inventory", "Check stock levels.", func(ctx context.Context, in orderInput) (string, error) { select { case <-time.After(time.Second): // a hung backend return "in stock", nil case <-ctx.Done(): // honour ctx: the deadline cancels it return "", ctx.Err() } }, weft.Timeout(20*time.Millisecond), // this tool's own deadline ) report := weft.Tool("report", "Build the monthly report.", func(ctx context.Context, in orderInput) (string, error) { time.Sleep(30 * time.Millisecond) // longer than the agent default return "report ready", nil }, weft.Timeout(0), // lifts the agent's default for this tool alone ) agt := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "inventory", Args: `{"order_id":"1234"}`}, wefttest.Call{Name: "report", Args: `{"order_id":"1234"}`}, ), wefttest.Say("Inventory timed out; the report is ready."), ), slow, report, weft.Timeout(10*time.Millisecond)) // the default for every other tool ``` [toolpolicy/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go) The agent's `Timeout(10*time.Millisecond)` covers every tool without its own. `inventory` gets 20 ms; `report` gets none. ### How it works The loop resolves each call's policy when it dispatches it: the tool's own value when set, else the agent's. Every policy failure becomes a tool result the model reads, never a run error: a timed-out call is `IsError: true` and its siblings keep running ([rule 1](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). The result cap is applied last, over every outcome. | Option | Kind | On `New` | On a tool | |---|---|---|---| | `Timeout(d)` | `PolicyOption` | default deadline; none by default | this tool's deadline; `Timeout(0)` lifts the default | | `MaxResultBytes(n)` | `PolicyOption` | default cap, 64 KiB | this tool's cap; `MaxResultBytes(0)` removes it | | `StrictInput()` | `PolicyOption` | every tool | this tool | | `Sequential()` | `PolicyOption` | every call one at a time | a barrier: this call runs alone | | `WrapTools(mw...)` | `PolicyOption` | wraps every call | wraps this tool, inside the agent's chain | | `PromptSnippet(text)` | `ToolOption` | — | system-prompt lines for this tool | | `RequireApproval()` | `ToolOption` | — | parks the call ([approvals](https://weftgo.dev/docs/guides/approvals/)) | | `Replay(p)` | `ToolOption` | — | the side-effect class for re-runs ([replay](https://weftgo.dev/docs/observe/playground/replay/)) | | `Origin(name)` | `ToolOption` | — | the tools record's source | ### Combine per-tool options A [`weft.ToolOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOption) configures one tool at definition time. A [`weft.PolicyOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PolicyOption) is both an `Option` and a `ToolOption`: accepted by `New` and by `Tool`, the agent default on one and the override on the other. [`weft.ToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOptions) composes several into one value, applied in order, so a package of policy travels under one name: ```go title="toolpolicy/main.go" // A package of per-tool policy under one name. backend := weft.ToolOptions( weft.Timeout(5*time.Second), weft.MaxResultBytes(4096), weft.StrictInput(), ) // Middleware on one tool runs inside the agent's chain. tag := func(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { out, err := next(ctx, call) return "[cache] " + out, err } } lookup := weft.Tool("lookup", "Look up an order.", func(_ context.Context, in orderInput) (string, error) { return "order " + in.OrderID + " has shipped", nil }, backend, weft.WrapTools(tag), weft.Origin("orders-plugin"), ) ``` [toolpolicy/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go) The manifest records both levels: a tool that overrides a default carries its own `timeout`, `max_result_bytes`, `strict_input`, `sequential`, `require_approval`, `replay_policy` and `prompt_snippet` keys, and a tool without options renders without them ([Describe your agents in weft.json](https://weftgo.dev/docs/guides/manifest/)). The package example is [`ExampleToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolOptions). ### Set a timeout `Timeout(d)` on a tool is that tool's deadline. The handler's ctx carries it; when it expires the loop records an error result the model sees and moves on: ```text tool "inventory" timed out after 20ms ``` The loop abandons the handler's goroutine at the deadline, so a handler must honour ctx to release what it holds ([rule 9](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). On `New`, `Timeout(d)` is the default for every tool without its own, and non-positive values are ignored there. On a tool, `Timeout(0)` removes the agent's default for that tool alone; the manifest records it as `"timeout": "0s"`. Without any `Timeout`, only the run's ctx bounds a call. ### Cap a tool's result `MaxResultBytes(n)` caps one tool result's text at n bytes. The agent default is 64 KiB. The loop cuts on a rune boundary and appends a marker naming the bytes the model did not receive, so it knows the output is partial ([rule 8](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)): ```go title="toolpolicy/main.go" logs := weft.Tool("logs", "Read the service logs.", func(context.Context, orderInput) (string, error) { return strings.Repeat("x", 40), nil }, weft.MaxResultBytes(16), // cap this tool at 16 bytes ) invoice := weft.Tool("invoice", "Render the invoice.", func(context.Context, orderInput) (string, error) { return strings.Repeat("y", 40), nil }, weft.MaxResultBytes(0), // this tool's output always arrives whole ) agt := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "logs", Args: `{"order_id":"1234"}`}, wefttest.Call{Name: "invoice", Args: `{"order_id":"1234"}`}, ), wefttest.Say("done"), ), logs, invoice, weft.MaxResultBytes(8)) // the agent default for other tools ``` [toolpolicy/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go) ```text logs (error: false): xxxxxxxxxxxxxxxx …[truncated 24 bytes] ``` The cap applies to successes, failures and panics alike. `MaxResultBytes(0)` removes the cap: on `New` for every tool, on a tool for that tool alone, as `invoice` shows. Negative values are ignored. [`agt.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) returns uncapped output and applies no timeout: both are run policy, applied by the loop. ### Run a tool alone Under any parallelism, a step's tools start in call order. `Sequential()` on a tool is a barrier: the dispatcher lets every in-flight call of the step finish, runs this call alone, then resumes the step's parallelism for the calls after it: ```go title="toolpolicy/main.go" write := weft.Tool("write_ledger", "Append to the ledger.", func(ctx context.Context, _ orderInput) (string, error) { log("write_ledger runs") return "written", nil }, weft.Sequential(), // a barrier: in-flight calls finish, this one runs alone ) check := weft.Tool("check_ledger", "Verify the ledger.", func(ctx context.Context, _ orderInput) (string, error) { call, _ := weft.CallFromContext(ctx) log(call.CallID + " starts") time.Sleep(10 * time.Millisecond) log(call.CallID + " ends") return "verified", nil }) agt := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "check_ledger", Args: `{"order_id":"1"}`}, wefttest.Call{Name: "write_ledger", Args: `{"order_id":"1"}`}, wefttest.Call{Name: "check_ledger", Args: `{"order_id":"1"}`}, ), wefttest.Say("done"), ), write, check, weft.Parallelism(4)) ``` [toolpolicy/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go) ```text order: call_1 starts, call_1 ends, write_ledger runs, call_3 starts, call_3 ends ``` Results stay in call order either way. When the run's parallelism is 1 (`Sequential()` or `Parallelism(1)`, on `New` or per run), the loop sets `ModelRequest.SequentialTools`, so adapters that can ask the provider not to emit parallel batches do. A barrier on one tool does not set it. The package example is [`ExampleSequential`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Sequential). ### Reject undeclared arguments By default an argument field the input struct does not declare is ignored, the `encoding/json` default: models add stray keys, and a rejection costs a round trip. `StrictInput()` rejects them as an [`ErrInvalidToolInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidToolInput) result naming the field: ```go title="toolpolicy/main.go" refund := weft.Tool("refund", "Refund an order.", func(_ context.Context, in orderInput) (string, error) { return "refunded " + in.OrderID, nil }, weft.StrictInput(), // an undeclared field is an error result naming it ) agt := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "refund", Args: `{"order_id":"1234","amount":50}`}), wefttest.ToolCalls(wefttest.Call{Name: "refund", Args: `{"order_id":"1234"}`}), wefttest.Say("Refunded."), ), refund) ``` [toolpolicy/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go) ```text refund (error: true): INVALID_INPUT: tool "refund": unknown field "amount": not in the schema retry: refunded 1234 ``` The model reads the error and calls again without the field. Use it where an ignored field would be a silent misreading of the call: here, an amount the handler would drop. On `New` it applies to every tool, and a tool cannot opt out of an agent-level `StrictInput`. A [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) is unaffected: it receives the raw arguments. `StrictInput` checks only for extra fields, never for missing ones. A required field the model leaves out still decodes to its zero value, with or without it: [How do tools work?](https://weftgo.dev/docs/concepts/tools/#edge-cases-in-schemas-and-arguments) shows the pointer-and-`ModelRetry` check. ### Attach prompt lines to a tool [`weft.PromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PromptSnippet) keeps a tool's usage rules next to the tool. The loop appends the snippets of the tools it advertises to the agent's instructions for every model call, one paragraph per tool in the order the step advertises them (registration order unless a `PrepareStep` function reorders them), separated by blank lines: ```go title="toolpolicy/main.go" search := weft.Tool("search", "Search the help centre.", func(context.Context, orderInput) (string, error) { return "", nil }, weft.PromptSnippet("Cite the article you used."), ) agt := weft.New(model, weft.Instructions("You are a support agent."), search) ``` [toolpolicy/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go) ```text system sent: "You are a support agent.\n\nCite the article you used." ``` Only advertised tools contribute, so a tool a [`PrepareStep`](https://weftgo.dev/docs/guides/prepare-step/) function or `OnlyTools` removes takes its snippet with it. Empty snippets add nothing. [`ToolDef.PromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.PromptSnippet) reports a tool's text, empty when unset, and the manifest records it. The package example is [`ExamplePromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-PromptSnippet). ### Name a tool's origin [`weft.Origin`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Origin) names where a tool came from, for the observability record only: it is the `source` of the tool on the run's tools record and, since 0.20.0, for a tool that is not local, the `weft.tool.origin` attribute of each call's `execute_tool` span. It changes nothing the model sees or the loop does. A tool is `local` by default; `weft.Subagent` sets `subagent`, and `mcp.Tools` sets `mcp:` under `mcp.Server(name)`, else `mcp` ([MCP identity](https://weftgo.dev/docs/guides/mcp/#mcp-identity)). [`weft.OriginDetail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OriginDetail) records the origin in parts beside it. Any other string is recorded verbatim, and the last `Origin` wins. The example under [Combine per-tool options](https://weftgo.dev/docs/guides/tool-policy/#combine-per-tool-options) tags `lookup` as `orders-plugin`; the core example [`ExampleOrigin`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Origin) reads the record back. ### Mark a tool safe to re-run [`weft.Replay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Replay) sets a tool's side-effect class, a [`weft.ReplayPolicy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplayPolicy), for re-runs of a recorded conversation (a playground experiment, a replay fixture). [`weft.ReplayNever`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplayNever) is the zero value and the default: an unannotated tool counts as never, so a re-run substitutes its call with the recorded result or parks it, and never fires it again silently. [`weft.ReplaySafe`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplaySafe) vouches that the call is idempotent and side-effect free, a read, so a re-run may execute it. Any other value counts as never. Like every tool option the last one wins, so `Replay(ReplayNever)` after a shared `Replay(ReplaySafe)` takes the vouching back. [`ToolDef.ReplayPolicy`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.ReplayPolicy) reports the class, and the manifest writes `replay_policy` only for `safe`. How a re-run uses it is in [Replay a run from any step, with edits](https://weftgo.dev/docs/observe/playground/replay/). ### Wrap one tool with middleware `WrapTools` on a tool wraps that tool alone, inside the agent's chain: agent middleware, then tool middleware, then decode, then the handler. The first middleware listed is the outermost. In that example, `tag` prefixes `lookup`'s result: ```text lookup (error: false): [cache] order 1234 has shipped ``` Panic containment and timeouts sit outside the chain, so a panic in tool middleware is still an error result. [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) covers both seams. ### Complete example `toolpolicy/main.go` runs each region against a scripted model: ```go title="toolpolicy/main.go" // Command toolpolicy runs the examples of the guide "Set per-tool policy: // timeouts, caps, ordering and strict input": go run ./toolpolicy. Every // model is scripted with wefttest, so it runs offline. package main import ( "context" "fmt" "io" "os" "strings" "sync" "time" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) type orderInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } // results prints every tool result of a run's first step. func results(w io.Writer, res *weft.RunResult) { for _, r := range res.Steps[0].Results { fmt.Fprintf(w, "%s (error: %t): %s\n", r.Name, r.IsError, r.Content) } } // timeouts: an agent default, a tool's own deadline, and a lifted one. func timeouts(ctx context.Context, w io.Writer) error { slow := weft.Tool("inventory", "Check stock levels.", func(ctx context.Context, in orderInput) (string, error) { select { case <-time.After(time.Second): // a hung backend return "in stock", nil case <-ctx.Done(): // honour ctx: the deadline cancels it return "", ctx.Err() } }, weft.Timeout(20*time.Millisecond), // this tool's own deadline ) report := weft.Tool("report", "Build the monthly report.", func(ctx context.Context, in orderInput) (string, error) { time.Sleep(30 * time.Millisecond) // longer than the agent default return "report ready", nil }, weft.Timeout(0), // lifts the agent's default for this tool alone ) agt := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "inventory", Args: `{"order_id":"1234"}`}, wefttest.Call{Name: "report", Args: `{"order_id":"1234"}`}, ), wefttest.Say("Inventory timed out; the report is ready."), ), slow, report, weft.Timeout(10*time.Millisecond)) // the default for every other tool res, err := agt.Generate(ctx, weft.Prompt("Check order 1234.")) if err != nil { return err } results(w, res) return nil } // resultCap: one tool capped small, one uncapped. func resultCap(ctx context.Context, w io.Writer) error { logs := weft.Tool("logs", "Read the service logs.", func(context.Context, orderInput) (string, error) { return strings.Repeat("x", 40), nil }, weft.MaxResultBytes(16), // cap this tool at 16 bytes ) invoice := weft.Tool("invoice", "Render the invoice.", func(context.Context, orderInput) (string, error) { return strings.Repeat("y", 40), nil }, weft.MaxResultBytes(0), // this tool's output always arrives whole ) agt := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "logs", Args: `{"order_id":"1234"}`}, wefttest.Call{Name: "invoice", Args: `{"order_id":"1234"}`}, ), wefttest.Say("done"), ), logs, invoice, weft.MaxResultBytes(8)) // the agent default for other tools res, err := agt.Generate(ctx, weft.Prompt("Show order 1234.")) if err != nil { return err } results(w, res) return nil } // sequential: a barrier tool runs alone; results stay in call order. func sequential(ctx context.Context, w io.Writer) error { var mu sync.Mutex var order []string log := func(s string) { mu.Lock() defer mu.Unlock() order = append(order, s) } write := weft.Tool("write_ledger", "Append to the ledger.", func(ctx context.Context, _ orderInput) (string, error) { log("write_ledger runs") return "written", nil }, weft.Sequential(), // a barrier: in-flight calls finish, this one runs alone ) check := weft.Tool("check_ledger", "Verify the ledger.", func(ctx context.Context, _ orderInput) (string, error) { call, _ := weft.CallFromContext(ctx) log(call.CallID + " starts") time.Sleep(10 * time.Millisecond) log(call.CallID + " ends") return "verified", nil }) agt := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "check_ledger", Args: `{"order_id":"1"}`}, wefttest.Call{Name: "write_ledger", Args: `{"order_id":"1"}`}, wefttest.Call{Name: "check_ledger", Args: `{"order_id":"1"}`}, ), wefttest.Say("done"), ), write, check, weft.Parallelism(4)) res, err := agt.Generate(ctx, weft.Prompt("Record the payment.")) if err != nil { return err } results(w, res) fmt.Fprintln(w, "order:", strings.Join(order, ", ")) return nil } // strict: an undeclared argument field is rejected for one tool. func strict(ctx context.Context, w io.Writer) error { refund := weft.Tool("refund", "Refund an order.", func(_ context.Context, in orderInput) (string, error) { return "refunded " + in.OrderID, nil }, weft.StrictInput(), // an undeclared field is an error result naming it ) agt := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "refund", Args: `{"order_id":"1234","amount":50}`}), wefttest.ToolCalls(wefttest.Call{Name: "refund", Args: `{"order_id":"1234"}`}), wefttest.Say("Refunded."), ), refund) res, err := agt.Generate(ctx, weft.Prompt("Refund 50 on order 1234.")) if err != nil { return err } results(w, res) fmt.Fprintln(w, "retry:", res.Steps[1].Results[0].Content) return nil } // snippet: usage rules composed into the system prompt. func snippet(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("ok")) search := weft.Tool("search", "Search the help centre.", func(context.Context, orderInput) (string, error) { return "", nil }, weft.PromptSnippet("Cite the article you used."), ) agt := weft.New(model, weft.Instructions("You are a support agent."), search) if _, err := agt.Generate(ctx, weft.Prompt("How do refunds work?")); err != nil { return err } fmt.Fprintf(w, "system sent: %q\n", model.LastRequest().System) fmt.Fprintf(w, "snippet: %q\n", agt.Tools()[0].PromptSnippet()) return nil } // composed: a named policy and a tool's own middleware. func composed(ctx context.Context, w io.Writer) error { // A package of per-tool policy under one name. backend := weft.ToolOptions( weft.Timeout(5*time.Second), weft.MaxResultBytes(4096), weft.StrictInput(), ) // Middleware on one tool runs inside the agent's chain. tag := func(next weft.ToolCaller) weft.ToolCaller { return func(ctx context.Context, call weft.ToolCallPart) (string, error) { out, err := next(ctx, call) return "[cache] " + out, err } } lookup := weft.Tool("lookup", "Look up an order.", func(_ context.Context, in orderInput) (string, error) { return "order " + in.OrderID + " has shipped", nil }, backend, weft.WrapTools(tag), weft.Origin("orders-plugin"), ) agt := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup", Args: `{"order_id":"1234"}`}), wefttest.Say("Shipped."), ), lookup) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } results(w, res) return nil } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"timeouts", timeouts}, {"result cap", resultCap}, {"sequential", sequential}, {"strict input", strict}, {"prompt snippet", snippet}, {"composed policy", composed}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [toolpolicy/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/toolpolicy) · run it from `docs-site/examples`: ```sh go run ./toolpolicy go test ./toolpolicy ``` ```text == timeouts inventory (error: true): tool "inventory" timed out after 20ms report (error: false): report ready == result cap logs (error: false): xxxxxxxxxxxxxxxx …[truncated 24 bytes] invoice (error: false): yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy == sequential check_ledger (error: false): verified write_ledger (error: false): written check_ledger (error: false): verified order: call_1 starts, call_1 ends, write_ledger runs, call_3 starts, call_3 ends == strict input refund (error: true): INVALID_INPUT: tool "refund": unknown field "amount": not in the schema retry: refunded 1234 == prompt snippet system sent: "You are a support agent.\n\nCite the article you used." snippet: "Cite the article you used." == composed policy lookup (error: false): [cache] order 1234 has shipped ``` ### Best practices & gotchas - **Honour ctx in every handler.** A timeout abandons the handler's goroutine; a handler that ignores ctx keeps running and holding resources. (Source: AGENTS.md rule 9, `weft/core/tool.go:499-507`) - **Lift the cap only for output that must arrive whole.** The 64 KiB default keeps a runaway tool from filling the context window. (Source: `weft/core/agent.go:26-28`, AGENTS.md rule 8) - **Mark a tool `Sequential` when it writes shared state.** Other tools keep running in parallel; only the barrier is serialized. (Source: `weft/core/agent.go:233-243`, `ExampleSequential`) - **Use `StrictInput` where a dropped field changes meaning.** The default is lenient on purpose. (Source: `weft/core/tool.go:524-532`) - **Expect no cap or timeout from `CallTool`.** Manual dispatch applies `StrictInput` and the middleware, not run policy. (Source: `weft/core/loop.go:1687-1697`) ### See also - [How do tools work?](https://weftgo.dev/docs/concepts/tools/) - [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) - [Define tools at runtime: RawTool and ToolSource](https://weftgo.dev/docs/guides/dynamic-tools/) - [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/) - [Describe your agents in weft.json](https://weftgo.dev/docs/guides/manifest/) Symbols used: [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.ToolOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOption) · [`weft.PolicyOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PolicyOption) · [`weft.ToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOptions) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`weft.MaxResultBytes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxResultBytes) · [`weft.StrictInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StrictInput) · [`weft.Sequential`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Sequential) · [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) · [`weft.ToolCaller`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCaller) · [`weft.PromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PromptSnippet) · [`ToolDef.PromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.PromptSnippet) · [`weft.Origin`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Origin) · [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`weft.Replay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Replay) · [`weft.ReplayPolicy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplayPolicy) · [`weft.ReplaySafe`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplaySafe) · [`weft.ReplayNever`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplayNever) · [`ToolDef.ReplayPolicy`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.ReplayPolicy) · [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) · [`weft.ErrInvalidToolInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidToolInput) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExampleToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolOptions) · [`ExampleSequential`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Sequential) · [`ExamplePromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-PromptSnippet) · [`ExampleOrigin`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Origin) --- # Define tools at runtime: RawTool and ToolSource URL: https://weftgo.dev/docs/guides/dynamic-tools/ Markdown: https://weftgo.dev/docs/guides/dynamic-tools.md > Register a tool from a JSON Schema with weft.RawTool and ParseSchema, or serve a tool list that changes during a run with weft.ToolSource. [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) defines a tool from an explicit schema instead of a Go struct; its handler receives the model's arguments as raw JSON. [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) replaces the agent's tool list with a function the loop calls once per step (plus once when a resume runs approved calls, and once per manual `CallTool`), for a registry that changes while the agent runs. Use the first for tools defined outside Go source (plugin manifests, gateways, MCP remotes), the second when the set of tools is not known at `New`. A tool whose schema arrives as bytes, in `dynamictools/main.go`: ```go title="dynamictools/main.go" schema, err := weft.ParseSchema(json.RawMessage(pluginSchema)) if err != nil { return err // invalid JSON, or a top level that is not an object } export := weft.RawTool("export_report", "Export the monthly report.", schema, func(ctx context.Context, args json.RawMessage) (string, error) { var in struct { Format string `json:"format"` } if err := json.Unmarshal(args, &in); err != nil { return "", err // validation is the handler's job } if in.Format != "pdf" && in.Format != "csv" { return "", fmt.Errorf("format %q is not pdf or csv", in.Format) } return "exported as " + in.Format, nil }) ``` [dynamictools/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/dynamictools/main.go) The model sees the schema as written, `enum` included, and the handler checks its own input. ### How it works `weft.Tool` reflects a schema from the input struct and decodes the arguments into it. `RawTool` skips both: you hand it a [`*weft.Schema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Schema), and the handler gets the bytes. Everything else is the same tool: it runs through the `WrapTools` chain, takes per-tool options such as `Timeout` and `MaxResultBytes`, and its errors are results the model reads. A `ToolSource` changes where the loop finds tools, not how it runs them. At each step the loop calls the function once; a resume that runs approved calls fetches once more before step 0, and each manual `agt.CallTool` fetches its own snapshot. That one per-step snapshot is what the step advertises and what its calls dispatch against, so what the model was shown is exactly what runs. Without a source, the list given to `New` is the only source of tools. ### Register a tool from a JSON Schema [`weft.ParseSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParseSchema) reads a JSON Schema document into a `*Schema`. It fills the structured fields it knows, such as `Type`, `Properties` and `Required`, so the manifest and any reader that walks the tree see them. It also keeps the document's own bytes, which [`Schema.MarshalJSON`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Schema.MarshalJSON) re-emits. A keyword the `Schema` type cannot hold, such as `enum`, `oneOf` or `$ref`, still reaches the model on the openai and anthropic adapters: ```text schema sent: {"properties":{"format":{"description":"the export format","enum":["pdf","csv"],"type":"string"}},"required":["format"],"type":"object"} property type: string ``` The google adapter is narrower: it sends only the keywords Gemini's schema type has, so `enum` survives but `oneOf`, `$ref` and others are dropped without an error. [Use MCP both ways](https://weftgo.dev/docs/guides/mcp/#import-tools) lists what it keeps and drops; on Gemini, validate those constraints in the handler. The top level must be an object, because providers and MCP require one. Invalid JSON, trailing data or a non-object top level return an error naming the problem, at import rather than at the first model call. The structured view is lenient: a keyword whose shape `Schema` cannot hold, such as a type array `["string","null"]`, leaves that field zero and is not an error. The handler receives the arguments verbatim: no unmarshalling and no `ErrInvalidToolInput`. Validation belongs to it, and an error it returns is an error result the model reads: ```text step 0 (error: true): format "xml" is not pdf or csv step 1 (error: false): exported as csv ``` A nil schema becomes the empty object schema, so the tool accepts any object. `StrictInput` has no effect on a `RawTool`. `RawTool` panics on an empty name or a nil handler, as `Tool` does. The manifest records no `source` line for it, because the definition is not in Go source. `mcp.Tools` builds its imported tools this way ([Use MCP both ways](https://weftgo.dev/docs/guides/mcp/)). ### Serve tools that change during a run Pass `ToolSource` a function that returns the current list. Its owner synchronizes it; the agent stays immutable, because the source is a value: ```go title="dynamictools/main.go" reg := ®istry{} reg.Add(weft.Tool("install_billing", "Install the billing plugin.", func(context.Context, struct{}) (string, error) { reg.Add(refund) // callable from the next step's fetch return "billing plugin installed", nil })) agt := weft.New(model(), weft.ToolSource(reg.Tools)) ``` [dynamictools/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/dynamictools/main.go) The model calls `refund` and `install_billing` in step 0. `refund` is not in step 0's snapshot, so it fails as unknown, even though `install_billing` adds it during that step. Step 1 fetches again and the call runs: ```text step 0 refund (error: true): NO_SUCH_TOOL: no tool named "refund" step 0 install_billing (error: false): billing plugin installed step 1 refund (error: false): refunded 1234 agent.Tools(): 0 ``` A tool registered mid-step becomes callable on the next step's fetch. The sequential barrier and dispatch use the same snapshot as the advertisement, so a source that changes mid-step cannot produce a tool that was advertised and then not found. [`agt.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) fetches its own snapshot on each call. The source replaces the static list; it does not add to it. Tools passed to `New` beside a `ToolSource` are not advertised. [`Agent.Tools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Tools) and `weft.Manifest` keep reporting that static construction-time set, which is why the output prints `0`: a manifest describes the code, not the registry behind a source. Per-run rules still apply to the snapshot: `OnlyTools` narrows it, and `ParkAllExcept` and `ParkSource` match a source's tools by name like any other. ### Handle a malformed snapshot `New` panics on a duplicate tool name or a nil `*ToolDef`. A snapshot is built at run time, so the same mistakes fail the run instead, with [`weft.ErrDuplicateTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrDuplicateTool) or [`weft.ErrNilTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNilTool): ```go title="dynamictools/main.go" dup := weft.New(wefttest.Script(wefttest.Say("never")), weft.ToolSource(func() []*weft.ToolDef { return []*weft.ToolDef{lookup, lookup} })) _, err := dup.Generate(ctx, weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, errors.Is(err, weft.ErrDuplicateTool), err) withNil := weft.New(wefttest.Script(wefttest.Say("never")), weft.ToolSource(func() []*weft.ToolDef { return []*weft.ToolDef{lookup, nil} })) _, err = withNil.Generate(ctx, weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, errors.Is(err, weft.ErrNilTool), err) ``` [dynamictools/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/dynamictools/main.go) ```text true weft: run failed at step 0: weft: duplicate tool name from tool source: "lookup" true weft: run failed at step 0: weft: nil tool in tool source snapshot: entry 1 ``` Both are run errors, a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) with the partial transcript on `.Result`, and match with `errors.Is` ([rule 1](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). The run fails rather than silently dropping the second tool or advertising a nil every adapter would dereference. `agt.CallTool` returns the same errors, and the tool list a [`PrepareStep`](https://weftgo.dev/docs/guides/prepare-step/) function returns is checked by the same rule. ### Complete example `dynamictools/main.go` runs each region against a scripted model: ```go title="dynamictools/main.go" // Command dynamictools runs the examples of the guide "Define tools at // runtime: RawTool and ToolSource": go run ./dynamictools. Every model is // scripted with wefttest, so it runs offline. package main import ( "context" "encoding/json" "errors" "fmt" "io" "os" "sync" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // pluginSchema is a tool schema that arrives as bytes, for example from a // plugin manifest. The enum is a keyword weft.Schema has no field for. const pluginSchema = `{ "type": "object", "properties": { "format": {"type": "string", "enum": ["pdf", "csv"], "description": "the export format"} }, "required": ["format"] }` // rawTool defines a tool from an explicit schema and raw arguments. func rawTool(ctx context.Context, w io.Writer) error { schema, err := weft.ParseSchema(json.RawMessage(pluginSchema)) if err != nil { return err // invalid JSON, or a top level that is not an object } export := weft.RawTool("export_report", "Export the monthly report.", schema, func(ctx context.Context, args json.RawMessage) (string, error) { var in struct { Format string `json:"format"` } if err := json.Unmarshal(args, &in); err != nil { return "", err // validation is the handler's job } if in.Format != "pdf" && in.Format != "csv" { return "", fmt.Errorf("format %q is not pdf or csv", in.Format) } return "exported as " + in.Format, nil }) model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "export_report", Args: `{"format":"xml"}`}), wefttest.ToolCalls(wefttest.Call{Name: "export_report", Args: `{"format":"csv"}`}), wefttest.Say("Exported."), ) agt := weft.New(model, export) res, err := agt.Generate(ctx, weft.Prompt("Export the report.")) if err != nil { return err } sent, err := json.Marshal(model.Requests()[0].Tools[0].InputSchema) if err != nil { return err } fmt.Fprintln(w, "schema sent:", compact(sent)) fmt.Fprintln(w, "property type:", schema.Properties["format"].Type) for _, s := range res.Steps[:2] { r := s.Results[0] fmt.Fprintf(w, "step %d (error: %t): %s\n", s.Index, r.IsError, r.Content) } return nil } func compact(b []byte) string { var v any if err := json.Unmarshal(b, &v); err != nil { return string(b) } out, _ := json.Marshal(v) return string(out) } // registry is a tool list that changes while an agent runs: plugins // installed mid-run, servers polled per step. Its owner synchronizes it. type registry struct { mu sync.Mutex tools []*weft.ToolDef } func (r *registry) Tools() []*weft.ToolDef { r.mu.Lock() defer r.mu.Unlock() return append([]*weft.ToolDef(nil), r.tools...) } func (r *registry) Add(t *weft.ToolDef) { r.mu.Lock() defer r.mu.Unlock() r.tools = append(r.tools, t) } type orderInput struct { OrderID string `json:"order_id" jsonschema:"the order"` } // toolSource re-reads the registry each step. func toolSource(ctx context.Context, w io.Writer) error { refund := weft.Tool("refund", "Refund an order.", func(_ context.Context, in orderInput) (string, error) { return "refunded " + in.OrderID, nil }) reg := ®istry{} reg.Add(weft.Tool("install_billing", "Install the billing plugin.", func(context.Context, struct{}) (string, error) { reg.Add(refund) // callable from the next step's fetch return "billing plugin installed", nil })) agt := weft.New(model(), weft.ToolSource(reg.Tools)) res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234.")) if err != nil { return err } for _, s := range res.Steps { for _, r := range s.Results { fmt.Fprintf(w, "step %d %s (error: %t): %s\n", s.Index, r.Name, r.IsError, r.Content) } } fmt.Fprintln(w, "agent.Tools():", len(agt.Tools())) return nil } // model scripts: refund before it is installed, install, refund again. func model() weft.Model { return wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "refund", Args: `{"order_id":"1234"}`}, wefttest.Call{Name: "install_billing", Args: `{}`}, ), wefttest.ToolCalls(wefttest.Call{Name: "refund", Args: `{"order_id":"1234"}`}), wefttest.Say("Refunded."), ) } // badSnapshot shows the two malformed snapshots. func badSnapshot(ctx context.Context, w io.Writer) error { lookup := weft.Tool("lookup", "Look up an order.", func(_ context.Context, in orderInput) (string, error) { return "shipped", nil }) dup := weft.New(wefttest.Script(wefttest.Say("never")), weft.ToolSource(func() []*weft.ToolDef { return []*weft.ToolDef{lookup, lookup} })) _, err := dup.Generate(ctx, weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, errors.Is(err, weft.ErrDuplicateTool), err) withNil := weft.New(wefttest.Script(wefttest.Say("never")), weft.ToolSource(func() []*weft.ToolDef { return []*weft.ToolDef{lookup, nil} })) _, err = withNil.Generate(ctx, weft.Prompt("Where is order 1234?")) fmt.Fprintln(w, errors.Is(err, weft.ErrNilTool), err) return nil } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"raw tool", rawTool}, {"tool source", toolSource}, {"bad snapshot", badSnapshot}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [dynamictools/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/dynamictools/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/dynamictools) · run it from `docs-site/examples`: ```sh go run ./dynamictools go test ./dynamictools ``` ```text == raw tool schema sent: {"properties":{"format":{"description":"the export format","enum":["pdf","csv"],"type":"string"}},"required":["format"],"type":"object"} property type: string step 0 (error: true): format "xml" is not pdf or csv step 1 (error: false): exported as csv == tool source step 0 refund (error: true): NO_SUCH_TOOL: no tool named "refund" step 0 install_billing (error: false): billing plugin installed step 1 refund (error: false): refunded 1234 agent.Tools(): 0 == bad snapshot true weft: run failed at step 0: weft: duplicate tool name from tool source: "lookup" true weft: run failed at step 0: weft: nil tool in tool source snapshot: entry 1 ``` ### Best practices & gotchas - **Validate arguments in a `RawTool` handler.** The loop does not decode them and `StrictInput` does not apply. (Source: `weft/core/tool.go:403-410`) - **Parse foreign schemas with `ParseSchema`, not by hand.** It keeps the bytes whole, so keywords `Schema` has no field for reach the model on openai and anthropic. On google, `oneOf`, `$ref` and the other keywords Gemini lacks are dropped ([the table](https://weftgo.dev/docs/guides/mcp/#import-tools)). (Source: `weft/core/schema.go:42-58`, CHANGELOG 0.2.0, `weft/google/convert.go:354-381`) - **Return a copy of the list from a source, under the owner's lock.** Synchronization and freshness belong to the source's owner. (Source: `weft/core/agent.go:786-787`) - **Put every tool in the source when you use one.** The source replaces the static list for advertising and dispatch. (Source: `weft/core/agent.go:802-809`) - **Return `submit_output` from the source of an `Output[T]` agent.** It is not added for you: a source that leaves it out makes the model's submission read `NO_SUCH_TOOL: no tool named "submit_output"`, and `GenerateAs` returns `ErrNoOutput`. Append the `submit_output` entry of `agt.Tools()`, which reports it beside a source. (Source: `weft/core/agent.go:802-809, 902-911`; [structured output](https://weftgo.dev/docs/guides/structured-output/#best-practices--gotchas)) - **Change the tool list deliberately.** `ToolSource` and `PrepareStep` are the two knobs that can break a prompt-cache prefix. (Source: `weft/core/agent.go:174-175`) - **Do not expect a mutation after `New` to reach the agent.** Registered tools are deep-copied at `New`; `Agent.Tools` returns copies. (Source: `weft/core/tool.go:22-25`, CHANGELOG 0.2.0) ### See also - [How do tools work?](https://weftgo.dev/docs/concepts/tools/) - [Use MCP both ways](https://weftgo.dev/docs/guides/mcp/) - [Rewrite the request each step (PrepareStep)](https://weftgo.dev/docs/guides/prepare-step/) - [Set per-tool policy](https://weftgo.dev/docs/guides/tool-policy/) - [Describe your agents in weft.json](https://weftgo.dev/docs/guides/manifest/) Symbols used: [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) · [`weft.ParseSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParseSchema) · [`weft.Schema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Schema) · [`Schema.MarshalJSON`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Schema.MarshalJSON) · [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) · [`weft.ToolDef`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolDef) · [`weft.ErrDuplicateTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrDuplicateTool) · [`weft.ErrNilTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNilTool) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`Agent.Tools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Tools) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`weft.Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Manifest) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Continue a conversation URL: https://weftgo.dev/docs/guides/conversations/ Markdown: https://weftgo.dev/docs/guides/conversations.md > Feed a run's transcript back with weft.Messages plus the next weft.Prompt to continue a conversation, and store the transcript as JSON between requests. To continue a conversation, pass the previous run's transcript with [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) and the new question with [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt). The agent keeps no history: the conversation is the messages you pass, so you store them between requests and send them back. Two turns, from `conversations/main.go`: ```go title="conversations/main.go" res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } // The next turn: the transcript so far, then the new question. res2, err := agt.Generate(ctx, weft.Messages(res.Messages...), weft.Prompt("And order 5678?")) if err != nil { return err } ``` [conversations/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/conversations/main.go) [`res.Messages`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RunResult.Messages) is the full transcript, the input messages included. The second run sends the model three messages: the first question, the first answer and the new question. Its own `res2.Messages` holds four, ready for the turn after. ### Feed the transcript back `weft.Messages` adds existing messages to the run's input; `weft.Prompt` adds one `user` message after them. Options apply in order, so put `Messages` before `Prompt`. The package example [`ExampleAgent_conversation`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Agent-Conversation) is the same two turns. An [agent](https://weftgo.dev/docs/concepts/agents/) is an immutable value whose runs share no state. One agent can serve every conversation at once; which conversation a run continues depends only on the messages it is given. The system prompt is not part of the transcript, since there is no system role: each turn uses the agent's [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions), or a per-run override ([Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/)). The same pattern resumes a parked run: pass `res.Messages` back with `weft.Approve` or `weft.Deny` ([Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/)). After a failed run, the partial transcript is on the error's `Result` field ([`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError)), so you can continue from what the run got done. ### Store the transcript between requests A [`weft.Message`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Message) is a role plus typed parts, and its JSON encoding is a versioned wire format ([`weft.SchemaVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SchemaVersion)). Marshal the transcript after each run and unmarshal it before the next: ```go title="conversations/main.go" // store keeps each conversation's transcript as JSON between requests: // a database row, a cache entry or a file in a real program. type store map[string][]byte func (s store) save(id string, msgs []weft.Message) error { b, err := json.Marshal(msgs) if err != nil { return err } s[id] = b return nil } func (s store) load(id string) ([]weft.Message, error) { var msgs []weft.Message if b, ok := s[id]; ok { if err := json.Unmarshal(b, &msgs); err != nil { return nil, err } } return msgs, nil } // reply answers one request of conversation id. func reply(ctx context.Context, agt *weft.Agent, s store, id, prompt string) (string, error) { history, err := s.load(id) if err != nil { return "", err } res, err := agt.Generate(ctx, weft.Messages(history...), weft.Prompt(prompt)) if err != nil { return "", err } return res.Text(), s.save(id, res.Messages) } ``` [conversations/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/conversations/main.go) Each part carries a `type` discriminator, so the messages decode back into the same typed parts, provider reasoning signatures included. An unknown part type is a decode error, never a silent drop. The complete example prints the first stored message: `{"role":"user","content":[{"type":"text","text":"Where is order 1234?"}]}`. The [messages concept page](https://weftgo.dev/docs/concepts/messages/) has the whole format. To persist a long run step by step instead of at its end, register the [`weft.OnMessages`](https://weftgo.dev/docs/guides/observers/) observer: it receives each batch of messages as it joins the transcript. For durable conversations with a writer lease, queued sends, branches and compaction, use [sessions](https://weftgo.dev/docs/sessions/overview/) (`weft/thread`), which store the transcript for you. ### A fed-back transcript is repaired The loop repairs the input of every run with the same rule as [`weft.Repair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Repair): every tool call gets a result, and a result with no call is dropped. The one exception is a resume: the calls the earlier run left pending, which this run decides with `weft.Approve` or `weft.Deny`, are left for the run to resolve itself. A call whose result never arrived, as a crashed process can leave one, gets a visible error result. The model receives `no result recorded: the call was interrupted`, and the repaired message is part of the new run's transcript. The complete example feeds back such a transcript. ### Complete example `conversations/main.go` runs the three cases against scripted models: ```go title="conversations/main.go" // Command conversations runs the examples of the guide "Continue a // conversation": go run ./conversations. Every model is scripted with // wefttest, so it runs offline; swap in a provider adapter for a real one. package main import ( "context" "encoding/json" "fmt" "io" "os" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // continueConversation runs two turns of one conversation. func continueConversation(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.Say("Order 1234 shipped yesterday."), wefttest.Say("Order 5678 is still pending."), ) agt := weft.New(model, weft.Instructions("You are a support agent.")) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } // The next turn: the transcript so far, then the new question. res2, err := agt.Generate(ctx, weft.Messages(res.Messages...), weft.Prompt("And order 5678?")) if err != nil { return err } fmt.Fprintln(w, "turn 1:", res.Text()) fmt.Fprintln(w, "turn 2:", res2.Text()) fmt.Fprintf(w, "turn 2 sent %d messages; its transcript holds %d\n", len(model.LastRequest().Messages), len(res2.Messages)) return nil } // store keeps each conversation's transcript as JSON between requests: // a database row, a cache entry or a file in a real program. type store map[string][]byte func (s store) save(id string, msgs []weft.Message) error { b, err := json.Marshal(msgs) if err != nil { return err } s[id] = b return nil } func (s store) load(id string) ([]weft.Message, error) { var msgs []weft.Message if b, ok := s[id]; ok { if err := json.Unmarshal(b, &msgs); err != nil { return nil, err } } return msgs, nil } // reply answers one request of conversation id. func reply(ctx context.Context, agt *weft.Agent, s store, id, prompt string) (string, error) { history, err := s.load(id) if err != nil { return "", err } res, err := agt.Generate(ctx, weft.Messages(history...), weft.Prompt(prompt)) if err != nil { return "", err } return res.Text(), s.save(id, res.Messages) } // stored answers two HTTP-style requests through the store. func stored(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.Say("Order 1234 shipped yesterday."), wefttest.Say("Order 5678 is still pending."), ) agt := weft.New(model) s := store{} for _, prompt := range []string{"Where is order 1234?", "And order 5678?"} { text, err := reply(ctx, agt, s, "conv-1", prompt) if err != nil { return err } fmt.Fprintln(w, "reply:", text) } msgs, err := s.load("conv-1") if err != nil { return err } first, err := json.Marshal(msgs[0]) if err != nil { return err } fmt.Fprintf(w, "stored %d messages; the first is %s\n", len(msgs), first) return nil } // repaired feeds back a transcript whose last tool call never got its // result, as a crashed process leaves it. func repaired(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("The lookup was interrupted; let me try again.")) agt := weft.New(model) interrupted := []weft.Message{ weft.User("Where is order 1234?"), {Role: weft.RoleAssistant, Content: []weft.Part{ weft.ToolCallPart{ID: "call_1", Name: "lookup", Args: json.RawMessage(`{"order_id":"1234"}`)}, }}, } if _, err := agt.Generate(ctx, weft.Messages(interrupted...), weft.Prompt("Hello?")); err != nil { return err } for _, m := range model.LastRequest().Messages { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok { fmt.Fprintf(w, "the model received for %s: %q (error: %t)\n", r.CallID, r.Content, r.IsError) } } } return nil } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"continue", continueConversation}, {"store between requests", stored}, {"repair", repaired}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [conversations/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/conversations/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/conversations) · run it from `docs-site/examples`: ```sh go run ./conversations go test ./conversations ``` ```text == continue turn 1: Order 1234 shipped yesterday. turn 2: Order 5678 is still pending. turn 2 sent 3 messages; its transcript holds 4 == store between requests reply: Order 1234 shipped yesterday. reply: Order 5678 is still pending. stored 4 messages; the first is {"role":"user","content":[{"type":"text","text":"Where is order 1234?"}]} == repair the model received for call_1: "no result recorded: the call was interrupted" (error: true) ``` ### Best practices & gotchas - **Store `res.Messages`, not a rebuild from events.** The transcript holds the exact parts, signatures and block boundaries; events are a lossy view of them. (Source: `weft/core/run.go:551-574`, OnMessages godoc) - **Send the history back every turn.** A run with no `Messages` starts a new conversation; the agent remembers nothing between runs. (Source: `ExampleAgent_conversation`, `TestAgentHoldsNoHistory`) - **Do not edit stored transcripts by hand to fix them.** The loop repairs what it is given, and the repair is visible to the model. (Source: `weft/core/repair.go:5-16`, AGENTS.md rule 2) - **Bound what you send, not what you store.** A long history costs tokens on every call; trim the request with [`PrepareStep`](https://weftgo.dev/docs/guides/prepare-step/) and keep the full transcript. (Source: `weft/core/agent.go:154-175`) ### See also - [Messages, parts and the transcript](https://weftgo.dev/docs/concepts/messages/) - [What is a session?](https://weftgo.dev/docs/sessions/overview/) - [Observe a run without changing it](https://weftgo.dev/docs/guides/observers/) - [Rewrite the request each step (PrepareStep)](https://weftgo.dev/docs/guides/prepare-step/) Symbols used: [`weft.Messages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Messages) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`RunResult.Messages`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RunResult.Messages) · [`RunResult.Text`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#RunResult.Text) · [`weft.Message`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Message) · [`weft.SchemaVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SchemaVersion) · [`weft.Repair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Repair) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`weft.OnMessages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnMessages) · [`Agent.Generate`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Generate) · [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) · [`weft.ToolResultPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolResultPart) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExampleAgent_conversation`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Agent-Conversation) --- # Tag runs with metadata URL: https://weftgo.dev/docs/guides/metadata/ Markdown: https://weftgo.dev/docs/guides/metadata.md > Attach tenant, user or request ids to every span and record of a run with weft.Metadata or weft.WithMetadata, and read them back with weft.MetadataFromContext. [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) attaches caller key/value pairs to one run: every span and every record of the run carries them, and so do the runs of its subagents. [`weft.WithMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WithMetadata) puts the same pairs on a context, for every run started under it. [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext) reads the merged pairs back. Metadata is reporting only: it changes nothing the model sees. Tag a run in `metadata/main.go`: ```go title="metadata/main.go" res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), weft.Metadata(map[string]string{"tenant": "acme", "enduser.id": "u_42"}), weft.Metadata(map[string]string{"request.id": "req_7"}), // several options merge; a later key wins ) ``` [metadata/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/metadata/main.go) The pairs are on the run's `invoke_agent` span, its `chat` and `execute_tool` spans, and its records, so a trace backend can group or filter by tenant. The package example is [`ExampleMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Metadata). ### Metadata `Metadata` is a run option. Several `Metadata` options merge in order, and a later key wins. The pairs ride the run's context, so anything that receives that context can read them with `MetadataFromContext`: a `weft.Tap`, an `OnRunEnd` observer, a tool handler, or a subagent's child run. ```go title="metadata/main.go" lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in LookupInput) (string, error) { tenant := weft.MetadataFromContext(ctx)["tenant"] // the run's pairs, in the handler return "order " + in.OrderID + " of " + tenant + " has shipped", nil }) agt := weft.New(model, lookup, weft.Tap(func(ctx context.Context, ev weft.Event) { if _, ok := ev.(weft.RunStart); ok { md := weft.MetadataFromContext(ctx) fmt.Fprintln(w, "run start: tenant =", md["tenant"], "user =", md["enduser.id"]) } }), ) ``` [metadata/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/metadata/main.go) `MetadataFromContext` returns a copy of the pairs in force: the run's own merged over its ancestors'. It returns nil when there are none. Keys under `weft.` are the weft modules' namespace by convention. `weft/thread` stamps `weft.session.id` and `weft.turn` on every turn's run, and `weft.public_id` when the session has one, and an approval resume can name its decider with `weft.approval.actor`. The core does not police the prefix. Two keys also get the OpenTelemetry mirrors that backends group on: `weft.session.id` is repeated as `gen_ai.conversation.id` and `session.id`, and `enduser.id` as `user.id`. A run started on a tool call's context, such as a subagent's child run, also carries `weft.parent.run.id` and `weft.parent.call.id` on its `invoke_agent` span, beside the run's `weft.version` and, for a named agent, `weft.manifest.hash`. #### Inherit and remove pairs A [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent)'s child run inherits the parent's pairs, because they travel on the tool call's context. An empty value means "none": it is never stored, and it removes the key the run would otherwise inherit, from its parent run or from a `WithMetadata` context. ```go title="metadata/main.go" researcher := weft.New(wefttest.Script(wefttest.Say("notes"), wefttest.Say("notes")), weft.Name("researcher"), childTap) lead := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}), wefttest.Say("done"), ), weft.Subagent("research", "Research a topic.", researcher)) _, err := lead.Generate(ctx, weft.Prompt("Brief me."), weft.Metadata(map[string]string{"tenant": "acme", "weft.session.id": "s_01"})) if err != nil { return err } // A run that is not the enclosing session's work says so with "": _, err = researcher.Generate(weft.WithMetadata(ctx, map[string]string{"tenant": "acme", "weft.session.id": "s_01"}), weft.Prompt("Standalone."), weft.Metadata(map[string]string{"weft.session.id": ""})) ``` [metadata/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/metadata/main.go) The first child run prints `weft.session.id="s_01"`. The second run reads an empty string because the key is gone: `TestEmptyValueRemoves` checks that the key is absent, not empty. `weft/thread` uses this to stamp `weft.public_id` as `""` on a session that has none, so a turn started inside another session's tool handler never reads as that session's. #### Limits Metadata rides every span and record, so it is identity, not a payload: | Limit | Value | |---|---| | Keys per run | 64 | | Key length | 128 bytes | | Value length | 1024 bytes | An entry over a limit, or with an empty key, is dropped, never truncated, and counted on the run's `invoke_agent` span as `weft.metadata.dropped`. An empty value is a removal and is not counted. Removals apply before additions: a key an empty value removes frees its slot first, so at 64 inherited keys a run that removes one and adds one keeps the new key, whatever the two keys' sort order. At the key cap the `weft.` keys are kept first, then the rest in sorted key order, so a large tag set never costs a run its session identity. ### Context metadata `WithMetadata(ctx, kv)` returns a copy of `ctx` that carries `kv` for every run started under it. Use it where the code that learns a fact is not the code that calls `Generate`: `net/http` middleware that knows the tenant or the page before the handler runs. ```go title="metadata/main.go" tag := func(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { ctx := weft.WithMetadata(r.Context(), map[string]string{ "tenant": r.Header.Get("X-Tenant"), "region": "eu-west", }) next.ServeHTTP(rw, r.WithContext(ctx)) }) } chat := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { // The handler passes no metadata option: the run reads the context's pairs. res, err := agt.Generate(r.Context(), weft.Prompt(r.FormValue("q"))) if err != nil { http.Error(rw, err.Error(), http.StatusBadGateway) return } fmt.Fprint(rw, res.Text()) }) handler := tag(chat) ``` [metadata/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/metadata/main.go) The handler passes no metadata option, and the run still reads `tenant` and `region`. The rules match `Metadata`: - Pairs merge over any the context already carries, a later key winning, under the same limits. - A run's own `Metadata` options win over the context's pairs. - A subagent's child run inherits them as it inherits the parent's. - An entry over a limit is dropped and counted on each run started under the returned context; that run's children start from zero. This is how [`scope.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Header) stamps the request's page as `weft.page_url` on every run its handler starts. The package example is [`ExampleWithMetadata`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-WithMetadata). ### Complete example `metadata/main.go` tags a run, stamps pairs from HTTP middleware, shows inheritance and removal, and drops an over-long value: ```go title="metadata/main.go" // Command metadata runs the examples of the guide "Tag runs with // metadata": go run ./metadata. Every model is scripted with wefttest, // so it runs offline; swap in a provider adapter for a real one. package main import ( "context" "fmt" "io" "net/http" "net/http/httptest" "os" "strings" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // perRun tags one run and reads the pairs back in a tap and in a tool. func perRun(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), ) type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in LookupInput) (string, error) { tenant := weft.MetadataFromContext(ctx)["tenant"] // the run's pairs, in the handler return "order " + in.OrderID + " of " + tenant + " has shipped", nil }) agt := weft.New(model, lookup, weft.Tap(func(ctx context.Context, ev weft.Event) { if _, ok := ev.(weft.RunStart); ok { md := weft.MetadataFromContext(ctx) fmt.Fprintln(w, "run start: tenant =", md["tenant"], "user =", md["enduser.id"]) } }), ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), weft.Metadata(map[string]string{"tenant": "acme", "enduser.id": "u_42"}), weft.Metadata(map[string]string{"request.id": "req_7"}), // several options merge; a later key wins ) if err != nil { return err } fmt.Fprintln(w, "tool saw:", res.Steps[0].Results[0].Content) return nil } // fromRequest stamps metadata in net/http middleware, before the // handler starts a run. func fromRequest(ctx context.Context, w io.Writer) error { agt := weft.New(wefttest.Script(wefttest.Say("ok")), weft.Tap(func(ctx context.Context, ev weft.Event) { if _, ok := ev.(weft.RunStart); ok { md := weft.MetadataFromContext(ctx) fmt.Fprintln(w, "run start: tenant =", md["tenant"], "region =", md["region"]) } })) tag := func(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { ctx := weft.WithMetadata(r.Context(), map[string]string{ "tenant": r.Header.Get("X-Tenant"), "region": "eu-west", }) next.ServeHTTP(rw, r.WithContext(ctx)) }) } chat := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { // The handler passes no metadata option: the run reads the context's pairs. res, err := agt.Generate(r.Context(), weft.Prompt(r.FormValue("q"))) if err != nil { http.Error(rw, err.Error(), http.StatusBadGateway) return } fmt.Fprint(rw, res.Text()) }) handler := tag(chat) req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/chat?q=hello", nil) req.Header.Set("X-Tenant", "acme") rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) fmt.Fprintln(w, "response:", rec.Code, rec.Body.String()) return nil } // inherit shows a Subagent's child run inheriting the pairs, and an // empty value removing one. func inherit(ctx context.Context, w io.Writer) error { childTap := weft.Tap(func(ctx context.Context, ev weft.Event) { if _, ok := ev.(weft.RunStart); ok { md := weft.MetadataFromContext(ctx) fmt.Fprintf(w, "child run: tenant=%q weft.session.id=%q\n", md["tenant"], md["weft.session.id"]) } }) researcher := weft.New(wefttest.Script(wefttest.Say("notes"), wefttest.Say("notes")), weft.Name("researcher"), childTap) lead := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}), wefttest.Say("done"), ), weft.Subagent("research", "Research a topic.", researcher)) _, err := lead.Generate(ctx, weft.Prompt("Brief me."), weft.Metadata(map[string]string{"tenant": "acme", "weft.session.id": "s_01"})) if err != nil { return err } // A run that is not the enclosing session's work says so with "": _, err = researcher.Generate(weft.WithMetadata(ctx, map[string]string{"tenant": "acme", "weft.session.id": "s_01"}), weft.Prompt("Standalone."), weft.Metadata(map[string]string{"weft.session.id": ""})) return err } // limits shows an over-long value dropped, never truncated. func limits(ctx context.Context, w io.Writer) error { var got map[string]string agt := weft.New(wefttest.Script(wefttest.Say("ok")), weft.Tap(func(ctx context.Context, ev weft.Event) { if _, ok := ev.(weft.RunStart); ok { got = weft.MetadataFromContext(ctx) } })) _, err := agt.Generate(ctx, weft.Prompt("hi"), weft.Metadata(map[string]string{ "tenant": "acme", "notes": strings.Repeat("x", 1025), // over the 1024-byte value limit })) if err != nil { return err } _, kept := got["notes"] fmt.Fprintf(w, "keys kept: %d, notes kept: %t\n", len(got), kept) return nil } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"per run", perRun}, {"from the request", fromRequest}, {"inherited", inherit}, {"limits", limits}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [metadata/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/metadata/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/metadata) · run it from `docs-site/examples`: ```sh go run ./metadata go test ./metadata ``` ```text == per run run start: tenant = acme user = u_42 tool saw: order 1234 of acme has shipped == from the request run start: tenant = acme region = eu-west response: 200 ok == inherited child run: tenant="acme" weft.session.id="s_01" child run: tenant="acme" weft.session.id="" == limits keys kept: 1, notes kept: false ``` ### Best practices & gotchas - **Put identity in metadata, not content.** Pairs ride every span and record, and the limits drop anything over 1024 bytes without truncating it. (Source: `weft/core/metadata.go:10-20`, `TestMetadataLimits`) - **Read the drop counter when a key is missing.** A dropped pair leaves no trace except `weft.metadata.dropped` on the run's `invoke_agent` span. (Source: `weft/core/metadata.go:37-43`) - **Remove an inherited key with `""`, not by omitting it.** A child run inherits every pair it does not override; only an empty value removes one. (Source: `TestMetadataEmptyValueRemovesInherited`, CHANGELOG 0.15.1) - **Do not rely on metadata to change behaviour.** It is reporting only; the model never sees it. Use [run options](https://weftgo.dev/docs/guides/run-options/) to change what a run does. (Source: `weft/core/metadata.go:70-71`) - **Leave the `weft.` prefix to weft's modules.** Those keys are kept first under the cap because they carry a run's session identity. (Source: `TestMetadataCapKeepsWeftKeys`, CHANGELOG 0.8.0) ### See also - [Observe a run without changing it](https://weftgo.dev/docs/guides/observers/): the taps that read metadata - [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/) - [The record contract](https://weftgo.dev/docs/reference/record-contract/) - [Sessions and traces in Studio](https://weftgo.dev/docs/observe/studio/sessions-and-traces/) Symbols used: [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) · [`weft.WithMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WithMetadata) · [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`scope.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Header) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExampleMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Metadata) · [`ExampleWithMetadata`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-WithMetadata) --- # Observe a run without changing it: Tap, OnRunEnd, OnMessages URL: https://weftgo.dev/docs/guides/observers/ Markdown: https://weftgo.dev/docs/guides/observers.md > Watch every event with weft.Tap, get each run's outcome once with weft.OnRunEnd, persist the transcript as it grows with weft.OnMessages, and read the Debug lines weft.Logger writes. weft has four ways to watch a run, none of which can change it. [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) sees every event of every run. [`weft.OnRunEnd`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnRunEnd) is called once per run with the result and the error, failures included. [`weft.OnMessages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnMessages) receives the exact messages as they join the transcript. [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger) sets the sink for the loop's Debug lines. A tap that counts tool calls, in `observers/main.go`: ```go title="observers/main.go" var calls int agt := weft.New(script(), lookup, weft.Tap(func(_ context.Context, ev weft.Event) { if _, ok := ev.(weft.ToolStart); ok { calls++ } }), weft.Tap(func(context.Context, weft.Event) { panic("broken observer") }), ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } fmt.Fprintln(w, "tool calls:", calls) fmt.Fprintln(w, "answer:", res.Text()) fmt.Fprintln(w, "contained tap panics:", agt.TapPanics()) // one per event the broken tap saw ``` [observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go) Observers observe; behaviour attaches at the two middleware seams, `WrapModel` and `WrapTools`. That is [rule 10](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them): two behavioural seams, one tap, no more. ### How it works | Observer | Option kind | Called | Sees a failed run | |---|---|---|---| | `Tap` | agent `Option` | once per event, every run | its events up to the failure, no end | | `OnRunEnd` | agent `Option` | once per run, at the end | yes: `err` is the `*RunError` | | `OnMessages` | `RunOption`, per run | once per batch of transcript messages | the messages that joined before it | | `Logger` | agent `Option` | one Debug line per phase | yes: the error text | `Tap`, `OnRunEnd` and `OnMessages` are synchronous, and the run waits for them. A `Tap` runs on the goroutine that emits the event, a tool goroutine included, under the event-ordering lock. `OnMessages` and `OnRunEnd` run on the loop's goroutine. Each receives the run's context, which carries the run's span and its [metadata](https://weftgo.dev/docs/guides/metadata/). A panic in a `Tap`, `OnRunEnd` or `OnMessages` observer is recovered and counted, never breaking the run. ### Tap `Tap` registers an observer that sees every event of every run, including runs made with `Generate`, which has no stream to range over. Taps run in emission order, the order `Events()` delivers ([rule 3](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)), and several taps run in registration order. The package example is [`ExampleTap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Tap). The second tap in the region panics on every event. The run still answers, and [`agt.TapPanics()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.TapPanics) reports `9`: one contained panic per event that tap saw. The counter covers taps, `OnMessages` and `OnRunEnd` observers, and attempt reports whose tracer or logger panicked. Since 0.18.0 it also counts every other call the loop makes into its `TracerProvider` or `LoggerProvider` that panics. That covers `Tracer` and `Logger` at `New`, span starts and attribute calls on the four span kinds, and the records' `Enabled` and `Emit`. Each run names such a provider in one Warn line on the agent's logger. A span whose attribute calls panic is still ended, and the run's result and events equal a run with no provider. A rising count means an observer or a provider is broken. #### Slow observers A tap runs under the step's event-ordering lock. A slow tap delays every tool event of its step and blocks the tool goroutines that emit them, the same coupling a slow `Events()` consumer has. Do slow work, such as a database write or a network sink, off the tap: hand each event to a queue and drain it on your own goroutine. ```go title="observers/main.go" events := make(chan weft.Event, 1024) dropped := 0 // written only inside the tap, read after the run done := make(chan int) go func() { // the slow side: a database write, a network sink n := 0 for range events { n++ } done <- n }() agt := weft.New(script(), lookup, weft.Tap(func(_ context.Context, ev weft.Event) { select { case events <- ev: // never block inside a tap default: dropped++ // a full queue drops, visibly } })) _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) close(events) fmt.Fprintln(w, "events drained:", <-done, "dropped:", dropped) ``` [observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go) The tap never blocks: when the queue is full it drops the event and counts it. The package example is [`ExampleTap_async`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Tap-Async). ### On run end A failed run emits no event after its last delivered one ([ADR 0004](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0004-event-ordering.md)), so a tap cannot see a failure. `OnRunEnd` is the outcome signal. The loop calls it exactly once per run, after `RunFinish` is delivered or the `RunError` is built, and before `Generate` returns: ```go title="observers/main.go" agt := weft.New(wefttest.Script(wefttest.Fail(errors.New("provider down"))), weft.OnRunEnd(func(_ context.Context, res *weft.RunResult, err error) { var runErr *weft.RunError fmt.Fprintf(w, "run ended: id set=%t steps=%d run error=%t\n", res.ID != "", res.NumSteps(), errors.As(err, &runErr)) }), ) _, err := agt.Generate(ctx, weft.Prompt("hi")) fmt.Fprintln(w, "Generate returned:", err) ``` [observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go) ```text run ended: id set=true steps=0 run error=true Generate returned: weft: run failed at step 0: model stream: provider down ``` On success `err` is nil and `res` is complete. On failure `err` is the `*RunError` and `res` is its partial transcript, the same value `RunError.Result` holds. On cancellation `err` is the `RunError` wrapping the context's error. For a subagent's child run it fires inside the parent's tool call, and `res.ID` names the child. A run that panics, for example in a `PrepareStep` function, never fires it: the loop re-panics, to your caller under `Generate`; under `Stream` the panic crashes the program. The package example is [`ExampleOnRunEnd`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-OnRunEnd). ### On messages `OnMessages` is a run option: pass it to `Generate` or `Stream`, not to `New`. The loop calls it whenever messages join the run's transcript: the assistant message a step produced, in its final shape with reasoning signatures, the tool message that follows its calls, and the messages a [steering](https://weftgo.dev/docs/guides/steering/) drain delivered. ```go title="observers/main.go" var saved []weft.Message // stands in for an append-only store persist := weft.OnMessages(func(_ context.Context, step int, msgs []weft.Message) { for _, m := range msgs { b, _ := json.Marshal(m) fmt.Fprintf(w, "step %d: save %s (%d bytes)\n", step, m.Role, len(b)) } saved = append(saved, msgs...) }) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), persist) if err != nil { return err } // The prompt is the caller's input: it is in res.Messages, not in a batch. fmt.Fprintln(w, "saved equals the transcript after the prompt:", reflect.DeepEqual(saved, res.Messages[1:])) ``` [observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go) ```text step 0: save assistant (116 bytes) step 0: save tool (143 bytes) step 1: save assistant (81 bytes) saved equals the transcript after the prompt: true ``` On an ordinary run the batches concatenate to `res.Messages` after the run's input, so appending each batch to durable storage keeps the exact transcript of a run that crashes mid-way. An [approval resume](https://weftgo.dev/docs/guides/approvals/#resume-an-approval) is the exception: its first batch is the parked step's completed tool message, which belongs right after the parked assistant message, not at the end ([gotcha](https://weftgo.dev/docs/guides/observers/#best-practices--gotchas)). `msgs` is exactly what joined, in transcript order, as a deep copy: keeping or changing it changes nothing the run sees. `step` is the step the messages belong to; a steer's messages name the step whose drain delivered them. Rebuilding messages from events loses signatures and block boundaries; this does not. A subagent's child run does not inherit the observer. The package example is [`ExampleOnMessages`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-OnMessages). ### Agent from context `weft.Option` is sealed, so an observer packaged as `weft.Options(weft.Tap(…), weft.OnRunEnd(…))` never receives the agent it was installed on. [`weft.AgentFromContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AgentFromContext) returns it: the agent whose run produced the event, or that a tool handler is running for. ```go title="observers/main.go" who := weft.Tap(func(ctx context.Context, ev weft.Event) { if _, ok := ev.(weft.RunStart); ok { agt := weft.AgentFromContext(ctx) // the running *Agent; nil outside a run agt.Logger().DebugContext(ctx, "observer saw a run") fmt.Fprintln(w, "run start by", agt.Name()) } }) researcher := weft.New(wefttest.Script(wefttest.Say("notes")), weft.Name("researcher"), who) lead := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}), wefttest.Say("done"), ), weft.Name("lead"), who, weft.Subagent("research", "Research a topic.", researcher)) ``` [observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go) ```text run start by lead run start by researcher outside a run: true ``` For a subagent's child run it is the child. Outside a run, in a manual [`agt.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) or a handler called directly, it is nil, so an observer must not depend on it. The agent is read-only: an `Agent` is immutable after `New`. [`agt.Logger()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Logger) returns the run lines' sink, the `Logger` option's value or `slog.Default`, so an observer can log its own errors where the run's lines go. ### Debug log lines `weft.Logger(l)` sets the logger the agent's runs report to, at Debug level: one line when a run starts and ends, one per model call, one per tool call. ```go title="observers/main.go" scrub := func(_ []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey || a.Key == "dur" { // not reproducible return slog.Attr{} } return a } l := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: scrub})) agt := weft.New(script(), lookup, weft.Name("support-bot"), weft.Logger(l)) _, err := agt.Generate(ctx, weft.RunID("demo"), weft.Prompt("Where is order 1234?")) ``` [observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go) ```text level=DEBUG msg="run start" run=demo agent=support-bot provider=wefttest model=script level=DEBUG msg="model call" run=demo step=0 provider=wefttest model=script reason=tool_calls input_tokens=10 output_tokens=5 tool_calls=1 level=DEBUG msg="tool call" run=demo step=0 call=call_1 tool=lookup_order result_bytes=22 level=DEBUG msg="model call" run=demo step=1 provider=wefttest model=script reason=stop input_tokens=10 output_tokens=5 tool_calls=0 level=DEBUG msg="run finish" run=demo steps=2 input_tokens=20 output_tokens=10 stop=stop ``` The lines carry ids, the model, durations, usage, stop reasons and outcomes; never message text, tool arguments or tool results. The one exception is error text: a failed run, model call or tool call logs the error it returned. The region drops the time and the `dur` attribute only to make the output reproducible. Without the option the logger is `slog.Default`, which is silent until its handler enables Debug, so weft logs nothing in a program that did not ask. `slog.New(slog.DiscardHandler)` turns the lines off outright. The lines carry the span-carrying context, so a handler that bridges to OpenTelemetry correlates them with the spans. `mw.Log` and `mw.Audit` are separate: middleware you place, at the level you choose. The package example is [`ExampleLogger`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Logger). ### Complete example `observers/main.go` runs each region against a scripted model that calls `lookup_order` once and then answers: ```go title="observers/main.go" // Command observers runs the examples of the guide "Observe a run // without changing it": go run ./observers. Every model is scripted // with wefttest, so it runs offline; swap in a provider adapter for a // real one. package main import ( "context" "encoding/json" "errors" "fmt" "io" "log/slog" "os" "reflect" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // lookup is the one tool every example uses. var lookup = weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, in struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` }) (string, error) { return "order " + in.OrderID + " has shipped", 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."), ) } // tap counts tool calls and shows a panicking tap contained. func tap(ctx context.Context, w io.Writer) error { var calls int agt := weft.New(script(), lookup, weft.Tap(func(_ context.Context, ev weft.Event) { if _, ok := ev.(weft.ToolStart); ok { calls++ } }), weft.Tap(func(context.Context, weft.Event) { panic("broken observer") }), ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } fmt.Fprintln(w, "tool calls:", calls) fmt.Fprintln(w, "answer:", res.Text()) fmt.Fprintln(w, "contained tap panics:", agt.TapPanics()) // one per event the broken tap saw return nil } // async hands events to a queue and drains it on its own goroutine. func async(ctx context.Context, w io.Writer) error { events := make(chan weft.Event, 1024) dropped := 0 // written only inside the tap, read after the run done := make(chan int) go func() { // the slow side: a database write, a network sink n := 0 for range events { n++ } done <- n }() agt := weft.New(script(), lookup, weft.Tap(func(_ context.Context, ev weft.Event) { select { case events <- ev: // never block inside a tap default: dropped++ // a full queue drops, visibly } })) _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) close(events) fmt.Fprintln(w, "events drained:", <-done, "dropped:", dropped) return err } // runEnd sees a failed run, which no event reports. func runEnd(ctx context.Context, w io.Writer) error { agt := weft.New(wefttest.Script(wefttest.Fail(errors.New("provider down"))), weft.OnRunEnd(func(_ context.Context, res *weft.RunResult, err error) { var runErr *weft.RunError fmt.Fprintf(w, "run ended: id set=%t steps=%d run error=%t\n", res.ID != "", res.NumSteps(), errors.As(err, &runErr)) }), ) _, err := agt.Generate(ctx, weft.Prompt("hi")) fmt.Fprintln(w, "Generate returned:", err) return nil } // messages persists each batch of transcript messages as it joins. func messages(ctx context.Context, w io.Writer) error { agt := weft.New(script(), lookup) var saved []weft.Message // stands in for an append-only store persist := weft.OnMessages(func(_ context.Context, step int, msgs []weft.Message) { for _, m := range msgs { b, _ := json.Marshal(m) fmt.Fprintf(w, "step %d: save %s (%d bytes)\n", step, m.Role, len(b)) } saved = append(saved, msgs...) }) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), persist) if err != nil { return err } // The prompt is the caller's input: it is in res.Messages, not in a batch. fmt.Fprintln(w, "saved equals the transcript after the prompt:", reflect.DeepEqual(saved, res.Messages[1:])) return nil } // agentFromContext names the agent behind each RunStart, child runs // included. func agentFromContext(ctx context.Context, w io.Writer) error { who := weft.Tap(func(ctx context.Context, ev weft.Event) { if _, ok := ev.(weft.RunStart); ok { agt := weft.AgentFromContext(ctx) // the running *Agent; nil outside a run agt.Logger().DebugContext(ctx, "observer saw a run") fmt.Fprintln(w, "run start by", agt.Name()) } }) researcher := weft.New(wefttest.Script(wefttest.Say("notes")), weft.Name("researcher"), who) lead := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}), wefttest.Say("done"), ), weft.Name("lead"), who, weft.Subagent("research", "Research a topic.", researcher)) _, err := lead.Generate(ctx, weft.Prompt("Brief me.")) fmt.Fprintln(w, "outside a run:", weft.AgentFromContext(ctx) == nil) return err } // logger prints the Debug lines one run writes. func logger(ctx context.Context, w io.Writer) error { scrub := func(_ []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey || a.Key == "dur" { // not reproducible return slog.Attr{} } return a } l := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: scrub})) agt := weft.New(script(), lookup, weft.Name("support-bot"), weft.Logger(l)) _, err := agt.Generate(ctx, weft.RunID("demo"), weft.Prompt("Where is order 1234?")) return err } func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"tap", tap}, {"slow observer", async}, {"run end", runEnd}, {"messages", messages}, {"agent from context", agentFromContext}, {"logger", logger}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/observers) · run it from `docs-site/examples`: ```sh go run ./observers go test ./observers ``` ```text == tap tool calls: 1 answer: Order 1234 has shipped. contained tap panics: 9 == slow observer events drained: 9 dropped: 0 == run end run ended: id set=true steps=0 run error=true Generate returned: weft: run failed at step 0: model stream: provider down == messages step 0: save assistant (116 bytes) step 0: save tool (143 bytes) step 1: save assistant (81 bytes) saved equals the transcript after the prompt: true == agent from context run start by lead run start by researcher outside a run: true == logger level=DEBUG msg="run start" run=demo agent=support-bot provider=wefttest model=script level=DEBUG msg="model call" run=demo step=0 provider=wefttest model=script reason=tool_calls input_tokens=10 output_tokens=5 tool_calls=1 level=DEBUG msg="tool call" run=demo step=0 call=call_1 tool=lookup_order result_bytes=22 level=DEBUG msg="model call" run=demo step=1 provider=wefttest model=script reason=stop input_tokens=10 output_tokens=5 tool_calls=0 level=DEBUG msg="run finish" run=demo steps=2 input_tokens=20 output_tokens=10 stop=stop ``` ### Best practices & gotchas - **Never block inside a tap.** A tap runs under the event-ordering lock; a slow one gates the step's tool events. Queue the event and drain elsewhere. (Source: `weft/core/agent.go:437-451`, `ExampleTap_async`) - **Use `OnRunEnd`, not `Tap`, to record failures.** A failed run has no `RunFinish` and no event after its last one. (Source: ADR 0004, `TestFailureIsInvisibleToTap`) - **Pass `OnMessages` per run.** It is a `RunOption`; it is not an agent option and child runs do not inherit it. (Source: AGENTS.md:86-87, `weft/core/run.go:551-574`) - **Replace, do not append, a resume's first tool message.** On a resume, the step-0 batch starts with the completed tool message. If the parked step had a call that already ran, say `lookup` beside a gated `refund`, your store already holds a partial tool message with `lookup`'s result. Appending gives two tool messages for one step, and `weft.Repair` then keeps the partial one and answers `refund` with `no result recorded: the call was interrupted`, so the next model may refund again. Put the resume's tool message right after the parked assistant message, in place of any tool message stored there. `res.Messages[len(input):]` misses it the same way. `weft/thread` handles this for you ([sessions](https://weftgo.dev/docs/sessions/overview/)). (Source: `weft/core/loop.go:308-329, 431-440`, `weft/thread/perstep.go:111-117, 215-231`; scratch test) - **Watch `TapPanics`.** A panicking observer is contained and counted, so a broken one is otherwise silent. (Source: `weft/core/agent.go:1004-1011`, CHANGELOG 0.2.0) - **Check `AgentFromContext` for nil.** It is nil outside a run, such as a manual `CallTool`. (Source: `weft/core/subagent.go:149-159`) - **Do not expect content in `weft.Logger`'s lines.** `weft.Logger` only sets where the loop's own Debug lines go, and those lines carry ids and outcomes, never message text, tool arguments or results; content goes to the [observability pipeline](https://weftgo.dev/docs/observe/recording/) under its content policy. (Source: `weft/core/agent.go:511-524`) ### See also - [Add behaviour with middleware (the two seams)](https://weftgo.dev/docs/guides/middleware/): when you need to change a call, not watch it - [Stream a run's events](https://weftgo.dev/docs/guides/streaming/) - [Tag runs with metadata](https://weftgo.dev/docs/guides/metadata/) - [Record runs](https://weftgo.dev/docs/observe/recording/) - [Event types](https://weftgo.dev/docs/reference/events/) Symbols used: [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.OnRunEnd`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnRunEnd) · [`weft.OnMessages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnMessages) · [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger) · [`weft.AgentFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AgentFromContext) · [`Agent.Logger`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Logger) · [`Agent.TapPanics`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.TapPanics) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunID) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`wefttest.Fail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Fail) · [`ExampleTap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Tap) · [`ExampleTap_async`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Tap-Async) · [`ExampleOnRunEnd`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-OnRunEnd) · [`ExampleOnMessages`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-OnMessages) · [`ExampleLogger`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Logger) · [`weft.Repair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Repair) --- # Describe your agents in weft.json (the manifest) URL: https://weftgo.dev/docs/guides/manifest/ Markdown: https://weftgo.dev/docs/guides/manifest.md > Generate weft.json with weft.Manifest, keep it current with a wefttest.Golden test, and serve it to Studio's Agents page, where stored manifests and proposed prompts build on it. [`weft.Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Manifest) renders your agents as `weft.json`: one generated, committed, diffable description of every agent and tool. The code stays the only source of truth; the file is output, never input, and nothing is configured from it. Generate it in a golden test so a stale file fails `go test`, and give it to Studio, whose Agents page draws it. The golden test in `manifest/main_test.go`: ```go title="manifest/main_test.go" // TestManifest keeps weft.json current: a tool or policy change without // regenerating fails go test. Regenerate: go test ./manifest -update func TestManifest(t *testing.T) { b, err := weft.Manifest(newAgent()) if err != nil { t.Fatal(err) } wefttest.Golden(t, "weft.json", b) } ``` [manifest/main_test.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/manifest/main_test.go) [`wefttest.Golden`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Golden) compares the bytes with the committed file. A tool or policy change without regenerating fails the test, and the diff is the review artifact. ### Generate weft.json Build the agent in one function that both the program and the test call, and give it a name with [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name): ```go title="manifest/main.go" // newAgent builds the support agent; the app and the golden test both call it. func newAgent() *weft.Agent { lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, in LookupInput) (string, error) { return "order " + in.OrderID + " has shipped", nil }, weft.Timeout(5*time.Second), weft.Replay(weft.ReplaySafe)) refund := weft.Tool("refund_order", "Refund a customer's order.", func(_ context.Context, in RefundInput) (string, error) { return "refunded " + in.OrderID, nil }, weft.RequireApproval(), weft.PromptSnippet("Refund only after looking the order up.")) return weft.New(wefttest.Script(wefttest.Say("ok")), weft.Name("support-bot"), // the manifest requires a name weft.Instructions("You are a support agent."), weft.MaxSteps(8), weft.StopWhen(weft.HasToolCall("refund_order")), lookup, refund) } ``` [manifest/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/manifest/main.go) Regenerate the file after a change, then commit it: ```sh go test ./manifest -update ``` The `-update` flag goes after the package list: placed before it, the go tool routes it to the wrong package's binary. With `-update`, `Golden` writes the file and logs which files it created or rewrote; an up-to-date file is left untouched. Without it, a missing file fails with the regenerate hint. `Manifest` returns the bytes. It takes any number of agents and fails on a nil agent, an agent without a name, and two agents with the same name: ```go title="manifest/main.go" _, err = weft.Manifest(weft.New(wefttest.Script())) fmt.Fprintln(w, "unnamed:", err) ``` [manifest/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/manifest/main.go) ```text unnamed: weft: Manifest: agent 0 has no name (set one with the Name option) ``` The file is a review artifact, and `agent_1` in a diff is noise. The package example is [`ExampleManifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Manifest). #### What the file holds This is `manifest/weft.json`, the file the test keeps current: ```json { "weft": 1, "agents": [ { "name": "support-bot", "model": { "provider": "wefttest", "name": "script" }, "instructions": "You are a support agent.", "policy": { "parallelism": 4, "max_steps": 8, "max_result_bytes": 65536, "stop_when": [ "has_tool_call:refund_order" ], "max_model_retries": 3 }, "tools": [ { "name": "lookup_order", "description": "Look up an order by ID.", "input_schema": { "type": "object", "properties": { "order_id": { "type": "string", "description": "the order to look up" } }, "required": [ "order_id" ] }, "timeout": "5s", "replay_policy": "safe", "source": "weftgo.dev/docs/examples/manifest/main.go:32" }, { "name": "refund_order", "description": "Refund a customer's order.", "input_schema": { "type": "object", "properties": { "order_id": { "type": "string", "description": "the order to refund" } }, "required": [ "order_id" ] }, "require_approval": true, "prompt_snippet": "Refund only after looking the order up.", "source": "weftgo.dev/docs/examples/manifest/main.go:38" } ] } ] } ``` - `"weft": 1` is the format version. It changes only on a breaking shape change; new fields are added without a bump ([ADR 0012](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0012-manifest-format.md)). It is not [`weft.SchemaVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SchemaVersion), which versions the message wire format: the JSON of `Message` and its parts, which persistence layers envelope. - Each agent has `name`, `model`, `instructions` (when set: the construction-time prompt; a run-level `weft.Instructions` does not change it) and `policy`: `parallelism`, `max_steps`, `max_result_bytes` and `max_model_retries` always, the rest when set. Stop conditions are named (`has_tool_call:refund_order`, `step_count_is:3`); a custom function reads `custom`. - Each tool has its `name`, `description` when set, `input_schema`, `output_schema` when it has one (a verbatim `string` result has none) and, only when set, its own policy: `timeout`, `max_result_bytes`, `strict_input`, `sequential`, `require_approval`, `replay_policy` (written only for `safe`), `prompt_snippet`, and `subagent` for a [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) tool, naming the child agent. `Manifest` does not recurse into the child: it is described only when you pass it to `Manifest` too, and `subagent` is omitted when the child has no `weft.Name`. - `source` is the `weft.Tool(...)` call site as `/:`: the defining package's import path, the file's base name and the line, with `/` separators on every OS. Since 0.20.0 it is the same on every machine, since no `go.mod` is consulted; before, it was relative to the nearest `go.mod` (`manifest/main.go:32`). For a `main` package the import path is the binary's build-info path, such as `weftgo.dev/docs/examples/manifest`; a build without one, `go run main.go`, reads `main/main.go:32`. A [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) has none. The line moves with edits; that churn is expected. - Since 0.20.0 an agent also lists its `model_middleware` and `tool_middleware`, outer to inner, and its `hooks` (`prepare_step`, `tap`, `on_run_end`, `tool_source`), each `{name, params?, source?, opaque?}`. An agent built with `weft.Params` lists its sampling knobs as `params` (`temperature`, `top_p`, `max_tokens`, `stop`, `seed`), which Studio compares a run's overrides against. A tool lists its own `middleware`. A closure reads `func@/:` ([The onion in the record](https://weftgo.dev/docs/guides/middleware/#the-onion-in-the-record)). This guide's agents have none, so the file above shows none. The bytes are deterministic: tools keep registration order, agents argument order, and `encoding/json` sorts map keys. A `ToolSource`'s tools are runtime state, so the manifest does not list them; it names the hook that serves them. #### The manifest hash `New` computes the sha256 of a named agent's one-agent manifest once, and every run of that agent carries it as `weft.manifest.hash` on its `invoke_agent` span and `run_start` record. It answers "which version of this agent ran". `TestRunsCarryManifestHash` checks that the attribute equals the hash of `weft.Manifest(agt)`. ```go title="manifest/main.go" b, err := weft.Manifest(newAgent()) if err != nil { return err } w.Write(b) sum := sha256.Sum256(b) // a one-agent document's hash: its runs' weft.manifest.hash fmt.Fprintln(w, "sha256:", hex.EncodeToString(sum[:])[:12]) ``` [manifest/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/manifest/main.go) ### Studio's Agents page Studio's Agents page (`/agents/`) draws the manifest as agent and tool cards: schemas as trees, per-tool policy chips, and each tool's `source` file and line. Studio reads the agents from one of two sources: 1. **A `weft.json` file.** In setup A pass the bytes with [`studio.Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Manifest). With `weft studio` or `weft dev`, the file is `--manifest`, else `WEFT_MANIFEST`, else the nearest `weft.json` from the working directory upward. It is read once at start; a named file that cannot be read or does not parse is a start error. 2. **Runtime registrations.** Without a file, Studio shows the manifests your app's `runtime.Install` registers over the [playground](https://weftgo.dev/docs/observe/playground/connect/) link. It remembers each by (service, manifest hash) in memory, so a restart forgets them until the runtime registers again. ```sh weft studio --manifest weft.json ``` A link can open the page on one agent: `/agents?agent=` scrolls to that agent's card, rings it and opens it (0.20.0), and keeps the card in view while the numbers above it load and lay out, until you scroll (0.20.1). The devtools panel links its header's agent name there. `?window=24h` or `?window=7d` picks the window of the numbers each card shows under the `stats` capability. [Studio pages, URL parameters and keyboard](https://weftgo.dev/docs/reference/studio-urls/#agents-runtimes-and-experiment-parameters) lists both keys. Above the cards, the page lists each source on one line: `weft.json`, or the registering service's name; the manifest hash's first 12 characters (the full hash on hover); its state, `weft.json`, `live`, or `remembered · runtime gone`; and, for a registration, the runtime id and when it registered, relative (`registered 3m ago`), the full stamp on hover. The file wins when both exist. With neither, `GET /api/manifest` answers 404 with the reason and the UI hides the Agents nav. With `--no-playground` and no file, the Agents page, the playground and the run page's replay controls say why they are off, from `/api/meta`'s `capabilities_off`; `/api/meta`'s `manifest_sources` counts the sources `/api/manifest` lists. ![The support-bot card on Studio's Agents page, drawn from weft.json: its numbers over the last 24 hours (runs, failed, duration p50 and p95, first token, tokens, cost unpriced, retried, denials), the stale manifest badge, its policy chips and the lookup_order and refund_order tool cards with their schemas, source lines and per-tool calls, failure rate and latency](https://weftgo.dev/docs/_astro/studio-agents.light.BVg8mYUa.webp) *The Agents page over this guide's weft.json: support-bot's numbers, its policy chips and its two tool cards, each with its schema, source line and call numbers.* #### Policy chips Each agent card carries one chip per policy field of its manifest entry, and each tool card one per field the tool sets. Hover a chip for what it does and the option that set it. | Chip | Card | Means | |---|---|---| | `parallelism n` | agent | Up to n tool calls of one step run at once (`Parallelism`); at 1, one at a time (`Parallelism(1)` or `Sequential()`) | | `max steps n` | agent | The run fails with `ErrMaxSteps` rather than call the model an (n+1)th time (`MaxSteps`; default 10) | | `retries n` | agent | Consecutive RETRY results one tool may return before the run fails with `ErrModelRetriesExceeded` (`MaxModelRetries`; default 3) | | `cap 64 KiB`, `cap off` | agent, tool | A tool result longer than the cap is cut, with a marker the model sees (`MaxResultBytes`); `cap off` is `MaxResultBytes(0)`. On a tool card only when the tool sets its own | | `timeout 30s` | agent, tool | A tool call still running after it becomes an error result (`Timeout`) | | `strict input` | agent, tool | Arguments with fields the input struct does not declare are rejected (`StrictInput`) | | `loops n` | agent | n consecutive steps asking for the same tool calls fail the run with `ErrLoopDetected` (`DetectLoops`) | | `stops when …` | agent | One per `StopWhen` condition, as the manifest names it: `stops when has_tool_call:submit`, `stops when output_submitted`. The run ends successfully once it holds; `MaxSteps` is the budget behind it | | `usage ≤ 25.0k in / 50.0k out` | agent | The run fails with `ErrUsageLimit` before a model call once its tokens, subagents included, pass either figure (`UsageLimit`; a zero field is no limit and is left out) | | `sequential` | tool | The tool's call runs alone, a barrier between the calls before and after it (`Sequential` on the tool) | | `approval` | tool | A call parks the run until it is approved or denied (`RequireApproval`) | | `subagent: name` | tool | The call runs the agent `name` as a child run (`Subagent`) | Chips that are off are not drawn: no `timeout`, `strict input`, `loops`, `stops when` or `usage` chip appears unless the option was set. #### The manifest API `GET /api/manifest` returns the file's own bytes with a `sources` key appended, or the registered agents merged into one document. Each entry of `sources[]` names its `source` (`file` or `runtime`), its `manifest_hash` and its agents with their own hashes; a registered source also carries its `service`, `runtime_id`, `registered_at` and `live`, true while a connected runtime holds it. A remembered source is never shown as live, and two services that register one agent name in different versions both appear. The manifest carries every agent's system prompt, so a read-scoped panel token is refused (403, badge `hidden`). `/api/meta`'s `manifest_check` compares each manifest agent's hash with the `weft.manifest.hash` of that agent's latest stored run: `source`, `agents`, `checked`, `stale` (agents whose latest run ran another version) and `differs` (agents registered in several versions). It is given to the dev token, or to setup A's loopback; `weft doctor` prints it. #### Stored manifests `GET /api/manifests/{hash}` (capability `manifests`) answers the configuration a run's `manifest_hash` names, after it stopped being the current one: `{manifest_hash, agent, source, first_seen, current_manifest_hash, manifest}`. `current_manifest_hash` is the hash the current manifest gives that agent, `""` when it names no such agent. The run document carries `manifest_available: true` when its hash resolves. Studio writes the store from both sources: each agent of the `weft.json` at `New`, and every runtime registration. A `weft.json` rewritten while Studio runs is stored only after the next restart, or when an app running that configuration next registers; under `weft dev` an app with `runtime.Install` registers again on every save-and-restart. The DB must implement [`obsdb.ManifestStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ManifestStore), which both first-party backends do. Entries are content-addressed, the first write is kept, and they are kept forever: `DELETE /api/runs/{id}`, `DELETE /api/sessions/{id}` and the retention sweeper never touch them. The route follows `/api/manifest`'s rule for read tokens. ### Proposed prompts When you edit an agent's prompt in the playground or the devtools panel, "keep as prompt" copies it to the clipboard, and Studio also remembers it as the agent's proposed instructions. The Agents page shows it as "proposed" next to "registered", and `GET /api/manifest` carries it on the agent as `proposed: {instructions, instructions_hash, since}`. Nothing reaches the app or your files. The page says so above the cards, ending "to keep it, copy it into the agent's weft.Instructions(…) in your code"; do that, then regenerate `weft.json`. ```text PUT /api/agents/{name}/proposal {"instructions": "..."} DELETE /api/agents/{name}/proposal ``` - Capability `proposals`, for the dev token or setup A's loopback; every panel token gets 403. - An agent no manifest names is 404. While a file is served, an agent only a runtime registered is 409: `/api/manifest` serves the file, so the proposal would not show. - Proposals live in memory: at most 64 agents, the oldest forgotten first, all forgotten on restart. With no agent registered, "keep as prompt" says "copy the edited prompt" and only copies: there is no agent to propose to. Otherwise its toast says what happened in two parts, the copy (`copied`, or `copy failed — the browser refused the clipboard`) and the proposal: `copied · proposed as 's instructions (see Agents)`, `copied · proposal refused: ` in the server's words, or, where it may only copy (a panel token, or no `proposals` capability), `copied · a proposal needs the dev token`. On the Agents page, an agent with a proposal shows a `registered → proposed` block: the proposal's `since` and the first 12 characters of its hash (the full hash on hover), the line diff from the registered instructions to the proposed ones, and two buttons. **copy proposed** copies the proposed text ("copied"). **withdraw** sends the `DELETE` (`proposal for withdrawn`, or `withdraw refused: …` in the server's words); under a panel token, or when the `proposals` capability is off, it is disabled, its tooltip reading "a proposal needs the dev token". **keep as prompt** beside a step's system prompt in the run page's Request pane proposes the agent's instructions, not the composed prompt the model saw. When the manifest verifies the run's agent (its `weft.manifest.hash`) and the offered tools' [PromptSnippets](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PromptSnippet) end the recorded prompt, Studio strips them: adopting the composed prompt as `Instructions` would compose them twice. Otherwise the text goes as recorded, and the toast adds what it may carry, such as "proposed as recorded: may include 2 tool snippets or a PrepareStep rewrite (the manifest does not verify this run's agent)". ### Complete example `manifest/main.go` builds the agent, prints its manifest and hash, and shows the unnamed-agent error; `main_test.go` holds the golden test: ```go title="manifest/main.go" // Command manifest runs the examples of the guide "Describe your agents // in weft.json (the manifest)": go run ./manifest prints the manifest the // golden test in main_test.go keeps committed as manifest/weft.json. package main import ( "context" "crypto/sha256" "encoding/hex" "fmt" "io" "os" "time" "github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" ) // LookupInput is the lookup tool's input; its tags are the schema. type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"` } // RefundInput is the refund tool's input. type RefundInput struct { OrderID string `json:"order_id" jsonschema:"the order to refund"` } // newAgent builds the support agent; the app and the golden test both call it. func newAgent() *weft.Agent { lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, in LookupInput) (string, error) { return "order " + in.OrderID + " has shipped", nil }, weft.Timeout(5*time.Second), weft.Replay(weft.ReplaySafe)) refund := weft.Tool("refund_order", "Refund a customer's order.", func(_ context.Context, in RefundInput) (string, error) { return "refunded " + in.OrderID, nil }, weft.RequireApproval(), weft.PromptSnippet("Refund only after looking the order up.")) return weft.New(wefttest.Script(wefttest.Say("ok")), weft.Name("support-bot"), // the manifest requires a name weft.Instructions("You are a support agent."), weft.MaxSteps(8), weft.StopWhen(weft.HasToolCall("refund_order")), lookup, refund) } func run(_ context.Context, w io.Writer) error { b, err := weft.Manifest(newAgent()) if err != nil { return err } w.Write(b) sum := sha256.Sum256(b) // a one-agent document's hash: its runs' weft.manifest.hash fmt.Fprintln(w, "sha256:", hex.EncodeToString(sum[:])[:12]) _, err = weft.Manifest(weft.New(wefttest.Script())) fmt.Fprintln(w, "unnamed:", err) return nil } func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` [manifest/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/manifest/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/manifest) · run it from `docs-site/examples`: ```sh go run ./manifest go test ./manifest ``` ```text { "weft": 1, "agents": [ { "name": "support-bot", "model": { "provider": "wefttest", "name": "script" }, "instructions": "You are a support agent.", "policy": { "parallelism": 4, "max_steps": 8, "max_result_bytes": 65536, "stop_when": [ "has_tool_call:refund_order" ], "max_model_retries": 3 }, "tools": [ { "name": "lookup_order", "description": "Look up an order by ID.", "input_schema": { "type": "object", "properties": { "order_id": { "type": "string", "description": "the order to look up" } }, "required": [ "order_id" ] }, "timeout": "5s", "replay_policy": "safe", "source": "weftgo.dev/docs/examples/manifest/main.go:32" }, { "name": "refund_order", "description": "Refund a customer's order.", "input_schema": { "type": "object", "properties": { "order_id": { "type": "string", "description": "the order to refund" } }, "required": [ "order_id" ] }, "require_approval": true, "prompt_snippet": "Refund only after looking the order up.", "source": "weftgo.dev/docs/examples/manifest/main.go:38" } ] } ] } sha256: 7d00e7f2dfbd unnamed: weft: Manifest: agent 0 has no name (set one with the Name option) ``` ### Best practices & gotchas - **Gate the file with a golden test, not a build step.** A `go:generate` step is one nobody runs; a golden test fails exactly when the committed file lies. (Source: ADR 0012, Alternatives considered) - **Name every agent you describe.** `Manifest` errors on an unnamed or duplicate name, and an unnamed agent's runs carry no `weft.manifest.hash`. (Source: `weft/core/manifest.go:28-42`, `weft/core/agent.go:750-759`, `weft/core/loop.go:140`) - **Put `-update` after the package list.** Before it, the go tool hands the flag to the wrong binary. (Source: `weft/core/wefttest/golden.go:19-26`) - **Pass every subagent's agent to `Manifest`.** The file describes the agents it is given, not the fleet: a child you leave out appears only as the `subagent` name on its parent's tool, and an unnamed child not even that. (Source: `weft/core/manifest.go:123-127, 192`; `weft/core/subagent.go:344`) - **Never read the manifest back as configuration.** It is output; the agent is built from code. (Source: ADR 0012, Context) - **Build the binary from a package, never `go run main.go`.** A file list has no build info, so its sources read `main/…`. Its manifest hash then differs from the committed `weft.json`'s, and its runs read stale against the file. Use `go run .`, `go run ./cmd/app` or a module build; `weft dev -h` says the same. (Source: `weft/core/manifest.go:250-310`; `weft/cmd/weft/dev.go:95-98`) - **Expect `source` lines to churn.** They move with every edit above the tool. The path part does not: it is the import path, never an absolute or machine-dependent one. (Source: `weft/core/manifest.go:250-300`, ADR 0012 decision 2) - **A proposal does not say whether its snippets were stripped.** The proposal body is the text alone, so the Agents page cannot tell a stripped prompt from one proposed as recorded; read the toast when you keep it. (Source: `studio/web/src/lib/request-pane.ts:261-301`) - **Read a tool's `timeout 0s` chip as no deadline.** A tool built with `weft.Timeout(0)` lifts the agent's default, and the manifest records it as `"0s"`; the chip's title still reads "this tool's call still running after 0s becomes an error result". (Source: `weft/core/tool.go:500`; `weft/core/manifest.go:221-229`; `studio/web/src/lib/policy.ts:121-126`) - **Treat a proposal as a reminder, not a change.** It lives in Studio's memory only; the agent changes when your code does. (Source: `weft/studio/proposals.go:16-26`) ### See also - [Studio setup](https://weftgo.dev/docs/observe/studio/setup/) - [Connect your app to the playground](https://weftgo.dev/docs/observe/playground/connect/) - [Set per-tool policy](https://weftgo.dev/docs/guides/tool-policy/): the policy keys the manifest records - [Studio API reference](https://weftgo.dev/docs/reference/studio-api/) Symbols used: [`weft.Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Manifest) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`weft.SchemaVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#SchemaVersion) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`weft.Replay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Replay) · [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`weft.PromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PromptSnippet) · [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) · [`weft.HasToolCall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#HasToolCall) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.Instructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Instructions) · [`wefttest.Golden`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Golden) · [`studio.Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Manifest) · [`obsdb.ManifestStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ManifestStore) · [`ExampleManifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Manifest) --- # Sessions with weft/thread URL: https://weftgo.dev/docs/sessions/ Markdown: https://weftgo.dev/docs/sessions.md > When you need weft/thread and what it adds over the stateless core: durable multi-turn sessions on disk, one writer, branching, compaction, approvals and pools. The core is stateless: a run takes a transcript in and gives one back, and storing it between runs is your job ([Continue a conversation](https://weftgo.dev/docs/guides/conversations/)). Package [`weft/thread`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread) is the layer above it. A [session](https://weftgo.dev/docs/reference/glossary/#session) is a conversation stored as an append-only tree of entries in a backend, with one writer, turns that are durable step by step, and branching, compaction, approvals and child sessions built on the same tree. Use `weft/thread` when a conversation must outlive the process, survive a crash mid-turn, or be read by another process while it is written. Stay with `weft.Messages` when each request carries its whole history and nothing needs to be durable. What it adds over the core: - **Durability.** The prompt is written to the storage before the run starts, each step's messages as they join the run, and a turn entry at the end. A crash loses at most the step in flight and the turn's closing entry: the prompt and every finished step are already stored (thread rule T4). - **One writer.** A `Session` value is its session's only writer until it closes; a second writer gets `thread.ErrLocked` (T1, T2). - **A tree, not a list.** You branch back, fork into a new session and label entries; nothing is rewritten or deleted in place. - **Busy policies.** A message sent while a turn runs is queued, rejected, steered into the turn, interrupts it, or rolls it back, and every message accepted that way is written to the storage first. - **Compaction, approvals and pools.** Long sessions are summarized without deleting anything, parked tool calls survive restarts, and child sessions run under a bound. `weft/thread` is a package of the framework module, `github.com/weftgo/weft`, so it comes with `go get github.com/weftgo/weft@v0.20.2`. It is pre-1.0: its API and stored format may change between minor versions, each change recorded in the CHANGELOG. ### The pages The section has thirteen pages: this one and the twelve below, in reading order. 1. [What is a session?](https://weftgo.dev/docs/sessions/overview/): the entry tree, one writer per session, and what is durable when. 2. [Store sessions: JSONL, SQLite or memory](https://weftgo.dev/docs/sessions/storage/): pick a backend, list and delete sessions, tail one live. 3. [Write your own thread.Storage](https://weftgo.dev/docs/sessions/custom-storage/): the five methods, the optional capabilities, and `threadtest`. 4. [Send turns and wait for them](https://weftgo.dev/docs/sessions/turns/): `Send`, `Wait`, events, outcomes and run options. 5. [What happens when you send while a turn runs?](https://weftgo.dev/docs/sessions/busy-and-steering/): the busy policies, receipts and `Steer`. 6. [Label, branch and fork a session](https://weftgo.dev/docs/sessions/tree/): navigate the tree, fork, titles and public ids. 7. [Keep long sessions inside the context window (compaction)](https://weftgo.dev/docs/sessions/compaction/): summaries that replace old entries in the context. 8. [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/): parked calls that survive restarts, grants and approvers. 9. [Sign approval decisions](https://weftgo.dev/docs/sessions/signed-approvals/): decisions that cross a process boundary. 10. [Run bounded child sessions with a pool](https://weftgo.dev/docs/sessions/pools/): delegation with receipts. 11. [Operate sessions in production](https://weftgo.dev/docs/sessions/operations/): backups, locks, shutdown and crash recovery. 12. [The session log format](https://weftgo.dev/docs/sessions/format/): every entry kind and its fields. ### See also - [What is a session?](https://weftgo.dev/docs/sessions/overview/) - [Continue a conversation](https://weftgo.dev/docs/guides/conversations/): multi-turn without `weft/thread` - [`docs/thread-operations.md`](https://github.com/weftgo/weft/blob/v0.20.2/docs/thread-operations.md): the operator's page - [Package thread on pkg.go.dev](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread) --- # What is a session? URL: https://weftgo.dev/docs/sessions/overview/ Markdown: https://weftgo.dev/docs/sessions/overview.md > A weft/thread session is a conversation stored as an append-only tree of entries, written by one Session at a time, durable step by step; Open only reads. A [session](https://weftgo.dev/docs/reference/glossary/#session) is a conversation that `weft/thread` stores as an append-only tree of entries: messages, turn ledgers, labels, summaries. A [`*thread.Session`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session) holds that tree in memory and is the session's only writer until it closes. The prompt is written to the storage before the run starts and every step's messages land as they join the run, so a crash loses at most the step in flight and the turn's closing entry. `sessions/overview.go` creates a session on the JSONL backend, runs one turn and closes it: ```go title="sessions/overview.go" st, err := jsonl.Open(dir) // one .jsonl file per session if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_support", "a")) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text()) fmt.Fprintln(w, "run:", turn.RunID(), "entries:", len(s.Entries())) if err := s.Close(ctx); err != nil { // drain, seal, give up the writer's lease return err } ``` [sessions/overview.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/overview.go) ```text answer: Order 1234 shipped on Tuesday. run: s_support-t1 entries: 3 ``` The turn wrote three entries: the prompt, the reply and the turn's ledger. The `ids` helper pins the ids so the output is stable; an application leaves it out. `ctxWindow` is `thread.ContextWindow(128_000)`, the model's context window, which arms automatic compaction. ### What a session is The core is stateless on purpose; `weft/thread` is the layer above it. A session is a header and then its entries, in append order. Each entry has an id, a parent and a time, and the **leaf** is the entry the next one attaches to. What the model sees, [`s.Context()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context), is the messages on the path from a root to the leaf, repaired with `weft.Repair`. Nothing is rewritten or deleted in place: branching appends a leaf entry, a fork writes a new session, and a compaction appends a summary. > **Diagram:** A session log holds e1 (user: Where is order 1042?), e2 (assistant: Shipped this morning.), e3 (user: And 5678?) and e4 (assistant: Still processing.). s.Branch(ctx, e2) appends a leaf entry pointing at e2; nothing is rewritten. The next write, e5 (user: Cancel 1042 instead.), attaches to e2, so the model's context is e1, e2, e5. e3 and e4 stay in the file, off the path. > > **Diagram:** Session A holds e1, e2 and e3. s.Fork(ctx, e2) writes a new session B whose header names its parent, A#e2: B holds copies of e1 and e2 and continues with its own e3. Session A keeps its leaf and its entries; Fork never moves it. Runs in B carry weft.session.forked_from = A#e2. > > **Diagram:** A session log holds e1 to e5. s.Compact(ctx) appends a compaction entry C, a summary of e1 to e3. Those entries stay in the file; the context at the leaf becomes the summary, then e4 and e5, the kept recent entries. s.Uncompact(ctx) undoes it by branching back to the entry before the compaction. On the JSONL backend a session is one file you can read with `jq` and back up with `cp`: one header line, then one line per entry. The other backends store the same lines ([Store sessions](https://weftgo.dev/docs/sessions/storage/)). `thread` imports the core, the standard library and the OTel API (for the compaction marker record), never a database driver; the SQLite driver lives in `thread/sqlite` alone. Godoc examples cover most of the package; [`ExampleCreate`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Create) shows a session carrying a title, application state and an application message, and [`ExampleHeader`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Header) the header line itself. ### Create and open [`thread.Create(ctx, st, agent, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Create) starts a new session in a [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage): a fresh header under a new time-sortable id, and an empty tree. The header is all it writes. The agent is the session's own: `Send` runs it and compaction summarizes with its model; it must not be nil. An id the storage already holds fails with `thread.ErrExists`. [`thread.Open(ctx, st, id, agent, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Open) loads a stored session, positioned at its leaf. Options are [`thread.SessionOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionOption) values, the same at `Create`, `Open` and `Fork`; header options (`WithMeta`, `PublicID`, `WithLineage`) fail `Open` with `ErrCreateOnly`. **`Open` is read-only (T3).** It validates the tree (unique valid ids, every parent an earlier entry) and refuses a file that fails with `thread.ErrCorrupt`. It writes no entry, takes no lock and starts no run. Input a stopped writer had accepted and not settled is restored to the queue and waits for you. Here a writer is shut down while a turn runs and a second message waits behind it; the next process opens the session: ```go title="sessions/overview.go" st2, err := jsonl.Open(dir) if err != nil { return err } reopened, err := thread.Open(ctx, st2, "s_export", next, ctxWindow, ids("", "b")) if err != nil { return err } for _, q := range reopened.Queue() { // what the stopped writer accepted, restored fmt.Fprintln(w, "restored:", q.Policy, q.Msg.Text()) } fmt.Fprintln(w, "model calls after Open:", len(model.Requests())) turn, err := reopened.Continue(ctx) // run it now; the next Send would too if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "continued:", res.Text()) ``` [sessions/overview.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/overview.go) ```text restored: queue Then email it to me. model calls after Open: 0 continued: Sent to the address on file. ``` `Open` restored the queued send and called no model. [`s.Continue(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Continue) runs it now; without it, the next `Send` runs it first ([Send turns](https://weftgo.dev/docs/sessions/turns/#send-a-turn)). [`s.Queue()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Queue) lists what was restored and `s.ClearQueue(ctx)` drops it ([Busy policies](https://weftgo.dev/docs/sessions/busy-and-steering/#receipts)). The package example is [`ExampleOpen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Open). Three accessors identify a session: [`s.ID()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ID) is the header's id and the storage key; [`s.Storage()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Storage) returns the storage it was created or opened on, read-only by convention (`thread/pool` creates child sessions there); and inside a tool that a session's turn runs, [`thread.SessionFromContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext) returns that session. Outside a session's run it returns nil. ### One writer **One `Session` writes a session (T1).** A Session takes its session's writer lease with its first write (`Create` and `Fork` are first writes) and holds it until `Close`. Another Session on the same session opens and reads; every write it makes fails with [`thread.ErrLocked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrLocked) and changes nothing. A Session whose view fell behind, because another writer appended after it was opened, fails its write with [`thread.ErrStale`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrStale): open the session again. ```go title="sessions/overview.go" writer, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "b")) if err != nil { return err } other, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "c")) if err != nil { return err } if err := writer.Claim(ctx); err != nil { // the writer's lease, taken before any write return err } fmt.Fprintln(w, "other reads:", len(other.Context()), "messages") err = other.SetInfo(ctx, "Order 1234", nil) fmt.Fprintln(w, "other writes:", errors.Is(err, thread.ErrLocked)) if err := writer.SetInfo(ctx, "Order 1234: shipped", nil); err != nil { return err } if err := writer.Close(ctx); err != nil { return err } err = other.SetInfo(ctx, "Order 1234", nil) fmt.Fprintln(w, "after the writer closed:", errors.Is(err, thread.ErrStale)) if err := other.Close(ctx); err != nil { return err } again, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "d")) if err != nil { return err } fmt.Fprintln(w, "reopened:", again.Title()) ``` [sessions/overview.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/overview.go) ```text other reads: 2 messages other writes: true after the writer closed: true reopened: Order 1234: shipped ``` The rule has two layers. Between processes and between `Storage` values, the backend's own lock refuses a second writer with `ErrLocked` (a file lock on JSONL, a lock row on SQLite). Between Session values on one `Storage` value, the lease does it: the [`thread.Leaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) capability, which Memory, jsonl and sqlite implement. Reading never takes either: `Open`, `List`, `Load`, `Watch` and every read of a Session work while another writer holds the session. The stale check compares the stored header's creation time and the number of entry lines, not contents. The package example is [`ExampleSession_Close_handOver`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Close-HandOver). #### Claim [`s.Claim(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Claim) takes the writer lease now, without writing an entry. It returns nil when this Session holds the lease (or the storage has no `Leaser` to ask), `ErrLocked` while another writer holds the session (nothing taken), `ErrStale` when the stored session moved past this Session's view (the lease is given back, so a fresh Session can claim it), and `ErrClosed` once the Session is sealed. A Session that claimed holds the lease until `Close`, as one that wrote does, so claim only with a `Close` to come. `weft/runtime` uses it to make sure it is the writer before it acknowledges a debugger's decision. #### Close what you open **`s.Close(ctx)` is how a writer stops (T2).** [`Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Close) does four things in order: 1. New work stops at once: `Send` and `Continue` fail with [`thread.ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrClosed). 2. It waits for the running turn, the sends queued behind it and any approval resume those turns arm. Sends queued behind an approval boundary that nobody decides cannot drain: once no turn runs, `Close` goes on and their Turns end with `ErrClosed`. 3. It seals the Session: every later write fails with `ErrClosed`. Reads keep answering, and `Fork` still works because it writes another session. 4. It releases the lease and the backend's hold, so another writer can take the session. A queued Turn that ends with `ErrClosed` is not lost. Its `accepted` receipt stays in the file, the next `Open` restores it to `s.Queue()`, and it runs once the boundary is decided. A caller that sends the message again on `ErrClosed` gets it answered twice: reopen and read `s.Queue()` instead. If `ctx` ends while Close waits, Close gives up: it cancels the running turn, ends every queued `Turn` with `ErrClosed` and returns `ctx.Err()`. Call `Close` again to finish sealing and releasing. The queued sends keep their receipts in the file, and the next `Open` restores them, as the region above shows: ```text close gave up: true running turn: canceled queued turn: canceled true ``` `Close` is idempotent. It does not wait for `thread/pool` children (close the pool first), and it must not be called from inside the session's own run, a tool or a hook, because it would wait for the turn that calls it. The package example is [`ExampleSession_Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Close). ### Durability **Accepted input is durable input (T4).** A `Send` that returns a `Turn` has written and flushed its prompt, or the receipt entry of a message it queued or steered. The run's messages are appended as they join its transcript, through `weft.OnMessages`, the core's transcript observer, each step once ([ADR 0011 §7](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0011-thread-sessions.md)). The turn's end normally appends only its bookkeeping: the turn entry and any receipts or approval entries, in one atomic batch that completes even if the caller's context is canceled. So a crash mid-turn loses at most the step in flight (its partial text) and the closing turn entry; the prompt, or the receipt, and every finished step are already stored. A tool call left without a result is answered by the loop's input repair on the next run, so the next model sees a complete transcript. A failed turn whose final form differs from its raw tail (an interrupt's golden texts) is rewritten from its first differing message on a fresh line, attached after the last entry that still matches; the raw tail stays on its own branch. No leaf entry is written for that; a leaf entry back to where the turn started is written only for an overflow re-run's failed attempt. How durable "stored" is depends on the backend and its fsync policy. `thread.Memory()` loses everything with the process. On jsonl and sqlite every append is fsynced before it returns by default, so it survives an OS crash or a power cut; with [`thread.FsyncOnFlush()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncOnFlush) an append survives the process dying, and only what was flushed survives an OS crash ([Store sessions](https://weftgo.dev/docs/sessions/storage/#open-options)). **Readers fail loudly (T5).** An entry kind or a `"v"` version this build does not know is [`thread.ErrNewerFormat`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNewerFormat), never skipped. A damaged line is `ErrCorrupt` naming the line; opened with `thread.Salvage()` the backend skips it and reports the skip in [`s.LoadReport()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.LoadReport), as it always reports a torn final line it dropped ([Recover a damaged file with Salvage](https://weftgo.dev/docs/sessions/storage/#recover-a-damaged-file-with-salvage)). ### IDs and clocks Session and entry ids are time-sortable. [`thread.NewSessionID()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NewSessionID) returns `s_` plus 26 characters: a millisecond timestamp then random bits, in Crockford base32 (the ULID shape). [`thread.NewEntryID()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NewEntryID) returns `e_` plus 26. Ids born in the same millisecond order randomly, so a session's order of record is its entry order, never id order. [`thread.ValidID(id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ValidID) reports whether an id is 1 to 128 letters, digits, `_` or `-`, so an id is always one path component: ```go title="sessions/overview.go" id := thread.NewSessionID() fmt.Fprintln(w, "new id:", id[:2], len(id), thread.ValidID(id), thread.ValidID("../etc/passwd")) ``` [sessions/overview.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/overview.go) ```text new id: s_ 28 true false ``` Two options pin what a session mints, for tests and examples. [`thread.IDs(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#IDs) takes every id from `fn`: the session id `Create` or `Fork` generates, then each entry id. An id that fails `ValidID` or repeats one the session holds fails the write. [`thread.Clock(now)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Clock) makes `now` the session's time source: the header's `Created`, every entry's `Created`, and the approval machinery's expiry arithmetic, all in UTC. Both may run with the session's lock held, so they must return quickly and never call the Session; the `Clock` function may also be called from the runner's goroutine and must be safe for concurrent use. The examples are [`ExampleNewSessionID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-NewSessionID) and [`ExampleClock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Clock). ### What it does not do - **It does not merge writers.** One Session writes; a second is refused, not reconciled. On a backend without `Leaser` two Sessions on one `Storage` value both write, each blind to the other. - **It does not run anything on `Open`.** Restored input waits for `Send` or `Continue`. - **It does not delete history.** `thread.Delete` removes a whole session; nothing else removes data. `Delete` does not look for open Sessions, so close one first. - **It does not freeze the format yet.** ### Stability `weft/thread` is pre-1.0 and not frozen: its API and its stored format may change between minor versions, each change recorded in the CHANGELOG with what to write instead. What holds today: a reader fails loudly on what it does not know, and golden files pin every format version the current build reads ([The session log format](https://weftgo.dev/docs/sessions/format/)). ### Complete example `sessions/overview.go` creates, writes, hands over, restores and mints ids: ```go title="sessions/overview.go" package main import ( "context" "errors" "fmt" "io" "github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/thread/jsonl" "github.com/weftgo/weft/wefttest" ) // demoOverview is the page "What is a session?": create a session, run a // turn, close it; one writer at a time; and what Open restores after a // writer stopped with work queued. func demoOverview(ctx context.Context, w io.Writer, dir string) error { agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), ), weft.Name("support")) st, err := jsonl.Open(dir) // one .jsonl file per session if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_support", "a")) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text()) fmt.Fprintln(w, "run:", turn.RunID(), "entries:", len(s.Entries())) if err := s.Close(ctx); err != nil { // drain, seal, give up the writer's lease return err } if err := oneWriter(ctx, w, st, agent); err != nil { return err } if err := restore(ctx, w, dir); err != nil { return err } id := thread.NewSessionID() fmt.Fprintln(w, "new id:", id[:2], len(id), thread.ValidID(id), thread.ValidID("../etc/passwd")) return nil } // oneWriter opens the stored session twice on one Storage value: the // first Session to write is the writer until it closes; the other reads, // and its writes are refused. func oneWriter(ctx context.Context, w io.Writer, st thread.Storage, agent *weft.Agent) error { writer, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "b")) if err != nil { return err } other, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "c")) if err != nil { return err } if err := writer.Claim(ctx); err != nil { // the writer's lease, taken before any write return err } fmt.Fprintln(w, "other reads:", len(other.Context()), "messages") err = other.SetInfo(ctx, "Order 1234", nil) fmt.Fprintln(w, "other writes:", errors.Is(err, thread.ErrLocked)) if err := writer.SetInfo(ctx, "Order 1234: shipped", nil); err != nil { return err } if err := writer.Close(ctx); err != nil { return err } err = other.SetInfo(ctx, "Order 1234", nil) fmt.Fprintln(w, "after the writer closed:", errors.Is(err, thread.ErrStale)) if err := other.Close(ctx); err != nil { return err } again, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "d")) if err != nil { return err } fmt.Fprintln(w, "reopened:", again.Title()) return again.Close(ctx) } // restore stops a writer while a turn runs and a second message waits // behind it, then opens the session again as the next process would. func restore(ctx context.Context, w io.Writer, dir string) error { export, started, _ := slowTool("export") agent := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "export", ID: "call_1"}), ), export) st, err := jsonl.Open(dir) if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_export", "a")) if err != nil { return err } running, err := s.Send(ctx, weft.User("Export my order history.")) if err != nil { return err } <-started queued, err := s.Send(ctx, weft.User("Then email it to me.")) // Queue: an accepted receipt, flushed if err != nil { return err } // Shutdown with no time left: Close gives up waiting, cancels the // running turn and ends the queued Turn. A second Close finishes. expired, cancel := context.WithCancel(ctx) cancel() err = s.Close(expired) fmt.Fprintln(w, "close gave up:", errors.Is(err, context.Canceled)) if err := s.Close(ctx); err != nil { return err } _, err = running.Wait() fmt.Fprintln(w, "running turn:", running.Outcome()) _, err = queued.Wait() fmt.Fprintln(w, "queued turn:", queued.Outcome(), errors.Is(err, thread.ErrClosed)) // The next process: a fresh Storage over the same directory, and an // agent whose model has served nothing yet. model := wefttest.Script(wefttest.Say("Sent to the address on file.")) next := weft.New(model) st2, err := jsonl.Open(dir) if err != nil { return err } reopened, err := thread.Open(ctx, st2, "s_export", next, ctxWindow, ids("", "b")) if err != nil { return err } for _, q := range reopened.Queue() { // what the stopped writer accepted, restored fmt.Fprintln(w, "restored:", q.Policy, q.Msg.Text()) } fmt.Fprintln(w, "model calls after Open:", len(model.Requests())) turn, err := reopened.Continue(ctx) // run it now; the next Send would too if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "continued:", res.Text()) return reopened.Close(ctx) } ``` [sessions/overview.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/overview.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`: ```sh go run ./sessions overview go test ./sessions ``` ```text answer: Order 1234 shipped on Tuesday. run: s_support-t1 entries: 3 other reads: 2 messages other writes: true after the writer closed: true reopened: Order 1234: shipped close gave up: true running turn: canceled queued turn: canceled true restored: queue Then email it to me. model calls after Open: 0 continued: Sent to the address on file. new id: s_ 28 true false ``` Each `Session` value (from `Create`, `Open` or `Fork`) logs one `WARN` at its first turn, `thread: no context window known for this session`, unless `thread.ContextWindow` or `thread.ModelWindows` gives it a window; without one, automatic compaction stays off. `thread.NoAutoCompact()` turns compaction off and silences the line. The demo passes `ctxWindow`, so standard error stays empty ([compaction](https://weftgo.dev/docs/sessions/compaction/)). The tests in `sessions/sessions_test.go` also pin `ErrLocked` for a second writer, `ErrClosed` after `Close`, and the restored queue. ### Best practices & gotchas The rules that follow from this model are with the tasks they apply to: closing, retrying (a failed turn included) and `IDs`/`Clock` in [Send turns › Best practices](https://weftgo.dev/docs/sessions/turns/#best-practices--gotchas), deleting in [Store sessions › Best practices](https://weftgo.dev/docs/sessions/storage/#best-practices--gotchas), and never appending behind a Session in [Write your own thread.Storage](https://weftgo.dev/docs/sessions/custom-storage/#best-practices--gotchas). ### See also - [Store sessions: JSONL, SQLite or memory](https://weftgo.dev/docs/sessions/storage/) - [Send turns and wait for them](https://weftgo.dev/docs/sessions/turns/) - [Label, branch and fork a session](https://weftgo.dev/docs/sessions/tree/) - [Operate sessions in production](https://weftgo.dev/docs/sessions/operations/) - [Glossary: session](https://weftgo.dev/docs/reference/glossary/#session) Symbols used: [`thread.Session`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session) · [`thread.Create`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Create) · [`thread.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Open) · [`thread.SessionOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionOption) · [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage) · [`thread.Leaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) · [`Session.Send`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Send) · [`Session.Context`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context) · [`Session.Entries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Entries) · [`Session.Queue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Queue) · [`Session.Continue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Continue) · [`Session.Claim`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Claim) · [`Session.Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Close) · [`Session.SetInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.SetInfo) · [`Session.Title`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Title) · [`Session.ID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ID) · [`Session.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Storage) · [`Session.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.LoadReport) · [`thread.SessionFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext) · [`thread.IDs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#IDs) · [`thread.Clock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Clock) · [`thread.NewSessionID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NewSessionID) · [`thread.NewEntryID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NewEntryID) · [`thread.ValidID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ValidID) · [`thread.FsyncOnFlush`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncOnFlush) · [`thread.ErrLocked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrLocked) · [`thread.ErrStale`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrStale) · [`thread.ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrClosed) · [`thread.ErrNewerFormat`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNewerFormat) · [`thread.ErrCorrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCorrupt) · [`jsonl.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open) · [`weft.User`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#User) · [`weft.OnMessages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnMessages) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Store sessions: JSONL, SQLite or memory URL: https://weftgo.dev/docs/sessions/storage/ Markdown: https://weftgo.dev/docs/sessions/storage.md > Pick a thread.Storage backend (jsonl.Open, sqlite.Open or thread.Memory), set its open options, list and delete sessions, and tail one live with Watch. A session lives in a [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage) backend. Three ship with weft: [`jsonl.Open(dir)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open), one file per session; [`sqlite.Open(path)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#Open), every session in one database file; and [`thread.Memory()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Memory), in process. Pass the result to `thread.Create` or `thread.Open`; the Session API is the same on all three, and only the [capabilities](https://weftgo.dev/docs/sessions/storage/#backends) differ. `sessions/storage.go` opens a JSONL directory, runs one turn and reads the file back: ```go title="sessions/storage.go" sessions := filepath.Join(dir, "sessions") st, err := jsonl.Open(sessions, thread.FsyncOnFlush()) // fsync at the turn's end, not every append if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_jsonl", "a"), at(base)) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } if err := s.Close(ctx); err != nil { return err } data, err := os.ReadFile(filepath.Join(sessions, "s_jsonl.jsonl")) if err != nil { return err } lines := strings.Split(strings.TrimSpace(string(data)), "\n") fmt.Fprintln(w, "lines:", len(lines)) fmt.Fprintln(w, lines[0]) fmt.Fprintln(w, lines[1]) ``` [sessions/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go) ```text lines: 4 {"type":"session","weft":1,"id":"s_jsonl","created":"2026-10-18T09:00:00Z"} {"type":"message","id":"e_a1","created":"2026-10-18T09:00:00Z","message":{"role":"user","content":[{"type":"text","text":"Where is order 1234?"}]},"run_id":"s_jsonl-t1"} ``` The header line comes first, then one entry per line: the prompt (carrying the run id minted for its turn), the reply and the turn's ledger. In the demos, `ids` pins the ids for stable output and `ctxWindow` is `thread.ContextWindow(128_000)`, the model's context window ([why](https://weftgo.dev/docs/sessions/turns/#best-practices--gotchas)). ### Backends | Aspect | `thread/jsonl` | `thread/sqlite` | `thread.Memory` | |---|---|---|---| | Layout | one `.jsonl` file per session in a directory | one SQLite file for every session, WAL | a map in the process | | Survives the process | yes | yes | no | | One writer across processes | advisory file lock (`flock`, `LockFileEx` on Windows) | a lock row per session | one process only | | Default durability | every append fsynced | every commit fsynced (`synchronous=FULL`) | nothing to sync | | `Watch` (live tail) | yes | yes | no | | Use for | the default; `jq` and `cp` work on it | many sessions in one file; `TitleSearch` without reading entries | tests and examples | All three implement the `Releaser` and `Leaser` capabilities; jsonl and sqlite also implement `Flusher` and `Watcher`. All three accept the same [open options](https://weftgo.dev/docs/sessions/storage/#open-options) and pass the same conformance table ([Write your own thread.Storage](https://weftgo.dev/docs/sessions/custom-storage/)). jsonl and sqlite store the same line bytes, so they differ in where the lines live, never in what they say. Every backend's `Load` reads one snapshot: a session deleted under a concurrent load answers `thread.ErrNotFound` or the whole session, never a header without its entries. ADR 0026 lists three ways to store sessions: your own `thread.Storage` ([Write your own thread.Storage](https://weftgo.dev/docs/sessions/custom-storage/)), `thread/sqlite`, and a Postgres backend that it designs but that does not ship in v0.20.2. #### JSONL [`jsonl.Open(dir, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open) returns a storage rooted at `dir`: one `.jsonl` file per session, the directory created `0700` when missing and files created `0600`. `Create` writes the header and fsyncs the file and the directory; `Append` writes a batch in one write and fsyncs it. The writer lock is an advisory file lock taken on a session's first write and held until the session is released, deleted, or the process exits; the kernel drops it however the holder exits. It costs one open file descriptor per session the process is writing. On a platform with no advisory file lock (not unix, not Windows), `jsonl.Open` fails wrapping `errors.ErrUnsupported` unless you pass `thread.NoLock()`. A crash mid-append leaves at most a torn final line. A load drops it and reports it in `LoadReport.Torn`; the next writer truncates it before its first append. `List` reads every header in the directory on each call, so its cost grows with the number of sessions. The package examples are [`ExampleOpen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#example-Open), [`ExampleOpen_release`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#example-Open-Release) (a second `Storage` gets `ErrLocked` until the holder releases), [`ExampleOpen_tornTail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#example-Open-TornTail) and [`ExampleOpen_noLock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#example-Open-NoLock). Since thread 0.2.0 a header is read to its end, so a short read no longer hides a session from `List`. #### SQLite [`sqlite.Open(path, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#Open) opens, creating if needed, one database file holding every session, on the CGO-free `modernc.org/sqlite` driver. `thread/sqlite` is the only package that imports the driver; `thread` never does. (It was its own module when it shipped in thread 0.4.0; in v0.20.2 it is a package of `github.com/weftgo/weft`.) `":memory:"` opens a private in-process database. The file is created `0600`, its directory `0700`; `-wal` and `-shm` side files sit beside it. Every `Append` is one committed transaction, so a process that dies never loses an `Append` that returned. The one-writer rule is a lock row per session; a holder whose process died on this host is taken over, and a holder on another host is never judged dead from here (see [Operate sessions](https://weftgo.dev/docs/sessions/operations/) and `sqlite.BreakLock`). A second `Storage` over the same file is refused like another process: ```go title="sessions/storage.go" path := filepath.Join(dir, "sessions.db") st, err := sqlite.Open(path) // every session in one file, WAL if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_sqlite", "a")) if err != nil { return err } if err := s.SetInfo(ctx, "Refund for order 1234", nil); err != nil { return err } // A second Storage over the same file: another process, in effect. other, err := sqlite.Open(path) if err != nil { return err } reader, err := thread.Open(ctx, other, "s_sqlite", agent, ctxWindow, ids("", "b")) if err != nil { return err } fmt.Fprintln(w, "reader sees:", reader.Title()) err = reader.SetInfo(ctx, "Refund denied", nil) fmt.Fprintln(w, "second writer:", errors.Is(err, thread.ErrLocked)) ``` [sessions/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go) ```text reader sees: Refund for order 1234 second writer: true ``` Schema migrations are embedded and tracked in the `thread_migrations` table, so a thread database can share a file with the local sink's `obsdb_migrations`. A file migrated by a newer weft fails `Open` with [`sqlite.ErrNewerSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#ErrNewerSchema). The session title is kept in a column, so `Query.TitleSearch` never reads a session's entries. The package examples are [`ExampleOpen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#example-Open) and [`ExampleOpen_secondWriter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#example-Open-SecondWriter). #### Memory [`thread.Memory(opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Memory) keeps sessions in a map behind a mutex, gone when the process is: ```go title="sessions/storage.go" st := thread.Memory() // in process: tests and examples ``` [sessions/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go) It is for tests, examples, and the reference the durable backends are compared against. It takes the open options: `Salvage` and `OpenLogger` mean what they mean on disk, and the fsync options and `NoLock` are no-ops. Its `Storage` methods never return `ErrLocked`, since there is no second process; two Sessions on one `Memory` are still kept to one writer by its lease. The package example is [`ExampleMemory`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Memory). ### Open options Every backend's `Open` takes the same [`thread.OpenOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenOption) values, so you never learn a backend to say `Salvage`: | Option | Effect | |---|---| | [`thread.FsyncEveryAppend()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncEveryAppend) | The default: every `Append` fsyncs before it returns, so an accepted entry is durable before anything replies on it. | | [`thread.FsyncOnFlush()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncOnFlush) | Defer the fsync to the `Flusher` capability: a Session flushes after the prompt, every receipt and bookkeeping write, and at the turn's end; the steps in between are not synced. A crash can lose the unsynced tail of a turn, never a synced one. On sqlite it opens the database with `synchronous=NORMAL` instead of `FULL`, and `Flush` runs `PRAGMA wal_checkpoint(PASSIVE)`: every commit survives the process dying, and a power cut can roll back the commits since the last checkpoint. | | [`thread.NoLock()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NoLock) | Open a file backend without its cross-process lock. One writer per session becomes your promise: a second process can interleave lines. sqlite and Memory accept it and keep locking. | | [`thread.OpenLogger(l)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenLogger) | Where the backend reports what it repairs on its own: a torn tail truncated, a dead holder's lock taken over. One `Warn` line each; the default is `slog.Default()`. | | [`thread.Salvage()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Salvage) | Skip malformed lines instead of failing the load, each skip reported in `LoadReport.Skipped`. Data from a newer weft still fails with `ErrNewerFormat`. | #### Recover a damaged file with Salvage A damaged line that is not the final one fails the load with `thread.ErrCorrupt`, carried by a [`*thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CorruptError) that names the session and the 1-based line (the header is line 1). Here the reply's line is damaged, and the session is opened twice: ```go title="sessions/storage.go" st, err := jsonl.Open(sessions) if err != nil { return err } _, err = thread.Open(ctx, st, "s_jsonl", agent, ctxWindow) var corrupt *thread.CorruptError if errors.As(err, &corrupt) { fmt.Fprintln(w, "refused:", errors.Is(err, thread.ErrCorrupt), "line", corrupt.Line) } salvaged, err := jsonl.Open(sessions, thread.Salvage()) if err != nil { return err } s, err := thread.Open(ctx, salvaged, "s_jsonl", agent, ctxWindow) if err != nil { return err } report := s.LoadReport() fmt.Fprintln(w, "skipped lines:", report.Skipped, "orphaned:", report.Orphaned) ``` [sessions/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go) ```text refused: true line 3 skipped lines: [3] orphaned: [e_a3] ``` Under `Salvage` the load skips line 3 and the session opens. The turn entry whose parent was on that line is kept and listed as orphaned; a context below it starts at that entry. `Open` also logs the repair once through the agent's logger. Use `Salvage` to recover: open with it, read [`s.LoadReport()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.LoadReport), and decide whether the session is still usable. The package example is [`ExampleSalvage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Salvage). Storage-level loads report through [`thread.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport): `Torn` for a dropped final line, `Skipped` for salvaged ones. ### List sessions [`thread.List(ctx, st, q)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#List) returns a [`thread.Page`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Page) of session headers, never entries, and needs no Session. A [`thread.Query`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Query) filters and pages it. The demo creates five sessions, each with header metadata and a title: ```go title="sessions/storage.go" s, err := thread.Create(ctx, st, agent, ctxWindow, ids(c.id, "a"), at(base.Add(time.Duration(i)*time.Minute)), thread.WithMeta(map[string]string{"env": c.env})) // header metadata: what Query.Meta matches if err != nil { return err } if err := s.SetInfo(ctx, c.title, nil); err != nil { // the title: what Query.TitleSearch matches return err } ``` [sessions/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go) Then it filters, and pages through everything two at a time: ```go title="sessions/storage.go" page, err := thread.List(ctx, st, thread.Query{ Meta: map[string]string{"env": "prod"}, // every pair present, exactly TitleSearch: "checkout", // the current title, any case }) if err != nil { return err } for _, h := range page.Sessions { // newest first, headers only fmt.Fprintln(w, "match:", h.ID) } fmt.Fprintln(w, "total:", page.Total) q := thread.Query{Limit: 2} for { page, err := thread.List(ctx, st, q) if err != nil { return err } if len(page.Sessions) == 0 { break } var got []string for _, h := range page.Sessions { got = append(got, h.ID) } fmt.Fprintln(w, "page:", got, "of", page.Total) last := page.Sessions[len(page.Sessions)-1] // the keyset cursor q.Before, q.BeforeID = last.Created, last.ID } ``` [sessions/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go) ```text match: s_c match: s_a total: 2 page: [s_e s_d] of 5 page: [s_c s_b] of 5 page: [s_a] of 5 ``` - **`Page.Sessions`** is newest first by `Created`, ties by id descending. **`Page.Total`** counts every session the filters match, ignoring the cursor and the limit. - **`Query.Meta`** matches every pair exactly against the header's create-time metadata, what `thread.WithMeta` and `thread.PublicID` set. A key must be present to match, and a key a later `SetInfo` added never matches. - **`Query.TitleSearch`** matches the session's current title (the last info entry with a non-empty title, `s.Title()`) case-insensitively as a substring. It is the one filter that may read beyond headers: jsonl reads each candidate's file. - **`Query.Limit`** caps the page: 0 or negative means 50, above 500 clamps to 500. - **`Query.Before` and `Query.BeforeID`** are a keyset cursor over the same order: pass the last session of the previous page. `Before` alone returns only sessions created strictly before it and skips the rest of a group sharing that time; set `BeforeID` to walk through ties. There are no offsets: they drift under concurrent inserts. `List` skips what it cannot decode (a torn or foreign header, a newer envelope) without an error; `Load` on that id says why. The examples are [`ExampleList`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-List), [`ExampleQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Query) and [`ExampleQuery_keysetCursor`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Query-KeysetCursor). #### Delete a session [`thread.Delete(ctx, st, id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Delete) removes a session and its entries. It is the one operation that removes data: ```go title="sessions/storage.go" if err := thread.Delete(ctx, st, "s_b"); err != nil { return err } _, err = thread.Open(ctx, st, "s_b", agent, ctxWindow) fmt.Fprintln(w, "after Delete:", errors.Is(err, thread.ErrNotFound)) ``` [sessions/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go) ```text after Delete: true ``` An id the storage does not hold fails with [`thread.ErrNotFound`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotFound), as `Load` and `Append` do. `Create` over an id the storage holds fails with [`thread.ErrExists`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrExists): a session is never silently replaced. `Delete` does not look for open Sessions: through the `Storage` value the writer uses it always removes, and the writer's next write fails with `ErrNotFound`; through another `Storage` value it fails with `ErrLocked` while a writer holds the session. Close the session first. The package example is [`ExampleDelete`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Delete). ### Watch a session [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) is the optional capability that tails a session as it is appended to, for a reader in another process. jsonl and sqlite implement it. [`Watch(ctx, session, after)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) yields the entries after the entry `after` names (`""`: from the start) in arrival order, each once, then keeps yielding as appends land, until `ctx` ends: ```go title="sessions/storage.go" reader, err := jsonl.Open(sessions) // a reader: it never locks if err != nil { return err } wctx, stop := context.WithCancel(ctx) defer stop() tail, err := reader.(thread.Watcher).Watch(wctx, "s_watch", "") // "": from the first entry if err != nil { return err } seen := make(chan thread.Entry) go func() { defer close(seen) for e, err := range tail { if err != nil { return } seen <- e } }() turn, err := s.Send(ctx, weft.User("How long do refunds take?")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } for e := range seen { fmt.Fprintln(w, "watched:", kind(e)) if _, ok := e.(thread.TurnEntry); ok { stop() // the turn's ledger: the turn has landed } } ``` [sessions/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go) ```text watched: message (user) watched: message (assistant) watched: turn ``` A watcher is a reader that waits: it never locks, and the loop may call the same `Storage`. An unknown session, or an `after` the session does not hold, fails before the first yield. The stream ends with one error when the session is deleted (or deleted and created again) under it, `ErrNotFound`, or when it meets data it cannot decode. A torn final line is a write in flight: it is yielded once complete. The jsonl and sqlite watchers poll every 200 ms. The package example is [`ExampleWatcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Watcher). ### Complete example `sessions/storage.go` writes a JSONL session, salvages it, refuses a second SQLite writer, lists, deletes and watches: ```go title="sessions/storage.go" package main import ( "context" "errors" "fmt" "io" "os" "path/filepath" "strings" "time" "github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/thread/jsonl" "github.com/weftgo/weft/thread/sqlite" "github.com/weftgo/weft/wefttest" ) // demoStorage is the page "Store sessions: JSONL, SQLite or memory". func demoStorage(ctx context.Context, w io.Writer, dir string) error { agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("Refunds take three to five days."), )) if err := storeJSONL(ctx, w, dir, agent); err != nil { return err } if err := salvage(ctx, w, dir, agent); err != nil { return err } if err := storeSQLite(ctx, w, dir, agent); err != nil { return err } if err := listSessions(ctx, w, agent); err != nil { return err } return watch(ctx, w, dir, agent) } func storeJSONL(ctx context.Context, w io.Writer, dir string, agent *weft.Agent) error { sessions := filepath.Join(dir, "sessions") st, err := jsonl.Open(sessions, thread.FsyncOnFlush()) // fsync at the turn's end, not every append if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_jsonl", "a"), at(base)) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } if err := s.Close(ctx); err != nil { return err } data, err := os.ReadFile(filepath.Join(sessions, "s_jsonl.jsonl")) if err != nil { return err } lines := strings.Split(strings.TrimSpace(string(data)), "\n") fmt.Fprintln(w, "lines:", len(lines)) fmt.Fprintln(w, lines[0]) fmt.Fprintln(w, lines[1]) return nil } // salvage damages the reply's line in s_jsonl's file, then loads it twice: // without Salvage and with it. func salvage(ctx context.Context, w io.Writer, dir string, agent *weft.Agent) error { sessions := filepath.Join(dir, "sessions") path := filepath.Join(sessions, "s_jsonl.jsonl") data, err := os.ReadFile(path) if err != nil { return err } lines := strings.Split(string(data), "\n") lines[2] = `{"type":"message","id":` // line 3, the reply: a damaged line, not a torn tail if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")), 0o600); err != nil { return err } st, err := jsonl.Open(sessions) if err != nil { return err } _, err = thread.Open(ctx, st, "s_jsonl", agent, ctxWindow) var corrupt *thread.CorruptError if errors.As(err, &corrupt) { fmt.Fprintln(w, "refused:", errors.Is(err, thread.ErrCorrupt), "line", corrupt.Line) } salvaged, err := jsonl.Open(sessions, thread.Salvage()) if err != nil { return err } s, err := thread.Open(ctx, salvaged, "s_jsonl", agent, ctxWindow) if err != nil { return err } report := s.LoadReport() fmt.Fprintln(w, "skipped lines:", report.Skipped, "orphaned:", report.Orphaned) return nil } func storeSQLite(ctx context.Context, w io.Writer, dir string, agent *weft.Agent) error { path := filepath.Join(dir, "sessions.db") st, err := sqlite.Open(path) // every session in one file, WAL if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_sqlite", "a")) if err != nil { return err } if err := s.SetInfo(ctx, "Refund for order 1234", nil); err != nil { return err } // A second Storage over the same file: another process, in effect. other, err := sqlite.Open(path) if err != nil { return err } reader, err := thread.Open(ctx, other, "s_sqlite", agent, ctxWindow, ids("", "b")) if err != nil { return err } fmt.Fprintln(w, "reader sees:", reader.Title()) err = reader.SetInfo(ctx, "Refund denied", nil) fmt.Fprintln(w, "second writer:", errors.Is(err, thread.ErrLocked)) if err := reader.Close(ctx); err != nil { return err } return s.Close(ctx) } func listSessions(ctx context.Context, w io.Writer, agent *weft.Agent) error { st := thread.Memory() // in process: tests and examples seed := []struct{ id, env, title string }{ {"s_a", "prod", "Checkout bug"}, {"s_b", "dev", "Login flow"}, {"s_c", "prod", "Checkout again"}, {"s_d", "prod", "Refund for order 1234"}, {"s_e", "prod", "Address change"}, } for i, c := range seed { s, err := thread.Create(ctx, st, agent, ctxWindow, ids(c.id, "a"), at(base.Add(time.Duration(i)*time.Minute)), thread.WithMeta(map[string]string{"env": c.env})) // header metadata: what Query.Meta matches if err != nil { return err } if err := s.SetInfo(ctx, c.title, nil); err != nil { // the title: what Query.TitleSearch matches return err } if err := s.Close(ctx); err != nil { return err } } page, err := thread.List(ctx, st, thread.Query{ Meta: map[string]string{"env": "prod"}, // every pair present, exactly TitleSearch: "checkout", // the current title, any case }) if err != nil { return err } for _, h := range page.Sessions { // newest first, headers only fmt.Fprintln(w, "match:", h.ID) } fmt.Fprintln(w, "total:", page.Total) q := thread.Query{Limit: 2} for { page, err := thread.List(ctx, st, q) if err != nil { return err } if len(page.Sessions) == 0 { break } var got []string for _, h := range page.Sessions { got = append(got, h.ID) } fmt.Fprintln(w, "page:", got, "of", page.Total) last := page.Sessions[len(page.Sessions)-1] // the keyset cursor q.Before, q.BeforeID = last.Created, last.ID } if err := thread.Delete(ctx, st, "s_b"); err != nil { return err } _, err = thread.Open(ctx, st, "s_b", agent, ctxWindow) fmt.Fprintln(w, "after Delete:", errors.Is(err, thread.ErrNotFound)) return nil } // watch tails a session from a second Storage while the first one writes // a turn into it. func watch(ctx context.Context, w io.Writer, dir string, agent *weft.Agent) error { sessions := filepath.Join(dir, "sessions") st, err := jsonl.Open(sessions) if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_watch", "a")) if err != nil { return err } reader, err := jsonl.Open(sessions) // a reader: it never locks if err != nil { return err } wctx, stop := context.WithCancel(ctx) defer stop() tail, err := reader.(thread.Watcher).Watch(wctx, "s_watch", "") // "": from the first entry if err != nil { return err } seen := make(chan thread.Entry) go func() { defer close(seen) for e, err := range tail { if err != nil { return } seen <- e } }() turn, err := s.Send(ctx, weft.User("How long do refunds take?")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } for e := range seen { fmt.Fprintln(w, "watched:", kind(e)) if _, ok := e.(thread.TurnEntry); ok { stop() // the turn's ledger: the turn has landed } } return s.Close(ctx) } ``` [sessions/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`: ```sh go run ./sessions storage go test ./sessions ``` ```text lines: 4 {"type":"session","weft":1,"id":"s_jsonl","created":"2026-10-18T09:00:00Z"} {"type":"message","id":"e_a1","created":"2026-10-18T09:00:00Z","message":{"role":"user","content":[{"type":"text","text":"Where is order 1234?"}]},"run_id":"s_jsonl-t1"} refused: true line 3 skipped lines: [3] orphaned: [e_a3] reader sees: Refund for order 1234 second writer: true match: s_c match: s_a total: 2 page: [s_e s_d] of 5 page: [s_c s_b] of 5 page: [s_a] of 5 after Delete: true watched: message (user) watched: message (assistant) watched: turn ``` Standard error carries one line: the salvage warning `Open` logs through the agent's logger, `WARN thread: session loaded with a repair session=s_jsonl torn_line=0 skipped_lines=[3] orphaned_entries=[e_a3]`. ### Best practices & gotchas - **Back up sqlite with SQLite's own backup, not `cp`.** Committed data can still be in `-wal`; use `.backup` or `VACUUM INTO`, or stop every writer and copy the three files. A jsonl directory can be copied at any time. (Source: `docs/thread-operations.md` §3) - **Run one writer host per directory or database.** jsonl's lock is only as good as the filesystem's `flock`, and sqlite on a shared filesystem is outside SQLite's supported envelope. (Source: `docs/thread-operations.md` §4) - **Use `NoLock` only where no lock exists or can be trusted.** Two processes writing one session under it interleave their lines. (Source: `thread/open.go:68-86`) - **Use `Salvage` to recover, not by default.** It hides damage from every load; open with it, read `LoadReport`, decide. It never skips newer data. (Source: `thread/open.go:31-44`; `docs/thread-operations.md` §6) - **Page with `Before` and `BeforeID` together.** `Before` alone skips sessions sharing the cursor's creation time. (Source: `thread/storage.go:100-113`) - **Close a session before you delete it.** `Delete` does not look for open Sessions; a turn running at that moment loses the entries it had yet to write. (Source: `thread/session.go:826` Delete godoc) - **`Query.Meta` sees create-time metadata only.** Put what you filter on in `WithMeta` at `Create`; `SetInfo` keys never match. (Source: `thread/storage.go:117-125`) ### See also - [What is a session?](https://weftgo.dev/docs/sessions/overview/) - [Write your own thread.Storage](https://weftgo.dev/docs/sessions/custom-storage/) - [Operate sessions in production](https://weftgo.dev/docs/sessions/operations/): backups, locks, shutdown - [The session log format](https://weftgo.dev/docs/sessions/format/) Symbols used: [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage) · [`jsonl.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open) · [`sqlite.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#Open) · [`sqlite.ErrNewerSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#ErrNewerSchema) · [`sqlite.BreakLock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#BreakLock) · [`thread.Memory`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Memory) · [`thread.OpenOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenOption) · [`thread.FsyncEveryAppend`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncEveryAppend) · [`thread.FsyncOnFlush`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncOnFlush) · [`thread.NoLock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NoLock) · [`thread.OpenLogger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenLogger) · [`thread.Salvage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Salvage) · [`thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CorruptError) · [`thread.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport) · [`Session.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.LoadReport) · [`thread.List`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#List) · [`thread.Query`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Query) · [`thread.Page`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Page) · [`thread.Delete`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Delete) · [`thread.ErrNotFound`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotFound) · [`thread.ErrExists`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrExists) · [`thread.ErrLocked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrLocked) · [`thread.ErrCorrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCorrupt) · [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) · [`thread.WithMeta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithMeta) · [`Session.SetInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.SetInfo) · [`thread.Create`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Create) · [`thread.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Open) --- # Write your own thread.Storage URL: https://weftgo.dev/docs/sessions/custom-storage/ Markdown: https://weftgo.dev/docs/sessions/custom-storage.md > Implement the five thread.Storage methods over your own store, add the optional capabilities by type assertion, resolve the open options with thread/backend, and prove it with threadtest. A session backend is any type that implements [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage): `Create`, `Append`, `Load`, `List` and `Delete`. Extra behaviour, such as a writer lock or a live tail, comes from optional interfaces the session finds by type assertion. [`threadtest.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#Run) is the conformance table every backend runs before it may call itself one. Every shipped backend passes it, and [`threadtest.RunTurns`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunTurns) beside it; passing both is necessary, not sufficient, and a durable store also runs the [crash tests](https://weftgo.dev/docs/sessions/custom-storage/#crash-tests). `customstorage/mapstore.go` is a backend over a map, in about 200 lines. It stores the header and each entry as the JSON line a file backend would write: ```go title="customstorage/mapstore.go" // MapStore is a thread.Storage that keeps every session in a map: the // header and each entry as the JSON line a file backend would write. // Storing the encoded lines, not the values, is what keeps Load from // aliasing what is stored. It implements the five methods and none of // the optional capabilities. type MapStore struct { mu sync.Mutex sessions map[string]*stored cfg backend.Config } type stored struct { header []byte // the header line lines [][]byte // one line per entry, in append order title string // the last non-empty info title, for Query.TitleSearch } // NewMapStore takes the shared open vocabulary every backend accepts. A // map buffers, locks and repairs nothing, so each option is accepted and // is a no-op here, as thread/backend asks of a backend it means nothing to. func NewMapStore(opts ...thread.OpenOption) *MapStore { return &MapStore{sessions: map[string]*stored{}, cfg: backend.Resolve(opts...)} } var _ thread.Storage = (*MapStore)(nil) ``` [customstorage/mapstore.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/customstorage/mapstore.go) Its test runs the table: ```go title="customstorage/main_test.go" // TestConformance runs thread/threadtest's table against MapStore: a // fresh store per subtest. The rows for capabilities MapStore does not // implement (Flusher, Releaser, Leaser, Watcher, the raw-injection // corruption rows) skip. func TestConformance(t *testing.T) { threadtest.Run(t, func(*testing.T) thread.Storage { return NewMapStore() }) } // TestTurns runs the session-level rows a backend carries beside Run: // the turn machinery's durable shapes, reloaded from the store. func TestTurns(t *testing.T) { threadtest.RunTurns(t, func(*testing.T) thread.Storage { return NewMapStore() }) } ``` [customstorage/main_test.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/customstorage/main_test.go) `go test ./customstorage` passes: every row of `Run` and `RunTurns` that applies to a backend without capabilities. ### The Storage interface Each method has a contract that `threadtest` checks. Every method takes `ctx` first and fails before writing anything when it is already canceled. Implementations must be safe for concurrent use. **`Create(ctx, h)`** writes a session's header. The id must pass `thread.ValidID`, because some backend uses it as a path component; a zero `Header.Weft` means the current `thread.FormatVersion`, and any other envelope is rejected. An id the storage holds fails with `thread.ErrExists`: ```go title="customstorage/mapstore.go" // Create writes the header. The id must pass thread.ValidID, a zero // envelope means the current format, and an existing id is ErrExists. func (m *MapStore) Create(ctx context.Context, h thread.Header) error { if err := ctx.Err(); err != nil { return err // a canceled context fails before anything is written } if !thread.ValidID(h.ID) { return fmt.Errorf("mapstore: invalid session id %q", h.ID) } if h.Weft != 0 && h.Weft != thread.FormatVersion { return fmt.Errorf("mapstore: header envelope %d, want %d", h.Weft, thread.FormatVersion) } line, err := json.Marshal(h) // a zero Weft is written as FormatVersion if err != nil { return err } m.mu.Lock() defer m.mu.Unlock() if _, ok := m.sessions[h.ID]; ok { return fmt.Errorf("mapstore: %s: %w", h.ID, thread.ErrExists) } m.sessions[h.ID] = &stored{header: line} return nil } ``` [customstorage/mapstore.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/customstorage/mapstore.go) **`Append(ctx, session, entries...)`** adds entries in arrival order. A batch is validated whole before anything is written, and it is atomic against the writer's death: after a crash a `Load` returns all of it or none. An unknown session fails with `thread.ErrNotFound`; one another writer holds, with `thread.ErrLocked`: ```go title="customstorage/mapstore.go" // Append encodes the whole batch before it stores any of it: one entry // that does not encode rejects the batch, so it lands whole or not at all. func (m *MapStore) Append(ctx context.Context, session string, entries ...thread.Entry) error { if err := ctx.Err(); err != nil { return err } lines := make([][]byte, 0, len(entries)) title := "" for _, e := range entries { line, err := json.Marshal(e) // every entry kind carries its "type" if err != nil { return fmt.Errorf("mapstore: %s: encode entry: %w", session, err) } lines = append(lines, line) if info, ok := e.(thread.InfoEntry); ok && info.Title != "" { title = info.Title } } m.mu.Lock() defer m.mu.Unlock() s, ok := m.sessions[session] if !ok { return fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound) } s.lines = append(s.lines, lines...) if title != "" { s.title = title } return nil } ``` [customstorage/mapstore.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/customstorage/mapstore.go) **`Load(ctx, session)`** returns the header and every entry in append order, plus a [`*thread.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport) naming a dropped torn tail or skipped lines, nil when clean. The values must never alias what is stored. Decode with [`thread.UnmarshalEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#UnmarshalEntry) to keep the loud rules: an unknown kind or a newer `"v"` is `thread.ErrNewerFormat`, a malformed line `thread.ErrCorrupt` naming the line in a [`*thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CorruptError): ```go title="customstorage/mapstore.go" // Load decodes a snapshot taken under the lock, so a concurrent Delete // yields the whole session or ErrNotFound. Decoding fresh copies is what // makes the result the caller's to mutate; thread's own decoder keeps the // loud rules (an unknown kind or a newer "v" is ErrNewerFormat). func (m *MapStore) Load(ctx context.Context, session string) (thread.Header, []thread.Entry, *thread.LoadReport, error) { if err := ctx.Err(); err != nil { return thread.Header{}, nil, nil, err } m.mu.Lock() s, ok := m.sessions[session] var header []byte var lines [][]byte if ok { header, lines = s.header, slices.Clone(s.lines) } m.mu.Unlock() if !ok { return thread.Header{}, nil, nil, fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound) } var h thread.Header if err := json.Unmarshal(header, &h); errors.Is(err, thread.ErrNewerFormat) { return thread.Header{}, nil, nil, err // a newer envelope: never ErrCorrupt } else if err != nil { return thread.Header{}, nil, nil, &thread.CorruptError{Session: session, Line: 1, Err: err} } entries := make([]thread.Entry, 0, len(lines)) for i, line := range lines { e, err := thread.UnmarshalEntry(line) if errors.Is(err, thread.ErrNewerFormat) { return thread.Header{}, nil, nil, err // newer, not damaged: never a skip } if err != nil { return thread.Header{}, nil, nil, &thread.CorruptError{Session: session, Line: i + 2, Err: err} } entries = append(entries, e) } return h, entries, nil, nil // nil report: nothing dropped or skipped } ``` [customstorage/mapstore.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/customstorage/mapstore.go) **`List(ctx, q)`** returns a page of headers, never entries. `Query.Meta` matches the header's metadata, `Query.TitleSearch` the last non-empty info title, the order is newest first with ties by id descending, `Before` and `BeforeID` are a keyset cursor, a limit of 0 means 50 and anything above 500 clamps to 500, and `Total` ignores the cursor and the limit ([List sessions](https://weftgo.dev/docs/sessions/storage/#list-sessions)): ```go title="customstorage/mapstore.go" // List filters, orders newest first (ties by id, descending), applies the // keyset cursor and then the limit; Total ignores the cursor and limit. func (m *MapStore) List(ctx context.Context, q thread.Query) (thread.Page, error) { if err := ctx.Err(); err != nil { return thread.Page{}, err } m.mu.Lock() var match []thread.Header for _, s := range m.sessions { var h thread.Header if err := json.Unmarshal(s.header, &h); err != nil { continue // List skips what it cannot decode; Load names why } if !metaMatches(h.Meta, q.Meta) { continue } if q.TitleSearch != "" && !strings.Contains(strings.ToLower(s.title), strings.ToLower(q.TitleSearch)) { continue } match = append(match, h) } m.mu.Unlock() slices.SortFunc(match, func(a, b thread.Header) int { if c := b.Created.Compare(a.Created); c != 0 { return c } return cmp.Compare(b.ID, a.ID) }) page := thread.Page{Total: len(match)} limit := q.Limit switch { case limit <= 0: limit = 50 case limit > 500: limit = 500 } for _, h := range match { if !q.Before.IsZero() { older := h.Created.Before(q.Before) tiedAfter := q.BeforeID != "" && h.Created.Equal(q.Before) && h.ID < q.BeforeID if !older && !tiedAfter { continue } } if len(page.Sessions) == limit { break } page.Sessions = append(page.Sessions, h) } return page, nil } // metaMatches: every wanted key present, every value equal. func metaMatches(have, want map[string]string) bool { for k, v := range want { if got, ok := have[k]; !ok || got != v { return false } } return true } ``` [customstorage/mapstore.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/customstorage/mapstore.go) **`Delete(ctx, session)`** removes a session; an unknown one is `ErrNotFound`, one another `Storage` or process holds as its writer is `ErrLocked`. A hold of this `Storage` value's own does not refuse it. Nothing else in the interface removes data: ```go title="customstorage/mapstore.go" // Delete removes the session; nothing else in the interface removes data. func (m *MapStore) Delete(ctx context.Context, session string) error { if err := ctx.Err(); err != nil { return err } m.mu.Lock() defer m.mu.Unlock() if _, ok := m.sessions[session]; !ok { return fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound) } delete(m.sessions, session) return nil } ``` [customstorage/mapstore.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/customstorage/mapstore.go) Then a session runs on it like on any backend: ```go title="customstorage/main.go" st := NewMapStore() s, err := thread.Create(ctx, st, agent, thread.IDs(fixedIDs("s_map")), window) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } if err := s.Close(ctx); err != nil { return err } again, err := thread.Open(ctx, st, "s_map", agent, window) // Load, through the interface if err != nil { return err } fmt.Fprintln(w, "reopened:", len(again.Context()), "messages") turn, err = again.Send(ctx, weft.User("When will it arrive?")) if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text(), "run:", turn.RunID()) if err := again.Close(ctx); err != nil { return err } fmt.Fprintln(w, "stored:", st.Sessions()) _, isLeaser := thread.Storage(st).(thread.Leaser) fmt.Fprintln(w, "Leaser:", isLeaser) // no lease: two Sessions on one MapStore both write ``` [customstorage/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/customstorage/main.go) ```text reopened: 2 messages answer: It should arrive on Friday. run: s_map-t2 stored: [s_map] Leaser: false ``` ### Optional capabilities Capabilities are small interfaces discovered by type assertion, so `Storage` never grows (ADR 0011 §5). Implement the ones your store can honour: | Interface | Methods | What it gives | |---|---|---| | [`thread.Flusher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Flusher) | `Flush(ctx, session)` | Completes buffered durability work: with `FsyncOnFlush` an append writes without syncing and `Flush` makes the session durable. With the default policy it is a no-op that still returns any error held for the session. A missing session is `ErrNotFound`. | | [`thread.Releaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Releaser) | `Release(ctx, session)` | Ends this writer's hold on a session: flush, then let another `Storage` or process write it. A later `Append` re-acquires the hold. | | [`thread.Leaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) | `Acquire(ctx, session, holder)`, `Yield(ctx, session, holder)` | The per-Session writer lease that keeps two `Session` values on one `Storage` value to one writer. | | [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) | `Watch(ctx, session, after)` | The live tail ([Watch a session](https://weftgo.dev/docs/sessions/storage/#watch-a-session)). | `MapStore` implements none of them, so its last output line is `Leaser: false`. #### Leases The backend's lock tells `Storage` values and processes apart; it cannot tell two Sessions on one `Storage` value apart, because `Append` names a session, not a writer. A lease can. A Session calls [`Acquire`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) before every write, naming itself with `holder`, a comparable token it owns: - `Acquire` takes the backend's cross-instance lock as a first `Append` would (`ErrLocked` when another `Storage` or process holds the session, a torn tail repaired), then the lease: `ErrLocked` naming the session when a different holder has it on this `Storage` value. For the holder that has it, it is idempotent and does no I/O. - It reports the number of complete entry lines the storage holds (the lines `Load` accounts for, including those skipped under `Salvage`, never a torn tail) and the stored header's `Created`. A Session compares both with what it loaded; a difference is `thread.ErrStale`. - [`Yield`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) ends the holder's lease and the storage's hold with it. When a different holder has the lease, it releases nothing and returns nil. A Session's `Close` yields. The lease is bookkeeping over the lock, not a second lock: the `Storage` methods do not consult it. It ends when its holder yields, when the session is released or deleted through this `Storage` value, or with the process. Without `Leaser`, two Sessions on one value of your backend both write, each blind to the other, and the `ErrStale` check does not exist. #### Releaser `Release` speaks for the whole `Storage` value: it ends a lease whoever holds it, which is why a Session closes through `Yield` when the backend offers it. It must not race the session's own `Append`; it is the last call of a writer that is done. Releasing a session this `Storage` does not hold is a no-op; one the storage does not hold at all is `ErrNotFound`. A backend that does not lock (Memory) ends the lease and checks that the session exists. The package example is [`ExampleReleaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Releaser). ### Resolve open options Applications pass `thread`'s open options (`Salvage`, `FsyncEveryAppend`, `FsyncOnFlush`, `NoLock`, `OpenLogger`) to your constructor; package [`thread/backend`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/backend) turns them into what a backend acts on. Applications never import it. [`backend.Resolve(opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/backend#Resolve) folds the options over the defaults (every append fsynced, the lock on, no salvage, `slog.Default()`) in the order given, skipping nil, and returns a [`backend.Config`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/backend#Config): | Field | Meaning | |---|---| | `Salvage` | A malformed line is a skip reported in the `LoadReport`, not `ErrCorrupt`. `ErrNewerFormat` is never salvaged. | | `SyncEveryAppend` | `true`, the default, fsyncs every `Append`; `false` defers it to `Flusher`. | | `NoLock` | Turn off the cross-process writer lock; the caller vouches that one process writes. | | `Logger` | Where the backend reports its own repairs: a torn tail, a taken-over lock. Never nil. | Read the config once, at open. An option your backend has no use for is accepted and documented as a no-op, never rejected: `MapStore` buffers, locks and repairs nothing, so all five are no-ops there. ### Conformance Package [`thread/threadtest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest) is the executable form of the `Storage` promises. Every shipped backend runs it; each table takes a factory that returns fresh storage per subtest: | Function | What it checks | Runs when | |---|---|---| | [`Run(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#Run) | The interface: round trips without aliasing, atomic batches, arrival order, `ErrNotFound` and invalid ids on every method, `Create` validation, paging through ties, limit normalisation, filters, delete, concurrency, canceled contexts. Then each capability's row. | always | | [`RunTurns(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunTurns) | The turn machinery's durable shapes on reload: a resume's join, receipts restored from the file alone. | call it beside `Run` | | [`RunWatch(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunWatch) | The `Watcher` table: backlog, resume point, each entry once, cancel, loud failures, a torn tail waited out, a replaced session ending with `ErrNotFound`. | `Run` calls it for a `Watcher` | | [`RunLeaser(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunLeaser) | `Acquire` idempotent and counting lines, a second holder `ErrLocked`, `Yield` handing over, `Release` and `Delete` ending the lease. | `Run` calls it for a `Leaser` | | [`RunOneWriter(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunOneWriter) | The same rule as two `Session` values meet it: `ErrLocked`, `ErrStale`, `Create` and `Fork` taking the lease. | `RunLeaser` runs it | | [`RunTwoWriters(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunTwoWriters) | Two independent `Storage` values over the same sessions: the second writer `ErrLocked` naming the session, readers never lock, `Release` and `Yield` hand over. | you provide the two-storage factory | `Run`'s corruption rows (unknown kind, newer `"v"`, malformed and torn lines, a newer header) need a store that can hold undecodable bytes. They run when your storage also implements [`threadtest.RawInjector`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RawInjector) (`Inject(ctx, session, data)` appends raw bytes, verbatim) and [`threadtest.RawHeaderInjector`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RawHeaderInjector) (`InjectHeader(ctx, session, line)` creates a session with that first line), and skip otherwise. Memory implements both by holding the raw bytes. For `MapStore` these rows skip, as do Flusher, Releaser, Leaser and Watch: ```sh go test -v -run TestConformance ./customstorage ``` ```text --- SKIP: TestConformance/CorruptionIsLoud (0.00s) --- SKIP: TestConformance/AppendAfterTornTail (0.00s) --- SKIP: TestConformance/HeaderCorruptionIsLoud (0.00s) --- SKIP: TestConformance/Flusher (0.00s) --- SKIP: TestConformance/Releaser (0.00s) --- SKIP: TestConformance/Leaser (0.00s) --- SKIP: TestConformance/Watch (0.00s) ``` #### Crash tests A durable backend also proves what survives a killed process. The harness re-executes the test binary as a child, kills it, and asserts through a fresh `Storage` over the same location: - [`threadtest.CrashTurn(t, helperTest, path, reopen)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashTurn) SIGKILLs the child mid-second-step and checks the first step is on disk. The child side is [`RunCrashTurnChild(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunCrashTurnChild), which creates the session [`CrashSession`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashSession) (`s_crashturn`) at the path in `WEFT_THREADTEST_CRASH_STORAGE`. - [`threadtest.CrashMatrix(t, helperTest, pathFor, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashMatrix) walks every session-layer write point (prompt, turn end, approval, decision, compaction, steer, pool receipt, branch, fork, the expiry sweep, the automatic trim, a queued send's accepted receipt and more), a fresh location per point. The child side is [`RunCrashMatrixChild(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunCrashMatrixChild). The parent asserts over the sessions the child creates, by id: [`CrashMatrixTurnID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashMatrixTurnID), `CrashMatrixParkID`, `CrashMatrixSteerID`, `CrashMatrixPoolID`, `CrashMatrixForkID` and `CrashMatrixKidID` (the pool points' child). `thread/jsonl` wires both in two pairs of tests: `TestCrashMatrix` calls `CrashMatrix` with `jsonl.Open`, and `TestCrashMatrixHelper` returns at once unless `WEFT_THREADTEST_CRASH_STORAGE` is set, then calls `RunCrashMatrixChild`. A map cannot survive its process, so `MapStore` runs neither. ### Complete example `customstorage/mapstore.go` is the backend; `customstorage/main.go` runs a session on it: ```go title="customstorage/mapstore.go" package main import ( "cmp" "context" "encoding/json" "errors" "fmt" "maps" "slices" "strings" "sync" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/thread/backend" ) // MapStore is a thread.Storage that keeps every session in a map: the // header and each entry as the JSON line a file backend would write. // Storing the encoded lines, not the values, is what keeps Load from // aliasing what is stored. It implements the five methods and none of // the optional capabilities. type MapStore struct { mu sync.Mutex sessions map[string]*stored cfg backend.Config } type stored struct { header []byte // the header line lines [][]byte // one line per entry, in append order title string // the last non-empty info title, for Query.TitleSearch } // NewMapStore takes the shared open vocabulary every backend accepts. A // map buffers, locks and repairs nothing, so each option is accepted and // is a no-op here, as thread/backend asks of a backend it means nothing to. func NewMapStore(opts ...thread.OpenOption) *MapStore { return &MapStore{sessions: map[string]*stored{}, cfg: backend.Resolve(opts...)} } var _ thread.Storage = (*MapStore)(nil) // Create writes the header. The id must pass thread.ValidID, a zero // envelope means the current format, and an existing id is ErrExists. func (m *MapStore) Create(ctx context.Context, h thread.Header) error { if err := ctx.Err(); err != nil { return err // a canceled context fails before anything is written } if !thread.ValidID(h.ID) { return fmt.Errorf("mapstore: invalid session id %q", h.ID) } if h.Weft != 0 && h.Weft != thread.FormatVersion { return fmt.Errorf("mapstore: header envelope %d, want %d", h.Weft, thread.FormatVersion) } line, err := json.Marshal(h) // a zero Weft is written as FormatVersion if err != nil { return err } m.mu.Lock() defer m.mu.Unlock() if _, ok := m.sessions[h.ID]; ok { return fmt.Errorf("mapstore: %s: %w", h.ID, thread.ErrExists) } m.sessions[h.ID] = &stored{header: line} return nil } // Append encodes the whole batch before it stores any of it: one entry // that does not encode rejects the batch, so it lands whole or not at all. func (m *MapStore) Append(ctx context.Context, session string, entries ...thread.Entry) error { if err := ctx.Err(); err != nil { return err } lines := make([][]byte, 0, len(entries)) title := "" for _, e := range entries { line, err := json.Marshal(e) // every entry kind carries its "type" if err != nil { return fmt.Errorf("mapstore: %s: encode entry: %w", session, err) } lines = append(lines, line) if info, ok := e.(thread.InfoEntry); ok && info.Title != "" { title = info.Title } } m.mu.Lock() defer m.mu.Unlock() s, ok := m.sessions[session] if !ok { return fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound) } s.lines = append(s.lines, lines...) if title != "" { s.title = title } return nil } // Load decodes a snapshot taken under the lock, so a concurrent Delete // yields the whole session or ErrNotFound. Decoding fresh copies is what // makes the result the caller's to mutate; thread's own decoder keeps the // loud rules (an unknown kind or a newer "v" is ErrNewerFormat). func (m *MapStore) Load(ctx context.Context, session string) (thread.Header, []thread.Entry, *thread.LoadReport, error) { if err := ctx.Err(); err != nil { return thread.Header{}, nil, nil, err } m.mu.Lock() s, ok := m.sessions[session] var header []byte var lines [][]byte if ok { header, lines = s.header, slices.Clone(s.lines) } m.mu.Unlock() if !ok { return thread.Header{}, nil, nil, fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound) } var h thread.Header if err := json.Unmarshal(header, &h); errors.Is(err, thread.ErrNewerFormat) { return thread.Header{}, nil, nil, err // a newer envelope: never ErrCorrupt } else if err != nil { return thread.Header{}, nil, nil, &thread.CorruptError{Session: session, Line: 1, Err: err} } entries := make([]thread.Entry, 0, len(lines)) for i, line := range lines { e, err := thread.UnmarshalEntry(line) if errors.Is(err, thread.ErrNewerFormat) { return thread.Header{}, nil, nil, err // newer, not damaged: never a skip } if err != nil { return thread.Header{}, nil, nil, &thread.CorruptError{Session: session, Line: i + 2, Err: err} } entries = append(entries, e) } return h, entries, nil, nil // nil report: nothing dropped or skipped } // List filters, orders newest first (ties by id, descending), applies the // keyset cursor and then the limit; Total ignores the cursor and limit. func (m *MapStore) List(ctx context.Context, q thread.Query) (thread.Page, error) { if err := ctx.Err(); err != nil { return thread.Page{}, err } m.mu.Lock() var match []thread.Header for _, s := range m.sessions { var h thread.Header if err := json.Unmarshal(s.header, &h); err != nil { continue // List skips what it cannot decode; Load names why } if !metaMatches(h.Meta, q.Meta) { continue } if q.TitleSearch != "" && !strings.Contains(strings.ToLower(s.title), strings.ToLower(q.TitleSearch)) { continue } match = append(match, h) } m.mu.Unlock() slices.SortFunc(match, func(a, b thread.Header) int { if c := b.Created.Compare(a.Created); c != 0 { return c } return cmp.Compare(b.ID, a.ID) }) page := thread.Page{Total: len(match)} limit := q.Limit switch { case limit <= 0: limit = 50 case limit > 500: limit = 500 } for _, h := range match { if !q.Before.IsZero() { older := h.Created.Before(q.Before) tiedAfter := q.BeforeID != "" && h.Created.Equal(q.Before) && h.ID < q.BeforeID if !older && !tiedAfter { continue } } if len(page.Sessions) == limit { break } page.Sessions = append(page.Sessions, h) } return page, nil } // metaMatches: every wanted key present, every value equal. func metaMatches(have, want map[string]string) bool { for k, v := range want { if got, ok := have[k]; !ok || got != v { return false } } return true } // Delete removes the session; nothing else in the interface removes data. func (m *MapStore) Delete(ctx context.Context, session string) error { if err := ctx.Err(); err != nil { return err } m.mu.Lock() defer m.mu.Unlock() if _, ok := m.sessions[session]; !ok { return fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound) } delete(m.sessions, session) return nil } // Sessions returns the stored session ids, sorted — for the demo's output. func (m *MapStore) Sessions() []string { m.mu.Lock() defer m.mu.Unlock() return slices.Sorted(maps.Keys(m.sessions)) } ``` [customstorage/mapstore.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/customstorage/mapstore.go) ```go title="customstorage/main.go" // Command customstorage runs a weft/thread session on MapStore, a // thread.Storage written from scratch in mapstore.go: go run ./customstorage. // The model is scripted with wefttest, so it runs offline. main_test.go // proves the backend with thread/threadtest, the conformance table every // backend runs. package main import ( "context" "errors" "fmt" "io" "os" "github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/wefttest" ) func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func run(ctx context.Context, w io.Writer) error { agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("It should arrive on Friday."), )) st := NewMapStore() s, err := thread.Create(ctx, st, agent, thread.IDs(fixedIDs("s_map")), window) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } if err := s.Close(ctx); err != nil { return err } again, err := thread.Open(ctx, st, "s_map", agent, window) // Load, through the interface if err != nil { return err } fmt.Fprintln(w, "reopened:", len(again.Context()), "messages") turn, err = again.Send(ctx, weft.User("When will it arrive?")) if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text(), "run:", turn.RunID()) if err := again.Close(ctx); err != nil { return err } fmt.Fprintln(w, "stored:", st.Sessions()) _, isLeaser := thread.Storage(st).(thread.Leaser) fmt.Fprintln(w, "Leaser:", isLeaser) // no lease: two Sessions on one MapStore both write if err := thread.Delete(ctx, st, "s_map"); err != nil { return err } _, err = thread.Open(ctx, st, "s_map", agent) fmt.Fprintln(w, "after Delete:", errors.Is(err, thread.ErrNotFound)) return nil } // window is the model's context window, in tokens: it arms automatic // compaction, and without one each session logs a WARN at its first turn. var window = thread.ContextWindow(128_000) // fixedIDs mints the session id first, then e_1, e_2, … so the output is // the same on every run. func fixedIDs(session string) func() string { n := 0 return func() string { n++ if n == 1 { return session } return fmt.Sprintf("e_%d", n-1) } } ``` [customstorage/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/customstorage/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/customstorage) · run it from `docs-site/examples`: ```sh go run ./customstorage go test ./customstorage ``` ```text reopened: 2 messages answer: It should arrive on Friday. run: s_map-t2 stored: [s_map] Leaser: false after Delete: true ``` ### Best practices & gotchas - **Never return stored values from `Load` or `List`.** The caller may mutate them; `threadtest`'s round-trip row edits the result and loads again. Decode fresh copies, or deep-copy. (Source: `thread/storage.go:62-66`; `threadtest.Run` CreateLoadRoundTrip) - **Check `ctx` before every call.** A canceled context must fail `Create`, `Append`, `Load`, `List` and `Delete` alike, with nothing written. (Source: `threadtest.Run` ContextCancellation, `thread/threadtest/threadtest.go:1111-1136`) - **On `Load`, `Append`, `Delete` and the capability methods, answer invalid ids with `ErrNotFound`.** `Create` rejects them with any error. An id is a path component in some backend; `../escape` must not reach the filesystem. (Source: `threadtest.Run` InvalidIDs, CreateValidation, `thread/threadtest/threadtest.go:1243-1277`) - **Never wrap `ErrNewerFormat` as `ErrCorrupt`.** Newer data is not damage, and `Salvage` must never skip it; `MapStore.Load` returns it unwrapped from both the header and the entry decode. (Source: `thread/errors.go:60-75`; `thread/header.go:88-92`; AGENTS.md T5) - **Never write a session behind its Session.** An `st.Append` on a session a Session holds is invisible to that Session until the next `Open`, and its next write fails with `ErrStale`. (Source: AGENTS.md T1; `thread/session.go:318` Session godoc, One writer) - **Implement `Leaser` if two Sessions can share one `Storage` value.** Without it the one-writer rule between them is yours to keep. (Source: `thread/storage.go` Storage godoc, One writer) - **Run `RunTurns` beside `Run`.** It checks the shapes that only go wrong on a reload. (Source: `thread/threadtest/turns.go:15-25`) ### See also - [Store sessions: JSONL, SQLite or memory](https://weftgo.dev/docs/sessions/storage/) - [What is a session?](https://weftgo.dev/docs/sessions/overview/#one-writer): the writer lease - [The session log format](https://weftgo.dev/docs/sessions/format/): the lines a backend stores - [ADR 0026](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0026-thread-storage-backends.md): storage backends Symbols used: [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage) · [`thread.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Header) · [`thread.Entry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Entry) · [`thread.UnmarshalEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#UnmarshalEntry) · [`thread.InfoEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#InfoEntry) · [`thread.FormatVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FormatVersion) · [`thread.ValidID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ValidID) · [`thread.Query`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Query) · [`thread.Page`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Page) · [`thread.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport) · [`thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CorruptError) · [`thread.ErrNotFound`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotFound) · [`thread.ErrExists`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrExists) · [`thread.ErrLocked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrLocked) · [`thread.ErrStale`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrStale) · [`thread.ErrNewerFormat`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNewerFormat) · [`thread.ErrCorrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCorrupt) · [`thread.Flusher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Flusher) · [`thread.Releaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Releaser) · [`thread.Leaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) · [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) · [`thread.OpenOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenOption) · [`backend.Resolve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/backend#Resolve) · [`backend.Config`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/backend#Config) · [`threadtest.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#Run) · [`threadtest.RunTurns`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunTurns) · [`threadtest.RunWatch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunWatch) · [`threadtest.RunLeaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunLeaser) · [`threadtest.RunOneWriter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunOneWriter) · [`threadtest.RunTwoWriters`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunTwoWriters) · [`threadtest.RawInjector`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RawInjector) · [`threadtest.RawHeaderInjector`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RawHeaderInjector) · [`threadtest.CrashTurn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashTurn) · [`threadtest.RunCrashTurnChild`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunCrashTurnChild) · [`threadtest.CrashMatrix`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashMatrix) · [`threadtest.RunCrashMatrixChild`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunCrashMatrixChild) · [`threadtest.CrashSession`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashSession) · [`threadtest.CrashMatrixTurnID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashMatrixTurnID) · [`thread.Create`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Create) · [`thread.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Open) --- # Send turns and wait for them URL: https://weftgo.dev/docs/sessions/turns/ Markdown: https://weftgo.dev/docs/sessions/turns.md > Send a message to a weft/thread session with s.Send, wait for the turn with Wait, WaitContext or Done, stream its events, read its outcome, and pass run options. [`s.Send(ctx, msg, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Send) appends the message, runs the session's agent on the session's context plus that message, and returns a [`*thread.Turn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn) at once. The prompt is appended and flushed to the storage before the run starts. [`turn.Wait()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Wait) blocks for the result, and [`turn.Outcome()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Outcome) names how the turn ended. `sessions/turns.go`: ```go title="sessions/turns.go" s, err := thread.Create(ctx, thread.Memory(), agent, ctxWindow, ids("s_turns", "a")) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) // the prompt is durable when Send returns if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text()) fmt.Fprintln(w, "receipt:", turn.ID(), "run:", turn.RunID(), "outcome:", turn.Outcome()) ``` [sessions/turns.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go) ```text answer: Order 1234 shipped on Tuesday. receipt: e_a1 run: s_turns-t1 outcome: answered ``` The receipt is the prompt entry's id; the run id is `-t`. `ids` pins the ids for stable output, and `ctxWindow` gives the session its model's context window ([gotchas](https://weftgo.dev/docs/sessions/turns/#best-practices--gotchas)). ### Turns A [turn](https://weftgo.dev/docs/reference/glossary/#turn) is one accepted `Send` and the run it starts. In order: 1. `Send` captures its settings: the agent, the extra run options and the busy policy. 2. It appends the prompt entry and flushes it (thread rule T4). The entry carries the run id minted for the turn, so a reopened session never mints it again. 3. The run starts with `weft.Messages` set to the session's context and `weft.RunID` set to `-t`. Each step's messages are appended as they join the run's transcript. 4. At the end, success, failure or cancellation, a turn entry closes the ledger: run id, stop reason, usage, steps, the error text, pending approval calls. It lands in one atomic batch under `context.WithoutCancel`, so a caller who walks away still leaves a complete session. 5. Then the session runs its between-turn work, the automatic compaction when one is due, and the next queued send. One run per session at a time: a `Send` that meets a running turn follows the busy policy ([What happens when you send while a turn runs?](https://weftgo.dev/docs/sessions/busy-and-steering/)). A `Send` while approval requests are pending is queued behind the boundary ([Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/)). A turn's entries carry the session's clock, so [`thread.Clock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Clock) pins their times too. ### Send a turn `Send` takes a [`weft.Message`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Message), usually [`weft.User(text)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#User), and [`thread.SendOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SendOption) values. There are two: [`thread.As(p)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#As) overrides the busy policy for this one send ([busy policies](https://weftgo.dev/docs/sessions/busy-and-steering/#busy-policies)), and [`thread.RunOptions(opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#RunOptions) carries extra run options into the turn's run: ```go title="sessions/turns.go" turn, err := s.Send(ctx, weft.User("Hi."), thread.RunOptions( weft.Metadata(map[string]string{"tenant": "acme"}), weft.MaxSteps(4), )) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } md := meta.of(turn.RunID()) fmt.Fprintln(w, "tenant:", md["tenant"], "session:", md["weft.session.id"], "turn:", md["weft.turn"]) _, err = s.Send(ctx, weft.User("Hi."), thread.RunOptions(weft.Prompt("something else"))) fmt.Fprintln(w, "refused:", errors.Is(err, weft.ErrInvalidRunOption)) ``` [sessions/turns.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go) ```text tenant: acme session: s_acme turn: 1 refused: true ``` `RunOptions` takes budgets, taps, thinking, metadata and the rest of the run options. Three things are the session's own, and `Send` rejects an option that would set one with an error wrapping [`weft.ErrInvalidRunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidRunOption), before anything is written: - the transcript and the run id: `weft.Messages`, `weft.Prompt`, `weft.RunID`; - the steering source, `weft.Steering`: the session owns the steer queue; - approval decisions, `weft.Approve`, `weft.Deny`, `weft.Resolve`, `weft.ResolveError`: decisions go through `s.Decide`. The options bind every run the session starts on the turn's behalf: the resume of a boundary it parked, its overflow re-run, and the follow-up a steer aimed at it becomes. They are process state, not entries: a reopened session's restored sends run without them. The session's identity metadata (`weft.session.id`, `weft.turn`) wins over a colliding key you pass ([identity](https://weftgo.dev/docs/sessions/tree/#identity)). The package example is [`ExampleRunOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-RunOptions). A tool that a turn runs can reach its session with [`thread.SessionFromContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext); the complete example's `lookup_order` prints it. #### Run what Open restored [`s.Continue(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Continue) starts the work a session holds but is not running, and returns the first turn that will run, or nil when nothing waits. After `Open` that is the steers and sends a stopped writer had accepted; it also runs sends queued behind an approval boundary that has since been decided. Restored work runs under `Continue`'s `ctx`, since the `Send` that accepted it is gone. Without `Continue` the same work starts with the next `Send`, `Decide` or `Resume`. A closed session fails with `ErrClosed`. [What is a session?](https://weftgo.dev/docs/sessions/overview/#create-and-open) shows a restore and a `Continue`; the package example is [`ExampleSession_Continue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Continue). #### Wait for the session to be idle `Wait` returns when the turn is decided: its entries have landed. The session may still be between items, running the automatic compaction or handing off to the next queued send. [`s.WaitIdle(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.WaitIdle) blocks until nothing is in progress, and returns `ctx.Err()` if `ctx` ends first. A caller that only sends the next message need not call it: the `Send` queues behind that work. Idle is not empty: sends held by an open approval boundary and steers restored by `Open` are still queued when it returns. The package example is [`ExampleSession_Send`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Send). ### Wait for a turn A `Turn` is the receipt and the handle of one accepted `Send`; it is safe for concurrent use. Its methods: | Method | Returns | |---|---| | [`Wait()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Wait) | The run's `*weft.RunResult` and error once the turn ends. Safe from any number of goroutines, any number of times, during or after `Events`. | | [`WaitContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.WaitContext) | `Wait` bounded by `ctx`: nil and `ctx.Err()` as soon as `ctx` ends. The turn keeps running. | | [`Done()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Done) | A channel closed when the turn ends, for a `select`. | | [`Events()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Events) | The run's events in emission order. | | [`Outcome()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Outcome) | How the turn ended, or `TurnRunning`. | | [`ID()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.ID) | The receipt id: the prompt entry; for a send accepted while busy, the id its prompt will take; for a steer, its receipt entry; for a resume, its turn entry. | | [`RunID()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.RunID) | `-t`, unique across a reopen; after an overflow re-run, the re-run's id. | | [`Next()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Next) | The turn that continues this one: the resume of a parked boundary, or the follow-up a deferred steer became; otherwise nil. | Bound a wait, then select on `Done`: ```go title="sessions/turns.go" turn, err := s.Send(ctx, weft.User("Export my order history.")) if err != nil { return err } <-started short, cancel := context.WithTimeout(ctx, 20*time.Millisecond) defer cancel() _, err = turn.WaitContext(short) // bounds the wait, not the turn fmt.Fprintln(w, "gave up waiting:", errors.Is(err, context.DeadlineExceeded), "outcome:", turn.Outcome()) close(release) // the export finishes select { case <-turn.Done(): res, err := turn.Wait() // returns at once fmt.Fprintln(w, "done:", res.Text(), err) case <-ctx.Done(): return ctx.Err() } if err := s.WaitIdle(ctx); err != nil { // the between-turn work too return err } ``` [sessions/turns.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go) ```text gave up waiting: true outcome: running done: Exported 42 orders. ``` Giving up the wait changes nothing for the turn. To stop the turn, cancel the context its `Send` was given. The package examples are [`ExampleTurn_WaitContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Turn.WaitContext) and [`ExampleTurn_Done`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Turn.Done). #### Stream a turn's events `Events` yields the run's events as the session observes them. Unlike the core's `Run`, a `Turn`'s events may be ranged more than once, and breaking out of the range cancels nothing: the session drives the run. A failed run delivers its error once, as the last element. A turn with no run of its own, a steer or a turn that never started, yields nothing: ```go title="sessions/turns.go" turn, err = s.Send(ctx, weft.User("And order 5678?")) if err != nil { return err } for ev, err := range turn.Events() { if err != nil { // a failed run: once, as the last element return err } switch ev := ev.(type) { case weft.ToolStart: fmt.Fprintln(w, "tool:", ev.Name, ev.Args) case weft.ToolFinish: fmt.Fprintln(w, "result:", ev.Content) case weft.RunFinish: fmt.Fprintln(w, "steps:", ev.Steps) } } res, err = turn.Wait() // the same end, at once if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text(), "run:", turn.RunID()) ``` [sessions/turns.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go) ```text tool: lookup_order {"order_id":"5678"} result: order 5678 is processing steps: 2 answer: Order 5678 is still processing. run: s_turns-t2 ``` The package example is [`ExampleTurn_Events`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Turn.Events). #### Read the outcome [`thread.TurnOutcome`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TurnOutcome) tells apart the ends `Wait` reports alike. Its `String` method returns the name in the second column: | Outcome | Name | `Wait` returns | |---|---|---| | `TurnRunning` | `running` | (not ended: queued, running, or a steer waiting for its fate) | | `TurnAnswered` | `answered` | the result | | `TurnParked` | `parked` | the result, with `RunResult.Pending`; `Next` is the resume once one is armed | | `TurnDelivered` | `delivered` | nil, nil: a steer the running turn drained | | `TurnDeferred` | `deferred` | nil, nil: a steer that became a follow-up turn, `Next` | | `TurnDropped` | `dropped` | an error wrapping `ErrDropped` | | `TurnFailed` | `failed` | the error: the run failed, could not start, or its end was not persisted | | `TurnCanceled` | `canceled` | the error: its context ended, an `Interrupt` or `Rollback` felled it, or the session closed first | ### Errors The error `Wait` returns says what kind of end it was. Match with `errors.Is` and `errors.As`: - **`*weft.RunError`**: the run started and failed, as the core reports it; `Result` carries the partial transcript. A canceled run's cause is `context.Canceled`. The prompt and the steps that finished stay on the session's path, so [retry from before the turn](https://weftgo.dev/docs/sessions/turns/#best-practices--gotchas), not with a second identical `Send`. - **[`thread.ErrNotRun`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotRun)**: the run never started. The `Send`'s context ended first (the error also wraps `context.Canceled` or `context.DeadlineExceeded`), the prompt entry could not be written, or a resume's boundary was gone. No model was called. - **`thread.ErrClosed`**: the session closed before the turn ran. - **[`thread.ErrDropped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrDropped)**: `ClearQueue` removed the message, or an interrupting send had to take it back. - **[`thread.ErrTurnPanicked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrTurnPanicked)**: the session's own turn machinery panicked, including your `IDs` or `Clock` function. The panic is contained and the session keeps working. Tool and model panics are run errors instead. - **[`thread.ErrNotPersisted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotPersisted)**: the run ended but the batch carrying its turn entry was refused. Its usage is in no ledger; the step messages that landed are in the tree. When the run succeeded, the result rides beside the error. Treat it as a storage incident. Two more sentinels refuse a call before it writes: `thread.ErrCreateOnly` for a header option passed to `Open`, and `thread.ErrReservedKey` for a `weft.` key passed to `SetInfo` ([identity](https://weftgo.dev/docs/sessions/tree/#identity)). ### Usage [`s.Usage()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Usage) returns the session's cost ledger, a [`thread.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Usage), over every entry in the file, not only the leaf's path: ```go title="sessions/turns.go" u := s.Usage() fmt.Fprintln(w, "turn tokens:", u.Turns.InputTokens, "in,", u.Turns.OutputTokens, "out") ``` [sessions/turns.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go) ```text turn tokens: 30 in, 15 out ``` - **`Turns`** sums every turn entry: every run the session made, abandoned branches included, since those tokens were spent. A turn that overflowed and re-ran counts both attempts. - **`Summaries`** sums the summarizer usage of every compaction, in its own bucket. It counts only each stored summary's call: rejected retries, failed compactions and `SummarizeLeft` summaries are not counted ([compaction gotchas](https://weftgo.dev/docs/sessions/compaction/#best-practices--gotchas)). - **`Delegated`** sums what settled `thread/pool` children cost. It is never part of `Turns`, and never part of a run's `RunResult.Usage` (AGENTS rule 13). The package example is [`ExampleSession_Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Usage). ### What the model sees A session's context is a transcript the model reads, so its shape is a model-visible contract (AGENTS rule 5). Changes to it are listed under "Model-visible changes" in the CHANGELOG. Those in thread 0.9.0: - After a mixed tool batch resumes, the model sees one complete tool message for the step, not the partial one with the parked call unanswered. - A step whose write failed is no longer shown to the next turn as an interrupted call beside a duplicated message. - A retried `Send` after a failed prompt flush shows the user message once. - No text changed in approval results; a request that expired or was interrupted after it already held an approval is denied with the expiry or interrupt reason, not "conflicting decisions". - A recorded trim shows the same stubs under any options; a custom `Trimmer`'s stubs reach the model; the first summary survives a trim; a truncated summary is never shown; `BeforeCompact`'s edits shape the summarizer's input; a `SummarizeLeft` branch summary is built from the compacted view. - A context is never built across a broken parent link (the file is refused); a salvaged session's context starts at the orphaned entry. ### Resume A parked turn resumes after `Decide`, `Resume`, a `Send` or `Continue` ([Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/)). The resume runs on the arming call's context for cancellation, and takes the parked turn's context values for every key the arming context lacks, so a park rule or metadata that rode the parked turn binds the resumed steps whoever decides. A second `Resume` while one is in flight joins it: the armed resume, not the transcript's dangling tail, is what makes it idempotent. ### Complete example `sessions/turns.go` sends, streams, bounds a wait and passes run options: ```go title="sessions/turns.go" package main import ( "context" "errors" "fmt" "io" "time" "github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/wefttest" ) // demoTurns is the page "Send turns and wait for them". func demoTurns(ctx context.Context, w io.Writer, _ string) error { var inSession string // what the tool sees; printed after the turn lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in struct { OrderID string `json:"order_id"` }) (string, error) { inSession = thread.SessionFromContext(ctx).ID() // the session whose turn runs this call return "order " + in.OrderID + " is processing", nil }) agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.ToolCalls(wefttest.Call{ID: "call_1", Name: "lookup_order", Args: `{"order_id":"5678"}`}), wefttest.Say("Order 5678 is still processing."), ), lookup) s, err := thread.Create(ctx, thread.Memory(), agent, ctxWindow, ids("s_turns", "a")) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) // the prompt is durable when Send returns if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text()) fmt.Fprintln(w, "receipt:", turn.ID(), "run:", turn.RunID(), "outcome:", turn.Outcome()) turn, err = s.Send(ctx, weft.User("And order 5678?")) if err != nil { return err } for ev, err := range turn.Events() { if err != nil { // a failed run: once, as the last element return err } switch ev := ev.(type) { case weft.ToolStart: fmt.Fprintln(w, "tool:", ev.Name, ev.Args) case weft.ToolFinish: fmt.Fprintln(w, "result:", ev.Content) case weft.RunFinish: fmt.Fprintln(w, "steps:", ev.Steps) } } res, err = turn.Wait() // the same end, at once if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text(), "run:", turn.RunID()) fmt.Fprintln(w, "the tool ran in session:", inSession) u := s.Usage() fmt.Fprintln(w, "turn tokens:", u.Turns.InputTokens, "in,", u.Turns.OutputTokens, "out") if err := s.Close(ctx); err != nil { return err } if err := waitBounded(ctx, w); err != nil { return err } return runOptions(ctx, w) } // waitBounded waits for a long turn three ways. func waitBounded(ctx context.Context, w io.Writer) error { work, started, release := slowTool("export") agent := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "export", ID: "call_1"}), wefttest.Say("Exported 42 orders."), ), work) s, err := thread.Create(ctx, thread.Memory(), agent, ctxWindow, ids("s_wait", "a")) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Export my order history.")) if err != nil { return err } <-started short, cancel := context.WithTimeout(ctx, 20*time.Millisecond) defer cancel() _, err = turn.WaitContext(short) // bounds the wait, not the turn fmt.Fprintln(w, "gave up waiting:", errors.Is(err, context.DeadlineExceeded), "outcome:", turn.Outcome()) close(release) // the export finishes select { case <-turn.Done(): res, err := turn.Wait() // returns at once fmt.Fprintln(w, "done:", res.Text(), err) case <-ctx.Done(): return ctx.Err() } if err := s.WaitIdle(ctx); err != nil { // the between-turn work too return err } return s.Close(ctx) } // runOptions passes per-run options into one turn. func runOptions(ctx context.Context, w io.Writer) error { var meta runMeta agent := weft.New(wefttest.Script(wefttest.Say("Hello, Acme.")), meta.tap()) s, err := thread.Create(ctx, thread.Memory(), agent, ctxWindow, ids("s_acme", "a")) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Hi."), thread.RunOptions( weft.Metadata(map[string]string{"tenant": "acme"}), weft.MaxSteps(4), )) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } md := meta.of(turn.RunID()) fmt.Fprintln(w, "tenant:", md["tenant"], "session:", md["weft.session.id"], "turn:", md["weft.turn"]) _, err = s.Send(ctx, weft.User("Hi."), thread.RunOptions(weft.Prompt("something else"))) fmt.Fprintln(w, "refused:", errors.Is(err, weft.ErrInvalidRunOption)) return s.Close(ctx) } ``` [sessions/turns.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/turns.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`: ```sh go run ./sessions turns go test ./sessions ``` ```text answer: Order 1234 shipped on Tuesday. receipt: e_a1 run: s_turns-t1 outcome: answered tool: lookup_order {"order_id":"5678"} result: order 5678 is processing steps: 2 answer: Order 5678 is still processing. run: s_turns-t2 the tool ran in session: s_turns turn tokens: 30 in, 15 out gave up waiting: true outcome: running done: Exported 42 orders. tenant: acme session: s_acme turn: 1 refused: true ``` ### Best practices & gotchas - **Cancel the `Send`'s context to stop a turn, not the wait's.** `WaitContext` and `Done` only stop you waiting. (Source: `thread/turn.go:2154` WaitContext godoc) - **Call `WaitIdle` before reading state that compaction may change.** `Wait` returns before the between-turn compaction; a test or a tool that prints the tree waits for idle. (Source: `thread/turn.go:2183` WaitIdle godoc) - **Give every session a context window.** Each `Session` value (from `Create`, `Open` or `Fork`) logs one `WARN`, `thread: no context window known for this session`, at its first turn unless `thread.ContextWindow` or `thread.ModelWindows` gives it a window, and its automatic compaction stays off. `thread.NoAutoCompact()` turns compaction off and silences it. The demos pass `ctxWindow`, `thread.ContextWindow(128_000)`. (Source: `thread/compaction.go:1306-1319`; `thread/session.go:425-432`) - **Pass per-turn run settings through `RunOptions`.** The transcript, the run id, the steering source and approval decisions are the session's own and are refused; session-level settings are `SessionOption`s at `Create` or `Open`. (Source: `thread/turn.go:139-215`) - **Do not rely on run options after a restart.** Restored sends and boundaries run without them; pass what must survive as entries or session options. (Source: `thread/turn.go:139-172` RunOptions godoc) - **Treat `ErrNotPersisted` as a storage incident.** The model answered and the storage did not keep the turn's end. (Source: `thread/errors.go:133-141`; `docs/thread-operations.md` §7) - **Close every Session that wrote.** Until it closes no other Session can write that session; a forgotten one holds its lease for the life of the process. (Source: AGENTS.md T2; `docs/thread-operations.md` §4) - **Retry a failed turn from the leaf before it, not with the same `Send`.** The failed turn's prompt stays on the path, so sending it again puts it in the model's context twice. Take `before := s.Leaf()` before the `Send`, and on failure call `s.Branch(ctx, before)` and then `Send` again; the failed attempt keeps its own branch in the tree ([Branch and fork](https://weftgo.dev/docs/sessions/tree/#branch-and-fork)). (Source: `thread/turn.go:240-247` Send godoc; `thread/session.go:932-935`; `thread/branch.go:47-67`; scratch proof in `sources`) - **Treat `ErrLocked` as retry, `ErrStale` and `ErrClosed` as reopen.** `ErrLocked` clears when the other writer closes; a stale or closed Session value never writes again, so `thread.Open` the session anew. A queued Turn that `Close` ended with `ErrClosed` is still in the file and runs after the reopen, so check `s.Queue()` rather than send it again. (Source: `thread/doc.go` Errors; `docs/thread-operations.md` §7; `thread/session.go:1643-1649`) - **Keep `IDs` and `Clock` functions trivial.** Both may run under the session's lock, so calling the Session from them deadlocks; `Clock` must also be safe for concurrent use. A panic in either ends the turn with `ErrTurnPanicked`. (Source: `thread/session.go:116-145`; `thread/errors.go:164`) ### See also - [What happens when you send while a turn runs?](https://weftgo.dev/docs/sessions/busy-and-steering/) - [What is a session?](https://weftgo.dev/docs/sessions/overview/) - [Stream a run's events](https://weftgo.dev/docs/guides/streaming/): the events a turn forwards - [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/): parked turns and `Next` Symbols used: [`Session.Send`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Send) · [`Session.Continue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Continue) · [`Session.WaitIdle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.WaitIdle) · [`Session.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Usage) · [`Session.Leaf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Leaf) · [`Session.Branch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Branch) · [`thread.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Usage) · [`thread.Turn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn) · [`Turn.Wait`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Wait) · [`Turn.WaitContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.WaitContext) · [`Turn.Done`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Done) · [`Turn.Events`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Events) · [`Turn.Outcome`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Outcome) · [`Turn.ID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.ID) · [`Turn.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.RunID) · [`Turn.Next`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Next) · [`thread.TurnOutcome`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TurnOutcome) · [`thread.SendOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SendOption) · [`thread.As`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#As) · [`thread.RunOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#RunOptions) · [`thread.Clock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Clock) · [`thread.SessionFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext) · [`thread.ErrNotRun`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotRun) · [`thread.ErrDropped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrDropped) · [`thread.ErrTurnPanicked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrTurnPanicked) · [`thread.ErrNotPersisted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotPersisted) · [`thread.ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrClosed) · [`thread.ErrCreateOnly`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCreateOnly) · [`thread.ErrReservedKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrReservedKey) · [`weft.User`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#User) · [`weft.Message`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Message) · [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext) · [`weft.ErrInvalidRunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidRunOption) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.RunResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunResult) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # What happens when you send while a turn runs? URL: https://weftgo.dev/docs/sessions/busy-and-steering/ Markdown: https://weftgo.dev/docs/sessions/busy-and-steering.md > A Send on a busy weft/thread session follows its busy policy (Queue, Reject, Steer, Interrupt or Rollback); every accepted message is a durable receipt, and s.Steer joins the running turn or returns ErrNotRunning. A session runs one turn at a time. A `Send` that arrives while a turn runs follows the session's busy policy, set with [`thread.BusyPolicy(p)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BusyPolicy) or for one send with [`thread.As(p)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#As): `Queue` (the default) runs it next, `Reject` fails it with `thread.ErrBusy`, `Steer` delivers it into the running turn, `Interrupt` cancels the turn and queues the message behind any sends already waiting, and `Rollback` also branches back before the interrupted turn. Every message accepted while a turn runs is written to the storage, as a receipt entry, before `Send` returns; an idle `Send` writes its prompt entry instead. `sessions/busy.go` builds a `Reject` session, sends while its tool runs, then steers one message in with `As(Steer)`: ```go title="sessions/busy.go" s, err := thread.Create(ctx, thread.Memory(), weft.New(model, work), ctxWindow, ids("s_reject", "a"), thread.BusyPolicy(thread.Reject)) if err != nil { return err } turn, err := s.Send(ctx, weft.User("How far is the lighthouse?")) if err != nil { return err } <-started // the tool is running _, err = s.Send(ctx, weft.User("Also, the ferry times?")) fmt.Fprintln(w, "while busy:", errors.Is(err, thread.ErrBusy)) steer, err := s.Send(ctx, weft.User("Use metric units."), thread.As(thread.Steer)) if err != nil { return err } close(release) res, err := turn.Wait() if err != nil { return err } if _, err := steer.Wait(); err != nil { // nil result: a steer has no run of its own return err } fmt.Fprintln(w, "steer:", steer.Outcome()) fmt.Fprintln(w, "the model's last request ends with:", model.LastRequest().LastText()) fmt.Fprintln(w, "answer:", res.Text()) ``` [sessions/busy.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/busy.go) ```text while busy: true steer: delivered the model's last request ends with: Use metric units. answer: About 8 kilometres. ``` The rejected send wrote nothing. The steered one joined the running turn: the model's second request ended with it, and the answer is the running turn's. In the demos, `ids` pins the ids for stable output and `ctxWindow` is `thread.ContextWindow(128_000)`, the model's context window ([why](https://weftgo.dev/docs/sessions/turns/#best-practices--gotchas)). ### Busy policies [`thread.Policy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Policy) is what a `Send` does when the session is already running a turn: | Policy | `String()` | What a busy `Send` does | Its `Turn` | |---|---|---|---| | [`thread.Queue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Queue) | `queue` | Holds the message and runs it as the next turn, in acceptance order. An `accepted` receipt carries it until its turn starts. The default. | the queued turn | | [`thread.Reject`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Reject) | `reject` | Fails with [`thread.ErrBusy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrBusy); nothing written. | none | | [`thread.Steer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Steer) | `steer` | Delivers the message into the running turn at its next drain point; a `queued` receipt carries it until then. | a receipt with no run of its own: `delivered`, `deferred` or `dropped` | | [`thread.Interrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Interrupt) | `interrupt` | Cancels the running turn and queues the message at the back, as `Queue` does: sends already waiting run first. | a queued turn | | [`thread.Rollback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Rollback) | `rollback` | An `Interrupt` that also branches the leaf back to before the interrupted turn's receipt entry. Sends already waiting run first, on the rolled-back line. | a queued turn | The policy is captured when `Send` is called and recorded on the turn entry (`TurnEntry.Policy`, the [`Policy.String`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Policy.String) value). On a session that is not busy every policy does the same thing: the message runs as a plain turn. That includes the window between a turn's end and the session's between-turn work. A `Send` while approval requests are pending is queued behind the boundary; under `Reject` a pending boundary reads as busy. Concurrent sends are accepted in the order they take the session's lock. The package examples are [`ExampleBusyPolicy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-BusyPolicy) and [`ExampleAs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-As). #### Steer into the running turn A steer is delivered at the loop's two drain points ([ADR 0019](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0019-steering-hook.md)): after a step's tool batch, when every call already has its result, and at what would have been the final step, which the delivery turns into one more step. The delivered message is an ordinary user message in that run's transcript. The model sees it once. A steer that meets an intended end (`StopWhen`) or an open approval boundary is never drained, and neither is one that arrives after the run's last drain point. It becomes a deferred follow-up that runs as the next turn, and [`steer.Next()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Next) is that turn. Here the tool that a `StopWhen` condition ends on steers: ```go title="sessions/busy.go" turn, err := s.Send(ctx, weft.User("File a ticket: my parcel is late.")) if err != nil { return err } if _, err := turn.Wait(); err != nil { // StopWhen ended the run after submit return err } if _, err := steer.Wait(); err != nil { return err } fmt.Fprintln(w, "steer:", steer.Outcome()) followUp := steer.Next() // the turn the steer became res, err := followUp.Wait() if err != nil { return err } fmt.Fprintln(w, "follow-up:", res.Text(), "run:", followUp.RunID()) ``` [sessions/busy.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/busy.go) ```text steer: deferred follow-up: Added your phone number to ticket 77. run: s_ticket-t3 ``` The follow-up runs under the run options of the turn the steer was aimed at, with the steer's own options after them, so a turn sent with `weft.ParkAllExcept` keeps its follow-ups parked. It runs on the steer's `Send` context for cancellation. The steer reports run id `t2`, minted at acceptance and used by no run; the follow-up is `t3`. The package examples are [`ExampleSteer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Steer) and [`ExampleTurn_Next`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Turn.Next). #### Queue, list and clear [`s.Queue()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Queue) returns what the session has accepted and not yet given to a model, as [`thread.QueuedSteer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#QueuedSteer) values: first the steers waiting for the running turn (`Policy` is `Steer`), then the sends waiting for a turn of their own (`Policy` is `Queue`). `Receipt` is the id the message's `Turn` reports and `Msg` the message. [`s.ClearQueue(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ClearQueue) drops all of them in one atomic append and returns how many: ```go title="sessions/busy.go" later, err := s.Send(ctx, weft.User("Then email it to me.")) // Queue, the default if err != nil { return err } nudge, err := s.Send(ctx, weft.User("Skip the archived orders."), thread.As(thread.Steer)) if err != nil { return err } for _, q := range s.Queue() { // steers first, then sends fmt.Fprintln(w, "waiting:", q.Policy, q.Receipt, q.Msg.Text()) } n, err := s.ClearQueue(ctx) fmt.Fprintln(w, "dropped:", n, err) close(release) if _, err := running.Wait(); err != nil { return err } _, err = later.Wait() fmt.Fprintln(w, "queued send:", later.Outcome(), errors.Is(err, thread.ErrDropped)) fmt.Fprintln(w, "steer:", nudge.Outcome(), "model calls:", len(model.Requests())) ``` [sessions/busy.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/busy.go) ```text waiting: steer e_a5 Skip the archived orders. waiting: queue e_a3 Then email it to me. dropped: 2 queued send: dropped true steer: dropped model calls: 2 ``` Each dropped message's `Turn` ends `TurnDropped` and its `Wait` returns an error wrapping [`thread.ErrDropped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrDropped). The model was called twice, both for the running turn. Delivered or deferred steers are untouched, though a deferred steer's follow-up is a queued send and is dropped. The queue is unbounded: if users can pile messages onto a running turn, check `len(s.Queue())` before you send. The package example is [`ExampleSession_Queue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Queue). #### Interrupt and roll back `As(thread.Interrupt)` cancels the running turn's context and queues the new message. Here nothing else is waiting, so it runs next: ```go title="sessions/busy.go" long, err := s.Send(ctx, weft.User("Research everything about tides.")) if err != nil { return err } <-started short, err := s.Send(ctx, weft.User("Stop. Just the short version."), thread.As(thread.Interrupt)) if err != nil { return err } _, err = long.Wait() fmt.Fprintln(w, "first turn:", long.Outcome(), errors.Is(err, context.Canceled)) res, err := short.Wait() if err != nil { return err } fmt.Fprintln(w, "second turn:", res.Text()) for _, m := range s.Context() { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok { fmt.Fprintln(w, "the model reads:", r.Content) } } } ``` [sessions/busy.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/busy.go) ```text first turn: canceled true second turn: Two tides a day. the model reads: tool call research was interrupted: the run was canceled for a newer message ``` The calls the interrupted turn left without a result carry that interruption text, so the next model sees what was cut off. An approval boundary the interrupt supersedes is denied with the interrupted reason. The interrupted turn's entries stay on the tree as evidence. An interrupt that lands between `Send` and the run's start still fells the run at birth. `Rollback` does the same and moves the leaf back to before the interrupted turn's receipt entry: the follow-up answers as though the interrupted message was never sent, while its entries keep their own line of the tree. The package examples are [`ExampleInterrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Interrupt) and [`ExampleRollback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Rollback). ### Receipts A message accepted while the session is busy is durable at acceptance (thread rule T4): its receipt entry is appended to the storage and flushed before `Send` returns, so neither a queued send nor a steer is lost to a crash. The `busy-policy` session above holds two receipt entries: ```go title="sessions/busy.go" for _, e := range s.Entries() { r, ok := e.(thread.ReceiptEntry) if !ok { continue } switch r.Status { case thread.ReceiptQueued, thread.ReceiptAccepted: // acceptance: the message rides here fmt.Fprintf(w, "receipt %s: %s %q\n", r.ID, r.Status, r.Msg.Text()) default: // a fate: delivered, deferred or dropped fmt.Fprintf(w, "receipt %s: %s, settles %s\n", r.ID, r.Status, r.Receipt) } } ``` [sessions/busy.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/busy.go) ```text receipt e_a3: queued "Use metric units." receipt e_a8: delivered, settles e_a3 ``` A [`thread.ReceiptEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptEntry)'s `Status` is one of: | Status | Meaning | |---|---| | [`ReceiptQueued`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptQueued) `queued` | A steer's acceptance: the message is held for the running turn's drain. | | [`ReceiptAccepted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptAccepted) `accepted` | A queued send's acceptance: the message is held for a turn of its own; `Turn` names the id its prompt entry will take. | | [`ReceiptDelivered`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptDelivered) `delivered` | The running run drained the steer; `RunID` names the run. `Unanswered` marks a run that ended before the model answered it. | | [`ReceiptDeferred`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptDeferred) `deferred` | The steer became a follow-up turn; `Turn` names its prompt entry. | | [`ReceiptDropped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptDropped) `dropped` | Removed before it reached a model: `ClearQueue`, or an interrupting send that was refused. | A fate links to its acceptance through `Receipt`. A queued send is settled by its prompt entry landing, or by a `dropped` receipt. Receipt entries never enter the model's context: the message reaches the model through the run that delivered it or the turn that ran it, exactly once. An acceptance with no fate is a message the writer never got to; `Open` restores it to `s.Queue()` and runs nothing until `Send`, `Decide`, `Resume` or `Continue` ([What is a session?](https://weftgo.dev/docs/sessions/overview/#create-and-open)). ### Steer a running turn `Send(…, As(Steer))` on an idle session runs the message as a plain turn. That is right for the session's owner, and wrong for a caller acting on a turn it does not own, such as a debugger: its "is a turn running?" check could never be atomic with the send. [`s.Steer(ctx, runID, msgs...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Steer) is that caller's verb. Under the session's lock it checks that a turn is running now and is `runID` (`""` accepts any running turn), and accepts the messages as a `Steer`-policy `Send` would: ```go title="sessions/busy.go" err = s.Steer(ctx, "", weft.User("Use metric units.")) fmt.Fprintln(w, "idle:", errors.Is(err, thread.ErrNotRunning), "entries:", len(s.Entries())) turn, err := s.Send(ctx, weft.User("How far is the lighthouse?")) // its tool steers the run if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "steer from the tool:", steerErr) fmt.Fprintln(w, "answer:", res.Text(), "after:", model.LastRequest().LastText()) err = s.Steer(ctx, turn.RunID(), weft.User("Thanks.")) fmt.Fprintln(w, "after the turn:", errors.Is(err, thread.ErrNotRunning)) ``` [sessions/busy.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/busy.go) ```text idle: true entries: 0 steer from the tool: answer: About 8 kilometres. after: Use metric units. after the turn: true ``` When no turn is running (idle, between turns, parked at an approval boundary, or a session reopened after a crash mid-turn), or the running turn is another run, `Steer` returns [`thread.ErrNotRunning`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotRunning) and writes nothing. The call never starts a turn. A steer it delivered that then misses its drain point (the turn meets `StopWhen`, parks, or ends first) still defers to a follow-up turn, under the aimed turn's options: that is the delivered steer's fate, recorded on its receipt. Every message must have the user role, or the call fails with `weft.ErrInvalidSteer` before anything is written; a closed session is `ErrClosed`. A multi-message `Steer` whose later append fails returns that error with the earlier messages already accepted. ### Complete example `sessions/busy.go` runs each policy against a slow tool: ```go title="sessions/busy.go" package main import ( "context" "errors" "fmt" "io" "github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/wefttest" ) // demoBusy is the page "What happens when you send while a turn runs?". func demoBusy(ctx context.Context, w io.Writer, _ string) error { for _, demo := range []func(context.Context, io.Writer) error{ rejectAndSteer, queueAndClear, interrupt, steerVerb, deferred, } { if err := demo(ctx, w); err != nil { return err } } return nil } // rejectAndSteer: a Reject session refuses a send while a turn runs; one // Send overrides the policy with As(Steer) and joins the running turn. func rejectAndSteer(ctx context.Context, w io.Writer) error { fmt.Fprintln(w, "== reject, and steer one send") work, started, release := slowTool("convert") model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "convert", ID: "call_1"}), wefttest.Say("About 8 kilometres."), ) s, err := thread.Create(ctx, thread.Memory(), weft.New(model, work), ctxWindow, ids("s_reject", "a"), thread.BusyPolicy(thread.Reject)) if err != nil { return err } turn, err := s.Send(ctx, weft.User("How far is the lighthouse?")) if err != nil { return err } <-started // the tool is running _, err = s.Send(ctx, weft.User("Also, the ferry times?")) fmt.Fprintln(w, "while busy:", errors.Is(err, thread.ErrBusy)) steer, err := s.Send(ctx, weft.User("Use metric units."), thread.As(thread.Steer)) if err != nil { return err } close(release) res, err := turn.Wait() if err != nil { return err } if _, err := steer.Wait(); err != nil { // nil result: a steer has no run of its own return err } fmt.Fprintln(w, "steer:", steer.Outcome()) fmt.Fprintln(w, "the model's last request ends with:", model.LastRequest().LastText()) fmt.Fprintln(w, "answer:", res.Text()) printReceipts(w, s) return s.Close(ctx) } // queueAndClear: the default policy queues; Queue lists what waits and // ClearQueue drops it. func queueAndClear(ctx context.Context, w io.Writer) error { fmt.Fprintln(w, "== queue and clear") work, started, release := slowTool("export") model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "export", ID: "call_1"}), wefttest.Say("Exported."), ) s, err := thread.Create(ctx, thread.Memory(), weft.New(model, work), ctxWindow, ids("s_queue", "a")) if err != nil { return err } running, err := s.Send(ctx, weft.User("Export my order history.")) if err != nil { return err } <-started later, err := s.Send(ctx, weft.User("Then email it to me.")) // Queue, the default if err != nil { return err } nudge, err := s.Send(ctx, weft.User("Skip the archived orders."), thread.As(thread.Steer)) if err != nil { return err } for _, q := range s.Queue() { // steers first, then sends fmt.Fprintln(w, "waiting:", q.Policy, q.Receipt, q.Msg.Text()) } n, err := s.ClearQueue(ctx) fmt.Fprintln(w, "dropped:", n, err) close(release) if _, err := running.Wait(); err != nil { return err } _, err = later.Wait() fmt.Fprintln(w, "queued send:", later.Outcome(), errors.Is(err, thread.ErrDropped)) fmt.Fprintln(w, "steer:", nudge.Outcome(), "model calls:", len(model.Requests())) printReceipts(w, s) return s.Close(ctx) } // interrupt: As(Interrupt) cancels the running turn and runs the new // message next. func interrupt(ctx context.Context, w io.Writer) error { fmt.Fprintln(w, "== interrupt") research, started, _ := slowTool("research") model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", ID: "call_1"}), wefttest.Say("Two tides a day."), ) s, err := thread.Create(ctx, thread.Memory(), weft.New(model, research), ctxWindow, ids("s_tides", "a")) if err != nil { return err } long, err := s.Send(ctx, weft.User("Research everything about tides.")) if err != nil { return err } <-started short, err := s.Send(ctx, weft.User("Stop. Just the short version."), thread.As(thread.Interrupt)) if err != nil { return err } _, err = long.Wait() fmt.Fprintln(w, "first turn:", long.Outcome(), errors.Is(err, context.Canceled)) res, err := short.Wait() if err != nil { return err } fmt.Fprintln(w, "second turn:", res.Text()) for _, m := range s.Context() { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok { fmt.Fprintln(w, "the model reads:", r.Content) } } } return s.Close(ctx) } // steerVerb: Session.Steer joins the turn running now, and never starts // one. func steerVerb(ctx context.Context, w io.Writer) error { fmt.Fprintln(w, "== Session.Steer") var s *thread.Session var steerErr error convert := weft.Tool("convert", "Convert a length.", func(ctx context.Context, _ struct{}) (string, error) { call, _ := weft.CallFromContext(ctx) steerErr = s.Steer(ctx, call.RunID, weft.User("Use metric units.")) // this run, by id return "5 miles", nil }) model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "convert", ID: "call_1"}), wefttest.Say("About 8 kilometres."), ) var err error s, err = thread.Create(ctx, thread.Memory(), weft.New(model, convert), ctxWindow, ids("s_steer", "a")) if err != nil { return err } err = s.Steer(ctx, "", weft.User("Use metric units.")) fmt.Fprintln(w, "idle:", errors.Is(err, thread.ErrNotRunning), "entries:", len(s.Entries())) turn, err := s.Send(ctx, weft.User("How far is the lighthouse?")) // its tool steers the run if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "steer from the tool:", steerErr) fmt.Fprintln(w, "answer:", res.Text(), "after:", model.LastRequest().LastText()) err = s.Steer(ctx, turn.RunID(), weft.User("Thanks.")) fmt.Fprintln(w, "after the turn:", errors.Is(err, thread.ErrNotRunning)) return s.Close(ctx) } // deferred: a steer that meets an intended end (StopWhen) is never // drained; it becomes a follow-up turn. func deferred(ctx context.Context, w io.Writer) error { fmt.Fprintln(w, "== deferred steer") var s *thread.Session var steer *thread.Turn // The user types while submit runs. The steer is sent on the app's // ctx, not the tool's: a deferred steer's follow-up runs on the // context its Send was given, and the tool's ends with the run. submit := weft.Tool("submit", "Submit the ticket.", func(context.Context, struct{}) (string, error) { steer, _ = s.Send(ctx, weft.User("Add my phone number too."), thread.As(thread.Steer)) return "ticket 77 submitted", nil }) model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "submit", ID: "call_1"}), wefttest.Say("Added your phone number to ticket 77."), ) agent := weft.New(model, submit, weft.StopWhen(weft.HasToolCall("submit"))) var err error s, err = thread.Create(ctx, thread.Memory(), agent, ctxWindow, ids("s_ticket", "a")) if err != nil { return err } turn, err := s.Send(ctx, weft.User("File a ticket: my parcel is late.")) if err != nil { return err } if _, err := turn.Wait(); err != nil { // StopWhen ended the run after submit return err } if _, err := steer.Wait(); err != nil { return err } fmt.Fprintln(w, "steer:", steer.Outcome()) followUp := steer.Next() // the turn the steer became res, err := followUp.Wait() if err != nil { return err } fmt.Fprintln(w, "follow-up:", res.Text(), "run:", followUp.RunID()) return s.Close(ctx) } // printReceipts lists a session's receipt entries: acceptance first, then // each fate, linked to the acceptance it settles. func printReceipts(w io.Writer, s *thread.Session) { for _, e := range s.Entries() { r, ok := e.(thread.ReceiptEntry) if !ok { continue } switch r.Status { case thread.ReceiptQueued, thread.ReceiptAccepted: // acceptance: the message rides here fmt.Fprintf(w, "receipt %s: %s %q\n", r.ID, r.Status, r.Msg.Text()) default: // a fate: delivered, deferred or dropped fmt.Fprintf(w, "receipt %s: %s, settles %s\n", r.ID, r.Status, r.Receipt) } } } ``` [sessions/busy.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/busy.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`: ```sh go run ./sessions busy go test ./sessions ``` ```text == reject, and steer one send while busy: true steer: delivered the model's last request ends with: Use metric units. answer: About 8 kilometres. receipt e_a3: queued "Use metric units." receipt e_a8: delivered, settles e_a3 == queue and clear waiting: steer e_a5 Skip the archived orders. waiting: queue e_a3 Then email it to me. dropped: 2 queued send: dropped true steer: dropped model calls: 2 receipt e_a4: accepted "Then email it to me." receipt e_a5: queued "Skip the archived orders." receipt e_a6: dropped, settles e_a5 receipt e_a7: dropped, settles e_a4 == interrupt first turn: canceled true second turn: Two tides a day. the model reads: tool call research was interrupted: the run was canceled for a newer message == Session.Steer idle: true entries: 0 steer from the tool: answer: About 8 kilometres. after: Use metric units. after the turn: true == deferred steer steer: deferred follow-up: Added your phone number to ticket 77. run: s_ticket-t3 ``` ### Best practices & gotchas - **Send a steer on a context that outlives the turn.** A deferred steer's follow-up runs on its `Send` context; a tool's context ends with the run, and the follow-up then fails with `ErrNotRun`. (Source: ADR 0019 amendment 2026-10-07; `thread/errors.go:150`) - **Use `s.Steer`, not `As(Steer)`, when you do not own the turn.** `As(Steer)` on an idle session starts a turn; `Steer` never does. (Source: ADR 0019 amendment 2026-10-11; `thread/steer.go:145`) - **Bound the queue yourself.** The session does not cap waiting steers or sends; each costs one entry. (Source: `docs/thread-operations.md` §8; ADR 0019 amendment 2026-10-01) - **A steer cannot decide a parked call.** On an open approval boundary it defers to a follow-up turn that runs after the boundary resolves. (Source: ADR 0019 §2; `ExampleTurn_Next`) - **Expect `Interrupt` and `Rollback` to wait behind the queue.** They cancel the running turn but enqueue at the back, exactly as `Queue` does. With a turn running, then sends A and B queued, then C sent `As(Interrupt)`, the model answers A, B and C in that order. Under `Rollback`, A and B also run on the rolled-back line. To run the new message next, call `s.ClearQueue(ctx)` before the send: the waiting sends and steers are dropped, and their Turns end with `ErrDropped`. (Source: `thread/interrupt.go:25-49`; `thread/turn.go:372-383`) - **Treat `ErrBusy` as retry.** The same call succeeds once the turn has ended (`turn.Wait` or `s.WaitIdle` first), or, when the turn parked, once its approval boundary is decided: under `Reject` an open boundary reads as busy. (Source: `thread/errors.go:8-15`; `thread/turn.go:290-300`; `docs/thread-operations.md` §7) ### See also - [Send turns and wait for them](https://weftgo.dev/docs/sessions/turns/) - [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/): `Send` and steers while calls are parked - [ADR 0019](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0019-steering-hook.md): steering, one pull hook in the loop - [Glossary: steer](https://weftgo.dev/docs/reference/glossary/#steer) Symbols used: [`thread.Policy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Policy) · [`Policy.String`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Policy.String) · [`thread.Queue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Queue) · [`thread.Reject`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Reject) · [`thread.Steer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Steer) · [`thread.Interrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Interrupt) · [`thread.Rollback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Rollback) · [`thread.BusyPolicy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BusyPolicy) · [`thread.As`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#As) · [`Session.Queue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Queue) · [`Session.ClearQueue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ClearQueue) · [`Session.Steer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Steer) · [`thread.QueuedSteer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#QueuedSteer) · [`thread.ReceiptEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptEntry) · [`thread.ReceiptQueued`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptQueued) · [`thread.ReceiptAccepted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptAccepted) · [`thread.ReceiptDelivered`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptDelivered) · [`thread.ReceiptDeferred`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptDeferred) · [`thread.ReceiptDropped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptDropped) · [`Turn.Next`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Next) · [`thread.ErrBusy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrBusy) · [`thread.ErrNotRunning`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotRunning) · [`thread.ErrDropped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrDropped) · [`weft.StopWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopWhen) · [`weft.HasToolCall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#HasToolCall) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`weft.ToolResultPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolResultPart) · [`weft.ErrInvalidSteer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidSteer) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Label, branch and fork a session URL: https://weftgo.dev/docs/sessions/tree/ Markdown: https://weftgo.dev/docs/sessions/tree.md > Navigate a weft/thread session's entry tree: Label an entry, Branch back to it (optionally summarizing what you leave), Fork into a new session, and set titles, metadata and public ids that every run carries. A session is a tree: [`s.Branch(ctx, entryID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Branch) moves the leaf back to any earlier entry so the next turn continues from there, [`s.Fork(ctx, entryID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Fork) copies the path up to an entry into a new, self-contained session, and [`s.Label(ctx, entryID, name)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Label) names an entry to come back to. Each is an appended entry or a new session; nothing is rewritten or deleted. `sessions/tree.go` labels the end of the first turn, asks a second question, then branches back to the label, summarizing the abandoned turn: ```go title="sessions/tree.go" shipped := s.Leaf() // the first turn's end if err := s.Label(ctx, shipped, "shipped"); err != nil { return err } if err := send(ctx, s, "When was it delivered?"); err != nil { return err } // Back to the label; the abandoned turn is summarized, not lost. if err := s.Branch(ctx, shipped, thread.SummarizeLeft()); err != nil { return err } if err := send(ctx, s, "Refund it instead."); err != nil { return err } for _, m := range s.Context() { fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text()) } path, err := s.Path(s.Leaf()) if err != nil { return err } fmt.Fprintln(w, "path:", len(path), "entries; tree:", len(s.Entries())) ``` [sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go) ```text user: "Where is order 1234?" assistant: "Order 1234 shipped on Tuesday." user: "\nThe user asked when order 1234 was delivered: Thursday.\n" user: "Refund it instead." assistant: "I have started a refund for order 1234." path: 7 entries; tree: 12 ``` The second question and its answer are off the path: the model sees the summary in their place. The tree still holds them, so it has 12 entries against the path's 7. In the demos, `ids` pins the ids for stable output and `ctxWindow` is `thread.ContextWindow(128_000)`, the model's context window ([why](https://weftgo.dev/docs/sessions/turns/#best-practices--gotchas)). ### Branch and fork > **Diagram:** A session log holds e1 (user: Where is order 1042?), e2 (assistant: Shipped this morning.), e3 (user: And 5678?) and e4 (assistant: Still processing.). s.Branch(ctx, e2) appends a leaf entry pointing at e2; nothing is rewritten. The next write, e5 (user: Cancel 1042 instead.), attaches to e2, so the model's context is e1, e2, e5. e3 and e4 stay in the file, off the path. **Read the tree.** [`s.Leaf()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Leaf) is the entry the next one attaches to ("" while the session is empty). [`s.Context()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context) is what the model sees at the leaf: the message and custom-message entries on its path, branch summaries as marked summaries, the latest compaction applied, and `weft.Repair` last. [`s.Entries()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Entries) is the whole tree in append order, abandoned branches included. [`s.Path(entryID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Path) is one chain of parent links from a root to `entryID`, inclusive. Both return deep copies. Each entry is a sealed [`thread.Entry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Entry) kind with a `type` discriminator on the wire ([`ExampleMessageEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-MessageEntry), [`ExampleSession_Path`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Path)). **Branch** appends a leaf entry pointing at `entryID`, and the model's context is rebuilt from that path alone: nothing appended on the abandoned branch reaches it again. `entryID` may be any entry the session holds, on any branch; `""` is the root, which restarts the conversation from nothing while the file keeps everything (the tree then has several roots). The context is rebuilt from the branch's own path only; tools come from the agent, not the tree. Branching is a between-turns operation: while a turn runs it fails with `thread.ErrBusy`, because the turn's transcript must land on the line it started on. A parked approval boundary is not a running turn, and branching away from it is the documented way out ([`ExampleSession_Branch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Branch)). Branching back to the `Leaf()` taken before a failed turn is also how to retry it without its prompt twice in the context ([Send turns › gotchas](https://weftgo.dev/docs/sessions/turns/#best-practices--gotchas)). [`thread.SummarizeLeft()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummarizeLeft), the one [`thread.BranchOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BranchOption), summarizes the branch being left (back to the common ancestor) into a `branch_summary` entry that the new branch's context carries in its place. The summarizer runs under the session's compaction chain, `SummaryModel` or the session's own model, with the lock released; the navigation and the summary land in one batch. The example's script answers the summary request with its third reply ([`ExampleSummarizeLeft`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-SummarizeLeft)). #### Label an entry A label is an appended [`thread.LabelEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LabelEntry), a bookmark a UI lists and a later `Branch` or `Fork` can return to. It never enters the model's context; `entryID` must be an entry the session holds and the name must not be empty. Read labels back from the tree: ```go title="sessions/tree.go" for _, e := range s.Entries() { if l, ok := e.(thread.LabelEntry); ok { fmt.Fprintln(w, "label:", l.Name, "→", l.Entry) } } ``` [sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go) ```text label: shipped → e_a3 ``` The package example is [`ExampleSession_Label`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Label). #### Fork into a new session > **Diagram:** Session A holds e1, e2 and e3. s.Fork(ctx, e2) writes a new session B whose header names its parent, A#e2: B holds copies of e1 and e2 and continues with its own e3. Session A keeps its leaf and its entries; Fork never moves it. Runs in B carry weft.session.forked_from = A#e2. Fork copies the path root → `entryID` into a new session in the same storage and returns it positioned at the end of that path; when the fork had to append settling entries (below), its leaf is the last of them, with the same context. The new file holds the whole copied path, the entries keeping their ids, and its header's `Parent` names the session and entry it grew from: ```go title="sessions/tree.go" leaf := s.Leaf() fork, err := s.Fork(ctx, shipped, ctxWindow, ids("s_whatif", "f")) if err != nil { return err } h, _, _, err := st.Load(ctx, fork.ID()) if err != nil { return err } fmt.Fprintln(w, "fork:", fork.ID(), "of", h.Parent.Session, "at", h.Parent.Entry, "messages:", len(fork.Context())) turn, err := fork.Send(ctx, weft.User("Send a replacement instead.")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } fmt.Fprintln(w, "fork run:", turn.RunID(), "forked_from:", meta.of(turn.RunID())["weft.session.forked_from"]) fmt.Fprintln(w, "this session's leaf moved:", s.Leaf() != leaf) ``` [sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go) ```text fork: s_whatif of s_tree at e_a3 messages: 2 fork run: s_whatif-t2 forked_from: s_tree#e_a3 this session's leaf moved: false ``` - **Options configure the fork**, as at `Create`: `IDs`, `Clock`, `WithMeta`, `PublicID`, the busy policy, compaction and approval options. Nothing is inherited from this session's options or header, not its public id, with one exception: a fork of a session that requires signed decisions requires them too. - **It inherits what the path records**: the conversation, compactions and branch summaries, the title and `SetInfo` metadata, labels, custom entries, the turn ledger (its run ids continue after the copied turns, hence `t2`), grants, and an open approval boundary, which each session then resolves on its own. - **It does not inherit work**: the running turn, queued sends and steers (recorded as dropped in the fork), mirrored pool requests, or unsettled pool delegations (settled as canceled). - **It works mid-turn and on a closed session**: it snapshots under the lock and writes elsewhere, and never moves this session's leaf. A leaf entry is a navigation, not a position, so `Fork` rejects one; fork the entry it points to. The fork is durable when `Fork` returns; if its entries cannot be written, the half-made session is deleted again. Its runs carry `weft.session.forked_from` as `#`. The package example is [`ExampleSession_Fork`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Fork). #### Keep application state and notes Two bookkeeping writes carry your own data. [`s.Custom(ctx, kind, data)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Custom) appends opaque JSON state under a kind you choose: it survives every compaction and never enters the model's context. [`s.CustomMessage(ctx, kind, msg)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.CustomMessage) appends a message that is always in the context, a note the model must see: ```go title="sessions/tree.go" if err := s.Custom(ctx, "cart", json.RawMessage(`{"items":2}`)); err != nil { // app state: never in the context return err } if err := s.CustomMessage(ctx, "note", weft.User("Note: the customer is on the paid plan.")); err != nil { // always in it return err } fmt.Fprintln(w, "context:", len(s.Context()), "messages; last:", s.Context()[len(s.Context())-1].Text()) ``` [sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go) ```text context: 6 messages; last: Note: the customer is on the paid plan. ``` Both reject an empty kind, and `Custom` rejects data that is not JSON. `CustomMessage` is a between-turns write: while a turn runs it fails with `ErrBusy`, because a message joining mid-run would land between the run's own messages. To reach a running turn, steer ([Steer into the running turn](https://weftgo.dev/docs/sessions/busy-and-steering/#steer-into-the-running-turn)). `Custom` is not restricted. ### Identity A session's identity rides on every run it starts, as run metadata on every span and record: ```go title="sessions/tree.go" s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_pub", "a"), thread.PublicID("pub_7f3a"), // stamped on every run as weft.public_id thread.WithMeta(map[string]string{"tenant": "acme"})) // header metadata: Query.Meta matches it if err != nil { return err } if err := s.SetInfo(ctx, "Refund for order 1234", map[string]string{"tier": "paid"}); err != nil { return err } err = s.SetInfo(ctx, "", map[string]string{"weft.public_id": "pub_other"}) fmt.Fprintln(w, "reserved key:", errors.Is(err, thread.ErrReservedKey)) turn, err := s.Send(ctx, weft.User("How long does a refund take?")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } md := meta.of(turn.RunID()) for _, k := range []string{"weft.session.id", "weft.turn", "weft.public_id", "weft.session.title"} { fmt.Fprintf(w, "%s = %s\n", k, md[k]) } fmt.Fprintln(w, "meta:", s.Meta()["tenant"], s.Meta()["tier"], "title:", s.Title()) page, err := thread.List(ctx, st, thread.Query{Meta: map[string]string{"weft.public_id": "pub_7f3a"}}) if err != nil { return err } fmt.Fprintln(w, "found by public id:", page.Sessions[0].ID) ``` [sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go) ```text reserved key: true weft.session.id = s_pub weft.turn = 1 weft.public_id = pub_7f3a weft.session.title = Refund for order 1234 meta: acme paid title: Refund for order 1234 found by public id: s_pub ``` | Key | Value | |---|---| | `weft.session.id` | the session id, always | | `weft.turn` | the counter the run id `-t` was minted from, always | | `weft.public_id` | the session's public id, when it was created with `thread.PublicID` | | `weft.session.title` | the session's title as the turn starts, once `SetInfo` named one | | `weft.session.forked_from` | `#`, on a fork | | `weft.session.parent`, `weft.session.parent_call` | the parent session and delegating call, on a pool child | | `weft.approval.actor` | who decided, on a resume run that applies decisions; `""` on every other run | | `weft.turn.parent` | since 0.18.0, the turn whose line this turn continues, on the first turn after a navigation (`Branch`, `Uncompact`, a rollback) took the leaf off the newest line; `"0"` when that line holds no turn; absent on a linear turn | | `weft.session.branch` | since 0.18.0, the branch the turn's line descends from: the label on the entry the newest navigation went to, else that navigation's leaf entry id; absent on a line no navigation made | Every run a session starts carries them: a send, a resume, an overflow re-run. The session's keys win over a colliding key you pass with `thread.RunOptions(weft.Metadata(...))`; other keys pass through. Studio's session page draws its tree view from `weft.turn.parent` and `weft.session.branch` ([A session's page](https://weftgo.dev/docs/observe/studio/sessions-and-traces/#a-sessions-page)). A key the session has no value for is stamped `""`, which the core reads as none: a turn sent from inside another session's tool handler, or a pool child's turn, never carries the enclosing run's public id, title, fork origin or lineage as its own. The title is a label, not content, so it survives a content-off destination, and Studio titles the session with it. #### Set a public id and metadata [`thread.PublicID(id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PublicID) sets an opaque, browser-safe handle for the session, stored as the header metadata key `weft.public_id`. It is exactly `thread.WithMeta(map[string]string{"weft.public_id": id})`, so `thread.List`'s `Query.Meta` finds the session by it. [`thread.WithMeta(meta)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithMeta) adds other header keys. Both are header options: `Create` and `Fork` write them, and `Open` fails with [`thread.ErrCreateOnly`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCreateOnly): ```go title="sessions/tree.go" _, err = thread.Open(ctx, st, "s_pub", agent, ctxWindow, thread.PublicID("pub_new")) fmt.Fprintln(w, "header option on Open:", errors.Is(err, thread.ErrCreateOnly)) ``` [sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go) ```text header option on Open: true ``` `Create` does not check that a public id is unused. Two `Create` calls with `thread.PublicID("pub_x")` both succeed, and `thread.List` then finds two sessions. Studio and the devtools panel scope a conversation by public id, so they show both sessions' turns under it. Deciding or steering a turn from the panel asks your `runtime.Sessions` resolver for the public id, and a turn of the session it does not return is refused: `the session resolver answered session for public id , not the run's session ` ([app turns](https://weftgo.dev/docs/observe/devtools/app-turns/#decide-and-steer)). To reuse a session per conversation, look the id up first with `thread.List(ctx, st, thread.Query{Meta: map[string]string{"weft.public_id": id}})` and `Open` the session it returns; `Create` only when it returns none. The public id is fixed for the session's life, and a fork does not inherit it. [`thread.WithLineage(parentSession, call)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithLineage) is the third header option, the pool lineage that [`s.Lineage()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Lineage) reads back; `thread/pool` sets it for its children ([pools](https://weftgo.dev/docs/sessions/pools/)). The examples are [`ExamplePublicID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-PublicID) and [`ExampleWithMeta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-WithMeta). To stamp your own pairs on every turn's run, such as a tenant or a batch tag, pass [`thread.WithRunMetadata(kv)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithRunMetadata) (since 0.18.0). They are the pairs `weft.Metadata` would stamp, on every span and record of each run. At `Create` and `Fork` they are written into the header (`Header.RunMeta`), so a reopened session keeps stamping them; at `Open` they are held over the stored pairs for that `Session`'s life, since the header is immutable. A fork takes its origin's pairs, its own over them. The session's identity keys always win, and a `Send`'s own `thread.RunOptions(weft.Metadata(...))` wins per key over the session's. [`s.RunMeta()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.RunMeta) returns the pairs in force, a copy. [`ExampleWithRunMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-WithRunMetadata) creates a session with `tenant=acme` (its `weft.turn=9` loses to the identity key), reopens it with `batch=b7`, and prints `acme turn 1`, then `acme b7 turn 2`. #### Edit the title and metadata [`s.SetInfo(ctx, title, meta)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.SetInfo) appends an info entry, never a rewrite of the header. [`s.Title()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Title) is the last info entry's non-empty title, and [`s.Meta()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Meta) the header's metadata overlaid by every info entry's, in append order. An empty title keeps the current one; a key set to `""` blanks it, and there is no removal. A call that names neither a title nor a key writes nothing. Keys under the reserved `weft.` prefix are the session's identity and belong to the header: `SetInfo` rejects them with [`thread.ErrReservedKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrReservedKey) and writes nothing. `List`'s `Query.Meta` matches the header only, so a key `SetInfo` added never matches there, while runs read the merged `Meta`. ### Complete example `sessions/tree.go` branches, labels, forks, keeps state and stamps identity. weft's own [`thread/examples/session`](https://github.com/weftgo/weft/tree/v0.20.2/thread/examples/session) walks the same tree on disk, with a previewed compaction and a reopen (`go run ./thread/examples/session` in the weft repository). ```go title="sessions/tree.go" package main import ( "context" "encoding/json" "errors" "fmt" "io" "github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/wefttest" ) // demoTree is the page "Label, branch and fork a session". func demoTree(ctx context.Context, w io.Writer, _ string) error { var meta runMeta agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("It was delivered on Thursday."), wefttest.Say("The user asked when order 1234 was delivered: Thursday."), // the branch summary wefttest.Say("I have started a refund for order 1234."), wefttest.Say("A replacement for order 1234 ships tomorrow."), // the fork's turn ), meta.tap()) st := thread.Memory() s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_tree", "a")) if err != nil { return err } if err := send(ctx, s, "Where is order 1234?"); err != nil { return err } shipped := s.Leaf() // the first turn's end if err := s.Label(ctx, shipped, "shipped"); err != nil { return err } if err := send(ctx, s, "When was it delivered?"); err != nil { return err } // Back to the label; the abandoned turn is summarized, not lost. if err := s.Branch(ctx, shipped, thread.SummarizeLeft()); err != nil { return err } if err := send(ctx, s, "Refund it instead."); err != nil { return err } for _, m := range s.Context() { fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text()) } path, err := s.Path(s.Leaf()) if err != nil { return err } fmt.Fprintln(w, "path:", len(path), "entries; tree:", len(s.Entries())) for _, e := range s.Entries() { if l, ok := e.(thread.LabelEntry); ok { fmt.Fprintln(w, "label:", l.Name, "→", l.Entry) } } leaf := s.Leaf() fork, err := s.Fork(ctx, shipped, ctxWindow, ids("s_whatif", "f")) if err != nil { return err } h, _, _, err := st.Load(ctx, fork.ID()) if err != nil { return err } fmt.Fprintln(w, "fork:", fork.ID(), "of", h.Parent.Session, "at", h.Parent.Entry, "messages:", len(fork.Context())) turn, err := fork.Send(ctx, weft.User("Send a replacement instead.")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } fmt.Fprintln(w, "fork run:", turn.RunID(), "forked_from:", meta.of(turn.RunID())["weft.session.forked_from"]) fmt.Fprintln(w, "this session's leaf moved:", s.Leaf() != leaf) if err := fork.Close(ctx); err != nil { return err } if err := s.Custom(ctx, "cart", json.RawMessage(`{"items":2}`)); err != nil { // app state: never in the context return err } if err := s.CustomMessage(ctx, "note", weft.User("Note: the customer is on the paid plan.")); err != nil { // always in it return err } fmt.Fprintln(w, "context:", len(s.Context()), "messages; last:", s.Context()[len(s.Context())-1].Text()) if err := s.Close(ctx); err != nil { return err } return identity(ctx, w, st) } // send runs one turn and waits until the session is idle again. func send(ctx context.Context, s *thread.Session, text string) error { turn, err := s.Send(ctx, weft.User(text)) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } return s.WaitIdle(ctx) } // identity: the public id, the title and the metadata every run carries. func identity(ctx context.Context, w io.Writer, st thread.Storage) error { var meta runMeta agent := weft.New(wefttest.Script(wefttest.Say("A refund takes three to five days.")), meta.tap()) s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_pub", "a"), thread.PublicID("pub_7f3a"), // stamped on every run as weft.public_id thread.WithMeta(map[string]string{"tenant": "acme"})) // header metadata: Query.Meta matches it if err != nil { return err } if err := s.SetInfo(ctx, "Refund for order 1234", map[string]string{"tier": "paid"}); err != nil { return err } err = s.SetInfo(ctx, "", map[string]string{"weft.public_id": "pub_other"}) fmt.Fprintln(w, "reserved key:", errors.Is(err, thread.ErrReservedKey)) turn, err := s.Send(ctx, weft.User("How long does a refund take?")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } md := meta.of(turn.RunID()) for _, k := range []string{"weft.session.id", "weft.turn", "weft.public_id", "weft.session.title"} { fmt.Fprintf(w, "%s = %s\n", k, md[k]) } fmt.Fprintln(w, "meta:", s.Meta()["tenant"], s.Meta()["tier"], "title:", s.Title()) page, err := thread.List(ctx, st, thread.Query{Meta: map[string]string{"weft.public_id": "pub_7f3a"}}) if err != nil { return err } fmt.Fprintln(w, "found by public id:", page.Sessions[0].ID) if err := s.Close(ctx); err != nil { return err } _, err = thread.Open(ctx, st, "s_pub", agent, ctxWindow, thread.PublicID("pub_new")) fmt.Fprintln(w, "header option on Open:", errors.Is(err, thread.ErrCreateOnly)) return nil } ``` [sessions/tree.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/tree.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`: ```sh go run ./sessions tree go test ./sessions ``` ```text user: "Where is order 1234?" assistant: "Order 1234 shipped on Tuesday." user: "\nThe user asked when order 1234 was delivered: Thursday.\n" user: "Refund it instead." assistant: "I have started a refund for order 1234." path: 7 entries; tree: 12 label: shipped → e_a3 fork: s_whatif of s_tree at e_a3 messages: 2 fork run: s_whatif-t2 forked_from: s_tree#e_a3 this session's leaf moved: false context: 6 messages; last: Note: the customer is on the paid plan. reserved key: true weft.session.id = s_pub weft.turn = 1 weft.public_id = pub_7f3a weft.session.title = Refund for order 1234 meta: acme paid title: Refund for order 1234 found by public id: s_pub header option on Open: true ``` `sessions/sessions_test.go` also pins a branch's context and a fork's `Parent`. ### Best practices & gotchas - **Branch between turns.** `Branch`, `CustomMessage`, `Compact`, `ApplyCompaction` and `Uncompact` fail with `ErrBusy` while a turn is in flight; wait for the turn first. `Fork`, `Label`, `SetInfo`, `Custom` and `Pin` do not wait. (Source: `thread/errors.go:8-15`; `thread/branch.go:67` Branch godoc; `thread/session.go:1327-1450`; CHANGELOG.md:5187) - **A fork is another session.** It has its own writer, its own public id (or none) and its own id; a branch keeps one session and one context line. (Source: `thread/branch.go:266` Fork godoc) - **Put filterable keys in `WithMeta` at `Create`.** `SetInfo` metadata reaches runs and `Meta()` but never `Query.Meta`. (Source: `thread/storage.go:117-125`; `ExampleWithMeta`) - **Never put a `weft.` key in `SetInfo`.** It is rejected with `ErrReservedKey`; identity is set once, in the header. (Source: `thread/errors.go:172-177`) - **Look a public id up before you `Create` with it.** `Create` writes a second session under an id already in use; `thread.List`'s `Query.Meta` on `weft.public_id` finds the existing one to `Open`. (Source: `thread/session.go:507-549`; `thread/storage.go:117-125`) - **Keep the public id opaque.** It is shown to browsers and stamped on every record; an email or a name does not belong there. (Source: `thread/session.go:244` PublicID godoc) - **`SummarizeLeft` makes a model call.** It runs the session's summary chain (`SummaryModel`, else the session's model) before the branch lands, so it costs a request; in a scripted test it consumes a scripted reply. That request is on no ledger: a `branch_summary` entry records no usage, so `s.Usage().Summaries` does not count it. (Source: `thread/branch.go:33-45`; `thread/session.go:1532-1536`; `ExampleSummarizeLeft`) ### See also - [What is a session?](https://weftgo.dev/docs/sessions/overview/) - [Keep long sessions inside the context window (compaction)](https://weftgo.dev/docs/sessions/compaction/) - [Tag runs with metadata](https://weftgo.dev/docs/guides/metadata/) - [The session log format](https://weftgo.dev/docs/sessions/format/): `leaf`, `label`, `info`, `custom` and `branch_summary` entries Symbols used: [`Session.Branch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Branch) · [`Session.Fork`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Fork) · [`Session.Label`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Label) · [`Session.Leaf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Leaf) · [`Session.Context`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context) · [`Session.Entries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Entries) · [`Session.Path`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Path) · [`Session.Custom`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Custom) · [`Session.CustomMessage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.CustomMessage) · [`Session.SetInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.SetInfo) · [`Session.Title`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Title) · [`Session.Meta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Meta) · [`Session.Lineage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Lineage) · [`thread.SummarizeLeft`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummarizeLeft) · [`thread.BranchOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BranchOption) · [`thread.Entry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Entry) · [`thread.LabelEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LabelEntry) · [`thread.PublicID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PublicID) · [`thread.WithMeta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithMeta) · [`thread.WithLineage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithLineage) · [`thread.List`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#List) · [`thread.Query`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Query) · [`thread.ErrBusy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrBusy) · [`thread.ErrCreateOnly`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCreateOnly) · [`thread.ErrReservedKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrReservedKey) · [`thread.RunOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#RunOptions) · [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) · [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.User`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#User) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Keep long sessions inside the context window (compaction) URL: https://weftgo.dev/docs/sessions/compaction/ Markdown: https://weftgo.dev/docs/sessions/compaction.md > Arm weft/thread's compaction with ContextWindow so a long session summarizes its older part behind a fixed marker and keeps the recent part raw; preview, apply, pin, hook and undo it, and nothing is ever deleted. [Compaction](https://weftgo.dev/docs/reference/glossary/#compaction) keeps a long session inside the model's context window: the older part of the conversation is summarized behind a fixed marker, the recent part stays raw, and the summarized entries stay in the file. [`thread.ContextWindow(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ContextWindow) arms the automatic trigger; [`s.Compact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Compact) compacts by hand; [`s.Uncompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Uncompact) undoes it. `sessions/compaction.go` gives the session a 1,000-token window and a scripted model whose second reply reports 900 input tokens: ```go title="sessions/compaction.go" agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday.").WithUsage(weft.Usage{InputTokens: 300}), wefttest.Say("Order 5678 is still processing.").WithUsage(weft.Usage{InputTokens: 900}), wefttest.Say("Goal: track orders 1234 and 5678."), // the summary, made by the same model )) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_window", "a"), thread.ContextWindow(1_000), // arms the trigger: fire past 1,000 − Reserve thread.Reserve(200), // default 16,384 thread.KeepRecent(40)) // default 20,000: estimated tokens kept raw if err != nil { return err } for _, q := range []string{"Where is order 1234?", "And order 5678?"} { if err := send(ctx, s, q); err != nil { // send waits for WaitIdle: the trigger runs after the turn return err } } for _, e := range s.Entries() { if c, ok := e.(thread.CompactionEntry); ok { fmt.Fprintln(w, "compaction:", c.Reason, "first kept:", c.FirstKept, "tokens before:", c.TokensBefore) } } for _, m := range s.Context() { fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text()) } fmt.Fprintln(w, "entries in the file:", len(s.Entries())) ``` [sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go) ```text compaction: threshold first kept: e_a4 tokens before: 81 user: "\nGoal: track orders 1234 and 5678.\n" user: "And order 5678?" assistant: "Order 5678 is still processing." entries in the file: 7 ``` The second turn crossed `window − Reserve` (800), so the session compacted after it. The model now sees the summary and the last turn; the file still holds both turns' six entries plus the compaction entry. The small `Reserve` and `KeepRecent` only make the demo fit; the defaults are 16,384 and 20,000 tokens. ### How compaction works > **Diagram:** A session log holds e1 to e5. s.Compact(ctx) appends a compaction entry C, a summary of e1 to e3. Those entries stay in the file; the context at the leaf becomes the summary, then e4 and e5, the kept recent entries. s.Uncompact(ctx) undoes it by branching back to the entry before the compaction. A compaction is a [`thread.CompactionEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactionEntry) appended at the leaf: the summary text, the id of the first entry kept raw, the estimated tokens before, the reason, the summarizer's usage and model, the files the range read, the pinned ids and a hash of the summarized range. Nothing is deleted. A later compaction summarizes from the previous kept boundary and is fed the previous summary, so the chain is iterative. **The trigger.** It runs on the session's runner before a turn starts (after the prompt is on the path) and after each turn ends. It fires when the last turn's measured input plus an estimate of the messages added since crosses `window − Reserve`. The measured input is the provider-reported input of the turn's final model step plus an estimate of that step's own messages, the tail the report cannot cover, recorded on the turn entry. The reported number is the signal; only what no report covers is estimated, never the whole context. When it fires, it checks the rate limits, tries the trimmer if one is set, and summarizes. The trigger stands down when no step was ever measured, when a `Branch` or `Uncompact` moved the line since the measurement, or when a compaction landed after it; the next turn's report re-arms it. A turn that reported 0 input tokens counts as measured, so the trigger in practice never fires ([gotcha](https://weftgo.dev/docs/sessions/compaction/#best-practices--gotchas)). **The cut.** Walking back from the leaf, the session keeps about `KeepRecent` estimated tokens raw. The cut lands only on a user or assistant message and never between a tool call and its result. A single turn larger than `KeepRecent` is split at an assistant message inside it and summarized in one pass. **The summary.** By default the session's own model writes it (`Agent.Model()`, middleware included, so `mw.Retry` and `mw.Fallback` apply), with no cache hints and the output capped at 0.8 × `Reserve`. The prompt is a fixed skeleton with the headings `Goal:`, `Constraints:`, `Progress:`, `Key Decisions:`, `Next Steps:`, `Critical Context:`, then cumulative `Files read:` and `Files modified:` lists. The range goes to the summarizer as the conversation's own role-tagged messages, the previous summary first, under the skeleton system prompt: tool results capped at 2,000 characters plus a `…[truncated]` marker, signed reasoning dropped, files reduced to `[file: name]`. (ADR 0020 §2 says a plain transcript; the code sends the messages.) A summary that hits the output cap is never stored. **The context after it.** [`s.Context()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context) is, in order: 1. The summary, as one user message: `\n` + summary + `\n`. 2. The pinned entries below the cut, raw, in path order. 3. The kept tail from `FirstKept` on, with every recorded trim replayed. Signed reasoning recorded before the latest compaction or trim is stripped. 4. Branch summaries where they sit on the path, behind the same marker. 5. `weft.Repair` last, so every tool call shown has a result. **Undo is a navigation.** `Uncompact` appends a `leaf` entry pointing at the entry before the latest compaction or trim on the path, so the context is exactly what it was when that entry landed. Every turn sent after the compaction is off the new path too: it stays in the file, but the model no longer sees it ([gotcha](https://weftgo.dev/docs/sessions/compaction/#best-practices--gotchas)). After a compaction and then a trim, the first `Uncompact` undoes the trim and a second one the compaction. **Between turns only.** `Compact`, `ApplyCompaction` and `Uncompact` fail with `thread.ErrBusy` while a turn runs; `Compact` checks before it pays for a model call. `Compact` and `ApplyCompaction` fail with [`thread.ErrAwaitingApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrAwaitingApproval) while approval requests are pending, and an open boundary holds the automatic trigger too: the parked calls must stay raw for their decisions to resolve ([approvals](https://weftgo.dev/docs/sessions/approvals/)). The trigger re-arms on the turn that resolves the boundary. **Cost.** Each entry records its summarizer's usage, and `s.Usage().Summaries` sums them in their own bucket, never mixed with the turns' ([usage](https://weftgo.dev/docs/sessions/turns/#usage)). Only the summary call that was stored is counted: a rejected or truncated attempt, a `SummaryModel` that failed before the fallback, and a compaction that failed outright leave no entry, so their tokens are on no ledger ([gotcha](https://weftgo.dev/docs/sessions/compaction/#best-practices--gotchas)). Every compaction is logged at Info through the agent's logger, as `thread: compacted` or `thread: trimmed old tool results`, with `trace=compaction`, the session, the reason and `tokens_before`. #### With no window Without `ContextWindow` (or a `ModelWindows` entry for the agent's model) there is no automatic compaction and the session logs one warning through the agent's logger, once per `Session` value: ```go title="sessions/compaction.go" logger := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{ ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey { return slog.Attr{} // stable output } return a }, })) agent := weft.New(wefttest.Script(wefttest.Say("Shipped."), wefttest.Say("Processing.")), weft.Logger(logger)) s, err := thread.Create(ctx, thread.Memory(), agent) // no ContextWindow if err != nil { return err } for _, q := range []string{"Order 1234?", "Order 5678?"} { if err := send(ctx, s, q); err != nil { return err } } ``` [sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go) ```text level=WARN msg="thread: no context window known for this session; automatic compaction stays off until one is configured (manual Compact always works)" ``` Manual compaction and the overflow re-run still work. [`thread.NoAutoCompact()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NoAutoCompact) turns the trigger off on purpose: no trigger, no trim and no warning, for a session that compacts only by hand. It took this name in thread 0.9.0; the CHANGELOG's migration checklist maps the old one. A known window must leave room for the other two knobs: `Reserve` below the window, and `KeepRecent` below `window − Reserve`. Otherwise `Create` and `Open` fail with [`thread.ErrCompactConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCompactConfig) rather than build a session that never compacts. #### When a turn overflows A turn that fails with [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow), which every first-party adapter maps, compacts with reason `overflow` and re-runs once over the shrunken path, under a fresh run id: ```go title="sessions/compaction.go" agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Fail(weft.ErrContextOverflow), // the provider refuses the request wefttest.Say("Goal: track order 1234."), // the overflow compaction's summary wefttest.Say("Order 5678 is processing."), // the re-run, over the shrunken path )) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_overflow", "a"), thread.KeepRecent(40)) // ReRunOnOverflow is on by default if err != nil { return err } if err := send(ctx, s, "Where is order 1234?"); err != nil { return err } turn, err := s.Send(ctx, weft.User("And order 5678?")) if err != nil { return err } res, err := turn.Wait() fmt.Fprintln(w, "turn:", err, "|", res.Text(), "| run:", turn.RunID()) fmt.Fprintln(w, "compaction:", lastCompaction(s).Reason) ``` [sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go) ```text turn: | Order 5678 is processing. | run: s_overflow-t3 compaction: overflow ``` The caller sees one turn with the re-run's answer; run `t2` is the attempt that overflowed. A second overflow fails the turn with both errors joined. [`thread.ReRunOnOverflow(false)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReRunOnOverflow) turns the re-run off, and the first overflow then fails the turn. `NoAutoCompact` does not affect it. While an approval boundary is open the overflow compaction is skipped and the turn fails ([`ExampleReRunOnOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-ReRunOnOverflow)). ### Compact by hand [`s.PreviewCompaction(ctx, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.PreviewCompaction) runs the whole algorithm, the hook and the summarizer included, and returns the plan as a [`*thread.Compaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Compaction) without writing anything. [`s.ApplyCompaction(ctx, plan)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ApplyCompaction) writes it as it stands, and `s.Compact(ctx, opts...)` does both. [`s.Pin(ctx, entryID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Pin) keeps an entry in the context through every compaction: ```go title="sessions/compaction.go" first := s.Entries()[0].(thread.MessageEntry) // "Where is order 1234?" if err := s.Pin(ctx, first.ID); err != nil { // keep it raw through every compaction return err } before := len(s.Context()) plan, err := s.PreviewCompaction(ctx, thread.SummaryInstructions("Keep every order number.")) if err != nil { return err } fmt.Fprintln(w, "plan:", plan.Summary, "| first kept:", plan.FirstKept, "| pinned:", plan.Pinned) sys := model.Requests()[len(model.Requests())-1].System fmt.Fprintln(w, "the summarizer's prompt ends:", sys[strings.LastIndex(sys, "\n")+1:]) if err := s.ApplyCompaction(ctx, plan); err != nil { // writes the plan as previewed return err } for _, m := range s.Context() { fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text()) } if err := s.Uncompact(ctx); err != nil { // a branch back: nothing deleted return err } fmt.Fprintln(w, "after Uncompact:", len(s.Context()), "messages, as before:", len(s.Context()) == before) // Preview and apply in one call; the session model summarizes again. if err := s.Compact(ctx); err != nil { return err } fmt.Fprintln(w, "after Compact:", lastCompaction(s).Summary, "|", len(s.Context()), "messages") ``` [sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go) ```text plan: Goal: refund order 1234 and email the receipt. | first kept: e_a7 | pinned: [e_a1] the summarizer's prompt ends: Keep every order number. user: "\nGoal: refund order 1234 and email the receipt.\n" user: "Where is order 1234?" user: "Email me the receipt." assistant: "The receipt is on its way." after Uncompact: 6 messages, as before: true after Compact: Goal: refund order 1234. | 4 messages ``` - **[`thread.SummaryInstructions(text)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryInstructions)** is the one [`thread.CompactOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactOption): it appends per-call instructions to this compaction's summary prompt, as the last line. The agent's own `weft.Instructions` are untouched. It took this name in thread 0.9.0, like `NoAutoCompact`. - **`Uncompact` rewinds later turns too.** The example calls `Uncompact` right after `Compact`, so nothing is lost. After later turns, `Uncompact` rewinds past them: q1 to q3, `Compact`, q4 and q5, then `Uncompact` leaves the context `[q1 a1 q2 a2 q3 a3]`. To get the later turns back, take `leaf := s.Leaf()` before the undo and call `s.Branch(ctx, leaf)`: the context is again the summary, `a3`, and q4 to a5. - **A preview is a dry run.** It may run while a turn is in flight, since it reads a snapshot, but applying it fails at once with `ErrBusy` until the turn ends; it does not wait. A tail that fits inside `KeepRecent` is `ErrNothingToCompact`, not an empty plan. - **`ApplyCompaction` validates the plan against the leaf's path**, whatever happened since it was computed. `FirstKept` must be an entry on the path (`ErrNoEntry` when the session does not hold it, `ErrInvalidCompaction` when it is on another branch), at or after the previous summary's boundary. The same boundary twice is `ErrNothingToCompact`. A plan without a summary must be a trim with its record. An empty `Reason` is recorded as `manual`. You can hand it your own plan: `&thread.Compaction{Summary: "…", FirstKept: id}` ([`ExampleSession_ApplyCompaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.ApplyCompaction)). - **A pin does not hold the cut back.** Compactions summarize past a pinned entry, record its id in `Pinned`, and the context re-includes it raw after the summary. Only an entry that contributes a message can be pinned (a message, a `custom_message` or a `branch_summary`); anything else is `ErrNotPinnable`, an unknown id `ErrNoEntry`. A pin is read when a compaction is computed, so a pin on an entry already below the boundary takes effect at the next one. The pin is a reserved custom entry, kind `weft/pin` ([`ExampleSession_Pin`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Pin)). The package examples are [`ExampleSession_Compact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Compact) and [`ExampleSession_PreviewCompaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.PreviewCompaction). ### Configure compaction Every part of the algorithm is replaceable, in five layers (ADR 0020 §3): knobs, the summary, swapped implementations, hooks, and provider-native compaction. All are [`thread.SessionOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionOption) values passed to `Create` or `Open`. Every function or implementation you supply runs without the session lock and may call the session; the write after a hook re-validates against the tree as it is then. An `Estimator` that called back into the session used to deadlock; since thread 0.2.0 it runs outside the lock like the rest. #### Options | Option | Default | Effect | |---|---|---| | [`ContextWindow(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ContextWindow) | unknown: no automatic compaction | The window the trigger budgets against, in tokens. Zero or negative is ignored. | | [`ModelWindows(map)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ModelWindows) | none | Per-model windows keyed by `weft.ModelInfo`; the agent's model is looked up once, at `Create` or `Open`, and overrides `ContextWindow`. A run that swaps its model with `weft.UseModel` keeps the agent's window. | | [`ModelReserves(map)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ModelReserves) | none | Per-model `Reserve`, resolved the same way. | | [`Reserve(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Reserve) | 16,384 | The headroom: fire before the context is within `n` tokens of the window. Also sizes the summary cap (0.8 × `n`). | | [`KeepRecent(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#KeepRecent) | 20,000 | Roughly how many estimated tokens of the tail stay raw. | | [`TriggerFunc(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TriggerFunc) | `LastInput + Estimated > Window − Reserve` | Replaces the condition. Consulted only when a window is known and a report describes the path; a panic reads as "do not fire". | | [`MinTurnsBetween(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#MinTurnsBetween) | 0: no limit | No automatic compaction or trim within `n` turns of the last compaction on the leaf's path. | | [`MaxPerSession(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#MaxPerSession) | 0: no cap | At most `n` automatic compactions (trims included) on the leaf's path; manual `Compact` keeps working. | | [`WithEstimator(est)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithEstimator) | a quarter of the wire bytes | Replaces the token estimator: the trigger's delta, the cut's walk, `TokensBefore`. | | [`NoAutoCompact()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NoAutoCompact) | off | No trigger, no trim, no warning. Manual calls and the overflow re-run are unaffected. | | [`SummaryModel(m)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryModel) | the session's model | A cheaper model for summaries. On failure the session's model takes over; then the compaction fails. | | [`SummaryPrompt(tmpl)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryPrompt) | the skeleton | Replaces the summarizer's system prompt whole. | | [`SummaryFocus(text)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryFocus) | none | Appends a standing instruction ("keep every file path") after the prompt. | | [`SummaryMaxTokens(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryMaxTokens) | 0.8 × `Reserve` | The summary's output cap. A summary that reaches it fails as `ErrSummaryTruncated`. | | [`WithSummarizer(s)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithSummarizer) | a model call | Replaces text production only. `SummaryModel` and `PreferNative` do not apply; `CheckSummary` does. | | [`WithCompactor(c)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithCompactor) | the built-in algorithm | Replaces everything past the cut; no summary layer runs. | | [`WithTrimmer(t)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithTrimmer) | off | A custom pre-pass before summarizing, on the threshold trigger only: `Compact` and the overflow re-run always summarize. | | [`ClearOldToolResults(keepLast)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ClearOldToolResults) | off | The built-in trimmer: stub every tool result but the newest `keepLast`. | | [`BeforeCompact(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BeforeCompact) | none | Sees every summary compaction before the summarizer runs and returns a `Verdict`. | | [`AfterCompact(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#AfterCompact) | none | Runs with the durable `CompactionEntry` after any compaction or trim lands. | | [`CompactFailed(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactFailed) | none | Runs when a compaction that was to be written is not, with the reason it was attempted for. | | [`CheckSummary(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CheckSummary) | none | Validates each summary; a rejection retries once, then falls back. | | [`PreferNative()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PreferNative) | off | Use the provider's own compaction when the summary model implements `NativeCompactor`. | | [`ReRunOnOverflow(on)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReRunOnOverflow) | on | Compact and re-run once when a turn fails with `weft.ErrContextOverflow`. | The examples are [`ExampleSummaryModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-SummaryModel) (its cost lands in `Usage().Summaries`), [`ExampleTriggerFunc`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-TriggerFunc) and [`ExampleCheckSummary`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-CheckSummary). **The summary chain.** With `SummaryModel` set the chain is that model, then the session's model, then no compaction. Each source gets one retry when its summary is rejected, by `CheckSummary` or as truncated at the cap; a source that errors outright is not retried. A summary with no text is a failure. When the chain is exhausted nothing is stored, the error is returned, and `CompactFailed` hears of it. #### Hook a compaction [`thread.BeforeCompact(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BeforeCompact) is told the reason and returns a [`thread.Verdict`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Verdict): [`thread.Proceed()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Proceed) runs the compaction with whatever the hook edited (the zero `Verdict` proceeds), [`thread.Cancel()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Cancel) stops it, and [`thread.Replace(c)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Replace) writes the hook's own compaction, recorded with reason `from_hook`: ```go title="sessions/compaction.go" verdict := "cancel" hook := thread.BeforeCompact(func(ctx context.Context, p *thread.Preparation) (thread.Verdict, error) { switch verdict { case "cancel": return thread.Cancel(), nil case "replace": // your own summary; recorded with Reason from_hook return thread.Replace(&thread.Compaction{Summary: "Order 1234: refund started.", FirstKept: p.FirstKept}), nil } for i, m := range p.Messages { // redact the range before the summarizer sees it p.Messages[i] = weft.Message{Role: m.Role, Content: []weft.Part{ weft.TextPart{Text: strings.ReplaceAll(m.Text(), "ada@example.com", "[email]")}, }} } return thread.Proceed(), nil }) s, err := thread.Create(ctx, thread.Memory(), weft.New(model), ids("s_hook", "a"), thread.KeepRecent(40), hook) if err != nil { return err } ``` [sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go) The same session compacted three times, the hook's answer changed between calls: ```go title="sessions/compaction.go" n := len(s.Entries()) err = s.Compact(ctx) fmt.Fprintln(w, "cancel:", errors.Is(err, thread.ErrCompactCanceled), "entries written:", len(s.Entries())-n) verdict = "replace" if err := s.Compact(ctx); err != nil { return err } fmt.Fprintln(w, "replace:", lastCompaction(s).Reason, lastCompaction(s).Summary) verdict = "proceed" if err := s.Uncompact(ctx); err != nil { return err } if err := s.Compact(ctx); err != nil { return err } fed := model.Requests()[len(model.Requests())-1].Messages[0].Text() fmt.Fprintln(w, "proceed:", lastCompaction(s).Reason, "| the summarizer saw:", fed[:len("I am [email].")]) ``` [sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go) ```text cancel: true entries written: 0 replace: from_hook Order 1234: refund started. proceed: manual | the summarizer saw: I am [email]. ``` `Cancel` writes nothing and the call fails with [`thread.ErrCompactCanceled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCompactCanceled); on the automatic path it stays quiet. A `Replace` plan's `FirstKept` must be an entry the session holds; `ApplyCompaction`'s rules decide the rest. A hook error or panic fails the compaction with that error. A trim never passes through the hook, since it summarizes nothing. The package example is [`ExampleBeforeCompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-BeforeCompact). The hook receives a [`*thread.Preparation`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Preparation). Four fields are editable, and the compaction proceeds with the edited values; edits to the rest are ignored: | Field | Editable | Holds | |---|---|---| | `Reason` | no | Why the compaction runs. | | `Context` | no | The context the model is shown now: the previous summary, pins, the kept tail with trims applied. | | `Messages` | yes | The range to summarize, as stored. Redact here. | | `PrevSummary` | no | The previous summary on the path, trims skipped. | | `FirstKept` | yes | The first entry kept raw. It must be a user or assistant message on the path, past the previous boundary, that splits no call from its result; moved alone, the range is rebuilt. | | `TokensBefore` | no | The estimated size of `Context`. | | `Instructions` | yes | The per-call text from `SummaryInstructions`. | | `Pinned` | yes | The pinned ids below the cut. | The two observers run after the fact. [`thread.AfterCompact(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#AfterCompact) gets the durable entry for every compaction however it was written (`Compact`, `ApplyCompaction`, the trigger, the overflow re-run, a trim), and the `Context` it reads already shows it. [`thread.CompactFailed(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactFailed) runs when a compaction that was to be written is not, after every fallback, including an `ApplyCompaction` that fails to validate or store. It does not run for `PreviewCompaction`, nor for the refusals that attempt nothing: `ErrNothingToCompact`, `ErrCompactCanceled`, `ErrBusy` and `ErrAwaitingApproval`. A panic in either is contained and logged. [`thread.CheckSummary(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CheckSummary) validates each [`thread.Summary`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Summary); a panic in it counts as a rejection, and a truncated summary never reaches it. #### Clear old tool results first [`thread.ClearOldToolResults(keepLast)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ClearOldToolResults) is a cheap pre-pass: when the trigger fires, every tool result in the context except the newest `keepLast` is replaced with a stub naming the call. If that brings the estimate under `window − Reserve`, no summary is made: ```go title="sessions/compaction.go" read := weft.Tool("read_file", "Read a file.", func(ctx context.Context, in struct { Path string `json:"path"` }) (string, error) { return strings.Repeat(in.Path+" ", 300), nil // about 450 estimated tokens each }) agent := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "read_file", ID: "call_a", Args: `{"path":"a.go"}`}, wefttest.Call{Name: "read_file", ID: "call_b", Args: `{"path":"b.go"}`}, ), wefttest.Say("Both files read.").WithUsage(weft.Usage{InputTokens: 1_900}), ), read) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_trim", "a"), thread.ContextWindow(2_000), thread.Reserve(500), thread.KeepRecent(40), thread.ClearOldToolResults(1)) // keep the newest result raw if err != nil { return err } if err := send(ctx, s, "Read a.go and b.go."); err != nil { return err } c := lastCompaction(s) fmt.Fprintln(w, "compaction:", c.Reason, "| summary empty:", c.Summary == "", "| stubs:", len(c.Trim.Stubs)) for _, m := range s.Context() { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok { fmt.Fprintln(w, r.CallID+":", r.Content[:min(38, len(r.Content))]) } } } ``` [sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go) ```text compaction: trim | summary empty: true | stubs: 1 call_a: [cleared tool result read_file call_a] call_b: b.go b.go b.go b.go b.go b.go b.go b.g ``` The entry has reason `trim`, no summary, and a [`thread.TrimRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TrimRecord) whose [`thread.TrimStub`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TrimStub) values name each stubbed result: the entry, the call id, the replacement content. The stored results are untouched. Later context builds replay the record, never the option, so reopening with another `keepLast` never changes what a recorded trim shows. A trim keeps the boundary in force; it never governs it and never feeds the summary chain. A trim that changes nothing, or does not fit, writes nothing and the summary runs ([`ExampleClearOldToolResults`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-ClearOldToolResults)). #### Swap the parts Four interfaces replace a part of the algorithm: - **[`thread.Summarizer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Summarizer)**, `Summarize(ctx, SummaryInput) (Summary, error)`, produces the text and nothing else; the cut, the serialization, the entry and the retry chain stay the session's. A [`thread.SummaryInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryInput) carries `Messages` (the range, serialized), `PrevSummary`, `Instructions`, `MaxTokens`, `Reason` and `SystemPrompt`, the prompt the default would send, which a custom summarizer may reuse or ignore. It returns a `thread.Summary` with `Text` (empty is a failure) and the `Usage` and `Model` it cost, zero when no model ran. One that knows it was cut short returns an error wrapping `ErrSummaryTruncated` ([`ExampleWithSummarizer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-WithSummarizer)). - **[`thread.Compactor`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Compactor)**, `Compact(ctx, Preparation) (*Compaction, error)`, is the whole algorithm past the cut, after the hook's edits. It may keep any `FirstKept` on the path past the previous boundary; a returned plan with no `Reason` takes the preparation's. - **[`thread.Trimmer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Trimmer)**, `Trim(ctx, msgs) ([]weft.Message, error)`, edits a copy of the context. The one change the record can hold is a tool result's `Content` (and `IsError`) replaced in place; any other change fails the trim with `ErrInvalidCompaction`, reported through the logger and `CompactFailed`, and the summary runs instead. An error or panic is logged and the summary runs. - **[`thread.Estimator`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Estimator)**, `Estimate(msgs) int64`, weighs messages in tokens, called with one message during the cut's walk and with a batch otherwise. The default weighs a message's JSON, so an inline file's base64 bytes count as text ([gotcha](https://weftgo.dev/docs/sessions/compaction/#best-practices--gotchas)). A panic in a `Summarizer` or `Compactor` fails the compaction. [`thread.NativeCompactor`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NativeCompactor), `CompactNative(ctx, req, instructions)`, is what an adapter implements when its provider compacts server-side; `PreferNative` looks for it on the summary model by following `Unwrap()` through middleware. The walk compares models structurally under a depth cap of 64, so an unhashable or self-wrapping wrapper ends the walk instead of panicking or looping (since thread 0.2.0). Only the returned message's text is kept, stored like any other summary. No first-party adapter implements the interface in v0.20.2, and on a model without it, an error or an empty text, the text summary runs. #### What a compaction records A [`thread.Compaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Compaction) is the plan `PreviewCompaction` returns and `ApplyCompaction` writes, field for field: | Field | Meaning | |---|---| | `Summary` | The summary text, shown behind the marker. Empty only on a trim. | | `FirstKept` | The first entry the context still shows raw. | | `TokensBefore` | The estimated size of the context the model was shown, the compacted view, not the raw path. | | `Reason` | Why it ran (below). | | `SummarizerUsage`, `SummarizerModel` | What the summary cost and which model made it. | | `FilesRead` | The file URLs the summarized range carried, sorted and deduplicated. | | `Pinned` | The pinned ids below `FirstKept`, re-included after the summary. | | `RangeHash` | The SHA-256 of the serialized range the summarizer was fed. | | `Trim` | The trim record: required on a trim, forbidden otherwise. | The [`thread.Reason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Reason) values are [`ReasonManual`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReasonManual) (`"manual"`: `Compact`, or `ApplyCompaction` of a preview), [`ReasonThreshold`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReasonThreshold) (`"threshold"`: the trigger), [`ReasonOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReasonOverflow) (`"overflow"`: before the re-run), [`ReasonFromHook`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReasonFromHook) (`"from_hook"`: a `Replace`) and [`ReasonTrim`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReasonTrim) (`"trim"`). `MaxPerSession` counts every reason but `manual` as automatic. The trigger reads a [`thread.TriggerInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TriggerInput): `LastInput`, the last step's provider-reported input plus an estimate of that step's own messages, recorded on the turn entry; `Estimated`, the tokens added since that turn; and the `Window` and `Reserve` in force. #### Errors Match each with `errors.Is`; nothing is written on any of them. | Error | Returned when | |---|---| | [`ErrNothingToCompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNothingToCompact) | The tail fits inside `KeepRecent`, nothing new sits past the previous boundary, or a plan names the boundary the previous compaction left. | | [`ErrCompactCanceled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCompactCanceled) | `BeforeCompact` answered `Cancel`. | | [`ErrSummaryTruncated`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrSummaryTruncated) | The last summarizer in the chain stopped at the output cap (the chain wraps its last error); raise `SummaryMaxTokens` or `Reserve`. | | [`ErrInvalidCompaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrInvalidCompaction) | A plan that cannot be written as given: `FirstKept` off the path or before the boundary, a summary-less non-trim, a bad trim record, or a `Trimmer` change the record cannot hold. | | [`ErrCompactConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCompactConfig) | `Create` or `Open` with a known window and `Reserve` or `KeepRecent` too large for it. | | [`ErrNotPinnable`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotPinnable) | `Pin` on an entry that contributes no message. | | [`ErrNoEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNoEntry) | `Pin` or a plan names an entry the session does not hold, or `Uncompact` finds no compaction on the path. | | [`ErrAwaitingApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrAwaitingApproval) | `Compact` or `ApplyCompaction` while approval requests are pending. | | `ErrBusy` | `Compact`, `ApplyCompaction` or `Uncompact` while a turn runs. | `TrimRecord`, `TrimStub`, `Compaction.Trim` and these sentinels arrived in thread 0.9.0. ### The compaction marker Each compaction also emits one informational OTel log record of kind `compaction` through the agent's `LoggerProvider` as it lands, filed under the id of the last run of this session that produced the compacted context. `obsdb.DB.Compactions` reads it back: ```go title="sessions/compaction.go" p, err := otel.Start(ctx, otel.Local(filepath.Join(dir, "weft.db")), otel.NoEnv(), otel.NoGlobal()) if err != nil { return err } defer p.Shutdown(context.WithoutCancel(ctx)) agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("The refund for order 1234 is started."), wefttest.Say("The receipt is on its way."), wefttest.Say("Goal: refund order 1234."), ), weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_marker", "a"), thread.KeepRecent(40)) if err != nil { return err } if err := longHistory(ctx, s); err != nil { return err } if err := s.Compact(ctx); err != nil { // the marker goes out as the entry lands return err } marks, err := p.LocalDB().Compactions(ctx, "s_marker-t3") // the last run that produced the context if err != nil { return err } for _, m := range marks { fmt.Fprintln(w, "marker:", m.Scope, m.Reason, "replaced", m.Replaced, "messages with", m.Entries) } ``` [sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go) ```text marker: session manual replaced 4 messages with 1 ``` - **What it carries.** Counts and a hash, never messages. It has the event name `weft.compaction` and the attributes `weft.compaction.scope = session`, `weft.compaction.hash` (the SHA-256 of the entry's JSON), `weft.content = none`, `gen_ai.agent.name` and the session's run metadata (`weft.session.id`, `weft.turn`, `weft.public_id`, …), but not the `gen_ai.conversation.id` and `session.id` mirrors a run's records carry. The body is `{scope, hash, entry, reason, replaced, entries, messages_before, messages_after, tokens_before, tokens_after, summarizer_model?, summarizer_usage?, held?}` ([record contract](https://weftgo.dev/docs/reference/record-contract/#compaction)). Since 0.18.0 `summarizer_model` (`{provider, name}`) and `summarizer_usage` say what the summary cost, counts and a model id, never content; both are absent for a trim or a summarizer that ran no model. - **Where it is filed.** Under the last run whose turn produced the context. A context no run of this session produced (entries appended by hand, a fork's copied path) holds the marker for the next run this `Session` drives. Still held at `Close`, it goes out then with `held: true` in its body, filed under no run and keyed by `weft.session.id`, as the [state log's records](https://weftgo.dev/docs/reference/record-contract/#thread) are: a store indexes it by session, and no run's `Compactions` reads it. - **The summarizer's calls.** Since 0.18.0 every summary model call, of a compaction or a `SummarizeLeft` branch, is also a `chat` span with `weft.chat.role` `summarizer`, its model and its usage, filed under the turn in flight or the last run. It is never in that run's own usage, provider, model or metadata: [`obsdb.SessionRow.SummarizerUsage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionRow) sums it per session, apart from `Usage`, and Studio prices it at read time ([See what a run cost](https://weftgo.dev/docs/observe/studio/cost/#own-and-delegated-cost)). A failed call's span carries `error.type` `summarizer`. - **Who reads it.** No reader applies it: the next run's input record already holds the compacted context. [`obsdb.DB.Compactions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) returns a run's run-scope compaction views first, then the session markers filed under it, scope [`obsdb.CompactionSession`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CompactionSession). Studio's run page draws it at the top as "session compaction · after this run", with its token line and counts. ### Complete example `sessions/compaction.go` runs the trigger, the warning, the manual calls, the hook, a trim, an overflow and the marker, each on its own session: ```go title="sessions/compaction.go" package main import ( "context" "errors" "fmt" "io" "log/slog" "path/filepath" "strings" "github.com/weftgo/weft" "github.com/weftgo/weft/otel" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/wefttest" ) // demoCompaction is the page "Keep long sessions inside the context // window (compaction)". func demoCompaction(ctx context.Context, w io.Writer, dir string) error { steps := []func(context.Context, io.Writer, string) error{ compactionWindow, compactionWarn, compactionManual, compactionHook, compactionTrim, compactionOverflow, compactionMarker, } for _, step := range steps { if err := step(ctx, w, dir); err != nil { return err } } return nil } // compactionWindow: ContextWindow arms the trigger, and a turn whose // reported input crosses window − Reserve compacts after it ends. func compactionWindow(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== automatic") agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday.").WithUsage(weft.Usage{InputTokens: 300}), wefttest.Say("Order 5678 is still processing.").WithUsage(weft.Usage{InputTokens: 900}), wefttest.Say("Goal: track orders 1234 and 5678."), // the summary, made by the same model )) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_window", "a"), thread.ContextWindow(1_000), // arms the trigger: fire past 1,000 − Reserve thread.Reserve(200), // default 16,384 thread.KeepRecent(40)) // default 20,000: estimated tokens kept raw if err != nil { return err } for _, q := range []string{"Where is order 1234?", "And order 5678?"} { if err := send(ctx, s, q); err != nil { // send waits for WaitIdle: the trigger runs after the turn return err } } for _, e := range s.Entries() { if c, ok := e.(thread.CompactionEntry); ok { fmt.Fprintln(w, "compaction:", c.Reason, "first kept:", c.FirstKept, "tokens before:", c.TokensBefore) } } for _, m := range s.Context() { fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text()) } fmt.Fprintln(w, "entries in the file:", len(s.Entries())) return s.Close(ctx) } // compactionWarn: a session with no window logs one warning and never // compacts on its own. func compactionWarn(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== no window") logger := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{ ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey { return slog.Attr{} // stable output } return a }, })) agent := weft.New(wefttest.Script(wefttest.Say("Shipped."), wefttest.Say("Processing.")), weft.Logger(logger)) s, err := thread.Create(ctx, thread.Memory(), agent) // no ContextWindow if err != nil { return err } for _, q := range []string{"Order 1234?", "Order 5678?"} { if err := send(ctx, s, q); err != nil { return err } } return s.Close(ctx) } // longHistory runs three short turns, so a manual compaction has a cut. func longHistory(ctx context.Context, s *thread.Session) error { for _, q := range []string{"Where is order 1234?", "Refund it.", "Email me the receipt."} { if err := send(ctx, s, q); err != nil { return err } } return nil } // compactionManual: preview, apply, pin and undo by hand. func compactionManual(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== by hand") model := wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("The refund for order 1234 is started."), wefttest.Say("The receipt is on its way."), wefttest.Say("Goal: refund order 1234 and email the receipt."), // the preview's summary wefttest.Say("Goal: refund order 1234."), // Compact's summary ) s, err := thread.Create(ctx, thread.Memory(), weft.New(model), ids("s_manual", "a"), thread.KeepRecent(40)) if err != nil { return err } if err := longHistory(ctx, s); err != nil { return err } first := s.Entries()[0].(thread.MessageEntry) // "Where is order 1234?" if err := s.Pin(ctx, first.ID); err != nil { // keep it raw through every compaction return err } before := len(s.Context()) plan, err := s.PreviewCompaction(ctx, thread.SummaryInstructions("Keep every order number.")) if err != nil { return err } fmt.Fprintln(w, "plan:", plan.Summary, "| first kept:", plan.FirstKept, "| pinned:", plan.Pinned) sys := model.Requests()[len(model.Requests())-1].System fmt.Fprintln(w, "the summarizer's prompt ends:", sys[strings.LastIndex(sys, "\n")+1:]) if err := s.ApplyCompaction(ctx, plan); err != nil { // writes the plan as previewed return err } for _, m := range s.Context() { fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text()) } if err := s.Uncompact(ctx); err != nil { // a branch back: nothing deleted return err } fmt.Fprintln(w, "after Uncompact:", len(s.Context()), "messages, as before:", len(s.Context()) == before) // Preview and apply in one call; the session model summarizes again. if err := s.Compact(ctx); err != nil { return err } fmt.Fprintln(w, "after Compact:", lastCompaction(s).Summary, "|", len(s.Context()), "messages") return s.Close(ctx) } // compactionHook: BeforeCompact decides — Cancel, Replace or Proceed // with an edited Preparation. func compactionHook(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== hook") model := wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("The refund for order 1234 is started."), wefttest.Say("The receipt is on its way."), wefttest.Say("Goal: refund the order; the customer is [email]."), // the Proceed summary ) verdict := "cancel" hook := thread.BeforeCompact(func(ctx context.Context, p *thread.Preparation) (thread.Verdict, error) { switch verdict { case "cancel": return thread.Cancel(), nil case "replace": // your own summary; recorded with Reason from_hook return thread.Replace(&thread.Compaction{Summary: "Order 1234: refund started.", FirstKept: p.FirstKept}), nil } for i, m := range p.Messages { // redact the range before the summarizer sees it p.Messages[i] = weft.Message{Role: m.Role, Content: []weft.Part{ weft.TextPart{Text: strings.ReplaceAll(m.Text(), "ada@example.com", "[email]")}, }} } return thread.Proceed(), nil }) s, err := thread.Create(ctx, thread.Memory(), weft.New(model), ids("s_hook", "a"), thread.KeepRecent(40), hook) if err != nil { return err } if err := send(ctx, s, "I am ada@example.com. Where is order 1234?"); err != nil { return err } if err := longHistoryFrom(ctx, s, 1); err != nil { return err } n := len(s.Entries()) err = s.Compact(ctx) fmt.Fprintln(w, "cancel:", errors.Is(err, thread.ErrCompactCanceled), "entries written:", len(s.Entries())-n) verdict = "replace" if err := s.Compact(ctx); err != nil { return err } fmt.Fprintln(w, "replace:", lastCompaction(s).Reason, lastCompaction(s).Summary) verdict = "proceed" if err := s.Uncompact(ctx); err != nil { return err } if err := s.Compact(ctx); err != nil { return err } fed := model.Requests()[len(model.Requests())-1].Messages[0].Text() fmt.Fprintln(w, "proceed:", lastCompaction(s).Reason, "| the summarizer saw:", fed[:len("I am [email].")]) return s.Close(ctx) } // longHistoryFrom runs the rest of longHistory's turns, from turn i. func longHistoryFrom(ctx context.Context, s *thread.Session, i int) error { for _, q := range []string{"Where is order 1234?", "Refund it.", "Email me the receipt."}[i:] { if err := send(ctx, s, q); err != nil { return err } } return nil } // lastCompaction is the newest compaction entry on the session's path. func lastCompaction(s *thread.Session) thread.CompactionEntry { var out thread.CompactionEntry path, _ := s.Path(s.Leaf()) for _, e := range path { if c, ok := e.(thread.CompactionEntry); ok { out = c } } return out } // compactionTrim: ClearOldToolResults stubs old tool results first; // when that is enough, no summary is made. func compactionTrim(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== trim") read := weft.Tool("read_file", "Read a file.", func(ctx context.Context, in struct { Path string `json:"path"` }) (string, error) { return strings.Repeat(in.Path+" ", 300), nil // about 450 estimated tokens each }) agent := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "read_file", ID: "call_a", Args: `{"path":"a.go"}`}, wefttest.Call{Name: "read_file", ID: "call_b", Args: `{"path":"b.go"}`}, ), wefttest.Say("Both files read.").WithUsage(weft.Usage{InputTokens: 1_900}), ), read) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_trim", "a"), thread.ContextWindow(2_000), thread.Reserve(500), thread.KeepRecent(40), thread.ClearOldToolResults(1)) // keep the newest result raw if err != nil { return err } if err := send(ctx, s, "Read a.go and b.go."); err != nil { return err } c := lastCompaction(s) fmt.Fprintln(w, "compaction:", c.Reason, "| summary empty:", c.Summary == "", "| stubs:", len(c.Trim.Stubs)) for _, m := range s.Context() { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok { fmt.Fprintln(w, r.CallID+":", r.Content[:min(38, len(r.Content))]) } } } return s.Close(ctx) } // compactionOverflow: a turn failing with weft.ErrContextOverflow // compacts and re-runs once. func compactionOverflow(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== overflow") agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Fail(weft.ErrContextOverflow), // the provider refuses the request wefttest.Say("Goal: track order 1234."), // the overflow compaction's summary wefttest.Say("Order 5678 is processing."), // the re-run, over the shrunken path )) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_overflow", "a"), thread.KeepRecent(40)) // ReRunOnOverflow is on by default if err != nil { return err } if err := send(ctx, s, "Where is order 1234?"); err != nil { return err } turn, err := s.Send(ctx, weft.User("And order 5678?")) if err != nil { return err } res, err := turn.Wait() fmt.Fprintln(w, "turn:", err, "|", res.Text(), "| run:", turn.RunID()) fmt.Fprintln(w, "compaction:", lastCompaction(s).Reason) return s.Close(ctx) } // compactionMarker: each compaction emits one session marker record, // which obsdb reads back under the run that produced the context. func compactionMarker(ctx context.Context, w io.Writer, dir string) error { fmt.Fprintln(w, "== marker") p, err := otel.Start(ctx, otel.Local(filepath.Join(dir, "weft.db")), otel.NoEnv(), otel.NoGlobal()) if err != nil { return err } defer p.Shutdown(context.WithoutCancel(ctx)) agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("The refund for order 1234 is started."), wefttest.Say("The receipt is on its way."), wefttest.Say("Goal: refund order 1234."), ), weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_marker", "a"), thread.KeepRecent(40)) if err != nil { return err } if err := longHistory(ctx, s); err != nil { return err } if err := s.Compact(ctx); err != nil { // the marker goes out as the entry lands return err } marks, err := p.LocalDB().Compactions(ctx, "s_marker-t3") // the last run that produced the context if err != nil { return err } for _, m := range marks { fmt.Fprintln(w, "marker:", m.Scope, m.Reason, "replaced", m.Replaced, "messages with", m.Entries) } return s.Close(ctx) } ``` [sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`: ```sh go run ./sessions compaction go test ./sessions ``` ```text == automatic compaction: threshold first kept: e_a4 tokens before: 81 user: "\nGoal: track orders 1234 and 5678.\n" user: "And order 5678?" assistant: "Order 5678 is still processing." entries in the file: 7 == no window level=WARN msg="thread: no context window known for this session; automatic compaction stays off until one is configured (manual Compact always works)" == by hand plan: Goal: refund order 1234 and email the receipt. | first kept: e_a7 | pinned: [e_a1] the summarizer's prompt ends: Keep every order number. user: "\nGoal: refund order 1234 and email the receipt.\n" user: "Where is order 1234?" user: "Email me the receipt." assistant: "The receipt is on its way." after Uncompact: 6 messages, as before: true after Compact: Goal: refund order 1234. | 4 messages == hook cancel: true entries written: 0 replace: from_hook Order 1234: refund started. proceed: manual | the summarizer saw: I am [email]. == trim compaction: trim | summary empty: true | stubs: 1 call_a: [cleared tool result read_file call_a] call_b: b.go b.go b.go b.go b.go b.go b.go b.g == overflow turn: | Order 5678 is processing. | run: s_overflow-t3 compaction: overflow == marker marker: session manual replaced 4 messages with 1 ``` The other sessions log their own no-window warning and their Info lines on stderr, through `slog.Default`. `sessions/sessions_test.go` also pins that a compaction only appends, that `Uncompact` restores the context, and that `Cancel` writes nothing and calls no model. ### Best practices & gotchas - **Set `ContextWindow` for every session that runs long.** Without it nothing compacts until a turn overflows the provider's window and pays for a failed request first. (Source: `thread/compaction.go:1306-1320`; ADR 0020 §2) - **Compact between turns.** `Compact`, `ApplyCompaction` and `Uncompact` fail with `ErrBusy` while a turn runs; wait for the turn, or call `s.WaitIdle`. (Source: `thread/compaction.go:290-308`, 606-611) - **Do not offer `Uncompact` as "show the full history".** It branches back to the entry before the latest compaction, so every turn sent since then leaves the model's context. With `ContextWindow` the latest compaction can be many turns back. Undo right after compacting, or keep `s.Leaf()` from before the undo and `Branch` back to it. To keep the raw history in view, read `s.Entries()` or `s.Path(leaf)` instead. (Source: `thread/compaction.go:594-635`) - **Decide approvals before compacting.** A pending approval holds the tail raw: `Compact` fails with `ErrAwaitingApproval` and the trigger waits. (Source: `thread/compaction.go:123-126`; ADR 0021 amendment 2026-09-29) - **Redact in `BeforeCompact`, not after.** The hook's `Preparation.Messages` is what the summarizer reads; the summary lands in the context and the file. (Source: `thread/compactopts.go:351-362`; `ExampleBeforeCompact`) - **Wait for idle before reading what the trigger did.** The trigger runs after the turn is decided, so a caller of `turn.Wait` may read the session before the compaction lands. (Source: `thread/turn.go:1274-1276`; `ExampleClearOldToolResults`) - **A summary costs a model call.** In a scripted test it consumes a scripted reply; in production the stored summary's call is billed under `Usage().Summaries`. (Source: ADR 0020 §4 cost ledger; `ExampleSummaryModel`) - **Count summary spend from the provider, not from `Summaries`.** `Summaries` sums `CompactionEntry.SummarizerUsage`, the accepted summary's call alone. Rejected or truncated retries, a failed `SummaryModel` before the fallback, a compaction that failed and every `SummarizeLeft` summary are not counted. Without a `SummaryModel`, a compaction that is always rejected costs two summary calls at each trigger, and `Summaries` stays zero. (Source: `thread/compaction.go:795, 951-989`; `thread/session.go:1532-1536`) - **Fix a compaction that keeps failing.** The trigger runs before and after every turn. A failed attempt writes no compaction entry, so `MinTurnsBetween` and `MaxPerSession` never count it. Once the gap from the last stored compaction has passed, it is retried at every trigger with no backoff. Each failure logs `thread: automatic compaction failed` at WARN; the turn itself still runs. (Source: `thread/turn.go:951, 1282`; `thread/compaction.go:1381-1385, 1398-1419, 1580-1606`) - **Make sure the provider reports input tokens.** The trigger's signal is the final step's reported `InputTokens`. A turn that reports 0 still counts as measured, so the trigger compares only an estimate of the newest messages with the window: it never fires in practice, and nothing is logged. What still compacts: a manual `s.Compact`, a `thread.TriggerFunc` that decides on something other than the reported number (it still receives the `TriggerInput`), and the [overflow re-run](https://weftgo.dev/docs/sessions/compaction/#when-a-turn-overflows) when the provider's error maps to `weft.ErrContextOverflow`. An OpenAI-compatible server without `include_usage` reports 0 ([providers](https://weftgo.dev/docs/guides/providers/#token-usage)). (Source: `thread/turn.go:1661-1671`; `thread/compaction.go:1331-1338, 1375-1380, 1424-1428`; `thread/compactopts.go:123-141`) - **Give scripted turns usage in a compaction test.** `wefttest.Say` and `wefttest.ToolCalls` report a fixed 10 input tokens, so the signal stays at 10 however long the scripted conversation grows. Set the reported input on each turn with `Turn.WithUsage`, as `sessions/compaction.go` does: `wefttest.Say("…").WithUsage(weft.Usage{InputTokens: 900})`. (Source: `weft/core/wefttest/model.go:32-36, 124-127`) - **Weigh inline files yourself.** The default estimate is a quarter of a message's JSON bytes, and an inline `FilePart`'s `Data` is base64 in that JSON. A 400 KiB PNG sent inline weighs about 136k estimated tokens, so the trigger before that turn can compact a session whose real input is a few thousand tokens, and pay for the summary. Send the file as a URL `FilePart`, or pass `WithEstimator` an `Estimator` that gives file parts their own weight. (Source: `thread/compaction.go:1244-1250`; `thread/compactopts.go:188-202`) - **Raise the cap, not the retries, on `ErrSummaryTruncated`.** A cut summary is never stored; give it room with `SummaryMaxTokens` or `Reserve`. (Source: `thread/compaction.go:98-103`) ### See also - [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/): why an open boundary holds compaction - [Label, branch and fork a session](https://weftgo.dev/docs/sessions/tree/): `Uncompact` is a branch; `SummarizeLeft` uses the same summarizer - [Send turns and wait for them](https://weftgo.dev/docs/sessions/turns/): the cost ledger and what the model sees - [The session log format](https://weftgo.dev/docs/sessions/format/): the `compaction` entry and its `"v":5` trim record Symbols used: [`thread.ContextWindow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ContextWindow) · [`thread.Reserve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Reserve) · [`thread.KeepRecent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#KeepRecent) · [`thread.NoAutoCompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NoAutoCompact) · [`thread.ReRunOnOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReRunOnOverflow) · [`thread.SummaryInstructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryInstructions) · [`thread.BeforeCompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BeforeCompact) · [`thread.Proceed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Proceed) · [`thread.Cancel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Cancel) · [`thread.Replace`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Replace) · [`thread.ClearOldToolResults`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ClearOldToolResults) · [`thread.Preparation`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Preparation) · [`thread.Compaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Compaction) · [`thread.CompactionEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactionEntry) · [`Session.Compact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Compact) · [`Session.PreviewCompaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.PreviewCompaction) · [`Session.ApplyCompaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ApplyCompaction) · [`Session.Uncompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Uncompact) · [`Session.Pin`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Pin) · [`Session.Context`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context) · [`Session.Entries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Entries) · [`Session.Path`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Path) · [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow) · [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger) · [`weft.LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#LoggerProvider) · [`weft.TracerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TracerProvider) · [`otel.Start`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Start) · [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) · [`obsdb.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`wefttest.Say`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Say) · [`wefttest.ToolCalls`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ToolCalls) · [`Turn.WithUsage`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Turn.WithUsage) · [`weft.FilePart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#FilePart) · [`thread.Estimator`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Estimator) · [`thread.WithEstimator`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithEstimator) --- # Approvals in sessions URL: https://weftgo.dev/docs/sessions/approvals/ Markdown: https://weftgo.dev/docs/sessions/approvals.md > In a weft/thread session a parked tool call becomes a durable request entry: list it with Pending, decide it with Decide (approve, deny, resolve) and the session resumes on its own; grants, a live Approver, Quorum, RequestExpiry and the audit trail shape the flow. In a session, a tool call that needs approval parks as a durable request entry, written with the turn that parked it. [`s.Pending()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Pending) lists the undecided requests, after a restart too, and [`s.Decide(ctx, thread.Approve(id))`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Decide) records the decision and resumes the conversation on its own. The core's [approval boundary](https://weftgo.dev/docs/reference/glossary/#approval-boundary) (`weft.RequireApproval`, [Require human approval](https://weftgo.dev/docs/guides/approvals/)) is unchanged; the session makes it durable. `sessions/approvals.go` parks a refund, restarts the process by reopening the JSONL file, and approves: ```go title="sessions/approvals.go" s, err := thread.Create(ctx, st, agent, ids("s_refund", "a")) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Refund order 1234.")) if err != nil { return err } res, err := parked.Wait() // the run ends successfully, parked if err != nil { return err } fmt.Fprintln(w, "turn:", parked.Outcome(), "| pending calls:", len(res.Pending)) if err := s.Close(ctx); err != nil { // the process stops return err } s, err = thread.Open(ctx, st, "s_refund", agent, ids("", "b")) // and starts again if err != nil { return err } for _, r := range s.Pending() { // requests are entries: they survive the restart fmt.Fprintln(w, "pending:", r.CallID, r.Tool, string(r.Args), "|", r.Reason, "| request", r.ID) } resume, err := s.Decide(ctx, thread.Approve("call_1")) // recorded, then resumed if err != nil { return err } res, err = resume.Wait() if err != nil { return err } fmt.Fprintln(w, "resumed:", res.Text(), "| run:", resume.RunID()) ``` [sessions/approvals.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/approvals.go) ```text turn: parked | pending calls: 1 pending: call_1 refund {"order_id":"1234"} | tool requires approval | request e_a4 resumed: Refund issued for order 1234. | run: s_refund-t2 ``` The parked turn ended successfully with the call on `res.Pending`. The request survived the restart because it is an entry; `Decide` completed the boundary, so the session started the resume run, `s_refund-t2`, and returned its [`*thread.Turn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn). ### How it works > **Diagram:** The model calls refund_order, a tool built with RequireApproval(). The call gets a ToolStart but is not executed and gets no ToolFinish; the step's other calls run. The run then ends successfully, err is nil, with the parked call on res.Pending and RunFinish.Pending. Later, over any transport, a decision arrives and a new run resumes: agt.Generate(ctx, weft.Messages(res.Messages...), weft.Approve(id)). An approved call runs with Call.Approved set; weft.Deny(id, why) gives the model the result DENIED: why; a call with no decision gets DENIED: no decision. The results complete the earlier tool message and the loop continues with the next model call. - **A parked call is a request.** Each becomes an `approval_request` entry (call id, tool, arguments and their SHA-256, run id, reason, optional expiry) in the same append as the turn entry that ends the turn (the step messages were already written as they joined), so no window exists where the turn is durable and the request is not. A [`thread.Request`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Request) is its view; `Reason` is `tool requires approval` for a `RequireApproval` tool and `middleware required approval` when the tool chain parked it. - **The decision chain runs first.** Before a call parks, the session asks, in order: the grants, then an optional live `Approver`, then it parks. Every step writes an audit entry, automatic approvals included. The chain runs after the core run has ended at the boundary, so a call a grant or the Approver decides still ends its turn `parked`; the session resumes at once and the parked turn's [`Next`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Next) is that resume. - **Decisions are entries.** `Decide` writes `approval_decision` entries; when every pending call of the boundary has one, the session resumes with the core's `Approve`, `Deny`, `Resolve` or `ResolveError` (`AutoResume`, on by default). The resume runs on the deciding call's context for cancellation and takes the parked turn's context values for every key that context lacks. - **A decision belongs to one occurrence.** Call ids repeat across turns (ADR 0021 §1); the request entry's id and the run that parked it do not. Decisions fold per parked run, never per bare call id, and a decision is spent by the resume that applies it: after a `Branch` back to a decided boundary, or a `Fork` of one, the calls are pending again and need new decisions. A resume that finished never runs an approved call twice on one approval. A crash after a resume's `started` entry and before an approved call's result is recorded leaves that call's decision in force, so the next resume runs it again ([after a crash](https://weftgo.dev/docs/sessions/operations/#an-approved-call-cut-off-by-a-crash)). - **The boundary holds the session.** A plain `Send` while approvals pend queues behind the boundary; only the resume resolves it. Compaction is held too: `Compact` fails with [`thread.ErrAwaitingApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrAwaitingApproval) and the trigger stands down ([compaction](https://weftgo.dev/docs/sessions/compaction/)). A `Branch` away from the boundary is the documented way out. Approval is a policy seam, not a security boundary (AGENTS rule 12). A decision that crosses a process boundary should be signed ([Sign approval decisions](https://weftgo.dev/docs/sessions/signed-approvals/)). ### Decide A [`thread.Decision`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Decision) is one call's outcome. Build it with a constructor; set `Who` yourself: | Constructor | `Kind` | What the model sees | |---|---|---| | [`thread.Approve(id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Approve) | [`OutcomeApprove`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OutcomeApprove) | the tool's own result; it runs with `Call.Approved` set | | [`thread.ApproveAlways(id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ApproveAlways) | `OutcomeApprove`, `Always: true` | the same, and a grant for these exact arguments ([grants](https://weftgo.dev/docs/sessions/approvals/#grants)) | | [`thread.Deny(id, reason)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Deny) | [`OutcomeDeny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OutcomeDeny) | `DENIED: `, as an error result | | [`thread.Resolve(id, content)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Resolve) | [`OutcomeResolve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OutcomeResolve) | `content`, verbatim; the handler never runs | | [`thread.ResolveError(id, content)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ResolveError) | [`OutcomeResolveError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OutcomeResolveError) | `content`, marked as an error | Its `CallID` names the pending call, `Kind` the outcome, `Reason` a deny's text and `Content` a resolve's payload. The [`thread.Outcome`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Outcome) values are stored bytes: `approve`, `deny`, `resolve`, `resolve_error`. A decision entry with any other value never resolves a call. One `Decide` can carry a whole batch, here three calls parked by one step: ```go title="sessions/approvals.go" _, err = s.Decide(ctx, thread.Approve("call_a"), thread.Deny("call_a", "twice")) fmt.Fprintln(w, "one call, two verdicts:", errors.Is(err, thread.ErrInvalidDecision)) _, err = s.Decide(ctx, thread.Approve("call_9")) fmt.Fprintln(w, "not pending:", errors.Is(err, thread.ErrNotPending)) no := thread.Deny("call_a", "over the refund limit") no.Who = "agent-7" // an opaque id for the audit trail if _, err := s.Decide(ctx, no, thread.Resolve("call_b", "refunded by hand: ticket 88"), // the handler never runs thread.ResolveError("call_c", "the payment provider is down"), ); err != nil { return err } res, err := parked.Next().Wait() // the resume the decisions started if err != nil { return err } results(w, s) fmt.Fprintln(w, "answer:", res.Text()) ``` [sessions/approvals.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/approvals.go) ```text one call, two verdicts: true not pending: true call_a: DENIED: over the refund limit (error: true) call_b: refunded by hand: ticket 88 (error: false) call_c: the payment provider is down (error: true) answer: One refund was denied, one done by hand, one failed. ``` The batch is validated whole and recorded in one atomic append; on any error none of it is recorded and no run starts on its account. Expired requests are denied first, on every call, and those denials stand and can start the resume even when `Decide` then returns an error ([expiry](https://weftgo.dev/docs/sessions/approvals/#approvers-quorum-and-expiry)): | Error | When | |---|---| | [`thread.ErrInvalidDecision`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrInvalidDecision) | no decisions, a decision without an outcome, or two decisions for one call | | [`thread.ErrNotPending`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotPending) | a call that is not pending, raised before any of the batch lands or runs | | [`thread.ErrExpired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrExpired) | a request past its expiry ([expiry](https://weftgo.dev/docs/sessions/approvals/#approvers-quorum-and-expiry)) | | [`thread.ErrSignatureRequired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrSignatureRequired) | the session requires signed decisions | | [`thread.ErrDelegated`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrDelegated) | a call that delegates to a `thread/pool` child; decide the child's request instead ([pools](https://weftgo.dev/docs/sessions/pools/)) | - **`Who`** is the caller's declaration, verified by nobody, and the identity `Quorum` counts for unsigned decisions. The run that applies the decision carries it as the `weft.approval.actor` metadata pair on every span and record, to every destination and through content-off; on a `Quorum(n > 1)` resume it names every approver that counted toward the quorum, sorted and comma-joined (since 0.18.0; before, the last signer alone). Put an opaque id in it, never an email or a name. - **`Via`** names the channel and the session fills it: `user` for `Decide` and `signed` for `DecideSigned`, whatever the field holds. Its own paths record `grant`, `approver` (an Approver's answer may name its own), `expiry`, `interrupt`, and the pool's `child` and `parent`. - **`Next` follows the flow.** `Decide` returns the resume's `Turn` when it completed the boundary, and `nil, nil` otherwise. The parked turn's `Next` is the same `Turn`, whichever path armed it. After a restart the parked `Turn` value is gone; use what `Decide` returns ([`ExampleTurn_Next`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Turn.Next)). - **Split verdicts deny.** A deny beside an approve, an approve beside a resolve (either order), or two resolves fold to a deny with the pinned reason `conflicting decisions`. A deny alone resolves. The session's own denials (expiry, an interrupting `Send`) are the exception: they resolve with their own stated reason even beside an approval. - **Decisions are durable when `Decide` returns** under `thread.FsyncOnFlush`, as are `Grant`, `Revoke` and `Pin`. The package example is [`ExampleSession_Decide`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Decide). #### Resume by hand With [`thread.AutoResume(false)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#AutoResume) the session records decisions as they arrive and waits; [`s.Resume(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Resume) starts the resume now, denying every undecided call with the core's `no decision` text: ```go title="sessions/approvals.go" s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_resume", "a"), thread.AutoResume(false)) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Deploy to both regions.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } turn, err := s.Decide(ctx, thread.Approve("call_eu")) fmt.Fprintln(w, "decided; resumed on its own:", turn != nil, err) resume, err := s.Resume(ctx) // the undecided call is denied if err != nil { return err } if _, err := resume.Wait(); err != nil { return err } results(w, s) ``` [sessions/approvals.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/approvals.go) ```text decided; resumed on its own: false call_eu: deployed to eu (error: false) call_us: DENIED: no decision (error: true) ``` `Resume` with no open boundary fails with `ErrNotPending`. A second `Resume` while the first is armed or running returns that same turn: one boundary resumes once. Expired requests are denied first, as on every path ([`ExampleSession_Resume`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Resume)). ### Grants A [`thread.Grant`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Grant) approves future calls without asking, or with `Deny` refuses them. [`s.Grant(ctx, g)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Grant) appends it as an entry; [`s.Revoke(ctx, grantID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Revoke) ends it with another: ```go title="sessions/approvals.go" err = s.Grant(ctx, thread.Grant{ // every refund whose order id starts with "12" Tool: "refund", Args: []thread.Arg{thread.ArgPrefix("/order_id", "12")}, }) if err != nil { return err } err = s.Grant(ctx, thread.Grant{ // a standing refusal Tool: "refund", Deny: true, Reason: "order 9999 is under review", Args: []thread.Arg{thread.ArgEquals("/order_id", []byte(`"9999"`))}, }) if err != nil { return err } if _, err := ask("Refund 1234."); err != nil { // the prefix grant approves it return err } parked, err := ask("Refund 5678.") // no grant matches: it parks if err != nil { return err } if _, err := s.Decide(ctx, thread.ApproveAlways("call_2")); err != nil { // approve, and grant these exact args return err } if _, err := settle(parked); err != nil { return err } if _, err := ask("Refund 5678 again."); err != nil { // the minted grant approves it return err } if _, err := ask("Refund 9999."); err != nil { // the deny-grant refuses it return err } for _, e := range s.Entries() { // revoke the prefix grant: an appended entry if g, ok := e.(thread.GrantEntry); ok && len(g.Args) == 1 && g.Args[0].Prefix == "12" { if err := s.Revoke(ctx, g.ID); err != nil { return err } } } if _, err := ask("Refund 1299."); err != nil { // parks again return err } ``` [sessions/approvals.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/approvals.go) ```text Refund 1234. → "Refunded 1234." pending: 0 Refund 5678. → "" pending: 1 Refund 5678 again. → "Refunded 5678 again." pending: 0 Refund 9999. → "Order 9999 cannot be refunded." pending: 0 Refund 1299. → "" pending: 1 ``` The model saw `DENIED: order 9999 is under review` for the refused call. The grant's fields: - **`Tool`** is matched exactly and must not be empty: a grant for every tool is a policy this shape does not have. - **`Args`** are [`thread.Arg`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Arg) predicates, every one of which must match; none matches any arguments. Each has a `Pointer`, an RFC 6901 JSON pointer such as `/order_id`, and one test: `Equals`, `Prefix` or `Glob` (tried in that order on a hand-made `Arg` with several). - **`Deny`** makes it a standing refusal; **`Reason`** is then the model-visible text, `denied by grant` when empty, or a note on an approval grant. - **`Expiry`** lapses it (zero: never), strictly after the time. **`MaxUses`** bounds how often a session grant matches (0: unlimited), counted from its audit entries, within one turn too; a deny-grant's matches count as well. Build the predicates with their constructors: - **[`thread.ArgEquals(pointer, value)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ArgEquals)**: JSON equality. Strings and booleans exactly, arrays and objects deeply (key order never matters); two integers compare digit for digit, and once either side has a fraction or an exponent both compare as `float64`. Pointer `""` is the whole arguments document; no arguments read as `{}`. - **[`thread.ArgPrefix(pointer, prefix)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ArgPrefix)**: a plain string prefix. End it with the separator, or `/ws` matches `/ws-evil`. An empty prefix matches nothing. - **[`thread.ArgGlob(pointer, glob)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ArgGlob)**: `*` matches any run, `?` one code point, every other character itself. There is no escape, and `*` spans separators: `go test*` matches `go test ./...` and anything after it on the line. Array indexes in a pointer are strict (`/01` is not `/1`). The chain consults session grants newest first, from the next boundary on. A match writes a `StepGrant` audit entry whose `GrantID` names the grant, which is one way to find the id `Revoke` needs; the other is the `thread.GrantEntry` in `s.Entries()`. **Approve and always allow.** `thread.ApproveAlways(id)` approves the call and mints a session grant for the tool plus the call's exact arguments, so the next such call never parks. The grant is minted only when the call's effective verdict is approve: with the decision when one approval resolves it, with the completing approval under `Quorum`, never beside a denial. `Always` on a deny or a resolve records the decision and nothing else. A richer grant (a glob, a prefix) is `s.Grant`'s to make ([`ExampleSession_Grant`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Grant)). **Shared grants.** [`thread.WithGrantStore(gs)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithGrantStore) adds an application-wide scope behind the [`thread.GrantStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#GrantStore) interface you implement. Its one method, `Grants(ctx) ([]SharedGrant, error)`, returns the live grants in the order they are tried, first match wins. The chain calls it after the session's own grants, once per gated call per turn that no session grant matched, on the runner goroutine, holding no session lock; the turn waits for the answer, so answer from memory. An error reads as no match, with a warning. Each [`thread.SharedGrant`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SharedGrant) is an `ID` for the audit trail plus the `Grant`; its expiry, uses and revocation are the store's to enforce. The store must be safe for concurrent use. `s.Grant` is an in-process, unsigned call: whoever can call it can pre-approve, under `RequireSigned` too. ### Approvers, quorum and expiry **A live approver.** [`thread.WithApprover(a, timeout)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithApprover) sets the chain's "ask now" step, a [`thread.Approver`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Approver): consulted after grants and before parking, under a context with `timeout` as its deadline. It returns a `Decision` and `true`, or `false` to decline, and the call parks. [`thread.OnRequest(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OnRequest) is told when a request parks: ```go title="sessions/approvals.go" approver := func(ctx context.Context, r thread.Request) (thread.Decision, bool) { if !strings.Contains(string(r.Args), `"staging"`) { return thread.Decision{}, false // not mine to decide: the call parks } d := thread.Approve(r.CallID) d.Who = "ci-bot" return d, true } s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_deploy", "a"), thread.WithApprover(approver, 2*time.Second), // asked before a call parks, bounded thread.OnRequest(func(r thread.Request) { // after the request is durable fmt.Fprintln(w, "notify:", r.Tool, string(r.Args), "parked as", r.ID) })) if err != nil { return err } for _, q := range []string{"Deploy to staging.", "Now prod."} { turn, err := s.Send(ctx, weft.User(q)) if err != nil { return err } res, err := settle(turn) if err != nil { return err } fmt.Fprintf(w, "%s → %q pending: %d\n", q, res.Text(), len(s.Pending())) } ``` [sessions/approvals.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/approvals.go) ```text Deploy to staging. → "Staging is live." pending: 0 notify: deploy {"env":"prod"} parked as e_a14 Now prod. → "" pending: 1 ``` - The timeout must be positive; `Create` and `Open` fail otherwise. A timeout or a panic reads as a decline, audited. Before thread 0.9.0 the timeout was a separate option; it is now this required argument. - The `Request` the Approver gets has no `ID`, `Nonce` or `Created`: the chain asks before the request is persisted. It must not call back into the same session; the turn is still running. - `OnRequest` runs after the request entry is durable, once per parked call, in call order, synchronously on the runner, before the parking turn's `Wait` returns. A slow `fn` holds the session, so hand the request to a queue and return. It may call `Pending` or `Request`; it must not wait for the turn that calls it. A panic is contained and logged. The package example is [`ExampleWithApprover`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-WithApprover). **Quorum.** [`thread.Quorum(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Quorum) needs approvals from `n` distinct approver identities before a call resolves: ```go title="sessions/approvals.go" s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_quorum", "a"), thread.Quorum(2)) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Deploy to prod.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } approve := func(who string) (*thread.Turn, error) { d := thread.Approve("call_1") d.Who = who // unsigned: a declared identity return s.Decide(ctx, d) } resume, err := approve("alice") fmt.Fprintln(w, "after alice:", resume != nil, err, "| pending:", len(s.Pending())) resume, err = approve("bob") if err != nil { return err } res, err := resume.Wait() if err != nil { return err } fmt.Fprintln(w, "after bob:", res.Text()) ``` [sessions/approvals.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/approvals.go) ```text after alice: false | pending: 1 after bob: Prod is live. ``` Values below 2 mean one decision resolves. A deny resolves alone, and conflicting decisions deny with `conflicting decisions`. An identity depends on the door: a signed approval is its key, whatever `Who` it carries; an unsigned approval is its `Who`, which one caller can write twice under two names; a grant's approval is one identity of its own. A grant or an Approver's single approval under `Quorum(2)` leaves the boundary waiting for the second identity. A quorum that must hold against the deciding process needs `RequireSigned` and one key per approver ([`ExampleQuorum`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Quorum)). **Expiry.** [`thread.RequestExpiry(d)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#RequestExpiry) gives every request a lifetime: strictly past `Created + d` it takes no decision. The demo moves the session's clock (`thread.Clock`) instead of sleeping: ```go title="sessions/approvals.go" c := &clock{t: base} s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_expiry", "a"), thread.Clock(c.now), thread.RequestExpiry(10*time.Minute)) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Deploy to prod.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } fmt.Fprintln(w, "expires:", s.Pending()[0].Expiry.Format(time.RFC3339)) c.advance(11 * time.Minute) // nobody decided in time _, err = s.Decide(ctx, thread.Approve("call_1")) fmt.Fprintln(w, "too late:", errors.Is(err, thread.ErrExpired)) if _, err := parked.Next().Wait(); err != nil { // the expiry's denial resumed the boundary return err } results(w, s) ``` [sessions/approvals.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/approvals.go) ```text expires: 2026-10-18T09:10:00Z too late: true call_1: DENIED: expired: no decision before 2026-10-18T09:10:00Z (error: true) ``` Nothing fires on a timer. An expired request is denied with its stated reason the next time the session looks at the boundary: a `Decide`, `DecideSigned`, `Request`, `Resume`, a `Send`, or the runner's own pickup. Those denials stand even when the call that found them returns `ErrExpired`, and when they complete the boundary the resume starts; reach it through the parked turn's `Next`, or `Resume`. `ErrExpired` answers only the path that finds the lapse. Once one path has denied the request, it is no longer pending: a later `Decide`, `DecideSigned` or `Request` for it fails with `ErrNotPending`. The runner's pickup runs right after a parked turn's `Wait` returns, so it can be that first path. A retry after `ErrExpired` reads `ErrNotPending` too. Values of `d` at or below zero, the default, mean requests never expire ([`ExampleRequestExpiry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-RequestExpiry)). ### The audit trail [`s.Audit()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Audit) returns every request, chain step, decision, grant and revocation the session recorded, in order, as `thread.ApprovalRequestEntry`, `thread.ApprovalAuditEntry`, `thread.ApprovalDecisionEntry`, `thread.GrantEntry` and `thread.GrantRevokedEntry`. The expiry session above: ```go title="sessions/approvals.go" for _, e := range s.Audit() { switch e := e.(type) { case thread.ApprovalRequestEntry: fmt.Fprintln(w, "request:", e.CallID, e.Tool, "|", e.Reason) case thread.ApprovalAuditEntry: // Detail is prose for a human, never parsed line := "step: " + e.Step + " " + e.Outcome if e.Detail != "" { line += " | " + e.Detail } fmt.Fprintln(w, line) case thread.ApprovalDecisionEntry: fmt.Fprintln(w, "decision:", e.CallID, e.Outcome, "via", e.Via, "|", e.Reason) } } ``` [sessions/approvals.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/approvals.go) ```text request: call_1 deploy | tool requires approval step: park parked step: expiry denied | request expired at 2026-10-18T09:10:00Z decision: call_1 deny via expiry | expired: no decision before 2026-10-18T09:10:00Z step: resume started | 1 call(s) to resolve step: resume completed ``` An audit entry's `Step` is one of: | Step | Written when | |---|---| | [`StepGrant`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#StepGrant) (`grant`) | a live grant decided; `GrantID` names it, `GrantShared` marks a store's | | [`StepApprover`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#StepApprover) (`approver`) | the Approver was consulted: decided, declined or timed out | | [`StepPark`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#StepPark) (`park`) | the request persisted and the turn ended pending | | [`StepExpiry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#StepExpiry) (`expiry`) | an expired request was denied | | [`StepResume`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#StepResume) (`resume`) | twice per resume: `started` before the run, listing the decisions it applies, then `completed` or `failed` | | [`StepSigned`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#StepSigned) (`signed`) | a signed decision was refused; no decision beside it ([signed approvals](https://weftgo.dev/docs/sessions/signed-approvals/#security-properties)) | A `started` entry with no second entry after it is a resume that never finished: a crash, or a run still in flight. `Detail` is prose for a human and never parsed; what the session reads back lives in typed fields. The trail is an index of the session's log, not tamper-evidence: entries are plain appended lines, unsigned and unchained, so whoever can write the storage can change them. Put tamper-evidence in the storage, such as an append-only volume or a signed export ([`ExampleSession_Audit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Audit)). ### The approvals example weft ships [`thread/examples/approvals`](https://github.com/weftgo/weft/tree/v0.20.2/thread/examples/approvals): it parks a call, restarts by reopening the JSONL file, decides signed, resumes, replays a rejected signature and prints the audit trail, offline, its output pinned by its test. From the weft repository: ```sh go run ./thread/examples/approvals ``` ```text == a session parks a gated call parked: deploy as call_1 == the process restarts; the pending request survived pending after reopen: 1 unsigned: true == the UI asks for a challenge and signs a decision challenge: call call_1 key k1 resumed: Deployed. The change is live. == a replayed signature fails closed replay: thread: decision signature replayed: nonce already decided call "call_1" == the audit trail request call_1 on deploy audit park parked decision call_1 approve via signed audit resume started (1 call(s) to resolve) audit resume completed audit signed refused (replayed) ``` With `-serve addr` the same gate runs as a small web app whose parked turns are decided from the devtools panel. ### Complete example `sessions/approvals.go` decides across a restart, decides a batch, grants, consults an approver, needs a quorum, lets a request expire and resumes by hand: ```go title="sessions/approvals.go" package main import ( "context" "errors" "fmt" "io" "strings" "sync" "time" "github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/thread/jsonl" "github.com/weftgo/weft/wefttest" ) // demoApprovals is the page "Approvals in sessions". func demoApprovals(ctx context.Context, w io.Writer, dir string) error { steps := []func(context.Context, io.Writer, string) error{ approvalsDecide, approvalsOutcomes, approvalsGrant, approvalsApprover, approvalsQuorum, approvalsExpiry, approvalsResume, } for _, step := range steps { if err := step(ctx, w, dir); err != nil { return err } } return nil } // refundTool refunds an order, and only after a decision. func refundTool() *weft.ToolDef { return weft.Tool("refund", "Refund an order.", func(ctx context.Context, in struct { OrderID string `json:"order_id"` }) (string, error) { return "refunded " + in.OrderID, nil }, weft.RequireApproval()) } // refundCall is a model turn asking to refund one order. func refundCall(id, order string) wefttest.Turn { return wefttest.ToolCalls(wefttest.Call{Name: "refund", ID: id, Args: `{"order_id":"` + order + `"}`}) } // results prints every tool result the session's context holds, // leaving out the calls still pending (the context shows those // repaired, as interrupted). func results(w io.Writer, s *thread.Session) { pending := map[string]bool{} for _, r := range s.Pending() { pending[r.CallID] = true } for _, m := range s.Context() { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok && !pending[r.CallID] { fmt.Fprintf(w, "%s: %s (error: %v)\n", r.CallID, r.Content, r.IsError) } } } } // settle waits for a turn and, while the session resumed its boundary, // for each resume after it (Turn.Next); it returns the last result. func settle(t *thread.Turn) (*weft.RunResult, error) { res, err := t.Wait() if err != nil { return nil, err } if next := t.Next(); next != nil { return settle(next) } return res, nil } // approvalsDecide: a parked call survives a restart, and Decide // records the decision and resumes. func approvalsDecide(ctx context.Context, w io.Writer, dir string) error { fmt.Fprintln(w, "== decide") agent := weft.New(wefttest.Script( refundCall("call_1", "1234"), wefttest.Say("Refund issued for order 1234."), ), refundTool()) st, err := jsonl.Open(dir) if err != nil { return err } s, err := thread.Create(ctx, st, agent, ids("s_refund", "a")) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Refund order 1234.")) if err != nil { return err } res, err := parked.Wait() // the run ends successfully, parked if err != nil { return err } fmt.Fprintln(w, "turn:", parked.Outcome(), "| pending calls:", len(res.Pending)) if err := s.Close(ctx); err != nil { // the process stops return err } s, err = thread.Open(ctx, st, "s_refund", agent, ids("", "b")) // and starts again if err != nil { return err } for _, r := range s.Pending() { // requests are entries: they survive the restart fmt.Fprintln(w, "pending:", r.CallID, r.Tool, string(r.Args), "|", r.Reason, "| request", r.ID) } resume, err := s.Decide(ctx, thread.Approve("call_1")) // recorded, then resumed if err != nil { return err } res, err = resume.Wait() if err != nil { return err } fmt.Fprintln(w, "resumed:", res.Text(), "| run:", resume.RunID()) results(w, s) return s.Close(ctx) } // approvalsOutcomes: Deny, Resolve and ResolveError in one batch; the // parked turn's Next is the resume. func approvalsOutcomes(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== deny, resolve, resolve_error") agent := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "refund", ID: "call_a", Args: `{"order_id":"1111"}`}, wefttest.Call{Name: "refund", ID: "call_b", Args: `{"order_id":"2222"}`}, wefttest.Call{Name: "refund", ID: "call_c", Args: `{"order_id":"3333"}`}, ), wefttest.Say("One refund was denied, one done by hand, one failed."), ), refundTool()) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_batch", "a")) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Refund orders 1111, 2222 and 3333.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } _, err = s.Decide(ctx, thread.Approve("call_a"), thread.Deny("call_a", "twice")) fmt.Fprintln(w, "one call, two verdicts:", errors.Is(err, thread.ErrInvalidDecision)) _, err = s.Decide(ctx, thread.Approve("call_9")) fmt.Fprintln(w, "not pending:", errors.Is(err, thread.ErrNotPending)) no := thread.Deny("call_a", "over the refund limit") no.Who = "agent-7" // an opaque id for the audit trail if _, err := s.Decide(ctx, no, thread.Resolve("call_b", "refunded by hand: ticket 88"), // the handler never runs thread.ResolveError("call_c", "the payment provider is down"), ); err != nil { return err } res, err := parked.Next().Wait() // the resume the decisions started if err != nil { return err } results(w, s) fmt.Fprintln(w, "answer:", res.Text()) return s.Close(ctx) } // approvalsGrant: a grant approves future calls without asking; // ApproveAlways mints one for the exact arguments; Revoke ends one. func approvalsGrant(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== grants") agent := weft.New(wefttest.Script( refundCall("call_1", "1234"), wefttest.Say("Refunded 1234."), refundCall("call_2", "5678"), wefttest.Say("Refunded 5678."), refundCall("call_3", "5678"), wefttest.Say("Refunded 5678 again."), refundCall("call_4", "9999"), wefttest.Say("Order 9999 cannot be refunded."), refundCall("call_5", "1299"), ), refundTool()) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_grant", "a")) if err != nil { return err } ask := func(prompt string) (*thread.Turn, error) { turn, err := s.Send(ctx, weft.User(prompt)) if err != nil { return nil, err } res, err := settle(turn) // a grant decides in the chain: the turn parks, the resume follows at once if err != nil { return nil, err } fmt.Fprintf(w, "%s → %q pending: %d\n", prompt, res.Text(), len(s.Pending())) return turn, nil } err = s.Grant(ctx, thread.Grant{ // every refund whose order id starts with "12" Tool: "refund", Args: []thread.Arg{thread.ArgPrefix("/order_id", "12")}, }) if err != nil { return err } err = s.Grant(ctx, thread.Grant{ // a standing refusal Tool: "refund", Deny: true, Reason: "order 9999 is under review", Args: []thread.Arg{thread.ArgEquals("/order_id", []byte(`"9999"`))}, }) if err != nil { return err } if _, err := ask("Refund 1234."); err != nil { // the prefix grant approves it return err } parked, err := ask("Refund 5678.") // no grant matches: it parks if err != nil { return err } if _, err := s.Decide(ctx, thread.ApproveAlways("call_2")); err != nil { // approve, and grant these exact args return err } if _, err := settle(parked); err != nil { return err } if _, err := ask("Refund 5678 again."); err != nil { // the minted grant approves it return err } if _, err := ask("Refund 9999."); err != nil { // the deny-grant refuses it return err } for _, e := range s.Entries() { // revoke the prefix grant: an appended entry if g, ok := e.(thread.GrantEntry); ok && len(g.Args) == 1 && g.Args[0].Prefix == "12" { if err := s.Revoke(ctx, g.ID); err != nil { return err } } } if _, err := ask("Refund 1299."); err != nil { // parks again return err } results(w, s) return s.Close(ctx) } // deployTool deploys, and only after a decision. func deployTool() *weft.ToolDef { return weft.Tool("deploy", "Deploy the service.", func(ctx context.Context, in struct { Env string `json:"env"` }) (string, error) { return "deployed to " + in.Env, nil }, weft.RequireApproval()) } // deployCall is a model turn asking to deploy to env. func deployCall(id, env string) wefttest.Turn { return wefttest.ToolCalls(wefttest.Call{Name: "deploy", ID: id, Args: `{"env":"` + env + `"}`}) } // approvalsApprover: the live step decides what it can; OnRequest // reports what parks. func approvalsApprover(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== approver") agent := weft.New(wefttest.Script( deployCall("call_1", "staging"), wefttest.Say("Staging is live."), deployCall("call_2", "prod"), ), deployTool()) approver := func(ctx context.Context, r thread.Request) (thread.Decision, bool) { if !strings.Contains(string(r.Args), `"staging"`) { return thread.Decision{}, false // not mine to decide: the call parks } d := thread.Approve(r.CallID) d.Who = "ci-bot" return d, true } s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_deploy", "a"), thread.WithApprover(approver, 2*time.Second), // asked before a call parks, bounded thread.OnRequest(func(r thread.Request) { // after the request is durable fmt.Fprintln(w, "notify:", r.Tool, string(r.Args), "parked as", r.ID) })) if err != nil { return err } for _, q := range []string{"Deploy to staging.", "Now prod."} { turn, err := s.Send(ctx, weft.User(q)) if err != nil { return err } res, err := settle(turn) if err != nil { return err } fmt.Fprintf(w, "%s → %q pending: %d\n", q, res.Text(), len(s.Pending())) } return s.Close(ctx) } // approvalsQuorum: Quorum(2) needs two distinct approvers. func approvalsQuorum(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== quorum") agent := weft.New(wefttest.Script(deployCall("call_1", "prod"), wefttest.Say("Prod is live.")), deployTool()) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_quorum", "a"), thread.Quorum(2)) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Deploy to prod.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } approve := func(who string) (*thread.Turn, error) { d := thread.Approve("call_1") d.Who = who // unsigned: a declared identity return s.Decide(ctx, d) } resume, err := approve("alice") fmt.Fprintln(w, "after alice:", resume != nil, err, "| pending:", len(s.Pending())) resume, err = approve("bob") if err != nil { return err } res, err := resume.Wait() if err != nil { return err } fmt.Fprintln(w, "after bob:", res.Text()) return s.Close(ctx) } // clock is a session clock the demo moves by hand. type clock struct { mu sync.Mutex t time.Time } func (c *clock) now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t } func (c *clock) advance(d time.Duration) { c.mu.Lock(); defer c.mu.Unlock(); c.t = c.t.Add(d) } // approvalsExpiry: a request past its expiry takes no decision and is // denied with the stated reason. func approvalsExpiry(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== expiry") agent := weft.New(wefttest.Script(deployCall("call_1", "prod"), wefttest.Say("The deploy request lapsed.")), deployTool()) c := &clock{t: base} s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_expiry", "a"), thread.Clock(c.now), thread.RequestExpiry(10*time.Minute)) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Deploy to prod.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } fmt.Fprintln(w, "expires:", s.Pending()[0].Expiry.Format(time.RFC3339)) c.advance(11 * time.Minute) // nobody decided in time _, err = s.Decide(ctx, thread.Approve("call_1")) fmt.Fprintln(w, "too late:", errors.Is(err, thread.ErrExpired)) if _, err := parked.Next().Wait(); err != nil { // the expiry's denial resumed the boundary return err } results(w, s) for _, e := range s.Audit() { switch e := e.(type) { case thread.ApprovalRequestEntry: fmt.Fprintln(w, "request:", e.CallID, e.Tool, "|", e.Reason) case thread.ApprovalAuditEntry: // Detail is prose for a human, never parsed line := "step: " + e.Step + " " + e.Outcome if e.Detail != "" { line += " | " + e.Detail } fmt.Fprintln(w, line) case thread.ApprovalDecisionEntry: fmt.Fprintln(w, "decision:", e.CallID, e.Outcome, "via", e.Via, "|", e.Reason) } } return s.Close(ctx) } // approvalsResume: with AutoResume off the caller drives the resume. func approvalsResume(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== resume") agent := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "deploy", ID: "call_eu", Args: `{"env":"eu"}`}, wefttest.Call{Name: "deploy", ID: "call_us", Args: `{"env":"us"}`}, ), wefttest.Say("The EU region is live."), ), deployTool()) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_resume", "a"), thread.AutoResume(false)) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Deploy to both regions.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } turn, err := s.Decide(ctx, thread.Approve("call_eu")) fmt.Fprintln(w, "decided; resumed on its own:", turn != nil, err) resume, err := s.Resume(ctx) // the undecided call is denied if err != nil { return err } if _, err := resume.Wait(); err != nil { return err } results(w, s) return s.Close(ctx) } ``` [sessions/approvals.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/approvals.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`: ```sh go run ./sessions approvals go test ./sessions ``` ```text == decide turn: parked | pending calls: 1 pending: call_1 refund {"order_id":"1234"} | tool requires approval | request e_a4 resumed: Refund issued for order 1234. | run: s_refund-t2 call_1: refunded 1234 (error: false) == deny, resolve, resolve_error one call, two verdicts: true not pending: true call_a: DENIED: over the refund limit (error: true) call_b: refunded by hand: ticket 88 (error: false) call_c: the payment provider is down (error: true) answer: One refund was denied, one done by hand, one failed. == grants Refund 1234. → "Refunded 1234." pending: 0 Refund 5678. → "" pending: 1 Refund 5678 again. → "Refunded 5678 again." pending: 0 Refund 9999. → "Order 9999 cannot be refunded." pending: 0 Refund 1299. → "" pending: 1 call_1: refunded 1234 (error: false) call_2: refunded 5678 (error: false) call_3: refunded 5678 (error: false) call_4: DENIED: order 9999 is under review (error: true) == approver Deploy to staging. → "Staging is live." pending: 0 notify: deploy {"env":"prod"} parked as e_a14 Now prod. → "" pending: 1 == quorum after alice: false | pending: 1 after bob: Prod is live. == expiry expires: 2026-10-18T09:10:00Z too late: true call_1: DENIED: expired: no decision before 2026-10-18T09:10:00Z (error: true) request: call_1 deploy | tool requires approval step: park parked step: expiry denied | request expired at 2026-10-18T09:10:00Z decision: call_1 deny via expiry | expired: no decision before 2026-10-18T09:10:00Z step: resume started | 1 call(s) to resolve step: resume completed == resume decided; resumed on its own: false call_eu: deployed to eu (error: false) call_us: DENIED: no decision (error: true) ``` Stderr also carries the no-window `WARN` line once per `Session` value that runs a turn ([compaction](https://weftgo.dev/docs/sessions/compaction/#with-no-window)). `sessions/sessions_test.go` also pins that `Decide` returns the parked turn's `Next`, that `Quorum(2)` resumes only on the second identity, and that a request expires strictly after its expiry. ### Best practices & gotchas - **Follow `Next` after `Wait`.** A call a grant or the Approver decided still ends its turn `parked`; the answer is on the resume. (Source: `thread/turn.go:1213-1252`; `Turn.Next` godoc) - **Notify from `OnRequest`, not from your `Send` caller.** It fires once per parked call after the request is durable, before `Wait` returns; keep it quick. (Source: `thread/approval.go:268-287`) - **Put an opaque id in `Who`.** It rides every span and record as `weft.approval.actor`, through content-off. (Source: `thread/approval.go:157-166`) - **Anchor globs and end prefixes with a separator.** `*` spans separators and a prefix is a plain string prefix. (Source: `thread/grants.go:78-102`) - **Do not count unsigned `Who`s as people.** Under `Quorum` an unsigned approval is whatever name the caller wrote; use `RequireSigned` and a key per approver when it matters. (Source: `thread/approval.go:296-311`; ADR 0021 §5) - **Touch an idle session to expire its requests.** Expiry is lazy; nothing fires on a timer. (Source: `thread/approval.go:313-326`; thread-operations §11) - **Make an approved tool idempotent when it must not run twice.** A crash after a resume's `started` entry and before the approved call's result is recorded leaves its decision in force, and the next resume (`Resume`, `Continue`, a `Send` under `AutoResume`, or `Recover`) runs it again. Key it by `weft.CallFromContext`'s call id, the session id (`weft.session.id` in [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext)) and a business key for what the call acts on, such as the order id. The call id is the same on every run of one call, so the run a resume repeats finds the first run's entry. The session id keeps conversations apart, but it is the same on every turn of one session. Within a session only the business key reliably tells operations apart, because a later turn may reuse a call id (weft's Gemini adapter, for one, numbers calls `call_0`, `call_1`, … per step when the API sends no id): keyed by the order id, a later turn's refund of the same order under a repeated call id reads as already done. Name the operation itself, such as a refund request id, when one order may be refunded twice. (Source: `thread/approval.go:1127-1130`, 1327-1335; [the example](https://weftgo.dev/docs/sessions/pools/#make-an-approved-tool-idempotent)) - **Expect `ErrNotPending` after `ErrExpired`.** Once a path has denied a lapsed request, every later decide or `Request` for it reads `ErrNotPending`. (Source: `thread/approval.go:313-326` RequestExpiry godoc) - **Branch away to abandon a boundary.** Until it resolves, `Compact` fails with `ErrAwaitingApproval` and a plain `Send` queues behind it. (Source: `thread/compaction.go:123-126`; `Session.Decide` godoc; ADR 0021 amendment 2026-09-29) ### See also - [Sign approval decisions](https://weftgo.dev/docs/sessions/signed-approvals/) - [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/): the core boundary under the session - [What happens when you send while a turn runs?](https://weftgo.dev/docs/sessions/busy-and-steering/): a steer never decides a parked call - [Run bounded child sessions with a pool](https://weftgo.dev/docs/sessions/pools/): a child's parked call surfaces in its parent's `Pending` Symbols used: [`Session.Pending`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Pending) · [`Session.Decide`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Decide) · [`Session.Resume`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Resume) · [`Session.Grant`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Grant) · [`Session.Revoke`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Revoke) · [`Session.Audit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Audit) · [`Turn.Next`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.Next) · [`thread.Decision`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Decision) · [`thread.Request`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Request) · [`thread.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Approve) · [`thread.ApproveAlways`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ApproveAlways) · [`thread.Deny`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Deny) · [`thread.Resolve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Resolve) · [`thread.ResolveError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ResolveError) · [`thread.Grant`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Grant) · [`thread.Arg`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Arg) · [`thread.ArgPrefix`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ArgPrefix) · [`thread.ArgEquals`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ArgEquals) · [`thread.ArgGlob`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ArgGlob) · [`thread.WithApprover`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithApprover) · [`thread.OnRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OnRequest) · [`thread.Quorum`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Quorum) · [`thread.RequestExpiry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#RequestExpiry) · [`thread.AutoResume`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#AutoResume) · [`thread.Clock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Clock) · [`thread.ApprovalAuditEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ApprovalAuditEntry) · [`jsonl.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open) · [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Sign approval decisions URL: https://weftgo.dev/docs/sessions/signed-approvals/ Markdown: https://weftgo.dev/docs/sessions/signed-approvals.md > Make weft/thread approval decisions that cross a process boundary verifiable: a Keyring of HMAC keys, a challenge from s.Request, a signature from ring.Sign or key.Sign, and DecideSigned, which verifies fail-closed; RequireSigned closes the unsigned door for the session's whole life. A signed decision is an approval that crossed a process boundary, a web UI or a chat integration, and can be checked: the session mints a challenge over one pending request with [`s.Request(callID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Request), the signing side signs a decision over it with [`ring.Sign`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Keyring.Sign) or [`key.Sign`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Key.Sign), and [`s.DecideSigned`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.DecideSigned) verifies it before anything is recorded. [`thread.RequireSigned()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#RequireSigned) refuses every unsigned decision, for the session's whole life. `sessions/signed.go` builds a keyring and a session that requires signed decisions: ```go title="sessions/signed.go" ring, err := thread.NewKeyring(thread.Key{ ID: "ops-1", // only the id is ever written to the session Secret: []byte("held by the approval service only"), // never written anywhere by thread Active: true, // new challenges are minted under it }) if err != nil { return err } s, err := thread.Create(ctx, st, agent, ids("s_signed", "a"), thread.Clock(c.now), thread.WithKeyring(ring), thread.RequireSigned(), // stored in the header: every Open enforces it thread.RequestExpiry(time.Hour)) if err != nil { return err } ``` [sessions/signed.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/signed.go) Then it parks a deploy and decides it signed: ```go title="sessions/signed.go" _, err = s.Decide(ctx, thread.Approve("call_1")) fmt.Fprintln(w, "unsigned:", errors.Is(err, thread.ErrSignatureRequired), "| requires signed:", s.RequiresSigned()) challenge, err := s.Request("call_1") // a fresh challenge; travels to the signing side if err != nil { return err } fmt.Fprintln(w, "challenge: request", challenge.ID, "run", challenge.RunID, "key", challenge.KeyID, "| nonce:", challenge.Nonce != "", "| expires:", challenge.Expiry.Format(time.RFC3339)) signed, err := ring.Sign(challenge, thread.Approve("call_1")) // travels back if err != nil { return err } resume, err := s.DecideSigned(ctx, signed) // verified, then recorded, then resumed if err != nil { return err } res, err := resume.Wait() if err != nil { return err } fmt.Fprintln(w, "resumed:", res.Text()) ``` [sessions/signed.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/signed.go) ```text unsigned: true | requires signed: true challenge: request e_a4 run s_signed-t1 key ops-1 | nonce: true | expires: 2026-10-18T10:00:00Z resumed: Prod is live. ``` The unsigned `Decide` was refused with [`thread.ErrSignatureRequired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrSignatureRequired). The challenge names the request entry and the run that parked the call, and the signed approval resumed the session as `Decide` would ([Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/)). ### Sign a decision **The keyring.** A [`thread.Keyring`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Keyring) holds HMAC-SHA256 keys by id. [`thread.NewKeyring(keys...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NewKeyring) needs at least one [`thread.Key`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Key): each a non-empty, unique `ID`, a non-empty `Secret` of any length, and `Active` on at most one. Every key verifies; the active key is the one new challenges are minted under. A ring with no active key is verify-only: it checks decisions over earlier challenges and mints none. A ring is immutable and safe for concurrent use. Keys never touch the session file, only key ids do, so a leaked file cannot forge a decision. **The session.** [`thread.WithKeyring(r)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithKeyring) makes the session verify under `r` and mint challenges from its active key. A ring is configuration, not state: pass it at every `Create` and `Open`. `RequireSigned` adds the rule that only signed decisions count. `Create` writes it into the header as the metadata key `weft.require_signed`, so every later `Open` enforces it whether or not it passes the option, a `Fork` inherits it (with the origin's keyring unless given its own), and pool children inherit it. Nothing loosens it. [`s.RequiresSigned()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.RequiresSigned) reports it, for a caller that must know before it promises a decision: ```go title="sessions/signed.go" _, err = thread.Open(ctx, st, "s_signed", agent) // no keyring: the header's rule cannot be met fmt.Fprintln(w, "open without a keyring:", err) again, err := thread.Open(ctx, st, "s_signed", agent, ids("", "b"), thread.WithKeyring(ring)) // no RequireSigned passed if err != nil { return err } fmt.Fprintln(w, "requires signed:", again.RequiresSigned(), "| header:", again.Meta()["weft.require_signed"]) ``` [sessions/signed.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/signed.go) ```text open without a keyring: thread: RequireSigned needs WithKeyring: without a keyring no decision could be verified requires signed: true | header: true ``` `Create` and `Open` fail when `RequireSigned` is in force and the session has no keyring, or a ring with no active key: no call it parked could ever be decided. Under the rule the session's own machinery still records, each with its audit entry: grants, the Approver, expiry, an interrupting `Send`'s denial, a pool delegation's resolution. **The challenge.** `s.Request(callID)` returns the pending [`thread.Request`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Request) with a fresh nonce and the active key's id. For a live request it writes nothing and may be called any number of times, each call minting another valid challenge. It fails with `ErrNotPending` for a call that is not pending, `ErrDelegated` for a call that delegates to a pool child, `ErrExpired` for a request past its expiry, and an error when the session has no keyring with an active key. A lapsed request is swept before `ErrExpired` returns, as every other path sweeps it. `Request` records the expiry's denial, so `Pending` stops offering it, and, under `AutoResume` (the default), resumes the boundary when that completes it. Under `RequireSigned` no unsigned `Decide` comes to sweep it. Once any path has denied it, `Request`, `Decide` and `DecideSigned` for it fail with `ErrNotPending`, not `ErrExpired` ([expiry](https://weftgo.dev/docs/sessions/approvals/#approvers-quorum-and-expiry)). The `Pending()` view of the same request carries no nonce. | `Request` field | Holds | |---|---| | `ID` | The request entry's id: this occurrence of the call. Empty on the request an Approver is handed. | | `Session` | The session the request lives in. | | `CallID`, `Tool` | The pending call's id and tool name. | | `Args`, `ArgsSHA256` | The arguments as the model wrote them, and their hex SHA-256. | | `RunID` | The run that parked the call. | | `Reason` | Why it parked. | | `Expiry`, `Created` | When it lapses (zero: never) and when it was persisted. | | `Nonce`, `KeyID` | The challenge and the key it was minted under; set by `Request` only. | | `Child` | The pool child session a mirrored request parks in; empty on an ordinary request. | **The signature.** The signing side signs with what it holds, and each returns a [`thread.SignedDecision`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SignedDecision): - **`ring.Sign(req, d)`** for a process holding the whole ring: it looks up the key the challenge names, and fails with [`thread.ErrUnknownKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrUnknownKey) when the ring does not hold it. - **`key.Sign(req, d)`** for an approver holding a key of their own: the signature names that key, whichever key minted the challenge, so under `Quorum` it counts as this approver. The verifying ring must hold the key ([`ExampleQuorum`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Quorum)). - **[`thread.SignDecision(secret, req, d)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SignDecision)** for a signer with a bare secret, the key `req.KeyID` names. An empty `d.Who` is signed as the key's id. `ring.Sign` and `key.Sign` fail on a request without a nonce, the `Pending` view; `key.Sign` also on a key with no id or secret. Both arrived in thread 0.9.0, replacing a hand-kept map of secrets passed to `SignDecision`. The MAC covers the challenge and the decision together, so neither can be altered in flight: | `SignedDecision` field | Holds | |---|---| | `Session`, `RequestID`, `RunID` | The occurrence the challenge was minted for. | | `CallID`, `Tool`, `ArgsSHA256` | The call it answers, and the arguments hash the signer approved. | | `Expiry` | The request's expiry as the challenge stated it; it must equal the request's own. | | `Kind`, `Reason`, `Content`, `Always` | The decision: the outcome, a deny reason, a resolve payload, approve-and-always-allow. | | `Who` | A label for the audit trail; the identity is `KeyID`. | | `Nonce`, `KeyID`, `MAC` | The challenge answered, the signing key, and the HMAC-SHA256 over every field above. | **The verification.** `s.DecideSigned(ctx, sd)` records no decision until every check passes (the expiry sweep's own denials and a refusal's audit entry may still land), then records the decision with `Via` `signed`, its nonce and key id, and resumes when the boundary completes, as `Decide` does. The checks, in order: | Check | Error | |---|---| | The MAC under the key `sd.KeyID` names (constant-time), an outcome that is one of the four, this session, a non-empty nonce. An unknown key id fails the same way, in the same words. | [`ErrBadSignature`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrBadSignature) | | The nonce has not answered a recorded decision. | [`ErrReplay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrReplay) | | The request is not past its own expiry, by the session's clock. | `ErrExpired` | | A pending call with that id, and the occurrence signed (request entry and run). | `ErrNotPending` | | A nonce the ring minted for this request, and the request's own expiry. | `ErrBadSignature` | | The arguments hash is the request's. | [`ErrArgsChanged`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrArgsChanged) | | The tool is the request's. | `ErrBadSignature` | A signature that passes every check but names a call delegating to a pool child fails with `ErrDelegated`, unrecorded. `DecideSigned` without a keyring fails. The package example is [`ExampleSession_DecideSigned`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.DecideSigned). **Rotation.** Build a new ring with the new key active and the old keys still in it, and hand it to sessions as they open: requests challenged under an old key keep verifying. Drop an old key only when nothing minted under it can still be pending; after that a decision signed with it is `ErrBadSignature`. ### Security properties No refusal records a decision from the signer: ```go title="sessions/signed.go" _, err = s.DecideSigned(ctx, signed) // the same bytes again fmt.Fprintln(w, "replayed:", errors.Is(err, thread.ErrReplay)) parked, err = s.Send(ctx, weft.User("Deploy to prod again.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } challenge, err = s.Request("call_2") if err != nil { return err } forged, err := thread.Key{ID: "ops-1", Secret: []byte("a guess")}.Sign(challenge, thread.Approve("call_2")) if err != nil { return err } _, err = s.DecideSigned(ctx, forged) fmt.Fprintln(w, "forged:", errors.Is(err, thread.ErrBadSignature), "| still pending:", len(s.Pending())) stranger := challenge stranger.KeyID = "ops-9" // a key this ring does not hold _, err = ring.Sign(stranger, thread.Approve("call_2")) fmt.Fprintln(w, "unknown key:", errors.Is(err, thread.ErrUnknownKey)) late, err := ring.Sign(challenge, thread.Approve("call_2")) // genuine, but signed too late if err != nil { return err } c.advance(2 * time.Hour) // past the request's own expiry _, err = s.DecideSigned(ctx, late) fmt.Fprintln(w, "expired:", errors.Is(err, thread.ErrExpired)) if _, err := parked.Next().Wait(); err != nil { // the session denied it and resumed return err } for _, e := range s.Audit() { if a, ok := e.(thread.ApprovalAuditEntry); ok && a.Step == thread.StepSigned { fmt.Fprintln(w, "audit:", a.Step, a.Outcome, a.CallID, "|", a.Detail) } } ``` [sessions/signed.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/signed.go) ```text replayed: true forged: true | still pending: 1 unknown key: true expired: true audit: signed refused call_1 | replayed audit: signed refused call_2 | bad signature audit: signed refused call_2 | expired ``` The forged signature left the call pending. The unknown key was refused on the signer's side, by `ring.Sign`. The expired request was then denied by the session itself, with its stated reason, and the parked turn's `Next` resumed it. What the signing guarantees, as of thread 0.9.0: - **A signature answers one occurrence.** The challenge signs the request entry's id and the run id beside the call id, and both are checked against the pending request, so a signature for one turn's `call_1` cannot approve a later turn's `call_1` (`ErrNotPending`). The challenge domain is `weft/approval-challenge/v2`; no v1 signature verifies, so a challenge minted before thread 0.9.0 must be requested again. - **A nonce is the session's.** An empty nonce is a bad signature, and the nonce must carry a tag only a ring key can compute for that request, so a nonce made up elsewhere or lifted from another challenge fails. Nonces are recorded on decision entries, so the replay guard survives restarts. - **The request's expiry rules.** The session enforces the request's own expiry, by its clock, on every path that records a decision or arms a resume (`Decide`, `DecideSigned`, `Resume`, `Send`, the runner's pickup), never the expiry the signer stated. - **`RequireSigned` is durable.** It lives in the header: every `Open` enforces it, a fork and a pool child inherit it, and it does not block the session's own denials and resolutions. - **A decision is spent by its resume.** After a `Branch` back to a decided boundary the calls are pending again and need new signatures. - **Quorum counts keys.** One key that signs as two `Who`s is one approver; give every approver their own key. - **Key ids stay private.** An unknown key id and a bad MAC both read `ErrBadSignature` and cost the same time, so `DecideSigned` tells a caller nothing about which ids exist. Only `ring.Sign`, on the ring holder's side, says `ErrUnknownKey`. - **Refusals are audited, within bounds.** A refused signature leaves a [`StepSigned`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#StepSigned) audit entry naming the reason, the call and, when the ring holds it, the key; at most 16 per request, and nothing for a signature that fails its MAC and names no pending call ([the audit trail](https://weftgo.dev/docs/sessions/approvals/#the-audit-trail)). What it does not cover: `s.Grant` stays an in-process, unsigned call, so whoever can call it can pre-approve; the audit trail is plain appended lines, not tamper-evidence; and a signed decision's `Who` is a label, its key the identity. ### Complete example `sessions/signed.go` decides signed, then shows each refusal and a reopen: ```go title="sessions/signed.go" package main import ( "context" "errors" "fmt" "io" "time" "github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/thread/jsonl" "github.com/weftgo/weft/wefttest" ) // demoSigned is the page "Sign approval decisions". func demoSigned(ctx context.Context, w io.Writer, dir string) error { agent := weft.New(wefttest.Script( deployCall("call_1", "prod"), wefttest.Say("Prod is live."), deployCall("call_2", "prod"), wefttest.Say("The second deploy lapsed."), ), deployTool()) st, err := jsonl.Open(dir) if err != nil { return err } c := &clock{t: base} fmt.Fprintln(w, "== signed decision") ring, err := thread.NewKeyring(thread.Key{ ID: "ops-1", // only the id is ever written to the session Secret: []byte("held by the approval service only"), // never written anywhere by thread Active: true, // new challenges are minted under it }) if err != nil { return err } s, err := thread.Create(ctx, st, agent, ids("s_signed", "a"), thread.Clock(c.now), thread.WithKeyring(ring), thread.RequireSigned(), // stored in the header: every Open enforces it thread.RequestExpiry(time.Hour)) if err != nil { return err } parked, err := s.Send(ctx, weft.User("Deploy to prod.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } _, err = s.Decide(ctx, thread.Approve("call_1")) fmt.Fprintln(w, "unsigned:", errors.Is(err, thread.ErrSignatureRequired), "| requires signed:", s.RequiresSigned()) challenge, err := s.Request("call_1") // a fresh challenge; travels to the signing side if err != nil { return err } fmt.Fprintln(w, "challenge: request", challenge.ID, "run", challenge.RunID, "key", challenge.KeyID, "| nonce:", challenge.Nonce != "", "| expires:", challenge.Expiry.Format(time.RFC3339)) signed, err := ring.Sign(challenge, thread.Approve("call_1")) // travels back if err != nil { return err } resume, err := s.DecideSigned(ctx, signed) // verified, then recorded, then resumed if err != nil { return err } res, err := resume.Wait() if err != nil { return err } fmt.Fprintln(w, "resumed:", res.Text()) fmt.Fprintln(w, "== refusals") _, err = s.DecideSigned(ctx, signed) // the same bytes again fmt.Fprintln(w, "replayed:", errors.Is(err, thread.ErrReplay)) parked, err = s.Send(ctx, weft.User("Deploy to prod again.")) if err != nil { return err } if _, err := parked.Wait(); err != nil { return err } challenge, err = s.Request("call_2") if err != nil { return err } forged, err := thread.Key{ID: "ops-1", Secret: []byte("a guess")}.Sign(challenge, thread.Approve("call_2")) if err != nil { return err } _, err = s.DecideSigned(ctx, forged) fmt.Fprintln(w, "forged:", errors.Is(err, thread.ErrBadSignature), "| still pending:", len(s.Pending())) stranger := challenge stranger.KeyID = "ops-9" // a key this ring does not hold _, err = ring.Sign(stranger, thread.Approve("call_2")) fmt.Fprintln(w, "unknown key:", errors.Is(err, thread.ErrUnknownKey)) late, err := ring.Sign(challenge, thread.Approve("call_2")) // genuine, but signed too late if err != nil { return err } c.advance(2 * time.Hour) // past the request's own expiry _, err = s.DecideSigned(ctx, late) fmt.Fprintln(w, "expired:", errors.Is(err, thread.ErrExpired)) if _, err := parked.Next().Wait(); err != nil { // the session denied it and resumed return err } for _, e := range s.Audit() { if a, ok := e.(thread.ApprovalAuditEntry); ok && a.Step == thread.StepSigned { fmt.Fprintln(w, "audit:", a.Step, a.Outcome, a.CallID, "|", a.Detail) } } if err := s.Close(ctx); err != nil { return err } fmt.Fprintln(w, "== reopen") _, err = thread.Open(ctx, st, "s_signed", agent) // no keyring: the header's rule cannot be met fmt.Fprintln(w, "open without a keyring:", err) again, err := thread.Open(ctx, st, "s_signed", agent, ids("", "b"), thread.WithKeyring(ring)) // no RequireSigned passed if err != nil { return err } fmt.Fprintln(w, "requires signed:", again.RequiresSigned(), "| header:", again.Meta()["weft.require_signed"]) return again.Close(ctx) } ``` [sessions/signed.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/signed.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`: ```sh go run ./sessions signed go test ./sessions ``` ```text == signed decision unsigned: true | requires signed: true challenge: request e_a4 run s_signed-t1 key ops-1 | nonce: true | expires: 2026-10-18T10:00:00Z resumed: Prod is live. == refusals replayed: true forged: true | still pending: 1 unknown key: true expired: true audit: signed refused call_1 | replayed audit: signed refused call_2 | bad signature audit: signed refused call_2 | expired == reopen open without a keyring: thread: RequireSigned needs WithKeyring: without a keyring no decision could be verified requires signed: true | header: true ``` Stderr also carries the no-window `WARN` line once per `Session` value that runs a turn: once here, since the reopened session runs none. `sessions/sessions_test.go` also pins that a forged signature records no decision and resolves nothing, and that `RequireSigned` survives a reopen that does not pass it. weft's [`thread/examples/approvals`](https://github.com/weftgo/weft/tree/v0.20.2/thread/examples/approvals) runs the same flow across a restart ([the approvals example](https://weftgo.dev/docs/sessions/approvals/#the-approvals-example)). ### Best practices & gotchas - **Keep secrets in the signing process.** The session needs the ring to verify; the session file never holds key bytes, only ids. (Source: `thread/signing.go:23-25`; ADR 0021 §3) - **Mint a fresh challenge per signature.** `Request` writes nothing for a live request, and each nonce answers one decision; a reused signature is `ErrReplay`. (Source: `thread/signing.go:408-420`) - **Pass `WithKeyring` on every `Open`.** A session created with `RequireSigned` cannot be opened without a ring that has an active key. (Source: `thread/signing.go:171-188`; thread-operations §11) - **Give each approver their own key under `Quorum`.** A key is one identity whatever `Who` it signs. (Source: `thread/approval.go:1437-1451`; CHANGELOG.md:3642) - **Keep old keys through a rotation.** Drop one only when nothing it challenged can still be pending. (Source: thread-operations §11) - **Put an opaque id in `KeyID` and `Who`.** The signed decision's key id rides the resumed run as `weft.approval.actor`. (Source: `thread/approval.go:157-166`) ### See also - [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/): `Pending`, `Decide`, grants, quorum and expiry - [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/): the core boundary - [Operate sessions in production](https://weftgo.dev/docs/sessions/operations/): key rotation and the approvals runbook Symbols used: [`thread.NewKeyring`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NewKeyring) · [`thread.Keyring`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Keyring) · [`Keyring.Sign`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Keyring.Sign) · [`thread.Key`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Key) · [`Key.Sign`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Key.Sign) · [`thread.SignDecision`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SignDecision) · [`thread.SignedDecision`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SignedDecision) · [`thread.WithKeyring`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithKeyring) · [`thread.RequireSigned`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#RequireSigned) · [`thread.Request`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Request) · [`Session.Request`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Request) · [`Session.DecideSigned`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.DecideSigned) · [`Session.RequiresSigned`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.RequiresSigned) · [`Session.Audit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Audit) · [`thread.RequestExpiry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#RequestExpiry) · [`thread.Clock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Clock) · [`thread.ErrBadSignature`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrBadSignature) · [`thread.ErrReplay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrReplay) · [`thread.ErrExpired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrExpired) · [`thread.ErrArgsChanged`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrArgsChanged) · [`thread.ErrUnknownKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrUnknownKey) · [`thread.ErrSignatureRequired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrSignatureRequired) · [`jsonl.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open) --- # Run bounded child sessions with a pool URL: https://weftgo.dev/docs/sessions/pools/ Markdown: https://weftgo.dev/docs/sessions/pools.md > Delegate work from a weft/thread session to child agents with thread/pool: pool.New(max) bounds the child runs at work, MustWrap and Submit start children as sessions of their own, receipts record each delegation, and Decide, Wait, Forward, Cancel, Recover and Close manage them. [`pool.New(max)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#New) returns a [`*pool.Pool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool) that admits at most `max` child runs at work at once. [`p.MustWrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.MustWrap) turns an agent into a delegation tool, and [`p.Submit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Submit) hands it work directly. Every child runs as a [session](https://weftgo.dev/docs/reference/glossary/#session) of its own in the parent's storage, each delegation leaves receipt entries in the parent, and the child's cost lands in the parent's `Usage.Delegated`. `sessions/pools.go` wraps a research agent and lets the support agent call it: ```go title="sessions/pools.go" p := pool.New(4, childIDs()) // at most 4 child runs at work at once researcher := weft.New(wefttest.Script(wefttest.Say("Order 1234 left the Leeds depot on Monday."))) research := p.MustWrap("research", "Research an order in depth.", researcher) support := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", ID: "call_1", Args: `{"prompt":"Trace order 1234."}`}), wefttest.Say("Order 1234 left the depot on Monday."), ), research) s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_support", "a"), at(base)) if err != nil { return thread.Usage{}, err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) if err != nil { return thread.Usage{}, err } res, err := turn.Wait() if err != nil { return thread.Usage{}, err } fmt.Fprintln(w, "reply:", res.Text()) for _, r := range pool.Receipts(s) { fmt.Fprintf(w, "receipt %s: %s child %s call %s stop %q\n", r.ID, r.State, r.Child, r.Call, r.Stop) } u := s.Usage() fmt.Fprintln(w, "output tokens: run", res.Usage.OutputTokens, "| turns", u.Turns.OutputTokens, "| delegated", u.Delegated.OutputTokens) ``` [sessions/pools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/pools.go) ```text reply: Order 1234 left the depot on Monday. receipt e_a3: done child c_1 call call_1 stop "Order 1234 left the Leeds depot on Monday." output tokens: run 10 | turns 10 | delegated 5 ``` The call waited for the child and read its answer. The receipt names the child session (`c_1`, minted by `childIDs`, a [`pool.IDs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#IDs) option that keeps the output stable) and the call that delegated. The child's 5 output tokens are in `Delegated`, not in the run's usage. `ids`, `at` and `ctxWindow` are the demos' helpers for pinned ids, a pinned clock and a context window. ### How a pool works A pool is a bound on concurrent child runs, per `Pool` value: two pools are two bounds, and a process that wants one bound shares one `Pool`. The bound is the pool's reason to exist, so `pool.New` panics when `max` is below 1. - **A slot is held while a child works, not while it waits.** A child holds one slot during its model calls and tool calls. A child waiting on a sync delegation of its own gives its slot up for the wait and queues for one again before it works again. A child parked at an approval holds none. That hand-off is why fan-out times depth is safe on any `max`, 1 included. - **Admission is first in, first out**, in the order work queued: `Submit` queues before it returns, a wrapped tool queues when it is called, and a parent taking its slot back queues behind whatever was already waiting. - **Depth has its own bound.** [`pool.MaxDepth(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#MaxDepth) caps how deep a chain of delegations goes: 1 allows children, 2 children of children. The default is [`pool.DefaultMaxDepth`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#DefaultMaxDepth), 8. Since waiting parents hold no slot, depth costs sessions and tokens, not capacity ([`ExampleMaxDepth`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-MaxDepth)). In thread 0.5.0 the bound doubled as the depth guard and a too-deep chain read `SUBAGENT_CYCLE`; since thread 0.9.0 depth is `MaxDepth`'s and reads `SUBAGENT_DEPTH`. - **A child is a session.** It is created in the parent's storage with a header whose `lineage` names the parent session and, for a wrapped tool, the delegating call. A wrapped child also records the wrap's name in its header metadata (`pool_agent`): the name is the resume key after a restart. The child inherits the parent's approval policy through [`thread.InheritApprovals`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#InheritApprovals): request expiry, quorum, keyring, `RequireSigned` and clock. - **A child's events are its own.** They are not [`weft.Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested) events in the parent's stream; read or tail the child session instead. - **The pool changes nothing in the core.** A wrapped tool is the core's [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) under a tool-level [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) middleware, plus session entries and pool-owned goroutines. A pool is safe for concurrent use; the zero value is not usable. The package's own API, in one place: | Call | Does | |---|---| | [`pool.New(max, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#New) | A pool of `max` slots; options `pool.MaxDepth`, `pool.IDs` | | [`p.Wrap(name, desc, agent, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Wrap) | A delegation tool, `(*weft.ToolDef, error)`; `p.MustWrap` panics instead | | [`p.Submit(ctx, parent, agent, prompt)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Submit) | Start a child now; returns its `*Receipt` at once | | [`p.Wait(ctx, parent, receiptID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Wait) | Block until the delegation is settled or parked | | [`p.Decide(ctx, parent, ds...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Decide) | Record decisions over children's requests and arm the children; does not wait | | [`p.DecideSigned(ctx, parent, sd)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.DecideSigned) | `Decide` for one signed decision | | [`p.Forward(ctx, parent, receiptID, msg)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Forward) | Steer a running child | | [`p.Cancel(ctx, parent, receiptID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Cancel) | End one delegation | | [`p.Register(sessionID, agent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Register) | Attach an agent to a child no wrap names, before `Recover` | | [`p.Recover(ctx, parent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Recover) | After a restart, make the parent's ledger say what is true | | [`p.Close(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Close) | Cancel what runs, drain, take no more work | | [`pool.Receipts(parent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipts) | The parent's delegations, from its entries | | [`pool.Children(ctx, parent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Children), [`pool.Descendants(ctx, parent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Descendants) | The child sessions, direct or the whole subtree | ### Delegate with a pool There are two ways in. A wrapped tool lets the parent's model delegate; `Submit` lets your code delegate. Both create the child session, write the acceptance receipt in the parent and queue the child before they return. #### Wait for the child's answer `p.Wrap(name, description, agent, opts...)` returns a subagent tool whose children the pool runs. Inside a session's run, found through the run's context ([`thread.SessionFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext)), the call is sync by default: it waits, and the result is the child's answer. The tool's input is the subagent schema, `{"prompt": "..."}`. - `Wrap` fails on a nil agent or an empty name, and with [`pool.ErrDuplicateWrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrDuplicateWrap) for a name the pool already wraps a different agent under: one name names one agent. Wrapping the same agent again returns another tool for it. `MustWrap` panics on those errors, for wiring where the arguments are the program's own. - [`pool.ToolOptions(opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ToolOptions) forwards weft tool options to the underlying subagent tool: `Timeout`, `MaxResultBytes`, a snippet. `weft.RequireApproval` gates the act of delegating, as on any tool. - A wrapped tool called outside any session, from a bare `Generate`, has no parent to receipt into. It falls back to the ordinary subagent path under a slot (`TestWrapOutsideSession`). The package example is [`ExamplePool_Wrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Wrap). #### Delegate in the background [`pool.Async()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Async) makes the tool's result an acceptance receipt instead of the child's answer. The model reads one line, and the child runs on: ```go title="sessions/pools.go" p := pool.New(4, childIDs()) refunds := p.MustWrap("refunds", "Start a refund in the background.", refunder, pool.Async()) support := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "refunds", ID: "call_1", Args: `{"prompt":"Refund order 1234."}`}), wefttest.Say("The refund has started."), ), refunds) s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_async", "a"), at(base)) if err != nil { return pool.Receipt{}, err } turn, err := s.Send(ctx, weft.User("Refund order 1234.")) if err != nil { return pool.Receipt{}, err } res, err := turn.Wait() if err != nil { return pool.Receipt{}, err } fmt.Fprintln(w, "the model read:", lastToolResult(res.Messages)) fmt.Fprintln(w, "reply:", res.Text()) ``` [sessions/pools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/pools.go) ```text the model read: background task accepted; receipt e_a3 reply: The refund has started. ``` The line `background task accepted; receipt ` is model-visible text, pinned by `TestWrapAsyncGolden`. The answer reaches the model only when your application delivers it in a later turn. `Async` needs a parent session. Under a plain `Generate`, with no `thread.Session` on the context, the wrap takes the bare path before it checks `Async`: the call blocks until the child finishes, and the model reads the child's answer instead of the receipt line. `p.Submit(ctx, parent, agent, prompt)` is the same primitive, called by your code. It returns a [`*pool.Receipt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipt) at once, state `accepted`. The child runs on a pool-owned context: the submitting caller's cancellation does not reach it, and only `Cancel` or `Close` end it. Its context still carries the delegating run's values, so a `weft.ParkAllExcept` list and the run metadata bind it as they bind a sync child. `parent` and `agent` must not be nil. Called from inside a pool child's run, `Submit` counts depth and ancestry from there and fails with [`pool.ErrDepth`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrDepth) or [`pool.ErrCycle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrCycle). Four submits on a pool of two: ```go title="sessions/pools.go" p := pool.New(2, childIDs()) var receipts []*pool.Receipt for i := range 4 { r, err := p.Submit(ctx, parent, wk.agent(), fmt.Sprintf("task %d", i+1)) if err != nil { return 0, err } receipts = append(receipts, r) // returned at once, state accepted } <-wk.started <-wk.started // two children are inside their tool; the other two queue states := map[pool.State]int{} for _, r := range pool.Receipts(parent) { states[r.State]++ } fmt.Fprintln(w, "running:", states[pool.Running], "accepted:", states[pool.Accepted]) close(wk.release) for i, r := range receipts { final, err := p.Wait(ctx, parent, r.ID) if err != nil { return 0, err } fmt.Fprintf(w, "task %d: %s\n", i+1, final.State) } if err := p.Close(ctx); err != nil { return 0, err } ``` [sessions/pools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/pools.go) ```text running: 2 accepted: 2 task 1: done task 2: done task 3: done task 4: done ``` Two children hold the slots; the other two wait in the pool's queue, their receipts `accepted`. `p.Wait` blocks until a delegation is at rest: settled, or parked at an approval. A receipt no child of this pool is working returns at once, as it stands. `TestPoolBound` asserts that no more than two were ever at work at once; the package example is [`ExamplePool_Submit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Submit). To watch a child live, tail its session: `r.Child` names it, and a storage with the [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) capability (jsonl, sqlite; `thread.Memory` has none) yields its entries as they land ([`ExamplePool_Submit_watch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Submit-Watch), [Watch a session](https://weftgo.dev/docs/sessions/storage/#watch-a-session)). #### Decide a child's approvals A child that reaches a `weft.RequireApproval` tool parks, and its request surfaces on the parent's [`s.Pending()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Pending). Decide it through the pool: ```go title="sessions/pools.go" r := pool.Receipts(s)[0] rest, err := p.Wait(ctx, s, r.ID) // at rest: settled, or parked at an approval if err != nil { return pool.Receipt{}, err } fmt.Fprintln(w, "receipt:", rest.State) for _, req := range s.Pending() { fmt.Fprintln(w, "pending:", req.CallID, req.Tool, "in", req.Child) } if err := p.Decide(ctx, s, thread.Approve(s.Pending()[0].CallID)); err != nil { return pool.Receipt{}, err // Decide records and arms the child; it does not wait } final, err := p.Wait(ctx, s, r.ID) if err != nil { return pool.Receipt{}, err } fmt.Fprintf(w, "receipt: %s %q | delegated output tokens: %d\n", final.State, final.Stop, s.Usage().Delegated.OutputTokens) ``` [sessions/pools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/pools.go) ```text receipt: parked pending: c_1/call_r refund in c_1 receipt: done "Refunded order 1234." | delegated output tokens: 10 ``` The request's call id is namespaced, `/`, and `Request.Child` names the session it parks in. `p.Decide` records the decision in the parent first, through the parent's own `Decide` (validation, quorum, audit and expiry live there), then runs the pump: every child whose pending calls now all hold a verdict is queued to resume. It returns once the decisions are recorded and the children queued; follow the child with `p.Wait`. The error joins every failure: the parent's refusal (nothing recorded, nothing pumped), or per child, why it could not be armed. A `RequireSigned` parent refuses `Decide` with `thread.ErrSignatureRequired`; use [`p.DecideSigned`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.DecideSigned) ([Sign approval decisions](https://weftgo.dev/docs/sessions/signed-approvals/)). `p.Decide(ctx, parent)` with no decisions is the pump alone, and always safe to call. The mechanism is in [Nested approvals](https://weftgo.dev/docs/sessions/pools/#nested-approvals); the package example is [`ExamplePool_Decide`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Decide). #### Steer a running child `p.Forward(ctx, parent, receiptID, msg)` sends `msg` to the child's session under the `Steer` policy. It is delivered at the run's next drain point, or deferred to a follow-up turn when the run ends first ([Steer into the running turn](https://weftgo.dev/docs/sessions/busy-and-steering/#steer-into-the-running-turn)). Nothing is ever forwarded implicitly: ```go title="sessions/pools.go" r, err := p.Submit(ctx, s, converter, "Convert the totals.") if err != nil { return err } <-started // the child is mid-run, inside its tool if _, err := p.Forward(ctx, s, r.ID, weft.User("Use euros, not dollars.")); err != nil { return err } close(release) final, err := p.Wait(ctx, s, r.ID) if err != nil { return err } fmt.Fprintln(w, "forwarded:", final.State, final.Stop) _, err = p.Forward(ctx, s, r.ID, weft.User("Too late.")) var se *pool.StateError fmt.Fprintln(w, "after the end:", errors.Is(err, pool.ErrNotRunning), errors.As(err, &se) && se.State == pool.Done) ``` [sessions/pools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/pools.go) ```text forwarded: done Converted the totals to euros. after the end: true true ``` A child that is not running refuses with a [`*pool.StateError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#StateError) naming its state: `accepted` (a steer now would run as the session's first turn), `parked` (its fate is the decision) or settled. The returned `*thread.Turn` is the steer's receipt turn ([`ExamplePool_Forward`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Forward)). **A child that has just taken its slot can refuse for a moment; retry.** `Forward` needs the run's turn in flight, not only its `running` receipt. Between taking the slot and sending its turn, the child refuses as the state it is leaving: `accepted` before its first turn, `parked` before a resume. The refusal changes nothing, and a retry a moment later steers. Once the send is under way, `Forward` waits for it, bounded by `ctx`. A refusal of this pool's child never reads `running`; only an `Orphan`'s can (`TestForwardRetriedFromTheReceiptSteers`). #### Cancel a delegation `p.Cancel(ctx, parent, receiptID)` ends one delegation: ```go title="sessions/pools.go" r, err = p.Submit(ctx, s, holder, "Wait for the warehouse.") if err != nil { return err } <-held if err := p.Cancel(ctx, s, r.ID); err != nil { // cancels the run; Wait follows the settlement return err } final, err = p.Wait(ctx, s, r.ID) if err != nil { return err } fmt.Fprintln(w, "canceled:", final.State, final.Settled()) fmt.Fprintln(w, "cancel again:", errors.Is(p.Cancel(ctx, s, r.ID), pool.ErrNotRunning)) fmt.Fprintln(w, "unknown receipt:", errors.Is(p.Cancel(ctx, s, "e_nope"), pool.ErrUnknownReceipt)) ``` [sessions/pools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/pools.go) ```text canceled: canceled true cancel again: true unknown receipt: true ``` What it does depends on where the child is: - **Running:** the run is canceled and the child records a canceled turn. - **Queued for a slot:** it never starts; the child session records no turn. In both cases the receipt settles `canceled` on the delegation's goroutine. `Cancel` does not wait for that; `Wait` does. A sync delegation's model reads `SUBAGENT_CANCELED`. - **Parked:** the child's pending requests are denied in the child session, its run is not resumed, the receipt settles `canceled` before `Cancel` returns, and the mirrored requests leave the parent's `Pending`. - **Unsettled in the ledger with no child of this pool running:** a previous process's. It is recovered first, then canceled if recovery left it parked. - **Still parking** (its requests mirrored, perhaps its receipt reading `parked`): `Cancel` waits for the park to finish, bounded by `ctx`, then cancels it as a parked child. A running child that reaches its approval boundary before the cancel stops it does not park; it settles `canceled`. **A child that is itself a parent ends its own sync delegations first.** Each parked or running grandchild is canceled and settles `canceled` in the child's ledger, never resumed. The child waits for them at most 30 s. A grandchild still running past that, such as a handler that ignores its context with no `Timeout`, is settled `canceled` by the pool. Its stop names the bound, and its run is abandoned; `Close`'s drain still counts it. Async children the child submitted are not ended with it. A settled receipt fails with a `*pool.StateError` ([`pool.ErrNotRunning`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrNotRunning) under `errors.Is`); an id the ledger does not hold fails with [`pool.ErrUnknownReceipt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrUnknownReceipt) ([`ExamplePool_Cancel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Cancel)). #### Recover after a restart The ledger is entries; the pool's memory is not. A new process brings a parent's delegations back with `p.Recover(ctx, parent)`, once per parent session it takes over, after the agents are wrapped or registered. Here the first process parks a sync delegation and stops; the second opens the same files: ```go title="sessions/pools.go" // The second process: a new Storage, a new pool, the same agents // wrapped under the same names. st, err := jsonl.Open(sessions) if err != nil { return pool.Receipt{}, err } p := pool.New(4) refunder := weft.New(wefttest.Script(wefttest.Say("Refunded order 1234.")), refundTool()) support := weft.New(wefttest.Script(wefttest.Say("Order 1234 is refunded.")), p.MustWrap("refunds", "Run the refund flow.", refunder)) s, err := thread.Open(ctx, st, "s_refunds", support, ctxWindow, ids("", "b"), at(base)) if err != nil { return pool.Receipt{}, err } if err := p.Recover(ctx, s); err != nil { // once per parent session, after the wraps return pool.Receipt{}, err } req := s.Pending()[0] fmt.Fprintln(w, "after Recover:", pool.Receipts(s)[0].State, "| pending", req.CallID) if err := p.Decide(ctx, s, thread.Approve(req.CallID)); err != nil { return pool.Receipt{}, err } final, err := p.Wait(ctx, s, pool.Receipts(s)[0].ID) if err != nil { return pool.Receipt{}, err } fmt.Fprintln(w, "receipt:", final.State, final.Stop) if err := p.Close(ctx); err != nil { return pool.Receipt{}, err } if err := s.Close(ctx); err != nil { // waits for the parent's own resume return pool.Receipt{}, err } msgs := s.Context() fmt.Fprintln(w, "parent:", msgs[len(msgs)-1].Text()) ``` [sessions/pools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/pools.go) ```text first process: pending 1 | receipt parked after Recover: parked | pending c_1/call_r receipt: done Refunded order 1234. parent: Order 1234 is refunded. ``` For each unsettled receipt no child of this pool is working, `Recover` reads the child session and makes the ledger say what is true: | The child | Recover | |---|---| | is parked at an approval | rebuilds the bridge (reopens the child under its agent), mirrors any request the parent lacks, records `parked`; the child resumes when decided. A child whose resume was under way when the process died is here too: its decisions are on file, so it resumes again, and an approved call whose result was not recorded runs again | | finished its run | settles the receipt from the child's own ledger, with its usage: `done` with its final text, or `failed`, `capped`, `canceled` with the recorded cause | | never finished its first run (queued, or mid-run with no approval boundary on file) | settles `failed`, saying so; the run is not started again | | is gone | settles `failed` | A sync delegation's call still parked in the parent is resolved with the settlement, and last the pump runs. A child whose agent the pool does not hold is reported with [`pool.ErrNoAgent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrNoAgent) and left for a later call. Wrapped children need nothing more than the same wraps under the same names. A `Submit` child, or a wrap renamed between runs, needs `p.Register(childID, agent)` first ([`ExamplePool_Register`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Register)). `Recover` on a live session leaves alone the receipts this pool is working ([`ExamplePool_Recover`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Recover)). ##### Make an approved tool idempotent A child's first run is never started again, but its resume is. A resume that started and did not finish leaves the boundary resumable, with its decisions in force. The pump at the end of `Recover` resumes it, and an approved call whose result was not recorded runs again. The same holds at any depth: a grandchild resumes through its parent's recovered delegation (`TestNestedRestartMidApprovedCallRunsItAgain`). Nothing on file tells a call that never started from one cut off half-way. `weft.Replay`'s side-effect classes are the playground's and do not gate a session resume. So a tool that must not run twice has to be idempotent itself. Key it by the call id from [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext), the session id (`weft.session.id`, which thread stamps on every run, read with [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext)) and a business key for what the call acts on. The call id is the same on every run of one call, so the run a resume repeats finds the first run's entry. The session id keeps conversations apart, but it is the same on every turn of one session. Within a session only the business key reliably tells operations apart, because a later turn may reuse a call id (weft's Gemini adapter, for one, numbers calls `call_0`, `call_1`, … per step when the API sends no id): keyed by the order id, a later turn's refund of the same order under a repeated call id reads as already done. Name the operation itself, such as a refund request id, when one order may be refunded twice: ```go title="sessions/idempotent.go" // refunds stands in for the payment side's ledger: one row per // idempotency key. A real one is a table with a unique key, written in // the same transaction as the refund itself. type refunds struct { mu sync.Mutex done map[string]string // key → the result the first run returned runs int // times the handler ran paid int // refunds actually issued } // tool is a refund tool that pays each approved call once. A resume // that runs the call again, after a crash cut the first run off, reads // the recorded result instead of paying twice. func (r *refunds) tool() *weft.ToolDef { return weft.Tool("refund", "Refund an order. Requires a human decision.", func(ctx context.Context, in struct { OrderID string `json:"order_id"` }) (string, error) { call, _ := weft.CallFromContext(ctx) // The call id is the same on every run of this call, so the // run a resume repeats finds this entry. The session id keeps // conversations apart but is the same on every turn, so within // a session only the order id reliably tells operations apart: // a later turn may reuse a call id (weft's Gemini adapter // numbers call_0, call_1, … per step when the API sends none), // and a later refund of the same order under a repeated id // reads as done. Key by a refund request id instead when one // order may be refunded twice. session := weft.MetadataFromContext(ctx)["weft.session.id"] key := session + "/" + call.CallID + "/" + in.OrderID r.mu.Lock() defer r.mu.Unlock() r.runs++ if out, ok := r.done[key]; ok { return out, nil } r.paid++ out := "Refunded order " + in.OrderID + "." r.done[key] = out return out, nil }, weft.RequireApproval(), ) } ``` [sessions/idempotent.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/idempotent.go) `TestIdempotentRefund` resumes one parked call twice under one approval: the handler runs twice and pays once. `TestIdempotentRefundPerSession` sends the same call id and order on plain `Generate` runs under two session ids, stamped with `weft.Metadata` as thread stamps `weft.session.id`, and opens no `thread` session: two refunds. #### Delete a parent and its children Deleting a session deletes none of its children. [`pool.Children`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Children) lists the direct ones, and [`pool.Descendants`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Descendants) the whole subtree, deepest first: ```go title="sessions/pools.go" children, err := pool.Children(ctx, s) if err != nil { return err } all, err := pool.Descendants(ctx, s) // deepest first if err != nil { return err } fmt.Fprintln(w, "children:", children, "descendants:", all) for _, id := range append(all, s.ID()) { // the parent last if err := thread.Delete(ctx, st, id); err != nil { return err } } page, err := thread.List(ctx, st, thread.Query{}) if err != nil { return err } fmt.Fprintln(w, "sessions left:", page.Total) ``` [sessions/pools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/pools.go) ```text children: [c_1] descendants: [c_4 c_1] sessions left: 0 ``` Deleting in the order returned, the parent last, never leaves a child whose parent is already gone. `Children` lists the child of every receipt whose stored header names the parent as its lineage, and leaves out deleted ones. A child still running when its parent is deleted runs to its end and cannot record its settlement (the failure is logged). A `Branch` in the parent moves no child. A `Fork` copies the ledger but not the delegations: the fork's copies of unsettled receipts are settled `canceled`, and `Children` does not list the origin's children for the fork ([`ExampleDescendants`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Descendants)). #### Close the pool `p.Close(ctx)` stops taking work and drains. Every queued or running child is canceled (a sync child's parent model reads `SUBAGENT_CANCELED`), wrapped calls running outside any session are canceled too, and `Close` waits for all of them to settle their receipts and end. A child parked at an approval under a parent at rest is not canceled: its session is closed, its receipt stays `parked`, and a later pool resumes it. A sync grandchild parked under a child that `Close` cancels is canceled at its boundary, and settles `canceled` in that child's ledger. A canceled child that is itself a parent waits for its own sync delegations under `Cancel`'s 30 s bound. `ctx` bounds the wait; a second `Close` returns nil. After `Close`, `Submit`, `Decide`, `Recover` and a wrapped tool's call fail with [`pool.ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrClosed). `Session.Close` does not wait for pool children, so close pools before sessions ([shutdown](https://weftgo.dev/docs/sessions/operations/#close-and-shutdown); [`ExamplePool_Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Close)). ### Receipts A delegation's journey is a run of [`thread.PoolReceiptEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolReceiptEntry) entries in the parent (`pool_receipt`, `"v": 4` on the wire: [the format](https://weftgo.dev/docs/sessions/format/#poolreceiptentry)). [`pool.Receipts(parent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipts) reads them back, in acceptance order, each at the state its entries record last. It reads the same after a restart as live: entries are the truth, and the pool holds no receipt state of its own. The first settlement a receipt records is its state for good. A session that never delegated returns nil. A [`pool.Receipt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipt) is the handle and what is known: | Field | Is | |---|---| | `ID` | the acceptance entry's id: the handle `Wait`, `Cancel` and `Forward` take | | `State` | the state the ledger records last, a [`pool.State`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#State) | | `Child` | the child session's id | | `Call` | the delegating tool call, for a wrapped tool; empty for a `Submit` | | `Stop` | on settlement, the child's answer when `done`; the cause otherwise | [`r.Settled()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipt.Settled) reports whether the receipt reached a final state ([`ExampleReceipts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Receipts)). `*pool.StateError` reports a receipt whose child is not in the state a call serves: `Forward` to a queued, parked or settled child, `Cancel` of a settled one. Its fields are `Receipt` (the id the call named), `State`, and `Orphan` (an unsettled receipt no child of this pool runs for, which `Recover` settles). `Error` names the receipt and its state; `Is` matches `pool.ErrNotRunning`. #### Receipt states `accepted` → `running` ⇄ `parked` → exactly one of `done`, `failed`, `canceled`, `capped`. A delegation canceled or failed before its child ever ran settles straight from `accepted`. The `pool.State` constants are the wire strings of the `thread.PoolAccepted` to `thread.PoolCapped` constants: | `pool.State` | `thread` constant | Wire | Means | |---|---|---|---| | `pool.Accepted` | [`thread.PoolAccepted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolAccepted) | `accepted` | recorded, and queued for a slot | | `pool.Running` | [`thread.PoolRunning`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolRunning) | `running` | the slot is acquired and the child's turn started (or the child waits, slotless, on a sync delegation of its own); written before the turn flies | | `pool.Parked` | [`thread.PoolParked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolParked) | `parked` | the run ended at an approval boundary; no slot; the next `running` is its resume | | `pool.Done` | [`thread.PoolDone`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolDone) | `done` | ran to its intended end; `Stop` is its answer, `Usage` its total cost | | `pool.Failed` | [`thread.PoolFailed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolFailed) | `failed` | the run failed, or the delegation could not proceed; `Stop` is the cause | | `pool.Canceled` | [`thread.PoolCanceled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolCanceled) | `canceled` | `Cancel`, the pool's `Close`, or for a sync child the delegating call's own cancellation or timeout; never the submitting turn's end, which an async child survives | | `pool.Capped` | [`thread.PoolCapped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolCapped) | `capped` | died on a budget: `weft.ErrMaxSteps` or `weft.ErrUsageLimit` (the stop text says which) | [`State.Settled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#State.Settled) is true for the last four; an unknown state, a newer writer's, is not settled. [`State.String`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#State.String) returns the wire string. A receipt that stays `accepted` or `running` across a restart needs `Recover`. ### Usage A pool child is a session, not a tool-call child of the core's `weft.Subagent`, so the core's rule "a child's usage is yours" does not reach it. Its usage is on neither the parent run's `RunResult.Usage` nor `StepRecord.SubagentUsage`. It is on the settling receipt, and [`s.Usage()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Usage) sums the settled receipts into [`thread.Usage.Delegated`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Usage), the ledger's third bucket beside `Turns` and `Summaries` (AGENTS rule 13's one exception; `TestDelegatedUsage`). A settlement's `Usage` is the child session's turns and summaries: every run it made for the delegation, the ones before a park included. That is why the async refund above reports 10 output tokens: the child's model ran once to park and once to finish. It does not include the child's own `Delegated`, and a session's `Delegated` sums only its direct receipts, so a grandchild's tokens are not in the root's `Delegated`. For a nested tree, sum `Usage().Delegated` over the sessions [`pool.Descendants`](https://weftgo.dev/docs/sessions/pools/#delete-a-parent-and-its-children) returns as well. A budget such as [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) on the parent run does not see delegated work; a budget that must cover it reads `Delegated`, across the tree. ### Nested approvals A child parks in its own session; the pool mirrors its requests onto the parent so the parent's `Pending` shows them with their lineage: - **The mirror.** Each mirrored request is an `approval_request` entry in the parent with a namespaced call id (`/`), `child` naming the child session and `wrapper` the parent-side delegating call (empty for an async delegation). `Pending()` lists the mirrors and hides the parked wrapper call. - **The wrapper is never decidable.** A decision naming the delegating call fails with [`thread.ErrDelegated`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrDelegated): approving it would run the delegation a second time, in a second child session. The parent's decision chain keeps the same rule: no grant and no live `Approver` is consulted for a delegating call when it parks (`TestChainNeverDecidesWrapper`). - **The replay.** When a child resumes, the parent's decisions for its pending calls are replayed into the child session, keeping the decider's identity, with `via` `parent`. Only calls pending in the child now are replayed, so an earlier park's decisions never are. - **A re-park supersedes.** A grandchild that parks again while the child waits on it mirrors its new request up the chain. The new request keeps the namespaced call id and names the new occurrence by its run. It supersedes the earlier one, and a decision recorded for the earlier one does not decide it. - **The resolution.** When the child ends, a sync delegation's parked call resolves with the child's outcome (`via` `child`): a resolve with the answer for a `done` child, a `resolve_error` otherwise. That resumes the parent: the parked turn's `Next` is the continuation once `Wait` reports the receipt settled. A child that parks again mirrors its new requests and waits for the next `Decide`. - **Decisions by other paths reach the children.** The pool watches every parent it delegates from. A `Session.Decide` or `DecideSigned` used directly, an interrupting `Send`'s denial (the child resumes with `DENIED: interrupted by a newer message`), or a request lapsing past its expiry runs the pump on a pool goroutine. After a restart nothing is watched until the pool next touches the parent: `Recover`, `Decide`, `DecideSigned` or a new delegation. [`thread.MirroredRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#MirroredRequest) is one mirror as the parent holds it. `Request` is the mirror: its `CallID` in the namespaced form, `Child`, and `RunID` the child run that parked. `Wrapper` is the delegating call, empty for async. Then `Decisions` (the decisions in force for this occurrence, in record order) and `Decided` (whether they reach an effective verdict under the parent's `Quorum`, the moment the pool replays them). `thread.InheritApprovals(parent)` is the session option that gives a child the parent's expiry, quorum, keyring, `RequireSigned` rule and clock; `Submit` and `Wrap` apply it. ### Limits and errors | Name | Kind | Meaning | |---|---|---| | [`pool.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Option) | type | configures a pool at `New` | | `pool.MaxDepth(n)` | option | delegation depth; `New` panics below 1 | | `pool.DefaultMaxDepth` | const, 8 | the depth when `MaxDepth` is not given | | `pool.IDs(f)` | option | mints child session ids and every entry id inside each child; the parent's ids stay its own. Called from many goroutines under session locks: safe for concurrent use, quick, never repeating | | [`pool.WrapOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#WrapOption) | type | configures one wrapped tool: `pool.Async`, `pool.ToolOptions` | | `pool.ErrClosed` | error | work handed to a closed pool | | `pool.ErrCycle` | error | `Submit` to an agent already running above the delegating run; a wrapped tool reports `SUBAGENT_CYCLE` | | `pool.ErrDepth` | error | `Submit` past `MaxDepth`; a wrapped tool reports `SUBAGENT_DEPTH` | | `pool.ErrDuplicateWrap` | error | `Wrap` of a different agent under a name already in use | | `pool.ErrNoAgent` | error | `Decide`, `Recover`, `Cancel` need to reopen a child and the pool holds no agent for it: wrap it again under its name, or `Register` it | | `pool.ErrNotRunning` | error | what every `*StateError` matches | | `pool.ErrUnknownReceipt` | error | `Cancel`, `Forward`, `Wait` with an id the parent's ledger does not hold | | [`pool.CodeSubagentDepth`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#CodeSubagentDepth) | const | `SUBAGENT_DEPTH`, refused before any child is created; the core has no depth limit | | [`pool.CodeSubagentCanceled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#CodeSubagentCanceled) | const | `SUBAGENT_CANCELED`, a sync child the pool canceled; the parent's own cancellation ends the parent's run instead | #### Result codes What a delegating model reads is a contract (AGENTS rule 5), every string pinned by a test. Besides the child's answer and the async receipt line: | Result | When | |---|---| | `SUBAGENT_CYCLE: agent "" is already running in this call chain` | the agent is already running above the call; only for a real cycle | | `SUBAGENT_DEPTH: delegation depth exceeds the pool's limit ` | the delegation would exceed `MaxDepth` (it used to read `SUBAGENT_CYCLE`) | | `SUBAGENT_FAILED: agent "" failed at step : ` | the child's run failed: the core's text, byte for byte | | `SUBAGENT_FAILED: agent "" failed: ` | a failure outside a child run, or one `Recover` read from the ledger | | `SUBAGENT_FAILED: agent "" parked at an approval the pool could not surface: ` | the mirror could not be written on the parent | | `SUBAGENT_CANCELED: agent "" was canceled before it finished` | `Cancel` or `Close` ended a sync child | | `DENIED: the delegation was canceled while awaiting approval` | what a canceled, parked child's model reads if its session is ever resumed | | `thread/pool: pool is closed` | a wrapped tool called after the pool's `Close`: the model reads `pool.ErrClosed`'s text as the result | A delegating call is never re-executed by a decision: its result is the child's answer, once. Arguments that do not decode as `{"prompt": "..."}` read `thread/pool: decode "" arguments: ` followed by `encoding/json`'s description, and leave no receipt. ### Session plumbing The pool lives in another package, so `thread` exports what it needs to write its ledger and bridge approvals. An application delegates with `Wrap` and `Submit`, decides with `Decide`, `DecideSigned` and `p.Decide`, and never calls these. Go has no package-private export; this is the boundary (`thread/poolplumbing.go:11-25`), and it is still exported before the freeze (a known limit). | Method or function | What the pool uses it for | |---|---| | [`Session.AppendPoolReceipt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.AppendPoolReceipt) | one receipt entry per state; returns it stored, its id the receipt handle. Exactly one settlement per receipt is the caller's contract, since `Usage` sums them | | [`Session.AppendApprovalRequests`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.AppendApprovalRequests) | mirrored requests, one atomic batch; every request must name its `Child` | | [`Session.MirroredRequests`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.MirroredRequests) | the mirrors in force, decided or not; expiry resolved first | | [`Session.ReplayDecisions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ReplayDecisions) | in a child, record the parent's decisions (`via` `parent`) and resume; idempotent | | [`Session.ResolveDelegation`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ResolveDelegation) | resolve a delegating call with the child's outcome (`who` `thread/pool`, `via` `child`) | | [`Session.DenyMirrored`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.DenyMirrored) | deny a child's still-pending mirrors when its delegation ends | | [`Session.CancelDelegated`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.CancelDelegated) | in a parked child, deny every pending request and resume nothing | | [`Session.WatchMirrors`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.WatchMirrors) | be told when the parent records a decision for a mirror | | [`Session.MirrorWatchers`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.MirrorWatchers) | the owners holding a `WatchMirrors` notification on the session: the pools delegating from it, or handed it by `Decide`, `DecideSigned` or `Recover`. With several pools on one parent, each pool's pump walks every receipt of the parent's ledger and asks it to tell another pool's child from one it cannot resume | | [`Session.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Storage), [`Session.Lineage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Lineage), [`thread.SessionFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext) | where to create children; a session's parent; the session a run's context carries | | [`thread.WithLineage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithLineage), [`thread.WithMeta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithMeta), `thread.InheritApprovals` | the child's header options and inherited policy | `thread.Request.Child` names the session a mirrored request parks in. ### Complete example `sessions/pools.go` wraps, bounds, delegates in the background, steers, cancels, recovers and cascades: ```go title="sessions/pools.go" package main import ( "context" "errors" "fmt" "io" "path/filepath" "sync" "sync/atomic" "github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/thread/jsonl" "github.com/weftgo/weft/thread/pool" "github.com/weftgo/weft/wefttest" ) // demoPools is the page "Run bounded child sessions with a pool". func demoPools(ctx context.Context, w io.Writer, dir string) error { fmt.Fprintln(w, "== wrap") if _, err := poolWrap(ctx, w); err != nil { return err } fmt.Fprintln(w, "== bound") if _, err := poolBound(ctx, w); err != nil { return err } fmt.Fprintln(w, "== async") if _, err := poolAsync(ctx, w); err != nil { return err } fmt.Fprintln(w, "== forward and cancel") if err := poolForwardCancel(ctx, w); err != nil { return err } fmt.Fprintln(w, "== recover") if _, err := poolRecover(ctx, w, dir); err != nil { return err } fmt.Fprintln(w, "== cascade") return poolCascade(ctx, w) } // childIDs mints the ids of the child sessions a pool creates, and // the entry ids inside them: c_1, c_2, … It is safe for concurrent // use and never repeats, as pool.IDs requires. An application leaves // pool.IDs out and gets time-sortable random ids. func childIDs() pool.Option { var n atomic.Int64 return pool.IDs(func() string { return fmt.Sprintf("c_%d", n.Add(1)) }) } // poolWrap: a sync delegation. The wrapped tool's child runs as a // session of its own; the call waits for its answer. It returns the // parent session's ledger for the test. func poolWrap(ctx context.Context, w io.Writer) (thread.Usage, error) { st := thread.Memory() p := pool.New(4, childIDs()) // at most 4 child runs at work at once researcher := weft.New(wefttest.Script(wefttest.Say("Order 1234 left the Leeds depot on Monday."))) research := p.MustWrap("research", "Research an order in depth.", researcher) support := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", ID: "call_1", Args: `{"prompt":"Trace order 1234."}`}), wefttest.Say("Order 1234 left the depot on Monday."), ), research) s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_support", "a"), at(base)) if err != nil { return thread.Usage{}, err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) if err != nil { return thread.Usage{}, err } res, err := turn.Wait() if err != nil { return thread.Usage{}, err } fmt.Fprintln(w, "reply:", res.Text()) for _, r := range pool.Receipts(s) { fmt.Fprintf(w, "receipt %s: %s child %s call %s stop %q\n", r.ID, r.State, r.Child, r.Call, r.Stop) } u := s.Usage() fmt.Fprintln(w, "output tokens: run", res.Usage.OutputTokens, "| turns", u.Turns.OutputTokens, "| delegated", u.Delegated.OutputTokens) if err := s.Close(ctx); err != nil { return thread.Usage{}, err } return u, p.Close(ctx) } // worker is a child agent whose one tool call blocks until release is // closed, recording how many such calls are in flight at once. type worker struct { started chan struct{} release chan struct{} mu sync.Mutex active int peak int tool *weft.ToolDef } func newWorker() *worker { wk := &worker{started: make(chan struct{}, 16), release: make(chan struct{})} wk.tool = weft.Tool("work", "Do one slow task.", func(ctx context.Context, _ struct{}) (string, error) { wk.mu.Lock() wk.active++ wk.peak = max(wk.peak, wk.active) wk.mu.Unlock() defer func() { wk.mu.Lock(); wk.active--; wk.mu.Unlock() }() wk.started <- struct{}{} select { case <-wk.release: return "finished", nil case <-ctx.Done(): return "", ctx.Err() } }) return wk } // agent returns a fresh child agent: each child gets its own script. func (wk *worker) agent() *weft.Agent { return weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "work", ID: "call_w"}), wefttest.Say("done"), ), wk.tool) } // poolBound: four children on a pool of two. Two work, two wait in // the pool's queue with an accepted receipt. It returns the peak // number of children at work at once. func poolBound(ctx context.Context, w io.Writer) (int, error) { parent, err := thread.Create(ctx, thread.Memory(), weft.New(wefttest.Script()), ctxWindow, ids("s_batch", "a"), at(base)) if err != nil { return 0, err } wk := newWorker() p := pool.New(2, childIDs()) var receipts []*pool.Receipt for i := range 4 { r, err := p.Submit(ctx, parent, wk.agent(), fmt.Sprintf("task %d", i+1)) if err != nil { return 0, err } receipts = append(receipts, r) // returned at once, state accepted } <-wk.started <-wk.started // two children are inside their tool; the other two queue states := map[pool.State]int{} for _, r := range pool.Receipts(parent) { states[r.State]++ } fmt.Fprintln(w, "running:", states[pool.Running], "accepted:", states[pool.Accepted]) close(wk.release) for i, r := range receipts { final, err := p.Wait(ctx, parent, r.ID) if err != nil { return 0, err } fmt.Fprintf(w, "task %d: %s\n", i+1, final.State) } if err := p.Close(ctx); err != nil { return 0, err } fmt.Fprintln(w, "at work at once, at most:", wk.peak) return wk.peak, parent.Close(ctx) } // poolAsync: an async wrapped tool. The model reads a receipt line; // the child parks at an approval, the application decides it through // the pool and waits for the settlement. It returns the final receipt. func poolAsync(ctx context.Context, w io.Writer) (pool.Receipt, error) { st := thread.Memory() refunder := weft.New(wefttest.Script( refundCall("call_r", "1234"), wefttest.Say("Refunded order 1234."), ), refundTool()) p := pool.New(4, childIDs()) refunds := p.MustWrap("refunds", "Start a refund in the background.", refunder, pool.Async()) support := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "refunds", ID: "call_1", Args: `{"prompt":"Refund order 1234."}`}), wefttest.Say("The refund has started."), ), refunds) s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_async", "a"), at(base)) if err != nil { return pool.Receipt{}, err } turn, err := s.Send(ctx, weft.User("Refund order 1234.")) if err != nil { return pool.Receipt{}, err } res, err := turn.Wait() if err != nil { return pool.Receipt{}, err } fmt.Fprintln(w, "the model read:", lastToolResult(res.Messages)) fmt.Fprintln(w, "reply:", res.Text()) r := pool.Receipts(s)[0] rest, err := p.Wait(ctx, s, r.ID) // at rest: settled, or parked at an approval if err != nil { return pool.Receipt{}, err } fmt.Fprintln(w, "receipt:", rest.State) for _, req := range s.Pending() { fmt.Fprintln(w, "pending:", req.CallID, req.Tool, "in", req.Child) } if err := p.Decide(ctx, s, thread.Approve(s.Pending()[0].CallID)); err != nil { return pool.Receipt{}, err // Decide records and arms the child; it does not wait } final, err := p.Wait(ctx, s, r.ID) if err != nil { return pool.Receipt{}, err } fmt.Fprintf(w, "receipt: %s %q | delegated output tokens: %d\n", final.State, final.Stop, s.Usage().Delegated.OutputTokens) if err := s.Close(ctx); err != nil { return pool.Receipt{}, err } return final, p.Close(ctx) } // lastToolResult returns the content of the last tool result in msgs. func lastToolResult(msgs []weft.Message) string { out := "" for _, m := range msgs { for _, part := range m.Content { if r, ok := part.(weft.ToolResultPart); ok { out = r.Content } } } return out } // poolForwardCancel: steer a running child, then cancel another. func poolForwardCancel(ctx context.Context, w io.Writer) error { s, err := thread.Create(ctx, thread.Memory(), weft.New(wefttest.Script()), ctxWindow, ids("s_steer", "a"), at(base)) if err != nil { return err } p := pool.New(2, childIDs()) convert, started, release := slowTool("convert") converter := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "convert", ID: "call_c"}), wefttest.Say("Converted the totals to euros."), ), convert) r, err := p.Submit(ctx, s, converter, "Convert the totals.") if err != nil { return err } <-started // the child is mid-run, inside its tool if _, err := p.Forward(ctx, s, r.ID, weft.User("Use euros, not dollars.")); err != nil { return err } close(release) final, err := p.Wait(ctx, s, r.ID) if err != nil { return err } fmt.Fprintln(w, "forwarded:", final.State, final.Stop) _, err = p.Forward(ctx, s, r.ID, weft.User("Too late.")) var se *pool.StateError fmt.Fprintln(w, "after the end:", errors.Is(err, pool.ErrNotRunning), errors.As(err, &se) && se.State == pool.Done) hold, held, _ := slowTool("hold") holder := weft.New(wefttest.Script(wefttest.ToolCalls(wefttest.Call{Name: "hold", ID: "call_h"})), hold) r, err = p.Submit(ctx, s, holder, "Wait for the warehouse.") if err != nil { return err } <-held if err := p.Cancel(ctx, s, r.ID); err != nil { // cancels the run; Wait follows the settlement return err } final, err = p.Wait(ctx, s, r.ID) if err != nil { return err } fmt.Fprintln(w, "canceled:", final.State, final.Settled()) fmt.Fprintln(w, "cancel again:", errors.Is(p.Cancel(ctx, s, r.ID), pool.ErrNotRunning)) fmt.Fprintln(w, "unknown receipt:", errors.Is(p.Cancel(ctx, s, "e_nope"), pool.ErrUnknownReceipt)) if err := p.Close(ctx); err != nil { return err } return s.Close(ctx) } // poolRecover: a sync delegation parks at an approval, the process // stops, and a second process recovers it from the JSONL files. // It returns the final receipt. func poolRecover(ctx context.Context, w io.Writer, dir string) (pool.Receipt, error) { sessions := filepath.Join(dir, "pool-sessions") // The first process: the child parks, then pool and session close. { st, err := jsonl.Open(sessions) if err != nil { return pool.Receipt{}, err } p := pool.New(4, childIDs()) refunder := weft.New(wefttest.Script(refundCall("call_r", "1234")), refundTool()) support := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "refunds", ID: "call_1", Args: `{"prompt":"Refund order 1234."}`}), ), p.MustWrap("refunds", "Run the refund flow.", refunder)) s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_refunds", "a"), at(base)) if err != nil { return pool.Receipt{}, err } turn, err := s.Send(ctx, weft.User("Refund order 1234.")) if err != nil { return pool.Receipt{}, err } res, err := turn.Wait() if err != nil { return pool.Receipt{}, err } fmt.Fprintln(w, "first process: pending", len(res.Pending), "| receipt", pool.Receipts(s)[0].State) if err := p.Close(ctx); err != nil { // a parked child stays parked return pool.Receipt{}, err } if err := s.Close(ctx); err != nil { return pool.Receipt{}, err } } // The second process: a new Storage, a new pool, the same agents // wrapped under the same names. st, err := jsonl.Open(sessions) if err != nil { return pool.Receipt{}, err } p := pool.New(4) refunder := weft.New(wefttest.Script(wefttest.Say("Refunded order 1234.")), refundTool()) support := weft.New(wefttest.Script(wefttest.Say("Order 1234 is refunded.")), p.MustWrap("refunds", "Run the refund flow.", refunder)) s, err := thread.Open(ctx, st, "s_refunds", support, ctxWindow, ids("", "b"), at(base)) if err != nil { return pool.Receipt{}, err } if err := p.Recover(ctx, s); err != nil { // once per parent session, after the wraps return pool.Receipt{}, err } req := s.Pending()[0] fmt.Fprintln(w, "after Recover:", pool.Receipts(s)[0].State, "| pending", req.CallID) if err := p.Decide(ctx, s, thread.Approve(req.CallID)); err != nil { return pool.Receipt{}, err } final, err := p.Wait(ctx, s, pool.Receipts(s)[0].ID) if err != nil { return pool.Receipt{}, err } fmt.Fprintln(w, "receipt:", final.State, final.Stop) if err := p.Close(ctx); err != nil { return pool.Receipt{}, err } if err := s.Close(ctx); err != nil { // waits for the parent's own resume return pool.Receipt{}, err } msgs := s.Context() fmt.Fprintln(w, "parent:", msgs[len(msgs)-1].Text()) return final, nil } // poolCascade: deleting a parent deletes no child; Descendants lists // the subtree deepest first, the order to delete in. func poolCascade(ctx context.Context, w io.Writer) error { st := thread.Memory() p := pool.New(2, childIDs()) lookup := weft.New(wefttest.Script(wefttest.Say("Order 1234: Leeds depot."))) research := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup", ID: "call_l", Args: `{"prompt":"Find order 1234."}`}), wefttest.Say("It is at the Leeds depot."), ), p.MustWrap("lookup", "Look an order up.", lookup)) support := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", ID: "call_r", Args: `{"prompt":"Where is order 1234?"}`}), wefttest.Say("Order 1234 is at the Leeds depot."), ), p.MustWrap("research", "Research an order.", research)) s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_tree", "a"), at(base)) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } if err := p.Close(ctx); err != nil { return err } if err := s.Close(ctx); err != nil { return err } children, err := pool.Children(ctx, s) if err != nil { return err } all, err := pool.Descendants(ctx, s) // deepest first if err != nil { return err } fmt.Fprintln(w, "children:", children, "descendants:", all) for _, id := range append(all, s.ID()) { // the parent last if err := thread.Delete(ctx, st, id); err != nil { return err } } page, err := thread.List(ctx, st, thread.Query{}) if err != nil { return err } fmt.Fprintln(w, "sessions left:", page.Total) return nil } ``` [sessions/pools.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/pools.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`: ```sh go run ./sessions pools go test ./sessions ``` ```text == wrap reply: Order 1234 left the depot on Monday. receipt e_a3: done child c_1 call call_1 stop "Order 1234 left the Leeds depot on Monday." output tokens: run 10 | turns 10 | delegated 5 == bound running: 2 accepted: 2 task 1: done task 2: done task 3: done task 4: done at work at once, at most: 2 == async the model read: background task accepted; receipt e_a3 reply: The refund has started. receipt: parked pending: c_1/call_r refund in c_1 receipt: done "Refunded order 1234." | delegated output tokens: 10 == forward and cancel forwarded: done Converted the totals to euros. after the end: true true canceled: canceled true cancel again: true unknown receipt: true == recover first process: pending 1 | receipt parked after Recover: parked | pending c_1/call_r receipt: done Refunded order 1234. parent: Order 1234 is refunded. == cascade children: [c_1] descendants: [c_4 c_1] sessions left: 0 ``` Standard error carries 12 lines of `WARN thread: no context window known for this session`, one per child `Session` value that ran a turn: the pool creates each child without a `thread.ContextWindow` ([gotchas](https://weftgo.dev/docs/sessions/pools/#best-practices--gotchas)). ### Best practices & gotchas - **Let one pool own a storage's delegations.** `Recover` treats an unsettled receipt no child of this pool is running as left by a dead process; with two live pools over the same sessions, a `Recover` or `Cancel` through one settles the other's running work `failed`. (Source: `docs/thread-operations.md` §10; `thread/pool/pool.go:176` Pool godoc) - **Keep wrap names stable.** The name is the resume key a restarted process finds the agent by. Renamed a wrap or used `Submit`? `p.Register(childID, agent)` before `Recover`. (Source: `thread/pool/wrap.go:135` Wrap godoc; `thread/pool/bridge.go:941`) - **Wrap and register before `Recover`, and call it once per parent the process takes over.** A child whose agent the pool lacks is left for later with `ErrNoAgent`. (Source: `thread/pool/recover.go:58` Recover godoc) - **`Recover` never re-runs a child's first run.** A child that died mid-run with no approval boundary on file settles `failed`. A finished child's answer is read back as its last assistant text, so a structured `Output` answer is not recovered as such. The cycle guard above a rebuilt child restarts at that child's own agent (the depth limit still holds). (Source: `CHANGELOG.md:4101`; `docs/thread-operations.md` §10) - **Make an approved tool idempotent.** A child whose resume a crash cut off resumes again after `Recover`, and an approved call whose result was not recorded runs again, at any depth. Key the side effect by `weft.CallFromContext`'s call id, the session id (`weft.session.id` in [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext)) and a business key for what the call acts on, such as the order id. The call id is the same on every run of one call, so the run a resume repeats finds the first run's entry. The session id keeps conversations apart, but it is the same on every turn of one session. Within a session only the business key reliably tells operations apart, because a later turn may reuse a call id (weft's Gemini adapter, for one, numbers calls `call_0`, `call_1`, … per step when the API sends no id): keyed by the order id, a later turn's refund of the same order under a repeated call id reads as already done. Name the operation itself, such as a refund request id, when one order may be refunded twice. (Source: `thread/pool/recover.go:13-36` Recover godoc; `thread/pool/twolevel_test.go:632` TestNestedRestartMidApprovedCallRunsItAgain) - **Budgets on the parent run do not cover delegated work.** Read `s.Usage().Delegated`, summed over `pool.Descendants` for a nested tree. (Source: AGENTS rule 13; `thread/pool/pool.go:34-43`, 1089-1090; `thread/session.go:1535-1539`) - **Pool children get no context window.** The pool creates children with lineage, inherited approvals, metadata and ids only, so each child `Session` value logs the no-window `WARN` at its first turn and never compacts on its own. (Source: `thread/pool/pool.go:886-897`; `thread/compaction.go:1306-1319`) - **Close pools before sessions.** `Session.Close` does not wait for pool children; a parked child stays parked across `Close`. (Source: `docs/thread-operations.md` §5; `thread/pool/pool.go:629` Close godoc) - **Cascade deletes yourself.** Delete `Descendants` in the order returned, then the parent. (Source: `thread/pool/pool.go:763`; `ExampleDescendants`) - **Default-deny reaches every child.** A parent turn sent with `thread.RunOptions(weft.ParkAllExcept(...))` binds its children, sync and async, on every turn they run; name a wrap's tool in the list for the delegation itself to run. (Source: `docs/thread-operations.md` §10; `CHANGELOG.md:3247`) - **Run an `Async` wrap inside a session turn.** Called from a plain `Generate`, the tool ignores `pool.Async()`: it waits for the child and returns its answer, so the run is as slow as the child and nothing is receipted. Send the turn through `s.Send` instead. (Source: `thread/pool/wrap.go:156-160`, 178-184) - **Do not decide the delegating call.** Decide the child's mirrored requests; the delegating call completes with the child's answer, and deciding it fails with `thread.ErrDelegated`. (Source: `thread/approval.go:73-83`; `TestWrapperNotDecidable`) ### See also - [Delegate to a subagent](https://weftgo.dev/docs/guides/subagents/): the core's `weft.Subagent`, which the pool builds on - [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/) - [Operate sessions in production](https://weftgo.dev/docs/sessions/operations/#pool-operations) - [The session log format](https://weftgo.dev/docs/sessions/format/#poolreceiptentry) - [Package thread/pool on pkg.go.dev](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool) Symbols used: [`pool.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#New) · [`pool.Pool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool) · [`Pool.Wrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Wrap) · [`Pool.MustWrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.MustWrap) · [`Pool.Submit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Submit) · [`Pool.Wait`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Wait) · [`Pool.Decide`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Decide) · [`Pool.DecideSigned`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.DecideSigned) · [`Pool.Forward`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Forward) · [`Pool.Cancel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Cancel) · [`Pool.Register`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Register) · [`Pool.Recover`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Recover) · [`Pool.Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Close) · [`pool.Receipts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipts) · [`pool.Receipt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipt) · [`pool.State`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#State) · [`pool.StateError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#StateError) · [`pool.Children`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Children) · [`pool.Descendants`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Descendants) · [`pool.Async`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Async) · [`pool.ToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ToolOptions) · [`pool.MaxDepth`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#MaxDepth) · [`pool.IDs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#IDs) · [`thread.PoolReceiptEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolReceiptEntry) · [`thread.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Usage) · [`thread.MirroredRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#MirroredRequest) · [`thread.InheritApprovals`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#InheritApprovals) · [`thread.ErrDelegated`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrDelegated) · [`Session.Pending`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Pending) · [`Session.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Usage) · [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) · [`thread.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Approve) · [`thread.Create`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Create) · [`thread.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Open) · [`thread.Delete`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Delete) · [`thread.List`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#List) · [`jsonl.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) · [`weft.Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested) · [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) · [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`weft.ParkAllExcept`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkAllExcept) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) --- # Operate sessions in production URL: https://weftgo.dev/docs/sessions/operations/ Markdown: https://weftgo.dev/docs/sessions/operations.md > Run weft/thread in production: pick a backend and fsync policy, back it up, read the writer lock and lease, shut down cleanly, recover after a crash with Salvage and LoadReport, act on each error class, retain and delete, upgrade, and know the limits. A `weft/thread` deployment is a storage backend, an fsync policy, one writer per session, and a shutdown that closes what it opened. A reader that meets data it does not understand fails loudly and never guesses: [`thread.ErrCorrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCorrupt) for a damaged line, [`thread.ErrNewerFormat`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNewerFormat) for a newer weft's data. This page is weft's operator's page (`docs/thread-operations.md`) for users: what is on disk, how to back it up, what each error means, and what to do after a crash. `sessions/operations.go` opens a JSONL directory with the backend's logger set: ```go title="sessions/operations.go" logger := textLogger(w) // your application's logger sessions := filepath.Join(dir, "ops") st, err := jsonl.Open(sessions, thread.OpenLogger(logger), // where the backend reports its own repairs ) if err != nil { return err } agent := say(logger, "Order 1234 shipped on Tuesday.", "It arrives on Friday.") s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_ops", "a"), at(base)) ``` [sessions/operations.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/operations.go) [Store sessions](https://weftgo.dev/docs/sessions/storage/) covers the three [storage](https://weftgo.dev/docs/reference/glossary/#storage) backends and their options. `ids`, `at` and `ctxWindow` are the demos' helpers for pinned ids, a pinned clock and a context window. ### Set up a production store Four decisions, each with its default: | Decision | Default | Choose otherwise when | |---|---|---| | Backend | [`jsonl.Open(dir)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open): one file per session; `jq` and `cp` work on it | many sessions in one file, `List` paged in SQL, `TitleSearch` without reading entries: [`sqlite.Open(path)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#Open). `thread.Memory()` loses everything with the process: tests only | | Fsync policy | [`thread.FsyncEveryAppend()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncEveryAppend): every append survives a power cut | appends must be cheaper and a power cut may cost the unsynced tail of a turn: [`thread.FsyncOnFlush()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncOnFlush) | | Locking | the backend's cross-process lock, one writer per session | the platform has no advisory file lock, or the filesystem's locks cannot be trusted: [`thread.NoLock()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NoLock) on jsonl, and one writer becomes your promise | | Logs | the backend reports its own repairs (a torn tail removed, a lock taken over) to `slog.Default()` | pass [`thread.OpenLogger(l)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenLogger) to route them to your logger | Session-level warnings (a repaired load, a failed step write, a compaction that failed) go through the agent's logger, [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger), not the backend's. `weft/thread` is pre-1.0 and not frozen: the API and the stored format may change between minor versions, and the CHANGELOG says how. Nothing here is a compatibility promise beyond the reader's behaviour. #### What is on disk | Aspect | `thread/jsonl` | `thread/sqlite` | |---|---|---| | Layout | one directory; one `.jsonl` file per session | one database file holding every session | | A session | the header line, then one JSON line per entry, append-only | the same line bytes, one per row (`sessions.header`, `entries.line`) | | Permissions | files `0600`; the directory `0700` when `Open` creates it (an existing directory keeps its mode) | the file `0600` and its directory `0700` when `Open` creates them | | Side files | none | `-wal` and `-shm` (WAL mode, set once on the file) | | Lock | an advisory lock on the session file | a row per session in `session_locks` | | Schema | the format itself | embedded migrations, tracked in `thread_migrations`; a database from a newer weft fails `Open` with [`sqlite.ErrNewerSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#ErrNewerSchema) | A session id is 1 to 128 letters, digits, `_` or `-` ([`thread.ValidID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ValidID)), always one path component. Read a jsonl session with `jq -c . /.jsonl`; [The session log format](https://weftgo.dev/docs/sessions/format/) lists every entry kind and field. `thread/sqlite` is the one package that imports the SQLite driver. #### Durability - **jsonl** fsyncs every `Append` before it returns, and the file and directory at `Create`. Under `FsyncOnFlush` a Session flushes after the prompt, every receipt and bookkeeping write, and at the turn's end; the step appends in between are not synced. A crash can lose the unsynced tail of a turn, never a synced one. - **sqlite** commits every `Append` as one transaction in WAL mode, so a process that dies never loses an `Append` that returned. The fsync policy is SQLite's `synchronous` level: `FsyncEveryAppend` is `synchronous=FULL`, the log fsynced at every commit. `FsyncOnFlush` is `synchronous=NORMAL`: a power cut or kernel crash can roll back the commits since the last sync (the database stays consistent), and `Flush` runs `PRAGMA wal_checkpoint(PASSIVE)`, which syncs the log. - **Both:** an `Append` batch is atomic against the writer's death. After a crash a load returns all of it or none of it. ### Backups **jsonl.** `cp`, rsync or a filesystem snapshot of the directory is a backup, at any time, with writers running. A file copied mid-append can end in a half-written line; the copy still loads (the torn line is dropped and reported) and is missing at most that one batch. Restore by putting files back. The advisory lock is not in the file, so a restored copy is unlocked. **sqlite.** The main file alone is not a backup while the database is in use: committed data can still be in `-wal`. Use SQLite's online backup, or stop every writer and copy the main file with `-wal` and `-shm`: ```sh sqlite3 sessions.db ".backup out.db" sqlite3 sessions.db "VACUUM INTO 'out.db'" ``` A sqlite backup carries the `session_locks` rows of the writers that held sessions when it was taken. Restored on the same host they belong to a dead process and are taken over on first write, one `Warn` line each. Restored on a host with a different hostname they are never taken over: [break them](https://weftgo.dev/docs/sessions/operations/#break-a-stale-lock) after such a restore. Neither backend has export, import or encryption at rest; encrypt the volume. ### Locks and leases: one writer per session There are two layers, and they answer different questions ([T1](https://weftgo.dev/docs/sessions/overview/#one-writer)). **The backend's lock: which `Storage` value, in which process, may write.** It is taken on a session's first write and held until the session is released, deleted, or the process dies. A second writer gets [`thread.ErrLocked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrLocked). Readers never lock: `Load`, `List`, `Watch`, `thread.Open` and every read of a `Session` always work. - **jsonl:** `flock` on unix, `LockFileEx` on Windows. The kernel drops it however the holder exits, so a crashed writer never strands a session. It costs one open file descriptor per session a process is writing, until that session is closed: size the fd limit for the sessions you hold open at once. - **sqlite:** the lock row names its holder by `Storage` instance, host, a random per-process token, pid and process start time. A later writer decides from those whether the holder is dead: | The row's holder | Judged | |---|---| | this process, another `Storage` value | alive: `ErrLocked` | | this process's pid under another process token (a restarted container that is PID 1 again) | an earlier incarnation: taken over | | a pid that is not running, or running but started at another time (the pid was reused) | dead: taken over | | a different hostname | never judged dead from here: `ErrLocked` | The start time is read from `/proc` on Linux and from the kernel on macOS and Windows. On other unixes it is unknown, and an unrelated live process wearing a dead holder's pid keeps the session locked until it exits. A takeover is logged as one `Warn` through `OpenLogger`. **The lease: which `Session` value may write.** Two `Session` values on one `Storage` look identical to the backend, so a Session takes the session's lease with its first write (`Create` and `Fork` are first writes) and keeps it until `Close`. Another Session on the same `Storage` opens and reads normally, and every write it makes fails with `ErrLocked`. A Session opened before another writer appended fails its write with [`thread.ErrStale`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrStale) instead. Stale detection is a count plus the header's creation time: it catches a writer that appended behind it and a session deleted and re-created under the same id, and it is not a content comparison. - [`s.Claim(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Claim) asks the lease question ahead of a write: it takes the lease, or fails with `ErrLocked`, `ErrStale` or `ErrClosed` and changes nothing. A Claim with no later write still holds the lease (jsonl's `flock`, sqlite's lock row) until `Close`: claim only with a `Close` to come. - A Session someone forgot to close holds its lease for the life of the process. `st.(thread.Releaser).Release(ctx, id)` ends the hold whoever has it; use it only when that Session is truly abandoned. - **Containers.** A restarted container that keeps its hostname reclaims its sqlite sessions on its own. A replacement with a new hostname, the default for a new pod or `docker run`, does not: give session writers a stable hostname, or close sessions on shutdown so no rows are left. - **Several hosts.** jsonl's lock is only as good as the filesystem's `flock` (network filesystems vary), and a sqlite database on a shared filesystem is outside SQLite's supported envelope. Run one writer host per directory or database; jsonl readers elsewhere are fine. #### Break a stale lock [`sqlite.BreakLock(ctx, st, session)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#BreakLock) removes the writer lock on a session, whoever holds it. It is the operator's way out of the one case the lock cannot decide: a row left by a holder on another host, after a container was replaced under a new hostname or a backup carrying lock rows was restored. Here a second `Storage` value stands in for the new host: ```go title="sessions/operations.go" stB, err := sqlite.Open(path, thread.OpenLogger(logger)) // another Storage: another process, as the lock sees it if err != nil { return err } s, err := thread.Open(ctx, stB, "s_lock", agent, ctxWindow) if err != nil { return err } err = s.SetInfo(ctx, "Order 1234", nil) // the error names the holder's pid and host fmt.Fprintln(w, "before:", errors.Is(err, thread.ErrLocked), classify(err)) // You vouch that the holder is gone: nothing can check it. if err := sqlite.BreakLock(ctx, stB, "s_lock"); err != nil { return err } report(w, "after BreakLock", s.SetInfo(ctx, "Order 1234", nil)) // The old holder's ErrLocked is not a retry: its lock is gone, and the // session may have been written since. It must open the session again. err = held.SetInfo(ctx, "Order 5678", nil) fmt.Fprintf(w, "the old holder: %v\n → reopen (ErrLocked: %v)\n", err, errors.Is(err, thread.ErrLocked)) ``` [sessions/operations.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/operations.go) ```text before: true retry after BreakLock: ok the old holder: thread: session is locked by another writer: s_lock (this writer's lock was broken; the session may have been written since — open it again) → reopen (ErrLocked: true) ``` You vouch that the holder is gone: nothing can check it. A holder that was alive after all is stopped at its next write, which finds the row is no longer its own and fails with `ErrLocked`. Here `ErrLocked` is not a retry: the error says to open the session again, and a Session it serves answers `ErrStale` if the session was written in between. The demo labels it "reopen" for that reason. The removal is logged at `Warn` on the storage's logger, naming the holder. A session with no lock row is left as it is (`BreakLock` returns nil), and one the database does not hold fails with [`thread.ErrNotFound`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotFound). `st` must be a `Storage` this package's `Open` returned. To clear a whole database after a host change, `List` the sessions and break each. ### Close and shutdown [`s.Close(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Close) works in order. `Send` and `Continue` fail with [`thread.ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrClosed) at once. Close waits for the running turn and the queue behind it to drain. The Session is sealed: every later write is `ErrClosed`, and reads keep answering. The lease and the backend's hold are released, and with them jsonl's file descriptor and sqlite's lock row. If `ctx` ends first, Close cancels the running turn (recorded as canceled), ends the queued turns with `ErrClosed`, and returns `ctx.Err()`. The canceled turn may still be writing its end: call `Close` again to finish sealing and releasing. Sends still queued when it gives up keep their `accepted` receipts in the file, steers their `queued` ones, and the next `Open` restores both ([the queue](https://weftgo.dev/docs/sessions/operations/#the-queue)). A parked approval boundary has the same effect without any deadline. Sends queued behind a boundary nobody decides cannot drain, so `Close` returns at once and their Turns end with `ErrClosed`. Their receipts stay, and they run after the next `Open`, once the boundary is decided. In an Open, Send, Close per request handler, do not resend on `ErrClosed`: the message would be answered twice. Reopen and check `s.Queue()` and `s.Pending()` instead. A shutdown that leaves nothing behind: stop accepting requests, close each pool, close each session with a deadline you can afford, exit: ```go title="sessions/operations.go" // shutdown stops a process that writes sessions: pools first, so their // running children settle their receipts; then every open session. func shutdown(ctx context.Context, pools []*pool.Pool, sessions []*thread.Session) error { ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() var errs []error for _, p := range pools { errs = append(errs, p.Close(ctx)) // a parked child stays parked } for _, s := range sessions { errs = append(errs, s.Close(ctx)) // drains the running turn and the queue } return errors.Join(errs...) } ``` [sessions/operations.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/operations.go) `p.Close` cancels running pool children and lets them settle their receipts; parked ones stay parked for the next process. `Session.Close` does not wait for pool children, hence the order. Skipping the sequence is survivable (the crash rules cover it) but costs the in-flight turn, and on sqlite it leaves lock rows for the next process to take over. Never call `Close` from inside the session's own run (a tool, a hook): it would wait for the turn that is calling it. ### After a crash **The torn tail.** A writer killed inside an append can leave a final line without its newline. Nothing needs doing by hand: ```go title="sessions/operations.go" // A writer killed inside an append leaves bytes without a newline. path := filepath.Join(sessions, "s_ops.jsonl") f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0) if err != nil { return err } if _, err := f.WriteString(`{"type":"message","id":"e_a4","par`); err != nil { return err } if err := f.Close(); err != nil { return err } s, err = thread.Open(ctx, st, "s_ops", agent, ctxWindow, ids("", "b"), at(base)) if err != nil { return err } fmt.Fprintln(w, "torn line dropped:", s.LoadReport().Torn) if err := sendWait(ctx, s, "When does it arrive?"); err != nil { // the next write truncates it return err } fmt.Fprintln(w, "answer:", s.Context()[len(s.Context())-1].Text()) ``` [sessions/operations.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/operations.go) ```text level=WARN msg="thread: session loaded with a repair" session=s_ops torn_line=5 skipped_lines=[] orphaned_entries=[] torn line dropped: 5 level=WARN msg="thread/jsonl: removed a torn tail before appending" session=s_ops dropped_bytes=34 answer: It arrives on Friday. ``` The load drops the torn line and says so twice: [`LoadReport.Torn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport) (from [`s.LoadReport()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.LoadReport) on an opened session, or from `Storage.Load`), and one `Warn` through the agent's logger. The next writer removes it before appending (jsonl truncates to the last newline and fsyncs; sqlite deletes the torn row) and logs one `Warn` through `OpenLogger`. A live tail (`Watch`) treats a torn line as a write in flight and waits. A crash costs the half-written batch and nothing after it. **A damaged line elsewhere** fails the load with `ErrCorrupt`, carried by a [`*thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CorruptError) naming the session, the line and, when the tree is the problem, the entry. Open the backend with [`thread.Salvage()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Salvage) to skip such lines and report them: ```go title="sessions/operations.go" damaged := slicesWith(lines, 2, `{"type":"message","id":`) // line 3: a damaged line, not a torn tail if err := os.WriteFile(path, []byte(strings.Join(damaged, "\n")+"\n"), 0o600); err != nil { return err } st, err := jsonl.Open(sessions) if err != nil { return err } _, err = thread.Open(ctx, st, "s_errs", agent, ctxWindow) report(w, "a damaged line", err) salvaged, err := jsonl.Open(sessions, thread.Salvage()) if err != nil { return err } s, err := thread.Open(ctx, salvaged, "s_errs", agent, ctxWindow) if err != nil { return err } lr := s.LoadReport() fmt.Fprintln(w, "salvaged: skipped", lr.Skipped, "orphaned", lr.Orphaned, "torn", lr.Torn) // The same line from a newer weft: "v" above what this build reads. newer := slicesWith(lines, 2, strings.Replace(lines[2], `{"type":"message",`, `{"type":"message","v":2,`, 1)) if err := os.WriteFile(path, []byte(strings.Join(newer, "\n")+"\n"), 0o600); err != nil { return err } _, err = thread.Open(ctx, salvaged, "s_errs", agent, ctxWindow) report(w, "a newer line, under Salvage", err) ``` [sessions/operations.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/operations.go) ```text a damaged line: thread: session s_errs line 3 is corrupt: unexpected end of JSON input → terminal: inspect the line, or open with Salvage salvaged: skipped [3] orphaned [e_a3] torn 0 a newer line, under Salvage: thread: session format newer than this build: entry kind "message" carries v=2, this build reads v=1 → terminal: upgrade this build ``` - [`thread.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport) is what a load dropped or skipped: `Torn`, the 1-based line number of the incomplete final line (0 when the session ended on a complete line), and `Skipped`, the 1-based line numbers skipped under `Salvage`, in file order. A clean load returns a nil report. - [`thread.OpenReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenReport) embeds it and adds `Orphaned`: the ids of entries whose parent was on a skipped line. They are kept, never dropped, and a context for a leaf below one starts at that entry: everything before the skipped line is off the path. - `Salvage` never skips data from a newer weft. It is a recovery tool: open with it, read `s.LoadReport()`, decide whether the session is still usable. **A file with no complete header line**, a crash inside `Create`, is `ErrCorrupt` on line 1 and is not repaired: `thread.Delete` it and create the session again. **The interrupted turn.** Its prompt and every message its steps emitted are in the file. A tool call left without a result is given an error result by the loop's input repair ([`weft.Repair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Repair)), so the next turn's model sees a complete transcript. The turn entry may be missing; the run id is not reused, since it is on the prompt entry. **An approved call cut off by a crash runs again.** A resume writes its `started` audit entry before its run starts, and the approved calls' results join the transcript right after they run, before the next model call. A crash after the `started` entry and before an approved call's result is recorded leaves that call unanswered on the boundary, with its decision still in force. The next resume runs it again: `Resume`, `Continue`, a `Send` under `AutoResume`, or a pool's `Recover` for a child. A crash after the result is recorded leaves no open boundary, and nothing runs again. Nothing on file tells a call that never started from one cut off half-way, and `weft.Replay` classes do not gate a session resume. Make such a tool idempotent, keyed by the call id from [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) together with the session id (`weft.session.id` in [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext)) and a business key such as the order id ([an example](https://weftgo.dev/docs/sessions/pools/#make-an-approved-tool-idempotent)). The call id is the same on every run of one call, so the run a resume repeats finds the first run's entry. The session id keeps conversations apart, but it is the same on every turn of one session. Within a session only the business key reliably tells operations apart, because a later turn may reuse a call id (weft's Gemini adapter, for one, numbers calls `call_0`, `call_1`, … per step when the API sends no id): keyed by the order id, a later turn's refund of the same order under a repeated call id reads as already done. Name the operation itself, such as a refund request id, when one order may be refunded twice. **Accepted input that never ran** is back in `s.Queue()` after `Open`, and `Open` never runs anything on its own ([the queue](https://weftgo.dev/docs/sessions/operations/#the-queue)). Pool delegations a dead process left unsettled need [`Recover`](https://weftgo.dev/docs/sessions/operations/#pool-operations). ### Errors Match with `errors.Is`. Each error has a class that says what the caller does next: ```go title="sessions/operations.go" // classify maps a thread error to what the caller does next. func classify(err error) string { switch { case err == nil: return "ok" case errors.Is(err, thread.ErrBusy), errors.Is(err, thread.ErrLocked): return "retry" case errors.Is(err, thread.ErrStale), errors.Is(err, thread.ErrClosed): return "reopen" case errors.Is(err, thread.ErrNewerFormat): return "terminal: upgrade this build" case errors.Is(err, thread.ErrCorrupt): return "terminal: inspect the line, or open with Salvage" } return "unknown: " + err.Error() } ``` [sessions/operations.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/operations.go) The demo provokes three of them on one directory: ```go title="sessions/operations.go" // Another Session on the same session, while the writer holds it. other, err := thread.Open(ctx, st, "s_errs", agent, ctxWindow) // reads always work if err != nil { return err } report(w, "another Session", other.SetInfo(ctx, "Order 1234", nil)) if err := writer.Close(ctx); err != nil { return err } report(w, "after Close", writer.SetInfo(ctx, "Order 1234", nil)) // other was opened before the writer's last append: its view is behind. ahead, err := thread.Open(ctx, st, "s_errs", agent, ctxWindow) if err != nil { return err } if err := ahead.SetInfo(ctx, "Order 1234", nil); err != nil { return err } if err := ahead.Close(ctx); err != nil { return err } report(w, "a view behind", other.SetInfo(ctx, "Order 1234", nil)) ``` [sessions/operations.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/operations.go) ```text another Session: thread: session is locked by another writer: s_errs → retry after Close: thread: session is closed: session s_errs → reopen a view behind: thread: session changed since it was opened: session s_errs holds 4 entries, this Session has seen 3; open it again → reopen ``` | Error | Class | Means | Do | |---|---|---|---| | [`thread.ErrBusy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrBusy) | retry | a turn is running: a `Reject`-policy `Send`, or `Branch`, `Compact`, `ApplyCompaction`, `Uncompact`, `CustomMessage` | wait (`turn.Wait`, `s.WaitIdle`) and call again, or send under `Queue` | | `thread.ErrLocked` | retry | another writer holds the session: another process, another `Storage`, or another `Session` not yet closed | retry after that writer closes; a dead sqlite holder on another host: [break the lock](https://weftgo.dev/docs/sessions/operations/#break-a-stale-lock) | | `thread.ErrStale` | reopen | the stored session moved on behind this Session, or was deleted and created again | `thread.Open` it again and redo the write | | `thread.ErrClosed` | reopen | this Session's `Close` has run | `thread.Open` it again | | `thread.ErrNotFound` | terminal for the call | no such session, or it was deleted under an open Session | — | | [`thread.ErrExists`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrExists) | terminal for the call | `Create` over an existing id | pick another id | | `thread.ErrCorrupt` | terminal for the data | a line this build cannot decode, or a tree that does not hold together | inspect the line named; reopen the backend with `Salvage` to read around it | | `thread.ErrNewerFormat` | terminal for this build | written by a newer weft: an unknown entry kind, a newer `"v"`, a newer header envelope | upgrade the reader; `Salvage` does not skip it | | [`thread.ErrAwaitingApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrAwaitingApproval) | wait | compaction while approval requests are pending | decide them first | | `sqlite.ErrNewerSchema` | terminal for this build | the database was migrated by a newer weft | upgrade | `ErrNewerFormat` covers the header too: a header whose envelope is ahead of [`thread.FormatVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FormatVersion) fails `Load` with it on both durable backends, not as line-1 corruption. `List` reads headers only, so it still shows a session whose entries are newer; it cannot show one whose header is newer. **`*thread.CorruptError`** is the typed shape `ErrCorrupt` takes when the failure belongs to one place: `Session`, `Line` (1-based, the header is line 1; 0 when no one line), `Entry` (the entry id, when the tree is the problem) and `Err` (the cause). `Error` names the session and the place, then the cause. `Unwrap` returns both the class and the cause, so `errors.Is(err, thread.ErrCorrupt)` is true for every `CorruptError` and `errors.Is`/`errors.As` also reach what `Err` wraps. How a turn ended is on `turn.Outcome()`, and the error `turn.Wait()` returns says why ([Send turns](https://weftgo.dev/docs/sessions/turns/#errors)). `ErrNotPersisted` is a storage incident: the run ended but its end could not be written, and its usage is in no ledger. A turn entry with `late_steps > 0` means step writes failed and landed late: nothing was lost, and the storage was unhealthy for that long. The decision errors (`ErrNotPending`, `ErrExpired`, `ErrDelegated`, `ErrInvalidDecision`, `ErrSignatureRequired`, `ErrBadSignature`, `ErrReplay`, `ErrArgsChanged`) each refuse one decision and record no decision from the caller. A refused signed decision naming a pending call leaves a `signed` audit entry (at most 16 per request), and an expired request is denied by the session itself ([Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/)). ### The queue A `Send` that meets a busy session is, by default, queued, and durable: an `accepted` receipt entry is written and flushed before `Send` returns. A steer writes a `queued` receipt the same way. Receipts are written only for a busy session; an idle `Send` writes its prompt entry instead. After a crash or a `Close` that gave up, `thread.Open` restores both kinds to `s.Queue()`, and nothing runs until the application says so: - the next `Send` runs behind the restored sends, in order, and a restored steer is delivered into the first turn that runs; - `s.Continue(ctx)` runs them now, with no new message; - `s.ClearQueue(ctx)` drops them, on the record. A failed `Send` of a message that will not run leaves the line as it found it, best effort: the receipt is settled `dropped` and a `leaf` entry moves the leaf back, in one flushed append. Restored messages run with no run options: run options are not entries. **The queue is unbounded:** if users can pile messages onto a running turn, check `len(s.Queue())` before sending. [What happens when you send while a turn runs?](https://weftgo.dev/docs/sessions/busy-and-steering/) has the policies. ### Costs and limits The numbers are from weft's budget tests, measured on the maintainer's machine on the dates given; CI enforces generous bounds around them, not the numbers. - **Opening a session reads all of it** into memory, and a `Session` holds its whole tree. A 100,000-entry session opens in about 3 s on both backends (2026-09-30). - **`List` on jsonl reads every header in the directory on every call**: the directory is the index. A page over 10,000 sessions takes about 70 ms (2026-10-01) and allocates a header's worth per file. A header line longer than 1 MiB is not listed. - **`List` on sqlite pages in SQL**: walking 10,000 sessions a hundred at a time takes about 0.17 s in all (2026-10-01). - **`Query.TitleSearch` costs more**: jsonl reads each candidate's whole file; sqlite scans a title column. - **A Session's lock is held across its storage writes.** Under the default fsync policy every method of that Session, reads included, waits out an fsync in progress. - **`Watch` polls** every 200 ms and reads only what is new. - **`Delete` does not look for open Sessions.** Close first; a turn running at that moment loses the entries it had yet to write. ### Pool operations - **One pool per storage's delegations.** With two live pools over the same sessions, a `Recover` or `Cancel` through one settles the other's running work `failed`. - **After a restart**, for each parent the new process takes over: wrap or register the agents, then `p.Recover(ctx, parent)`. It reattaches parked children, settles finished ones from their own files, and settles `failed` those that never finished their first run; that run is not started again. A child whose resume a crash cut off resumes again, so an approved call whose result was not recorded runs again ([below](https://weftgo.dev/docs/sessions/operations/#an-approved-call-cut-off-by-a-crash)). - **Wrap names are resume keys.** Renamed a wrap, or used `Submit`? `p.Register(childID, agent)` before `Recover`. - **A receipt that stays `accepted` or `running` across a restart needs `Recover`.** - **`p.Decide` records and arms; it does not wait.** Follow with `p.Wait`. `p.Decide(ctx, parent)` with no decisions pumps whatever was decided by other paths, and is always safe. - **Deleting a parent deletes no child.** Delete `pool.Descendants(ctx, parent)` in the order returned, the parent last. - **Cost.** A child's usage is on its receipt and in the parent's `Usage().Delegated`, not in the parent run's `RunResult.Usage`. - **Depth.** `pool.MaxDepth(n)` (default 8) bounds a delegation chain; the model reads `SUBAGENT_DEPTH` past it. [Run bounded child sessions with a pool](https://weftgo.dev/docs/sessions/pools/) has the code. ### Approvals operations - **Keys.** A `thread.Keyring` holds HMAC keys by id; the active key mints challenges, every key verifies. Keys are never written to a session, only key ids. Pass the ring with `thread.WithKeyring` at every `Create` and `Open`. - **Rotation.** Build a new ring with the new key active and the old keys still in it. Drop an old key only when nothing minted under it can still be pending; after that a decision signed with it is `ErrBadSignature`. - **`RequireSigned`** is stored in the header at `Create` (`weft.require_signed`) and enforced by every later `Open`; nothing turns it off. `s.Grant` stays an in-process, unsigned call. - **Expiry is lazy.** An expired request is denied the next time the session is touched (`Decide`, `Resume`, `Send`, the runner, the pool's pump), never on a timer. - **Quorum.** A signed approval counts as its key; an unsigned one as whatever `Who` the caller wrote. A quorum that must hold against the deciding process itself needs `RequireSigned` and one key per approver. - **The audit trail is an index, not evidence.** `s.Audit()` entries are unsigned and unchained; put tamper-evidence in the storage (an append-only volume, a signed export). Refused signed decisions are recorded, at most 16 per request. [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/) and [Sign approval decisions](https://weftgo.dev/docs/sessions/signed-approvals/) have the code. ### Retention There is one retention operation: [`thread.Delete(ctx, st, id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Delete). It removes the session and all its entries; nothing else in the module removes data (compaction, branching, `Uncompact` and `ClearQueue` all append). There is no TTL, no archive tier and no per-entry redaction; build them on [`thread.List`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#List) and `Delete`: ```go title="sessions/operations.go" cutoff := base.Add(-48 * time.Hour) // keep two days for { page, err := thread.List(ctx, st, thread.Query{Before: cutoff, Limit: 100}) if err != nil { return err } if len(page.Sessions) == 0 { break } for _, h := range page.Sessions { if err := thread.Delete(ctx, st, h.ID); err != nil { // closed sessions only return err } fmt.Fprintln(w, "deleted:", h.ID, h.Created.Format(time.DateOnly)) } } ``` [sessions/operations.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/operations.go) ```text deleted: s_week 2026-10-15 deleted: s_old 2026-10-12 kept: 1 ``` `Query.Before` alone returns sessions created strictly before the cutoff, which is the retention rule; each pass lists the next page of what is left. Add `pool.Descendants` for a parent's children. A session grows for as long as it is used, and so does the cost of opening it. ### Observability Every run a session starts carries these as run metadata, on every span and every log record of the run: | Key | Value | |---|---| | `weft.session.id` | the session id | | `weft.turn` | the turn counter the run id `-t` was minted from | | `weft.public_id` | the session's public id, when created with `thread.PublicID` | | `weft.session.forked_from` | `#`, on a fork | | `weft.session.parent`, `weft.session.parent_call` | the parent session and delegating call, on a pool child | | `weft.session.title` | the session's current title, once a `SetInfo` has named one | The session's keys win over a caller's colliding `thread.RunOptions(weft.Metadata(...))`. A key the session has no value for is set to `""`, so a session's turn sent from inside another session's tool handler never carries the enclosing run's public id, title, fork origin or lineage as its own ([Identity](https://weftgo.dev/docs/sessions/tree/#identity)). Every compaction that lands emits one record of kind `compaction` (event name `weft.compaction`) through the agent's `LoggerProvider`, under the id of the last run that produced the compacted context ([The compaction marker](https://weftgo.dev/docs/sessions/compaction/#the-compaction-marker)). What the module logs on its own: | Through | Level | For | |---|---|---| | the agent's logger (`weft.Logger`) | `Warn` | a repaired load at `Open`, a step write that failed and was held, a compaction that failed or fell back | | the agent's logger | `Error` | what could not be recorded (a turn end, a rollback, a receipt), a contained panic in a hook | | the agent's logger | `Info` | each compaction that lands | | the backend's logger (`thread.OpenLogger`) | `Warn` | a torn tail removed, a lock taken over or broken | No `Warn` or `Error` line from `thread` means the storage took every write the session made. To follow a session from another process, tail it with the [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) capability that jsonl and sqlite implement: a watcher is a reader that waits, never locks, and polls every 200 ms ([Watch a session](https://weftgo.dev/docs/sessions/storage/#watch-a-session)). ### Upgrade weft The format has one envelope, `"weft": 1` in every header, and entry versions. A kind added after format 1 carries `"v": N`, the minimum reader version. So does an entry of a format-1 kind that carries a field an older reader would misread (a trim compaction, `"v": 5`) ([the version rule](https://weftgo.dev/docs/sessions/format/#the-version-rule)). What follows for an upgrade: - **A new build reads every older file.** The goldens of every format, `thread/testdata/format1` to `format5`, are read by every release. Nothing is rewritten on open, and there is no migration tool: none has been needed while every change was additive. - **An older build fails loudly on newer data.** A process still on the old build that opens a session the new build wrote with a newer kind or `"v"` fails with `ErrNewerFormat` until it is upgraded. Upgrade every process that opens the storage no later than the first one that writes the newer data. - **Some additions change what an older build does, not what it reads.** A build from before the `accepted` receipt status does not restore a queued send; one from before `weft.require_signed` does not enforce it. Do not roll writers back across those versions. - **sqlite migrates its schema at `Open`.** After a newer build opened a database, an older one fails `Open` with `sqlite.ErrNewerSchema`. - **Read the CHANGELOG before upgrading.** Pre-1.0, breaking changes ship without deprecation shims and are recorded there; a breaking `thread` change adds a line to its migration checklist saying what to write instead. ### Known limits From the CHANGELOG's thread 0.9.0 section (2026-10-02); each item still holds at v0.20.2: - **Windows is unexecuted.** jsonl's `LockFileEx` lock and sqlite's Windows liveness and start-time checks compile and pass `GOOS=windows go vet`, run by hand; CI has no Windows job, and no test has run them. - **Stale-writer detection is a count and the header's creation time**, not a content comparison of the entries. - **sqlite's lock does not cross hostnames on its own.** A row left by a holder with another hostname is never taken over; call `sqlite.BreakLock`. - **`Recover` never re-runs a child's first run.** A child whose resume a crash cut off resumes again, and an approved call whose result was not recorded runs again (since 0.18.1 the godoc says so). It reads a finished child's answer as its last assistant text; a structured `Output` answer is not recovered as such. It cannot rebuild the agent ancestry above a rebuilt child, though the depth limit still holds. It assumes one pool owns a storage's delegations: with two live pools over the same sessions, a `Recover` or `Cancel` through one settles the other's running work as failed. Several pools of one process delegating from one parent session are the exception: each skips the receipts whose child another pool watching that parent holds (since 0.18.1). - **`Audit()` is an index, not evidence**: entries are unsigned and unchained; whoever can write the storage can change them. - **`s.Grant` is an unsigned, in-process call**, under `RequireSigned` too. - **The steer queue is unbounded**; check `len(s.Queue())`. - **jsonl `List` reads every header per call**; sqlite pages in SQL. - **The pool's plumbing is still exported** on `Session` (`thread/poolplumbing.go`), and the option names mix three dialects (`With*`, bare, `Require*`/`On*`); both wait for the freeze. ### Complete example `sessions/operations.go` repairs a torn tail, provokes each error class, salvages, breaks a lock, applies retention and shuts down: ```go title="sessions/operations.go" package main import ( "context" "errors" "fmt" "io" "log/slog" "os" "path/filepath" "strings" "time" "github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/thread/jsonl" "github.com/weftgo/weft/thread/pool" "github.com/weftgo/weft/thread/sqlite" "github.com/weftgo/weft/wefttest" ) // demoOperations is the page "Operate sessions in production". func demoOperations(ctx context.Context, w io.Writer, dir string) error { steps := []func(context.Context, io.Writer, string) error{ opsCrash, opsErrors, opsSalvage, opsBreakLock, opsRetention, opsShutdownDemo, } for _, step := range steps { if err := step(ctx, w, dir); err != nil { return err } } return nil } // textLogger writes slog lines to w without their time, so the demo's // output is the same on every run. func textLogger(w io.Writer) *slog.Logger { return slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if len(groups) == 0 && a.Key == slog.TimeKey { return slog.Attr{} } return a }, })) } // say is an agent whose model answers each turn with the next reply. func say(logger *slog.Logger, replies ...string) *weft.Agent { turns := make([]wefttest.Turn, len(replies)) for i, r := range replies { turns[i] = wefttest.Say(r) } return weft.New(wefttest.Script(turns...), weft.Logger(logger)) } // sendWait sends one user message and waits for its turn. func sendWait(ctx context.Context, s *thread.Session, text string) error { turn, err := s.Send(ctx, weft.User(text)) if err != nil { return err } _, err = turn.Wait() return err } // opsCrash: a writer killed mid-append leaves a torn final line; the // next Open drops it and says so, the next write removes it. func opsCrash(ctx context.Context, w io.Writer, dir string) error { fmt.Fprintln(w, "== after a crash") logger := textLogger(w) // your application's logger sessions := filepath.Join(dir, "ops") st, err := jsonl.Open(sessions, thread.OpenLogger(logger), // where the backend reports its own repairs ) if err != nil { return err } agent := say(logger, "Order 1234 shipped on Tuesday.", "It arrives on Friday.") s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_ops", "a"), at(base)) if err != nil { return err } if err := sendWait(ctx, s, "Where is order 1234?"); err != nil { return err } if err := s.Close(ctx); err != nil { return err } // A writer killed inside an append leaves bytes without a newline. path := filepath.Join(sessions, "s_ops.jsonl") f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0) if err != nil { return err } if _, err := f.WriteString(`{"type":"message","id":"e_a4","par`); err != nil { return err } if err := f.Close(); err != nil { return err } s, err = thread.Open(ctx, st, "s_ops", agent, ctxWindow, ids("", "b"), at(base)) if err != nil { return err } fmt.Fprintln(w, "torn line dropped:", s.LoadReport().Torn) if err := sendWait(ctx, s, "When does it arrive?"); err != nil { // the next write truncates it return err } fmt.Fprintln(w, "answer:", s.Context()[len(s.Context())-1].Text()) return s.Close(ctx) } // classify maps a thread error to what the caller does next. func classify(err error) string { switch { case err == nil: return "ok" case errors.Is(err, thread.ErrBusy), errors.Is(err, thread.ErrLocked): return "retry" case errors.Is(err, thread.ErrStale), errors.Is(err, thread.ErrClosed): return "reopen" case errors.Is(err, thread.ErrNewerFormat): return "terminal: upgrade this build" case errors.Is(err, thread.ErrCorrupt): return "terminal: inspect the line, or open with Salvage" } return "unknown: " + err.Error() } // opsErrors provokes each error class on one jsonl directory. func opsErrors(ctx context.Context, w io.Writer, dir string) error { fmt.Fprintln(w, "== errors") logger := textLogger(io.Discard) sessions := filepath.Join(dir, "errs") st, err := jsonl.Open(sessions) if err != nil { return err } agent := say(logger, "Order 1234 shipped on Tuesday.") writer, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_errs", "a"), at(base)) if err != nil { return err } if err := sendWait(ctx, writer, "Where is order 1234?"); err != nil { return err } // Another Session on the same session, while the writer holds it. other, err := thread.Open(ctx, st, "s_errs", agent, ctxWindow) // reads always work if err != nil { return err } report(w, "another Session", other.SetInfo(ctx, "Order 1234", nil)) if err := writer.Close(ctx); err != nil { return err } report(w, "after Close", writer.SetInfo(ctx, "Order 1234", nil)) // other was opened before the writer's last append: its view is behind. ahead, err := thread.Open(ctx, st, "s_errs", agent, ctxWindow) if err != nil { return err } if err := ahead.SetInfo(ctx, "Order 1234", nil); err != nil { return err } if err := ahead.Close(ctx); err != nil { return err } report(w, "a view behind", other.SetInfo(ctx, "Order 1234", nil)) return other.Close(ctx) } // opsSalvage: a damaged line fails Open with ErrCorrupt; Salvage skips // it and reports it. A line from a newer weft is never skipped. func opsSalvage(ctx context.Context, w io.Writer, dir string) error { fmt.Fprintln(w, "== salvage") sessions := filepath.Join(dir, "errs") // s_errs from opsErrors path := filepath.Join(sessions, "s_errs.jsonl") agent := say(textLogger(io.Discard)) data, err := os.ReadFile(path) if err != nil { return err } lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n") damaged := slicesWith(lines, 2, `{"type":"message","id":`) // line 3: a damaged line, not a torn tail if err := os.WriteFile(path, []byte(strings.Join(damaged, "\n")+"\n"), 0o600); err != nil { return err } st, err := jsonl.Open(sessions) if err != nil { return err } _, err = thread.Open(ctx, st, "s_errs", agent, ctxWindow) report(w, "a damaged line", err) salvaged, err := jsonl.Open(sessions, thread.Salvage()) if err != nil { return err } s, err := thread.Open(ctx, salvaged, "s_errs", agent, ctxWindow) if err != nil { return err } lr := s.LoadReport() fmt.Fprintln(w, "salvaged: skipped", lr.Skipped, "orphaned", lr.Orphaned, "torn", lr.Torn) // The same line from a newer weft: "v" above what this build reads. newer := slicesWith(lines, 2, strings.Replace(lines[2], `{"type":"message",`, `{"type":"message","v":2,`, 1)) if err := os.WriteFile(path, []byte(strings.Join(newer, "\n")+"\n"), 0o600); err != nil { return err } _, err = thread.Open(ctx, salvaged, "s_errs", agent, ctxWindow) report(w, "a newer line, under Salvage", err) return nil } // slicesWith returns a copy of lines with line i replaced. func slicesWith(lines []string, i int, line string) []string { out := append([]string(nil), lines...) out[i] = line return out } // report prints what a call returned and what classify makes of it. func report(w io.Writer, what string, err error) { if err == nil { fmt.Fprintf(w, "%s: ok\n", what) return } fmt.Fprintf(w, "%s: %v\n → %s\n", what, err, classify(err)) } // opsBreakLock: a lock row held by a writer that is still alive, // broken by hand. The old writer is stopped at its next write. func opsBreakLock(ctx context.Context, w io.Writer, dir string) error { fmt.Fprintln(w, "== break a lock") logger := textLogger(io.Discard) // BreakLock logs one Warn naming the holder it removed path := filepath.Join(dir, "ops.db") stA, err := sqlite.Open(path, thread.OpenLogger(logger)) if err != nil { return err } agent := say(textLogger(io.Discard), "Order 1234 shipped on Tuesday.") held, err := thread.Create(ctx, stA, agent, ctxWindow, ids("s_lock", "a"), at(base)) if err != nil { return err } if err := sendWait(ctx, held, "Where is order 1234?"); err != nil { return err } stB, err := sqlite.Open(path, thread.OpenLogger(logger)) // another Storage: another process, as the lock sees it if err != nil { return err } s, err := thread.Open(ctx, stB, "s_lock", agent, ctxWindow) if err != nil { return err } err = s.SetInfo(ctx, "Order 1234", nil) // the error names the holder's pid and host fmt.Fprintln(w, "before:", errors.Is(err, thread.ErrLocked), classify(err)) // You vouch that the holder is gone: nothing can check it. if err := sqlite.BreakLock(ctx, stB, "s_lock"); err != nil { return err } report(w, "after BreakLock", s.SetInfo(ctx, "Order 1234", nil)) // The old holder's ErrLocked is not a retry: its lock is gone, and the // session may have been written since. It must open the session again. err = held.SetInfo(ctx, "Order 5678", nil) fmt.Fprintf(w, "the old holder: %v\n → reopen (ErrLocked: %v)\n", err, errors.Is(err, thread.ErrLocked)) if err := s.Close(ctx); err != nil { return err } _ = held.Close(ctx) // its lease was taken from it; Close still seals it return nil } // opsRetention deletes the sessions created before a cutoff. func opsRetention(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== retention") st := thread.Memory() agent := say(textLogger(io.Discard)) for i, name := range []string{"s_old", "s_week", "s_new"} { created := base.Add(-time.Duration(2-i) * 72 * time.Hour) // 6 days, 3 days, 0 days old s, err := thread.Create(ctx, st, agent, ctxWindow, ids(name, "a"), at(created)) if err != nil { return err } if err := s.Close(ctx); err != nil { return err } } cutoff := base.Add(-48 * time.Hour) // keep two days for { page, err := thread.List(ctx, st, thread.Query{Before: cutoff, Limit: 100}) if err != nil { return err } if len(page.Sessions) == 0 { break } for _, h := range page.Sessions { if err := thread.Delete(ctx, st, h.ID); err != nil { // closed sessions only return err } fmt.Fprintln(w, "deleted:", h.ID, h.Created.Format(time.DateOnly)) } } page, err := thread.List(ctx, st, thread.Query{}) if err != nil { return err } fmt.Fprintln(w, "kept:", page.Total) return nil } // shutdown stops a process that writes sessions: pools first, so their // running children settle their receipts; then every open session. func shutdown(ctx context.Context, pools []*pool.Pool, sessions []*thread.Session) error { ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() var errs []error for _, p := range pools { errs = append(errs, p.Close(ctx)) // a parked child stays parked } for _, s := range sessions { errs = append(errs, s.Close(ctx)) // drains the running turn and the queue } return errors.Join(errs...) } // opsShutdownDemo runs shutdown over one pool and one session. func opsShutdownDemo(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== shutdown") s, err := thread.Create(ctx, thread.Memory(), say(textLogger(io.Discard)), ctxWindow, ids("s_shut", "a"), at(base)) if err != nil { return err } p := pool.New(2) if _, err := p.Submit(ctx, s, say(textLogger(io.Discard), "Done."), "Tidy up."); err != nil { return err } err = shutdown(ctx, []*pool.Pool{p}, []*thread.Session{s}) fmt.Fprintln(w, "shutdown:", err) report(w, "a write after shutdown", s.SetInfo(ctx, "late", nil)) return nil } ``` [sessions/operations.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/operations.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`: ```sh go run ./sessions operations go test ./sessions ``` ```text == after a crash level=WARN msg="thread: session loaded with a repair" session=s_ops torn_line=5 skipped_lines=[] orphaned_entries=[] torn line dropped: 5 level=WARN msg="thread/jsonl: removed a torn tail before appending" session=s_ops dropped_bytes=34 answer: It arrives on Friday. == errors another Session: thread: session is locked by another writer: s_errs → retry after Close: thread: session is closed: session s_errs → reopen a view behind: thread: session changed since it was opened: session s_errs holds 4 entries, this Session has seen 3; open it again → reopen == salvage a damaged line: thread: session s_errs line 3 is corrupt: unexpected end of JSON input → terminal: inspect the line, or open with Salvage salvaged: skipped [3] orphaned [e_a3] torn 0 a newer line, under Salvage: thread: session format newer than this build: entry kind "message" carries v=2, this build reads v=1 → terminal: upgrade this build == break a lock before: true retry after BreakLock: ok the old holder: thread: session is locked by another writer: s_lock (this writer's lock was broken; the session may have been written since — open it again) → reopen (ErrLocked: true) == retention deleted: s_week 2026-10-15 deleted: s_old 2026-10-12 kept: 1 == shutdown shutdown: a write after shutdown: thread: session is closed: session s_shut → reopen ``` Standard error is empty: every agent logs through `textLogger`, to the output or to `io.Discard`. The shutdown demo's pool child has no context window (the pool gives children none), and its no-window warning goes to its discarded logger. ### Best practices & gotchas - **Make a tool that must not run twice idempotent.** A crash after a resume's `started` entry and before the approved call's result is recorded runs the call again when its boundary is resumed, by the session or by `Recover`. Key it by `weft.CallFromContext`'s call id, the session id (`weft.session.id` in [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext)) and a business key for what the call acts on, such as the order id. The call id is the same on every run of one call, so the run a resume repeats finds the first run's entry. The session id keeps conversations apart, but it is the same on every turn of one session. Within a session only the business key reliably tells operations apart, because a later turn may reuse a call id (weft's Gemini adapter, for one, numbers calls `call_0`, `call_1`, … per step when the API sends no id): keyed by the order id, a later turn's refund of the same order under a repeated call id reads as already done. Name the operation itself, such as a refund request id, when one order may be refunded twice. (Source: `thread/approval.go:1127-1130`, 1327-1335; `thread/pool/recover.go:13-36`; `docs/thread-operations.md:400-418`) - **Close what you opened to write.** A forgotten Session holds its lease, jsonl's file descriptor and sqlite's lock row for the life of the process. (Source: AGENTS.md T2; `docs/thread-operations.md` §4) - **Close pools before sessions.** `Session.Close` does not wait for pool children. (Source: `docs/thread-operations.md` §5) - **Back up sqlite with `.backup` or `VACUUM INTO`, not `cp`** of the main file alone. (Source: `docs/thread-operations.md` §3) - **Use `Salvage` to recover, not by default.** It hides damage from every load, and never skips a newer weft's data. (Source: `thread/open.go` Salvage godoc; AGENTS.md T5) - **Never write a session behind its Session.** `st.Append` on a session a Session holds breaks the one-writer rule. (Source: AGENTS.md T1) - **Give session writers a stable hostname on sqlite**, or close sessions on shutdown; `BreakLock` only once the old host is known gone. (Source: `docs/thread-operations.md` §4; `thread/sqlite/sqlite.go:1170-1191`) - **Watch for `Warn` and `Error` lines from `thread`.** Their absence means the storage took every write. (Source: `docs/thread-operations.md` §13) - **Grants and the Approver never decide a delegating call at v0.20.2.** weft's operator page still advises scoping them away from wrap names, and points to `Pool.Decide`'s godoc for whether a version has the gap; v0.20.2's godoc and `TestChainNeverDecidesWrapper` say it is closed. (Source: `docs/thread-operations.md` §10; `thread/pool/bridge.go:1045` Decide godoc; `thread/approval.go:861-895`) ### See also - [What is a session?](https://weftgo.dev/docs/sessions/overview/): the thread rules T1 to T5 - [Store sessions: JSONL, SQLite or memory](https://weftgo.dev/docs/sessions/storage/) - [The session log format](https://weftgo.dev/docs/sessions/format/) - [Run bounded child sessions with a pool](https://weftgo.dev/docs/sessions/pools/) Symbols used: [`jsonl.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open) · [`sqlite.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#Open) · [`sqlite.BreakLock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#BreakLock) · [`sqlite.ErrNewerSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#ErrNewerSchema) · [`thread.FsyncEveryAppend`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncEveryAppend) · [`thread.FsyncOnFlush`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncOnFlush) · [`thread.NoLock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NoLock) · [`thread.OpenLogger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenLogger) · [`thread.Salvage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Salvage) · [`thread.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport) · [`thread.OpenReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenReport) · [`Session.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.LoadReport) · [`Session.Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Close) · [`Session.Claim`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Claim) · [`thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CorruptError) · [`thread.ErrBusy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrBusy) · [`thread.ErrLocked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrLocked) · [`thread.ErrStale`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrStale) · [`thread.ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrClosed) · [`thread.ErrCorrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCorrupt) · [`thread.ErrNewerFormat`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNewerFormat) · [`thread.ErrNotFound`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotFound) · [`thread.ErrExists`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrExists) · [`thread.ErrAwaitingApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrAwaitingApproval) · [`thread.FormatVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FormatVersion) · [`thread.ValidID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ValidID) · [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) · [`thread.Releaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Releaser) · [`thread.List`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#List) · [`thread.Query`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Query) · [`thread.Delete`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Delete) · [`thread.Create`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Create) · [`thread.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Open) · [`Pool.Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Close) · [`pool.Descendants`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Descendants) · [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger) · [`weft.Repair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Repair) --- # The session log format URL: https://weftgo.dev/docs/sessions/format/ Markdown: https://weftgo.dev/docs/sessions/format.md > Reference for the weft/thread session log: the header line, all sixteen entry kinds with their JSON keys and Go fields, the "weft" envelope and the "v" version rule, what a reader does with newer data, and how jsonl and sqlite store the same lines. A stored session is lines of JSON: a header line first, then one entry per line in append order. Every line carries a `type`; the header carries the envelope `"weft": 1`, and an entry kind added after format 1 carries `"v"`, its minimum reader version. A reader fails with [`thread.ErrNewerFormat`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNewerFormat) on a kind it does not know or a `"v"` above what it reads, and ignores every other unknown key. Signatures and doc comments are on [pkg.go.dev](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread); this page groups the wire. `sessions/format.go` writes a session with a parked call, a decision, a label, an info edit, a custom entry and a pool delegation, then reads the files back: ```go title="sessions/format.go" sessions := filepath.Join(dir, "format") st, err := jsonl.Open(sessions) if err != nil { return nil, nil, err } agent := weft.New(wefttest.Script( refundCall("call_1", "1234"), // parks: refund requires approval wefttest.Say("Refunded order 1234."), ), refundTool(), quiet) s, err := thread.Create(ctx, st, agent, ctxWindow, thread.PublicID("pub_42"), ids("s_fmt", "a"), at(base)) if err != nil { return nil, nil, err } turn, err := s.Send(ctx, weft.User("Refund order 1234.")) if err != nil { return nil, nil, err } if _, err := turn.Wait(); err != nil { return nil, nil, err } resumed, err := s.Decide(ctx, thread.Approve("call_1")) if err != nil { return nil, nil, err } if _, err := settle(resumed); err != nil { return nil, nil, err } if err := s.Label(ctx, "e_a1", "refund-asked"); err != nil { return nil, nil, err } if err := s.SetInfo(ctx, "Refund for order 1234", nil); err != nil { return nil, nil, err } if err := s.Custom(ctx, "ticket", json.RawMessage(`{"id":88}`)); err != nil { return nil, nil, err } p := pool.New(1, childIDs()) mailer := weft.New(wefttest.Script(wefttest.Say("Receipt sent.")), quiet) r, err := p.Submit(ctx, s, mailer, "Email the receipt.") if err != nil { return nil, nil, err } if _, err := p.Wait(ctx, s, r.ID); err != nil { return nil, nil, err } if err := p.Close(ctx); err != nil { return nil, nil, err } if err := s.Close(ctx); err != nil { return nil, nil, err } parent, err = fileLines(filepath.Join(sessions, "s_fmt.jsonl")) if err != nil { return nil, nil, err } child, err = fileLines(filepath.Join(sessions, r.Child+".jsonl")) ``` [sessions/format.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/format.go) ```text {"type":"session","weft":1,"id":"s_fmt","created":"2026-10-18T09:00:00Z","meta":{"weft.public_id":"pub_42"}} {"type":"message","id":"e_a1","created":"2026-10-18T09:00:00Z","message":{"role":"user","content":[{"type":"text","text":"Refund order 1234."}]},"run_id":"s_fmt-t1"} {"type":"message","id":"e_a2","parent":"e_a1","created":"2026-10-18T09:00:00Z","message":{"role":"assistant","content":[{"type":"tool_call","id":"call_1","name":"refund","args":{"order_id":"1234"}}]}} {"type":"turn","id":"e_a3","parent":"e_a2","created":"2026-10-18T09:00:00Z","run_id":"s_fmt-t1","stop_reason":"tool_calls","usage":{"input_tokens":10,"output_tokens":5},"steps":1,"pending":[{"type":"tool_call","id":"call_1","name":"refund","args":{"order_id":"1234"}}],"policy":"queue","last_input":38} {"type":"approval_request","v":2,"id":"e_a4","parent":"e_a3","created":"2026-10-18T09:00:00Z","call_id":"call_1","tool":"refund","args":{"order_id":"1234"},"args_sha256":"7d0656a84e6bbb1695439d794ea5a55e75f09fcb176bbef1b717cf1142332df6","run_id":"s_fmt-t1","reason":"tool requires approval"} {"type":"approval_audit","v":2,"id":"e_a5","parent":"e_a4","created":"2026-10-18T09:00:00Z","call_id":"call_1","step":"park","outcome":"parked","run_id":"s_fmt-t1"} {"type":"approval_decision","v":2,"id":"e_a6","parent":"e_a5","created":"2026-10-18T09:00:00Z","call_id":"call_1","outcome":"approve","via":"user","run_id":"s_fmt-t1","request_id":"e_a4"} {"type":"approval_audit","v":2,"id":"e_a8","parent":"e_a6","created":"2026-10-18T09:00:00Z","step":"resume","outcome":"started","detail":"1 call(s) to resolve","run_id":"s_fmt-t2","decisions":["e_a6"]} {"type":"message","id":"e_a9","parent":"e_a8","created":"2026-10-18T09:00:00Z","message":{"role":"tool","content":[{"type":"tool_result","call_id":"call_1","name":"refund","content":"refunded 1234","is_error":false}]}} {"type":"message","id":"e_a10","parent":"e_a9","created":"2026-10-18T09:00:00Z","message":{"role":"assistant","content":[{"type":"text","text":"Refunded order 1234."}]}} {"type":"turn","id":"e_a7","parent":"e_a10","created":"2026-10-18T09:00:00Z","run_id":"s_fmt-t2","stop_reason":"stop","usage":{"input_tokens":10,"output_tokens":5},"steps":1,"last_input":30} {"type":"approval_audit","v":2,"id":"e_a11","parent":"e_a7","created":"2026-10-18T09:00:00Z","step":"resume","outcome":"completed","run_id":"s_fmt-t2"} {"type":"label","id":"e_a12","parent":"e_a11","created":"2026-10-18T09:00:00Z","entry":"e_a1","name":"refund-asked"} {"type":"info","id":"e_a13","parent":"e_a12","created":"2026-10-18T09:00:00Z","title":"Refund for order 1234"} {"type":"custom","id":"e_a14","parent":"e_a13","created":"2026-10-18T09:00:00Z","kind":"ticket","data":{"id":88}} {"type":"pool_receipt","v":4,"id":"e_a15","parent":"e_a14","created":"2026-10-18T09:00:00Z","status":"accepted","child":"c_1","prompt":"Email the receipt."} {"type":"pool_receipt","v":4,"id":"e_a16","parent":"e_a15","created":"2026-10-18T09:00:00Z","receipt":"e_a15","status":"running","child":"c_1"} {"type":"pool_receipt","v":4,"id":"e_a17","parent":"e_a16","created":"2026-10-18T09:00:00Z","receipt":"e_a15","status":"done","child":"c_1","stop":"Receipt sent.","usage":{"input_tokens":10,"output_tokens":5}} -- the child's header {"type":"session","weft":1,"id":"c_1","created":"2026-10-18T09:00:00Z","lineage":{"parent_session":"s_fmt"}} ``` The ids and the clock are pinned by the demo's `ids` and `at` helpers; an application gets time-sortable ids and real times. File order is append order, and `parent` is what links the tree. `TestFormatLinesParse` decodes every line back as the kind this page lists for it. ### The file | Aspect | `thread/jsonl` | `thread/sqlite` | |---|---|---| | Where a session lives | `/.jsonl` | rows in one database file | | The header line | line 1 of the file | `sessions.header`, verbatim; `sessions.envelope` holds its `"weft"` integer (0 for a row that is not a session header) | | Entry lines | lines 2 onward, one per line, each ending in a newline | `entries.line`, one row per entry, ordered by `entries.seq` (arrival order) | | A torn final line | bytes after the last newline | a row with `entries.torn = 1`, only in data written through `threadtest.RawInjector`'s `Inject`: sqlite's own appends never tear | | Derived columns | none: the file is the index | `sessions.created`, `sessions.title` (the last non-empty info title), `sessions.gen` (a random generation set at `Create`) | | The writer lock | an advisory lock on the file, not in it | a `session_locks` row: `host`, `owner`, `pid`, `taken`, `process`, `started` | | Schema version | the format itself | `thread_migrations`; migrations `0001_sessions`, `0002_sessions_title`, `0003_leases_keyset` | Both backends store the same line bytes, so they differ in where the lines live, never in what they say. Line numbers in a [`*thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CorruptError) and a [`thread.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport) are 1-based, the header being line 1. sqlite's own time columns (`sessions.created`, `session_locks.taken`) are RFC 3339 with nine-digit nanoseconds, UTC, so their text order is time order. The stored lines keep their own encoding, the same bytes as jsonl. ### Header [`thread.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Header) is a session's first line: its identity, creation time, fork origin, pool lineage and create-time metadata. `"type": "session"` marks it; no other line carries that type. Beyond that the header is immutable: title and metadata edits are `info` entries. | JSON key | Go field | Type | Notes | |---|---|---|---| | `type` | — | `"session"` | written by [`Header.MarshalJSON`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Header.MarshalJSON) | | `weft` | `Weft` | integer | the envelope, `1`; a zero `Weft` writes `FormatVersion`, and `Create` rejects any other value | | `id` | `ID` | string | the session id: 1 to 128 letters, digits, `_` or `-` ([`thread.ValidID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ValidID)) | | `created` | `Created` | RFC 3339 time | | | `parent` | `Parent` | [`ParentRef`](https://weftgo.dev/docs/sessions/format/#parentref) | a fork's origin; optional | | `lineage` | `Lineage` | [`Lineage`](https://weftgo.dev/docs/sessions/format/#lineage) | a pool child's parent; optional (format 4) | | `meta` | `Meta` | object of strings | create-time metadata; optional. Keys under `weft.` are reserved: `weft.public_id`, `weft.require_signed` (`"true"`). A child a pool wrap made carries `pool_agent`, the wrap's name | | `run_meta` | `RunMeta` | object of strings | the run metadata every turn of the session carries ([`thread.WithRunMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithRunMetadata)), stamped on each run under the session's identity keys, which win; optional (0.18.0). Additive: a reader from before ignores it and stamps none | [`Header.UnmarshalJSON`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Header.UnmarshalJSON) enforces the envelope: a `weft` above `FormatVersion` fails with `ErrNewerFormat`; any other value but `1`, or a `type` other than `session`, fails as not a header this format wrote. Unknown keys are ignored. #### FormatVersion [`thread.FormatVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FormatVersion) is `1`: the wire version of every document the thread module writes, the integer every weft wire document carries. It moves only for a layout change a reader cannot handle additively; a new entry kind, a new optional key or a new entry version never moves it. #### ParentRef [`thread.ParentRef`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ParentRef) names a fork's origin. The fork's file holds the copied path as its first entries, so it is self-contained. | JSON key | Go field | Notes | |---|---|---| | `session` | `Session` | the session the fork was made from | | `entry` | `Entry` | the entry its copied path ends at | #### Lineage [`thread.Lineage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Lineage) names a pool child's origin. It is a reference, not a copy: the child's file holds only its own entries. | JSON key | Go field | Notes | |---|---|---| | `parent_session` | `Session` | the parent session | | `parent_call_id` | `Call` | the delegating call, for a wrapped delegation; omitted for a `Submit` | ### Entry [`thread.Entry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Entry) is the sealed set of entry kinds: a session is an append-only tree of them, and the leaf is the entry the next one attaches to. External types cannot join. Every entry of every kind carries these keys: | JSON key | Go field | Notes | |---|---|---| | `type` | — | the kind's discriminator, written by each kind's `MarshalJSON` | | `v` | — | the minimum reader version, on kinds added after format 1 ([the version rule](https://weftgo.dev/docs/sessions/format/#the-version-rule)) | | `id` | `ID` | the entry's id, unique in the session | | `parent` | `ParentID` | the entry it attaches to; omitted on a root (a session may have several roots) | | `created` | `Created` | RFC 3339 time, from the session's clock | Whether a kind enters the model's context is part of its contract: `message` and `custom_message` do; `compaction` and `branch_summary` contribute their summary; the bookkeeping kinds never do. #### UnmarshalEntry [`thread.UnmarshalEntry(b)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#UnmarshalEntry) decodes one entry line, dispatching on its `type`. A line with no `type` fails. A kind this build does not know fails with `ErrNewerFormat`, as does a known kind whose `"v"` is above the version this build reads of it. Every other unknown key is ignored. Each kind's `MarshalJSON` writes it back with its `type` and, where it has one, its `"v"`; the goldens round-trip to the same bytes. #### ErrNoEntry [`thread.ErrNoEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNoEntry) is returned when an operation names an entry the session does not hold, `Pin`'s target or a compaction's `FirstKept`, or asks for one the leaf's path does not have (`Uncompact` with no compaction to undo). ### Entry kinds | `type` | Go type | Since | `"v"` | In the model's context | |---|---|---|---|---| | `message` | [`MessageEntry`](https://weftgo.dev/docs/sessions/format/#messageentry) | 1 | — | yes | | `turn` | [`TurnEntry`](https://weftgo.dev/docs/sessions/format/#turnentry) | 1 | — | no | | `compaction` | [`CompactionEntry`](https://weftgo.dev/docs/sessions/format/#compactionentry) | 1 | — (5 with `trim`) | the summary | | `branch_summary` | [`BranchSummaryEntry`](https://weftgo.dev/docs/sessions/format/#branchsummaryentry) | 1 | — | the summary | | `leaf` | [`LeafEntry`](https://weftgo.dev/docs/sessions/format/#leafentry) | 1 | — | no | | `label` | [`LabelEntry`](https://weftgo.dev/docs/sessions/format/#labelentry) | 1 | — | no | | `info` | [`InfoEntry`](https://weftgo.dev/docs/sessions/format/#infoentry) | 1 | — | no | | `custom` | [`CustomEntry`](https://weftgo.dev/docs/sessions/format/#customentry) | 1 | — | no | | `custom_message` | [`CustomMessageEntry`](https://weftgo.dev/docs/sessions/format/#custommessageentry) | 1 | — | yes | | `approval_request` | [`ApprovalRequestEntry`](https://weftgo.dev/docs/sessions/format/#approvalrequestentry) | 2 | 2 | no | | `approval_decision` | [`ApprovalDecisionEntry`](https://weftgo.dev/docs/sessions/format/#approvaldecisionentry) | 2 | 2 | no | | `approval_audit` | [`ApprovalAuditEntry`](https://weftgo.dev/docs/sessions/format/#approvalauditentry) | 2 | 2 | no | | `grant` | [`GrantEntry`](https://weftgo.dev/docs/sessions/format/#grantentry) | 2 | 2 | no | | `grant_revoked` | [`GrantRevokedEntry`](https://weftgo.dev/docs/sessions/format/#grantrevokedentry) | 2 | 2 | no | | `receipt` | [`ReceiptEntry`](https://weftgo.dev/docs/sessions/format/#receiptentry) | 3 | 3 | no | | `pool_receipt` | [`PoolReceiptEntry`](https://weftgo.dev/docs/sessions/format/#poolreceiptentry) | 4 | 4 | no | "Since" is the format step that introduced the kind: 1 is thread v0.1, 2 approvals (v0.2), 3 steering receipts (v0.3), 4 the pool (v0.5), 5 the trim record (thread 0.9.0). In the field tables below, every entry's common keys are left out, and an optional key is one the writer omits when empty. #### MessageEntry [`thread.MessageEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#MessageEntry) is one message of the transcript, embedded with the core's message wire verbatim. It is how conversation content is stored, and it is always in the model's context. | JSON key | Go field | Type | Notes | |---|---|---|---| | `message` | `Message` | [`weft.Message`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Message) | `{role, content: [parts]}`; roles `user`, `assistant`, `tool` | | `run_id` | `RunID` | string, optional | on a turn's prompt entry only: the run id minted for the turn, `-t`, written before the run does anything, so a reopened session never mints it again | #### TurnEntry [`thread.TurnEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TurnEntry) is the per-turn ledger: it records the turn's outcome, never its content. One run, one turn entry; a turn that overflowed and re-ran leaves two, the failed attempt's (with `rerun`) and the re-run's. `Session.Usage` sums both. | JSON key | Go field | Type | Notes | |---|---|---|---| | `run_id` | `RunID` | string | `-t` | | `stop_reason` | `StopReason` | [`weft.StopReason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopReason), optional | `stop`, `tool_calls`, `max_tokens` | | `usage` | `Usage` | [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage) | `input_tokens`, `output_tokens`, optional `cached_input_tokens`, `cache_write_tokens`, `reasoning_tokens` | | `steps` | `Steps` | integer, optional | model steps the run took | | `err` | `Err` | string, optional | the error text on failure | | `pending` | `Pending` | tool-call parts, optional | the calls left on the approval boundary | | `canceled` | `Canceled` | bool, optional | the turn's context ended: canceled (the caller walked away, an `Interrupt` or `Rollback` send, `Close`) or past its deadline; `err` says which | | `policy` | `Policy` | string, optional | the busy policy the `Send` was called under: `queue`, `reject`, `steer`, `interrupt`, `rollback`; a steer's follow-up records `steer`; empty on a resume turn | | `rerun` | `ReRun` | string, optional | on an overflow attempt that was re-run, the re-run's run id, written before it starts | | `last_input` | `LastInput` | integer, optional | the compaction trigger's baseline: the final step's reported input plus the estimated tokens of that step's own messages; absent on a turn that ran no step | | `late_steps` | `LateSteps` | integer, optional | per-step appends that failed and were written late; nothing was lost, and the storage was unhealthy for that long | #### CompactionEntry [`thread.CompactionEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactionEntry) records one compaction ([compaction](https://weftgo.dev/docs/sessions/compaction/#what-a-compaction-records)). Nothing is deleted: the summarized entries stay in the file. A summary compaction is a format-1 line with no `"v"`; one carrying a trim record is written with `"v": 5`, so an older reader fails instead of replaying the trim from its own options. | JSON key | Go field | Type | Notes | |---|---|---|---| | `summary` | `Summary` | string, optional | the summary text; empty on a trim | | `first_kept` | `FirstKept` | string | the first entry kept raw after it | | `tokens_before` | `TokensBefore` | integer | estimated size of the context the model was shown when it ran (the compacted view, not the raw path) | | `reason` | `Reason` | [`thread.Reason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Reason), optional | `manual`, `threshold`, `overflow`, `from_hook`, `trim` | | `summarizer_usage` | `SummarizerUsage` | `weft.Usage`, optional | what the summary cost; absent on a trim | | `summarizer_model` | `SummarizerModel` | [`weft.ModelInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelInfo), optional | `{provider, name}` of the model that made it | | `files_read` | `FilesRead` | strings, optional | | | `files_modified` | `FilesModified` | strings, optional | a format-1 field kept readable: no build writes it, and a file that carries it round-trips unchanged | | `pinned` | `Pinned` | strings, optional | entries kept through the compaction | | `range_hash` | `RangeHash` | string, optional | a hash of the summarized range | | `trim` | `Trim` | [`TrimRecord`](https://weftgo.dev/docs/sessions/format/#trimrecord), optional | present exactly on a trim | A trim is the same entry with an empty `summary`, `reason` `trim` and a `trim` record. It never moves the boundary: the latest summary compaction below it keeps governing the context, the stubs layer over the kept range, and its `first_kept` only repeats the boundary in force. #### TrimRecord [`thread.TrimRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TrimRecord) is what a trim did, persisted so the context replays it from the file alone: the walk applies exactly these stubs and never consults the session's configured trimmer. | JSON key | Go field | Notes | |---|---|---| | `stubs` | `Stubs` | the [`TrimStub`](https://weftgo.dev/docs/sessions/format/#trimstub) list | #### TrimStub [`thread.TrimStub`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TrimStub) is one stubbed tool result. The stored result is untouched. | JSON key | Go field | Notes | |---|---|---| | `entry` | `Entry` | the entry that holds the result | | `call_id` | `CallID` | the call it answers | | `content` | `Content` | what the model sees in its place | | `is_error` | `IsError` | what the stubbed part reports; optional, false for the built-in trimmer's stub | #### BranchSummaryEntry [`thread.BranchSummaryEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BranchSummaryEntry) summarizes the branch a `Branch` leaves behind, so the context shows the summary in place of that branch's messages. | JSON key | Go field | Notes | |---|---|---| | `summary` | `Summary` | the text | | `from_entry` | `FromEntry` | the entry the abandoned branch grew from | #### LeafEntry [`thread.LeafEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LeafEntry) moves the session's leaf to an existing entry: branch navigation without a rewrite. The next entry attaches to `entry`. Its `parent` is where the leaf entry itself was appended. | JSON key | Go field | Notes | |---|---|---| | `entry` | `Entry` | the entry the leaf moves to; empty is the root | | `abandoned` | `Abandoned` | `true` on the one leaf entry that is no navigation: a failed or refused send's unwind, moving the leaf back to where that send found it. A reader naming the branch a turn descends from (`weft.session.branch`) skips it. Optional (0.18.0); a session written before reads its unwinds as navigations | It is written by `Branch`, by `Uncompact`, by a `Rollback` send, and by an overflow re-run, whose failed attempt keeps its messages on their own branch. It is also written by the unwind of a `Send` that failed or was refused (a failed prompt or receipt flush, a refused interrupting send, a steer whose follow-up could not be queued). A failed turn whose final form differs from its raw tail writes no leaf entry: the corrected tail attaches after the last entry that still matches. ADR 0011 §7 says a leaf entry is written there; the code does not. #### LabelEntry [`thread.LabelEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LabelEntry) names an entry: bookmarks, checkpoints, a UI's anchors. | JSON key | Go field | Notes | |---|---|---| | `entry` | `Entry` | the entry named | | `name` | `Name` | the label | #### InfoEntry [`thread.InfoEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#InfoEntry) edits the title and metadata as an append. The current title is the last info entry's non-empty `title`; the current metadata is every info entry's `meta` merged in order over the header's. | JSON key | Go field | Notes | |---|---|---| | `title` | `Title` | optional | | `meta` | `Meta` | object of strings, optional; never a `weft.` key | #### CustomEntry [`thread.CustomEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CustomEntry) carries application state. It survives every compaction and never enters the model's context. | JSON key | Go field | Notes | |---|---|---| | `kind` | `Kind` | caller-chosen, not empty | | `data` | `Data` | any JSON, verbatim; optional (nil writes no key) | #### CustomMessageEntry [`thread.CustomMessageEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CustomMessageEntry) carries an application message that is always in the model's context, a note the model must see without attributing it to the user. | JSON key | Go field | Notes | |---|---|---| | `kind` | `Kind` | caller-chosen, not empty | | `message` | `Message` | a `weft.Message` | #### ApprovalRequestEntry [`thread.ApprovalRequestEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ApprovalRequestEntry) is a parked call made durable, written in the same append as the turn entry that parked it. Its id names this one occurrence of the call: call ids repeat across turns, entry ids never do. | JSON key | Go field | Notes | |---|---|---| | `call_id` | `CallID` | the pending call; `/` on a pool mirror | | `tool` | `Tool` | the tool name | | `args` | `Args` | the arguments as the model wrote them; optional | | `args_sha256` | `ArgsSHA256` | hex SHA-256 of the arguments | | `run_id` | `RunID` | the run that parked the call | | `reason` | `Reason` | why it parked: `tool requires approval`, `middleware required approval`; optional | | `expiry` | `Expiry` | when the request lapses; optional | | `child` | `Child` | the pool child session this request mirrors; optional | | `wrapper` | `Wrapper` | the parent-side delegating call it parks under; optional | #### ApprovalDecisionEntry [`thread.ApprovalDecisionEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ApprovalDecisionEntry) is one decision over a parked call. The model sees it only through the result the resumed run produces. | JSON key | Go field | Notes | |---|---|---| | `call_id` | `CallID` | the call decided | | `outcome` | `Outcome` | [`thread.Outcome`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Outcome): `approve`, `deny`, `resolve`, `resolve_error` | | `reason` | `Reason` | a deny's reason; optional | | `content` | `Content` | a resolve's result; optional | | `who` | `Who` | the decider; optional | | `via` | `Via` | the channel: `user`, `signed`, `approver`, `grant`, `expiry`, `interrupt`, `child`, `parent`; optional | | `run_id` | `RunID` | the run the decided request belonged to; optional | | `nonce` | `Nonce` | a signed decision's nonce, the replay guard; optional | | `key_id` | `KeyID` | the key that vouched for a signed decision, and its identity under `Quorum`; optional | | `request_id` | `RequestID` | the request entry the decision answers; empty on a grant's or the Approver's decision; optional | | `always` | `Always` | an `ApproveAlways`: the grant is minted when the verdict becomes approve; optional | #### ApprovalAuditEntry [`thread.ApprovalAuditEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ApprovalAuditEntry) is the decision chain's own trail, automatic approvals included, so `s.Audit()` can tell the whole story from the file alone. `detail` is prose for a human and never parsed. | JSON key | Go field | Notes | |---|---|---| | `call_id` | `CallID` | optional | | `step` | `Step` | `grant`, `approver`, `park`, `expiry`, `resume`, `signed` | | `outcome` | `Outcome` | how the step ended, such as `parked`, or a resume's `started`, `completed`, `failed`; optional | | `detail` | `Detail` | optional | | `run_id` | `RunID` | optional | | `grant_id` | `GrantID` | the grant a `grant` step matched; one entry is one use of a `MaxUses` grant; optional | | `grant_shared` | `GrantShared` | the grant is a `GrantStore`'s, and `grant_id` is the store's id; optional | | `key_id` | `KeyID` | the key a refused signed decision claimed; optional | | `decisions` | `Decisions` | the decision entries a resume applied (`resume`, `started`); optional | #### GrantEntry [`thread.GrantEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#GrantEntry) is a session-scoped grant made durable: a standing approval, or with `deny` a standing refusal, for future calls of one tool. It embeds [`thread.Grant`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Grant), whose keys sit at the top level of the line. Liveness is derived, never stored. | JSON key | Go field | Notes | |---|---|---| | `tool` | `Grant.Tool` | the tool name, matched exactly | | `args` | `Grant.Args` | `[{pointer, equals \| prefix \| glob}]`, every predicate must match; optional | | `deny` | `Grant.Deny` | a standing refusal; optional | | `reason` | `Grant.Reason` | a deny's model-visible text (`denied by grant` when empty), or an approval's note; optional | | `expiry` | `Grant.Expiry` | optional | | `max_uses` | `Grant.MaxUses` | counted from `approval_audit.grant_id`; optional | #### GrantRevokedEntry [`thread.GrantRevokedEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#GrantRevokedEntry) ends a grant. Revocation is an append: the grant entry stays, and the audit trail keeps both. | JSON key | Go field | Notes | |---|---|---| | `grant_id` | `GrantID` | the grant entry's id | #### ReceiptEntry [`thread.ReceiptEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptEntry) is the receipt of a message accepted while the session was busy. An idle `Send` writes no receipt: its message is the prompt entry. A steer is two entries, `queued` and then its fate linked by `receipt`; a queued send is one `accepted` entry, settled by its prompt entry landing or a `dropped` entry ([Receipts](https://weftgo.dev/docs/sessions/busy-and-steering/#receipts)). | JSON key | Go field | Notes | |---|---|---| | `receipt` | `Receipt` | the acceptance entry a later one settles; optional | | `status` | `Status` | `queued`, `accepted`, `delivered`, `deferred`, `dropped` | | `msg` | `Msg` | the message, on an acceptance; optional | | `run_id` | `RunID` | the run that delivered a steer, or the run minted for a queued send; optional | | `turn` | `Turn` | the prompt entry id a queued send or deferred steer will take; optional | | `unanswered` | `Unanswered` | on a delivered receipt: the run took the steer and failed before answering it; optional | An `accepted` receipt with neither a prompt entry nor a `dropped` entry is a send the writer never got to: `Open` restores it to the queue. #### PoolReceiptEntry [`thread.PoolReceiptEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolReceiptEntry) is one step of a pool delegation's journey ([Receipts](https://weftgo.dev/docs/sessions/pools/#receipts)). One entry records acceptance; every later one links back to it by `receipt`. | JSON key | Go field | Notes | |---|---|---| | `receipt` | `Receipt` | the acceptance entry; empty on the acceptance itself | | `status` | `Status` | `accepted`, `running`, `parked`, `done`, `failed`, `canceled`, `capped` | | `child` | `Child` | the child session; optional on the wire, always set by the pool | | `call` | `Call` | the delegating tool call, for a wrapped delegation; optional | | `prompt` | `Prompt` | the task, on the acceptance; optional | | `stop` | `Stop` | on a settlement: the answer (`done`) or the cause; optional | | `usage` | `Usage` | on a settlement: the child session's whole cost; summed into `Usage.Delegated`; optional | ### The version rule - **The envelope.** The header carries `"weft": 1`. It moves only for a layout change a reader cannot handle additively. - **Entry versions.** A kind born in format 1 carries no `"v"`. A kind added later is written with `"v": N`, its minimum reader version. A format-1 kind that gains a field an older reader would misread writes `"v": N` on the entries carrying that field (the compaction's trim record, 5). - **What this build reads:** the format-1 kinds at 1, `compaction` up to 5, the approval kinds at 2, `receipt` at 3, `pool_receipt` at 4. - **Additive keys need no version.** A new optional key an older reader loses nothing by ignoring is added without one. ### What a reader does with newer data An older reader never guesses (thread rule T5). This is what v0.20.2 does with lines a newer weft could write: ```go title="sessions/format.go" for _, line := range []string{ `{"type":"message","v":2,"id":"e_1","created":"2026-10-18T09:00:00Z","message":{"role":"user","content":[]}}`, `{"type":"snapshot","v":6,"id":"e_2","created":"2026-10-18T09:00:00Z"}`, } { _, err := thread.UnmarshalEntry([]byte(line)) fmt.Fprintln(w, errors.Is(err, thread.ErrNewerFormat), err) } var h thread.Header err := json.Unmarshal([]byte(`{"type":"session","weft":2,"id":"s_x","created":"2026-10-18T09:00:00Z"}`), &h) fmt.Fprintln(w, errors.Is(err, thread.ErrNewerFormat), err) ``` [sessions/format.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/format.go) ```text true thread: session format newer than this build: entry kind "message" carries v=2, this build reads v=1 true thread: session format newer than this build: entry kind "snapshot" is unknown to this build true thread: session format newer than this build: session header has weft=2, this build reads 1 ``` | It meets | It does | |---|---| | an unknown entry kind | fails with `ErrNewerFormat`, `Salvage` or not | | a known kind with `"v"` above what it reads | fails with `ErrNewerFormat`, `Salvage` or not | | a header envelope above `FormatVersion` | fails `Load` with `ErrNewerFormat`; `List` does not show the session | | an unknown key on a line it reads | ignores it | | a malformed line | [`thread.ErrCorrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCorrupt) naming the line; skipped and reported under `Salvage` | | a torn final line | drops it and reports it in `LoadReport.Torn` | Two additions change what an older build does, not what it reads: a build from before the `accepted` receipt status reads the entry and does not restore the queued send, and one from before `weft.require_signed` ignores the key and does not enforce it. [Upgrade weft](https://weftgo.dev/docs/sessions/operations/#upgrade-weft) has the operational side. ### Format history The changes since format 1, from the CHANGELOG. The header envelope has been `"weft": 1` throughout. | Release | Wire change | |---|---| | thread 0.1.0 | the format-1 kinds `message`, `turn`, `compaction`, `branch_summary`, `leaf`, `label`, `info`, `custom`, `custom_message`; the `{"weft":1}` envelope and the `"v"` rule | | thread 0.2.0 | `approval_request`, `approval_decision`, `approval_audit`, `grant`, `grant_revoked`, at `"v": 2`; a v0.1 reader fails loudly on a session that used approvals | | thread 0.3.0 | `receipt`, `"v": 3` | | thread 0.5.0 | `pool_receipt`, `"v": 4`; the header's `lineage` | | thread 0.5.0 | `approval_request`: `child`, `wrapper`; mirrored call ids `/` (additive, no `"v"` change) | | thread 0.9.0 | `compaction` with a trim record at `"v": 5` (an older build fails on it on purpose; a summary compaction is unchanged) | | thread 0.9.0 | `message`: `run_id` on a turn's prompt entry | | thread 0.9.0 | `turn`: `policy`, `rerun`, `late_steps`; `canceled` also set on a deadline | | thread 0.9.0 | `receipt`: the status `accepted` with `msg`, `turn`, `run_id`; `unanswered` on a delivered receipt | | thread 0.9.0 | `pool_receipt`: the status `parked` | | thread 0.9.0 | `approval_decision`: `request_id`, `always`; `via` values `interrupt`, `child`, `parent` | | thread 0.9.0 | `approval_audit`: `grant_id`, `grant_shared`, `key_id`, `decisions`; the step `signed`; the `resume` outcomes `started`, `completed`, `failed` | | thread 0.9.0 | header metadata `weft.require_signed` (`"true"`) | | thread 0.9.0 | the signing challenge's domain string `weft/approval-challenge/v2`, covering the request entry id and the run id; not stored; in-flight v1 signatures do not verify | | thread 0.9.0 | `thread/sqlite` migration `0003_leases_keyset`: `session_locks` gains `process` and `started`; `sessions` gains `gen` and `envelope`; the index `sessions_order(envelope, created DESC, id DESC)` replaces `sessions_created`; the title re-derived under the last-non-empty rule | | thread 0.9.0 | grant uses counted from `approval_audit.grant_id`; uses recorded only as prose (`detail`) are not counted, so a `MaxUses` grant in such a file starts again | | thread 0.9.0 | `TurnEntry.Policy`, `ReRun`, `LateSteps`, `MessageEntry.RunID`, `ReceiptEntry.Unanswered` and `thread.ReceiptAccepted` added to the Go API | | weft 0.18.0 | the header's `run_meta` (`Header.RunMeta`, `WithRunMetadata`); `leaf`: `abandoned` (additive, no `"v"` change) | Goldens for every kind and most variants live in `thread/testdata/format1` to `format5`, with a whole session in `format1/session.jsonl`. `TestReadEveryGolden` reads and re-marshals the goldens of all five formats to the same bytes; `TestTrimRecordGolden` also writes and pins `format5/compaction_trim.json`. No golden yet carries a mirrored request's `child` and `wrapper` or a fork header's `parent`. The format is not frozen: the freeze that would make it a compatibility promise is deferred (ADR 0011, amendment §D). ### Complete example `sessions/format.go` writes the session above and decodes newer data: ```go title="sessions/format.go" package main import ( "context" "encoding/json" "errors" "fmt" "io" "os" "path/filepath" "strings" "github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/thread/jsonl" "github.com/weftgo/weft/thread/pool" "github.com/weftgo/weft/wefttest" ) // demoFormat is the page "The session log format": it writes a real // session with a parked call, a decision, a label, an info edit, a // custom entry and a pool delegation, and prints its file. func demoFormat(ctx context.Context, w io.Writer, dir string) error { parent, child, err := formatCapture(ctx, dir) if err != nil { return err } for _, line := range parent { fmt.Fprintln(w, line) } fmt.Fprintln(w, "-- the child's header") fmt.Fprintln(w, child[0]) fmt.Fprintln(w, "-- a newer weft's data") return formatNewer(w) } // formatCapture writes the session and returns the lines of the // parent's file and of its pool child's file. func formatCapture(ctx context.Context, dir string) (parent, child []string, err error) { quiet := weft.Logger(textLogger(io.Discard)) sessions := filepath.Join(dir, "format") st, err := jsonl.Open(sessions) if err != nil { return nil, nil, err } agent := weft.New(wefttest.Script( refundCall("call_1", "1234"), // parks: refund requires approval wefttest.Say("Refunded order 1234."), ), refundTool(), quiet) s, err := thread.Create(ctx, st, agent, ctxWindow, thread.PublicID("pub_42"), ids("s_fmt", "a"), at(base)) if err != nil { return nil, nil, err } turn, err := s.Send(ctx, weft.User("Refund order 1234.")) if err != nil { return nil, nil, err } if _, err := turn.Wait(); err != nil { return nil, nil, err } resumed, err := s.Decide(ctx, thread.Approve("call_1")) if err != nil { return nil, nil, err } if _, err := settle(resumed); err != nil { return nil, nil, err } if err := s.Label(ctx, "e_a1", "refund-asked"); err != nil { return nil, nil, err } if err := s.SetInfo(ctx, "Refund for order 1234", nil); err != nil { return nil, nil, err } if err := s.Custom(ctx, "ticket", json.RawMessage(`{"id":88}`)); err != nil { return nil, nil, err } p := pool.New(1, childIDs()) mailer := weft.New(wefttest.Script(wefttest.Say("Receipt sent.")), quiet) r, err := p.Submit(ctx, s, mailer, "Email the receipt.") if err != nil { return nil, nil, err } if _, err := p.Wait(ctx, s, r.ID); err != nil { return nil, nil, err } if err := p.Close(ctx); err != nil { return nil, nil, err } if err := s.Close(ctx); err != nil { return nil, nil, err } parent, err = fileLines(filepath.Join(sessions, "s_fmt.jsonl")) if err != nil { return nil, nil, err } child, err = fileLines(filepath.Join(sessions, r.Child+".jsonl")) return parent, child, err } // fileLines returns a session file's lines, header first. func fileLines(path string) ([]string, error) { data, err := os.ReadFile(path) if err != nil { return nil, err } return strings.Split(strings.TrimSuffix(string(data), "\n"), "\n"), nil } // formatNewer decodes lines a newer weft could write: each fails with // ErrNewerFormat, never a skip. func formatNewer(w io.Writer) error { for _, line := range []string{ `{"type":"message","v":2,"id":"e_1","created":"2026-10-18T09:00:00Z","message":{"role":"user","content":[]}}`, `{"type":"snapshot","v":6,"id":"e_2","created":"2026-10-18T09:00:00Z"}`, } { _, err := thread.UnmarshalEntry([]byte(line)) fmt.Fprintln(w, errors.Is(err, thread.ErrNewerFormat), err) } var h thread.Header err := json.Unmarshal([]byte(`{"type":"session","weft":2,"id":"s_x","created":"2026-10-18T09:00:00Z"}`), &h) fmt.Fprintln(w, errors.Is(err, thread.ErrNewerFormat), err) return nil } ``` [sessions/format.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/format.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`: ```sh go run ./sessions format go test ./sessions ``` The output is the session's lines above, then: ```text -- a newer weft's data true thread: session format newer than this build: entry kind "message" carries v=2, this build reads v=1 true thread: session format newer than this build: entry kind "snapshot" is unknown to this build true thread: session format newer than this build: session header has weft=2, this build reads 1 ``` ### Best practices & gotchas - **Never write a line by hand into a session a Session holds.** Write through the Session; a line behind its back breaks the one-writer rule and the stale check. (Source: AGENTS.md T1) - **A tool reading session files decodes with `thread.UnmarshalEntry`, or applies its rule:** fail on an unknown `type` or a newer `"v"`, ignore unknown keys. (Source: `thread/entry.go:979-998`) - **The format is documented, not frozen.** Pre-1.0 a minor release may change it, with a CHANGELOG entry. (Source: `thread/header.go:9-24`; ADR 0011 amendment §D) - **ADR 0011 is stale on two points.** It calls `thread` a module of its own (it is a package of `github.com/weftgo/weft`), and its §7 says a failed turn's rewrite writes a leaf entry (the code writes none). (Source: `thread/turn.go:1592-1619`; ADR 0027) ### See also - [What is a session?](https://weftgo.dev/docs/sessions/overview/) - [Operate sessions in production](https://weftgo.dev/docs/sessions/operations/): Salvage, backups, upgrades - [Store sessions: JSONL, SQLite or memory](https://weftgo.dev/docs/sessions/storage/) - [Package thread on pkg.go.dev](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread) Symbols used: [`thread.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Header) · [`thread.ParentRef`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ParentRef) · [`thread.Lineage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Lineage) · [`thread.FormatVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FormatVersion) · [`thread.Entry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Entry) · [`thread.UnmarshalEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#UnmarshalEntry) · [`thread.ErrNoEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNoEntry) · [`thread.ErrNewerFormat`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNewerFormat) · [`thread.ErrCorrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCorrupt) · [`thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CorruptError) · [`thread.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport) · [`thread.ValidID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ValidID) · [`thread.MessageEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#MessageEntry) · [`thread.TurnEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TurnEntry) · [`thread.CompactionEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactionEntry) · [`thread.Reason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Reason) · [`thread.TrimRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TrimRecord) · [`thread.TrimStub`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TrimStub) · [`thread.BranchSummaryEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BranchSummaryEntry) · [`thread.LeafEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LeafEntry) · [`thread.LabelEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LabelEntry) · [`thread.InfoEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#InfoEntry) · [`thread.CustomEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CustomEntry) · [`thread.CustomMessageEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CustomMessageEntry) · [`thread.ApprovalRequestEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ApprovalRequestEntry) · [`thread.ApprovalDecisionEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ApprovalDecisionEntry) · [`thread.Outcome`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Outcome) · [`thread.ApprovalAuditEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ApprovalAuditEntry) · [`thread.GrantEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#GrantEntry) · [`thread.Grant`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Grant) · [`thread.GrantRevokedEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#GrantRevokedEntry) · [`thread.ReceiptEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReceiptEntry) · [`thread.PoolReceiptEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolReceiptEntry) · [`weft.Message`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Message) · [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage) · [`weft.ModelInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelInfo) · [`weft.StopReason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopReason) --- # Observe and debug agents URL: https://weftgo.dev/docs/observe/ Markdown: https://weftgo.dev/docs/observe.md > How weft's recording, Studio, the devtools panel, the playground and the weft command fit together: one OpenTelemetry pipeline records every run, and every surface reads that recording back. weft records a run as OpenTelemetry data: spans for its structure, log records for its events, transcript and requests. [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) sends them to one or more [destinations](https://weftgo.dev/docs/reference/glossary/#destination), by default the [local sink](https://weftgo.dev/docs/reference/glossary/#local-sink) `./.weft/weft.db`. Studio, the devtools panel, the playground and the `weft` command all read that recording back; the playground also sends commands to your running app, which dials Studio through `weft/runtime`. > **Diagram:** Your app runs agents with agt.Generate; every run leaves as OpenTelemetry spans and log records. otel.Install starts the pipeline and sends them to every destination at once; with no options and no destination named by the environment it writes the local sink only. otel.Local writes .weft/weft.db synchronously; otel.Studio exports OTLP over HTTP to a running weft studio. The Inspector reads them back: embedded with studio.Handler over otel.LocalDB(), or served by weft studio. The core reports every run through the OTel API, which does nothing until a provider is registered. `weft/otel` registers one, configured for weft: one line installs it, each destination has its own content policy, and the local sink needs no network. Any OTLP backend takes the same data, and a non-Go agent that exports the standard GenAI spans appears in Studio too. ### Record runs Start here. Every other page reads what these pages set up. - [Record every run with otel.Install](https://weftgo.dev/docs/observe/recording/): one line, the local sink, heartbeats, reading a run back through `obsdb`. - [Send records to Studio, Datadog, Langfuse or any OTLP backend](https://weftgo.dev/docs/observe/destinations/): several destinations at once, each with its own content policy, queue and signals. - [Bridge your app's slog lines into runs](https://weftgo.dev/docs/observe/app-logs/): your log lines stored under the span they were logged in. - [Use your own OpenTelemetry SDK](https://weftgo.dev/docs/observe/opentelemetry/): weft's spans and records through your own `TracerProvider` and `LoggerProvider`. - [Inspect agents written in other languages](https://weftgo.dev/docs/observe/other-languages/): what Studio derives from a Python or TypeScript agent's GenAI spans. ### Studio The Inspector: a web UI and JSON API over the recording, embedded in your app or run as `weft studio`. - [Run Studio: embedded, local binary or hosted](https://weftgo.dev/docs/observe/studio/setup/) - [Find runs: the runs list, search and filters](https://weftgo.dev/docs/observe/studio/runs/) - [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/) - [Browse sessions and traces in Studio](https://weftgo.dev/docs/observe/studio/sessions-and-traces/) - [Watch runs live](https://weftgo.dev/docs/observe/studio/live/) - [Compare runs step by step](https://weftgo.dev/docs/observe/studio/compare/) - [See what a run cost](https://weftgo.dev/docs/observe/studio/cost/) - [Export a run](https://weftgo.dev/docs/observe/studio/export/) - [Get around Studio: keyboard, panes and settings](https://weftgo.dev/docs/observe/studio/navigation/) ### Playground Your app dials Studio and runs its experiment commands as runs of the agents you register. - [How does the playground work?](https://weftgo.dev/docs/observe/playground/overview/) - [Connect your app to Studio's playground (weft/runtime)](https://weftgo.dev/docs/observe/playground/connect/) - [Replay a run from any step, with edits](https://weftgo.dev/docs/observe/playground/replay/) - [Run experiments with the option lab](https://weftgo.dev/docs/observe/playground/experiments/) - [Pause runs at breakpoints, then steer or cancel them](https://weftgo.dev/docs/observe/playground/breakpoints/) ### Devtools panel Studio's run view inside your own web page, scoped to the conversation on screen. - [What is the devtools panel?](https://weftgo.dev/docs/observe/devtools/overview/) - [Install the devtools panel](https://weftgo.dev/docs/observe/devtools/install/) - [Scope the panel to a conversation](https://weftgo.dev/docs/observe/devtools/scope/) - [Lay out and theme the panel](https://weftgo.dev/docs/observe/devtools/layout-and-theme/) - [Drive the panel from your page (host API and events)](https://weftgo.dev/docs/observe/devtools/host-api/) - [Read a run in the panel](https://weftgo.dev/docs/observe/devtools/reading-runs/) - [Replay, edit and experiment from the panel](https://weftgo.dev/docs/observe/devtools/replay/) - [Approve and steer your app's own turns](https://weftgo.dev/docs/observe/devtools/app-turns/) - [Secure the devtools panel](https://weftgo.dev/docs/observe/devtools/security/) ### The weft command - [Use the weft command](https://weftgo.dev/docs/observe/cli/): list runs, open one, export it, check a Studio. - [Develop with weft dev](https://weftgo.dev/docs/observe/weft-dev/): Studio and your app in one command, restarted on save. - [Let Claude Code or Cursor read your runs (weft mcp)](https://weftgo.dev/docs/observe/weft-mcp/) ### See also - [Record every run with otel.Install](https://weftgo.dev/docs/observe/recording/): the page to read first - [Environment variables](https://weftgo.dev/docs/reference/env/): what adds a destination without code - [The record contract](https://github.com/weftgo/weft/blob/v0.20.2/docs/record-contract.md): what the pipeline emits and what Studio reads, field by field --- # What is the devtools panel? URL: https://weftgo.dev/docs/observe/devtools/overview/ Markdown: https://weftgo.dev/docs/observe/devtools/overview.md > The devtools panel is Studio's view of one conversation, drawn in a corner of your own app's page: its turns, steps, tool calls and timing, read live from Studio's API. The devtools panel is Studio's view of one conversation, drawn in a corner of your own app's page. One script tag loads it from Studio's `/panel.js`. It shows the turns of the conversation the page is having, each step's story with its tool calls, usage and timing, and a live tail of the running turn. It reads Studio's API, so it needs a Studio to talk to and records nothing itself. ```html ``` That tag is the whole install for a Go app that embeds Studio at `/studio/` ([setup A](https://weftgo.dev/docs/reference/glossary/#setup-a-b-c)). [Install the devtools panel](https://weftgo.dev/docs/observe/devtools/install/) covers the other setups and the npm package. ![The weft devtools panel docked on the right of an app page, its Story tab showing a step's tool calls and their errors](https://weftgo.dev/docs/_astro/panel-docked-right.light.BuHdPlbl.webp) *The panel docked on the right of an app's page, on its story tab.* ### What the panel is The panel is one custom element, ``, which draws itself inside its own shadow DOM. Your page's CSS does not reach it, and its CSS does not reach your page. The element is defined by one ES module, `panel.js`, which Studio's handler serves at `/panel.js` with no token. The file is embedded in the `studio` package, so a Studio of version X serves the panel of version X. The same bytes ship in the npm package `@weftgo/devtools`, for apps that bundle their JavaScript instead of loading script tags. When the module loads, it does four things in order: 1. It defines ``, so markup already in the page upgrades. 2. It watches `window.__WEFT__`, the global a single-page app sets to switch conversations. 3. It reads its configuration: `` tags and its own script tag. 4. It mounts the dock, unless the page has its own `` or the tag says `data-auto="false"`. The panel then asks Studio's `/api/meta`. If no Studio answers, the dock it mounted by itself removes itself, unless you named a loopback endpoint ([When the panel does not connect](https://weftgo.dev/docs/observe/devtools/install/#when-the-panel-does-not-connect)). Your page loses nothing when Studio is down. A Studio that refuses the token (a 401 or 403) is there, so since 0.20.0 the panel stays and says which token it wants. #### What it shows Inside the panel, the open turn has four tabs: | Tab | What it shows | |---|---| | story | The steps of the turn: what the model was sent and replied, each tool call and its result, the step's attempts and timing ("attempt 4 of 4 · fallback to glm-b", "1.2 s · first token 180 ms"), approvals, and each child run inline at any depth | | request | One step's request: the prompt, the messages, the tool catalog and the parameters | | waterfall | The run's spans on a time axis (Timeline before 0.20.0), or its steps in event order when it has no spans | | raw | The run's JSON, as a tree you can filter and copy | A badge marks anything the recording does not hold: a truncated result, a gap, content stripped by a content-off destination. ⤢ links open the same run, at the same step, in Studio. [Read a run in the panel](https://weftgo.dev/docs/observe/devtools/reading-runs/) explains each tab. #### What it follows The panel follows a [scope](https://weftgo.dev/docs/reference/glossary/#scope): a conversation's [public id](https://weftgo.dev/docs/reference/glossary/#public-id), and optionally the session, flow and run inside it, written `pub_…;session=…;flow=…;run=…`. The public id is the one your app gave its `thread` session with `thread.PublicID`. Its runs carry it as `weft.public_id`, and the panel lists them as the conversation's turns. Since 0.20.0 a scope may also name a page of unrelated runs, with or without a public id. `tag.=` matches a run's metadata pair; repeat it to require several. `agent=` narrows to one agent. `;tag.arena.batch=b1` is a whole scope. The page names the scope, or the panel detects it: from `data-scope` on the tag, from the `Weft-Scope` header your chat handler sets, from a `data-weft-scope` attribute on the chat's element, or from the page URL. Since 0.20.0, when nothing names a scope, a panel token's claims become it: its public id and its tags. With none of these, the header reads `no conversation detected on this page · how to scope` and lists the newest runs. [Scope the panel to a conversation](https://weftgo.dev/docs/observe/devtools/scope/) is the whole ladder. While a run of the conversation runs, the collapsed dock (the pill) pulses and shows the live step count, `● 3`. ### Panel or Studio The panel and Studio read the same database through the same JSON API and the same live stream. They differ in how much they show and where: | Aspect | The panel | Studio | |---|---|---| | Where | A corner or a side of your app's page | Its own pages, at `` | | What | One conversation: the scope the page names | Every run, session and trace in the database | | Finds runs by | The scope (public id, session, run) | Lists, search, filters, ⌘K | | Extra | Replay verbs, and deciding your app's parked turns | The run page, compare, cost, settings, the playground, export | | Loaded by | ``: same origin, no token | | B · a separate `weft studio` or `weft dev` | `` | | A bundled app with no ` ``` Open the page. The dock mounts in its corner, reads `no conversation detected on this page`, and follows the first conversation your page names. [Scope the panel to a conversation](https://weftgo.dev/docs/observe/devtools/scope/) shows how a page names one. ![The weft devtools panel docked on the right of an app page, its Story tab showing a step's tool calls and their errors](https://weftgo.dev/docs/_astro/panel-docked-right.light.BuHdPlbl.webp) ### The script tag [`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler) serves the panel at `/panel.js`: static, unauthenticated, embedded in the `studio` package, so the panel is always the version of the Studio that serves it. `weft studio` (setup B) serves it at its root, `/panel.js`. The file is one ES module: load it with `type="module"`. It is built apart from Studio's UI, as a separate Vite library-mode bundle with no React in it; a Studio build without the bundle answers `/panel.js` with a 500. `data-weft` marks the tag as the panel's. The panel finds its own tag by that attribute, whatever the file is called, so a bundle served from a proxy or renamed `/assets/devtools.abc123.js` still reads its configuration. Without `data-weft`, a module tag counts only when its `src` resolves to the panel's own URL. A tag is never taken for the panel's because it carries a `data-endpoint` or `data-token`: a third-party widget's attributes are not the panel's configuration. Setup A, the page on Studio's origin, needs nothing more. In setups B and C the page is on another origin, so the tag also names the Studio and a token: ```html ``` A dev page against `weft studio` must be on `localhost` or `127.0.0.1`: [When the panel does not connect](https://weftgo.dev/docs/observe/devtools/install/#when-the-panel-does-not-connect) says why. On your own machine the token is `weft studio`'s dev token. In a page you ship it is a per-page panel token your backend mints through `POST /api/panel-tokens`, never the dev or server token: [Secure the devtools panel](https://weftgo.dev/docs/observe/devtools/security/). What the tag does when it loads: - **A `` in your markup** upgrades in place and is configured by its own attributes. The panel mounts no second dock. - **No markup:** the panel appends a dock to ``, unless `data-auto="false"`. That dock is the panel's own. If no Studio answers its `/api/meta` request, it removes itself, unless you named a loopback endpoint ([When the panel does not connect](https://weftgo.dev/docs/observe/devtools/install/#when-the-panel-does-not-connect)). A Studio that answers 401 or 403 never removes it. - **A mount you made** (your ``, or `mount()` from npm) stays when no Studio answers, and shows one line, `Studio not reachable at · retry`. While a retry asks again, `retry` reads `checking…`. - **Attribute changes apply live.** The element watches every field in the table below except `data-mode` and `data-open`, which are read once as the initial mode and state. A framework that rewrites them, or remounts the element, reconfigures the panel without removing it. - **`?weft=debug`** in the page URL, or `debug: true` under `localStorage["weft.devtools"]`, mounts the dock even with `data-auto="false"`: a switch for a staging page. The older `localStorage.weft_debug=1` is migrated into that key. #### When the panel does not connect The panel asks `/api/meta` once at start. Since 0.20.0 it tells two cases apart: - **Studio refused the token** (a 401 or 403). Studio is there and wants a token, so the panel is never removed, however it was installed. Its line reads `Studio needs a token at — add data-token (the dev token) or a panel token (POST /api/panel-tokens) · retry`. - **No Studio answered**: no answer, any other non-2xx answer, a request the browser blocks, or a 200 that is not Studio's meta (an app's catch-all route). The self-mounted dock removes itself, silently. Two exceptions show `Studio not reachable at · retry` instead: a loopback endpoint you named (your own Studio, not started yet) and a mount you made. A bare tag, with no endpoint and no `data-weft`, whose guessed endpoint is on loopback also logs one console line, once per page: `weft devtools: Studio did not answer at ; add data-weft or data-endpoint on the panel's ``` Take the asset of the release your Studio runs: a panel older than Studio says `Studio is newer than this panel; update panel.js`. The npm package's `panel.js.sha256` carries the same hash as the asset's `.sha256`. In weft's repository `make studio-panel-asset` stages the two files. ### Where configuration comes from Each field resolves on its own: the first source that sets it wins, so a meta tag can carry the token while the script tag carries the endpoint. The sources, highest first: | # | Source | Example | |---|---|---| | 1 | `mount(opts)` from `@weftgo/devtools` (not in the script-tag bundle) | `mount({ endpoint: "/studio/" })` | | 2 | the `` element's attributes | `` | | 3 | meta tags | `` | | 4 | the panel's ` ``` A `weft:token` meta tag is a token in your page's source, exactly like `data-token`. ### npm `@weftgo/devtools` is the same `panel.js`, byte for byte, packaged with a small typed module and three framework helpers, for apps that bundle everything and ship no ` ` // newAgent is the chat's agent. The model is scripted so the program // runs offline: it answers the same line for the first thousand turns. func newAgent(opts ...weft.Option) *weft.Agent { turns := make([]wefttest.Turn, 1000) for i := range turns { turns[i] = wefttest.Say("Order 1234 has shipped.") } return weft.New(wefttest.Script(turns...), append([]weft.Option{weft.Name("support-bot")}, opts...)...) } // publicIDOf is the conversation a request belongs to: the public id // the app hands out. This page sends it as ?c=. func publicIDOf(r *http.Request) string { if c := r.URL.Query().Get("c"); c != "" { return c } return "pub_demo" } // question is the request body: the user's words. func question(r *http.Request) string { raw, _ := io.ReadAll(io.LimitReader(r.Body, 64<<10)) if q := strings.TrimSpace(string(raw)); q != "" { return q } return "hello" } // chats holds one thread session per public id: the conversation the // panel follows is the session created with thread.PublicID. type chats struct { agt *weft.Agent st thread.Storage mu sync.Mutex sessions map[string]*thread.Session } func newChats(agt *weft.Agent) *chats { return &chats{agt: agt, st: thread.Memory(), sessions: map[string]*thread.Session{}} } // session returns the conversation's one Session, created on first use. func (c *chats) session(ctx context.Context, publicID string) (*thread.Session, error) { c.mu.Lock() defer c.mu.Unlock() if s, ok := c.sessions[publicID]; ok { return s, nil } s, err := thread.Create(ctx, c.st, c.agt, thread.PublicID(publicID)) if err != nil { return nil, err } c.sessions[publicID] = s return s, nil } // close closes every Session (thread's T2: close what you opened to write). func (c *chats) close() { c.mu.Lock() defer c.mu.Unlock() for _, s := range c.sessions { _ = s.Close(context.Background()) } } // chat answers one question: one turn of the conversation's session. func (c *chats) chat(w http.ResponseWriter, r *http.Request) { // The turn outlives the request: keep r.Context()'s values (the // page URL scope.Header put there), drop its cancellation. ctx := context.WithoutCancel(r.Context()) s, err := c.session(ctx, publicIDOf(r)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // The page the request came from, which scope.Header put on the context. if page, ok := scope.PageURLFromContext(r.Context()); ok { log.Printf("chat from %s", page) } turn, err := s.Send(ctx, weft.User(question(r))) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // The run id is known: narrow the scope to it before the first write. scope.Set(w, scope.Scope{PublicID: publicIDOf(r), RunID: turn.RunID()}) res, err := turn.Wait() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } _, _ = io.WriteString(w, res.Text()) } // routes is the app: Studio under /studio/, the page at /, the chat at // POST /chat. It records every run into the local sink Studio serves; // the returned func closes the sessions and the pipeline. func routes(agt *weft.Agent) (http.Handler, func()) { c := newChats(agt) stop := otel.Install(otel.Local("")) // ./.weft/weft.db (or $WEFT_DB), content on mux := http.NewServeMux() // Studio, and with it /studio/panel.js and /studio/panel-config.json. mux.Handle("/studio/", http.StripPrefix("/studio", studio.Handler(studio.DB(otel.LocalDB())))) // The app's own page, which loads /studio/panel.js with one script tag. mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = io.WriteString(w, page) }) mux.Handle("POST /chat", scope.Header(http.HandlerFunc(c.chat), func(r *http.Request) scope.Scope { return scope.Scope{PublicID: publicIDOf(r)} })) return mux, func() { c.close(); stop() } } // parsed reads a scope's string form back, as the panel's parseScope // does: an unknown key is ignored, the fields come back in their order. func parsed() (scope.Scope, string) { s := scope.Parse("pub_demo;flow=f_3;tenant=acme;run=r_9") // s.PublicID "pub_demo", s.FlowID "f_3", s.RunID "r_9"; tenant= is ignored form := s.String() // "pub_demo;flow=f_3;run=r_9" return s, form } func main() { h, stop := routes(newAgent()) defer stop() fmt.Println("app: http://127.0.0.1:8080/ · studio: http://127.0.0.1:8080/studio/") srv := &http.Server{Addr: "127.0.0.1:8080", Handler: h} if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Print(err) } } ``` [devtools/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/devtools/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/devtools) · from `docs-site/examples`: ```sh go run ./devtools go test ./devtools ``` ```text app: http://127.0.0.1:8080/ · studio: http://127.0.0.1:8080/studio/ ``` `TestPanelFilesResolve` fetches the page, `/studio/panel.js` and `/studio/panel-config.json`, and checks that a non-loopback `Host` gets a 404 for the config. ### Best practices & gotchas - **Keep `data-weft` on the tag.** It is how the panel finds its own tag, and with it the endpoint, whatever the file is called. Setup A also finds an unmarked module tag by its URL, but a renamed or proxied file needs the attribute, and so does a tag configured only by `window.__WEFT__`. (Source: `studio/README.md:870-874`; `studio/web/src/panel/config.ts:273-298`) - **Load the panel from the Studio it talks to.** `/panel.js` is embedded in the Studio of the same version; a copied or npm-installed panel older than Studio says `Studio is newer than this panel; update panel.js`. (Source: `studio/web/npm/README.md:22-27`) - **Never put a dev or server token in a page you ship.** `data-token` and `weft:token` are in the page's source; mint a per-page panel token instead. (Source: `studio/README.md:1297-1299`) - **Gate the npm import in production with a dynamic `import()`.** A static import loads `panel.js` and its self-mounted dock whatever `mount()`'s `enabled` says; only the helpers' `enabled: false` loads nothing. (Source: `studio/web/src/npm/index.ts:20`, `index.ts:262`; `studio/web/src/panel/main.ts:66-67`; `studio/web/src/npm/marker.ts:32-34`; observed with `vite build`) - **A panel that vanishes found no Studio; one that asks for a token was refused.** A 401 or 403 keeps the panel with its `Studio needs a token` line: a 401 is a missing, expired or rotated token, a 403 setup A on a `Host` it does not answer. A vanished dock is a failed connection, a CORS error (a page origin Studio does not allow) or a non-Studio answer; the browser's network tab tells them apart. (Source: `studio/web/src/panel/state.ts:2055-2068`; `studio/web/src/panel/client.ts:66-86`; `studio/auth.go:166-215`; observed in Chromium) - **Use `localhost` or `127.0.0.1` for a dev page against `weft studio`.** Any other page origin gets no panel; [When the panel does not connect](https://weftgo.dev/docs/observe/devtools/install/#when-the-panel-does-not-connect) has the ways out, a phone included. (Source: `studio/auth.go:774-792`; `cmd/weft/main.go:875-907`; observed with curl) - **Build the package from the tag you run.** The package is not on the registry; `make devtools-npm` at a different tag gives a panel of a different version. (Source: `studio/README.md:1446-1450`; `AGENTS.md:400`) ### See also - [Scope the panel to a conversation](https://weftgo.dev/docs/observe/devtools/scope/) - [Lay out and theme the panel](https://weftgo.dev/docs/observe/devtools/layout-and-theme/) - [Drive the panel from your page](https://weftgo.dev/docs/observe/devtools/host-api/) - [Secure the devtools panel](https://weftgo.dev/docs/observe/devtools/security/) - [Run Studio: embedded, local binary or hosted](https://weftgo.dev/docs/observe/studio/setup/) Symbols used: [`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler) · [`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB) · [`studio.AllowOrigins`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#AllowOrigins) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`scope.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Header) --- # Connect your app to Studio's playground (weft/runtime) URL: https://weftgo.dev/docs/observe/playground/connect/ Markdown: https://weftgo.dev/docs/observe/playground/connect.md > Register your agents with Studio's playground in one deferred runtime.Install call: the Studio to dial, the agents, model alternates, a resolver, per-experiment budgets and the tools allowed to run for real. [`runtime.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Install) registers your agents with a Studio and opens the [runtime link](https://weftgo.dev/docs/reference/glossary/#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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Enabled), 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](https://weftgo.dev/docs/observe/playground/connect/#setup-a-playground): ```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/playground/main.go) 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. ### Install `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](https://weftgo.dev/docs/observe/playground/connect/#link-log-lines) lists each line. Each [`runtime.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Option): | Option | Effect | |---|---| | [`runtime.Studio(url, token)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Studio) | 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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Local) | talk to the embedded `*studio.Server` in-process, no socket (setup A, [below](https://weftgo.dev/docs/observe/playground/connect/#setup-a-playground)) | | [`runtime.Agents(agents...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Agents) | the agents experiments may run; only registered agents are playable | | [`runtime.Models(map)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Models) | the model alternates a command may switch to, by display name | | [`runtime.ModelResolver(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#ModelResolver) | any other model name a command proposes: your code decides, before the ack | | [`runtime.Limits(runtime.Budget{…})`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Limits) | per-experiment caps ([Budgets](https://weftgo.dev/docs/observe/playground/experiments/#budgets)) | | [`runtime.AllowSideEffects(tools...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#AllowSideEffects) | tools that run for real under `side_effects: "allow"` ([below](https://weftgo.dev/docs/observe/playground/connect/#side-effects)) | | [`runtime.Threads(store)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Threads) | the thread storage transcripts resolve through first; fork mode needs it ([below](https://weftgo.dev/docs/observe/playground/connect/#thread-stores)) | | [`runtime.Sessions(resolve)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Sessions) | your app's own thread turns take approvals and steer from Studio ([Approve and steer your app's own turns](https://weftgo.dev/docs/observe/devtools/app-turns/)) | | [`runtime.Enabled(on)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Enabled) | 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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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](https://weftgo.dev/docs/observe/destinations/)). 2. The [discovery file](https://weftgo.dev/docs/reference/glossary/#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#example-Install) builds the whole call with `runtime.Enabled(false)`, so it stays inert. ### Agents and models [`runtime.Agents`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Agents) names the agents a runtime exposes. An agent without a [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) cannot register, since its manifest would be nameless: it is skipped with a WARN. A duplicate name keeps the first. [`runtime.Models`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Models) maps display names to [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#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: ```json {"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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 : `. The example's resolver serves `acme/*` names only: ```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/playground/main.go) From `TestOverrideRefusalsNameTheirRule`, a command with `"model": "openai/gpt-4.1"` ends on this row: ```json {"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 : 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#example-ModelResolver) refuses every name that is not `anthropic/claude-*`. ### Side effects [`runtime.AllowSideEffects`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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?](https://weftgo.dev/docs/observe/playground/overview/#side-effects). 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`. ### Thread stores [`runtime.Threads`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Threads) sets the [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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: ```json {"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. ### Setup A playground In [setup A](https://weftgo.dev/docs/reference/glossary/#setup-a-b-c) Studio is embedded in your app. Build it with `studio.Playground(true)` and hand the server to [`runtime.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Local): ```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/playground/main.go) 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](https://weftgo.dev/docs/observe/studio/setup/#embed-studio)). weft's [`runtime/examples/local`](https://github.com/weftgo/weft/tree/v0.20.2/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: ```sh 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 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`): ```sh curl -s http://127.0.0.1:8080/studio/api/runtimes ``` ```json {"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 `-` and the link adopts it: two replicas in one directory get distinct ids. **Studio keeps the link's state** through [`obsdb.CommandStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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. ### Acks and at-most-once Each command runs at most once. The runtime acks it **before** it executes, and Studio refuses a reused command id with 409: ```json {"error":{"code":"conflict","message":"command id cmd_replay_1 was already used"}} ``` A command's row moves through five states: | State | Means | |---|---| | `queued` | Studio put it on the runtime's stream | | `accepted` | the runtime validated it and will run it; `run_id` names the run (empty for a fork until its turn starts) | | `rejected` | the runtime refused it; `error` says why (`budget_exceeded`, a validation sentence, the resolver's text) | | `finished` | the run ended; `status` is `succeeded` or `failed`, `error` a failed run's text | | `lost` | Studio gave up waiting; `error` says what it waited for | Send one, here the replay [Replay a run from any step](https://weftgo.dev/docs/observe/playground/replay/) starts with: ```sh 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"}' ``` ```json {"command_id":"cmd_docs_1","state":"queued"} ``` Then poll it with `GET /api/playground/commands/{id}`: ```sh curl -s http://127.0.0.1:8080/studio/api/playground/commands/cmd_docs_1 ``` ```json {"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. ### Link log lines 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: | Level | Message | Attributes | When | |---|---|---|---| | WARN | `weft/runtime: Install without agents: no link opened` | `hint` `runtime.Agents(...) names the agents a runtime exposes` | `Install` was given no `runtime.Agents`, or an empty one. Nothing opens | | WARN | `weft/runtime: no Studio to dial: no link opened` | `hint` `runtime.Studio(url, token), runtime.Local(srv), or a Studio destination in weft/otel` | No `Studio`, no `Local`, no pipeline Studio destination and no trusted discovery file. Nothing opens | | WARN | `weft/runtime: the pipeline records only into a Local store (otel.Local, or otel.Install's default) and names no Studio: no link opened` | `hint` | The installed `weft/otel` pipeline records into a Local store and names no Studio, and `Install` names none either. Nothing opens ([weft dev](https://weftgo.dev/docs/observe/weft-dev/)) | | INFO | `weft/runtime: joined the running Studio` | `url`, `pid`, `file`, `hint` | The discovery file named the Studio to dial | | WARN | `weft/runtime: the Studio token travels unencrypted over http to a non-loopback host` | `hint` `use an https Studio URL` | A token is set and the URL is `http://` to a host other than `localhost` or a loopback IP (setup C). The link still opens | | WARN | `weft/runtime: agent without core.Name is not playable` | `hint` `core.Name names an agent in its manifest` | A nameless agent in `runtime.Agents`; it is skipped | | WARN | `weft/runtime: link failed to start` | `err` | The link could not start. Nothing opens. In v0.20.2 the link's start returns no error, so this line is not expected | | WARN | `weft/runtime: Studio refused the runtime link; the playground stays off until the token is right` | `status` (`401 Unauthorized` or `403 Forbidden`), `hint` `runtime.Studio(url, token) carries the token — with runtime.Local(srv) too, when srv was built with studio.Token` | The register call was refused for its token. Logged once per link | | DEBUG | `weft/runtime: register failed; retrying` | `err`, such as `weft/runtime: register: 401 Unauthorized` | Every 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 | | DEBUG | `weft/runtime: command stream ended; reconnecting` | `err` | The 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. #### Command log lines 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. | Level | Message | Attributes | When | |---|---|---|---| | WARN | `weft/runtime: undecodable run command` | `err` | A run frame that is not a command. The runtime rejects it with `undecodable command` when its id is usable | | WARN | `weft/runtime: command frame without a usable id ignored` | none | A frame with no id, or one Studio would refuse. It is neither run nor acked | | WARN | `weft/runtime: the accepted ack was not taken; the command is not run` | `command_id` | Studio refused the accepted ack or did not confirm it ([above](https://weftgo.dev/docs/observe/playground/connect/#acks-and-at-most-once)). Nothing runs | | WARN | `weft/runtime: the accepted ack was not taken; the decision is not applied` | `command_id` | The same for a decision on a parked playground run: the resume does not run, and the park keeps that call | | WARN | `weft/runtime: the accepted ack was not taken; the decision is not held` | `command_id` | The same for a decision that leaves other parked calls undecided: it is not held, so deciding again is not refused as already decided | | WARN | `weft/runtime: the accepted ack was not taken; the session is not written` | `command_id` | The same for a decision or steer on your app's own turn ([App-owned turns](https://weftgo.dev/docs/observe/devtools/app-turns/)) | | WARN | `weft/runtime: ack failed` | `command_id`, `state`, `err` | Posting an ack failed in transport; it counts as unconfirmed | | WARN | `weft/runtime: ack unconfirmed` | `command_id`, `state`, `status` | Studio answered an ack with a 5xx | | WARN | `weft/runtime: ack refused` | `command_id`, `state`, `status` | Studio answered an ack with any other non-200 status, such as 409 once it marked the command lost | | WARN | `weft/runtime: playground run failed` | `command_id`, `run_id`, `err` | A playground run ended in an error; its finished ack carries the text | | WARN | `weft/runtime: fork command failed` | `command_id`, `source`, `err` | A `"thread": "fork"` command could not fork or run its turn | | WARN | `weft/runtime: fork resume failed` | `session`, `err` | A decision on a parked fork could not resume its session | | WARN | `weft/runtime: forked session not released` | `session`, `err` | Closing a forked session failed, so its writer lease may still be held | | WARN | `weft/runtime: session command failed` | `command_id`, `session`, `verb`, `err` | A decision or steer on your app's own turn failed after its ack; the finished ack says why | | WARN | `weft/runtime: source transcript unresolved; running on the input alone` | `run_id`, `err` | A command with a fresh input whose source transcript could not be read runs on the input ([Replay](https://weftgo.dev/docs/observe/playground/replay/)) | | WARN | `weft/runtime: the source step's compaction view could not be read; it is unknown, the thread's messages are used` | `run_id`, `step`, `err` | A 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 | | WARN | `weft/runtime: no request record places the source step's messages (derived); the replay uses the transcript cut at the step, no compaction view known` | `run_id`, `step` | No request record places the source step's messages: an older run, or a request recorded with content off | | WARN | `weft/runtime: this Studio does not answer the transcript as of a step (ADR 0029); a compaction view of the source step is unknown` | `run_id`, `step` | The Studio is older than `GET /api/runs/{id}/transcript?step=` | | WARN | `weft/runtime: manifest for agent failed` | `agent`, `err` | Building a registered agent's manifest failed; it registers without one. Not expected, since names are checked first | | ERROR | `weft/runtime: command panicked` | `command_id`, `panic` | A 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 | | ERROR | `weft/runtime: in-process Studio handler panicked` | `path`, `panic` | Under `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. ### Complete example ```go title="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 } ``` [playground/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/playground/main.go) [View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/playground) · run it from `docs-site/examples`: ```sh go run ./playground go test ./playground ``` ```text playground: http://127.0.0.1:8080/studio/playground source run: dd66354adfaac2b44848f0c1ed75516f ``` The tests in [`main_test.go`](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/playground/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. ### Best practices & gotchas - **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`) ### See also - [How does the playground work?](https://weftgo.dev/docs/observe/playground/overview/) - [Replay a run from any step, with edits](https://weftgo.dev/docs/observe/playground/replay/) - [Run Studio](https://weftgo.dev/docs/observe/studio/setup/) - [Develop with weft dev](https://weftgo.dev/docs/observe/weft-dev/) - [Environment variables](https://weftgo.dev/docs/reference/env/) Symbols used: [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`runtime.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Install) · [`runtime.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Option) · [`runtime.Studio`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Studio) · [`runtime.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Local) · [`runtime.Agents`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Agents) · [`runtime.Models`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Models) · [`runtime.ModelResolver`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#ModelResolver) · [`runtime.Limits`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Limits) · [`runtime.Budget`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Budget) · [`runtime.AllowSideEffects`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#AllowSideEffects) · [`runtime.Threads`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Threads) · [`runtime.Sessions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Sessions) · [`runtime.Enabled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Enabled) · [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Model) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage) · [`otel.StudioEndpoint`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#StudioEndpoint) · [`obsdb.CommandStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CommandStore) · [`studio.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#New) · [`studio.Playground`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Playground) --- # Find runs: the runs list, search and filters URL: https://weftgo.dev/docs/observe/studio/runs/ Markdown: https://weftgo.dev/docs/observe/studio/runs.md > Find a recorded run in Studio by status, agent, text, tool, model, tokens, cost, tag or id: the runs list, its filters, full-text search, the ⌘K palette and the API behind them. The runs list (`/runs`, the page Studio opens on) lists the recorded runs newest first, one row each. The heading counts the top-level runs. You narrow the list from the toolbar: a text search, an agent, a status, more filters behind **+ filter** (its button counts the ones set), the top-level toggle, and a **? keys** chip that lists the keys. Each filter is a removable chip and a key in the URL, so a filtered list is a link. To jump to one run by its id, press ⌘K (or Ctrl+K) and paste the id. ![weft Studio's runs list: each run's status, prompt and id, agent, steps, tokens, cost, start and duration, newest first, with a checkbox per row to pick runs to compare](https://weftgo.dev/docs/_astro/studio-runs.light.CFMu-KA1.webp) *The runs list: status, the prompt as the title with the id under it, agent, steps, tokens, cost, start and duration.* ### The runs list A row is one [run](https://weftgo.dev/docs/reference/glossary/#run). Its columns: | Column | Shows | |---|---| | status | A dot and a [status word](https://weftgo.dev/docs/observe/studio/runs/#status-words) | | run | The title, then the id (copyable) and the public id; under them what stopped the run, the error of a failed run, and [problem badges](https://weftgo.dev/docs/observe/studio/runs/#problem-counters) | | agent | The agent's `weft.Name`; "unnamed agent" when it has none | | session | The thread session the run is a turn of: its short id and turn (`s_01M567…RBQA ·t3`), linked to the session | | model | `provider/model` | | steps | Steps taken | | tokens in / out | Input and output tokens; when the run reports them, a hover card splits out the cached, cache-write and reasoning tokens | | cost | The run's own cost at read time, under the `pricing` capability ([See what a run cost](https://weftgo.dev/docs/observe/studio/cost/)) | | started, duration | Relative start (absolute on hover), and the run's length; elapsed so far while it runs | The title is the run's own prompt: the turn's question, cut to 200 runes in the API's `prompt_preview`. Without a prompt the title falls back to the agent (drawn "agent · (content not captured)" when the run was recorded with content off), else "(content not captured)", else the id. A run that ended other than by the model answering (a `StopWhen`, a park, a budget) says what stopped it under the title, from the row's `stopped_by`: "parked on an approval", "max steps reached", "usage limit reached". The list shows the word alone (its hover is the hint) and skips a run that succeeded on `final_answer`; [the stop chip](https://weftgo.dev/docs/observe/studio/run-page/#the-stop-chip) lists every word and the detail the run page adds. The list is top-level only by default: a [child run](https://weftgo.dev/docs/reference/glossary/#child-run) is on its parent's page. Press **top-level only** to switch to **with child runs** (`?subagents=all`): the loaded rows are drawn as trees, each child under its parent. A run that started others carries a "⑂ n" chip (the failed ones counted in red); it opens that run's children under it, read through `?parent=`. It draws the first 100 children, one level deeper; a grandchild is read when its own chip is opened. Past them a line links the full list at `/runs?parent=`: `+N more · open the list` when the row counts more, or `+ more · open the list` when the read has a next page the count does not show. "⑂ ?" means the children could not be counted. The refresh button at the end of the toolbar's first row reads the list again; the filters wrap among themselves, never the button onto a row of its own. A filter that matches nothing says "No runs match these filters." with **clear filters**; an empty database says how to record runs instead. With an agent filter set, **follow** streams that agent's run frames from `/api/live?agent=` and updates the list as runs start and finish. **load more** reads the next page; the line beside it says "showing N of total". Keys on the list: `/` focuses the search box, `j` and `k` (or ↓ ↑) move the selection, Enter opens the selected run, `?` lists every key. Clicking a row opens the run. On a narrow window the quieter columns fold away, in this order: session and model (below 1536 px), steps, tokens and cost, started and agent. From 1280 to 1800 px with the sidebar open every column stays in the frame: the status, tokens and cost wrap rather than widen the table, a token pair breaks only at its dot ("20 in ·" over "10 out"), and a run that delegated shows its subagents' tokens on a second line under its own. The run column is 14 rem wide, 16 rem from 1360 px and 20 rem from 1680 px, and 14 rem again from 1536 px, where the session and model columns join. The same rows are `GET /api/runs` (top-level only; `all=1` adds every child run, `parent=` lists one run's children), and `weft runs` prints them in a terminal with PROMPT and STOPPED BY columns ([The weft command](https://weftgo.dev/docs/observe/cli/)). ### Status words One status vocabulary is shared by the runs list, the run header, a session's turns, the live table and the devtools panel. Four words are stored; `parked` and `cancelled` are read at request time, never stored. | Word | Means | |---|---| | `running` | The recorder's heartbeat is fresh | | `succeeded` | The run finished with a result | | `failed` | The loop returned an error; a kind chip such as `[max_steps]` names it | | `interrupted` | Stored as running, but nothing was heard for over 30 s: a crash or a kill | | `parked` | Succeeded with calls pending at the [approval boundary](https://weftgo.dev/docs/reference/glossary/#approval-boundary), and no resume known | | `cancelled` | Failed with error type `cancelled`: the run's context ended. Its cancel cause is in the hover. Beside the status word (the run header, the devtools panel) the stop chip reads the cause alone; the runs list's stop line reads `cancelled · ` | A parked run that was resumed reads `parked → t2`, a link to the turn that resumed it: the row's stored `resumed_by` (set when the resume passed [`weft.ResumeOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResumeOf)), else a later turn of its thread session. With no turn number to name, the word carries the resuming run's id cut to 8 characters ("parked → 3f9a1c2b…"). A plain `Generate` resume without `ResumeOf` has no link, so its parked run keeps reading `parked`. The detail under a parked word says how sure it is: | Detail | Shown when | |---|---| | `1 call awaiting a decision` | A session turn read against its session's whole turn list, where a resume could not be missed | | `1 call pending · no resume recorded here` | Any other session turn: the page did not read every later turn | | `1 call pending · a resume, if any, is not linked yet` | A plain `Generate` run, with no session to look in | | `1 call decided · resumed in t2` | The stored `resumed_by` link names the resume | | `1 call · next turn t2 (decided or dropped)` | Only a later turn of its session was found. After a `Branch`, a `Rollback` or an undecided `Send`, that turn is no resume: it decided the calls or dropped them | Under the `parked` filter, a row the page reads as decided only because a later turn of its session followed it says "decided by a later turn the record does not link". The status filter offers all six. `parked` lists the open parks only (pending calls, no run whose `resumed_from` names it), and `cancelled` the failed runs whose error type is cancelled; both are applied by the server, so paging and the total count the filtered set. ### Problem counters A run row carries counters Studio derives at ingest from the run's spans, and the list badges a run only when it had a problem; a clean run draws nothing. Hover a badge for its words. | Badge | Counter | Means | |---|---|---| | `↻2` | `attempts_retried` | Model attempts that failed and were retried | | `⇄` | `fallbacks` | Model calls a fallback model answered | | `✗3` | `tool_errors` | Tool calls that ended in an error (a `RETRY`, a denial or a cancellation is not counted) | | `✋` | `denied` | Calls denied, or held at a park | | `✂1` | `truncated` | Tool results cut by the result cap | | `⚒` | `repaired` | Tool calls whose arguments a model middleware repaired (`mw.RepairJSON`, `Reporter.Repair`); since 0.20.0, before which the core reported none | | `⚠1` | `tap_panics` | Observer panics the run contained | | `E1`, `W2` | `log_error`, `log_warn` | App log lines at ERROR and WARN under the run (`≥` when the count hit the reader's cap); counted when the run itself is read, so they show on the run header, not in the list | A failed run also gets a kind chip in brackets from its `error_type`, such as `[max_steps]`. The run header spells the same counters out beside the step count, with each tool error's kind in the order first seen ("3 tool errors: RATE_LIMITED ×1, timeout ×1, panic · handler ×1"). `/api/runs` and `/api/search` filter on `error_type=` and `stopped_by=` (exact, or a prefix ending in `:` such as `has_tool_call:`). ### Search Type in the search box: every term must occur in the run's prompt, its answer (the last assistant text), its error, or the name of a tool it called, ignoring case. Terms are separated by spaces; a `"quoted phrase"` is one term. Search never reads the system prompt, a tool result or the tool catalog. ![The runs list searched for "refund": the matching runs, parked ones linked to the run that resumed them](https://weftgo.dev/docs/_astro/studio-search.light.5zzjd95v.webp) *The runs list searched for refund.* **+ filter** opens the other filters. Each one set is a chip; a chip Studio could not apply is drawn struck through with "not applied —". | Filter | URL key | Matches | |---|---|---| | search box | `q` | Every term, as above | | agent | `agent` | The agent's name, exact | | status | `status` | One of the six words | | tool | `tool` | A tool the run called, exact | | model | `model` | The model name, exact | | error contains | `error` | A substring of the error, ignoring case | | since, until | `since`, `until` | The start: a day `YYYY-MM-DD` (UTC; `until` includes the day) or an RFC 3339 time with its zone | | ≥ seconds | `min_duration` | Duration at least, applied to the loaded rows | | ≥ tokens | `min_tokens` | Input + output tokens at least | | ≥ $ | `min_cost` | Own + delegated cost at least, under `pricing`; an unpriced run never matches | | + tag k=v | `tag` | A metadata pair; repeatable | | session, public id | `session`, `public_id` | One conversation | | experiments | `experiments` | any runs, experiments off, or experiments only | Click the started, duration, tokens or cost column header to sort (`?sort=duration|tokens|cost`, longest or most first; newest first without it). A day that does not exist, or a time without a zone, stays in the URL as a "not applied" chip with a note, and is never sent. #### Where search runs With a text, a search-only filter or a sort, the list reads `GET /api/search`; otherwise `GET /api/runs`. Search needs the `search` capability, which Studio lists when its database implements [`obsdb.Searcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Searcher). Both first-party backends do: SQLite through an FTS5 trigram index kept on write, ClickHouse through case-insensitive substring scans. Without it, the box is off and says why; tool and text chips are not applied, and model, error, the date range and the minimums (≥ $ only under `pricing`) filter only the loaded rows, saying so. `min_cost` and `sort=cost` are applied in Studio, since cost is computed at read time: it prices the first 2,000 runs of the match in the order asked. A larger match is cut there, and the page says the runs past it were neither priced nor listed (the API's `cost_sort_cap`). Duration is always filtered over the loaded rows; the API has no duration filter. The same search from a terminal, against a `weft studio` with its dev token (`$TOKEN`): ```sh curl -s -H "Authorization: Bearer $TOKEN" \ 'http://127.0.0.1:7331/api/search?q=refund&status=failed&min_tokens=1000&sort=tokens&limit=20' ``` It answers run rows (no snippet), `total`, `sort` and `next_offset` for the next page. `limit` is 50 by default, 500 at most. #### Find a run by id with ⌘K ⌘K (Ctrl+K) opens the palette on any page: runs, sessions, traces under `traces`, experiments under `playground`, and the pages. A pasted id is looked up, never fuzzy-matched: - one word of 4 characters or more is an id prefix, looked up as a run (`GET /api/runs?id_prefix=…&all=1`, child runs included), as a session (`GET /api/sessions?id_prefix=…`) and as a trace (`GET /api/traces?id_prefix=…`), and also as a public id; - `pub_…` is a public id at any length; - `key=value` is a tag. Their matches rank first under **Exact match**, and Enter opens the first. Every other item matches by contiguous substrings of its words, never a subsequence, so text that matches nothing opens nothing. `id_prefix` matches byte for byte on every route: no wildcard, no case folding ([`obsdb.SessionQuery.IDPrefix`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionQuery), [`obsdb.TraceQuery.IDPrefix`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TraceQuery), both backends). The list also picks runs to compare: `x` (or a row's pick box) marks the selected run, and with two or more marked **compare N** opens them on the compare page, the first as the base ([Compare runs step by step](https://weftgo.dev/docs/observe/studio/compare/)). A row's own and delegated tokens read "3 in · 1 out" with "+9 in · 5 out" on a second line under it when it has subagent child runs. They are `own_usage` and `delegated_usage` on the run row, omitted with no Subagent child, while running, when a child read failed, or when a panel token cannot see a child. ### Best practices & gotchas - **Give agents a name.** The agent filter, follow and the palette key on `weft.Name`; a nameless agent reads "unnamed agent" everywhere. (Source: `lib/format.ts` `UNNAMED_AGENT`; CHANGELOG.md:316) - **Pass `weft.ResumeOf` when you resume a park.** Without it a plain `Generate` resume is not linked, and its parked run keeps reading `parked` in the list and the `parked` filter. (Source: `studio/README.md:2044-2081`) - **Keep content on where you search.** A content-off run has no prompt or answer to match; only its error text and tool names can match, and its title falls back to its agent. (Source: `obsdb/search.go:43-48`; `lib/title.ts:244-254`) - **Cost filters stop at 2,000 runs.** Narrow by agent or date first when `min_cost` or `sort=cost` reports the cap. (Source: `studio/search.go:55-80`) ### See also - [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/) - [Browse sessions and traces in Studio](https://weftgo.dev/docs/observe/studio/sessions-and-traces/) - [Get around Studio: keyboard, panes and settings](https://weftgo.dev/docs/observe/studio/navigation/) - [Studio HTTP API](https://weftgo.dev/docs/reference/studio-api/) - [Studio pages, URL parameters and keyboard](https://weftgo.dev/docs/reference/studio-urls/) Symbols used: [`obsdb.Searcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Searcher) · [`obsdb.SearchQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SearchQuery) · [`obsdb.RunQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RunQuery) · [`weft.ResumeOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ResumeOf) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) --- # Bridge your app's slog lines into runs URL: https://weftgo.dev/docs/observe/app-logs/ Markdown: https://weftgo.dev/docs/observe/app-logs.md > Add otel.Slog() to otel.Install and every slog line logged with a run's context — your tool handlers', weft.Logger's, mw.Log's, mw.Audit's — is stored under the span it was logged in and shown on the run's logs in Studio. [`otel.Slog()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Slog) bridges `slog.Default` into weft's pipeline: every line logged with a context that carries a span becomes an [app log record](https://weftgo.dev/docs/reference/glossary/#app-log-record) under that span, beside the run's own records. A tool handler's `slog.InfoContext(ctx, …)` then shows on that tool call in Studio. The lines still go wherever they went before. Bridge `slog.Default` and log from a tool handler, in `applogs/main.go`: ```go title="applogs/main.go" defer otel.Install(otel.Local(""), otel.Slog())() // slog.Default now tees to the pipeline lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in LookupInput) (string, error) { slog.InfoContext(ctx, "looking up order", "order_id", in.OrderID) // ctx carries the call's span slog.WarnContext(ctx, "order not in cache", slog.Group("cache", "region", "eu-1", "hit", false)) return "", &weft.ToolError{Code: "ORDER_NOT_FOUND", Message: "order " + in.OrderID + " does not exist"} }) ``` [applogs/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/applogs/main.go) The `ctx` a tool handler receives carries its `execute_tool` span, so both lines land on that tool call. A line logged with a context that has no span, outside any run, stays with your handler alone. ### Bridge slog `otel.Slog()` is an `Install` option. Once the pipeline is registered, it wraps the default logger's handler, so every `slog.Default` line logged under a span reaches the pipeline as well as its old handler: your own, those of [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger) (whose default is `slog.Default`), [`mw.Log(nil)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Log) and [`mw.Audit(slog.Default())`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Audit). Shutdown restores the previous default. The package example [`ExampleSlog`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#example-Slog) installs it and reads weft's run lines back as the run's app logs. Each line becomes one record: | Field | Value | |---|---| | span | the context's span (table below) | | scope | `github.com/weftgo/weft/otel/slog` | | severity | the slog level + 9, held to 1–24: DEBUG 5, INFO 9, WARN 13, ERROR 17; the level's name as severity text | | body | the slog message | | attributes | flattened, a group's keys joined with `.` (`cache.region`); durations and times as strings; a key starting `weft.` renamed `slog.weft.…`; the first 120 kept and the rest counted in `weft.log.attrs_dropped` | Which span a line lands on is the context it was logged with: | Span | Lines | |---|---| | `invoke_agent` | `weft.Logger`'s `run start`, `run finish` and, for a failed run in its place, `run error` | | `chat` | `weft.Logger`'s `model call` and `model attempt`; `mw.Log`'s lines; anything the model chain logs | | `execute_tool` | `weft.Logger`'s `tool call`; `mw.Audit`'s lines; a tool handler's own lines | The bridge has no level of its own: every level, DEBUG included, goes to the pipeline, while the handler you had keeps filtering at its level. That is why the example's DEBUG lines from `weft.Logger` are recorded although the terminal shows INFO and above. Lines from the pipeline itself, its WARNs about destinations, are never bridged. A program that never called `slog.SetDefault` is on slog's built-in handler, which cannot be wrapped. Its lines keep going to the `log` package's writer through a `slog.TextHandler` at the level `slog.SetLogLoggerLevel` set (INFO unless changed, read once at `Install`), so their format changes to `time=… level=… msg=…` while the bridge is installed; shutdown puts the old form back. One `Slog` pipeline at a time: a second `Install(…, otel.Slog())` wraps the first's bridge. Shut them down in reverse order; out of order, the last shutdown still restores what the first found. #### Bridge a logger you build [`otel.SlogHandler(next)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#SlogHandler) returns a handler that tees each record to `next` (when `next` is non-nil and enables the level) and to the installed pipeline, looked up per record. Build `slog.New(otel.SlogHandler(h))` before or after `Install`: it starts teeing once `Install` has run and stops after shutdown. Pass that logger to `weft.Logger`, `mw.Log` or `mw.Audit` to route weft's own lines through it. [`ExampleSlogHandler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#example-SlogHandler) builds one before `Install` and stores a tool handler's WARN under its `execute_tool` span. Under [`otel.NoGlobal()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoGlobal) nothing is installed, and `otel.Slog()` leaves `slog.Default` alone. Bind a handler to the pipeline with [`p.SlogHandler(next)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline.SlogHandler) instead, as a test in `applogs/main_test.go` does: ```go title="applogs/main_test.go" p, err := otel.Start(ctx, otel.NoEnv(), otel.NoGlobal(), otel.Local(path), // takes app logs: content on otel.Exporters(nil, vendor, otel.AppLogs(true)), // opted in: receives them stripped otel.Exporters(nil, other), // not opted in: receives none ) if err != nil { t.Fatal(err) } logger := slog.New(p.SlogHandler(slog.DiscardHandler)) // tee to this pipeline, and to next lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in LookupInput) (string, error) { logger.WarnContext(ctx, "slow lookup", "order_id", in.OrderID, "weft.run.id", "spoofed") return "shipped", nil }) agt := weft.New(script(), lookup, weft.Logger(logger), // weft's own Debug run lines through the same bridge weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) ``` [applogs/main_test.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/applogs/main_test.go) #### Choose which destinations take the lines An app may log anything, prompts included, so app log lines are content. [`otel.AppLogs(on)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#AppLogs) decides per destination; by default Local and Studio with content on take them, and Datadog, Langfuse, `OTLP` and `Exporters` do not. `AppLogs(true)` admits the lines and never bypasses the destination's content policy: - A content-on destination applies its `Redact` to the message and every string attribute, with the kind [`otel.ContentLog`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#ContentLog) (`"log"`), then its `MaxBytes` cap (32 KiB by default), and sums what it cut in `weft.content.truncated_bytes`. A `Redact` that panics drops the line. [`ExampleContentLog`](https://github.com/weftgo/weft/blob/v0.20.2/otel/example_test.go#L161) masks a card number this way. - A content-off destination that opted in receives each line stripped: message and string values empty, `weft.content` `stripped`, time, severity, span and other attributes kept. In the test above, `vendor` receives the lines that way and `other` receives none. `AppLogs(false)` keeps the lines from a Local or Studio destination. Under a full queue, bridged lines are shed with the deltas, before weft's own records ([queues](https://weftgo.dev/docs/observe/destinations/#queue-size-and-blocking)). Records your app emits through the OTel Logs API itself are not the bridge's, and `AppLogs` does not govern them. An agent built with [`weft.Content(false)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Content) keeps content out of its own lines before any destination sees them: `weft.Logger`'s `tool call` line logs an error result's size (`err_bytes`) instead of its text, and `mw.Audit` logs `err_bytes` and the `ToolError` code instead of the error and its cause. The switch is per agent: a [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) child built without `Content(false)` logs the error text and cause again, so build every agent in the delegation with it. #### The bridge mark While a bridge is live, each run's `invoke_agent` span carries `weft.logs.bridged`, the number of lines the bridge had emitted, on the copy sent to each destination that takes app logs. The span carries the count as it stood when the run began; each heartbeat carries the count so far. The mark says "this store holds the run's bridged lines". When a run's stored root span lacks it and no line is attributed to the run, Studio's logs route reads that as "no weft slog bridge was recorded for this run" and names the fix, `otel.Install(…, otel.Slog())` or `slog.New(otel.SlogHandler(h))`. ### In Studio The run page's **logs** view (`?view=logs`, key `l`) lists every line attributed to the run, in time order: its offset from the run's start, severity, body and attributes. A severity filter, `?lsev=info|warn|error`, keeps a level and above. **Jump to span** opens the run-tree row the line was logged under (`?sel=t:&tab=logs`), or its nearest drawn ancestor. A tree row that holds WARN or ERROR lines carries a tick, `E1 W2`, read at `severity=warn` when the run counts such lines, and its drawer has a **Logs** tab. When that read hit its 10,000-line cap the tick reads `≥E1 W2`: the counts are floors, and its title says `at least …` and `the first 10,000 WARN+ lines were read`. The view reads 1,000 lines a page up to 10,000 and badges a longer list `truncated`; while the run runs it reads on every 5 seconds. The devtools panel's step heads link to the same view. ![A run page's logs view: seven lines under the run's spans, the app's own INFO "looking up order" and WARN "order not in cache" lines among weft's DEBUG run, model and tool lines, each with jump to span](https://weftgo.dev/docs/_astro/studio-run-logs.light.B0DmM1Vt.webp) *This page's program in Studio's logs view: "looking up order" at INFO and "order not in cache" at WARN, with the cache.* attributes flattened.* The JSON API behind it is `GET /api/runs/{id}/logs?from=&limit=&severity=`, under the capability `logs` in `/api/meta`: ```json {"logs": [{"index": 2, "time": "…", "severity": "INFO", "severity_number": 9, "body": "looking up order", "attrs": {"order_id": "5678"}, "span_id": "…"}], "holes": []} ``` - A row carries `event_name` when the line is an OpenTelemetry event: the OTLP record's EventName when it has one; a plain line has none. The logs view also takes an older SDK's `event.name` attribute, which stays in the row's `attrs`. The logs view draws a GenAI event (`gen_ai..message`, `gen_ai.choice`) as that message, with its role, content, an assistant's tool calls and a choice's finish reason, and `weft mcp`'s `logs` tool answers the field too. - `from` is the first index; `next_from` continues a full page. `limit` defaults to 100, at most 1,000. - `severity` keeps a level and above: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, or a number 1–24. - `holes` names what the page cannot show: `not_recorded` (the run stored no span to attribute lines through, or the bridge hint above), `truncated` (the run's traces hold more than 10,000 log lines in its window, so later lines may be missing), `gap` (lines naming a span that is not stored). A running run's page is `partial` instead: lines under spans still open appear once those spans end. - A line logged through the OTel Logs API on the pipeline's provider is an app log too, attributed the same way. - A read-scoped panel token is refused the route, 403 with the `hidden` badge: the lines may carry prompts. The run row carries `delta_count` beside them: the deltas the run streamed, counted and never stored. The route reads [`obsdb.DB.OtherLogs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB), which your program can call on the local sink too. The example reads its lines back and names each one's span: ```go title="applogs/main.go" db := otel.LocalDB() page, err := db.OtherLogs(ctx, res.ID, obsdb.LogQuery{}) // what Studio's runs/{id}/logs serves if err != nil { return err } spans, err := db.RunSpans(ctx, res.ID) if err != nil { return err } name := map[string]string{} for _, s := range spans { name[s.SpanID] = s.Name } for _, l := range page.Logs { fmt.Fprintf(w, "%-5s %-18s %s%s\n", obsdb.SeverityText(l.Severity), l.Body, name[l.SpanID], attrs(l.Attrs)) } ``` [applogs/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/applogs/main.go) ### Complete example ```go title="applogs/main.go" // Command applogs runs the example of the guide "Bridge your app's slog // lines into runs": go run ./applogs. The model is scripted with // wefttest, so it runs offline; the run and its log lines are recorded // to ./.weft/weft.db (or $WEFT_DB) and read back from it. package main import ( "context" "fmt" "io" "log" "log/slog" "os" "sort" "strings" "github.com/weftgo/weft" "github.com/weftgo/weft/obsdb" "github.com/weftgo/weft/otel" "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"` } // 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":"5678"}`}), wefttest.Say("I could not find order 5678."), ) } func main() { if err := run(context.Background(), os.Stdout); err != nil { log.Fatal(err) } } func run(ctx context.Context, w io.Writer) error { defer otel.Install(otel.Local(""), otel.Slog())() // slog.Default now tees to the pipeline lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in LookupInput) (string, error) { slog.InfoContext(ctx, "looking up order", "order_id", in.OrderID) // ctx carries the call's span slog.WarnContext(ctx, "order not in cache", slog.Group("cache", "region", "eu-1", "hit", false)) return "", &weft.ToolError{Code: "ORDER_NOT_FOUND", Message: "order " + in.OrderID + " does not exist"} }) agt := weft.New(script(), weft.Name("support-bot"), lookup) res, err := agt.Generate(ctx, weft.Prompt("Where is order 5678?")) if err != nil { return err } slog.InfoContext(ctx, "outside any run") // no span on ctx: not bridged db := otel.LocalDB() page, err := db.OtherLogs(ctx, res.ID, obsdb.LogQuery{}) // what Studio's runs/{id}/logs serves if err != nil { return err } spans, err := db.RunSpans(ctx, res.ID) if err != nil { return err } name := map[string]string{} for _, s := range spans { name[s.SpanID] = s.Name } for _, l := range page.Logs { fmt.Fprintf(w, "%-5s %-18s %s%s\n", obsdb.SeverityText(l.Severity), l.Body, name[l.SpanID], attrs(l.Attrs)) } return nil } // attrs prints the app's own attributes of a line, sorted. func attrs(m map[string]any) string { var keys []string for k := range m { if k == "order_id" || strings.HasPrefix(k, "cache.") { keys = append(keys, k) } } sort.Strings(keys) var b strings.Builder for _, k := range keys { fmt.Fprintf(&b, " %s=%v", k, m[k]) } return b.String() } ``` [applogs/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/applogs/main.go) From `docs-site/examples`: ```sh go run ./applogs go test ./applogs ``` Standard output, the lines read back from the local sink: ```text DEBUG run start invoke_agent support-bot DEBUG model call chat script INFO looking up order execute_tool lookup_order order_id=5678 WARN order not in cache execute_tool lookup_order cache.hit=false cache.region=eu-1 DEBUG tool call execute_tool lookup_order DEBUG model call chat script DEBUG run finish invoke_agent support-bot ``` On standard error the built-in handler, now a `TextHandler`, prints the INFO and WARN lines and `outside any run`; that last line had no span and is not in the database. `TestPipelineSlogHandler` checks the WARN's severity (13), the `weft.run.id` key renamed `slog.weft.run.id`, the bridge mark on the root span and the stripped copy; `TestAttributeCap` logs 130 attributes and reads `weft.log.attrs_dropped` 10. ### Best practices & gotchas - **Log with the context you were given.** Only a line logged with a span-carrying context is bridged; `slog.Info` without a context, or with `context.Background()`, names no run. (Source: `otel.SlogHandler` godoc) - **Expect DEBUG lines in the store.** The bridge sends every level; weft's run lines are DEBUG. Filter in Studio with `lsev=`, not at the bridge. (Source: record contract §4, app log records) - **Opt a third party in deliberately.** `AppLogs(true)` on a content-off destination sends severity, span and non-string attributes only; on a content-on one it sends what you logged, after `Redact`. (Source: `otel.AppLogs` godoc; `TestPipelineSlogHandler`) - **Shut bridged pipelines down in reverse order.** Two `Install(…, otel.Slog())` pipelines wrap each other; out of order, the last shutdown still restores what the first found. (Source: `otel.Slog` godoc) - **Set `Content(false)` on every agent of a delegation.** It governs only the agent it is passed to; a Subagent child without it logs `err` and `cause` text. (Source: `CHANGELOG.md:283`; `core/content.go:32-45`) - **Use `p.SlogHandler` under `NoGlobal`.** `otel.Slog()` and `otel.SlogHandler` follow the installed pipeline, and a `NoGlobal` pipeline is not installed. (Source: `otel.Slog` godoc) ### See also - [Record every run with otel.Install](https://weftgo.dev/docs/observe/recording/) - [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/) - [Observe a run without changing it](https://weftgo.dev/docs/guides/observers/): `weft.Logger`'s lines - [Control what content leaves the process](https://weftgo.dev/docs/production/content-and-privacy/) Symbols used: [`otel.Slog`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Slog) · [`otel.SlogHandler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#SlogHandler) · [`Pipeline.SlogHandler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline.SlogHandler) · [`otel.AppLogs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#AppLogs) · [`otel.ContentLog`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#ContentLog) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.Start`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Start) · [`otel.NoGlobal`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoGlobal) · [`otel.Exporters`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Exporters) · [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger) · [`weft.Content`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Content) · [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`mw.Log`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Log) · [`mw.Audit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Audit) · [`obsdb.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) · [`ExampleSlog`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#example-Slog) · [`ExampleSlogHandler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#example-SlogHandler) · [`ExampleContentLog`](https://github.com/weftgo/weft/blob/v0.20.2/otel/example_test.go#L161) --- # Scope the panel to a conversation URL: https://weftgo.dev/docs/observe/devtools/scope/ Markdown: https://weftgo.dev/docs/observe/devtools/scope.md > Tell the devtools panel which conversation and run to show: name it with data-scope or window.__WEFT__, or let the panel detect it from the page URL, a data-weft-scope marker or the Weft-Scope header your Go handler sets with package weft/scope. The panel follows one [scope](https://weftgo.dev/docs/reference/glossary/#scope): a conversation's [public id](https://weftgo.dev/docs/reference/glossary/#public-id), and optionally the session, flow and run inside it, written `pub_…;session=…;flow=…;run=…`, or a page of unrelated runs named by their agent and their run metadata, `;agent=…;tag.=` ([Tags, agents and flows](https://weftgo.dev/docs/observe/devtools/scope/#name-a-batch-of-runs-by-tags-agent-or-flow)). Name it yourself with `data-scope` on the panel's tag or `window.__WEFT__`, or let the panel detect it: from the page URL, from a `data-weft-scope` attribute on your chat's element, or from the `Weft-Scope` header your chat handler sets with package [`scope`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope). Name it on the tag: ```html ``` Or set it from Go, on the chat handler in `docs-site/examples/devtools/main.go`, so every response names the conversation it belongs to: ```go title="devtools/main.go" mux.Handle("POST /chat", scope.Header(http.HandlerFunc(c.chat), func(r *http.Request) scope.Scope { return scope.Scope{PublicID: publicIDOf(r)} })) ``` [devtools/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/devtools/main.go) The public id is the one the conversation's session was created with, `thread.PublicID(id)`: its runs carry it as `weft.public_id`, and the panel lists them as the conversation's turns. ### The detection ladder The panel takes the first scope it finds, in this order: | Order | Rung | Where the scope comes from | When it is on | |---|---|---|---| | 1st | 1 · explicit | `data-scope`, `window.__WEFT__`, `scope()` / `mount({scope})` | always | | 2nd | 4 · the page URL | `?weft_scope=…`, else `#weft_scope=…` | always | | 3rd | 3 · DOM markers | `data-weft-scope="…"` on an element of the page | by default everywhere, except a page off loopback under a read-scoped panel token | | 4th | 2 · response headers | the `Weft-Scope` header of the page's own `fetch` responses | by default only with the page and Studio on loopback, and no token or a dev token | | 5th | 4b · a panel token's claims | a `weft_pt.` token's `public_id` claim and its `tags`, read as a hint (Studio still enforces the token) | when rungs 1 to 4 name nothing, under a panel token | | — | 5 · the fallback | nothing names a scope: `no conversation detected on this page · how to scope`, over the newest runs | when nothing names one | So a page given only `data-token` with a panel token lists exactly what that token can read: its conversation, or its batch. The rungs are numbered in the order they were added; the order above is how deliberate each one is. Your page's own word comes first, then a link someone followed, then what the page shows passively. `data-detect` switches rungs 2 and 3 ([Detection switches](https://weftgo.dev/docs/observe/devtools/scope/#detection-switches)); nothing turns rungs 1 and 4 off. The panel's footer says in one word which rungs are installed: `detect: headers`, `detect: markers` or `detect: headers+markers`, led by `url` (`detect: url+headers+markers`) while it follows the URL's scope. With neither rung installed it reads `detect: off`, `detect: explicit` (rung 1 names the scope) or `detect: none`. Before it, the footer names the rung that chose the scope followed: `scope: explicit`, `scope: url`, `scope: marker`, `scope: header from /run` (the path of the response that carried it), `scope: switcher` (your pick) or `scope: none`. `scope: none` covers both the fallback and a scope read from a panel token's claims (rung 4b). An explicit or URL public id with no run in Studio reads "Studio has no runs for pub_… yet — check the id (scope: explicit)", or `(scope: url)`: it may be a wrong id. What the panel does with each field of the scope: - **The public id** selects the conversation. - **`run`** pins the selected turn, and its live tail, to that run once; your clicks own the selection after that. A run that is not the conversation's reads `run r_… not in this conversation`. - **`session`** narrows the turn list to that session's runs. Passed to `scope()`, a scope with a session and no public id (`;session=s_…`) is resolved through `GET /api/sessions/{id}/public_id`, which only setup A and the dev token may ask; under a panel token the panel says `session s_…: the session lookup needs the dev token`. While no public id is known, the list is the newest 10 runs, unpaged, and the session narrows within those 10 only ([The turn list](https://weftgo.dev/docs/observe/devtools/reading-runs/#the-turn-list)). Two more lines say when the session could not narrow anything: - `session s_…: these runs carry no session id — not narrowed`: none of the listed turns carries `weft.session.id` (plain `Generate` runs, not thread turns), so the list is shown whole; - `session s_…: Studio did not answer the lookup`: the `public_id` lookup failed for another reason than a 401, 403 or 404, such as a network error or a 5xx. - **`flow`** narrows every read to the runs stamped with it: a flow is run metadata, `weft.flow`, which `scope.Header` stamps on the runs its handler starts ([Flows](https://weftgo.dev/docs/observe/devtools/scope/#narrow-by-a-flow)). It shows as a `flow ` chip in the header and in the switcher's labels, and two scopes that differ only by `flow` count as two conversations there. When more than one conversation is known (an explicit scope, the markers on the page, the scopes headers named), the header shows a switcher. It is a ` ``` The dock opens across the bottom, dark, under any of your elements with a `z-index` above 50. The form stays above it. Once you drag, resize or re-dock it, your placement wins over these attributes on the next load, until `localStorage.removeItem("weft.devtools")`. ![The layout page's complete example: an Order help page with its composer kept above a dark panel docked along the bottom, the panel's accent recoloured blue, showing a turn's Story](https://weftgo.dev/docs/_astro/panel-dock-bottom-dark.light.D6XsBjLF.webp) *This example's page: the dark dock across the bottom with the blue accent, the composer kept above it by --weft-devtools-inset.* ### Best practices & gotchas - **Set the starting layout, then let the user own it.** After the first placement the stored layout wins over `data-position`, `data-open` and `data-mode` on every load; to see your attributes again, clear `localStorage["weft.devtools"]`. (Source: `studio/README.md:1191-1197`; `panel/layout.ts:79-97`) - **`data-mode` and `data-open` are read once.** The element does not observe `data-mode`, and reads `data-open` only on its first connect; a framework that changes either after mount changes nothing. (Source: `panel/element.ts:412-425`, `904-914`) - **Keep fixed elements clear with the variable, not the padding.** `data-push` pads ``, which never moves `position: fixed` or `sticky` content; use `var(--weft-devtools-inset, 0)`. (Source: `studio/README.md:1135`) - **Override tokens on the `weft-devtools` selector.** Your page's CSS cannot reach inside the shadow tree, but a rule on the host element sets its custom properties in both themes. (Source: `studio/README.md:1153-1160`) - **Keyboard shortcuts need focus in the panel.** Only `Alt+W` works from the page; the rest fire inside the panel, so they never clash with your app's keys. (Source: `studio/README.md:1199-1207`; `panel/element.ts:496-499`) ### See also - [Drive the panel from your page (host API and events)](https://weftgo.dev/docs/observe/devtools/host-api/) - [Install the devtools panel](https://weftgo.dev/docs/observe/devtools/install/) - [Read a run in the panel](https://weftgo.dev/docs/observe/devtools/reading-runs/) - [Devtools panel reference](https://weftgo.dev/docs/reference/panel/) - [What is the devtools panel?](https://weftgo.dev/docs/observe/devtools/overview/) --- # Use your own OpenTelemetry SDK URL: https://weftgo.dev/docs/observe/opentelemetry/ Markdown: https://weftgo.dev/docs/observe/opentelemetry.md > Send weft's spans and log records through a TracerProvider and LoggerProvider you already run, with weft.TracerProvider and weft.LoggerProvider or the OTel globals, and read which spans, attributes and records a run produces. weft's core reports every run through the OpenTelemetry API, its one dependency. Register an SDK globally and every agent's spans and log records reach it with no weft option; or pass your providers to one agent with [`weft.TracerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TracerProvider) and [`weft.LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#LoggerProvider). Exporters and backends stay yours; `weft/otel` is one way to configure them, not a requirement. Give an agent an SDK tracer provider and logger provider, in `otelx/main.go`: ```go title="otelx/main.go" spans := tracetest.NewInMemoryExporter() // your exporter: OTLP, stdout, a vendor's tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(spans)) defer func() { _ = tp.Shutdown(ctx) }() records := &recordKinds{} lp := sdklog.NewLoggerProvider(sdklog.WithProcessor(sdklog.NewSimpleProcessor(records))) defer func() { _ = lp.Shutdown(ctx) }() agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(tp), // spans: invoke_agent › chat, execute_tool weft.LoggerProvider(lp), // records: events, deltas, transcript batches ) if _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil { return err } ``` [otelx/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/otelx/main.go) The in-memory exporters stand in for yours: an OTLP exporter, stdout, a vendor's. ### Tracer and logger providers The core's only dependencies are the OTel trace API (`go.opentelemetry.io/otel` v1.46.0, with semconv v1.41.0) and the Logs API (`go.opentelemetry.io/otel/log` v0.22.0); the SDK, exporters and `weft/otel` live outside it. `weft.TracerProvider(tp)` sets the provider the agent's runs report spans to. Without it, runs use the global tracer provider of `go.opentelemetry.io/otel`, a no-op until an SDK registers one. So a program that sets up an SDK globally gets weft's spans with no option, and a test or a program that injects its dependencies passes its own provider instead of touching the global. `weft.LoggerProvider(lp)` does the same for records, through the OTel Logs API (`go.opentelemetry.io/otel/log`): the run's events, deltas, transcript batches and request records. Without it, runs use the Logs API's global provider. [`Agent.LoggerProvider()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.LoggerProvider) returns the provider an agent emits through, for code whose own records must land beside the run's: `weft/thread`'s compaction marker uses it. Two more accessors, since 0.18.0, serve the same code. [`Agent.TracerProvider()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.TracerProvider) returns the tracer provider the runs open their spans on, the option's value or the global resolved at `New`; `weft/thread` opens its summarizer's `chat` spans through it. [`Agent.ContentCapture()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.ContentCapture) returns `(capture, set bool)`: `set` is false when no `weft.Content` option was given (content then follows the logger, as below), and `capture` is the option's value when it was. `weft/thread` asks it, so `Content(false)` keeps its session records' content out as it keeps the runs'. [`ExampleAgent_ContentCapture`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Agent.ContentCapture) reads all three back. **The globals are read once, at `weft.New`.** Before any SDK is set, the OTel API's global is a placeholder that forwards to the first provider ever set, and only that one. An SDK registered after `New` therefore reaches the agent only when it is the process's first global registration. An agent built after a provider was already set keeps that provider for good, whatever is set later. **Content follows the provider's answer.** The core asks the logger's `Enabled` before it puts content into a record, unless the agent says otherwise with [`weft.Content`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Content): `Content(true)` always, `Content(false)` never. The SDK's simple and batch processors answer yes to every record, so a stock `sdklog.LoggerProvider` receives full content: transcript batches, request records, the catalog. `weft/otel`'s destinations answer per destination instead. To keep content out of your provider: ```go title="otelx/main.go" quiet := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(tp), weft.LoggerProvider(lp), weft.Content(false), // no content in this agent's records, whatever the provider answers ) ``` [otelx/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/otelx/main.go) Spans never carry content, whichever provider you use. A stock SDK provider also never receives raw provider bodies: those need `weft/otel`'s provider and [`otel.RawBodies`](https://weftgo.dev/docs/observe/destinations/#record-provider-wire-bodies-development-only). To use `weft/otel`'s pipeline with your own exporters instead, pass them as a destination with `otel.Exporters` ([Your own exporters](https://weftgo.dev/docs/observe/destinations/#your-own-exporters)). `otel.Install` registers its providers globally, so agents built after it need no option. An agent built before it reaches the pipeline only when no SDK was set globally earlier in the process. Beside a global SDK of your own, start the pipeline with `otel.Start(ctx, otel.NoGlobal(), …)`, so it does not replace your SDK as the global, and pass `p.TracerProvider()` and `p.LoggerProvider()` from [`otel.Start`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Start) to the agent. ### Spans Every run reports one span tree, children nested under their parents: ```text invoke_agent support-bot the run (Internal) ├─ chat one model call: a step (Client) │ └─ attempt one try, when the model chain reports attempts (Client) ├─ execute_tool lookup_order one tool call (Internal) │ └─ invoke_agent research a Subagent child run, under its delegating call └─ chat ``` No span carries content: no prompt, message, tool argument or tool result, only ids, names, counts, durations, reasons and error types. Error text does travel: a failed run or model call records its error as the span's exception, with status `Error`. Every span carries `weft.run.id` and the run's [metadata](https://weftgo.dev/docs/guides/metadata/). `weft.version` on the run span and the resource is the framework's release, pinned by a test so it cannot go stale across a release. | Span | Key attributes | |---|---| | `invoke_agent` | `gen_ai.agent.name`, `gen_ai.provider.name`, `gen_ai.request.model`, `weft.version`, `weft.instructions.hash`, `weft.manifest.hash`; for a child `weft.parent.run.id` and `weft.parent.call.id`; at the end the run's `gen_ai.usage.*` totals (subagents included), `weft.run.steps`, `weft.run.events`, `weft.run.messages`, `weft.run.stop_reason`, `weft.run.stopped_by`, `weft.cancel.cause`, `error.type` | | `chat` | `weft.step.index`, `weft.stream`, the model asked; at the end the call's `gen_ai.usage.*`, `gen_ai.response.finish_reasons` (`stop`, `tool_calls`, `max_tokens`), `gen_ai.response.model`, `weft.model.tool_calls`, `weft.ttft_ms`, `error.type` | | `attempt` | `weft.attempt.index` (from 1), `weft.attempt.layer` (`fallback` on `mw.Fallback`'s backup), `weft.attempt.wait_ms`, `weft.attempt.retry_after_ms`, `http.response.status_code`, `error.type` | | `execute_tool` | `gen_ai.tool.name`, `gen_ai.tool.call.id`, `weft.step.index`, `weft.tool.seq`; `weft.tool.result_bytes`, `weft.tool.truncated_bytes`, `weft.tool.timeout_ms`, `weft.tool.queue_ms`, `weft.tool.pending`, `weft.tool.approved`, `weft.tool.denied`, `error.type` | `error.type` on a run span is a closed table of snake_case tokens: `max_steps`, `usage_limit`, `loop_detected`, `model_retries_exceeded`, `model_contract`, `no_output`, `model_error` (a provider failure, the default) and others, plus `context.Canceled` and `context.DeadlineExceeded`. On a tool span it is the `ToolError` code when there is one (`INVALID_INPUT`, `NO_SUCH_TOOL`, `RETRY`, your own), else `timeout`, `panic`, the context error, the error's own `ErrorType()` string when an error in its chain declares one (`weft/mcp`'s `mcp_transport`, for example), or `tool_error`. A cancelled tool call reports `context.Canceled` like its run. [The record contract §3](https://github.com/weftgo/weft/blob/v0.20.2/docs/record-contract.md#3-spans) lists every attribute and when it is set. Spans and slog lines are the loop's own reporting, not an observer: a [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) sees the same events and receives the span-carrying context. [`ExampleTracerProvider`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-TracerProvider) prints a run's span tree. ### Log records Every record is one OTel log record from the logger `github.com/weftgo/weft/core`, with an `EventName`, a JSON body, severity INFO (WARN for an errored `tool_finish`), and the attributes `weft.record` (its kind), `weft.run.id`, `gen_ai.agent.name`, `weft.content` and the run's metadata: | `weft.record` | One per | Position | |---|---|---| | `event` | durable event, `run_start` to `run_finish` | `weft.event.pos` | | `delta` | streamed text, reasoning or argument delta | `weft.delta.pos` | | `messages` | transcript batch (content on only) | `weft.messages.index` | | `request`, `prompt`, `tools` | model-call attempt; distinct system prompt; distinct catalog | their own `.index` | | `raw` | HTTP exchange, `otel.RawBodies` in development only | `weft.raw.index` | | `compaction` | `thread` session compaction, emitted by `weft/thread` | none: keyed on `weft.compaction.hash` | | `heartbeat` | open run every 10 s, emitted by `weft/otel`'s pipeline only, never stored | none | Each positioned kind's positions run from 0 per run. A record carries the trace and span ids of the context it was emitted on: event, delta and transcript records the `invoke_agent` span's, the model-call records the `chat` span's. Join records to spans on weft's ids (`weft.run.id`, `weft.step.index`, `gen_ai.tool.call.id`), not on span ids, which are zero without an SDK. [`ExampleLoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-LoggerProvider) prints a run's record sequence; [the record contract §4](https://github.com/weftgo/weft/blob/v0.20.2/docs/record-contract.md#4-log-records) gives every body. ### GenAI semantic conventions weft writes the OTel GenAI conventions (semconv v1.41.0) beside its own keys, so a GenAI-aware backend renders its traces: | Key | Where | |---|---| | `gen_ai.operation.name` | every span but `attempt`: `invoke_agent`, `chat`, `execute_tool` | | `gen_ai.agent.name` | `invoke_agent`; every record | | `gen_ai.provider.name`, `gen_ai.request.model` | `invoke_agent`, `chat`, `attempt` | | `gen_ai.response.model` | `chat`, `attempt` on success; the `step_finish` record | | `gen_ai.response.finish_reasons` | `chat` | | `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` | `invoke_agent` (run totals), `chat` (the call's) | | `gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.cache_creation.input_tokens`, `gen_ai.usage.reasoning.output_tokens` | the same spans, when non-zero | | `gen_ai.tool.name`, `gen_ai.tool.call.id` | `execute_tool`; `tool_start` and `tool_finish` records | | `gen_ai.conversation.id` | every span and record of a run with a `weft.session.id`, and, under `weft/otel`'s pipeline, its heartbeats | | `error.type` | failed spans | weft never writes the conventions' opt-in content attributes, the input and output messages on spans: content travels in log records under each destination's content policy. weft emits no OpenTelemetry metrics, only spans and log records. It never uses a `MeterProvider`, so the conventions' `gen_ai.client.token.usage` and `gen_ai.client.operation.duration` histograms are not produced, and a metrics pipeline wired to weft receives nothing. Token counts are on the spans instead: the `gen_ai.usage.*` attributes of `invoke_agent` and `chat` in the table above. ### Resource and sampling When `weft/otel` builds the providers, three options shape them: ```go title="otelx/main_test.go" p, err := otel.Start(ctx, otel.NoEnv(), otel.NoGlobal(), otel.Service("support-api"), // service.name; else OTEL_SERVICE_NAME, else the binary's name otel.Resource(sdkresource.NewSchemaless(attribute.String("deployment.environment.name", "staging"))), otel.Sampler(sdktrace.NeverSample()), // spans only: records are never sampled otel.Exporters(spanExp, sdklog.Exporter(multi{logExp, svc})), ) ``` [otelx/main_test.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/otelx/main_test.go) - [`otel.Service(name)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Service) sets `service.name`; without it, `OTEL_SERVICE_NAME`, else the binary's name. Studio shows each run's service and filters traces by it. - [`otel.Resource(r)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Resource) merges `r` over the detected resource. The order, lowest first: the binary's name and `weft.version`, then `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES`, then `Service`, then `Resource`. - [`otel.Sampler(s)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Sampler) sets the trace sampler; the default is `ParentBased(AlwaysOn)`. It applies to spans only: records are log records and are never sampled, so a run sampled out of tracing still has its events and transcript. `TestResourceAndSampling` runs under `NeverSample`, gets no span, and still gets the run's records. With your own SDK, set the resource and sampler on your providers as usual; weft adds nothing to them. ### Convert SDK data [`otel.FromSDKSpans`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#FromSDKSpans) and [`otel.FromSDKRecords`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#FromSDKRecords) turn what an SDK exporter receives into `obsdb`'s model, value for value what Studio's OTLP ingest makes of the same data: ```go title="otelx/main.go" converted := otel.FromSDKSpans(spans.GetSpans().Snapshots()) // obsdb.Span values, as OTLP ingest makes them ``` [otelx/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/otelx/main.go) Use them in an exporter of your own that writes to an `obsdb.DB` (`db.Write(ctx, obsdb.Batch{Spans: …, Records: …})`), or to assert on spans in a test. ### Without an SDK With no provider registered and no option, both providers are the API's no-ops: spans are non-recording, `Enabled` answers no, and nothing is marshalled for a record. A whole two-step run on this path stays under 160 allocations (128 measured), with no goroutine, lock or background flush. `TestWithoutAnSDK` runs the example's agent with no provider and gets the same answer. ### The otel example The weft repository's [`examples/otel`](https://github.com/weftgo/weft/tree/v0.20.2/examples/otel) is its own module with the real SDK. A stdout exporter prints the span tree of a run that delegates to a subagent, and its test asserts the tree through the SDK's in-memory exporter. Its acceptance test checks that every record correlates to the run's trace, event positions are contiguous, and the transcript records rebuild the transcript byte for byte. All of it runs offline. ### Complete example ```go title="otelx/main.go" // Command otelx runs the example of the guide "Use your own // OpenTelemetry SDK": go run ./otelx. The agent reports to an SDK // tracer provider and logger provider the program built itself, with // in-memory exporters; the model is scripted with wefttest, so it runs // offline. package main import ( "context" "fmt" "io" "log" "os" "sort" "strings" "sync" "go.opentelemetry.io/otel/attribute" sdklog "go.opentelemetry.io/otel/sdk/log" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/sdk/trace/tracetest" "github.com/weftgo/weft" "github.com/weftgo/weft/otel" "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"` } 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", 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() { if err := run(context.Background(), os.Stdout); err != nil { log.Fatal(err) } } func run(ctx context.Context, w io.Writer) error { spans := tracetest.NewInMemoryExporter() // your exporter: OTLP, stdout, a vendor's tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(spans)) defer func() { _ = tp.Shutdown(ctx) }() records := &recordKinds{} lp := sdklog.NewLoggerProvider(sdklog.WithProcessor(sdklog.NewSimpleProcessor(records))) defer func() { _ = lp.Shutdown(ctx) }() agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(tp), // spans: invoke_agent › chat, execute_tool weft.LoggerProvider(lp), // records: events, deltas, transcript batches ) if _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil { return err } stubs := spans.GetSpans() sort.Slice(stubs, func(i, j int) bool { return stubs[i].StartTime.Before(stubs[j].StartTime) }) byID := map[string]tracetest.SpanStub{} for _, s := range stubs { byID[s.SpanContext.SpanID().String()] = s } for _, s := range stubs { depth := 0 for p := s.Parent; p.IsValid(); p = byID[p.SpanID().String()].Parent { depth++ } fmt.Fprintf(w, "%s%s%s\n", strings.Repeat(" ", depth), s.Name, keyAttrs(s.Attributes)) } fmt.Fprintln(w, "records:", records.summary()) quiet := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(tp), weft.LoggerProvider(lp), weft.Content(false), // no content in this agent's records, whatever the provider answers ) records.reset() if _, err := quiet.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil { return err } fmt.Fprintln(w, "records with Content(false):", records.summary()) converted := otel.FromSDKSpans(spans.GetSpans().Snapshots()) // obsdb.Span values, as OTLP ingest makes them fmt.Fprintln(w, "converted spans:", len(converted)) // both runs: 4 spans each return nil } // keyAttrs prints the span attributes the page talks about, in a fixed // order, for the spans that carry them. func keyAttrs(kvs []attribute.KeyValue) string { want := []string{"gen_ai.operation.name", "weft.step.index", "gen_ai.tool.name", "gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens", "gen_ai.response.finish_reasons", "weft.run.stopped_by"} have := map[string]string{} for _, kv := range kvs { have[string(kv.Key)] = kv.Value.Emit() } var b strings.Builder for _, k := range want { if v, ok := have[k]; ok { fmt.Fprintf(&b, " %s=%s", strings.TrimPrefix(strings.TrimPrefix(k, "gen_ai."), "weft."), v) } } return b.String() } // recordKinds is a log exporter that counts records by weft.record kind // and weft.content value. type recordKinds struct { mu sync.Mutex n map[string]int } func (r *recordKinds) Export(_ context.Context, recs []sdklog.Record) error { r.mu.Lock() defer r.mu.Unlock() if r.n == nil { r.n = map[string]int{} } for _, rec := range recs { kind, content := "", "" rec.WalkAttributes(func(kv attribute.KeyValue) bool { switch kv.Key { case "weft.record": kind = kv.Value.AsString() case "weft.content": content = kv.Value.AsString() } return true }) r.n[kind+"("+content+")"]++ } return nil } func (r *recordKinds) reset() { r.mu.Lock() defer r.mu.Unlock() r.n = nil } func (r *recordKinds) summary() string { r.mu.Lock() defer r.mu.Unlock() var out []string for k, v := range r.n { out = append(out, fmt.Sprintf("%s %d", k, v)) } sort.Strings(out) return strings.Join(out, ", ") } func (*recordKinds) Shutdown(context.Context) error { return nil } func (*recordKinds) ForceFlush(context.Context) error { return nil } ``` [otelx/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/otelx/main.go) From `docs-site/examples`: ```sh go run ./otelx go test ./otelx ``` ```text invoke_agent support-bot operation.name=invoke_agent usage.input_tokens=20 usage.output_tokens=10 run.stopped_by=final_answer chat script operation.name=chat step.index=0 usage.input_tokens=10 usage.output_tokens=5 response.finish_reasons=["tool_calls"] execute_tool lookup_order operation.name=execute_tool step.index=0 tool.name=lookup_order chat script operation.name=chat step.index=1 usage.input_tokens=10 usage.output_tokens=5 response.finish_reasons=["stop"] records: delta(full) 1, event(full) 8, messages(full) 4, request(full) 2, tools(full) 1 records with Content(false): delta(none) 1, event(none) 8, request(stripped) 2 converted spans: 8 ``` The stock logger provider received full content: four transcript batches, two request records and the catalog. With `weft.Content(false)` the same run sends no transcript or catalog record, its events and deltas marked `none` and its request records stripped. ### Best practices & gotchas - **Decide content before you hand weft a stock provider.** Its processors answer yes to every record, so transcripts and tool results reach your exporter. Use `weft.Content(false)`, or `weft/otel` with a content-off destination. (Source: `weft.Content` godoc; `TestOwnSDK`) - **Join on weft ids, not span ids.** Span ids are zero without an SDK and missing when sampled out; every record carries `weft.run.id`. (Source: record contract §1, §4) - **Sampling never thins records.** A `Sampler` drops spans only; to send fewer records, use `otel.Signals` or `otel.NoDeltas` on a destination. (Source: `otel.Sampler` godoc; `TestResourceAndSampling`) - **Do not wait for weft metrics.** There is no `MeterProvider` option and no `gen_ai.client.*` histogram; read token counts from the spans' `gen_ai.usage.*` attributes. (Source: `weft/docs/adr/0016-observability.md:290-294`) - **Install the pipeline before you build agents, or pass its providers.** An agent binds to the global providers at `weft.New`. One built after your own global SDK, or after an earlier `otel.Install`, keeps reporting there: a later `Install` never reaches it. Once that earlier pipeline is shut down, its runs are recorded nowhere, with no error and no WARN. Call `otel.Install` once, at startup, before `weft.New`; otherwise build the agent with `weft.TracerProvider(p.TracerProvider())` and `weft.LoggerProvider(p.LoggerProvider())`, `p` from `otel.Start(ctx, otel.NoGlobal(), …)` when your own SDK stays the global. (Source: `weft/core/agent.go:698-710`, `weft/otel/pipeline.go:313-314, 842-847`; scratch proof in `sources`) - **Pass providers explicitly in tests.** The globals are process-wide; `weft.TracerProvider` and `weft.LoggerProvider` keep a test's spans its own. (Source: `weft.TracerProvider` godoc) ### See also - [Record every run with otel.Install](https://weftgo.dev/docs/observe/recording/): the pipeline that configures these providers for you - [Send records to Studio, Datadog, Langfuse or any OTLP backend](https://weftgo.dev/docs/observe/destinations/) - [Inspect agents written in other languages](https://weftgo.dev/docs/observe/other-languages/): the same conventions from a non-Go agent - [The record contract](https://github.com/weftgo/weft/blob/v0.20.2/docs/record-contract.md) Symbols used: [`weft.TracerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TracerProvider) · [`weft.LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#LoggerProvider) · [`weft.Content`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Content) · [`Agent.LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.LoggerProvider) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`otel.Service`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Service) · [`otel.Resource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Resource) · [`otel.Sampler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Sampler) · [`otel.FromSDKSpans`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#FromSDKSpans) · [`otel.FromSDKRecords`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#FromSDKRecords) · [`otel.Exporters`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Exporters) · [`otel.Start`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Start) · [`obsdb.Batch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Batch) · [`ExampleTracerProvider`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-TracerProvider) · [`ExampleLoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-LoggerProvider) --- # Run experiments with the option lab URL: https://weftgo.dev/docs/observe/playground/experiments/ Markdown: https://weftgo.dev/docs/observe/playground/experiments.md > Run a matrix of variants (prompt, tools, model, thinking, sampling, tool choice) over inputs from Studio's playground, or over the runs of one failure class, judge each cell with a pass predicate, save it as an experiment you can re-run and compare, and cap its spend with runtime.Limits. An [experiment](https://weftgo.dev/docs/reference/glossary/#experiment) is a matrix of playground runs: each variant is one set of overrides (prompt, tools, model, thinking, sampling, tool choice), each input one source run or text, and each cell one command sent under the experiment's id. Build it on Studio's `/playground` page and press **Run matrix**, or start one from the runs list over the runs of one failure class: the page saves the definition with `POST /api/experiments`, and every cell's run carries `weft.experiment.id`, so the experiment reads back with its runs and their cost. A pass predicate such as `status = succeeded AND cost < 0.01` judges each cell, and the grid names the cheapest variant that passes every row. [`runtime.Limits`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Limits) caps what one experiment may spend in your process. The saved definition is plain JSON. Two variants over one source run, continued from step 1: ```sh curl -s -X POST http://127.0.0.1:8080/studio/api/experiments -d '{ "id": "tracking-link", "name": "tracking link", "agent": "acme-support", "variants": [ {"key": "a", "overrides": {}}, {"key": "b", "overrides": {"instructions": "You are Acme'"'"'s support agent. Always include the tracking link.", "options": {"temperature": 0.2}}} ], "inputs": [{"key": "src", "source_run_id": "dd66354adfaac2b44848f0c1ed75516f"}], "engine": "live", "side_effects": "substitute", "thread": "ephemeral", "from_step": 1, "source_run_id": "dd66354adfaac2b44848f0c1ed75516f" }' ``` ```json {"id":"tracking-link","name":"tracking link","agent":"acme-support","variants":[{"key":"a","overrides":{}},{"key":"b","overrides":{"instructions":"You are Acme's support agent. Always include the tracking link.","options":{"temperature":0.2}}}],"inputs":[{"key":"src","source_run_id":"dd66354adfaac2b44848f0c1ed75516f"}],"engine":"live","side_effects":"substitute","thread":"ephemeral","from_step":1,"source_run_id":"dd66354adfaac2b44848f0c1ed75516f","created":"2026-10-18T10:13:09.477022685Z","updated":"2026-10-18T10:13:09.477022685Z","run_count":2,"succeeded":2,"last_run":"2026-10-18T10:13:07.374947632Z","cost_usd":0,"cost_known":true,"cost_badge":"scripted","cost_reason":"a scripted model: nothing bills it, an exact $0","cache":"exact","runs":null} ``` The two cells had already run with `"experiment_id": "tracking-link"`, so the save finds them: `run_count` 2, `succeeded` 2. ### Experiments On the `/playground` page, each variant is a column: **+ variant** adds one, and a variant can be renamed, duplicated and removed. A variant's name is required, at most 32 characters, with no leading or trailing spaces and no control characters, and unique in the form ("variant B already exists"). The name keys the cells and the experiment's variants. The **Experiment matrix** below the form adds inputs with **+ input**. Its header names the shape and the step: "Experiment matrix · 1 variant × 1 input · over the source run · from step 1". Every cell continues from that one `from_step`, the source block's step picker; past step 0 an input row's text is not sent, and the cell runs with the page's transcript edits instead. Each variant runs on the engine the command can take, chosen as the replay drawer chooses it ([Choose the engine](https://weftgo.dev/docs/observe/playground/replay/#choose-the-engine)): two radios per variant, and Run names the variant and the engine, **Run A on scripted · 0 tokens** or **Run A live on `` · ≈ $x**. An engine you pick rides the URL and the form. Breakpoints are not set per variant: the form points to [Runtimes](https://weftgo.dev/docs/observe/playground/runtimes/#breakpoints), with the count in force. The playground's Run and Run matrix wait for the preview and hold on its refusal and on the [target check](https://weftgo.dev/docs/observe/playground/replay/#the-target-check). **Run matrix** has the page save the definition (`POST /api/experiments`) and issue every cell's command under the experiment's id, so the budget caps the whole matrix. When the last cell settles, one toast says how many succeeded and failed, with the bill when pricing is on. The grid then shows each cell ([The grid](https://weftgo.dev/docs/observe/playground/experiments/#the-grid)). ![Studio's playground over a recorded acme-support turn, on the acme-app runtime: variant A's source run, step, system prompt, tools, model, thinking, engine, side effects and where it writes, with the option fields below them and the experiment matrix beside the variant](https://weftgo.dev/docs/_astro/studio-playground.light.C_3iakPV.webp) *The playground: a variant's settings with the option lab under them, and the experiment matrix beside the variant.* The name field is free text, and the experiment's id follows the command id's rule, `[A-Za-z0-9._:-]{1,128}`. A name that fits is its own id; any other is slugged with a per-page nonce, and an empty one becomes `exp_