26. The agent loop

Why this layer exists

Chapter 24 gave a client that sends one request and returns one response; chapter 25 gave a decoder that turns the response’s tool calls into checked Calls and a list of Problems. Neither decides what happens next. The loop does: it reads the model’s reply, runs the calls, puts the results back in front of the model, and decides when to stop. This is where a model becomes an agent. The difficulty is in the stops, in the order of the replies, in what a refused call looks like to the model, and in what the run leaves behind.

Everything later attaches here. Chapter 27’s tools implement agent.Tool; chapter 28’s router implements agent.Router; chapter 42’s scheduler and chapter 47’s gate are agent.Approvers and policies; chapter 45’s workers are loops on sessions of their own; chapters 40, 42, 47, 49 and 51 read or extend the trace the loop writes. Two of the course’s cross-part obligations are decided in this chapter’s code. Traces before observability: chapter 49 scores and prices a trace format, so the format has to exist, and have been used by a running loop, before chapter 49 starts; this chapter fixes it, with a lab that rebuilds a trajectory from spans alone. Approval as protocol: a call that needs a human’s consent is bound to that one dispatch, and silence ends in a timeout, not a hang. Only the loop sits between a decoded call and its execution, so the binding is checked here. Chapter 27 marks the tools and writes the approvers.

aec v0 is the agent CLI that chapter 1’s table names: cmd/aec runs one task against one model with a few tools and writes a trace. It is the loop plus a command line. The loop is loop.go, 941 lines (straylight, at the finished repository), of which the gate and the dispatch that chapter 27 lists are 373; the eight files of the agent package are 1,501 lines, and the trace format is obs/trace.go, 442 lines.

Mechanism

The turn rule

Let hth_t be the session’s messages before turn tt, a sequence. A turn makes one model call, which returns an assistant message αt\alpha_t with ktk_t tool calls on the wire, and the loop extends the session:

ht+1=ht∥αt∥rt,1∥⋯∥rt,kt,∣ht+1∣=∣ht∣+1+kt, h_{t+1} = h_t \,\|\, \alpha_t \,\|\, r_{t,1} \,\|\, \cdots \,\|\, r_{t,k_t}, \qquad |h_{t+1}| = |h_t| + 1 + k_t ,

where rt,ir_{t,i} is the tool message that answers the ii-th call, in the order the model wrote the calls. A response with kt=0k_t = 0 ends the run: its text is the answer. The rule has seven parts, and each is a place where an unwritten default would have been a bug.

  1. A turn is a model call, and the budget counts model calls. Run appends the reader’s message and starts the run span. Before each model call the loop checks that fewer than TT (MaxTurns) have been made, and stops with max_turns otherwise. If the call fails, the run ends (cancelled when the context is done, error otherwise) and nothing is appended: there is no assistant message to append. When Loop.Context is set (chapter 29), it runs first and may end the run before the call: a refuse stops it with context_exceeded, in a turn that has a context span and no model_call.
  2. The assistant message goes into the history as received and before anything else is decided. A content_filter finish then ends the run as refused; the message’s tool calls, if it carries any, are not run and not counted, and each is answered denied: not run: the reply was refused (content_filter) with a tool_call span of its own. A message without tool calls ends the run as final; if the server ended it on finish_reason length (the cap, or the context, ran out), Stop.Truncated is set (chapter 53), and the text is a cut-off reply, not one that ended. Tool calls are not examined for the cut: the decode of part 3 reports a truncated argument as its truncated problem.
  3. Every wire call is answered, decoded or not. toolcall.Decode splits the calls into those that pass and Problems. A call with a defect it cannot repair (not JSON, unknown tool, schema violation, duplicate id) is answered with a tool message that lists its problems, error: tool call rejected; not_json: …, carrying the call’s own tool_call_id, so the model can write the call again. The three repairs of chapter 25 (fenced, nested_string, trailing_text) still yield a call, which runs, with a repaired attr on its span. A turn in which no call decodes still counts as a turn, because it cost a model call, which is what TT bounds; and it adds nothing to the tool-call count, so only TT ends a model that never writes a decodable call.
  4. Tool calls have their own budget, KK (MaxToolCalls), over the whole run. The decoded calls of a turn are counted together, before any runs. If counting them would pass KK, the run stops with max_tool_calls and the batch is not counted and, by part 6, not run.
  5. Spans start in wire order and replies are appended in wire order. The loop starts one tool_call span per wire call, in the order the model wrote them, before any call runs. The replies are appended in the same order whatever order the calls finished in, because the order of the calls is the one piece of structure that the model, the loop and the trace share. The binding on the wire is tool_call_id; in the trace it is position, which a reader can check without trusting a timestamp.
  6. A stop that ends a turn early still answers the turn. When the gate ends the run (an approval timeout under Abort) or part 4 does, every call of the turn that did not run is answered denied: not run: the run was aborted before this call ran, or denied: not run: max_tool_calls reached, with IsError set and a tool_call span whose result_kind is denied. A call that earned an approval attr keeps it. This includes calls that came before the one that timed out and had been allowed: an unanswered call is not neutral. The Anthropic wire requires a result for every tool_use block (chapter 24), and on any wire a model shown an empty result reads it as success.
  7. Calls run concurrently, and the loop stops waiting for a tool at its deadline or when the run is cancelled. The calls that passed the gate each run in a goroutine of their own. The loop waits for a call until the tool’s Timeout() (30 s without one) or until the run’s context ends, and not for the tool to notice: the model is answered timeout: no answer within 30s or cancelled whether or not the tool honoured its context (a tool that does gets 20 ms after the deadline to return before it counts as abandoned). If the run’s context is done by the time the calls are settled, the replies are appended first and the run stops with cancelled. If it is done before dispatch starts (the run was cancelled while the gates ran, or the model’s answer was already on the wire when it was), no call of the batch starts: each call not already settled is answered cancelled, and the ledger of chapter 40 is told of none, so a run whose context had ended before the check starts no tool. The check is made once: a cancel that lands after it, between the check and a tool’s goroutine starting (the loop marshals each call and the ledger’s Begin syncs a record to disk first), is a call in flight, and the batch is begun and ended in the ledger and answered cancelled whether or not the tool ran, a tool that ignores its context having run; TestCancelBetweenCheckAndBegin lands the cancel inside the ledger’s Begin and checks exactly this. Under the guard Stop.Calls counts the calls the guard answered, and a batch over max_tool_calls under an ended context stops max_tool_calls, not cancelled, because the abort branch is first. An abandoned tool’s goroutine is left to finish: it makes no tracer call, and its result is discarded.

The consequence of parts 3, 5, 6 and 7 is an invariant: after every turn the loop finishes, each assistant message with kk tool calls is followed by exactly kk tool messages, one per call id, in order. The history is therefore well formed after any stop, and a stopped session can be sent again, which is what chapter 40’s resume needs. The proof is the structure of toolTurn: it builds one pending per wire call and builds the replies from that list, so it emits kk replies if every pending has a result when it does. Each does, by exactly one of five routes: rejected at decode, decided by the gate (denied, timed out), filled in by the abort rule of part 6, answered cancelled because the run’s context had ended before dispatch (part 7), or run by dispatch, which gives every call it launches a Result, whether it ran, was abandoned (part 7), came from the idempotency cache, or followed a leader whose result it copies. The one path outside toolTurn is a filtered reply, whose calls refuseCalls answers (TestFilteredReplyWithToolCallsIsAnswered). The loop’s own tests check the invariant for the early stops, where it is easiest to lose: wireValid requires the replies in order by call id, each non-empty, and the history accepted by the real OpenAI-dialect encoder, after an approval timeout with an earlier call already allowed, after a max_tool_calls batch, and after a filtered reply.

One turn of the agent loop, with its spans A cycle of seven boxes read top to bottom. The session history feeds a model call, which writes a model_call span. If the response has no tool calls the run stops as final. Otherwise the calls are decoded by toolcall.Decode, with rejected calls answered by text; each decoded call gets its tool_call span, started in wire order just before that call passes the gate, a policy decision and, for a marked tool, an approval, each a span, and all of them are started before any call runs; the allowed calls are then dispatched concurrently, each in its own goroutine under its own deadline and abandoned at it; the replies are appended in wire order to the history, and the cycle repeats. On the right, the stop conditions at the point where each is checked: max_turns before the model call, max_tool_calls after decoding, approval_timeout at the gate, cancelled during dispatch; a stop that ends a turn early still answers every call of that turn that did not run, as denied; so does a refused reply that carries calls. On the left, a bracket marks the run span around every turn and the turn span around one cycle. run span: the whole Run turn span: one cycle History Session.Messages Model call model_call: model, finish_reason, usage before the call max_turns Tool calls in the answer? none: the text is the answer Stop final Decode toolcall.Decode; rejected calls answered budget exceeded max_tool_calls Span and gate, per call policy_decision; approval if marked silence, Abort approval_timeout Dispatch tool_call parallel, each under its deadline context done cancelled Replies one tool message per call, in wire order

Approval and the call that runs

The gate belongs to the loop because of what it protects. After decoding, a call can be denied by the loop’s Policy, and it can be marked by its tool (Marked.NeedsApproval) as needing the reader’s consent. A marked call goes to the Approver. Four properties make the consent a protocol and not a prompt. Chapter 27 shows the marked tools and the approvers that answer; the protocol is stated here because it lives in the loop.

The reply is bound to a dispatch, not only to a call’s content. A call’s Hash is the sha256 of its canonical name and arguments (chapter 25) and contains no call id, turn or session. The scripted run below and the live run both call add with {"a":2,"b":3}, with different call ids and different models, and both spans carry the same call_hash. That is what makes the hash the right identity for a policy (“this command, never”) and the wrong one for an approval. An approval bound to the hash alone is a bearer token for a piece of text: a reply that an approver kept while it waited for a person (chapter 41’s channel approver asks in chat and answers when the principal does), or that any process saw go by, approves every later identical call, in this turn or the next, in this run or another. So each dispatch gets a nonce. Loop.NewID draws it, 64 random bits from crypto/rand by default, from the loop’s own source and not from the tracer, so that approvals work with tracing off and are not weakened by a tracer whose ids are counters. It travels as ApprovalRequest.ID and is recorded in the approval span’s nonce attr. The reply must echo it in Approval.Request and echo the call’s hash in Approval.CallHash. The nonce binds a reply to a dispatch. It does not authenticate the approver: whoever receives the request can read the nonce and answer, and the approver is the authority.

The binding is checked before the decision is read. The order is: no approver means deny; a reply that arrives after the deadline is timeout whatever it says; an error from the approver is error (or cancelled if the run’s context ended); then the binding, where an empty or different Request, or a different CallHash, is mismatch, a denial; and only then Decision. So a stale or foreign reply cannot allow a call, and it cannot abort the run by claiming timeout either. The approval span records call_hash, call_id, nonce, timeout_s, decision and by.

Silence is bounded by the loop. The Approver runs in its own goroutine and the loop waits for its reply or for the deadline (ApprovalTimeout, 60 s by default, the figure the reader’s Hermes approval role uses, chapter 21), whichever comes first. An approver that ignores its context therefore cannot hold the run; its goroutine stays parked, because the loop abandons the wait and not the goroutine, and Approve may be called for the next call while an earlier one is still running. A late reply is not acted on, and the span cannot tell silence from a late answer: both write error no reply within 1m0s. A reply that arrives after the loop has moved on is dropped and recorded nowhere. What the timeout does is OnTimeout: Abort, the default, stops the run with approval_timeout after answering every call of the turn (part 6 of the turn rule); Observe answers that one call denied: approval timed out and continues.

What was approved is what runs. A Call handed to a hook by value still shares its Arguments map with the hook, and a Go map is a reference. A Policy or a NeedsApproval that normalises a path in place, or an approver that edits the arguments it was shown, changes the call after its hash was taken and approved. This is a time-of-check to time-of-use gap (CWE-367) with the check and the use in different packages. The loop closes it by ownership. It deep-copies each decoded call’s arguments before the gate. After the policy and the tool’s own check, rebind hashes a fresh copy of the arguments and compares the result with the hash the call was decoded with. After an approval it does so again. A difference is a denial: denied: arguments changed while the call was being checked (hash d6fb174cac0e, now …), or … after approval …, and the tool_call span gets a rebound_hash attr holding the new hash. Arguments that no longer hash at all are denied as … and no longer hash: …. When the hashes agree, the call keeps the copy that was hashed, which no hook has seen, and that copy is what the tool receives; the idempotency cache and the call_hash attr use the rehashed value. The one thing the loop cannot defend against is a hook that holds the map and changes it from another goroutine while the loop copies it, which is a data race, and a hook must not do it.

Termination and the wall-time bound

Every iteration of the loop either stops or makes a model call, so a run makes at most TT model calls (default 20) and ends. How long can that take? Let DD be the longest one model call can take, aa the approval timeout, dmaxd_{\max} the largest Timeout() among the tools offered (30 s, DefaultTimeout, for a tool without one), and KK the tool-call budget (default 50). Turn tt has three phases, one after another.

The model call takes at most DD. The provider retries a transport error or a transient status (chapter 24), so DD is not the HTTP timeout. With AA attempts (default 3), each ending within the client’s timeout D1D_1 (cmd/aec’s client: 300 s, covering connect, headers and body) and at most A−1A-1 waits, each capped at WW (30 s),

D=AD1+(A−1)W=3⋅300+2⋅30=960 s. D = A D_1 + (A-1)\,W = 3 \cdot 300 + 2 \cdot 30 = 960 \text{ s}.

Then the gate asks about the turn’s qtq_t marked calls one after another, since the gate is sequential, and each wait ends within aa (the loop stops waiting at the deadline, above), so the gate takes at most qtaq_t a. Then the allowed calls run concurrently, each bounded by its own deadline, so the phase ends when the slowest does, within dmaxd_{\max} plus the 20 ms grace of part 7, which the arithmetic below drops (20 turns add 0.4 s). Summing over the at most TT turns:

∑t=1T(D+qta+dmax)=TD+a∑tqt+Tdmax≤TD+Ka+Tdmax. \sum_{t=1}^{T} \bigl(D + q_t a + d_{\max}\bigr) \;=\; T D + a \sum_{t} q_t + T d_{\max} \;\le\; T D + K a + T d_{\max}.

The inequality uses qt≤ctq_t \le c_t, where ctc_t is the number of decoded calls the loop counted in turn tt, and ∑tct≤K\sum_t c_t \le K: the counter grows by ctc_t only when the total stays within KK, and the one turn that would exceed it runs no gate at all. The defaults give 20⋅960+50⋅60+20⋅30=19200+3000+600=2280020 \cdot 960 + 50 \cdot 60 + 20 \cdot 30 = 19\,200 + 3\,000 + 600 = 22\,800 s, six hours and twenty minutes, of which the model-call term is 84%. A caller who wants a shorter worst case changes that term first: Attempts: 1 on the provider turns the retries off (chapter 24 argues the case for them), which gives D=300D = 300 and a bound of 9 600 s; a router that falls back along a chain adds the budget of every provider it tries (chapter 28). The bound holds on the loop’s side for any tool and any approver, because the loop abandons both at their deadlines; it does assume that the Policy (or PolicyContext) and NeedsApproval hooks, and Loop.Context at the start of a turn, return promptly: they run synchronously and the loop bounds none of them (chapter 47’s gate can be a Policy, and chapter 31’s compactor makes a model call of its own inside Context, bounded only by its own client).

What a timeout result then means is weaker than it sounds. It says that the loop stopped waiting, not that the tool stopped: an abandoned goroutine may still finish, and its side effect with it. A model that reads timeout and calls again may do the thing twice. This is a property of the loop and not of any tool, and what to do about it (idempotent tools, a result cache keyed by the call’s hash, confirming before retrying) is chapter 27’s subject, and killing what a tool started is chapter 43’s, with a sandbox. The trace says it in one attr: if the abandoned tool’s result arrived before its tool_call span ended, the span has late_result (arrived after the tool was abandoned, discarded); a result that comes later is dropped, because a tracer call after End would be an error and one from the goroutine would break determinism. A command-line run has an outer bound that is not this one: cmd/aec -timeout (ten minutes by default) is a deadline on the whole run’s context.

Prompt growth

Each turn sends the whole history. Let p1p_1 be the prompt tokens of the first model call and gsg_s the tokens that turn ss added to the history (the assistant message and its replies, as the next prompt counts them). Then turn tt’s prompt is pt=p1+∑s=1t−1gsp_t = p_1 + \sum_{s=1}^{t-1} g_s, and over nn turns the provider reports

Pn=∑t=1npt=np1+∑t=1n∑s=1t−1gs=np1+∑s=1n−1(n−s)gs. P_n = \sum_{t=1}^{n} p_t = n\,p_1 + \sum_{t=1}^{n} \sum_{s=1}^{t-1} g_s = n\,p_1 + \sum_{s=1}^{n-1} (n-s)\,g_s .

The last step swaps the order of summation: gsg_s appears in ptp_t for every t>st > s, which is n−sn - s turns of the nn. For a constant gg, ∑s=1n−1(n−s)=n(n−1)/2\sum_{s=1}^{n-1}(n-s) = n(n-1)/2 (pair the terms n−1,n−2,…,1n-1, n-2, \ldots, 1 forwards and backwards: n−1n-1 pairs each summing to nn, twice the sum), so Pn=np1+gn(n−1)/2P_n = n p_1 + g\,n(n-1)/2, quadratic in nn.

This is the number the provider reports and a cloud provider bills; it is what chapter 29 budgets and chapter 49 prices. It is not the work a local server does. Chapter 17’s engine keeps the last request’s keys and values and runs only the new suffix of the next prompt, and chapter 19 says what a slot does with it, so on one server with a warm slot the compute per turn is the suffix. Both numbers are in the live run below, measured on dixie.

The trace format

A trace is the set of spans that share a Trace id, one JSON line per span in a file. A span has: trace; id; parent (empty for the root); seq; kind; name; start and end (UTC); status (ok, error, timeout, denied or cancelled); attrs, a map of strings; usage, when the span is a model call or the run; and body, the name of a file. Six kinds exist, and each carries its identity in attrs:

kind parent name identity in attrs
run none, or the dispatching tool_call of a parent run (chapter 45) the session id (it is also the trace id) stop, turns, calls; usage sums the model calls
turn run the turn number none
model_call turn the provider request_hash, provider (both set before the call); model, finish_reason on success; role when routed; error on failure
tool_call turn the tool name tool, call_id, call_hash, result_kind; approval, rebound_hash, repaired, cached, problems, panic, late_result, copied_from when they apply
policy_decision turn policy, route or context policy, call_hash, call_id, decision (allow, deny or approve), reason; for route: role, source, calibrated, fail_open, provider, model, probabilities, error; for context (chapter 29’s Loop.Context, one per turn when set): action (keep, prune, summarise or refuse), the manager’s own attrs, error
approval turn the tool name call_hash, call_id, nonce, timeout_s, decision, by, reason, error

The run span’s status is ok for final, cancelled, timeout for an approval timeout, denied for a refusal and error for everything else, max_turns and max_tool_calls included. A consumer that counts calls counts tool_call spans, not Stop.Calls: a rejected call has a span and is not counted, and so does each call of a batch that max_tool_calls refused and each call of a reply the provider filtered (result_kind denied).

request_hash is the sha256 of the canonical JSON (canon.JSON, chapter 25) of a digest of the request: model, messages, tools, tool_choice, response_format, max_tokens, temperature, top_p and stop. It leaves out parallel_tool_calls and the provider-specific Extra, and takes model as the loop asked for it. A router may substitute a provider’s model, and the span’s model attr then names the model that answered (the response’s, else the router’s, else the loop’s). Under a router the loop’s Model is empty and the router chooses the model on its own copy of the request, so the hash covers the history, tools and sampling fields with the loop’s model and not the routed one: two routed calls to different models can share a request_hash, and a consumer keys on (request_hash, model). The hash is over a digest and not the wire bytes because the wire is the provider’s business (chapter 24) and two providers may encode one request differently. Equal hashes mean equal digests: the same model name, messages, tools and sampling fields, where the messages include the reasoning stored on assistant messages. That is the same wire request only for one provider configuration. The wire encoder drops stored reasoning unless SendReasoning is set (chapter 24; cmd/aec never sets it), so two runs whose reasoning text differs have different hashes and send the same bytes, while Extra and parallel_tool_calls, which change what the model sees, are in neither the digest nor the hash.

Bodies are not in spans. With -keep-bodies the tracer writes a model call’s request, before the call is made, and its response, after, to a file named <seq>-<kind>.jsonl in a directory beside the trace file, named like it without .jsonl, and the span’s body names it. The body holds the digest the hash was taken over, not the bytes that went on the wire. Two reasons: a response can be megabytes, and the span line is the index that a scanner reads; and the bodies carry the reader’s text, which the lines need not. A span carries hashes and a body is opt-in. A span carries a hash of the request and none of the response, so a response body cannot be checked against its span. The cost is that a trace alone cannot be replayed, and neither can the trace with its bodies, without the provider’s configuration: the digest has to be encoded again, with the same SendReasoning, Extra and parallel_tool_calls, and a different encoder version may write different bytes. The bodies support inspection. Only the model calls have bodies, so a tool’s result is in the history that the next request body holds, not in a body file of its own.

Three limits of the file. Text in names and attrs passes through Go strings as bodies that are not JSON do, so invalid UTF-8 in it is written as U+FFFD. Read takes lines of up to 16 MiB and nothing bounds an attr, so a span with an enormous attr can be written and not read back. A trace path that does not end in .jsonl puts its bodies in <path>.bodies. The approval span’s status is ok for allow, timeout for timeout and denied for every other decision (deny, mismatch, error, cancelled). A rejected call, and each call of a filtered reply, has no call_hash, because no call was decoded to hash.

The tracer maintains two invariants and the reader checks them. Seq is assigned when a span starts, under the tracer’s lock; the line is written when the span ends. Three properties follow.

(i) A valid trace is a tree, and Reconstruct finds it. Sort the spans by Seq. The tracer starts a child after its parent, so a child’s Seq is larger; Reconstruct does not assume it, it checks that every Parent names a span already seen, which is a span with a smaller Seq (it adds a span to its index only after checking its parent). Following Parent from any span therefore strictly decreases Seq, so the walk ends within nn steps, at a span with no parent. The check also refuses a span that is its own parent and a second span without a parent, so exactly one span has none: every span reaches the root, and since each span has one parent, the relation is a rooted tree. Nothing else is needed to rule out a cycle: a cycle would need an edge to a larger Seq. Reconstruct also enforces the table’s grammar: a non-empty trace id; kinds and statuses from the closed sets; a root that is a run; a run below the root only under a tool_call, a turn only under a run, every other kind only under a turn; and at most one model_call per turn. A reparented span that stays inside the grammar (a tool call moved to another turn, an edited attr) is not detected.

(ii) A crash is visible. The run span is started first (Seq 1) and ended last, after every other span of the run has ended, because each span ends before its parent does. So a file that holds the run’s line holds a line for every span the loop started, and a file that does not is a crashed run’s. Reconstruct refuses such a file, and says why through the numbering. On the arithmetic task’s golden, with the run’s line removed it reports reconstruct: seq gap: want 1, got 2; with one line removed from the middle, reconstruct: seq gap: want 4, got 5; with nothing, reconstruct: no spans (talos). The refusal is deliberate: a trajectory that stops early must not present itself as one that finished. What survives a crash is, first, the lines of the spans that had ended, which Read still parses, and second, for the spans in flight, the body files: a model call’s request line is written to its body file before the call is made. That is all. A span is written when it ends, and a tool_call span ends after every call of its batch has returned, so a tool in flight at the crash, and every call of its batch that had already finished, leave no line; an approval in flight leaves none either. Tools have no body files, and a kept response body shows the calls the model requested, not which of them ran. A file cannot say which call was running when the process died. The ledger that can is chapter 40’s, and chapter 49 says what it does with a refused trace. A gap in a file that does have its run line means a lost line, which is what a failed write is, and the tracer reports those: the first error from the span writer, from opening a body file or from closing one is kept, Tracer.Err() returns it, and cmd/aec closes the files and then exits 1 with aec: trace: … even when the run reached final. A worker must finish before its dispatching tool returns. The tracer reports a span started under a parent that has already ended, or under a parent another tracer started, as an error (Tracer.Err(), hence exit 1) and writes the span anyway, so nothing is lost silently; for a worker that outlives a tool the loop abandoned, Reconstruct still accepts the file, because the parent sits at a smaller Seq, and the error is the only report (TestWorkerStartedAfterItsDispatcherWasAbandonedIsReported). A full disk fails the run, because the file is meant to be complete. The format detects loss and does not detect tampering: a file edited consistently, with matching seq, ids and parents, passes Reconstruct, and chapter 48 chains a log of its own, of names and hashes of what the daemon did, beside the trace; traces/ itself stays editable.

(iii) Determinism. The tracer takes its clock and its id source as fields. With a fixed clock and counter ids, the bytes of a trace depend only on the sequence of Start and End calls and their attrs. Those calls come from sequential code (the run, the turn, the model call, the gate) or from toolTurn’s loops, which start the batch’s spans in wire order before any call runs and end them in wire order after all have finished; the loop’s own code starts and ends no span from a dispatch goroutine. The file’s line order is the order of End calls, so the batch’s lines come in wire order as well, and a map of attrs is written with its keys sorted. Two runs of a scripted task therefore write identical bytes, and the lab compares them. The property holds when every tool returns within the 20 ms grace of part 7: the late_result attr of an abandoned tool depends on timing, so a scripted task with a tool that ignores its context is reproducible only up to that attr. A worker loop that a dispatching tool runs does start spans from the tool’s goroutine, so the order among parallel workers is not fixed, and the bytes of such a trace are not deterministic.

Cost, a viewer, aggregation across runs and the rest of an observability stack are chapter 49’s, which reads this format and does not replace it.

The command and the fleet guard

cmd/aec is the loop with flags: a provider (-base, -model, -api-key-env, which names the variable and never prints its value) or a scripted model (-script), a tool set, limits, -trace, -keep-bodies, -approve deny|allow|tty. Its exit codes are 0 for final, 1 for an error (a trace write failure included), 2 for usage and 3 for any other stop. The final text goes to standard output and a stop’s error to standard error, and when the stream is a terminal both pass the filter of internal/termtext (chapter 42 lists it), because a model’s text or a provider’s error body can carry escape sequences that a terminal obeys (the error as one line, a newline in it escaped, so that it cannot start a line that looks like the command’s own); to a pipe or a file they are written byte for byte. Its HTTP client has a private transport that ignores HTTP_PROXY and refuses redirects, for two reasons: a proxy would answer the guard’s /models check itself and see the prompt, and a 307 would resend the prompt to a host nobody checked.

Requests to straylight and dixie go through route.Guard, a RoundTripper that is the fleet rule as code. Chapter 28 builds and lists it; cmd/aec installs it, and this is what it enforces. At llama.cpp b29c606 the router counts a sleeping model as running, so a request that names it wakes it, and autoload=false does not prevent that: it refuses only a model that is not running (chapter 21 reads server-models.h lines 94–96 and the lines in server-models.cpp that act on them). So immediately before every request that names a model, the guard sends GET /v1/models to the same server and requires that model’s status.value to be exactly loaded; anything else, a missing status included, refuses the request; and the request that does go out carries autoload=false, which stops an unloaded model from being loaded. A POST to a completion or embedding endpoint that names no model is refused as well, because the router could answer it with a model it loads. The check and the request are two round trips, so a model can change state between them, for reasons outside the caller’s control. The guard narrows the window and refuses the rest. A refusal is marked permanent, since the same request would be refused again: llm.Provider attempts it once and the run stops with the guard’s message. A failure to read the list is a transport failure, which the provider retries under its attempt budget, and each retry runs the check again.

Walkthrough

The trace types come first. Span is the line; Usage mirrors llm.Usage so that obs imports nothing from the model layer.

// Span is one record of a trace, written as one line of JSON (encoding/json
// v1, SetEscapeHTML(false)) to a trace file, <run id>.jsonl. A trace is the
// spans sharing Trace, ordered by Seq. Kind is one of run, turn, model_call,
// tool_call, policy_decision, approval. Identity lives in Attrs: a
// model_call's carry provider, model, role, finish_reason and request_hash
// (sha256 of the canonical JSON of the loop's digest of the request, {model,
// messages, tools, tool_choice, response_format, max_tokens, temperature,
// top_p, stop}: the request as the loop holds it, so it includes the
// reasoning stored on assistant messages, and it leaves out Extra and
// parallel_tool_calls; under a router the model is the loop's, not the routed
// one, so a consumer keys on request_hash and model together); a tool_call's carry tool, call_id, call_hash
// (toolcall.Call.Hash) and result_kind, and late_result when an abandoned
// tool's result arrived before the span ended; a policy_decision's carry
// policy, call_hash and decision; an approval's
// carry call_hash, decision, by and timeout_s. The run span's Status maps the
// stop reason (ok for final, cancelled, timeout for an approval timeout,
// denied for a refusal, else error) and its attrs carry stop, turns and
// calls. Bodies are not in spans: Body names a file in the body directory
// the tracer's Keep opens (cmd/aec: the trace file's name without .jsonl)
// holding the digest of a model call's request and its response, when the
// tracer is asked to keep bodies. They support inspection, not replay: the
// digest is not the bytes sent, and sending it again needs the provider's
// configuration (SendReasoning, Extra). The request line is
// written before the call is made, so a crash between request and response
// has written the request to the body file. A body that is not JSON is stored as a Go
// string, so invalid UTF-8 in it is normalised to U+FFFD: a text body is
// readable, not byte-faithful.
type Span struct {
    Trace  string            `json:"trace"`
    ID     string            `json:"id"`
    Parent string            `json:"parent,omitempty"`
    Seq    int               `json:"seq"`
    Kind   string            `json:"kind"`
    Name   string            `json:"name"`
    Start  time.Time         `json:"start"`
    End    time.Time         `json:"end"`
    Status string            `json:"status"` // ok | error | timeout | denied | cancelled
    Attrs  map[string]string `json:"attrs,omitempty"`
    Usage  *Usage            `json:"usage,omitempty"`
    Body   string            `json:"body,omitempty"`

    ended bool    // set by End under the tracer's lock; never serialised
    owner *Tracer // the tracer that started the span; never serialised
}

// Usage mirrors llm.Usage without importing llm (obs stays a leaf package).
type Usage struct {
    Prompt     int `json:"prompt_tokens"`
    Completion int `json:"completion_tokens"`
    Reasoning  int `json:"reasoning_tokens,omitempty"`
    Cached     int `json:"cached_tokens,omitempty"` // chapter 29: the provider's cached share of Prompt
}

The Tracer below is the whole writer. A nil *Tracer is usable and writes nothing, which is why the loop calls it without nil checks. Start assigns the id and Seq under the lock and inherits the trace id from the parent. Attach opens the body file through Keep on first use and writes one line per call (label, then the body as JSON, or as text when it is not JSON). End merges attrs, closes the body file and writes the line, and a second End on the same span does nothing. Every failure goes to fail, which keeps the first.

// Tracer writes spans. Now and NewID are injectable: tests pass a fixed clock
// and a counter so two runs of a scripted task write byte-identical trace
// files. Keep, when set, opens the body file a span's Attach writes to; nil
// means bodies are not kept. A nil *Tracer is usable and writes nothing; a
// Tracer built as a literal defaults Now to time.Now and NewID to RandomIDs.
//
// A Tracer records one run, and the worker runs nested under its tool_calls
// (Session.Parent): the root span's name, which must not be empty (the loop
// passes Session.ID), is the trace id, and a second root would make
// Reconstruct refuse the file.
//
// A trace is meant to be complete, so a failed write is not dropped: the first
// error from W, from Keep or from closing a body file is kept and returned
// by Err, and the caller checks it when the run ends. A span whose body file
// could not be opened never retries, so a body file is never partial without
// Err saying so.
type Tracer struct {
    W     io.Writer
    Now   func() time.Time
    NewID func() string
    Keep  func(name string) (io.WriteCloser, error)

    mu     sync.Mutex
    seq    int
    trace  string
    err    error
    bodies map[*Span]io.WriteCloser // a nil value: Keep failed for this span
}

// Err returns the first error the tracer met writing a span line or a body
// file, or nil. It is safe to call at any time and on a nil *Tracer.
func (t *Tracer) Err() error {
    if t == nil {
        return nil
    }
    t.mu.Lock()
    defer t.mu.Unlock()
    return t.err
}

// fail keeps the first error. The caller holds t.mu.
func (t *Tracer) fail(err error) {
    if t.err == nil {
        t.err = err
    }
}

// validKind reports whether kind is non-empty and made of [a-z_] only, so it
// is safe inside a file name.
func validKind(kind string) bool {
    if kind == "" {
        return false
    }
    for _, c := range kind {
        if (c < 'a' || c > 'z') && c != '_' {
            return false
        }
    }
    return true
}

// NewTracer writes to w with the real clock and random ids.
func NewTracer(w io.Writer) *Tracer {
    return &Tracer{W: w, Now: time.Now, NewID: RandomIDs(), bodies: map[*Span]io.WriteCloser{}}
}

// RandomIDs returns an id generator of 16 hex characters from crypto/rand.
func RandomIDs() func() string {
    return func() string {
        var b [8]byte
        if _, err := rand.Read(b[:]); err != nil {
            panic(err)
        }
        return hex.EncodeToString(b[:])
    }
}

// CounterIDs returns an id generator prefix1, prefix2, ... for deterministic
// traces.
func CounterIDs(prefix string) func() string {
    n := 0
    var mu sync.Mutex
    return func() string {
        mu.Lock()
        defer mu.Unlock()
        n++
        return fmt.Sprintf("%s%d", prefix, n)
    }
}

// FixedClock returns a clock that always reads t.
func FixedClock(t time.Time) func() time.Time { return func() time.Time { return t } }

// Start opens a span. The first span's name is the trace id when parent is
// nil and the tracer has no trace yet; later spans inherit the trace. Seq is
// assigned here, under the tracer's lock, so a caller that starts spans in a
// chosen order gets that order. A parent that has already ended, or that
// another Tracer started, is an error (see Err); the span is still written.
func (t *Tracer) Start(parent *Span, kind, name string) *Span {
    if t == nil {
        return &Span{Kind: kind, Name: name}
    }
    t.mu.Lock()
    defer t.mu.Unlock()
    if t.bodies == nil {
        t.bodies = map[*Span]io.WriteCloser{}
    }
    if t.Now == nil {
        t.Now = time.Now
    }
    if t.NewID == nil {
        t.NewID = RandomIDs()
    }
    t.seq++
    s := &Span{ID: t.NewID(), Seq: t.seq, Kind: kind, Name: name, Start: t.Now().UTC(), owner: t}
    if parent != nil {
        // The child is still written, so nothing is lost silently; the tracer
        // reports the misuse through Err (and cmd/aec exits 1).
        switch {
        case parent.owner != t:
            t.fail(fmt.Errorf("trace: span %s (%s) was started under span %s, which belongs to another tracer", s.ID, kind, parent.ID))
        case parent.ended:
            t.fail(fmt.Errorf("trace: span %s (%s) was started under span %s, which has already ended", s.ID, kind, parent.ID))
        }
        s.Parent = parent.ID
        s.Trace = parent.Trace
    } else if t.trace == "" {
        t.trace = name
        s.Trace = name
    } else {
        s.Trace = t.trace
    }
    return s
}

// Attach records body bytes for a span: one line {"label": label, "body":
// <body as JSON>} (or "text" when body is not JSON) in the span's body file,
// opened through Keep on the first call and named <seq>-<kind>.jsonl. With no
// Keep it does nothing. Attach on a span that has ended, or whose kind is not
// lowercase letters and underscores, is an error (see Err) and writes
// nothing: a late Attach never reopens a body file.
func (t *Tracer) Attach(s *Span, label string, body []byte) {
    if t == nil || t.Keep == nil {
        return
    }
    t.mu.Lock()
    defer t.mu.Unlock()
    if s.ended {
        t.fail(fmt.Errorf("trace: attach %q to span %s after it ended", label, s.ID))
        return
    }
    if !validKind(s.Kind) {
        t.fail(fmt.Errorf("trace: span %s has kind %q, which cannot name a body file", s.ID, s.Kind))
        return
    }
    w, ok := t.bodies[s]
    if !ok {
        name := fmt.Sprintf("%04d-%s.jsonl", s.Seq, s.Kind)
        var err error
        w, err = t.Keep(name)
        if err != nil {
            t.bodies[s] = nil
            t.fail(fmt.Errorf("trace: open body file %s: %w", name, err))
            return
        }
        t.bodies[s] = w
        s.Body = name
    }
    if w == nil {
        return // Keep failed for this span; the error is already kept
    }
    rec := map[string]any{"label": label}
    if json.Valid(body) {
        rec["body"] = json.RawMessage(body)
    } else {
        rec["text"] = string(body)
    }
    enc := json.NewEncoder(w)
    enc.SetEscapeHTML(false)
    if err := enc.Encode(rec); err != nil {
        t.fail(fmt.Errorf("trace: write body file %s: %w", s.Body, err))
    }
}

// End closes a span and writes its line. attrs are merged into the span's;
// usage is set when non-nil. A second End on the same span does nothing.
func (t *Tracer) End(s *Span, status string, attrs map[string]string, usage *Usage) {
    if t == nil {
        return
    }
    t.mu.Lock()
    defer t.mu.Unlock()
    if s.ended {
        return
    }
    s.ended = true
    if t.Now == nil {
        t.Now = time.Now
    }
    s.End = t.Now().UTC()
    s.Status = status
    if len(attrs) > 0 {
        if s.Attrs == nil {
            s.Attrs = map[string]string{}
        }
        for k, v := range attrs {
            s.Attrs[k] = v
        }
    }
    if usage != nil {
        s.Usage = usage
    }
    if w, ok := t.bodies[s]; ok {
        if w != nil {
            if err := w.Close(); err != nil {
                t.fail(fmt.Errorf("trace: close body file %s: %w", s.Body, err))
            }
        }
        delete(t.bodies, s)
    }
    if t.W == nil {
        return
    }
    enc := json.NewEncoder(t.W)
    enc.SetEscapeHTML(false)
    if err := enc.Encode(s); err != nil {
        t.fail(fmt.Errorf("trace: write span %s: %w", s.ID, err))
    }
}

Reconstruct is property (i) and the refusals of (ii) as code. The comment inside the loop is the proof’s key step: the index holds only spans with a smaller Seq when the parent is looked up.

// Read parses a trace file, one span per line.
func Read(r io.Reader) ([]Span, error) {
    var spans []Span
    sc := bufio.NewScanner(r)
    sc.Buffer(make([]byte, 0, 64*1024), 16*1024*1024)
    line := 0
    for sc.Scan() {
        line++
        b := bytes.TrimSpace(sc.Bytes())
        if len(b) == 0 {
            continue
        }
        var s Span
        if err := json.Unmarshal(b, &s); err != nil {
            return nil, fmt.Errorf("trace line %d: %w", line, err)
        }
        spans = append(spans, s)
    }
    if err := sc.Err(); err != nil {
        return nil, err
    }
    return spans, nil
}

// Trajectory is one trace as a tree: Root is the run span, Children maps a
// span id to its children in Seq order.
type Trajectory struct {
    Root     *Span
    Children map[string][]*Span
}

// Reconstruct orders one trace's spans by Seq and nests them by Parent. It
// refuses a Parent that is not in the trace, a Seq gap (Seq must run 1..n
// after sorting, so a span lost to a crash is detected), a duplicate id or
// Seq, a span that is its own parent, a parent that starts after its child,
// more than one root, spans from two traces, and anything outside the
// grammar of chapter 26's table: an empty trace id, a kind or status outside
// the closed sets, a root that is not a run, a parent of the wrong kind (a
// run sits at the root or under a tool_call, a turn under a run, every other
// kind under a turn), or a turn with two model_calls. It checks structure,
// not integrity: a file edited consistently passes (chapter 48 chains a log of names and hashes beside it; this file stays editable).
func Reconstruct(spans []Span) (Trajectory, error) {
    if len(spans) == 0 {
        return Trajectory{}, fmt.Errorf("reconstruct: no spans")
    }
    sorted := make([]*Span, len(spans))
    for i := range spans {
        sorted[i] = &spans[i]
    }
    sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].Seq < sorted[j].Seq })
    byID := make(map[string]*Span, len(sorted))
    tr := Trajectory{Children: map[string][]*Span{}}
    for i, s := range sorted {
        if i > 0 && s.Seq == sorted[i-1].Seq {
            return Trajectory{}, fmt.Errorf("reconstruct: duplicate seq %d", s.Seq)
        }
        if s.Seq != i+1 {
            return Trajectory{}, fmt.Errorf("reconstruct: seq gap: want %d, got %d", i+1, s.Seq)
        }
        if s.Trace == "" {
            return Trajectory{}, fmt.Errorf("reconstruct: span %s has an empty trace id", s.ID)
        }
        if !validKinds[s.Kind] {
            return Trajectory{}, fmt.Errorf("reconstruct: span %s has unknown kind %q", s.ID, s.Kind)
        }
        if !validStatuses[s.Status] {
            return Trajectory{}, fmt.Errorf("reconstruct: span %s has unknown status %q", s.ID, s.Status)
        }
        if s.Trace != sorted[0].Trace {
            return Trajectory{}, fmt.Errorf("reconstruct: span %s belongs to trace %q, not %q", s.ID, s.Trace, sorted[0].Trace)
        }
        if _, dup := byID[s.ID]; dup {
            return Trajectory{}, fmt.Errorf("reconstruct: duplicate id %q", s.ID)
        }
        if s.Parent == "" {
            if tr.Root != nil {
                return Trajectory{}, fmt.Errorf("reconstruct: two roots, %q and %q", tr.Root.ID, s.ID)
            }
            if s.Kind != "run" {
                return Trajectory{}, fmt.Errorf("reconstruct: the root span %s is a %s, not a run", s.ID, s.Kind)
            }
            byID[s.ID] = s
            tr.Root = s
            continue
        }
        if s.Parent == s.ID {
            return Trajectory{}, fmt.Errorf("reconstruct: span %s is its own parent", s.ID)
        }
        // byID holds only spans with a smaller Seq (s is added after this
        // check), so a parent found here started before its child; one not
        // found is absent or started later. Every parent edge therefore
        // points to a smaller Seq, which leaves no cycle.
        if _, ok := byID[s.Parent]; !ok {
            return Trajectory{}, fmt.Errorf("reconstruct: span %s has parent %q, which is not in the trace before it", s.ID, s.Parent)
        }
        if err := checkParentKind(s, byID[s.Parent]); err != nil {
            return Trajectory{}, err
        }
        if s.Kind == "model_call" {
            for _, sib := range tr.Children[s.Parent] {
                if sib.Kind == "model_call" {
                    return Trajectory{}, fmt.Errorf("reconstruct: turn %s has two model_calls, %s and %s", s.Parent, sib.ID, s.ID)
                }
            }
        }
        byID[s.ID] = s
        tr.Children[s.Parent] = append(tr.Children[s.Parent], s)
    }
    if tr.Root == nil {
        return Trajectory{}, fmt.Errorf("reconstruct: no root span")
    }
    return tr, nil
}

var validKinds = map[string]bool{"run": true, "turn": true, "model_call": true, "tool_call": true, "policy_decision": true, "approval": true}

var validStatuses = map[string]bool{"ok": true, "error": true, "timeout": true, "denied": true, "cancelled": true}

// checkParentKind enforces the table: a run under a tool_call (a worker run
// of chapter 45), a turn under a run, every other kind under a turn.
func checkParentKind(s, parent *Span) error {
    ok := false
    switch s.Kind {
    case "run":
        ok = parent.Kind == "tool_call"
    case "turn":
        ok = parent.Kind == "run"
    default:
        ok = parent.Kind == "turn"
    }
    if !ok {
        return fmt.Errorf("reconstruct: a %s span (%s) cannot be the child of a %s (%s)", s.Kind, s.ID, parent.Kind, parent.ID)
    }
    return nil
}

The loop’s interfaces are three. Tool is what chapter 27 implements: Call never returns a Go error, a failure is a Result the model reads, and the optional Timeouter, Idempotent and Marked change how the loop treats a tool.

// Tool is what the loop dispatches to. Call never returns a Go error: a
// failure is a Result the model observes (chapter 27's "errors as
// observations"). The loop enforces ctx and the tool's timeout.
type Tool interface {
    Spec() llm.Tool
    Call(ctx context.Context, call toolcall.Call) Result
}

// Result is a tool's observation. Kind is one of ok, error, timeout, denied,
// cancelled, empty. Parts is never nil for Kind ok: a tool with nothing to
// say says so in text ("no results for ..."), because an empty observation
// reads as success (chapter 27's "absence collapses into success"); the loop
// repairs an ok Result without parts into Kind empty.
type Result struct {
    Kind     string
    Parts    []llm.Part
    IsError  bool
    Duration time.Duration
}

// Optional tool interfaces chapter 27 defines and the loop honours.

// Timeouter sets a tool's Call deadline; without it, DefaultTimeout (30 s).
type Timeouter interface{ Timeout() time.Duration }

// Idempotent says a repeated call (same Hash within a run) may be answered
// from the first call's Result without running the tool again.
type Idempotent interface{ Idempotent() bool }

// Marked says a call needs the reader's approval before it runs, and why
// (chapter 27's approval marking).
type Marked interface {
    NeedsApproval(call toolcall.Call) (bool, string)
}

Loop is the configuration; its zero values are defaults (MaxTurns 20, MaxToolCalls 50, ApprovalTimeout 60 s). Policy is a plain function so that chapter 47’s gate can be one without a new type. PolicyContext is chapter 53’s: the same hook with the turn’s context. Context is chapter 29’s: the budget manager, and later chapter 31’s compactor, run before each model call. MaxTokens is chapter 53’s too: the completion cap each request carries (llm.Request.MaxTokens, and so the digest and request_hash below see it); 0, the default, sets none, and every request of the loop is the bytes it was without the field (an OpenAI-dialect route then sends no max_tokens; an Anthropic-dialect route, whose API requires one, sends its own 1024). Session holds the messages the loop extends in place, and Private and Role are read by the router. Ledger is chapter 40’s hook, nil in every run of Parts IV to VI. Parent is chapter 45’s hook: a dispatching tool takes its own tool_call span from agent.CallSpan(ctx) and runs a worker loop, on the same tracer, with that span as the worker session’s Parent, so the worker’s run span hangs under the call that started it and the whole file is still one tree (TestWorkerRunNestsUnderTheDispatchingToolCall).

// Loop is aec v0. Router (chapter 28) picks the model per turn; nil means
// Model on Client. Policy (chapter 47) runs before Marked tools, as does
// PolicyContext (chapter 53), which is Policy with the turn's context and is
// called in its place when both are set; both nil means no policy. Clock and
// Tracer are injectable. ApprovalTimeout bounds an Approver's silence; zero
// means DefaultApprovalTimeout. NewID draws the approval nonces
// (ApprovalRequest.ID): nil means random 64-bit ids from crypto/rand, the
// loop's own source and not the tracer's, so approvals work without a Tracer.
// Tests and deterministic runs pass obs.CounterIDs, whose nonces repeat from
// run to run.
type Loop struct {
    Client          llm.Client
    Model           string
    Tools           []Tool
    MaxTurns        int      // default 20
    MaxToolCalls    int      // default 50 per run
    Approver        Approver // nil: a marked call is denied
    OnTimeout       OnTimeout
    ApprovalTimeout time.Duration
    Router          Router // chapter 28's interface
    Policy          func(toolcall.Call) Decision
    Tracer          *obs.Tracer
    Clock           func() time.Time
    NewID           func() string
    // Context (chapter 29's budget, chapter 31's compaction) runs at the start
    // of every turn, before the model call and never inside a tool batch, and
    // may replace Session.Messages. It must keep the history wire-valid: an
    // assistant message with tool_calls stays with every tool reply it
    // received. Its decision is a policy_decision span named "context"; Action
    // Refuse ends the run with Stop.Reason context_exceeded. nil: no manager.
    Context ContextManager
    // Ledger (chapter 40) is told each batch before it is dispatched and each
    // call when it ends; nil: nothing is recorded. See ledger.go.
    Ledger Ledger
    // PolicyContext (chapter 53) is Policy with the turn's context: a model
    // check in flight ends when the turn is cancelled. When both are set,
    // PolicyContext is called and Policy is not. nil: Policy, as before.
    PolicyContext func(ctx context.Context, call toolcall.Call) Decision
    // MaxTokens (chapter 53) is the completion cap every model request of the
    // run carries (llm.Request.MaxTokens), and so is part of the request hash.
    // 0, the default, sets none in the request: it is the bytes it was before
    // the field existed, so an OpenAI-dialect route sends no max_tokens, while
    // an Anthropic-dialect route, whose API requires one, sends its own
    // default (1024) on the wire. Whatever the cap, a final reply the server
    // ended with finish_reason "length" (an Anthropic max_tokens stop too) is
    // Stop.Truncated.
    MaxTokens int
}

// Decision is a policy's answer about one call.
type Decision struct {
    Allow        bool
    NeedApproval bool
    Reason       string
}

// Session is the conversation the loop extends in place. ID names the trace.
// Private marks a session whose text is to reach no model provider the routes
// file does not mark local (route eligibility); Role forces a role for every turn when set.
type Session struct {
    ID       string
    Messages []llm.Message
    Private  bool
    Role     string
    // Parent, when set, is the span the run span is started under: a
    // dispatching tool_call of a parent run (chapter 45's worker hook). The
    // worker loop must share the parent's Tracer, so the whole file is one
    // trace that Reconstruct accepts; nil, the default, makes the run span the
    // root.
    Parent *obs.Span
}

// Stop says why Run returned. Reason is one of final, max_turns,
// max_tool_calls, cancelled, approval_timeout, refused, error. Final is the
// assistant's last text when Reason is final.
type Stop struct {
    Reason string
    Final  string
    Turns  int
    Calls  int
    Err    error
    // Truncated says a final reply ended with finish_reason "length": the
    // text is cut at the completion cap or the context, and is not an answer
    // that ended. False for every other stop and every other finish.
    Truncated bool `json:",omitempty"`
}

Router is chapter 28’s seam. route.Router satisfies it, and agent does not import route, so the loop builds and tests with a single client and nothing else.

// Router is what chapter 28 plugs in (route.Router satisfies it; agent does
// not import route). The loop builds the RouteRequest from the session: Text
// is the user message's text parts joined by newlines, HasImage is true when
// any part of the user message is image_url or input_audio, Private is
// Session.Private, Force is Session.Role. Complete and Stream set the
// llm.Request's Model to each provider's configured model as they walk the
// chain, so Loop.Model is ignored when Router is set.
type Router interface {
    Route(ctx context.Context, req RouteRequest) RouteDecision
    Complete(ctx context.Context, req RouteRequest, call llm.Request) (*llm.Response, RouteDecision, error)
    Stream(ctx context.Context, req RouteRequest, call llm.Request) (llm.Stream, RouteDecision, error)
}

// RouteRequest is what the loop knows before choosing a model.
type RouteRequest struct {
    Text     string
    HasImage bool
    Private  bool
    Force    string // a role name; "" lets the gate choose
}

// RouteDecision is written as a policy_decision span named "route" with
// attrs role, source, calibrated, fail_open and probabilities (canon.JSON).
// Provider and Model, when the router fills them, name the provider that
// answered and the model it was asked for; the model_call span carries
// them (Model only when the response names none).
type RouteDecision struct {
    Role          string
    Source        string // gate | forced | single | private | fail_open | disabled
    Calibrated    bool
    FailOpen      bool
    Probabilities map[string]float64
    Provider      string
    Model         string
    Err           error
}

Run is part 1 of the turn rule. It builds the user message and calls RunMessage, which chapter 40’s daemon calls with a message it built itself; a message that is not a user message is refused (ErrNotUser) before anything is appended or traced. RunMessage owns the run span and its closing attrs; turnsUntilStop is the loop proper, with one return per stop reason. r.assistant keeps the message whose calls the tool turn answers, for chapter 40’s Ledger. Every path that ends a turn ends its span first, with the status the stop maps to.

// Run extends s with user and then turns until a stop condition holds: a
// turn is one model call; a response with tool calls has each call decoded,
// policy-checked, approval-gated when marked, and dispatched (parallel calls
// run concurrently, results appended in call order); a response without
// tool calls is final. Every model call, tool call, policy decision and
// approval writes a span.
func (l *Loop) Run(ctx context.Context, s *Session, user string) Stop {
    stop, _ := l.RunMessage(ctx, s, llm.Text(llm.User, user))
    return stop
}

// RunMessage is Run with the inbound message given whole (chapter 40's daemon
// builds it: a fenced peer's text, an image part); the message must be a
// user message, else nothing runs and the error says so. Run(ctx, s, user)
// is RunMessage(ctx, s, llm.Text(llm.User, user)), byte for byte in the
// trace.
func (l *Loop) RunMessage(ctx context.Context, s *Session, msg llm.Message) (Stop, error) {
    if msg.Role != llm.User {
        return Stop{Reason: StopError, Err: ErrNotUser}, ErrNotUser
    }
    r := &run{l: l, s: s, byName: map[string]Tool{}, cache: map[string]Result{}, ids: l.NewID}
    if r.ids == nil {
        r.ids = obs.RandomIDs()
    }
    for _, t := range l.Tools {
        spec := t.Spec()
        r.specs = append(r.specs, spec)
        r.byName[spec.Name] = t
    }
    s.Messages = append(s.Messages, msg)
    r.route = routeRequest(s)
    span := l.Tracer.Start(s.Parent, "run", s.ID)
    stop := r.turnsUntilStop(ctx, span)
    stop.Turns, stop.Calls = r.turns, r.calls
    var usage *obs.Usage
    if r.sawUsage {
        u := r.usage
        usage = &u
    }
    l.Tracer.End(span, runStatus(stop), map[string]string{
        "stop": stop.Reason, "turns": strconv.Itoa(r.turns), "calls": strconv.Itoa(r.calls),
    }, usage)
    return stop, nil
}

func (r *run) turnsUntilStop(ctx context.Context, runSpan *obs.Span) Stop {
    maxTurns := r.l.MaxTurns
    if maxTurns <= 0 {
        maxTurns = DefaultMaxTurns
    }
    for {
        if r.turns >= maxTurns {
            return Stop{Reason: StopMaxTurns}
        }
        r.turns++
        turn := r.l.Tracer.Start(runSpan, "turn", strconv.Itoa(r.turns))
        if stop := r.prepareContext(ctx, turn); stop != nil {
            r.l.Tracer.End(turn, runStatus(*stop), nil, nil)
            return *stop
        }
        resp, stop := r.modelCall(ctx, turn)
        if stop != nil {
            r.l.Tracer.End(turn, runStatus(*stop), nil, nil)
            return *stop
        }
        r.s.Messages = append(r.s.Messages, resp.Message)
        if resp.FinishReason == "content_filter" {
            // The calls of a filtered message are not looked at, but they are
            // answered, so the history stays well formed.
            r.s.Messages = append(r.s.Messages, r.refuseCalls(turn, resp.Message.ToolCalls)...)
            r.l.Tracer.End(turn, "denied", nil, nil)
            return Stop{Reason: StopRefused, Final: textOf(resp.Message)}
        }
        if len(resp.Message.ToolCalls) == 0 {
            r.l.Tracer.End(turn, "ok", nil, nil)
            return Stop{Reason: StopFinal, Final: textOf(resp.Message), Truncated: resp.FinishReason == "length"}
        }
        r.assistant = resp.Message
        replies, stop := r.toolTurn(ctx, turn, resp.Message.ToolCalls)
        r.s.Messages = append(r.s.Messages, replies...)
        if stop != nil {
            r.l.Tracer.End(turn, runStatus(*stop), nil, nil)
            return *stop
        }
        r.l.Tracer.End(turn, "ok", nil, nil)
    }
}

The model call is where request_hash comes from. requestDigest is the digest of the Mechanism section, and RequestHash canonicalises it. With a router, a route span is started before the model_call span, so its Seq precedes the call it chose; the request body is attached before the call and the response body after it, so a crash between the two leaves the request on disk. The switch is the model rule: the response’s model, else the router’s, else the loop’s, else no attr, never an empty one.

// requestDigest is the request as hashed for the model_call span: the
// fields that decide what the model sees, in canonical JSON.
type requestDigest struct {
    Model          string              `json:"model"`
    Messages       []llm.Message       `json:"messages"`
    Tools          []llm.Tool          `json:"tools,omitempty"`
    ToolChoice     *llm.ToolChoice     `json:"tool_choice,omitempty"`
    ResponseFormat *llm.ResponseFormat `json:"response_format,omitempty"`
    MaxTokens      int                 `json:"max_tokens,omitempty"`
    Temperature    *float64            `json:"temperature,omitempty"`
    TopP           *float64            `json:"top_p,omitempty"`
    Stop           []string            `json:"stop,omitempty"`
}

// RequestHash is the sha256 (lowercase hex) of the canonical JSON of the
// request's digest, and the digest bytes themselves.
func RequestHash(req llm.Request) (string, []byte, error) {
    d := requestDigest{Model: req.Model, Messages: req.Messages, Tools: req.Tools, ToolChoice: req.ToolChoice,
        ResponseFormat: req.ResponseFormat, MaxTokens: req.MaxTokens, Temperature: req.Temperature, TopP: req.TopP, Stop: req.Stop}
    raw, err := json.Marshal(d)
    if err != nil {
        return "", nil, err
    }
    c, err := canon.JSON(json.RawMessage(raw))
    if err != nil {
        return "", nil, err
    }
    sum := sha256.Sum256(c)
    return hex.EncodeToString(sum[:]), c, nil
}

// modelCall makes the turn's one model call and writes its span. A Router,
// when set, chooses the model and is traced as a policy_decision named
// "route" started before the call, so its Seq precedes the call it chose.
func (r *run) modelCall(ctx context.Context, turn *obs.Span) (*llm.Response, *Stop) {
    req := llm.Request{Model: r.l.Model, Messages: append([]llm.Message(nil), r.s.Messages...), Tools: r.specs, MaxTokens: r.l.MaxTokens}
    hash, body, err := RequestHash(req)
    if err != nil {
        return nil, &Stop{Reason: StopError, Err: err}
    }
    attrs := map[string]string{"request_hash": hash}
    var routeSpan *obs.Span
    if r.l.Router != nil {
        routeSpan = r.l.Tracer.Start(turn, "policy_decision", "route")
    }
    span := r.l.Tracer.Start(turn, "model_call", providerName(r.l.Client))
    if span.Name != "" {
        attrs["provider"] = span.Name // set before the call, so a failed call names its provider
    }
    r.l.Tracer.Attach(span, "request", body)
    var resp *llm.Response
    var dec RouteDecision
    if r.l.Router != nil {
        resp, dec, err = r.l.Router.Complete(ctx, r.route, req)
        r.l.Tracer.End(routeSpan, routeStatus(dec), routeAttrs(dec), nil)
        if dec.Role != "" {
            attrs["role"] = dec.Role
        }
        if dec.Provider != "" {
            span.Name = dec.Provider
            attrs["provider"] = dec.Provider
        }
    } else {
        resp, err = r.l.Client.Complete(ctx, req)
    }
    if err != nil {
        if ctx.Err() != nil {
            r.l.Tracer.End(span, "cancelled", attrs, nil)
            return nil, &Stop{Reason: StopCancelled, Err: ctx.Err()}
        }
        attrs["error"] = err.Error()
        r.l.Tracer.End(span, "error", attrs, nil)
        return nil, &Stop{Reason: StopError, Err: err}
    }
    if resp == nil {
        err = errors.New("client returned no response")
        attrs["error"] = err.Error()
        r.l.Tracer.End(span, "error", attrs, nil)
        return nil, &Stop{Reason: StopError, Err: err}
    }
    r.l.Tracer.Attach(span, "response", resp.Raw)
    // The model that answered: the response's; else, on a routed call, the
    // one the router asked for (the router chose on its own copy of the
    // request, so req.Model says nothing there); else the loop's own; else
    // the attr is left out rather than naming a model nobody asked.
    switch {
    case resp.Model != "":
        attrs["model"] = resp.Model
    case dec.Model != "":
        attrs["model"] = dec.Model
    case req.Model != "":
        attrs["model"] = req.Model
    }
    attrs["finish_reason"] = resp.FinishReason
    var usage *obs.Usage
    if resp.Usage != nil {
        usage = &obs.Usage{Prompt: resp.Usage.Prompt, Completion: resp.Usage.Completion, Reasoning: resp.Usage.Reasoning, Cached: resp.Usage.Cached}
        r.usage.Prompt += usage.Prompt
        r.usage.Completion += usage.Completion
        r.usage.Reasoning += usage.Reasoning
        r.usage.Cached += usage.Cached
        r.sawUsage = true
    }
    r.l.Tracer.End(span, "ok", attrs, usage)
    return resp, nil
}

toolTurn is parts 3 to 7. The first loop pairs wire calls with decoded calls (Decode returns, in order, the calls that passed, so next indexes them) and answers the rejected ones; the deep copy of the arguments is the first line of the ownership rule. The budget check follows, and notRun is the text part 6 gives. Each call’s tool_call span is started, in wire order, just before that call’s gate, so the policy_decision and approval spans of call ii fall between its tool_call span and the next call’s in Seq order, and every span is started before any call runs; the gate is chapter 27’s listing (gate, with rebind and approve) and the dispatch is its dispatch and callOne. After a stop, every call not yet settled is filled in with deniedResult(notRun). The last loop appends the replies in wire order and ends the spans, with the status derived from the result’s kind and the result_kind attr set to it unless the gate set rejected already. The last three fields of pending (marked, nonce, rec) carry the approval binding and the call’s record to chapter 40’s ledger.

// repairable are toolcall's defect kinds that still yield a Call.
var repairable = map[string]bool{"fenced": true, "nested_string": true, "trailing_text": true}

// pending is one call of a turn on its way through policy, approval and
// dispatch.
type pending struct {
    wire  llm.ToolCall
    call  *toolcall.Call // nil when the wire call did not decode
    tool  Tool
    span  *obs.Span
    attrs map[string]string
    res   Result
    done  bool // res is final; nothing to dispatch
    // late is set when the loop stopped waiting for the tool; it receives
    // the tool's result if one ever comes. Only the loop reads it.
    late chan toolOutcome
    // marked and nonce are the approval binding the gate established, for
    // the Ledger's CallRecord (chapter 40); rec is that record once dispatch
    // built it, and is what End reports.
    marked bool
    nonce  string
    rec    CallRecord
}

// toolOutcome is what a tool's goroutine hands back.
type toolOutcome struct {
    res      Result
    panicked string
}

// toolTurn answers every tool call of one assistant message, in wire
// order: a call that did not decode is answered with its Problems; a call
// the policy or an approval denies is answered denied; the rest run
// concurrently. It returns the tool messages and a Stop when the turn ends
// the run (budget, approval timeout, cancellation).
func (r *run) toolTurn(ctx context.Context, turn *obs.Span, wire []llm.ToolCall) ([]llm.Message, *Stop) {
    calls, problems := toolcall.Decode(wire, r.specs)
    byIndex := map[int][]toolcall.Problem{}
    for _, p := range problems {
        byIndex[p.Index] = append(byIndex[p.Index], p)
    }
    ps := make([]*pending, len(wire))
    next := 0
    for i, w := range wire {
        p := &pending{wire: w, attrs: map[string]string{"tool": w.Name, "call_id": w.ID}}
        ps[i] = p
        fatal := false
        for _, pr := range byIndex[i] {
            if !repairable[pr.Kind] {
                fatal = true
            }
        }
        if fatal || next >= len(calls) {
            kinds := make([]string, 0, len(byIndex[i]))
            var text strings.Builder
            text.WriteString("error: tool call rejected")
            for _, pr := range byIndex[i] {
                kinds = append(kinds, pr.Kind)
                fmt.Fprintf(&text, "; %s: %s", pr.Kind, pr.Detail)
            }
            p.attrs["result_kind"] = "rejected"
            p.attrs["problems"] = strings.Join(kinds, ",")
            p.res = Result{Kind: KindError, IsError: true, Parts: []llm.Part{{Type: "text", Text: text.String()}}}
            p.done = true
            continue
        }
        c := calls[next]
        next++
        // Arguments is a map, so a Call passed by value still shares it with
        // the policy, the approver and the tool: the loop owns this copy and
        // rehashes it before dispatch (see rebind).
        c.Arguments = cloneArgs(c.Arguments)
        p.call = &c
        p.tool = r.byName[c.Name]
        p.attrs["call_hash"] = c.Hash
        if c.Repaired {
            p.attrs["repaired"] = "true"
        }
    }
    decoded := 0
    for _, p := range ps {
        if p.call != nil {
            decoded++
        }
    }
    maxCalls := r.l.MaxToolCalls
    if maxCalls <= 0 {
        maxCalls = DefaultMaxToolCalls
    }
    // A batch that would exceed the budget ends the run, but every call of it
    // is still answered (denied, not counted), so the session stays
    // wire-valid and resumable.
    var abort *Stop
    notRun := "not run: the run was aborted before this call ran"
    if r.calls+decoded > maxCalls {
        abort = &Stop{Reason: StopMaxToolCalls}
        notRun = "not run: max_tool_calls reached"
    } else {
        r.calls += decoded
    }
    // Spans start in wire order, before anything runs, so Seq is the
    // model's order whatever the dispatch order.
    for _, p := range ps {
        p.span = r.l.Tracer.Start(turn, "tool_call", p.wire.Name)
        if p.done || abort != nil {
            continue
        }
        if stop := r.gate(ctx, turn, p); stop != nil {
            abort = stop
        }
    }
    if abort != nil {
        // Whatever the gate did not already settle is answered, not left
        // empty: an empty observation reads as success. An approval attr the
        // call earned stays.
        for _, p := range ps {
            if !p.done {
                p.res = deniedResult(notRun)
                p.attrs["result_kind"] = KindDenied
                p.done = true
            }
        }
    } else if ctx.Err() != nil {
        // The run has ended (cancelled, or its deadline passed) while the gates
        // ran, or the model's answer was already on the wire when it was
        // cancelled: no call of this batch starts and the Ledger hears of none,
        // so a cancelled run cannot run a tool after the cancel. Each call is
        // answered as one cancelled in flight is.
        for _, p := range ps {
            if !p.done {
                p.res = Result{Kind: KindCancelled, IsError: true, Parts: []llm.Part{{Type: "text", Text: "cancelled"}}}
                p.done = true
            }
        }
    } else {
        r.dispatch(ctx, ps)
    }
    replies := make([]llm.Message, 0, len(ps))
    for _, p := range ps {
        status := "ok"
        switch p.res.Kind {
        case KindError, KindTimeout, KindDenied, KindCancelled:
            status = p.res.Kind
        }
        if p.attrs["result_kind"] == "" {
            p.attrs["result_kind"] = p.res.Kind
        }
        if p.attrs["result_kind"] == "rejected" {
            status = "error"
        }
        if p.late != nil {
            // The tool was abandoned. If its result has come in by now, say
            // so in the span; the goroutine itself never touches the tracer,
            // and a result that comes after this point is dropped.
            select {
            case <-p.late:
                p.attrs["late_result"] = "arrived after the tool was abandoned, discarded"
            default:
            }
        }
        r.l.Tracer.End(p.span, status, p.attrs, nil)
        replies = append(replies, llm.Message{Role: llm.ToolRole, ToolCallID: p.wire.ID, Name: p.wire.Name, Parts: p.res.Parts, IsError: p.res.IsError})
    }
    if abort != nil {
        return replies, abort
    }
    if ctx.Err() != nil {
        return replies, &Stop{Reason: StopCancelled, Err: ctx.Err()}
    }
    return replies, nil
}

A scripted model is how every trace in this chapter is reproducible. ScriptStep is what the wire would deliver, less the envelope; Fake turns a script into an llm.Fake whose responses carry the step as their Raw, so a kept body shows what was scripted.

// ScriptStep is one scripted model answer, as a JSON file for llm.Fake:
// what the wire would deliver, less the envelope. FinishReason defaults to
// "tool_calls" when ToolCalls is set and "stop" otherwise. Error, when set,
// makes the step fail with that message (and Status makes it a
// *llm.StatusError).
type ScriptStep struct {
    Content      string         `json:"content,omitempty"`
    ToolCalls    []llm.ToolCall `json:"tool_calls,omitempty"`
    FinishReason string         `json:"finish_reason,omitempty"`
    Usage        *llm.Usage     `json:"usage,omitempty"`
    Error        string         `json:"error,omitempty"`
    Status       int            `json:"status,omitempty"`
}

// Script is a scripted task: the user's text and the model's answers.
type Script struct {
    Task  string       `json:"task"`
    Steps []ScriptStep `json:"steps"`
}

// LoadScript reads a Script file.
func LoadScript(path string) (*Script, error) {
    b, err := os.ReadFile(path)
    if err != nil {
        return nil, err
    }
    var s Script
    if err := json.Unmarshal(b, &s); err != nil {
        return nil, fmt.Errorf("%s: %w", path, err)
    }
    if len(s.Steps) == 0 {
        return nil, fmt.Errorf("%s: no steps", path)
    }
    return &s, nil
}

// Fake builds the llm.Fake that answers the script, step by step. Each
// response's Raw is the step as JSON, so a kept body shows what was
// scripted; its ID is fake-N.
func (s *Script) Fake() *llm.Fake {
    f := &llm.Fake{}
    for i, st := range s.Steps {
        if st.Error != "" {
            f.Script = append(f.Script, llm.Step{Err: fmt.Errorf("%s", st.Error), Status: st.Status})
            continue
        }
        m := llm.Message{Role: llm.Assistant, ToolCalls: st.ToolCalls}
        if st.Content != "" {
            m.Parts = []llm.Part{{Type: "text", Text: st.Content}}
        }
        fr := st.FinishReason
        if fr == "" {
            fr = "stop"
            if len(st.ToolCalls) > 0 {
                fr = "tool_calls"
            }
        }
        raw, _ := json.Marshal(st)
        f.Script = append(f.Script, llm.Step{Response: &llm.Response{
            ID: fmt.Sprintf("fake-%d", i+1), Model: "fake", Message: m, FinishReason: fr, Usage: st.Usage, Raw: raw,
        }})
    }
    return f
}

The two tools are small enough that a trace shows the loop and nothing else. Both are idempotent, so a repeated call in a run is answered from the cache with a cached attr.

// Add and Mul are the two tools chapter 26's scripted tasks use: small
// enough that a trace shows the loop and nothing else. Both are idempotent.
type Add struct{}
type Mul struct{}

var arithSchema = schema([]string{"a", "b"}, map[string]any{
    "a": map[string]any{"type": "integer"},
    "b": map[string]any{"type": "integer"},
})

func (Add) Spec() llm.Tool {
    return llm.Tool{Name: "add", Description: "Add two integers.", Parameters: arithSchema}
}

func (Add) Idempotent() bool { return true }

func (t Add) Call(ctx context.Context, call toolcall.Call) agent.Result {
    if res, ok := validate(t.Spec().Parameters, call); !ok {
        return res
    }
    a, _ := intArg(call.Arguments, "a")
    b, _ := intArg(call.Arguments, "b")
    sum := a + b
    if (a > 0 && b > 0 && sum < 0) || (a < 0 && b < 0 && sum >= 0) {
        return agent.ErrorResult("add: overflow")
    }
    return agent.TextResult(strconv.FormatInt(sum, 10))
}

func (Mul) Spec() llm.Tool {
    return llm.Tool{Name: "mul", Description: "Multiply two integers.", Parameters: arithSchema}
}

func (Mul) Idempotent() bool { return true }

func (t Mul) Call(ctx context.Context, call toolcall.Call) agent.Result {
    if res, ok := validate(t.Spec().Parameters, call); !ok {
        return res
    }
    a, _ := intArg(call.Arguments, "a")
    b, _ := intArg(call.Arguments, "b")
    if a != 0 && b != 0 {
        p := a * b
        if p/b != a || (a == -1 && b == -9223372036854775808) || (b == -1 && a == -9223372036854775808) {
            return agent.ErrorResult("mul: overflow")
        }
        return agent.TextResult(strconv.FormatInt(p, 10))
    }
    return agent.TextResult("0")
}

The command is the loop plus flags. run takes its streams as arguments so that tests call it directly. A scripted run names its session after the script file unless -session says otherwise, and -deterministic sets a fixed clock and counter ids for both the tracer and the approval nonces. The trace file is closed once, after Run, and its errors are read after the stop line is printed.

// run is main without the process: tests call it with their own streams.
// Exit codes: 0 final, 1 error, 2 usage, 3 another stop (max_turns,
// max_tool_calls, cancelled, approval_timeout, refused).
func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
    fs := flag.NewFlagSet("aec", flag.ContinueOnError)
    fs.SetOutput(stderr)
    model := fs.String("model", "", "model id the provider serves")
    base := fs.String("base", "", "provider base URL, ending in /v1")
    keyEnv := fs.String("api-key-env", "", "name of the environment variable holding the API key (the value is never printed)")
    script := fs.String("script", "", "answer from this scripted model (a JSON file, see agent.Script) instead of a provider")
    trace := fs.String("trace", "", "write spans to this file")
    keep := fs.Bool("keep-bodies", false, "keep each model call's request and response under <trace file minus .jsonl>/")
    tools := fs.String("tools", "add,mul", "comma-separated tool names ("+strings.Join(toolNames(), ", ")+")")
    workspace := fs.String("workspace", ".", "directory the file and terminal tools work in")
    session := fs.String("session", "", "session id, which names the trace (default: random; scripted runs default to the script's name)")
    det := fs.Bool("deterministic", false, "fixed clock and counter ids, so two scripted runs write byte-identical traces")
    approve := fs.String("approve", "deny", "what a call marked for approval gets: deny | allow | tty")
    maxTurns := fs.Int("max-turns", agent.DefaultMaxTurns, "turn limit")
    maxCalls := fs.Int("max-tool-calls", agent.DefaultMaxToolCalls, "tool call limit per run")
    guard := fs.String("fleet-guard", "auto", "re-check /v1/models and send autoload=false: auto (on for straylight and dixie) | on | off")
    timeout := fs.Duration("timeout", 10*time.Minute, "deadline for the whole run")
    window := fs.Int("window", 0, "the context window the budget keeps to, in tokens (chapter 29); 0 runs without a budget check")
    reserve := fs.Int("reserve", 1024, "tokens held back for the completion when -window is set")
    system := fs.String("system", "", "system prompt placed before the task; @FILE reads it from a file")
    verbose := fs.Bool("v", false, "print each turn's usage, reasoning, llama-server timings and prefix report, and each budget check, to stderr")
    extra := fs.String("extra", "", "a JSON object of provider-specific request fields passed through untouched (llama-server: reasoning_budget_tokens, reasoning_effort, chat_template_kwargs); @FILE reads it from a file")
    if err := fs.Parse(args); err != nil {
        return 2
    }
    extraFields, err := parseExtra(*extra)
    if err != nil {
        fmt.Fprintln(stderr, "aec: -extra:", err)
        return 2
    }
    var mgr *budget.Manager
    if *window > 0 {
        mgr = &budget.Manager{
            Window:  budget.Window{Size: *window, Reserve: *reserve},
            Counter: &budget.Ratio{CharsPerToken: budget.DefaultCharsPerToken, Overhead: budget.DefaultOverhead},
        }
        if err := mgr.Window.Valid(); err != nil {
            fmt.Fprintln(stderr, "aec:", err)
            return 2
        }
    }
    if *script == "" && (*model == "" || *base == "") {
        fmt.Fprintln(stderr, "aec: either -script FILE, or -model ID and -base URL")
        return 2
    }
    var sc *agent.Script
    var client llm.Client
    if *script != "" {
        s, err := agent.LoadScript(*script)
        if err != nil {
            fmt.Fprintln(stderr, "aec:", err)
            return 2
        }
        sc = s
        client = s.Fake()
        if *session == "" {
            *session = strings.TrimSuffix(filepath.Base(*script), filepath.Ext(*script))
        }
    } else {
        u, err := url.Parse(*base)
        if err != nil || u.Host == "" {
            fmt.Fprintln(stderr, "aec: -base must be a URL")
            return 2
        }
        hc := newHTTPClient(guardOn(*guard, u.Hostname()))
        key := ""
        if *keyEnv != "" {
            key = os.Getenv(*keyEnv)
        }
        client = &llm.Provider{Name: u.Hostname(), BaseURL: strings.TrimRight(*base, "/"), APIKey: key, HTTP: hc}
    }
    if *verbose || mgr != nil {
        turn := 0
        client = &budget.Client{Client: client, Manager: mgr, OnTurn: func(req llm.Request, resp *llm.Response, prefix budget.PrefixReport) {
            turn++
            if *verbose {
                printTurn(stderr, turn, req, resp, prefix)
            }
        }}
    }
    // -extra sits outside the budget wrapper, so the wrapper sees the Extra
    // fields it compares for the prefix report.
    if len(extraFields) > 0 {
        client = &extraClient{Client: client, extra: extraFields}
    }
    task := strings.Join(fs.Args(), " ")
    if task == "" && sc != nil {
        task = sc.Task
    }
    if task == "" {
        fmt.Fprintln(stderr, "aec: no task given")
        return 2
    }
    suite, err := selectTools(strings.Split(*tools, ","), *workspace)
    if err != nil {
        fmt.Fprintln(stderr, "aec:", err)
        return 2
    }
    ids := obs.RandomIDs()
    now := time.Now
    if *det {
        ids = obs.CounterIDs("s")
        now = obs.FixedClock(time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC))
    }
    if *session == "" {
        *session = ids()
    }
    var tracer *obs.Tracer
    closeTrace := func() error { return nil }
    if *trace != "" {
        f, err := openTrace(*trace)
        if err != nil {
            fmt.Fprintln(stderr, "aec:", err)
            return 1
        }
        // Closed once, after Run, so a failed close is reported; the defer
        // covers the early returns before Run.
        closed := false
        closeTrace = func() error {
            if closed {
                return nil
            }
            closed = true
            return f.Close()
        }
        defer func() { _ = closeTrace() }()
        tracer = obs.NewTracer(f)
        tracer.Now, tracer.NewID = now, ids
        if *keep {
            dir := strings.TrimSuffix(*trace, ".jsonl")
            if dir == *trace {
                dir += ".bodies"
            }
            if err := os.MkdirAll(dir, 0o755); err != nil {
                fmt.Fprintln(stderr, "aec:", err)
                return 1
            }
            tracer.Keep = func(name string) (io.WriteCloser, error) { return os.Create(filepath.Join(dir, name)) }
        }
    }
    loop := &agent.Loop{
        Client: client, Model: *model, Tools: suite, MaxTurns: *maxTurns, MaxToolCalls: *maxCalls,
        Tracer: tracer, Clock: now,
    }
    if *det {
        loop.NewID = obs.CounterIDs("n")
    }
    if mgr != nil {
        loop.Context = &budgetChecker{m: mgr, out: stderr, verbose: *verbose}
    }
    switch *approve {
    case "deny":
    case "allow":
        loop.Approver = agent.ApproverFunc(func(ctx context.Context, req agent.ApprovalRequest) (agent.Approval, error) {
            return agent.Approval{Request: req.ID, CallHash: req.Call.Hash, Decision: agent.Allow, By: "flag", At: now()}, nil
        })
    case "tty":
        loop.Approver = newTTYApprover(stdin, stderr, now)
    default:
        fmt.Fprintln(stderr, "aec: -approve must be deny, allow or tty")
        return 2
    }
    ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
    defer cancel()
    ctx, cancelT := context.WithTimeout(ctx, *timeout)
    defer cancelT()
    sess := &agent.Session{ID: *session}
    if *system != "" {
        text := *system
        if strings.HasPrefix(text, "@") {
            b, err := os.ReadFile(text[1:])
            if err != nil {
                fmt.Fprintln(stderr, "aec: -system:", err)
                return 2
            }
            text = strings.TrimRight(string(b), "\n")
        }
        sess.Messages = []llm.Message{llm.Text(llm.System, text)}
    }
    stop := loop.Run(ctx, sess, task)
    // A trace is an audit record: a span or body that did not reach the disk
    // fails the run, whatever the loop concluded, once the file is closed.
    closeErr := closeTrace()
    fmt.Fprintf(stderr, "aec: stop=%s turns=%d calls=%d\n", stop.Reason, stop.Turns, stop.Calls)
    code := 3
    switch stop.Reason {
    case agent.StopFinal:
        // The final text is the model's: a terminal gets it through the
        // termtext filter, a pipe or a file the bytes as they are.
        fmt.Fprintln(stdout, termtext.For(stdout, stop.Final))
        code = 0
    case agent.StopError:
        fmt.Fprintln(stderr, "aec:", errLine(stderr, stop.Err))
        code = 1
    default:
        if stop.Err != nil {
            fmt.Fprintln(stderr, "aec:", errLine(stderr, stop.Err))
        }
    }
    if err := tracer.Err(); err != nil {
        fmt.Fprintf(stderr, "aec: trace: %v\n", err)
        return 1
    }
    if closeErr != nil {
        fmt.Fprintf(stderr, "aec: trace: %v\n", closeErr)
        return 1
    }
    return code
}

And the guard’s switch. guardOn decides, from -fleet-guard and the host of -base, whether newHTTPClient wraps its proxy-free transport in route.Guard; auto matches straylight and dixie by short name or as the first label of a longer one. The guard’s own code is chapter 28’s listing.

// guardOn decides whether a request to host goes through route.Guard, the
// fleet rule as a RoundTripper (chapter 28 lists it): immediately before every
// request that names a model it reads GET /v1/models and requires that
// model's status.value to be "loaded" (a sleeping model is not loaded, and at
// llama.cpp b29c606 a request wakes it), then sends the request with
// autoload=false. Mode "auto" guards straylight and dixie.
func guardOn(mode, host string) bool {
    switch mode {
    case "on":
        return true
    case "off":
        return false
    }
    h := strings.ToLower(host)
    return h == "straylight" || h == "dixie" || strings.HasPrefix(h, "straylight.") || strings.HasPrefix(h, "dixie.")
}

// newHTTPClient is the provider's client: a private transport that ignores
// HTTP_PROXY (a proxy would answer the guard's /models check itself and see
// the prompt), and no redirects (a 307 would send the prompt to a host the
// guard never checked). A guarded client wraps the transport in the fleet
// guard.
func newHTTPClient(guarded bool) *http.Client {
    tr := http.DefaultTransport.(*http.Transport).Clone()
    tr.Proxy = nil
    hc := &http.Client{
        Timeout:       5 * time.Minute,
        Transport:     tr,
        CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
    }
    if guarded {
        hc.Transport = &route.Guard{Next: tr}
    }
    return hc
}

A scripted run

The arithmetic task is (2+3)*(10+20) with an add and a mul, answered by a script of three steps: two add calls in one turn, one mul, and the text 150. The usage numbers in the script are made up (120, 190 and 225 prompt tokens); they exist so that the trace has usage to sum. On talos, from the repository root:

aec -script go/labs/ch26/testdata/scripts/arith.json -model fake -session scripted-arith \
    -trace arith.jsonl -deterministic
150
aec: stop=final turns=3 calls=3

The first line is stdout and the second stderr. -model fake and -session scripted-arith are what the lab passes: the digest hashes model, and the session names the trace, so without them the run is deterministic and still not the golden. With them, cmp arith.jsonl go/labs/ch26/testdata/traces/arith.jsonl printed nothing (talos, go1.27.1). The ten lines:

{"trace":"scripted-arith","id":"s3","parent":"s2","seq":3,"kind":"model_call","name":"fake","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok","attrs":{"finish_reason":"tool_calls","model":"fake","provider":"fake","request_hash":"d3de1a924f88a9757cc09e10481cf8a9808829ed33118dc36fba92f0525ef9ed"},"usage":{"prompt_tokens":120,"completion_tokens":40}}
{"trace":"scripted-arith","id":"s4","parent":"s2","seq":4,"kind":"tool_call","name":"add","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok","attrs":{"call_hash":"d6fb174cac0e4056f183561d5f8c33212f19460fba6d4626e214bed362a83fa1","call_id":"c1","result_kind":"ok","tool":"add"}}
{"trace":"scripted-arith","id":"s5","parent":"s2","seq":5,"kind":"tool_call","name":"add","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok","attrs":{"call_hash":"b8f8276d9b16facf16b24fb150f6a4feabe48367dc26a652bdf6dae44f6c8ab6","call_id":"c2","result_kind":"ok","tool":"add"}}
{"trace":"scripted-arith","id":"s2","parent":"s1","seq":2,"kind":"turn","name":"1","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok"}
{"trace":"scripted-arith","id":"s7","parent":"s6","seq":7,"kind":"model_call","name":"fake","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok","attrs":{"finish_reason":"tool_calls","model":"fake","provider":"fake","request_hash":"4028c2979ded637b4812807b70ef43322737422c84bbaeb3f03507b296d6a07d"},"usage":{"prompt_tokens":190,"completion_tokens":22}}
{"trace":"scripted-arith","id":"s8","parent":"s6","seq":8,"kind":"tool_call","name":"mul","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok","attrs":{"call_hash":"9f3c9e75781102fe22905631ac3d3222e214a3d1e40eaf7cc1e1819076c07399","call_id":"c3","result_kind":"ok","tool":"mul"}}
{"trace":"scripted-arith","id":"s6","parent":"s1","seq":6,"kind":"turn","name":"2","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok"}
{"trace":"scripted-arith","id":"s10","parent":"s9","seq":10,"kind":"model_call","name":"fake","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok","attrs":{"finish_reason":"stop","model":"fake","provider":"fake","request_hash":"ae5812c9d3db34a598968920e06bd620133fcefb1d0226e9d80da0668ae17409"},"usage":{"prompt_tokens":225,"completion_tokens":2}}
{"trace":"scripted-arith","id":"s9","parent":"s1","seq":9,"kind":"turn","name":"3","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok"}
{"trace":"scripted-arith","id":"s1","seq":1,"kind":"run","name":"scripted-arith","start":"2026-10-01T00:00:00Z","end":"2026-10-01T00:00:00Z","status":"ok","attrs":{"calls":"3","stop":"final","turns":"3"},"usage":{"prompt_tokens":535,"completion_tokens":64}}

Read them in file order, which is the order the spans ended. Line 1 is seq 3, the first turn’s model_call, and lines 2 and 3 are seq 4 and 5, the two add calls in the order the model wrote them, children of turn s2; the turn’s own line, seq 2, comes after them because a span ends after its children. seq is the order the spans started: sorted by it, the file is run (1), turn (2), model call (3), tool calls (4, 5), turn (6), and so on. The run span, seq 1, is the last line; its usage sums the three model calls, 535 prompt tokens (120 + 190 + 225) and 64 completion tokens (40 + 22 + 2), and its attrs say stop final, turns 3, calls 3. The three request_hashes differ because each request holds more messages than the last. The two call_hashes of the first turn are the hashes of add with {"a":2,"b":3} and with {"a":10,"b":20}, and call_id is the model’s c1 and c2, which the hash does not contain. Every time is the fixed 2026-10-01T00:00:00Z and the ids are s1 to s10 because the clock is fixed and the ids are a counter; a run that was not asked to be deterministic has real times and random ids.

A live run

The same loop against a real model: the reader’s dixie, ornith-1.5-9b-uncensored, which /v1/models reported loaded at 05:37 UTC (the guard checks again before each of the run’s three requests). From talos, 2026-10-02 at 05:38 UTC, paths shortened:

aec -base http://dixie:11434/v1 -model ornith-1.5-9b-uncensored -tools add,mul \
    -trace live/live.jsonl -keep-bodies -timeout 3m \
    'What is (2+3)*7? Use the add and mul tools, one call at a time, and answer with the number only.'
35
aec: stop=final turns=3 calls=2

-fleet-guard was auto, which is on for the host dixie. The model answered with a call to add, then a call to mul, then the number: three turns, two calls. The trace:

{"trace":"9071995b8a5ff58f","id":"8c182f2bc4ddb303","parent":"e53124dd19b71096","seq":3,"kind":"model_call","name":"dixie","start":"2026-10-02T05:38:04.005742626Z","end":"2026-10-02T05:38:06.233180397Z","status":"ok","attrs":{"finish_reason":"tool_calls","model":"ornith-1.5-9b-uncensored","provider":"dixie","request_hash":"636f3222fbdf59b6024164970674ae713e89d23b26909a430a7289af408f2c43"},"usage":{"prompt_tokens":382,"completion_tokens":88},"body":"0003-model_call.jsonl"}
{"trace":"9071995b8a5ff58f","id":"4c0ff2f85e4a698c","parent":"e53124dd19b71096","seq":4,"kind":"tool_call","name":"add","start":"2026-10-02T05:38:06.233340711Z","end":"2026-10-02T05:38:06.233429586Z","status":"ok","attrs":{"call_hash":"d6fb174cac0e4056f183561d5f8c33212f19460fba6d4626e214bed362a83fa1","call_id":"TRWAsEevjPX19JOVPiVwin6pj7pUkRja","result_kind":"ok","tool":"add"}}
{"trace":"9071995b8a5ff58f","id":"e53124dd19b71096","parent":"e24d82e62709dbe4","seq":2,"kind":"turn","name":"1","start":"2026-10-02T05:38:04.005563658Z","end":"2026-10-02T05:38:06.233441604Z","status":"ok"}
{"trace":"9071995b8a5ff58f","id":"f0d4dd18617c973a","parent":"af81f835964ca114","seq":6,"kind":"model_call","name":"dixie","start":"2026-10-02T05:38:06.233538612Z","end":"2026-10-02T05:38:07.242657447Z","status":"ok","attrs":{"finish_reason":"tool_calls","model":"ornith-1.5-9b-uncensored","provider":"dixie","request_hash":"c335828a9697643ac99c725e36a6367a05883f99f8a750b27d0107dfc9a8cca4"},"usage":{"prompt_tokens":435,"completion_tokens":47},"body":"0006-model_call.jsonl"}
{"trace":"9071995b8a5ff58f","id":"e3da44d2e9233139","parent":"af81f835964ca114","seq":7,"kind":"tool_call","name":"mul","start":"2026-10-02T05:38:07.242710672Z","end":"2026-10-02T05:38:07.242775673Z","status":"ok","attrs":{"call_hash":"d41cd9877de2ff2168579e224614e2ac3211a4700c38381c24cae8ba6ef02e46","call_id":"pT0qYQdDV3Of1qvIax3st5CJNFOLnJmy","result_kind":"ok","tool":"mul"}}
{"trace":"9071995b8a5ff58f","id":"af81f835964ca114","parent":"e24d82e62709dbe4","seq":5,"kind":"turn","name":"2","start":"2026-10-02T05:38:06.233445893Z","end":"2026-10-02T05:38:07.24278035Z","status":"ok"}
{"trace":"9071995b8a5ff58f","id":"dc1d54886af06cd1","parent":"ab89c5aefe63d6ac","seq":9,"kind":"model_call","name":"dixie","start":"2026-10-02T05:38:07.242845372Z","end":"2026-10-02T05:38:07.609164522Z","status":"ok","attrs":{"finish_reason":"stop","model":"ornith-1.5-9b-uncensored","provider":"dixie","request_hash":"e13fae5ca45999676f816d8d5243a88a86193affee8f0b0b17f8be40aa6c2c12"},"usage":{"prompt_tokens":490,"completion_tokens":13},"body":"0009-model_call.jsonl"}
{"trace":"9071995b8a5ff58f","id":"ab89c5aefe63d6ac","parent":"e24d82e62709dbe4","seq":8,"kind":"turn","name":"3","start":"2026-10-02T05:38:07.242781891Z","end":"2026-10-02T05:38:07.609182932Z","status":"ok"}
{"trace":"9071995b8a5ff58f","id":"e24d82e62709dbe4","seq":1,"kind":"run","name":"9071995b8a5ff58f","start":"2026-10-02T05:38:04.005562759Z","end":"2026-10-02T05:38:07.60918979Z","status":"ok","attrs":{"calls":"2","stop":"final","turns":"3"},"usage":{"prompt_tokens":1307,"completion_tokens":148}}
$ ls live/live
0003-model_call.jsonl
0006-model_call.jsonl
0009-model_call.jsonl

The run took 3.60 s of wall time: 2.23 s, 1.01 s and 0.37 s in the model calls, and under 0.1 ms in each tool call. The call_hash of the add call is d6fb174c…, the same value as the scripted run’s, with a different call id and a different model. The loop never set parallel_tool_calls, so llama-server at b29c606 took the template’s capability as the default (chapter 25 reads the line; its function-calling document says parallel calls are off by default). Each turn held one call, which is also what the prompt asked for.

At 05:39 UTC, 75 seconds after the first run started (74.64 s), the same command ran again. It answered 35 with aec: stop=final turns=3 calls=2. Live traces pin nothing: their ids, times and completion_tokens differ (88 and 112 on the first turn), and so do the request hashes of turns 2 and 3: the digest holds each run’s own stored reasoning and the call ids the server chose (TRWAs… in the first run, B2J3b… in the second; the ids are on the wire too). The first turn’s request_hash is 636f3222… in both, as it must be for two equal digests. The kept bodies show reasoning_content in the request because a body is the digest, not the bytes sent. The usage, from the spans and the kept bodies, in both runs:

turn prompt_tokens completion_tokens, run 1 / run 2 server cache_n, run 1 / run 2 server prompt_n, run 1 / run 2
1 382 88 / 112 0 / 378 382 / 4
2 435 47 / 47 378 / 378 57 / 57
3 490 13 / 13 431 / 431 59 / 59

(cache_n and prompt_n are the server’s timings: the prompt tokens taken from its cache and the ones it evaluated; cached_tokens in usage agrees with cache_n.) These check the derivation of Mechanism against real numbers. The increments are g1=435−382=53g_1 = 435 - 382 = 53 and g2=490−435=55g_2 = 490 - 435 = 55, and

P3=3⋅382+2⋅53+1⋅55=1146+106+55=1307=382+435+490, P_3 = 3 \cdot 382 + 2 \cdot 53 + 1 \cdot 55 = 1146 + 106 + 55 = 1307 = 382 + 435 + 490,

which is the prompt_tokens of the run span in both runs. The identity is arithmetic, so it holds; what the run adds is three observations. First, g1=53g_1 = 53 is not the 88 tokens the model generated that turn. The 88 include the reasoning, which the loop keeps in its history and its digest but does not send back (SendReasoning is off, chapter 24), so the next prompt gains only the call, its result and the framing. That fits turn 2’s prompt being 435 tokens in both runs although the first turn’s reasoning text, and completion count (88 and 112), differed. The growth term therefore has to be measured from prompt_tokens and not computed from completion_tokens. Second, the server evaluated 382 + 57 + 59 = 498 prompt tokens in the first run against the 1307 it reported, 38%, because it reused the cached prefix; and in the second run it evaluated 4 + 57 + 59 = 120, because the first run’s prefix was still in its cache (378 of the 382 tokens of turn 1), which no protocol promised. Third, the reported 1307, not the evaluated 498, is the figure in usage, and so the one that chapters 29 and 49 work from. The quadratic term is already in a three-turn run; a twenty-turn run pays it fully (exercise b).

Exercises

(a) A loop runs with MaxTurns 8, MaxToolCalls 12, a model call that can take at most 120 s (retries included), a 30 s approval timeout and tools whose longest deadline is 45 s. Bound the run’s wall time, and say which single change halves the bound.

Answer

8⋅120+12⋅30+8⋅45=960+360+360=16808 \cdot 120 + 12 \cdot 30 + 8 \cdot 45 = 960 + 360 + 360 = 1680 s. Halving means saving 840 s. No single term is that large except the model-call term (960 s), so a change to DD alone must cut it to 15 s (8⋅15=1208 \cdot 15 = 120, saving 840), which a 120 s model call cannot meet; at 60 s it saves 480 s and leaves 1200 s, a 29% cut. But TT multiplies two terms, 8⋅120+8⋅45=13208 \cdot 120 + 8 \cdot 45 = 1320 of the 1680, and a single change to TT does halve the bound: with T=2T = 2 it is 2⋅120+12⋅30+2⋅45=240+360+90=6902 \cdot 120 + 12 \cdot 30 + 2 \cdot 45 = 240 + 360 + 90 = 690 s, below 840 (T=3T = 3 gives 855 s, just above). The cost is that a task needing more than two model calls cannot finish. The 20 ms grace per turn is ignored. A script on talos confirmed 1680, 840, 1200, 690 and 855.

(b) A task starts at p1=400p_1 = 400 prompt tokens and adds g=150g = 150 tokens per turn. How many prompt tokens does the provider count over 20 turns, and what share is the growth term?

Answer

20⋅400+150⋅20⋅192=8000+150⋅190=8000+28500=3650020 \cdot 400 + 150 \cdot \tfrac{20 \cdot 19}{2} = 8000 + 150 \cdot 190 = 8000 + 28500 = 36500; the growth term is 28500/36500=0.78128500 / 36500 = 0.781 (a script on talos). The first-prompt term is linear in the turns and the growth term quadratic, so the share rises with the turn count.

(c) A run makes one call to a tool marked for approval, the approver allows it, and the model then answers with text. Its trace has seven spans. List them by seq. The file you are given has the run’s line but lacks the line for seq 5, in one copy, and for seq 7, in another. What does Reconstruct report for each, what can you still learn from the first, and which writer failure explains a file like either?

Answer

A run on talos (the loop’s own test rig) wrote: 1 run, 2 turn, 3 model_call, 4 tool_call, 5 approval, 6 turn, 7 model_call. The tool_call span is started before its call’s gate, so the approval comes after it in seq. Without seq 5, Reconstruct reports reconstruct: seq gap: want 5, got 6, and the surviving tool_call line still has approval allow in its attrs, so the decision is known without the approval span (its nonce, by and timeout are lost). Without seq 7 it reports nothing: the six spans form a valid tree whose second turn has no model call, although the run span says stop final. A lost line is visible as a gap only if a later span exists, so the loss of the highest-numbered span is invisible to Reconstruct; property (ii) covers a crash, which loses the run line, and not a failed write at the tail. Either file is what a failed write of a single line produces, and that case is the one Tracer.Err() exists for, and cmd/aec’s exit 1: a consumer who finds a turn without a model call in a file with a run line should treat it as damaged, unless that turn’s context decision ended the run (stop context_exceeded, or error with the context span’s error attr).

(d) A model never writes a decodable call. With MaxTurns 5 and the two-tool suite, how many model calls happen, how many tool calls are counted, how many spans does the trace hold, and why is a turn counted?

Answer

A script of six steps, each an add call with the arguments {"a": 2, "b": }, run with aec -script broken.json -model fake -trace broken.jsonl -deterministic -max-turns 5 (talos), printed aec: stop=max_turns turns=5 calls=0 and exited 3. The trace has 16 lines: the run, 5 turns, 5 model calls and 5 tool_call spans, all five with result_kind rejected. Five model calls, none counted against MaxToolCalls, so MaxTurns is the only bound on such a loop, which is why a turn whose calls all fail to decode must still count. The sixth step was never asked for.

(e) The guard found the model loaded and sent the request. Give a concrete interleaving of two clients of the same router in which the request nevertheless wakes a model, and one in which it is refused instead. Which of the two does autoload=false account for?

Answer

The check and the request are two round trips. (1) The guard’s GET /v1/models says loaded. (2) Something else puts the model to sleep (the router’s own idle handling, or another client’s action) before the guard’s POST arrives. (3) The POST finds a sleeping model, which at b29c606 the router counts as running, so it routes the request and wakes the model: the guard did what it was meant to and the fleet rule was broken anyway. Replace step 2 with an unload and the POST finds an unloaded model: autoload=false makes the router refuse it, and that refusal, not the guard, is what protects the fleet. So the guard narrows the window and does not close it, and what closes the sleeping case is that nobody else puts the model to sleep in it, which the guard cannot ensure. The refusal path itself was run on wntrmute against a loopback server (127.0.0.1, a free port) that reported its one model as sleeping and logged what it received: the built aec, given -fleet-guard on and no tools, made one GET /v1/models and no POST (the refusal is permanent, so the provider attempted it once), printed aec: stop=error turns=1 calls=0 and then aec: llm: 127.0.0.1: Post "http://127.0.0.1:43363/v1/chat/completions": fleet guard: m is "sleeping", not loaded; this client never loads a model, and exited 1. That run says nothing about proxies (Go never proxies a loopback address); TestProxyIsNotHonoured in cmd/aec is what checks them.

(f) Design the content-addressed message store that would let Reconstruct replay a run’s requests from its trace and the store, with the spans carrying only keys. State what the key is, what a model_call span carries, what Reconstruct would check on each key, and what the store saves over a 20-turn run that starts at p1=400p_1 = 400 prompt tokens and adds g=150g = 150 per turn (the numbers of exercise b), against a body directory that writes each request in full. What does the check still not catch?

Answer

The key of a message is the sha256 of its canonical JSON (canon.JSON, the encoding request_hash already uses), and the store maps key to those bytes, written once however many requests contain the message. A model_call span carries an attribute listing the keys of the messages added since the run’s previous model call, in order (all of them on the first call), plus one key for the tools and sampling fields, which a run does not change. The request of turn tt is the concatenation of the lists of turns 1 to tt. Reconstruct would, for each key, fetch the bytes, recompute the sha256 and compare it with the key; then assemble the digest, hash it the way the loop did and compare the result with the span’s request_hash. The first check finds a store entry that was edited or corrupted; the second finds a key list that does not add up to the request that was sent. Cost, with exercise (b)’s numbers: the body directory holds P20=20⋅400+150⋅190=36500P_{20} = 20 \cdot 400 + 150 \cdot 190 = 36500 prompt tokens of text over its 20 request bodies. The store holds each message once, so the requests together hold what the last request holds, p20=400+19⋅150=3250p_{20} = 400 + 19 \cdot 150 = 3250 tokens, or 3250/36500=0.0893250 / 36500 = 0.089 of the bodies, 11.2 times less (a script on talos; the reply of the 20th turn is one more message in both designs). The keys cost 39 of 64 hexadecimal characters each on the spans (one for the user message and two per later turn, the assistant message and the tool reply), 2,496 bytes; listing every request’s full key list instead would cost 400 keys, 25,600 bytes, quadratic again but 64 bytes per message and not its text. The secrecy cost does not go away: the store holds the reader’s prompts and tool output, so it is as private as the body directory and the spans stay shareable. What the check does not catch is a file edited consistently, spans and store together: that is integrity, which chapter 48 supplies only for its own log of hashes, not for the trace or the store, and Reconstruct checks structure only.

(g) The nonce is 64 bits from crypto/rand, and a run makes at most MaxToolCalls = 50 approval dispatches. Bound the chance that two dispatches of one run share a nonce. Then say what -deterministic changes about approvals, and what the nonce still does not prevent.

Answer

By the union bound over pairs, the chance is at most (502)⋅2−64=1225/264=6.6×10−17\binom{50}{2} \cdot 2^{-64} = 1225 / 2^{64} = 6.6 \times 10^{-17} (a script on talos). Under -deterministic the loop’s ids are the counter n1, n2, …: they are unique within a run but identical from run to run, so a reply captured from one run is a valid reply to the same dispatch of the next. A deterministic run is for tests, and its approvals must not be carried between runs. The nonce does not stop an approver that has been shown the request from answering it, in either mode: it binds a reply to a dispatch, it does not say who sent it.

(h) A script’s first step holds two add calls ({"a":1,"b":1} and {"a":2,"b":2}). Run it with -max-tool-calls 1. What does the run print, what do the two tool_call spans say, and what does the model see?

Answer

aec: stop=max_tool_calls turns=1 calls=0, exit 3 (talos). The batch of two would have passed the budget of one, so it was not counted (calls=0) and not run, and both spans have status denied and result_kind denied; the run span has status error. Each call is answered denied: not run: max_tool_calls reached, an error result, so the session is well formed if it is resumed with a larger budget; the model never saw an empty result and could not have taken the missing one for a success. The count of tool_call spans is 2 and Stop.Calls is 0, which is why a consumer counts spans.

Lab

The mechanics are chapter 22’s: go/labs/ch26/lab.go declares Runner and Impl and checks at compile time that the reference and go/labs/ch26/mine have the same API; mine/loop.go is the starter, a Run that returns an error; and

make lab CH=26 IMPL=mine

runs your loop. Provided: llm.Fake scripted from testdata/scripts/*.json through agent.Script, toolcall.Decode, the tracer, tool.Add and tool.Mul, and a block tool that the cancel task uses. The tests pin:

  • TestArith: the task of the scripted run above. Three turns, two parallel calls answered in wire order with their own tool_call_ids, seven messages in the end, and the request history the fake saw at each call (1, 4 and 6 messages).
  • TestMalformedFirstCall: a first call whose JSON is broken is answered as a rejection (error: tool call rejected; not_json: …) with its own tool_call_id, and the corrected call runs.
  • TestMaxTurns: MaxTurns 3 stops after exactly three model calls, with max_turns.
  • TestCancelledMidTool: the context is cancelled once the block tool has started; the run stops cancelled, and the tool’s reply says cancelled.
  • TestScriptedTraces: two fresh runs of each task write identical bytes, and the bytes equal the committed golden. The goldens have 10, 9, 10 and 4 lines (arith, malformed, maxturns, cancel); their sha256 begin 8eef2dfb, 9eebdbc7, c3bc1b51 and 103e42c4. Each was reproduced warm, in one process, and cold, by two separate processes compared with cmp, on talos, and by a cold run on straylight on 2026-10-02 (UTC) whose four hashes equal talos’s. No later change to the loop moved a golden, the abandoned-tool and filtered-reply changes of this chapter’s fix round included, and neither did the later guard that answers a batch cancelled under an ended context (TestScriptedTraces and the other goldens of chapters 26, 27, 37 and 40 pass unchanged with it, on wntrmute), and make check on straylight on 2026-10-02 (UTC) ran this test against the committed files again.
  • TestReconstructFromSpansAlone: from each golden’s spans and nothing else, Reconstruct rebuilds the trajectory, and it agrees, turn by turn and call by call, with the script that produced it (names, call ids, the decoded hashes, the stop reason, and the count of tool_call spans against the run’s calls plus its rejections). This is the chapter’s claim about its format, executed.
  • TestLive: your loop against a real model, once, skipped unless AEC_LIVE=dixie or AEC_LIVE=straylight names the one host it may contact. It reads that host’s /v1/models (which names no model), skips unless the 9b (on straylight, the 35b first) is loaded, and sends through route.Guard, which re-checks before each request and sends ?autoload=false. One add-then-multiply task; the test logs the stop and the span count. With the reference on dixie (from talos, 2026-10-02 14:19 UTC) it logged stop=final turns=3 calls=2 spans=9 in 4.06 s, three guarded request pairs, each a GET /v1/models then a POST /v1/chat/completions?autoload=false. The test fails if the run stops in error or writes no spans; it asserts nothing about the model’s answer.

With AEC_IMPL=mine the starter fails 14 tests (talos, 2026-10-02): the four task tests, and TestScriptedTraces and TestReconstructFromSpansAlone with their eight subtests. A passing make lab CH=26 IMPL=ref is the baseline.

This lab pins the turn rule and the trace format. The approval protocol is tested in chapter 27’s lab, and in the loop’s own tests (TestApprovalReplayFromAnEarlierDispatchIsRefused among them); a tool that ignores its context, and a filtered reply that carries calls, have TestToolThatIgnoresItsContextIsAbandonedAtItsTimeout and TestFilteredReplyWithToolCallsIsAnswered in internal/agent.

AEC_UPDATE=1 rewrites the goldens. It is legitimate after a deliberate change to the trace format, one recorded in DECISIONS.md, and it also means updating the hash that the repository’s privacy test keeps for each golden. It is not legitimate to silence a flaky run: a deterministic trace that differs between two runs has a bug, such as a span started from a goroutine or a map read in iteration order, and updating the golden would record the bug.

Further reading

results matching ""

    No results matching ""