The agent loop, from first principles
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.
From first principles
Section titled “From first principles”The forty-line loop
Section titled “The forty-line loop”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.
- Call the model with the transcript. A model failure is a run failure.
- Append the assistant message to the transcript.
- If it asked for no tools, return: the run is done.
- Run every requested tool. A tool failure becomes text the model reads.
- Append the results as one tool message, and go to 1.
- 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.
The vocabulary
Section titled “The vocabulary”Frameworks use these words differently. weft’s meanings, used on every page of these docs:
| Word | Meaning in weft |
|---|---|
| Run | One call to Generate or Stream: an id, an input transcript, a sequence of steps, then a result or a *RunError |
| Step | One model call plus the execution of the tool calls it requested; StepRecord records it |
| Turn | One 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 / result | ToolCallPart{ID, Name, Args} on an assistant message; ToolResultPart{CallID, Name, Content, IsError} on the tool message after it |
| Stop reason | Why the model turn ended (stop, tool_calls, max_tokens); recorded, never hidden |
| Stop condition | The intended end of a run (StopWhen); a success |
| Budget | A safety limit (MaxSteps, UsageLimit, MaxModelRetries, DetectLoops); a breach is a failure |
| Event | A progress notification on the stream: RunStart, StepStart, TextDelta, ToolStart, ToolFinish, StepFinish, RunFinish and the rest |
| Seam | Where behaviour attaches: around the model call and around the tool call; there are two |
| Tap | Where observation attaches: sees every event, changes nothing |
| Reasoning block | One provider thinking block; a delta carrying its signature closes it, and it is stored as one ReasoningPart the core never reads |
| File part | FilePart{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.
Why forty lines are not enough
Section titled “Why forty lines are not enough”Run the forty lines in production and these questions arrive, roughly in this order. Each has a section below.
| # | Question | The failure that forces it |
|---|---|---|
| 1 | When does the run end, and is ending a success? | A runaway loop that returns a plausible transcript |
| 2 | What is a tool failure? | One tool error aborts the whole run, or is swallowed |
| 3 | What runs at once, and in what order? | Four tools race, results come back shuffled, a hung tool hangs the run |
| 4 | Is the transcript always valid input? | A crash mid-tool leaves a dangling call the provider rejects on every later turn |
| 5 | What does the caller see while it runs? | A UI that cannot render interleaved progress; a recording that cannot be replayed |
| 6 | Where does cross-cutting behaviour attach? | Fifteen lifecycle hooks, each a contract |
| 7 | How does a person say yes or no? | The process blocks on a prompt; the decision cannot arrive over HTTP an hour later |
| 8 | How does one agent use another? | Graph DSLs, handoff primitives, opaque children |
| 9 | How much may a run cost? | Steps multiply across nesting; the same call repeats until the bill arrives |
| 10 | What survives a restart? | A deploy kills a run mid-tool |
| 11 | What can never change? | An upgrade that changes what the model reads, or breaks code that compiled yesterday |
Anatomy of one step in weft
Section titled “Anatomy of one step in weft”The concrete loop is Agent.execute in core/loop.go. Compressed to its control flow:
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 §9after the loop: ctx done? → that error; else ErrMaxSteps §1Two 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 model turn, in detail
Section titled “The model turn, in detail”The loop builds one weft.ModelRequest per step:
System: the instructions (the run’sInstructionsoverride, else the agent’s), then, after thePrepareStepchain, one paragraph per advertised tool’sPromptSnippet, 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. WithToolSourcethe 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 isErrStreamIdle: a silent stream is stopped, a slow one that keeps streaming is not. - The kill switch.
WEFT_MODEL_REQUESTS=denymakes every first-party adapter refuse its self-built client’s call withErrModelRequestsDeniedbefore any network I/O, read on every call. Test agents offline relies on it.
The full path, function by function
Section titled “The full path, function by function”Every function a run passes through at v0.20.2, in order:
- Options become a
runConfig. EachRunOptionapplies in the order given:PromptandMessagesappend to the input,RunIDsets the id,Approve,DenyandResolverecord 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.Generatecallsexecutewith a sink that discards events.Streamreturns a lazy*Run: nothing executes untilEvents()is ranged orWait()is called, sorun.ID()can be handed to a client first. - The producer goroutine.
Run.Events()marks the run started (a second call yields onlyErrRunConsumed), opens an unbuffered channel and runsexecuteon 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. executesets up the run. It extends the ancestry chain (the subagent cycle guard), mergesweft.Metadatawith what the ctx carries, rebuilds theWrapModelchain over aUseModelalternate, and starts theinvoke_agentspan. It builds thedeliverwrapper every event passes through: it drops the event if ctx is done, runs everyTapin registration order, records the event, then hands it to the sink. ThenRepairproduces the starting transcript,RunStart{ID, Model, Agent}is emitted, and the input is recorded.- Refusals before any model call. A
Resolveaimed at a call that is not pending fails the run at step 0. A run option that raisesMaxStepsorParallelismabove the agent’s, or anOnlyToolsname the agent does not have, fails withErrInvalidRunOption.ParkSourcefunctions are read once, and their names join the run’sParkOnset. - The resume branch. If decisions were given and the last assistant message has calls without results,
resolvePendingruns them (below) andattachResultscompletes the tool message. If calls park again, the run ends here with zero steps. - 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. ThePrepareStepchain 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), thenToolChoiceandParams. consume: the model turn under contract. The stream runs inside achatspan. Text deltas becomeTextDeltaevents and the step’s text; reasoning deltas becomeReasoningDeltaand accumulate into the open block, which a signature closes; tool calls are validated and collected; argument fragments becomeToolArgsDeltaprogress;ModelFinishis recorded. Any violation returns an error, andexecutefails the run at this step.- The assistant message. One
ReasoningPartper block with text or a signature, oneTextPartif text arrived, then eachToolCallPart, in that order. A message with no content is not appended. - The tool decision. No calls: nothing to run. A
max_tokensfinish with calls: every call gets the “was not executed” result. OtherwiseexecToolsruns them. execTools: dispatch in call order. A semaphore of capacityParallelismbounds the fan-out. For each call, in order: aSequentialtool first waits for every call in flight. A canceled run getsrun canceled before the tool startedand no events. Otherwise the slot is acquired on the dispatching goroutine andToolStartis emitted there, which is what makes start order equal call order. A goroutine runscallTooland, unless the call parked, emitsToolFinish. Results are assembled by index.callTool: policy and containment. The effective policy is computed: for the result cap and the timeout the tool’s own setting wins (a per-toolTimeout(0)orMaxResultBytes(0)lifts the agent’s). Strictness is on when either the agent or the tool setsStrictInput. The chain runs inside the containment boundary: a recovered panic becomestool "X" panicked: …, an expired deadlinetool "X" timed out after 5swith the handler goroutine abandoned. An error wrappingErrApprovalRequiredparks the call; any other error becomesIsError: true; the result is capped.chain: the call from the outside in. The agent’sWrapTools(first listed outermost) wraps the tool’s ownWrapTools, which wraps the base. The base returnsNO_SUCH_TOOLfor an unknown name (the chain still ran, somw.Allowandmw.Auditsaw it), parks aRequireApprovalorParkOncall that is not approved, decodes the arguments (INVALID_INPUTnaming the field on failure), runs the handler and renders the output.- Close the step. One
toolmessage with every result in call order is appended, theStepRecordadded, usage summed (subagent usage rolled in), andStepFinishemitted. - The exits, in this order. Pending calls end the run with
RunFinish{Pending}. AStopWhencondition 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 checksMaxModelRetries,UsageLimitandDetectLoops, and the next step begins. - 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.
Every exit, and what the caller holds
Section titled “Every exit, and what the caller holds”| Exit | Generate returns | Messages ends with | Last event |
|---|---|---|---|
| Model stopped asking for tools | (res, nil) | the final assistant message | RunFinish |
StopWhen fired | (res, nil) | the step’s tool message | RunFinish |
| Calls awaiting approval | (res, nil), res.Pending set | a tool message missing the parked calls, or none if every call parked | RunFinish with Pending |
| Model stream error or contract violation | (nil, *RunError), Result set | the previous step’s tool message | the last delta before the failure, then the error |
Misconfigured run (ErrInvalidRunOption, a bad Resolve, an invalid ToolChoice, an invalid steer) | (nil, *RunError), Result set | the input, or the step where it was found | RunStart (or that step’s StepStart), then the error |
| Cancellation | (nil, *RunError) matching context.Canceled, Pending set if calls were parked | whatever was appended before the check | nothing after cancellation; then the error |
Budget (ErrMaxSteps, ErrUsageLimit, ErrModelRetriesExceeded, ErrLoopDetected) | (nil, *RunError), Result set | the last allowed step’s tool message | StepFinish |
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”.
Goroutines and locks
Section titled “Goroutines and locks”| Who | Runs | Emits |
|---|---|---|
| The consumer | ranges Run.Events() | nothing |
| The loop goroutine | execute, consume, execTools’ dispatch, resolvePending, the steering drain | RunStart, StepStart, deltas, ToolStart, Steered, StepFinish, RunFinish |
| One goroutine per tool call | callTool and the chain; a subagent’s child run | ToolFinish, Nested |
| One goroutine per timed-out handler | the abandoned handler, until it notices ctx | nothing 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.
The resume path
Section titled “The resume path”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.
What the model sees, step after step
Section titled “What the model sees, step after step”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.
The eleven questions
Section titled “The eleven questions”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.StopWhenis the intended end. AStopConditionhas one method,Stop(steps []StepRecord) bool;weft.StopFuncadapts a function; the built-insweft.HasToolCallandweft.StepCountIsimplementfmt.Stringer, so the manifest andRunFinish.StoppedByname them (has_tool_call:submit). Conditions are checked after each step, before the steering drain, and a fired condition ends the run successfully.weft.MaxStepsis the safety budget, 10 by default. When the model still wants tools after the last allowed step, the run fails withErrMaxStepsand the full transcript, including the last step’s tool results, onRunError.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_tokenson a text-only reply is not an error:RunResult.StopReasonismax_tokensand the run succeeds; the caller decides what truncated text means.- A stop condition sees the whole
StepRecord, calls and results:HasToolCallreads 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 beforeStopWhenis checked, and the resumed call adds noStepRecord. - 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 text | When |
|---|---|
INVALID_INPUT: tool "x": field "days": expected integer, got string | arguments 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 limit | a 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.DeadlineExceededgets 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 allowedfrommw.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.
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
ToolStartis emitted there. ADR 0004 records the bug this fixed: a goroutine-per-call race for the semaphore neither started tools in call order nor madeSequential()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.
Seqis 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 startedand no events, so everyToolFinishfollows itsToolStart. - 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.Resultis the record. - Cancellation wins over
ErrMaxSteps. A cause passed throughcontext.WithCancelCause, such asweft.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 returningErrApprovalRequired) 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
CallIDnames 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/threaddoes it (ADR 0020): it triggers on provider-reported usage againstthread.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
ToolStartand noToolFinish; it is listed onRunFinish.Pending. It is the one exception to “every start has a finish”. ToolArgsDeltastreams fragments while the model is still writing a call; the assembled call arrives asToolStartwhen it runs.- A child run’s events arrive as
Nested{Seq, CallID, Event}, numbered from the parent’s counter; a grandchild’s event is aNestedinside aNested.
Tests that pin it: TestStreamEventOrdering, TestTapSeesEventsInStreamOrder, TestTapSeesNothingAfterCancellation, TestEventJSONRoundTrip, TestUnmarshalEventRejectsUnknownType, FuzzUnmarshalEvent. Stream a run’s events applies them.
6. Extension: two seams, one tap, no more
Section titled “6. Extension: two seams, one tap, no more”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 withweft.WrapModel. The chain is built once atNew, first listed outermost.weft.ToolMiddleware,func(next ToolCaller) ToolCaller, attached withweft.WrapToolson 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.Retryretries a model call only when it failed before yielding any event, because a mid-stream failure has already delivered half a turn. It retriesErrStreamIdle, network errors and HTTP 408, 409, 429 and 5xx (anx-should-retryheader 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 abovemw.MaxWait(60 s) fails at once wrappingmw.ErrRetryAfterTooLong.mw.Fallbackandmw.FallbackWhenswitch to the next model on the same before-first-event rule; cancellation and the kill switch never fall through, and amax_tokensfinish is a success, not a failure.mw.RepairJSONre-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.Allowis fixed policy (DENIED: tool "x" is not allowed),mw.Auditlogs each call with its cause, andmw.MapErrorsshapes 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:
- Blocking prompt. The call waits on a callback. Ties the decision to the process lifetime and one transport.
- 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.
- 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.
- 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.
- A
weft.RequireApprovaltool, a call named by the run’sweft.ParkOnor excluded byweft.ParkAllExcept, a name aweft.ParkSourcereturns, or any middleware returning an error that wrapsErrApprovalRequired, is not executed. The check is at the base of the chain. - The step’s other tools run. The run ends successfully with the parked calls on
RunResult.PendingandRunFinish.Pending; the parked call has aToolStartand noToolFinish. - Resume: with any decision present, the last assistant message’s unresolved calls are exempt from repair and resolved before the first model call.
weft.Approveruns the call,weft.DenygivesDENIED: <reason>,weft.Resolvesupplies a result computed elsewhere without running the handler, and an undecided call getsDENIED: no decision, visible, never silent. - 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.
8. Subagents: one agent using another
Section titled “8. Subagents: one agent using another”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’sToolStartandToolFinish. 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.SubagentUsagekeyed by call id and added toRunResult.Usage;StepFinish.Usagestays the model call’s own. - Run ids. The child’s id is
<parent>/<step>/<call>, or<parent>/resume/<call>for a call resumed underApprove: deterministic, self-describing lineage. - Cancellation. The child runs on the parent call’s ctx. Parent cancellation cancels it; a
Timeouton 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*RunErroronToolError.Errforerrors.As. A child that hits its ownMaxStepsis 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
ToolSourcecan 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 withSUBAGENT_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.CallToolon 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.
9. Budgets and runaway loops
Section titled “9. Budgets and runaway loops”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:
| Runaway | Bound | Default |
|---|---|---|
| Too many model calls | weft.MaxSteps → ErrMaxSteps | 10 |
| Too many tokens | weft.UsageLimit → ErrUsageLimit, subagents included | off |
| The same call repeating | weft.DetectLoops → ErrLoopDetected | off |
| A model that cannot self-correct | weft.MaxModelRetries → ErrModelRetriesExceeded | 3 |
| A huge tool result | weft.MaxResultBytes, with a visible marker | 64 KiB |
| A hung tool | weft.Timeout, per tool or agent | none |
| Nesting | the ancestry check, plus UsageLimit over the whole tree | on |
| Fan-out width | weft.Parallelism | 4 |
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.
10. Durability: what survives a restart
Section titled “10. Durability: what survives a restart”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.Replayon a tool records its re-run class,ReplaySafeor the defaultReplayNever, 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 theallowmode for tools opted in withruntime.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:
| Question | Status |
|---|---|
| Steering: input while the run is in flight | shipped: weft.Steering in the core, s.Steer and busy policies in thread (ADR 0019) |
| MCP interop: serve weft tools, consume foreign tools | shipped: mcp.Tools and mcp.Serve (ADR 0015) |
| Observability: spans and log lines | shipped: the loop’s own invoke_agent, chat and execute_tool spans and log records (ADR 0016, ADR 0024) |
| Record and replay for tests | shipped: wefttest.Record and wefttest.Replay (ADR 0017) |
| Tool progress: partial output from a long tool | not shipped; see the roadmap |
11. What can never change
Section titled “11. What can never change”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.
See also
Section titled “See also”- What happens in one step? The loop and parallel tools
- Design principles: the rules weft keeps
- Agent patterns and where they attach in weft
- How weft compares to other agent frameworks
- Architecture decision records
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