Skip to content

The agent loop, from first principles

View as Markdown

An agent loop calls a model, runs the tools it asks for, appends the results, and calls it again until it stops asking. That loop is about forty lines in any language. What a framework adds is the answers to the questions those forty lines get wrong. When does the run end, what is a tool failure, what runs at once, and what does the caller see? Where does behaviour attach, how does a person approve a call, and how does one agent use another? What bounds the cost, and what survives a restart? This page builds the loop from nothing, follows one run through weft v0.20.2 function by function, and then takes the questions one at a time.

It restates weft’s own long-form study, docs/agent-loop-deep-dive.md, against the v0.20.2 code; where that document describes a plan, this page says what shipped. The comparison with other frameworks is on How weft compares to other agent frameworks.

Strip any framework down and this remains. A model is a function from a transcript to a reply; a reply either answers or asks for tools.

  1. Call the model with the transcript. A model failure is a run failure.
  2. Append the assistant message to the transcript.
  3. If it asked for no tools, return: the run is done.
  4. Run every requested tool. A tool failure becomes text the model reads.
  5. Append the results as one tool message, and go to 1.
  6. After a fixed number of rounds, return an error: the safety budget.

Every line a framework adds on top of this has to answer a question this version gets wrong. Read in that light, weft’s design principles are the answers, and the rest of this page is the reasoning.

Frameworks use these words differently. weft’s meanings, used on every page of these docs:

WordMeaning in weft
RunOne call to Generate or Stream: an id, an input transcript, a sequence of steps, then a result or a *RunError
StepOne model call plus the execution of the tool calls it requested; StepRecord records it
TurnOne message in the transcript; a step produces one assistant turn and, if tools ran, one tool turn. In weft/thread a turn is one Send, which may be several runs
Transcript[]Message with roles user, assistant, tool; no system role, because instructions belong to the agent
Tool call / resultToolCallPart{ID, Name, Args} on an assistant message; ToolResultPart{CallID, Name, Content, IsError} on the tool message after it
Stop reasonWhy the model turn ended (stop, tool_calls, max_tokens); recorded, never hidden
Stop conditionThe intended end of a run (StopWhen); a success
BudgetA safety limit (MaxSteps, UsageLimit, MaxModelRetries, DetectLoops); a breach is a failure
EventA progress notification on the stream: RunStart, StepStart, TextDelta, ToolStart, ToolFinish, StepFinish, RunFinish and the rest
SeamWhere behaviour attaches: around the model call and around the tool call; there are two
TapWhere observation attaches: sees every event, changes nothing
Reasoning blockOne provider thinking block; a delta carrying its signature closes it, and it is stored as one ReasoningPart the core never reads
File partFilePart{MediaType, Data or URL} on a user message; the core never reads the bytes

Other frameworks say “superstep” (LangGraph), “iteration”, or “request” for what weft calls a step. Map to this table first when you read their docs.

Run the forty lines in production and these questions arrive, roughly in this order. Each has a section below.

#QuestionThe failure that forces it
1When does the run end, and is ending a success?A runaway loop that returns a plausible transcript
2What is a tool failure?One tool error aborts the whole run, or is swallowed
3What runs at once, and in what order?Four tools race, results come back shuffled, a hung tool hangs the run
4Is the transcript always valid input?A crash mid-tool leaves a dangling call the provider rejects on every later turn
5What does the caller see while it runs?A UI that cannot render interleaved progress; a recording that cannot be replayed
6Where does cross-cutting behaviour attach?Fifteen lifecycle hooks, each a contract
7How does a person say yes or no?The process blocks on a prompt; the decision cannot arrive over HTTP an hour later
8How does one agent use another?Graph DSLs, handoff primitives, opaque children
9How much may a run cost?Steps multiply across nesting; the same call repeats until the bill arrives
10What survives a restart?A deploy kills a run mid-tool
11What can never change?An upgrade that changes what the model reads, or breaks code that compiled yesterday

The concrete loop is Agent.execute in core/loop.go. Compressed to its control flow:

The agent loop: the model calls tools, their results go back to the model, and the run ends at RunFinish.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.
Generate / Stream
│ repair(input transcript) §4
│ emit RunStart{ID, Model, Agent} §5
│ refuse a raised MaxSteps/Parallelism, an unknown OnlyTools name
│ resolve pending approvals, if decisions were given §7
▼
for step < MaxSteps: §1
│ fetch the step's tool snapshot; emit StepStart
│ build ModelRequest: system, transcript, tools, thinking, tool choice, params
│ run the PrepareStep chain; validate; compose system + snippets
▼
model middleware chain → adapter → provider §6
│ contract enforced: one ModelFinish, nothing after it, panics → run error
▼
append the assistant message (reasoning, text, calls); never an empty one §4
├─ finish == max_tokens and calls > 0 → every call fails without executing §2
└─ calls > 0 → execTools (slot in call order → ToolStart → chain → ToolFinish) §3
│ append the tool message; record StepRecord; add usage; emit StepFinish
├─ pending > 0 → RunFinish{Pending}, success §7
├─ StopWhen met → RunFinish, success §1
├─ steering drain after the batch; at a would-be final step a delivery §5
│ redirects the run into one more step
├─ no calls, no steer → RunFinish, success
└─ guard: MaxModelRetries, UsageLimit, DetectLoops → *RunError §9
after the loop: ctx done? → that error; else ErrMaxSteps §1

Two things to notice. There are exactly two kinds of exit: a successful RunFinish (no more tool calls, a stop condition, or calls awaiting approval) and a *RunError carrying the partial transcript (model failure, cancellation, a budget, a misconfigured run). And nothing in the loop retries a model call, turns a tool error into a run error, or cancels sibling tools; the sections below explain why.

The loop builds one weft.ModelRequest per step:

  • System: the instructions (the run’s Instructions override, else the agent’s), then, after the PrepareStep chain, one paragraph per advertised tool’s PromptSnippet, blank-line separated, in registration order (composeSystem).
  • Messages: the transcript so far, a copy the adapter cannot write back into.
  • Tools: the step’s snapshot. With ToolSource the list is fetched fresh each step, and dispatch resolves against the same fetch, so what the model was shown is what runs.
  • Thinking, ToolChoice, Params: each the run option if one was given, else the agent’s default.
  • SequentialTools: true when the run’s parallelism is 1, so the provider is asked not to emit batches that would run one at a time anyway.

Model is one method, Stream(ctx, req) iter.Seq2[ModelEvent, error], and the loop enforces its contract instead of trusting it. A stream that ends without ModelFinish, continues after it, yields a call with an empty id or name or a repeated id within the step, yields an unknown event type, or panics fails the run wrapping ErrModelContract. Nothing from the failed turn is appended.

Two rules live below the core, in the adapters, because they read the wire:

  • The idle timeout. Each first-party adapter’s IdleTimeout (60 s by default; IdleTimeout(0) disables it) bounds the gap between chunks, not the whole call. Expiry is ErrStreamIdle: a silent stream is stopped, a slow one that keeps streaming is not.
  • The kill switch. WEFT_MODEL_REQUESTS=deny makes every first-party adapter refuse its self-built client’s call with ErrModelRequestsDenied before any network I/O, read on every call. Test agents offline relies on it.

Every function a run passes through at v0.20.2, in order:

  1. Options become a runConfig. Each RunOption applies in the order given: Prompt and Messages append to the input, RunID sets the id, Approve, Deny and Resolve record decisions by call id, and the dual options (Instructions, MaxSteps, Parallelism, Thinking, ToolChoice, Params) set run overrides. If no id was given, one is minted from 16 random bytes as 32 hex characters, so the id exists before anything runs. Generate calls execute with a sink that discards events. Stream returns a lazy *Run: nothing executes until Events() is ranged or Wait() is called, so run.ID() can be handed to a client first.
  2. The producer goroutine. Run.Events() marks the run started (a second call yields only ErrRunConsumed), opens an unbuffered channel and runs execute on a new goroutine. Its sink selects between sending and the run’s ctx being done, so a consumer that has gone never blocks the producer. Breaking out of the range cancels the run. A failed run’s error is yielded once, as the last element.
  3. execute sets up the run. It extends the ancestry chain (the subagent cycle guard), merges weft.Metadata with what the ctx carries, rebuilds the WrapModel chain over a UseModel alternate, and starts the invoke_agent span. It builds the deliver wrapper every event passes through: it drops the event if ctx is done, runs every Tap in registration order, records the event, then hands it to the sink. Then Repair produces the starting transcript, RunStart{ID, Model, Agent} is emitted, and the input is recorded.
  4. Refusals before any model call. A Resolve aimed at a call that is not pending fails the run at step 0. A run option that raises MaxSteps or Parallelism above the agent’s, or an OnlyTools name the agent does not have, fails with ErrInvalidRunOption. ParkSource functions are read once, and their names join the run’s ParkOn set.
  5. The resume branch. If decisions were given and the last assistant message has calls without results, resolvePending runs them (below) and attachResults completes the tool message. If calls park again, the run ends here with zero steps.
  6. The step header. A ctx check (cancellation between steps fails the run at that step), the step’s tool snapshot, StepStart{Index}, and the request. The PrepareStep chain may rewrite the request; its messages and tools are deep copies, so nothing it writes reaches the run’s transcript or the agent’s tools. The rewritten tools are validated (no duplicate or nil tool), then ToolChoice and Params.
  7. consume: the model turn under contract. The stream runs inside a chat span. Text deltas become TextDelta events and the step’s text; reasoning deltas become ReasoningDelta and accumulate into the open block, which a signature closes; tool calls are validated and collected; argument fragments become ToolArgsDelta progress; ModelFinish is recorded. Any violation returns an error, and execute fails the run at this step.
  8. The assistant message. One ReasoningPart per block with text or a signature, one TextPart if text arrived, then each ToolCallPart, in that order. A message with no content is not appended.
  9. The tool decision. No calls: nothing to run. A max_tokens finish with calls: every call gets the “was not executed” result. Otherwise execTools runs them.
  10. execTools: dispatch in call order. A semaphore of capacity Parallelism bounds the fan-out. For each call, in order: a Sequential tool first waits for every call in flight. A canceled run gets run canceled before the tool started and no events. Otherwise the slot is acquired on the dispatching goroutine and ToolStart is emitted there, which is what makes start order equal call order. A goroutine runs callTool and, unless the call parked, emits ToolFinish. Results are assembled by index.
  11. callTool: policy and containment. The effective policy is computed: for the result cap and the timeout the tool’s own setting wins (a per-tool Timeout(0) or MaxResultBytes(0) lifts the agent’s). Strictness is on when either the agent or the tool sets StrictInput. The chain runs inside the containment boundary: a recovered panic becomes tool "X" panicked: …, an expired deadline tool "X" timed out after 5s with the handler goroutine abandoned. An error wrapping ErrApprovalRequired parks the call; any other error becomes IsError: true; the result is capped.
  12. chain: the call from the outside in. The agent’s WrapTools (first listed outermost) wraps the tool’s own WrapTools, which wraps the base. The base returns NO_SUCH_TOOL for an unknown name (the chain still ran, so mw.Allow and mw.Audit saw it), parks a RequireApproval or ParkOn call that is not approved, decodes the arguments (INVALID_INPUT naming the field on failure), runs the handler and renders the output.
  13. Close the step. One tool message with every result in call order is appended, the StepRecord added, usage summed (subagent usage rolled in), and StepFinish emitted.
  14. The exits, in this order. Pending calls end the run with RunFinish{Pending}. A StopWhen condition ends it. Then the steering source, if any, is drained, after every step that reaches this point: delivered messages join the transcript, and at what would be the final step they redirect the run into one more step. A step with no calls and no delivery ends the run. Otherwise the guard checks MaxModelRetries, UsageLimit and DetectLoops, and the next step begins.
  15. After the loop. If ctx is done, the run fails with the ctx error at the last step: the cause wins over the budget. Otherwise it fails with ErrMaxSteps, the final step’s tool results on the error.
ExitGenerate returnsMessages ends withLast event
Model stopped asking for tools(res, nil)the final assistant messageRunFinish
StopWhen fired(res, nil)the step’s tool messageRunFinish
Calls awaiting approval(res, nil), res.Pending seta tool message missing the parked calls, or none if every call parkedRunFinish with Pending
Model stream error or contract violation(nil, *RunError), Result setthe previous step’s tool messagethe last delta before the failure, then the error
Misconfigured run (ErrInvalidRunOption, a bad Resolve, an invalid ToolChoice, an invalid steer)(nil, *RunError), Result setthe input, or the step where it was foundRunStart (or that step’s StepStart), then the error
Cancellation(nil, *RunError) matching context.Canceled, Pending set if calls were parkedwhatever was appended before the checknothing after cancellation; then the error
Budget (ErrMaxSteps, ErrUsageLimit, ErrModelRetriesExceeded, ErrLoopDetected)(nil, *RunError), Result setthe last allowed step’s tool messageStepFinish

Two invariants fall out. RunError.Result.Messages is always valid provider input, because no half-appended turn exists. Every successful run’s last event is RunFinish, so a consumer can treat “saw RunFinish” as “result available”.

WhoRunsEmits
The consumerranges Run.Events()nothing
The loop goroutineexecute, consume, execTools’ dispatch, resolvePending, the steering drainRunStart, StepStart, deltas, ToolStart, Steered, StepFinish, RunFinish
One goroutine per tool callcallTool and the chain; a subagent’s child runToolFinish, Nested
One goroutine per timed-out handlerthe abandoned handler, until it notices ctxnothing that is delivered

Three synchronisation points carry the ordering: the step’s event lock orders tool and nested events; the semaphore bounds fan-out; the run’s mutex guards the started flag and the stored result. Taps run on the emitting goroutine, so a tap that sees a ToolFinish runs on that tool’s goroutine under the event lock; a slow tap delays the step’s other tools. Generate has no consumer goroutine: execute runs on the caller’s.

resolvePending takes the unresolved calls of the last assistant message and the run’s decisions. Approved calls go through execTools with Call.Approved set, so the base of the chain lets a RequireApproval tool run; middleware can still park one again. A Resolve or ResolveError call never runs: the given content is its result, capped like any result. A denied call gets DENIED: <reason>, an undecided one DENIED: no decision. Results are reassembled in the original call order, so the tool message reads as if the step had run normally. Resumed calls have no StepRecord; their child runs take the id <parent>/resume/<call>. weft.ResumeOf links the resume to the parked run in the record, which the core cannot infer.

Between steps of one run, the request changes in one place by default: Messages grows by an assistant turn and a tool turn. System is fixed by the instructions and the advertised tools, Tools is the static list, and Thinking, ToolChoice and SequentialTools are fixed for the run. That stability has a price tag: provider prompt caches key on a byte-identical prefix of tools, system and messages. With anthropic.PromptCache(), an opt-in option, the Anthropic adapter marks three cache breakpoints for that reason (the system text, the last tool, the last message block). Four things can break the prefix on purpose: a ToolSource that returns a different set, a PrepareStep that rewrites the request, a steering delivery, and a thread session’s compaction. The loop itself never reorders what it sends.

Each question below follows one shape: the problem, what weft does at v0.20.2, the edge cases, and the tests that pin the rule. The deep dive also surveys how other frameworks answer each one; How weft compares carries the parts of that survey that could be checked against those frameworks’ own documentation.

1. Stopping: the intended end versus the safety budget

Section titled “1. Stopping: the intended end versus the safety budget”

The problem. The forty-line loop ends when the model stops asking for tools or when a counter runs out. The first is the normal end; the second is a bug (the model is looping) or a long task. If both read as success, a runaway returns a plausible transcript and nobody notices until the bill. If both read as failure, a twelve-step task fails for no reason. The options in the field are one integer, composable predicates, a request budget, or no default at all.

What weft does. Two concepts with two names, and the budget is a failure:

  • weft.StopWhen is the intended end. A StopCondition has one method, Stop(steps []StepRecord) bool; weft.StopFunc adapts a function; the built-ins weft.HasToolCall and weft.StepCountIs implement fmt.Stringer, so the manifest and RunFinish.StoppedBy name them (has_tool_call:submit). Conditions are checked after each step, before the steering drain, and a fired condition ends the run successfully.
  • weft.MaxSteps is the safety budget, 10 by default. When the model still wants tools after the last allowed step, the run fails with ErrMaxSteps and the full transcript, including the last step’s tool results, on RunError.Result. Per run it may only be lowered.

Cancellation during the last step’s tools is reported as cancellation, not exhaustion: the cause wins over the budget.

Structured output is the intended end as a tool call. weft.Output[T] registers a submit_output tool whose input schema is reflected from T, and a stop condition, output_submitted, that fires only on a non-error submit_output result. An invalid submission is an ordinary INVALID_INPUT tool error, so the repair loop is the loop. A tool works on every provider without an adapter flag, conformance failures come back as errors the model can correct, and the answer lands in the transcript where replay and audit already look. weft.GenerateAs[T] returns the decoded value, weft.OutputOf[T] reads it from a streamed run’s result, and a run that never submits gives ErrNoOutput. Get structured output applies it.

Edge cases.

  • max_tokens on a text-only reply is not an error: RunResult.StopReason is max_tokens and the run succeeds; the caller decides what truncated text means.
  • A stop condition sees the whole StepRecord, calls and results: HasToolCall reads the calls, so it fires on the step that issued the call, and a custom condition can wait for a result. A stop keyed on an approval-gated tool does not fire: the issuing step parks before StopWhen is checked, and the resumed call adds no StepRecord.
  • A run that resolves approvals and parks again ends with zero steps.

Tests that pin it: TestMaxStepsExceeded, TestStopWhenStepCountIsSucceedsWhereMaxStepsFails, TestCancellationBeatsMaxSteps.

2. Tool failure: data the model sees, or an error the caller sees

Section titled “2. Tool failure: data the model sees, or an error the caller sees”

The problem. Four tools run and one fails. errgroup semantics, where the first error cancels everything, are wrong for an agent loop: the model asked for four things, three succeeded, and it can recover from the fourth if it is told what went wrong. Turning the error into a run failure throws away the whole run.

The rule. A tool error is data the model sees. A run error is a Go error the caller sees.

What weft does. A handler error, a panic, an unknown tool, undecodable arguments and a timeout all become ToolResultPart{IsError: true} with the error’s text as content, and siblings keep running. The funnel is callTool: it runs the chain inside the containment boundary and folds every failure into the result.

Structured errors give the model a code to branch on and keep the cause out of the transcript. A handler returns &weft.ToolError{Code: "ORDER_NOT_FOUND", Message: "order 42 does not exist", Err: err}; the model reads ORDER_NOT_FOUND: order 42 does not exist, and Err stays reachable for middleware and logs through errors.As. The loop’s own failures use the same form:

Result textWhen
INVALID_INPUT: tool "x": field "days": expected integer, got stringarguments do not decode into the tool’s input
NO_SUCH_TOOL: no tool named "x"the model called a name the step did not advertise
DENIED: <reason>a person or mw.Allow refused the call
RETRY: <hint>the handler returned weft.ModelRetry(hint)
tool call X was not executed: the response hit the output token limita max_tokens step with calls (rule 11)

These strings are contract (rule 5). mw.MapErrors(nil) codes every plain error as INTERNAL: tool "x" failed, so a production transcript leaks no internals.

Truncated calls. A max_tokens finish that contains tool calls executes none of them. An intact-looking call may be the first of several the model never finished issuing, so each gets the “was not executed” result and the model retries with a full budget.

Asking the model to fix its arguments. weft.ModelRetry returns a *ToolError with code RETRY. The loop counts consecutive RETRY results per tool name; a success resets the count; past weft.MaxModelRetries (3 by default) the run fails with ErrModelRetriesExceeded at the next continuation point. A model that cannot correct itself is a run failure, not an endless loop.

Decoding. The base of the chain decodes Args into the tool’s input struct. The schema is derived once at construction: json tags name properties, jsonschema tags describe them, a pointer or omitempty marks a field optional. Decoding is lenient by default; weft.StrictInput rejects undeclared fields. Two escape hatches sit beside the struct path: weft.RawTool takes an explicit schema and raw JSON (the shape mcp.Tools uses for imported tools), and weft.ToolSource supplies the advertised set per step.

agt.CallTool is the manual form of the same chain for dispatchers outside the loop, and its differences are deliberate: no containment, no cap, no timeout, RequireApproval surfaces as ErrApprovalRequired, an unknown name returns an error wrapping ErrNoSuchTool, and outside a run nothing is recorded.

Edge cases.

  • A panic inside middleware is still a tool error: containment sits outside the chain.
  • A handler that honours its deadline and returns context.DeadlineExceeded gets the same named timeout text, unless the run’s own ctx expired, in which case the run is failing anyway.
  • An enormous result is cut at 64 KiB on a rune boundary with …[truncated N bytes], N the bytes the model did not receive.
  • To the model a refusal is a refusal, whoever refused: DENIED: tool "x" is not allowed from mw.Allow, DENIED: <reason> from a person.

Tests that pin it: TestToolErrorIsDataTheModelSees, TestPanickingToolIsContained, TestWrapToolsDenialAndPanicAreToolErrors, TestMaxTokensWithToolCallsFailsThemWithoutExecuting, TestDecodeErrorsNameTheField, TestModelRetryCountsPerTool, TestToolTimeout.

3. Concurrency: what runs at once, in what order, and who cancels whom

Section titled “3. Concurrency: what runs at once, in what order, and who cancels whom”

The problem. The model asks for four tools in one step. Running them one at a time is slow but safe for shared state; running them at once interleaves results, events and failures. Then a tool hangs, and then the caller cancels. Most confusion comes from conflating three orders: when each tool starts, where its result lands, and when the caller observes it. They can be decided separately, and weft does.

Three tool calls from one step run at once; their results join one tool message in call order.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.

What weft does. Start order is call order, result order is call order, event order is Seq order, always:

  • The slot is acquired on the dispatching goroutine, in call order, before the call’s goroutine is spawned, and ToolStart is emitted there. ADR 0004 records the bug this fixed: a goroutine-per-call race for the semaphore neither started tools in call order nor made Sequential() mean one at a time.
  • Results are collected by index and land on the tool message in call order, whatever order the calls finished in.
  • Seq is assigned and the event emitted under one lock, so two goroutines cannot take 5 and 6 and deliver 6 first.

weft.Parallelism(n) sets the bound, 4 by default; weft.Sequential() on the agent runs calls one at a time; weft.Sequential() on a tool makes it a barrier that waits for in-flight calls, runs alone, then lets the batch continue. Under a parallelism of 1 the loop also sets SequentialTools; the OpenAI and Anthropic adapters forward it to the provider, while Gemini has no such switch and the single slot serialises the calls.

Cancellation rules:

  • No tool starts after the run’s ctx is canceled; a call that never got a slot gets run canceled before the tool started and no events, so every ToolFinish follows its ToolStart.
  • A failing tool never cancels its siblings. Only ctx does.
  • No event is delivered after cancellation, to taps or sinks. The partial transcript on RunError.Result is the record.
  • Cancellation wins over ErrMaxSteps. A cause passed through context.WithCancelCause, such as weft.CancelCause, is named on the run’s span.

Timeouts are per tool call. A run’s deadline is its ctx, as in every Go library; weft.Timeout(d) on a tool or as the agent default bounds a call, because a call is smaller than a run. A hung handler’s goroutine is abandoned, so handlers must honour ctx.

Edge cases.

  • A barrier in the middle of a batch: calls 1 and 2 run together, call 3 waits for both and runs alone, calls 4 and 5 run together after it; results land in order 1 to 5.
  • An approval-gated tool does not make its siblings wait. It parks at once, the siblings in the same step run, and the run ends after the step. If siblings must wait for the decision, park them too (weft.ParkOn, or middleware returning ErrApprovalRequired) or deny them in middleware.
  • An abandoned handler that keeps writing writes into a result already recorded; the loop never reads it again. Handlers that share state must check ctx before side effects.

Tests that pin it: TestStreamEventOrdering, TestToolStartsInCallOrder, TestSequentialToolIsABarrier, TestToolTimeout, and -race on every test run. What happens in one step? shows the orders in a run.

4. Transcript integrity: always valid input

Section titled “4. Transcript integrity: always valid input”

The problem. A process dies between the assistant message that requested a tool and the tool message that answers it. The stored transcript has a dangling call, and every later request fails provider validation. Related: an empty assistant turn some providers reject, a tool message that lost its assistant message, two tool messages in a row.

What weft does. weft.Repair, applied to the input of every run, pure and idempotent (ADR 0001):

  • A tool message is matched against the assistant message immediately before it; only the first tool message after that assistant is kept.
  • A result survives only if its CallID names an unserved call of that assistant; the first result per id wins.
  • A call still missing a result gets a synthesised, visible error result: no result recorded: the call was interrupted.
  • Drops carry no marker; synthesis does.

Two loop rules complete it: an assistant turn with no reasoning, no text and no calls is never appended, and a step’s results go on one tool message (adapters fan out for providers that want one message per result). Approval is the one exception: when a run carries decisions, the unresolved calls of the last assistant message are exempt from repair because this run resolves them itself.

Edge cases.

  • A signed reasoning block with no text is content and is kept, before the text, in production order.
  • A transcript fed back without decisions has its pending calls repaired as interrupted, not denied. The model sees “no result recorded”, which is the truth.
  • Compaction, replacing older history with a summary, is not in the core. weft/thread does it (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, and keeps the compacted entries in the log. Keep long sessions inside the context window covers it.

Tests that pin it: TestRepairSynthesisesMissingResults, TestEmptyAssistantTurnIsNotRecorded, TestSignedEmptyReasoningIsKept, TestApprovalWithoutDecisionsIsRepairedAsInterrupted, and FuzzRepair.

5. Streaming and event ordering: replayable progress

Section titled “5. Streaming and event ordering: replayable progress”

The problem. A UI wants to render progress while four tools run; a recorder wants to store the stream and replay it identically; a tracing backend wants spans. All three need a total order on events that matches what was observed, with enough identity to pair a start with its finish.

What weft does. Run.Events() is an iter.Seq2[Event, error]: events in emission order, the error at most once as the final element, RunFinish the last event of a successful run. Breaking out of the range cancels the run; Wait() runs the agent itself if nobody consumed the events.

Tool events carry a per-run Seq assigned and emitted under one lock (ADR 0004), and so do the two other events that can interleave with them: Nested (a subagent’s event) and Steered (a steering delivery). Step-scoped events (RunStart, StepStart, the deltas, StepFinish, RunFinish) come from the single loop goroutine and need no Seq. Consumers pair tool events by CallID.

Every event marshals with a type discriminator (tool_start, run_finish, …), and weft.UnmarshalEvent restores it; an unknown type is an error, never a drop, because a recorded stream must replay exactly. The event set is sealed, so a type switch over it stays checkable and new types are additive.

Observation without a stream: weft.Tap sees every event of every run, Generate included, synchronously, in the same order as Events(). A panicking tap is recovered and counted. Taps see; seams change (question 6).

Steering. A run can take input while it runs (ADR 0019). weft.Steering is a pull source the loop drains at two fixed points: after a step’s tool batch, when every call has its result, and at what would be the final step, where a delivery redirects the run into one more step. It is never drained at the approval boundary or after StopWhen: those ends stay ends. Delivered messages are ordinary transcript, appended before the next step’s PrepareStep; a non-user role fails the run with ErrInvalidSteer. Steer a running turn applies it.

Edge cases.

  • Nothing after cancellation. A UI that must show every started tool derives the rest from RunError.Result, not from the stream.
  • A parked call has a ToolStart and no ToolFinish; it is listed on RunFinish.Pending. It is the one exception to “every start has a finish”.
  • ToolArgsDelta streams fragments while the model is still writing a call; the assembled call arrives as ToolStart when it runs.
  • A child run’s events arrive as Nested{Seq, CallID, Event}, numbered from the parent’s counter; a grandchild’s event is a Nested inside a Nested.

Tests that pin it: TestStreamEventOrdering, TestTapSeesEventsInStreamOrder, TestTapSeesNothingAfterCancellation, TestEventJSONRoundTrip, TestUnmarshalEventRejectsUnknownType, FuzzUnmarshalEvent. Stream a run’s events applies them.

The problem. Every harness feature wants to run “before the model call” or “around the tool call”: logging, retries, fallbacks, permission checks, approvals, audit, sandboxing, JSON repair. The naive answer is a lifecycle hook per phase. Each hook is a contract that can never be removed, and hooks that can change behaviour make registration order part of the semantics.

What weft does. Exactly two behavioural seams, both chi-style, and one observation tap (ADR 0006, rule 10):

  • weft.ModelMiddleware, func(next Model) Model, attached with weft.WrapModel. The chain is built once at New, first listed outermost.
  • weft.ToolMiddleware, func(next ToolCaller) ToolCaller, attached with weft.WrapTools on the agent or on one tool. The chain is built per call: agent middleware, then the tool’s own, then the base that resolves, parks, decodes and runs.
  • weft.Tap, which sees everything and changes nothing.

Panic containment and timeouts sit outside the tool chain, so no middleware can turn a panic into a run failure or defeat a deadline. Two conventions replace the hooks people reach for (docs/life-of-a-call.md): middleware that verified something puts it on ctx before next, and the handler reads it through a typed accessor as it reads weft.CallFromContext; handlers return *weft.ToolError when the model should branch on a code, and mw.MapErrors codes the rest centrally.

weft.PrepareStep is the one loop-level knob (ADR 0006’s amendment): it rewrites the request before the model seam, per step (system, messages, tools, tool choice, params), and what it returns is what the step both advertises and dispatches against. Routing and phased tool exposure live there without a graph. Rewrite each step’s request applies it.

The reference set, and the retry stance. Package mw ships one of each kind so the seams have worked examples:

  • mw.Retry retries a model call only when it failed before yielding any event, because a mid-stream failure has already delivered half a turn. It retries ErrStreamIdle, network errors and HTTP 408, 409, 429 and 5xx (an x-should-retry header overrides); never context errors, the kill switch, ErrUnsupported, ErrModelContract, other 4xx, or a context-window overflow. Backoff starts at 500 ms, doubles, caps at 8 s, each delay with ±25% jitter, 3 retries by default; a provider’s retry-after wins, and an ask above mw.MaxWait (60 s) fails at once wrapping mw.ErrRetryAfterTooLong.
  • mw.Fallback and mw.FallbackWhen switch to the next model on the same before-first-event rule; cancellation and the kill switch never fall through, and a max_tokens finish is a success, not a failure.
  • mw.RepairJSON re-encodes malformed tool arguments once (unterminated strings and containers, a Markdown fence); what it cannot repair fails decoding as before.
  • mw.Log, also on the model seam, logs one line per model call.
  • On the tool seam: mw.Allow is fixed policy (DENIED: tool "x" is not allowed), mw.Audit logs each call with its cause, and mw.MapErrors shapes what the model reads.

The retry stance in one place: transport retries belong to the vendor SDK’s configuration; logic retries, the model correcting its own argument, are ModelRetry with a per-tool budget; the loop itself never retries a model call. Each layer has one job.

Why this is the whole extension model. Sandboxing would wrap the tool call. Approval is enforced at the base of the tool chain, so mw.Allow can deny first and mw.Audit sees the attempt, and surfaces as a run boundary. Spans and log records are the loop’s own reporting at fixed phases (ADR 0016), not the tap’s job: a tap cannot decorate the tool context or see a canceled run’s end. A third seam, or a phase turned into a hook, needs an ADR.

Tests that pin it: TestWrapToolsDenialAndPanicAreToolErrors, TestTapPanicIsContained, and the mw tests. Add behaviour with middleware and Retry a failed model call apply them.

7. Human in the loop: four models, one chosen

Section titled “7. Human in the loop: four models, one chosen”

The problem. The model wants to refund an order and a person must say yes. The person is on a web page, in a chat tool, or asleep. The decision may arrive in a second or a day, over another transport, at another replica. The field uses four models:

  1. Blocking prompt. The call waits on a callback. Ties the decision to the process lifetime and one transport.
  2. Interrupt plus checkpoint. The node raises, the whole state is checkpointed, and resume re-executes the node. Needs a persistence layer under the loop, and side effects before the interrupt run twice.
  3. Suspend and resume a snapshot. The loop is a workflow whose snapshot is stored when a step suspends. Needs snapshot storage and a double-resume guard.
  4. Run boundary. The run ends successfully with the pending calls on the result and no result in the transcript; a later run resumes with the transcript and the decisions. Needs nothing under the loop.

What weft does. Model 4 (ADR 0007), and the transcript is the only state.

Approval: a gated call parks, the run ends with RunFinish.Pending, and the next run resumes with weft.Approve or weft.Deny.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.
  1. A weft.RequireApproval tool, a call named by the run’s weft.ParkOn or excluded by weft.ParkAllExcept, a name a weft.ParkSource returns, or any middleware returning an error that wraps ErrApprovalRequired, is not executed. The check is at the base of the chain.
  2. The step’s other tools run. The run ends successfully with the parked calls on RunResult.Pending and RunFinish.Pending; the parked call has a ToolStart and no ToolFinish.
  3. Resume: with any decision present, the last assistant message’s unresolved calls are exempt from repair and resolved before the first model call. weft.Approve runs the call, weft.Deny gives DENIED: <reason>, weft.Resolve supplies a result computed elsewhere without running the handler, and an undecided call gets DENIED: no decision, visible, never silent.
  4. Cancellation wins: a run canceled while calls are parked fails with the ctx error, the calls on RunError.Result.Pending, so the transcript stays resumable.

No new part types, no persistence in the core, no transport assumed. Durable approvals are built above it: weft/thread stores pending requests in the session, decides them with s.Decide, supports grants, quorums and expiry, and verifies signed decisions with a keyring: ADR 0021’s answer to a core in which “a decision is whatever the caller passes”. Require human approval for a tool and Approve tool calls in a session apply both layers.

The nested case. The orchestrator delegates to a research subagent, and inside the child the model calls a gated refund_order. Under the run-boundary model the child’s run ends with Pending set, but its handler must return a string to the parent’s tool chain. The parent’s transcript has nowhere to carry the child’s pending call, and no run option on the parent can carry a decision for a call id that exists only inside the child. Keeping the child transcript in memory works only in-process; parking the parent’s call and re-running the child re-parks forever; serialising the child into the tool result makes a result a state container the model also reads.

weft’s decision (ADR 0014): a child run that ends with pending calls is a loud tool error at the parent, SUBAGENT_PENDING: agent "research" ended awaiting approval of 1 call(s), visible to the parent model and to mw.Audit. The practical guidance: put approval-gated tools in the orchestrator, not in a child.

Security, stated plainly. ADR 0007, under the heading “Not a security boundary”: “Approval is a policy and UX seam.” Per-call prompts do not contain a compromised prompt or a malicious tool; the boundary that does is the sandbox a tool runs in, which is deployment, not weft (the thread/sandbox proposal, ADR 0023, was abandoned).

Tests that pin it: TestApprovalPendingStopsTheRunAndResumes, TestApprovalWithoutDecisionsIsRepairedAsInterrupted, TestCanceledRunWithPendingCallsFails, TestApprovalResumeCompletesInCallOrder, TestResolveComposesWithApproveDeny.

The problem. A task is too big for one context window, needs a different model, or needs isolation, so one agent hands work to another. The field has five shapes: the agent as a tool; a handoff that transfers the conversation; a supervisor or graph over shared state; lanes over one session; and pools of concurrent children with receipts. It is the area where frameworks have most often built machinery they later removed, and the two things every serious implementation adds to the first shape are usage attribution and lineage.

What weft does. Shape 1, with no new concept in the loop: weft.Subagent defines a tool whose handler runs the child agent (ADR 0014). Everything the tool contract gives, the child gets: Timeout bounds the child run, MaxResultBytes caps its answer, RequireApproval gates the delegation, Sequential makes it a barrier, WrapTools wraps it once, and the manifest lists it.

  • Input. One argument, prompt, described to the parent model as “The task, stated in full: the agent sees only this prompt, not the conversation.” The child starts on a fresh transcript.
  • Output. The child’s final text, or, for a child built with Output[T], the submitted JSON.
  • Events. Every child event arrives in the parent’s stream as Nested{Seq, CallID, Event}, numbered from the parent’s counter under the parent’s event lock, between the delegating call’s ToolStart and ToolFinish. The child’s taps see its raw events; the parent’s see the wrapped ones.
  • Usage. The child’s total, a failed child’s partial usage included, is recorded on StepRecord.SubagentUsage keyed by call id and added to RunResult.Usage; StepFinish.Usage stays the model call’s own.
  • Run ids. The child’s id is <parent>/<step>/<call>, or <parent>/resume/<call> for a call resumed under Approve: deterministic, self-describing lineage.
  • Cancellation. The child runs on the parent call’s ctx. Parent cancellation cancels it; a Timeout on the subagent tool cancels it at the deadline and the parent records the timeout.
  • Failure. A child run error is data to the parent: SUBAGENT_FAILED: agent "research" failed at step 0: …, the *RunError on ToolError.Err for errors.As. A child that hits its own MaxSteps is a tool error, and the parent model can try something else.
  • Cycles. Agents are immutable values, so a cycle cannot be built at construction, but a ToolSource can close one at run time. The guard is an ancestry check on ctx: a delegation to an agent already running above the call is refused with SUBAGENT_CYCLE: agent "a" is already running in this call chain. A depth cap was considered and rejected as a number every user would have to think about.
  • Outside the loop. agt.CallTool on a subagent tool runs the child with no event sink, no usage sink and no ancestry: it runs as any tool does.

What is deliberately not there. No handoff primitive: a handoff is “return the other agent’s result”, and moving the transcript is weft.Messages on the child’s run, in your code. No graph: PrepareStep routing plus subagents cover the orchestration patterns (Agent patterns). No shared mutable state between parent and child. Asynchronous delegation with bounded concurrency and receipts is a session concern, and ships above the core as weft/thread/pool (ADR 0022), where a child is a session rather than a tool call.

Tests that pin it: TestSubagentUsageRollsUp, TestSubagentOutsideTheLoop, and the subagent cases of core/contract_test.go. Delegate to another agent applies it.

The problem. A step budget is not enough. A model can call the same tool with the same arguments fifty times inside the budget; a subagent multiplies spend by nesting depth; a tool result can be a megabyte. Each is a different runaway and needs a different bound.

The bounds, one per failure:

RunawayBoundDefault
Too many model callsweft.MaxSteps → ErrMaxSteps10
Too many tokensweft.UsageLimit → ErrUsageLimit, subagents includedoff
The same call repeatingweft.DetectLoops → ErrLoopDetectedoff
A model that cannot self-correctweft.MaxModelRetries → ErrModelRetriesExceeded3
A huge tool resultweft.MaxResultBytes, with a visible marker64 KiB
A hung toolweft.Timeout, per tool or agentnone
Nestingthe ancestry check, plus UsageLimit over the whole treeon
Fan-out widthweft.Parallelism4

Two conventions are rules. Ship a bounded default: 10 steps, 4 in parallel, 64 KiB per result; UsageLimit and DetectLoops are off because their right values depend on the workload. A breach is a *RunError with the partial transcript, checked only at the continuation point, so a step that ends the run succeeds even if it overshot (rule 13).

Loop detection in detail. DetectLoops(n) hashes each step’s tool calls, name and raw argument bytes, sorted so a permuted batch is the same request, and fails the run when n consecutive steps share the hash. Varying arguments produce different hashes, so a retry with a corrected argument is not a loop. Results are not hashed: a tool whose output carries a timestamp would never look repeated, and a missed loop costs one more step.

What usage counts. Usage is input and output tokens, with cached-input, cache-write and reasoning counts carried as subsets of them, summed per step onto StepFinish and StepRecord, and per run onto RunResult.Usage. The adapters fold provider-specific counters into those two (the Anthropic adapter folds cache tokens into input, the Google adapter folds thought tokens into output), so a budget written against Usage means the same thing whichever model answered. UsageLimit compares input and output tokens only.

Budgets across subagents. A child has its own MaxSteps, so steps do not compose across nesting. Usage does: a child’s usage rolls into the parent’s RunResult.Usage each step, so UsageLimit(weft.Usage{OutputTokens: 50_000}) on the parent bounds the whole tree, and the breach is reported at the parent. A thread/pool child is the exception: its usage is on its receipt and in the parent session’s Usage.Delegated, not on the parent run.

Tests that pin it: TestUsageLimitFailsBeforeTheNextCall, TestUsageLimitFinalStepMayOvershoot, TestUsageLimitIncludesSubagents, TestDetectLoopsTripsOnIdenticalSteps, TestDetectLoopsIgnoresVaryingArgs, TestDetectLoopsIsOrderInsensitive. How does a run stop? has every exit.

The problem. A deploy kills the process in the middle of step 4, while a tool runs. What is lost, what can be resumed, and is it safe to run the interrupted tool again? The field’s answers are checkpoints per step, workflow snapshots, replay of a journal, and stateful objects.

What weft does. The core is stateless on purpose; a run is a function from an agent, an input transcript and decisions to a result and events. What it provides so the layers above can be thin:

  • Ids as keys. Every run has an id before its first event, and child ids derive from the parent.
  • A replayable stream. Seq-ordered events with pinned wire bytes.
  • Repair. A stored transcript with a dangling call is valid input after Repair.
  • The approval boundary needs no persistence, which is why it can be in the core while durability is not.
  • weft.Replay on a tool records its re-run class, ReplaySafe or the default ReplayNever, on the tool and in the manifest, and changes nothing in the loop. The playground (weft/runtime) reads it: when it re-runs a recorded run, a never-class call is substituted with its recorded result or parked, never fired again by surprise, unless the experiment chooses the allow mode for tools opted in with runtime.AllowSideEffects.

Above the core, two layers hold state. weft/thread makes a conversation durable: an append-only log in which accepted input is flushed before the run starts and each step’s messages are appended as they join (T4). weft/otel records every run as OpenTelemetry spans and log records into obsdb, where Studio reads it back. A run that was in flight when the process died is not resumed: its session holds the messages up to the last appended step, the next turn’s Repair gives any dangling call the “interrupted” result, and Studio shows the run as interrupted once its records stop for 30 s.

What the earlier design sketched, and what shipped. The deep dive described a store package recording a run per row behind a three-method interface. It shipped, and was removed in ADR 0024’s step 5 in favour of the OpenTelemetry pipeline and obsdb. Its other sketches shipped in weft/thread: a JSONL tree with id/parent entries that branch in place, file-level repair rules (a torn final line dropped and reported, damaged lines skipped only under thread.Salvage), compaction with a preview (s.PreviewCompaction), signed approval decisions, and a bounded child pool. A durable-execution engine (Temporal, DBOS, Restate) would attach at the two seams: WrapModel to journal the model call and WrapTools to journal each tool call. No such adapter ships.

The questions the deep dive deferred, at v0.20.2:

QuestionStatus
Steering: input while the run is in flightshipped: weft.Steering in the core, s.Steer and busy policies in thread (ADR 0019)
MCP interop: serve weft tools, consume foreign toolsshipped: mcp.Tools and mcp.Serve (ADR 0015)
Observability: spans and log linesshipped: the loop’s own invoke_agent, chat and execute_tool spans and log records (ADR 0016, ADR 0024)
Record and replay for testsshipped: wefttest.Record and wefttest.Replay (ADR 0017)
Tool progress: partial output from a long toolnot shipped; see the roadmap

The last question is not about the loop but about its users: what a release may break. weft’s answer is that the model-visible behaviour is a contract (rule 5). The public API is gated by apidiff in CI (core enforced, the framework module reported until its layers freeze). Interfaces are sealed so new event and part types are additive, and the CHANGELOG lists model-visible changes. Design principles states the principle; How the weft repository is organised and checked shows the gate.

Symbols used: weft.ModelRequest · weft.StopWhen · weft.MaxSteps · weft.Output · weft.ModelRetry · weft.StrictInput · weft.RawTool · weft.ToolSource · weft.CancelCause · weft.Repair · weft.Tap · weft.Steering · weft.PrepareStep · weft.RequireApproval · weft.ResumeOf · weft.Subagent · weft.Replay · core.Agent.CallTool · core.Run.Events