---
title: Agent patterns and where they attach in weft
description: 'Workflow and agent patterns, context management, tool design, safety controls, protocols, durable execution and evaluation, each mapped onto weft''s pieces: runs as values, the two seams, PrepareStep, Subagent and Go control flow.'
url: https://weftgo.dev/docs/explanation/patterns/
type: concept
sources:
  - 'weft/docs/agent-loop-deep-dive.md:2264-2848 (Part IV: above the loop; stale and planned passages checked against the code below)'
  - https://www.anthropic.com/engineering/building-effective-agents (workflows vs agents; prompt chaining, routing, parallelization (sectioning, voting), orchestrator-workers, evaluator-optimizer; simplicity, transparency, the agent-computer interface; published 2024-12-19)
  - https://modelcontextprotocol.io/specification/2025-06-18/server/tools (protocol errors vs isError results; listChanged; a human in the loop SHOULD be able to deny tool invocations; annotations untrusted unless from trusted servers)
  - 'https://modelcontextprotocol.io/specification/2025-06-18/schema (ToolAnnotations: readOnlyHint default false, destructiveHint default true, idempotentHint default false, openWorldHint default true)'
  - https://github.com/humanlayer/12-factor-agents (the twelve factors and the bonus thirteenth)
  - https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents (context rot; context engineering)
  - 'https://arxiv.org/abs/2406.12045 (τ-bench: pass^k for reliability over multiple trials)'
  - 'https://arxiv.org/abs/2405.15793 (SWE-agent: interface design affects agent performance)'
  - weft/core/subagent.go:284 (the prompt description); weft/mcp/client.go:72-75 (ToolListChangedHandler), 189-190 (readOnlyHint → Sequential)
  - 'weft/AGENTS.md:477-551 (block 7a: side_effects substitute | park | allow; runtime.AllowSideEffects)'
  - https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/ (private data, untrusted content, external communication; 95% is a failing grade)
  - docs-site/examples/explanation/main.go (regions chain, route, fanout, evaluate), main_test.go TestPatterns
  - weft/core/output.go:45 (Output), 121 (GenerateAs)
  - weft/core/agent.go:176 (PrepareStep), 796 (ToolSource), 125 (UsageLimit)
  - 'weft/core/subagent.go:283-349 (Subagent: fresh transcript, prompt-only input)'
  - weft/core/tool.go:411 (RawTool), 580 (WrapTools), 621 (RequireApproval), 642-752 (Replay, ReplaySafe, ReplayNever default)
  - 'weft/core/loop.go:1662-1675 (composeSystem: Instructions then PromptSnippet), 2213-2222 (result cap marker)'
  - weft/core/mw/tool.go:18-38 (Allow), 53 (Audit), 101-117 (MapErrors)
  - weft/mcp/client.go:26-78, 163-199 (imported tools are RawTools; Sequential unless readOnlyHint; elicitation not answered; listChanged via ToolSource), weft/mcp/server.go:20-40 (AddTools refuses RequireApproval tools), 121-150 (Serve is Subagent over the wire)
  - weft/anthropic/convert.go:168 (only under promptCache), 174-196 (markCache); weft/anthropic/model.go:144 (PromptCache)
  - weft/docs/adr/0021-thread-approvals.md:30
  - weft/thread/compactopts.go:36-43 (ContextWindow); weft/docs/adr/0020-thread-compaction.md:56-66 (trigger on reported usage; cut only at a user or assistant boundary)
  - weft/thread/signing.go (signed decisions), weft/docs/adr/0021-thread-approvals.md
  - 'weft/runtime/doc.go, weft/AGENTS.md:477-551 (playground: never-class calls substituted or parked)'
  - 'weft/README.md:1079-1100 (roadmap: serve and eval/prompt/mem/trace not shipped)'
  - weft/core/wefttest/replay.go:46-62 (Record, Replay)
---

# Agent patterns and where they attach in weft

Agent patterns are built from weft's pieces with ordinary Go. A workflow is runs composed with `if`, `switch`, `for` and goroutines; an agent is one run whose model directs its own tool use; delegation is a tool. Context management attaches at `PrepareStep` and the tool set, safety at the two seams and the approval boundary, durability around the transcript. v0.20.2 has no workflow DSL and no graph engine: composition is the Go you already write.

Routing, for example, is a cheap agent with a typed answer followed by a Go `switch`, in `explanation/main.go`:

```go title="explanation/main.go"
prompt := weft.Prompt("I was charged twice.")
r, _, err := weft.GenerateAs[Route](ctx, router, prompt)
if err != nil {
	return err
}
next := general
switch r.Kind {
case "billing":
	next = billing
}
res, err := next.Generate(ctx, prompt)
if err != nil {
	return err
}
```

[explanation/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/explanation/main.go)

`weft.GenerateAs[Route]` runs the router until it submits a valid `Route`; the `switch` is the routing table, and the next run receives the same prompt.

## Above the loop

[The agent loop, from first principles](https://weftgo.dev/docs/explanation/agent-loop/) answers the questions inside one run. This page covers the layer above it, following Part IV of weft's deep dive: how runs compose into workflows, how the model's context is managed, how tools are designed, how the whole is kept safe, which protocols it speaks, how it survives a restart, and how it is measured. Each section ends with where the idea lands in weft v0.20.2.

### Workflows and agent patterns

Anthropic's "Building effective agents" (December 2024) gives the vocabulary this section uses. **Workflows** are "systems where LLMs and tools are orchestrated through predefined code paths"; **agents** are systems "where LLMs dynamically direct their own processes and tool usage." Five workflow patterns sit between one call and a full agent:

| Pattern | Shape | In weft |
|---|---|---|
| **Prompt chaining** | ordered calls, each on the previous output, with checks between | two `Generate` calls and a Go `if` as the gate |
| **Routing** | classify the input, send it down a specialised path | an agent with `weft.Output[Route]` and a `switch`, or one agent whose `PrepareStep` changes tools and instructions per step |
| **Parallelization** | run work at once: *sectioning* (split it) or *voting* (repeat it and combine) | a goroutine per `Generate`; voting is the same fan-out with a reducer |
| **Orchestrator-workers** | a central model breaks the task down and delegates | `weft.Subagent` plus `weft.Parallelism`: several delegations in one step run together, events nested, usage rolled up |
| **Evaluator-optimizer** | one model generates, another critiques, in a loop | two agents in a `for` loop, the evaluator with `Output[Verdict]`; or one agent with a `review` tool and `StopWhen(HasToolCall("accept"))` |

The same write-up gives three principles: keep the design simple, show the agent's planning, and invest in the agent-computer interface through tool documentation and testing.

**Prompt chaining** needs nothing beyond the transcript being a value you can pass along:

```go title="explanation/main.go"
outline, err := outliner.Generate(ctx, weft.Prompt("A post about the cache bug."))
if err != nil {
	return err
}
if strings.Count(outline.Text(), ".") < 3 { // the gate is code, not a prompt
	return fmt.Errorf("outline too short: %q", outline.Text())
}
post, err := writer.Generate(ctx, weft.Prompt("Outline:\n"+outline.Text()))
if err != nil {
	return err
}
```

[explanation/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/explanation/main.go)

The gate is code, not a prompt: a short outline fails here, before the second call spends tokens.

**Parallelization** is the one place `errgroup`-style semantics are right. The runs are independent, so letting one failure cancel the rest is a policy choice; inside one step it would be the category error that rule 1 refuses. Results land by index:

```go title="explanation/main.go"
out := make([]string, len(sections))
errs := make([]error, len(sections))
var wg sync.WaitGroup
for i, s := range sections {
	wg.Go(func() {
		res, err := reviewer(s).Generate(ctx, weft.Prompt("Review the "+s+" section."))
		if err != nil {
			errs[i] = err
			return
		}
		out[i] = res.Text()
	})
}
wg.Wait()
```

[explanation/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/explanation/main.go)

An `Agent` is immutable and safe to run concurrently; here each section gets its own scripted reviewer so the output is deterministic.

**Evaluator-optimizer** is a `for` loop whose bound is yours:

```go title="explanation/main.go"
brief := "Summarise Q3 in two sentences."
var draft string
for round := 1; round <= 3; round++ { // the bound is yours, in Go
	res, err := generator.Generate(ctx, weft.Prompt(brief+"\n"+draft))
	if err != nil {
		return err
	}
	draft = res.Text()
	v, _, err := weft.GenerateAs[Verdict](ctx, evaluator, weft.Prompt("Brief: "+brief+"\nDraft: "+draft))
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "round %d: accept=%t feedback=%q\n", round, v.Accept, v.Feedback)
	if v.Accept {
		break
	}
	draft = "Previous draft: " + draft + "\nFeedback: " + v.Feedback
}
```

[explanation/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/explanation/main.go)

The evaluator's verdict is typed, so the stop decision is a Go `if v.Accept`, not a string match on the model's prose. Holding the loop in Go keeps each round a separate run with its own id, budget and record.

**Orchestrator-workers** is shown in [Delegate to another agent](https://weftgo.dev/docs/guides/subagents/): the orchestrator's model issues several subagent calls in one step and the loop runs them up to `Parallelism` at once.

Two other framings in the deep dive point the same way. OpenAI's practical guide to agents separates a manager pattern (agents as tools) from a decentralised one (agents handing off to agents) and argues for familiar programming constructs over declarative graphs. The graph camp's reply is that the hard part is giving the model the right context at each step, and that abstractions which hide what reaches the model make that harder. weft agrees with the diagnosis and answers with a loop that hides nothing. Every `ModelRequest` is visible at the model seam, every result in the transcript.

### Reasoning and action patterns from research

The research lineage behind "call the model, run the tools, repeat" (ReAct, Plan-and-Solve, Reflexion, Self-Refine, Tree of Thoughts and LATS, CodeAct, Voyager, SWE-agent) needs no new loop primitive. What each needs from the loop:

| Pattern | Loop requirement | In weft |
|---|---|---|
| Reasoning interleaved with actions | the reasoning stored, the actions executed | `ReasoningPart` stored and forwarded, never read; the loop is the action half |
| Plan first, then act | a planning step before the first tool | a plan tool the model calls and reads back, or a `PrepareStep` that injects the plan |
| Retry with a written reflection | the failed run's transcript as input to the next | `RunError.Result.Messages`; the memory of reflections is your code |
| Branching search over trajectories | a transcript that is a copyable value, ids that tell branches apart | `weft.Messages(res.Messages...)` plus `weft.RunID`; the search policy is your code |
| Code as the action space | one tool whose sandbox is the safety story | a `RawTool` named `execute_code`; the sandbox is deployment |
| A growing skill library | a tool set that changes during the run | `weft.ToolSource` |
| An agent-computer interface designed on purpose | explicit tool contracts | schemas from structs, pinned error text, capped results |

The list a core must get right is short: a bounded loop, tool errors as data, a copyable transcript, a tool set that can change, and somewhere to put a sandbox.

### Context engineering and memory

**The constraint.** The context window is finite, and Anthropic's post on context engineering calls the decline "context rot": "as the number of tokens in the context window increases, the model's ability to accurately recall information" from it decreases. Context engineering is deciding, at every step, which tokens the model sees. In weft terms it is everything that decides `ModelRequest.Messages` and `ModelRequest.System` at step *n*.

**Four verbs** index the techniques:

| Verb | Techniques | In weft |
|---|---|---|
| **Write**: save outside the window | scratchpads, notes, memory files, task lists | a tool the agent calls; nothing in the core |
| **Select**: pull in what is needed | just-in-time retrieval, tool search, skills loaded on demand | `ToolSource` for a changing set, `RawTool` for a search tool, `PrepareStep` for per-step selection |
| **Compress**: keep fewer tokens | compaction, tool-result clearing, trimming | `thread` compaction (`s.Compact`, `thread.ClearOldToolResults`), `MaxResultBytes` as the first cut |
| **Isolate**: split across contexts | subagents with fresh windows, sandboxes holding heavy objects | `Subagent`, whose child starts on a transcript holding only its prompt |

**Compaction, carefully.** `weft/thread` compacts a session (ADR 0020): it triggers on provider-reported usage against `thread.ContextWindow`, cuts only at a user or assistant boundary, never between a call and its result, writes a summary entry, and keeps everything it replaced in the log. Two consequences hold for any compaction. Instructions given in an early user message may not survive it, so rules belong in `weft.Instructions` and `weft.PromptSnippet`, which the loop composes into `System` on every request. And a compaction resets the cache prefix: every token after the cut is a cache write, so its timing is a cost decision as well as a quality one. [Keep long sessions inside the context window](https://weftgo.dev/docs/sessions/compaction/) covers the options.

**Memory architectures.** The literature's shapes start with operating-system-style tiers: a small core memory in the context, searchable recall, external archival storage, moved between by memory tools. Others are a memory stream retrieved by recency, importance and relevance with periodic reflection; the episodic, semantic and procedural split; and structured note-taking in a file the agent re-reads. Each needs the same two things from a loop: memory edits are ordinary tool calls whose effect shows in the next step's system or messages, and the transcript is a value a memory system can read after the run (`RunResult.Messages`). weft provides those and no memory store; a `mem` module is listed on the README's roadmap as not shipped.

**Prompt caching as a design constraint.** Keep tools and system byte-identical across steps; append messages, never rewrite them; put per-request detail after the stable prefix; avoid changing the thinking configuration mid-run; expect a `ToolSource` change or a compaction to rewrite the cache. The loop's contribution is determinism, and, with `anthropic.PromptCache()` (opt-in), the Anthropic adapter sets three `cache_control` breakpoints (the system text, the last tool, the last message block), keeping the fourth free for a compaction summary.

### Tool design: the agent-computer interface

A tool is the model's only sense and only hand; its name, schema, description and result text change agent quality as much as the model does. The rules the field has converged on, and where weft supports each:

- **Consolidate.** Fewer, higher-level tools (`schedule_event`, not `list_users` plus `list_events` plus `create_event`) reduce ambiguity.
- **Namespace.** Prefix by service and resource; `mcp.Prefix("gh_")` does it for imported tools.
- **Return meaning, not plumbing.** Names over opaque ids; a concise mode for large results.
- **Be token-efficient by default.** Pagination, filtering and truncation with sensible defaults; weft's `MaxResultBytes` (64 KiB, with a visible marker) is the same rule at the loop level.
- **Make errors actionable.** `weft.ToolError{Code, Message}` gives a branchable code and an instruction; the loop's own `INVALID_INPUT` names the field for this reason, and `weft.ModelRetry` asks for corrected arguments.
- **Name parameters unambiguously** (`user_id`, not `user`) and describe the tool as to a new colleague; `jsonschema` tags carry the descriptions, `weft.PromptSnippet` carries conventions a schema cannot.
- **Make the mistake impossible.** Require absolute paths rather than documenting relative ones; validate in the handler and return `ModelRetry`.
- **Evaluate tools like prompts.** Run realistic multi-call tasks and measure calls, tokens and tool errors.

**Annotations: what a tool says about itself.** MCP's `ToolAnnotations` carry the properties a loop needs without reading the handler, and the specification calls all of them hints: clients "MUST consider tool annotations to be untrusted unless they come from trusted servers". Each maps to a loop policy:

| MCP annotation (default) | Loop consequence | weft |
|---|---|---|
| `readOnlyHint` (false) | safe to run beside siblings | parallel is weft's default for its own tools, `Sequential()` the opt-out; an imported MCP tool without `readOnlyHint` is made `Sequential` |
| `destructiveHint` (true) | ask before running | `weft.RequireApproval()` |
| `idempotentHint` (false) | safe to re-run after a crash | `weft.Replay(weft.ReplaySafe)`; the default is `ReplayNever` |
| `openWorldHint` (true) | results are untrusted content | a `WrapTools` middleware can tag or strip them |

`mcp.Tools` applies only the first row, a missing `readOnlyHint` making the imported tool `Sequential`; the other rows are options the tool's author sets, and the manifest, `weft.json`, is where a reviewer sees them. MCP's result model (a content list, optional `structuredContent` against an `outputSchema`, `isError`) is richer than weft's one string; `mcp.Tools` returns `structuredContent`'s JSON when the server sends it, else the text items joined.

**The interface is the product.** The SWE-agent paper ("Agent-Computer Interfaces Enable Automated Software Engineering") studies "how interface design affects the performance of language model agents". The loop's job is to make the tool contract explicit (schema from the struct, pinned error text, capped results) so the interface can be designed on purpose.

### Safety and control

**The threat that is not solved.** Prompt injection is unsolved at the model layer. Simon Willison's *lethal trifecta* names the combination that turns it into a breach: access to private data, exposure to untrusted content, and the ability to communicate externally. His verdict on filters that catch 95% of attacks: "in web application security 95% is very much a failing grade." The working strategy is containment: assume an injection lands and make sure it cannot do much.

**The controls, and where each attaches:**

| Control | What it is | In weft |
|---|---|---|
| Least-privilege tool sets | each agent gets only the tools its task needs | the tool list is per agent; `weft.OnlyTools` narrows it per run; a `Subagent` child carries its own |
| Input guardrails | classify the request before the run | your code before `Generate`, or a `PrepareStep` |
| Tool guardrails | check arguments before execution, results after | `WrapTools`: `mw.Allow` for fixed policy, your classifier middleware for judgement, `mw.MapErrors` to strip causes |
| Output validation | check the final answer | `weft.Output[T]` with validation in the submission; a stop condition |
| Approval gates | a person or a policy model decides per call | `weft.RequireApproval`, `weft.ParkOn`, `weft.ParkAllExcept`; a model-as-approver is one middleware |
| Sandboxing | the boundary that contains | outside weft: process, container or VM isolation is deployment |
| Signed decisions | approvals in a client-held transcript can be forged | `weft/thread` keyrings and `s.DecideSigned` ([signed approvals](https://weftgo.dev/docs/sessions/signed-approvals/)) |
| Audit | every call, with its cause, outside the transcript | `mw.Audit`, `weft.Tap`, the `execute_tool` spans |
| Untrusted-content tagging | mark open-world results as data | a middleware that wraps results in delimiters; never in the core |
| Kill switches and budgets | stop the process, cap the spend | `WEFT_MODEL_REQUESTS=deny`, `MaxSteps`, `UsageLimit` |

**Stated plainly.** ADR 0021 puts it in one line: "Approval is a policy and UX seam, not a security boundary". The boundary is the sandbox and the tool set. A loop library's contribution to safety is to make the policy seams obvious (two of them), the audit complete, the budgets real (failures, not warnings), and the transcript the truth, so the containment built above it has something solid to stand on. [Secure an agent in production](https://weftgo.dev/docs/production/security/) applies it.

### Protocols: MCP, A2A, AG-UI, ACP

The protocol stack layers as A2A for agent to agent, MCP for agent to tools and data, AG-UI for agent to user interface, and ACP for editor to agent. At v0.20.2 weft implements MCP only.

**MCP** standardises what a tool is (name, description, input schema, optional output schema, annotations) and its two error channels: protocol errors for unknown tools or invalid arguments, and results with `isError: true` for execution failures. weft maps it both ways:

- [`mcp.Tools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Tools) imports a server's tools as `RawTool`s, schema verbatim. A remote `isError` result and a transport failure are both tool errors the model reads, never run errors. For a server whose list changes, you set the SDK's `ToolListChangedHandler` to re-run `mcp.Tools` into a slice that a `weft.ToolSource` serves; nothing refreshes it on its own. A server that asks for elicitation fails the call, as a tool error: weft does not block a call on a client prompt.
- [`mcp.Serve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Serve) exposes an agent as one MCP tool, `Subagent` over the wire, plus its registered tools. `mcp.AddTools` refuses a `RequireApproval` tool: MCP has no approval channel, and running a gated tool unapproved would bypass the policy.

The specification's instruction that there "SHOULD always be a human in the loop with the ability to deny tool invocations" is weft's approval boundary on the consuming side. [Use MCP tools, and serve an agent over MCP](https://weftgo.dev/docs/guides/mcp/) applies both directions.

**A2A, AG-UI and ACP** are not implemented. An A2A agent maps onto a `Subagent` whose handler speaks HTTP, and an AG-UI stream onto weft's events (`RunStart`/`RunFinish`, `StepStart`/`StepFinish`, `TextDelta`, `ToolArgsDelta` then `ToolStart`/`ToolFinish`), but exposing a weft agent over either is the job of a `serve` module the README lists as not shipped.

### Durable execution: the four models

| Model | How it survives a process death | Constraint on the loop |
|---|---|---|
| Event-sourced checkpoint | persist state after each step; reload and re-execute the interrupted node | nodes must be re-runnable from the top; side effects before an interrupt repeat |
| Workflow snapshot | serialise the run's state when it suspends | snapshot size and format churn |
| Replay by determinism | journal each model call and tool call; re-run the code and substitute journaled results | workflow code must be deterministic; every side effect behind the journal |
| Stateful object | the agent is an addressable object with its own storage | state lives in the object; concurrency is per object |

Three things follow for a loop that wants to sit on more than one of these, and weft provides each:

1. **Every side effect needs an id before it happens.** weft mints the run id before the first event, child ids as `<parent>/<step>/<call>`, and call ids come from the provider.
2. **The model call and the tool call are the activity boundaries**, which are weft's two seams: a journal adapter is a `WrapModel` around the stream and a `WrapTools` around each call. No such adapter ships.
3. **Re-execution safety is a per-tool fact.** `weft.Replay(weft.ReplaySafe)` marks it, as MCP's `idempotentHint` does; the playground (`weft/runtime`) honours it when it re-runs a recorded run, substituting or parking every call not marked safe, unless the experiment uses the `allow` mode, which runs the tools opted in with `runtime.AllowSideEffects` for real.

The transcript-as-state design is what lets weft stay neutral: a run is a function from the agent, the input transcript and the decisions to the result and the events, so any of the four models can hold the input and replay the output. `weft/thread` is weft's own durable layer: an append-only session log, not a checkpoint of a run in flight.

### Evaluation

A loop without a measurement is a demo. What the field measures:

- **Outcome versus trajectory.** End-state evaluation (did the agent reach the correct final state), judged by one model call with a rubric, is the common choice; trajectory evaluation checks each step.
- **Reliability, not only accuracy.** τ-bench proposes pass^k "to evaluate the reliability of agent behavior over multiple trials": success across *k* independent trials of the same task shows the inconsistency a single pass hides.
- **Reference sets** say the harness is not broken; a golden set mined from your own traces says it works for you.
- **Traces as tests.** Record real runs and replay them as regression tests.

In weft the pieces are `wefttest.Script` for deterministic offline runs, `wefttest.Golden` for pinned bytes, and `wefttest.Record` and `wefttest.Replay` for recorded model calls. Add the conformance suite per adapter, the manifest as a drift detector, and Studio's export of a recorded run as a passing replay test ([Turn a Studio run into a test](https://weftgo.dev/docs/testing/studio-runs-as-tests/)). An `eval` module that runs scored suites is on the roadmap, not shipped.

### The twelve factors, mapped

HumanLayer's "12-Factor Agents" is a practitioner checklist for reliable LLM applications. Each factor, and what weft does about it:

| Factor | weft |
|---|---|
| 1. Natural language to tool calls | `ToolCallPart`; schema from the struct |
| 2. Own your prompts | `Instructions` and `PromptSnippet` are the system text; the fixed model-visible texts (`submit_output`'s description, the `Subagent` prompt description, the loop's result strings) are pinned by tests and documented |
| 3. Own your context window | the transcript is a value; `PrepareStep` per step; compaction in `thread`, kept in the log |
| 4. Tools are just structured outputs | `ToolCallPart` is a value; `agt.CallTool` dispatches one yourself |
| 5. Unify execution state and business state | the transcript plus `Pending` is the whole run state |
| 6. Launch/Pause/Resume with simple APIs | a run ends; `Messages(...)` plus `Approve`/`Deny` resumes |
| 7. Contact humans with tool calls | `RequireApproval` parks a call; an `ask_user` tool is the same shape |
| 8. Own your control flow | no DSL; workflows are Go (above) |
| 9. Compact errors into the context window | coded tool errors; `MaxResultBytes` |
| 10. Small, focused agents | agents are cheap values; `Subagent` composes them |
| 11. Trigger from anywhere | `Generate` is a function; `thread` sessions take turns from any caller; an HTTP `serve` layer is not shipped |
| 12. Make your agent a stateless reducer | `execute` is that function; the `Agent` value holds no run state |
| 13. Pre-fetch all the context you might need | `Messages` and `FilePart` on the input; `PrepareStep` for per-step injection |

Most factors map onto a core property (the transcript as a value, tool errors as data, the run boundary) rather than onto an extra feature.

## The illustration in full

The snippets above come from one file, shown whole so each fragment can be read in context. Every model in it is scripted, and its test, `TestPatterns`, checks the four patterns' output; [Examples and recipes](https://weftgo.dev/docs/examples/) has complete programs to run.

```go title="explanation/main.go"
// Command explanation runs the examples of the Explanation page "Agent
// patterns and where they attach in weft": go run ./explanation. Each
// pattern is ordinary Go around weft.Agent values: a chain is two runs and
// an if, a router is a typed answer and a switch, a fan-out is goroutines,
// an evaluator loop is a for. 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"
	"os"
	"strings"
	"sync"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/wefttest"
)

// Route is the router's typed answer.
type Route struct {
	Kind string `json:"kind" jsonschema:"one of billing, shipping, other"`
}

// Verdict is the evaluator's typed answer.
type Verdict struct {
	Accept   bool   `json:"accept" jsonschema:"true when the draft meets the brief"`
	Feedback string `json:"feedback" jsonschema:"what to change when it does not"`
}

// chain: prompt chaining. Two runs in sequence, a Go if as the gate.
func chain(ctx context.Context, w io.Writer) error {
	outliner := weft.New(wefttest.Script(wefttest.Say("1. Problem 2. Fix 3. Result")),
		weft.Instructions("Outline the post in three numbered points."))
	writer := weft.New(wefttest.Script(wefttest.Say("We found the bug, fixed it, and shipped.")),
		weft.Instructions("Write the post from the outline."))
	outline, err := outliner.Generate(ctx, weft.Prompt("A post about the cache bug."))
	if err != nil {
		return err
	}
	if strings.Count(outline.Text(), ".") < 3 { // the gate is code, not a prompt
		return fmt.Errorf("outline too short: %q", outline.Text())
	}
	post, err := writer.Generate(ctx, weft.Prompt("Outline:\n"+outline.Text()))
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "outline:", outline.Text())
	fmt.Fprintln(w, "post:", post.Text())
	return nil
}

// route: routing. A cheap agent returns a typed Route; a switch picks the path.
func route(ctx context.Context, w io.Writer) error {
	router := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{ID: "o1", Name: "submit_output", Args: `{"kind":"billing"}`}),
	), weft.Output[Route](), weft.Instructions("Classify the request."))
	billing := weft.New(wefttest.Script(wefttest.Say("Your refund is on its way.")), weft.Name("billing"))
	general := weft.New(wefttest.Script(wefttest.Say("Thanks, we will reply soon.")), weft.Name("general"))
	prompt := weft.Prompt("I was charged twice.")
	r, _, err := weft.GenerateAs[Route](ctx, router, prompt)
	if err != nil {
		return err
	}
	next := general
	switch r.Kind {
	case "billing":
		next = billing
	}
	res, err := next.Generate(ctx, prompt)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "route: %s → %s: %s\n", r.Kind, next.Name(), res.Text())
	return nil
}

// fanout: parallelization (sectioning). Independent runs on goroutines;
// results land by index, so the output order is the input order.
func fanout(ctx context.Context, w io.Writer) error {
	sections := []string{"intro", "method", "results"}
	reviewer := func(section string) *weft.Agent {
		return weft.New(wefttest.Script(wefttest.Say(section+": ok")),
			weft.Instructions("Review one section."))
	}
	out := make([]string, len(sections))
	errs := make([]error, len(sections))
	var wg sync.WaitGroup
	for i, s := range sections {
		wg.Go(func() {
			res, err := reviewer(s).Generate(ctx, weft.Prompt("Review the "+s+" section."))
			if err != nil {
				errs[i] = err
				return
			}
			out[i] = res.Text()
		})
	}
	wg.Wait()
	for i := range sections {
		if errs[i] != nil {
			return errs[i]
		}
		fmt.Fprintln(w, "review:", out[i])
	}
	return nil
}

// evaluate: evaluator-optimizer. A generator drafts, an evaluator with a
// typed Verdict judges, and a Go for loop decides when to stop.
func evaluate(ctx context.Context, w io.Writer) error {
	generator := weft.New(wefttest.Script(
		wefttest.Say("Draft one."),
		wefttest.Say("Draft two, with the numbers."),
	), weft.Instructions("Write the summary."))
	evaluator := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{ID: "v1", Name: "submit_output", Args: `{"accept":false,"feedback":"add the numbers"}`}),
		wefttest.ToolCalls(wefttest.Call{ID: "v2", Name: "submit_output", Args: `{"accept":true}`}),
	), weft.Output[Verdict](), weft.Instructions("Judge the summary against the brief."))
	brief := "Summarise Q3 in two sentences."
	var draft string
	for round := 1; round <= 3; round++ { // the bound is yours, in Go
		res, err := generator.Generate(ctx, weft.Prompt(brief+"\n"+draft))
		if err != nil {
			return err
		}
		draft = res.Text()
		v, _, err := weft.GenerateAs[Verdict](ctx, evaluator, weft.Prompt("Brief: "+brief+"\nDraft: "+draft))
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "round %d: accept=%t feedback=%q\n", round, v.Accept, v.Feedback)
		if v.Accept {
			break
		}
		draft = "Previous draft: " + draft + "\nFeedback: " + v.Feedback
	}
	fmt.Fprintln(w, "final:", draft)
	return nil
}

func run(ctx context.Context, w io.Writer) error {
	for _, p := range []struct {
		name string
		fn   func(context.Context, io.Writer) error
	}{{"chain", chain}, {"route", route}, {"fanout", fanout}, {"evaluate", evaluate}} {
		fmt.Fprintln(w, "==", p.name)
		if err := p.fn(ctx, w); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	if err := run(context.Background(), os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

[explanation/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/explanation/main.go)

## What this means in practice

- **Keep the loop's bound in Go when you write the loop.** An evaluator loop in Go has a `for` limit; one inside the model (a `review` tool and `StopWhen`) is bounded by `MaxSteps`, which fails the run when hit. (Source: `weft/core/loop.go:861-871`, rule 13)
- **Put rules in `Instructions`, not the first user message.** Compaction may summarise early messages; `System` is recomposed from the instructions on every request. (Source: `weft/core/loop.go:1662-1675`, ADR 0020)
- **Treat MCP annotations as hints.** `mcp.Tools` makes a tool without `readOnlyHint` sequential; it does not grant parallelism or skip approval on a server's word. (Source: `weft/mcp/client.go:54-58, 182-191`)

## See also

- [Delegate to another agent (subagents)](https://weftgo.dev/docs/guides/subagents/)
- [Rewrite each step's request with PrepareStep](https://weftgo.dev/docs/guides/prepare-step/)
- [Get structured output](https://weftgo.dev/docs/guides/structured-output/)
- [The agent loop, from first principles](https://weftgo.dev/docs/explanation/agent-loop/)
- [Examples and recipes](https://weftgo.dev/docs/examples/)

Symbols used: [`weft.GenerateAs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#GenerateAs) · [`weft.Output`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Output) · [`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) · [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) · [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) · [`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.ModelRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRetry) · [`weft.OnlyTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnlyTools) · [`weft.ParkOn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkOn) · [`mcp.Tools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Tools) · [`mcp.Serve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mcp#Serve) · [`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) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
