# AgentCall Design

Status: draft for implementation
Date: 2026-11-25
Project: `agent_call`
Module namespace: `AgentCall`

## 1. Summary

`AgentCall` runs the tool loop that `LlmCall` deliberately does not: one call
takes a client, a canonical request and options, sends the request, runs the
tools the model asks for with `ToolCall.run/4`, appends the results, and repeats
until the model stops asking or the budget runs out. It returns the final
response, the transcript the model was last given, and the counters that
describe what happened.

The loop itself is small. The value is getting its hard edges right once, in a
library that can be tested against fixtures: parallel and streamed call
fragments, arguments the model did not generate as valid JSON, a tool that wants
human approval, a tool that fails or raises, a result too large for the next
request, and a loop that must stop.

The whole surface is two functions over data:

```text
AgentCall.run/3   -> {:ok | :exhausted, Result} | {:pending, Pending} | {:error, Error}
AgentCall.resume/3 -> the same, after an approval decision
```

`run/3` is a complete tool loop in one call. `resume/3` continues a loop that
paused on an approval request. There is no process, no supervision tree, no
store, no application config and no global state.

While it runs, an `on_event:` observer reports step, token and tool boundaries so
a product can show the work as it happens. The observer is read-only: it cannot
change a call, a result or an outcome.

Before each request, a caller-supplied `context:` policy may pass the transcript
through, replace it with a compacted one, or stop the run. The library never
counts tokens or drops a message on its own.

The loop can also pause for user input: a marked input-tool module or a
`prompt:` policy can ask a question, and `resume/3` carries the answer as a tool
result or a user message. Approval and input are two `Pending.kind`s, not two
APIs.

## 2. Position

### 2.1 What problem this solves

`LlmCall` names the agent loop as an anti-goal, and says so at the point of use:

> Approvals, audits and timeouts stay in `tool_call`, and the follow-up request
> stays with you: the library does not run an agent loop.

So every caller writes the same glue: read `LlmCall.Response.tool_calls/1`, run
each call through `ToolCall.run/4`, build a `%LlmCall.ToolResult{}`, append an
assistant turn plus a user turn of results, send again, and decide when to stop.
Every line of that glue has a hard edge.

The gap is narrow and real. Elixir's agent layer is already built on `req_llm`:
LangChain and Jido AI both depend on it. Both are frameworks — chains,
workflows, durable actors. A thin, stateless, one-call loop over a canonical IR
is unoccupied. It is also distribution: without an agent story, an `llm_call`
user who wants one adopts a different substrate and takes their message shapes
with them.

### 2.2 What this is not

`AgentCall` is not:

- a framework: no chains, graphs, workflows, planning, memory or prompt templates
- an orchestration runtime: no process per conversation, no durable actor, no
  scheduler
- a conversation store: no ETS, database or file format; `Pending` is data the
  caller stores
- a provider layer: providers remain `LlmCall` client modules; there is no
  catalog, routing or auth here
- a retry policy: it reports `LlmCall.Error.retryable?` and `retry_after_ms` and
  leaves the decision to the caller
- a tool framework: schema derivation, dispatch, approval, audit and timeouts
  stay in `tool_call`
- a streaming API: `stream: true` changes how a turn is read and enables delta
  events; it does not change the outcome
- an event bus: `on_event:` calls the caller's function in the loop's process;
  there is no queue, topic, replay or delivery guarantee beyond "in order"
- a context manager: it exposes a `context:` policy before each request, but
  owns no tokenizer, model window, trimming or summary. The caller decides
  whether to pass through, compact or stop.

### 2.3 Relationship to `llm_call` and `tool_call`

`llm_call` owns the wire: canonical request/response/messages, the codecs, the
client and the transport. `AgentCall` never re-encodes a request, never parses a
provider payload, and never invents a canonical message shape. Its transcript is
`LlmCall.Message` — assistant turns carry the response content verbatim,
including `ToolCall` parts, and tool results are content parts in a **user**
turn, which is `llm_call`'s canonical form.

`tool_call` owns dispatch: a module declares its tools and their schemas from
`@spec`/`@doc`, and `ToolCall.run/4` applies the module's approval, audit and
timeout policies. `AgentCall` derives its dispatch map from
`ToolCall.describe/2`, calls `ToolCall.run/4`, and turns the result into a
`%LlmCall.ToolResult{}`. It does not derive a schema.

`tool_call` is a direct dependency, not an implementation detail:
`%ToolCall.Approval.Request{}` appears in this library's public `Pending` type.

### 2.4 Relationship to LangChain and Jido AI

| Project | Focus |
| --- | --- |
| LangChain Elixir | Chains, conversation flow, tool execution, callbacks |
| Jido AI | Durable agents, actions, workflows, multi-agent orchestration |
| `AgentCall` | One stateless tool loop over `llm_call`'s canonical IR |

`AgentCall` can sit underneath those systems. It deliberately has no answer for
what a framework answers: where state lives, how many agents exist, or how a
conversation is routed.

## 3. Goals

- `AgentCall.run/3` performs a complete tool loop in one call.
- Correct on the hard edges: streamed call assembly, invalid arguments, tool
  failure, pending approval, result size, termination.
- Pure data in, pure data out. No processes, no supervision tree, no store, no
  application config, no globals.
- Testable end to end against a local HTTP fixture server, the way `llm_call`
  tests codecs — no network, no mocking of the protocol layer.
- Honest outcomes. A run that the loop itself stopped short — budget reached,
  approval needed, or a context policy stopped it — never returns `{:ok, _}`. A
  provider-side truncation (`:max_tokens`, `:content_filter`) is a normal model
  outcome, so it is carried in `Result.stop_reason` rather than flattened into
  success or hidden.
- Observable while it runs: an observe-only callback reports step, token and
  tool boundaries as they happen, so a product can render the loop live without
  this library owning a process.
- Context is a caller policy: before each request, a `context:` function may
  pass the transcript through, replace it, or stop the run. The library never
  trims silently and owns no tokenizer.
- User input is a pause: a marked input-tool module or a `prompt:` policy can
  ask the user a question; `resume/3` carries the answer as a tool result or a
  user message, and the four outcomes do not change.
- No provider-specific branch anywhere in this library.

## 4. Non-goals for 0.1

- Memory, RAG, prompt templates, planning, autonomous multi-agent
  orchestration, or agent-to-agent messaging. The synchronous, caller-owned
  sub-agent helper in §24 is supported; the library itself orchestrates
  nothing. A thread/session store or memory runtime is also out: the
  caller-owned `AgentCall.Thread` behaviour (§26) is the only contract.
- Persistence of any kind in the library. A caller may persist an
  `%AgentCall.Pending{}` or `%AgentCall.Checkpoint{}` and resume it (§25); the
  library stores nothing, and there is no session store, ETS table, database or
  process.
- A provider catalog or model routing. Providers remain caller modules.
- HTTP retry, backoff, or rate limiting. The loop surfaces
  `LlmCall.Error.retryable?` and `retry_after_ms`; the policy stays with the
  caller, as in `llm_call`.
- Control through the observer. `on_event:` is read-only: it cannot halt, skip
  or alter a call, and a callback error cannot change the run. Stopping a run
  early is the `context:` or `cancel_when:` policy's decision, not an observer
  return value.
- Built-in context management: token counting, model-window lookup, trimming,
  summarization, or a default compaction policy. The `context:` seam is the
  library's whole contribution; the caller implements the policy.
- A durable event log or trace. The library emits events; recording them is the
  caller's job.
- A public step machine. `run/3` is the only execution surface; approval is
  expressed as data, not as an insertion point.
- Tool schema authoring. `tool_call` derives schemas from `@spec`/`@doc`;
  `llm_call` projects them per dialect. Neither job moves here.

## 5. Design principles

1. **One call, one outcome.** The caller gets a finished state, not a machine to
   drive. Escape hatches are data (`Pending`) plus one resume function, not a
   second API.
2. **Honest outcomes.** `{:ok, _}` means the model asked for no more tools; it
   does not claim the answer was complete. A loop-stopped run is never `:ok`.
3. **Data, not processes.** Everything a paused run needs is in a struct, so the
   caller can persist it, hand it to a job, or drop it.
4. **Reuse the canonical form.** Transcripts are `LlmCall.Message`; tool results
   are `LlmCall.ToolResult`; failures are `LlmCall.Error` when `llm_call`
   produced them. No parallel types.
5. **Fail visibly, continue when the model can repair.** A broken tool result is
   sent back as an error result the model can read. A broken dispatcher or a
   broken approval is a tagged error to the caller.
6. **The budget guards side effects.** The step limit is checked before a model
   turn and again before any tool runs; a turn that has reached the budget still
   gets its answer, its tools do not run.
7. **Streaming is a reading mode.** `stream: true` and `stream: false` produce the
   same transcript and the same outcome shape from the same provider content.
8. **Observation is not control.** The observer sees step, token and tool
   boundaries in order; its return value is ignored and its errors never change
   the outcome. The library keeps no event history.
9. **Context is a policy, not a default.** Before each request the caller may
   pass the transcript through, replace it, or stop; the library never counts
   tokens, looks up a model window, or drops a message on its own. The transcript
   is what the model saw, and the event stream is the full history.
10. **One error type at the boundary.** `kind` says who is at fault;
    `cause` keeps the original `LlmCall.Error` for a caller that wants
    retryability.

## 6. Constraints

Hard facts this design lives with, each verified against the dependency:

| Constraint | Source |
| --- | --- |
| `ToolCall.run/4` returns `{:ok, term} \| {:pending, %ToolCall.Approval.Request{}} \| {:error, term}` | `deps/tool_call/lib/tool_call.ex` (`run/4`) |
| `%ToolCall.Approval.Request{}` holds `id, module, tool, args, reason, context, inserted_at` and contains no pids or closures | `deps/tool_call/lib/tool_call/approval.ex` |
| A resumed call must re-supply `validate_result:`, `timeout:`, `audit:`, `task_supervisor:`; the request stores no one-off options | `deps/tool_call/lib/tool_call/approval.ex` moduledoc |
| The pause happens before invocation; `{:required, reason}` does not run the tool | `deps/tool_call/lib/tool_call.ex` (`run/4` docs) |
| `LlmCall.Message.role` is `:user \| :assistant`; **tool results are content parts in a user turn**, not a `:tool` role | `deps/llm_call/lib/llm_call/message.ex` |
| `%LlmCall.ToolResult{}.content` is text-only (`[Content.Text.t()] \| String.t()`) | `deps/llm_call/lib/llm_call/tool_result.ex` |
| OpenAI Chat and Responses drop `is_error` on a tool result; the failure must be in the content text | `deps/llm_call/lib/llm_call/tool_result.ex` |
| A `ToolCall` with `arguments_error` set is replayable, and the repair is to send it back with a tool result saying the arguments were invalid | `llm_call` design §8.3 |
| `LlmCall.StreamAssembler.new/1` takes a `json_decoder:`; `feed/2` → `{:ok, asm, [ToolCall.t()]}`, and `finish/1` | `deps/llm_call/lib/llm_call/stream_assembler.ex` |
| `StreamAssembler` handles tool-call and stop events and ignores every other event | `deps/llm_call/lib/llm_call/stream_assembler.ex` |
| `%LlmCall.Response{}.usage` is `%LlmCall.Usage{} \| nil`, with `nil` meaning "not reported" per field | `deps/llm_call/lib/llm_call/usage.ex` |
| `LlmCall.Response.tool_calls/1` returns tool call parts in order | `deps/llm_call/lib/llm_call/response.ex` |
| `ToolCall.describe/2` returns `%{module:, name:, description:, parameters:}` per tool, so the dispatch map is derivable | `deps/tool_call/lib/tool_call.ex` |
| `LlmCall.complete/3` accepts only `codec:` and `headers:`; an unknown option is a `:validation` error attributed to the provider | `deps/llm_call/lib/llm_call.ex` (`@call_options`) |
| `LlmCall.stream/3` accepts `on_event:`, an observe-only 1-arity function whose return is ignored; a failure while reading raises `LlmCall.HTTP.Error` carrying an `%LlmCall.Error{}` | `deps/llm_call/lib/llm_call/stream.ex`, `http/error.ex` |
| `LlmCall.Tools.expand/2` turns modules, `{module, opts}` and specs into `%LlmCall.ToolSpec{}`; a module that does not `use ToolCall` is a `:validation` error | `deps/llm_call/lib/llm_call/tools.ex` |
| A stream that ends without its protocol terminator is an error, not a synthesized stop | `llm_call` design §12 |
| Capabilities are protocol-level; a model's context limit surfaces as a provider error, never a local fact | `deps/llm_call/lib/llm_call/capabilities.ex` |

Dependencies: `llm_call ~> 0.3` and `tool_call ~> 0.4`, both direct. Elixir
`~> 1.18`, matching `llm_call`.

Quality gate: the same VibeKit `mix ci` `llm_call` runs — `credo`, `dialyzer`,
`spec_lint` with warnings as errors, `ex_dna` at a zero clone budget, and
`reach`. That gate shapes the code: the tool-result failure paths share one
builder rather than a clause each.

## 7. Approaches considered

Three shapes were weighed.

**A1 — one-shot `run/3` that executes tools.** One call does everything and
returns a result. The 90% case writes nothing. Cost: no insertion point between
"the model asked" and "the tool ran".

**A2 — only a pure `step/2` machine.** `{:tool_calls, calls, cont}` or
`{:done, response}`. Fully inspectable, human-in-the-loop for free. Cost: the
caller writes the glue again, so the library earns nothing; without a `run/3`
nobody reaches for it.

**A3 — `run/3` implemented on top of `step/2`.** Both surfaces, one
implementation, so the step API cannot rot. Cost: two public APIs to specify and
defend.

**Chosen: A1.** The escape hatches that actually matter are expressible as data
rather than as an extra API. Pending approval was the first; the first release also includes user input
as a second `Pending.kind`, also a serializable struct plus `resume/3`. Both fit
A1: a pause is data, not a step machine. A3 was rejected as scope the project did
not want; A2 as a library with no reason to exist. A pause that needs to inspect
a running computation between steps — not just carry a value — would be the
signal to reopen a step API; the input pause does not.

### Observation

Three ways to expose the loop were weighed once live display became a
requirement rather than an afterthought.

**O1 — typed, observe-only events on `run/3` and `resume/3` (chosen).** An
`on_event:` 1-arity function receives an `%AgentCall.Event{}` at step, token,
tool and approval boundaries. Its return is ignored and its errors are rescued,
so it cannot alter the run. It fits A1: observation is data flowing out, not an
insertion point. Cost: a new public event vocabulary, and the caller must run the
loop off the UI process.

**O2 — forward `LlmCall.StreamEvent` and add tool events.** Full provider
fidelity and less new vocabulary, but a UI must handle two event types, raw
events carry no step or tool boundary, and `llm_call`'s event shape becomes part
of this library's public contract. Rejected.

**O3 — return an `Enumerable` of events, or subscribe to a run process.** The
most idiomatic streaming surface, with natural backpressure, but it replaces the
one-shot outcome model: errors and pauses become awkward inside an `Enumerable`,
and a caller that wants only the result must reduce. That is A3 in a different
dress. Rejected for 0.1.

### Context

Three ways to keep a growing transcript inside a model window were weighed.

**C1 — no seam; the caller pre-trims and restarts.** Smallest API, but the loop
grows the transcript after the caller has handed it over. When the window fills
mid-run there is no place to intervene; the provider fails the run after tools
have already run. Rejected.

**C2 — a caller-supplied policy before every request (chosen).** A `context:`
function receives the current transcript plus the step, the step budget, the
last turn's usage and the request; it returns the messages to send or a stop.
The caller owns token counting, window lookup, trimming and summarization. The
loop owns only the call site and the transcript replacement.

**C3 — library-owned context management.** Built-in tokenizers, model windows,
trimming or summarizing. Rejected: tokenizers and windows are model data
`llm_call` deliberately does not own, summarization is another model call with
its own cost and failure modes, and a default would silently change what the
model sees. Automatic retry on a provider context error is rejected for the same
reason plus provider-specific error detection.

## 8. Architecture

```text
                    caller (application, job, LiveView, CLI)
                                   |
                     AgentCall.run/3  |  resume/3
                                   |
                 +-----------------v------------------+
                 |            AgentCall loop          |
                 |  transcript, budget, tool results  |
                 +---------+----------------+---------+
                           |                |
            LlmCall.complete/3,       ToolCall.run/4
              LlmCall.stream/3               |
                           |                |
                 +---------v--------+   +---v------------------+
                 | LlmCall codecs   |   | tool_call modules    |
                 | OpenAI, Anthropic|   | (declared schemas,   |
                 | Gemini, ...      |   |  policies, dispatch) |
                 +---------+--------+   +----------------------+
                           |
                     provider HTTP
```

### Layers

1. **Loop** — sends a turn, reads tool calls, enforces the budget, builds the
   transcript, counts usage.
2. **Dispatch** — derives `name -> %AgentCall.Dispatch.Tool{}` (runner, spec,
   input marker) from `request.tools`, runs calls in ordered waves (serially by
   default) through `ToolCall.run/4`, renders results.
3. **Stream fold** — when enabled, folds events into the same response content
   the non-streaming path decodes.
4. **Observer** — emits `%AgentCall.Event{}` at step, token, tool and approval
   boundaries; the caller's function runs in the same process and its return is
   ignored. A separate `:telemetry` span layer reports shape and correlation to
   process-global handlers, never payloads.
5. **Context policy** — a caller function called before every request; it may
   replace the messages or stop the run, and the transcript follows what it
   returns.
6. **Types** — `Result`, `Pending`, `Error`, `Event`; plain structs, no behaviour.

Events leave the loop through the observer; they are not a return value and not
a stored log. The context policy sits between the budget check and the request,
not between the model and a tool call.

`LlmCall` keeps the transport, the codecs and the JSON seam. `ToolCall` keeps
schema derivation and execution policy. Neither is wrapped.

## 9. Public API

```elixir
@type outcome ::
        {:ok, AgentCall.Result.t()}
        | {:exhausted, AgentCall.Result.t()}
        | {:pending, AgentCall.Pending.t()}
        | {:error, AgentCall.Error.t()}

@spec run(LlmCall.Client.t(), LlmCall.Request.t(), keyword()) :: outcome()
@spec resume(LlmCall.Client.t(), AgentCall.Pending.t(), keyword()) :: outcome()
```

### 9.1 `run/3`

`run(client, request, opts)` — `request.tools` is the single source of truth: the
tools the model may call are the tools this loop can run. There is no second
`tools:` option to keep in sync; a `context:` policy may replace the request's
list per turn (§9.7), and the loop's dispatch map follows that same list.

| Option | Default | Meaning |
| --- | --- | --- |
| `max_steps:` | `8` | Model turns allowed. Must be a positive integer. |
| `max_concurrency:` | `1` | Maximum number of a turn's tool calls run at once; a positive integer. Calls run in ordered waves of at most this size: a later wave waits for the previous one, and a pause stops later waves. See §23.2. |
| `cancel_when:` | `nil` | `(AgentCall.Cancel.info() -> :cont \| {:cancel, term()})`, a caller policy checked at the safe boundaries; see §23.1. |
| `run_id:` | generated | Non-empty string identifying the run on `Result`, `Pending`, `Event` and telemetry; `nil` generates one. `resume/3` keeps the `Pending`'s id. |
| `stream:` | `false` | Run each turn over `LlmCall.stream/3` and assemble internally. |
| `tool_opts:` | `[]` | Passed to `ToolCall.run/4`: `timeout:`, `audit:`, `task_supervisor:`, `validate_result:`, `context:`, `approval:`. |
| `max_result_bytes:` | `8_192` | Cap on a rendered tool result before truncation is marked. |
| `format_result:` | `&__MODULE__.default_format/2` | `(term() -> String.t())` or `(term(), non_neg_integer() -> String.t())` for a tool's return value. |
| `on_event:` | `nil` | `(AgentCall.Event.t() -> any())`, observe-only; see §9.6. |
| `context:` | `nil` | `(messages, AgentCall.Context.info() -> AgentCall.Context.decision())`, called before each request; may also replace the tool entries for the turn; see §9.7. |
| `prompt:` | `nil` | `(AgentCall.Input.info() -> :cont \| {:ask, term()})`, caller/policy prompts at the turn or tool boundary; see §22. |
| `codec:` / `headers:` | — | Forwarded. These are the only two options `LlmCall.complete/3` accepts. |

An unknown key is a `:configuration` error, never forwarded: `llm_call` would
reject it as a `:validation` error attributed to the provider, which reads as the
wrong thing. `max_steps:` and `max_concurrency:` must be positive integers,
`max_result_bytes:` a non-negative one, `format_result:` a 1- or 2-arity function,
`on_event:` a 1-arity function or `nil`, `cancel_when:` a 1-arity function or
`nil`, `run_id:` a non-empty string or `nil`, and `stream:` a boolean; anything
else is a `:configuration` error. `context:` must be a 2-arity function or
`nil`; `prompt:` must be a 1-arity function or `nil`. `timeout:` is not a call
option — it is
`%LlmCall.Client{timeout:}` for reads and
`http_opts: [request_timeout: …]` for the request.

`tool_opts:` is forwarded verbatim, so a caller may pass `approval: :granted` to
auto-approve every call and never see a `Pending`. `resume/3` overrides
`approval:` for the head call it was paused on; the rest of the turn uses
`tool_opts:` unchanged.

`format_result:` must return a binary. A renderer that returns anything else is a
broken dispatcher, so it is a `:tool` error rather than a silently inspected
value. A renderer that raises, throws or exits is the same error: it cannot kill
the run after the tool's side effect.

The returned text must also be valid UTF-8, and that is the same `:tool` error.
Every codec's JSON encoder refuses an invalid byte, so letting one through would
surface as an `:llm` error on the *next* request instead of the `:tool` error it
is, and repairing the bytes would silently change what the caller asked the model
to read. The check covers the text that is *sent*: a result at or under
`max_result_bytes:` is walked once, and a longer one only as far as the cap, so
the cost follows the result and not the renderer's return value.

The message names the subject the same way the other renderer errors do: the
tool's name for a tool result, `"the input answer"` for a turn answer. A turn
answer is not a tool call, so blaming "a tool" would send the caller looking for
the wrong renderer.

`default_format/1` renders a binary verbatim and inspects everything else
without printable limits — a truncated map is a different bug than a large one.

A 2-arity renderer additionally receives a byte budget: `max_result_bytes:` plus
one, so a renderer that stops at its budget still produces one byte past the cap
and the result keeps its truncation marker. The entry limit `inspect/2` takes
counts collection *entries*, so the bound is exact only in the direction that
matters — every entry renders to at least one byte, so a rendering that elided
anything is necessarily over budget and a value that fits is never elided. One
large entry can still overrun it, and the result is then cut and marked as
usual. `default_format/2` is that bounded renderer, and it is the default.

`default_format/2` formats and does not truncate. A binary is returned whole: it
is already rendered text, and cutting it is the dispatch step's job, which owns
the code-point boundary and the marker. Keeping the cut out of the formatter is
what lets the formatter keep its `String.t()` contract — a value that is not
UTF-8 has no rendered text to return, and the dispatch step is where that can be
reported as a `:tool` error naming the call.

The 1-arity form remains for a renderer that owns its own budget; it renders the
whole value and the result is truncated afterwards.

### 9.2 `Result`

```elixir
defstruct [:run_id, :response, :transcript, :usage, :steps, :tool_calls, :stop_reason, :halt_reason]

@type t :: %__MODULE__{
        run_id: String.t(),
        response: LlmCall.Response.t() | nil,
        transcript: [LlmCall.Message.t()],
        usage: LlmCall.Usage.t() | nil,
        steps: non_neg_integer(),
        tool_calls: non_neg_integer(),
        stop_reason: LlmCall.stop_reason() | nil,
        halt_reason:
          nil | :budget | {:context, term()} | {:input, term()} | {:cancelled, term()}
      }
```

`Result` carries the run's `run_id`, the final `%LlmCall.Response{}`, the
`transcript` the model was last given, summed `usage`, `steps` taken (model
turns), how many tool results the loop produced (`tool_calls`), `stop_reason`,
which is the final response's own `LlmCall.stop_reason()` (`:end_turn |
:max_tokens | :content_filter | :error | …`) rather than a value of our own, and
`halt_reason`, which is `nil` for a normal finish, `:budget` when the step budget
stopped dispatch, `{:context, reason}` when the context policy stopped the run,
`{:input, reason}` when a turn-phase input prompt was cancelled, and
`{:cancelled, reason}` when the `cancel_when:` policy stopped the run. A
`tool_calls` count includes every non-`nil` result slot, including results a
parallel batch kept after an earlier call paused.

`response` and `stop_reason` are `nil` when there is no response to report: a
context policy stopped before the first request, a resumed run had no new model
turn — its next step was already beyond `max_steps:`, or the context policy
stopped before it — or a turn-phase input prompt was cancelled before the
request. `resume/3` does not receive the paused turn's response in `Pending`, so
a resumed run reports none rather than an invented one.

`{:ok, _}` means "the model asked for no more tools"; it does not claim the
answer was complete. A `:max_tokens` finish therefore stays visible in
`stop_reason` instead of being flattened into success.

A context policy may replace the transcript (§9.7). `Result.transcript` is the
model-visible context, not an audit log: the event stream is the full history.

`{:exhausted, result}` carries the transcript so far, including the assistant turn
whose tool calls did not run, so the caller can see what the model asked for and
decide whether to raise the budget. `halt_reason` says why the loop stopped.

### 9.3 `Pending`

```elixir
defstruct [:kind, :request, :approval, :input, :run_id, :transcript, :results, :remaining, :steps, :tool_calls, :usage, :last_usage]

@type t :: %__MODULE__{
        kind: :approval | :input,
        request: LlmCall.Request.t(),
        approval: ToolCall.Approval.Request.t() | nil,
        input: AgentCall.Input.t() | nil,
        run_id: String.t() | nil,
        transcript: [LlmCall.Message.t()],
        results: [LlmCall.ToolResult.t() | nil],
        remaining: [LlmCall.ToolCall.t()],
        steps: non_neg_integer(),
        tool_calls: non_neg_integer(),
        usage: LlmCall.Usage.t() | nil,
        last_usage: LlmCall.Usage.t() | nil
      }
```

`kind` is `:approval` for an approval pause and `:input` for the input pause;
the irrelevant payload is `nil`. `AgentCall.Input` and the resume rules are in
§22.

`results` is positional: one slot per assistant tool call, in call order, holding
the call's `%LlmCall.ToolResult{}` or `nil` when the call paused or was never
started. `remaining` is exactly the calls with a `nil` slot, in call order, the
paused one first; its length equals the `nil` count. A completed call has its
result at its own index, so a parallel batch keeps results for calls that
finished after an earlier pause. `tool_calls` is the run's completed tool-result
total: previous turns plus the non-`nil` slots of this pause.

`Pending` also carries the serializable `%ToolCall.Approval.Request{}`, the
request being run, the transcript up to the pause (assistant turn included), and
the counters so a resumed run reports totals once. `usage` is the accumulated
total; `last_usage` is the paused turn's own usage, kept so the context policy
sees the last prompt size after a resume. `run_id` is the id of the run that
paused; `resume/3` keeps it, so the resumed result and events correlate with the
original run. `request` is required, not optional: `resume/3` receives no
request, and needs it to rebuild the dispatch map and continue the conversation.
`request.messages` is the request as the turn began; a context policy may
already have compacted the transcript, and `resume/3` overrides
`request.messages` with `Pending.transcript` when it continues, so those
original messages are not sent again after a policy has run.

### 9.4 `Error`

```elixir
defstruct [:kind, :message, :cause]

@type kind :: :configuration | :llm | :tool
```

One error type at the boundary:

- `:configuration` — the caller's inputs cannot be run (unknown option, duplicate
  tool name, a `Pending` whose approval/input no longer matches the head call or
  whose positional results do not describe the assistant calls and `remaining`).
- `:llm` — `llm_call` refused or failed the call; `cause` holds the
  `%LlmCall.Error{}`, so retryability is `cause.retryable?`. This library passes
  the field through unchanged rather than re-deriving it: the classification
  lives in `llm_call` (a status, a transport reason, the provider's own code) and
  a copy here would drift. The requirement is therefore `llm_call ~> 0.4.0`, the
  release whose classification is the one this contract describes.
- `:tool` — the dispatcher itself is broken (a `tool_opts:` value
  `ToolCall.run/4` rejects, a `resolve` that raises, a renderer that raises,
  throws, exits or returns a non-binary).

### 9.5 `resume/3`

`resume(client, pending, opts)` takes exactly one of `approval:`
(`:granted | :denied`) or `input:` (`{:answer, term} | {:cancel, term}`),
matching `pending.kind`, plus whichever of `max_steps:`, `max_concurrency:`,
`cancel_when:`, `stream:`, `tool_opts:`, `max_result_bytes:`, `format_result:`,
`on_event:`, `context:`, `prompt:`, `codec:` and `headers:` the continued run
needs. A missing, duplicated or wrong-kind decision is a `:configuration` error
before anything runs.

`context:`, `prompt:`, `cancel_when:` and `max_concurrency:` are re-supplied, not
stored in `Pending`: they are code or batch policy, and the resumed run is a new
call. `context:` runs before the next request, not before the re-dispatched head
call; `pending.transcript` is the context at the pause, already compacted if the
policy compacted it.

`max_concurrency:` is a wave size for the re-dispatched batch: calls run in
ordered waves of at most that many, a later wave waits for the previous one, and
a pause stops later waves. A parallel pause resumed without it runs serially,
because the default is `1`. With a value greater than `1`, a tool-phase
`prompt:` and `format_result:` run in worker tasks, so a policy or renderer that
relies on process-local state is the caller's responsibility; `on_event:` stays
in the loop's process.

It re-dispatches the head of `pending.remaining` with the approval decision, then
runs the rest of `remaining` in call order (in waves when `max_concurrency:` is
greater than `1`) and sends **one** user turn of results in call order. A denial
becomes a normal `is_error` result — the model asked, was refused, and is told.
Re-dispatch is safe because the pause happened before invocation; the paused call
never ran.

The re-dispatched paused batch runs under the explicit approval/input decision
and is **not** checked again by `cancel_when:`. The policy is checked at each new
turn entry and before a new tool batch; a resumed run that re-pauses checks again
only when it starts one of those. A `:tools` cancel runs before the budget guard
for that turn, so it wins when both are due.

For `kind: :input`, §22.5 defines the continuation: a tool-target answer is a
`ToolResult` in the same user turn; a turn-target answer is a user message and
the next request; a cancel is an `is_error` result for a tool and
`{:exhausted, halt_reason: {:input, reason}}` for a turn.

The budget follows the run, not the call. A resumed tool-target pause already
passed both budget guards, so `resume/3` finishes it and the next model turn
checks the budget against `pending.steps`. A turn-target pause happened before
the request, so its answer's model turn is checked against `pending.steps` first.
Lowering `max_steps:` below the steps already taken therefore stops the loop
before a model turn, not in the middle of a paused tool target.

A resumed run can pause again on a later call in the same turn: it returns a new
`Pending` with the updated `results`, `remaining` and counters.

Before any call runs, `resume/3` checks that the pause still describes the head
call: for an approval pause, `approval.tool` and `approval.args` must match the
head's name and parsed arguments (the approval request stores no `call_id`, so
that is the strongest check the data allows); for a tool-target input pause,
`input.call`'s id, name and arguments must match. It also
checks that `pending.results` is a list with one slot per assistant tool call and
a `nil` count equal to the length of `pending.remaining`, and that
`pending.run_id` is a non-empty string or `nil`; a nil id is replaced with a
generated one on resume. Any mismatch is a `:configuration` error, not a
best-effort dispatch or a `MatchError`.

### 9.6 Events

```elixir
defstruct [:type, :step, :run_id, :data]

@type type ::
        :run_started
        | :context_updated
        | :step_started
        | :text_delta
        | :thinking_delta
        | :tool_call_started
        | :tool_result
        | :step_finished
        | :approval_required
        | :input_required
        | :checkpoint
        | :finished

@type t :: %__MODULE__{
        type: type(),
        step: pos_integer() | nil,
        run_id: String.t(),
        data: map()
      }
```

`on_event:` is an observe-only 1-arity function. It runs synchronously in the
loop's process, in order; its return value is ignored; an exception, throw or
exit from it is caught and does not change the run. It must return quickly — a UI
process is reached by `send/2` or PubSub, not by a blocking call. The library
adds no queue, no process and no backpressure, so a slow observer slows the loop.
`run/3` is synchronous; a product that must stay responsive runs it in a `Task`
or a job and lets the observer hand events to the UI process.

`step` is the model turn the event belongs to; it is `nil` on `:run_started` and
`:finished`.

| Event | When | Payload |
| --- | --- | --- |
| `:run_started` | once, before the first request | `%{resumed?: boolean, stream?: boolean, max_steps: pos_integer, max_concurrency: pos_integer, tools: [String.t()], context?: boolean, prompt?: boolean, cancel?: boolean, input_tools: [String.t()]}` |
| `:context_updated` | when the policy returns a different message list | `%{before: non_neg_integer, after: non_neg_integer}` |
| `:step_started` | before each model request | `%{tools: [String.t()]}`, the sorted names this turn offers; the step is on the event |
| `:text_delta` | as text arrives, only with `stream: true` | `%{text: String.t()}` |
| `:thinking_delta` | as thinking text arrives, only with `stream: true` | `%{text: String.t()}` |
| `:tool_call_started` | before a call is dispatched | `%{call: LlmCall.ToolCall.t(), module: module() \| nil}` |
| `:tool_result` | after a call is rendered | `%{call: LlmCall.ToolCall.t(), result: LlmCall.ToolResult.t()}` |
| `:step_finished` | after the response is complete, before dispatch | `%{response: LlmCall.Response.t()}` |
| `:checkpoint` | after all tool results of a completed tool turn, before the next turn | `%{checkpoint: AgentCall.Checkpoint.t()}` |
| `:approval_required` | when a call pauses | `%{pending: AgentCall.Pending.t()}` |
| `:input_required` | when an input pause is built | `%{pending: AgentCall.Pending.t()}` |
| `:finished` | once, last | `%{status: :ok \| :exhausted \| :pending \| :error, stop_reason: LlmCall.stop_reason() \| nil, steps: non_neg_integer(), tool_calls: non_neg_integer(), halt_reason: nil \| :budget \| {:context, term()} \| {:input, term()} \| {:cancelled, term()}}`, plus `error: AgentCall.Error.t()` when `status` is `:error` |

Guarantees:

- `:run_started` is first and `:finished` is last, exactly once. `status` mirrors
  the outcome union, so a UI renders the same four endings the caller receives.
- Every event carries `run_id`, the id of the run that emitted it; a resumed run
  keeps the `Pending`'s id. `run_id` is the `Event` field, not duplicated in any
  `data` map. `max_concurrency:`, `cancel?:` and the other shape keys of the
  `:run_started` payload are keys of `data`.
- Validation happens before `:run_started`: a run rejected for options, a bad
  tool map or a bad `Pending` emits no events.
- `:step_started` precedes the request for that step; `:step_finished` follows
  the assembled response and carries it whole, so a non-streaming UI is complete
  without delta events. A turn that errors before a response exists emits no
  `:step_finished`; `:finished(:error)` is the ending.
- A model turn is one `:step_started` / `:step_finished` pair; `:context_updated`
  may immediately precede `:step_started`, and the tool events for the turn's
  calls fall between `:step_finished` and the next `:context_updated` /
  `:step_started`.
- The context policy runs after the budget check and before `:step_started`.
  When it returns a different message list, `:context_updated` is emitted first;
  when it returns `{:stop, reason}`, no `:step_started` follows and
  `:finished(:exhausted, halt_reason: {:context, reason})` ends the run.
  `halt_reason` is `:budget`, `{:context, reason}`, `{:input, reason}` or
  `{:cancelled, reason}` on `:exhausted`, and `nil` on the other endings.
- Approval and input are both `:pending`; `Pending.kind` and `Input.source`
  discriminate. `:input_required` precedes `:finished(:pending)`, and a
  turn-phase cancel ends with `:finished(:exhausted, halt_reason: {:input,
  reason})`. The input contract is §22.
- Every dispatched call is announced before it runs. A call that pauses is
  announced, then `:approval_required` follows and no `:tool_result` exists yet;
  `resume/3` announces the same head call again before producing the result. A UI
  that keeps both the transcript and the live events dedupes by `call_id`, not by
  event count.
- A cancellation emits no request at `:turn` and no tool event at `:tools`; it
  ends with `:finished(:exhausted, halt_reason: {:cancelled, reason})`. A
  `:tools` cancel is checked before the budget guard, so it wins when both are
  due. The resume contract is §9.5 and §23.1.
- A completed tool turn emits exactly one `:checkpoint` after its
  `:tool_result` events and before the next `:context_updated` / `:step_started`.
  A pause or a no-tool final answer emits none. The event is additive; a
  consumer needs a catch-all clause.
- A parallel batch announces every call in a wave before its tasks start, emits
  a result for each completed call in call order, and follows the wave with its
  first pause. The `tool_calls` count in `:finished` counts completed results,
  including ones a pause kept in a later slot.
- Arguments that failed to parse, a name with no runner, a tool error and a
  raised tool all get the same start/result pair; the failure is in
  `result.is_error`, exactly as the model sees it.
- A dispatcher-level `:tool` error can end a run after `:tool_call_started`;
  `:finished(:error)` is the terminal signal and the UI clears the running call.
- Thinking signatures, provider `Raw` parts and response `raw` are not events of
  their own; they ride in the transcript and in `:step_finished`'s response. No
  event carries a `client`, header, credential or provider payload.
- A UI that appended delta events uses `:step_finished` to settle the step, not
  to render the same text again.
- Events are not stored. A caller that wants a full history records them; the
  transcript is the model-visible context, which a policy may have replaced.

`resume/3` emits `:run_started` with `resumed?: true` and continues step
numbering from `pending.steps`; the resumed head call keeps the step it was
announced under before the pause. `cancel?` reports the re-supplied
`cancel_when:` policy, and `max_concurrency:` reports the re-supplied batch size,
defaulting to `1`.

### 9.7 Context policy

```elixir
@type info :: %{
        step: pos_integer(),
        max_steps: pos_integer(),
        usage: LlmCall.Usage.t() | nil,
        request: LlmCall.Request.t()
      }

@type decision ::
        {:cont, [LlmCall.Message.t()]}
        | {:cont, [LlmCall.Message.t()], [LlmCall.Request.tool_entry()] | nil}
        | {:stop, term()}
```

`context:` is a 2-arity function called **before every model request**, after
the step-budget check and before `:step_started`. A module works too: pass
`&MyContext.fit/2`. It receives the current
messages; `info` carries the turn number, the step budget, the last response's
`LlmCall.Usage` (nil on the first request; `pending.last_usage` after a resume)
and the request being run, with `info.request.messages` equal to the first
argument. It decides:

- `{:cont, messages}` — send these messages. Returning the input unchanged is
  the no-op policy; returning a shorter list with old turns dropped, or a
  summarized one, is compaction. The returned list becomes the loop's messages
  and therefore the transcript.
- `{:cont, messages, tools}` — additionally replace the tool entries for this
  turn and every later one, until the policy returns a different list. The
  entries take the same shape as `LlmCall.Request.tools`; an empty list is
  legal and means the model is offered no tools; `nil` leaves the current set
  alone, so `{:cont, messages, nil}` equals `{:cont, messages}`. A malformed
  entry is a `:configuration` error before the request.
- `{:stop, reason}` — stop before the request. The run returns
  `{:exhausted, %Result{halt_reason: {:context, reason}}}`; no model call is
  made. If the policy stops before the first turn, `response` and `stop_reason`
  are `nil` and `steps` is `0`.

The policy owns the decision the library cannot make: token counting, the model
window, what to keep, whether to summarize, and whether to stop. The library
does none of it. `info.usage` is the provider's own count for the last request,
which a policy can use instead of tokenizing everything; the current tool
results are not in it yet.

A narrowed set is the set the model is offered **and** the set the loop
dispatches: a name absent from it is answered with the same `"no tool named
..."` result as a hallucinated one, never by running the tool. The entries are
written into the request the run carries, so `Pending` and `Checkpoint` persist
the narrowed set — a resume after a narrowed turn dispatches under it, not under
the run's original set. A policy may introduce an entry the original request did
not declare. `:step_started` reports each turn's set as
`data: %{tools: [String.t()]}`, which is how a gradual grant is audited.

`:run_started` is emitted before the first turn, so it cannot know what a policy
will narrow to. On `run/3` its `tools:` and `input_tools:` are the run's
**original** declaration, not the first turn's set. On `resume/3` and
`resume_checkpoint/3` there is no original left to report: they build the map
from the record, so the reported set is the one the `Pending`/`Checkpoint`
carried, which may already be narrowed. Either way a caller that needs the live
set reads `:step_started`, or the request it sends.

Calling the policy before `:run_started` would make the first case exact, and is
deliberately not done: it would move the policy out of the turn boundary it is
defined at.

The returned list must be a non-empty list of `%LlmCall.Message{}`. Tool-call and
tool-result pairing is the policy's responsibility: `llm_call` validates the
next request, and a broken pairing is an `:llm` error, not something the loop
repairs. A policy that raises or returns anything else is a `:configuration`
error; the loop does not crash on caller code.

```elixir
context: fn messages, info ->
  if MyTokens.count(messages) > MyWindow.for(info.request.model) do
    {:cont, MyCompactor.compact(messages)}
  else
    {:cont, messages}
  end
end
```

A compaction replaces the transcript. `Result.transcript` and
`Pending.transcript` are the context the model actually saw; the event stream
is the full history. `resume/3` re-supplies `context:` because a function is
not serializable and the resumed run is a new call.

If the policy lets a request through and the provider still rejects it as too
long, the run returns `{:error, %Error{kind: :llm}}`; there is no automatic
retry. The policy is the prevention; the provider error is the fallback.

## 10. The loop

```
run(client, request, opts):
  tools = dispatch_map(request.tools)           # name -> Tool, via ToolCall.describe/2
  turn(1, request.messages, counters, tools, opts, request)

turn(step, messages, counters, tools, opts, request):
  # The budget is checked before the request, and again before any tool runs.
  # A turn at the budget still gets its answer; its tools do not run.
  step > max_steps -> {:exhausted, result(transcript: messages, halt_reason: :budget)}

  info = %{
    step: step,
    max_steps: max_steps,
    usage: counters.last_usage,
    request: %{request | messages: messages}
  }

  case fit(messages, info) do
    {:stop, reason} ->
      {:exhausted, result(transcript: messages, halt_reason: {:context, reason})}

    {:cont, messages} ->
      case cancel(:turn, step, messages, nil) do
        {:cancel, reason} ->
          {:exhausted, result(transcript: messages, halt_reason: {:cancelled, reason})}

        :cont ->
          response  = complete(client, %{request | messages: messages}, opts)
          assistant = %Message{role: :assistant, content: response.content}
          calls     = LlmCall.Response.tool_calls(response)

          []    -> {:ok, result(transcript: messages ++ [assistant], stop_reason: response.stop_reason)}
          calls ->
              if step == max_steps,
                do: {:exhausted, result(transcript: messages ++ [assistant], stop_reason: response.stop_reason, halt_reason: :budget)},
                else: dispatch(step, messages, assistant, response, calls, tools, opts, counters, request)
      end
  end

dispatch(step, messages, assistant, response, calls, tools, opts, counters, request):
  # The cancel check is before the budget guard: a turn that is both at the
  # budget and cancelled reports the cancellation, and runs no call.
  case cancel(:tools, step, messages ++ [assistant], calls) do
    {:cancel, reason} ->
      {:exhausted, result(transcript: messages ++ [assistant], stop_reason: response.stop_reason, halt_reason: {:cancelled, reason})}

    :cont ->
      if step == max_steps,
        do: {:exhausted, result(transcript: messages ++ [assistant], stop_reason: response.stop_reason, halt_reason: :budget)},
        else: dispatch_calls(step, messages, assistant, calls, tools, opts, counters, request)
  end

dispatch_calls(step, messages, assistant, calls, tools, opts, counters, request):
  # `dispatch_calls` runs the admitted batch; `run_calls/3` is the dispatch
  # primitive that runs calls in ordered waves of at most `max_concurrency:`.
  # Serial `1` stops at the first pause; a larger value keeps the results of
  # calls completed after an earlier pause and stops later waves at a pause.
  case run_calls(calls, tools, opts) do
    {:ok, slots} ->
      turn(step + 1,
           messages ++ [assistant, %Message{role: :user, content: final_results(slots)}],
           count(counters, slots), tools, opts, request)

    {:pending, pause, slots, remaining} ->
      {:pending, %Pending{kind: kind(pause),
                          approval: approval(pause),
                          input: input(pause),
                          transcript: messages ++ [assistant],
                          results: slots,
                          remaining: remaining}}
  end
```

`fit/2` is the caller's `context:` policy, or a pass-through when none is
configured.

Six rules the pseudocode pins, each of which a naive loop gets wrong:

1. **The guard is at entry and before dispatch.** Only checking it on the
   no-calls branch lets a model call tools forever.
2. **A turn at `max_steps` still receives its answer; its tool calls do not
   run.** Running them would mean spending side effects after the budget is gone.
3. **`{:exhausted, _}` carries the transcript so far and a `halt_reason`**, so the
   caller can see what the model asked for and why the loop stopped.
4. **The context policy runs after the budget check and before the request.**
   `{:cont, messages}` replaces the transcript; `{:stop, reason}` is an
   `:exhausted` run with `halt_reason: {:context, reason}`, never `:ok` and never
   an `:llm` error. Nothing else in the loop drops a message.
5. **Cancellation is checked at two safe boundaries.** `:turn` is after the
   budget/context check and before the turn prompt and request; `:tools` is
   after the response and before any call starts, and before the budget guard.
   No request or tool runs on a cancel, and the result carries
   `halt_reason: {:cancelled, reason}`. A resumed paused batch is not checked
   again; see §9.5.
6. **Tool results are positional slots.** `run_calls` returns one slot per call,
   `nil` for a paused or unstarted call. A completed turn filters the nils into
   the one user turn in call order; a pause returns the slots and the calls still
   to dispatch.

Two shapes matter and are not interchangeable: the assistant turn carries the
response's content verbatim (including `ToolCall` parts), and the tool results go
into a **user** turn. That is `llm_call`'s canonical form; the four bundled codecs
each translate it into their own wire shape, and they accept it back.

`run_calls/3` runs calls in ordered waves of at most `max_concurrency:` and
stops at the first `{:pending, _}`. With `max_concurrency: 1` that is the serial
walk: the paused call is the head of `remaining` and every later call has a
`nil` slot. With a larger value, results completed after an earlier pause keep
their slots and a pause stops every later wave because those calls never
started. A paused call cannot be skipped: the model asked for it and no result
exists yet. `llm_call`'s pairing check validates result → call and leaves a call
with no result alone, so a turn sent with three calls and one result encodes
cleanly here and is rejected by the provider. That is the bug the
`results`/`remaining` split exists to prevent: `resume/3` re-dispatches the
`nil` slots with the approval/input decisions, continues the rest, then sends
one user turn of results in call order.

The input surface adds call sites without changing this turn shape: a
turn-phase `prompt:` runs after the context policy and before `:step_started`; a
tool-phase `prompt:` or a marked input tool runs before `ToolCall.run/4`. §22.6
is the ordering. The pseudocode above is the 0.1 subset; an input answer is a
user message (turn target) or a tool result (tool target), never a new outcome.

## 11. Tool dispatch

`request.tools` accepts `module`, `{module, opts}`, and `%LlmCall.ToolSpec{}`
(`llm_call` normalizes them per codec). Dispatch is built from the modules only:
`ToolCall.describe(module, codec_opts)` yields `%{module:, name:, ...}` per tool,
so `name -> %AgentCall.Dispatch.Tool{}` (the runner, the derived spec and the
input marker) needs no extra declaration and cannot drift from the schema
actually sent. `{module, opts}` reuses the codec options `llm_call` already
threads, not `tool_call` run options; run options live in `tool_opts:`. That is
exactly `strict:` with a boolean or `nil` value. Another key, or another value —
including `tool_call`'s own `strict: :fine_tuned` render mode — is a
`:configuration` error before the first event, because the entry is forwarded to
the codec verbatim and would otherwise fail there as an `:llm` error attributed
to the provider.

This validation stops at the entry's options. A `%LlmCall.ToolSpec{}`'s field
*types* are checked by the request shape check, but its field *values* are the
dialect's business: `kind: :builtin` is legal on Anthropic and Gemini and refused
by OpenAI Chat, `provider_options` keys must be strings for JSON, and
`parameters` must be JSON-encodable. Judging any of those here would put a
provider branch in a protocol-neutral module and over-reject a spec a different
dialect accepts.

- A `%LlmCall.ToolSpec{}` entry declares a tool with no runner. If the model
  calls it, the loop does **not** abort: the call becomes a `ToolResult` with
  `is_error: true` and content naming the missing runner, and the model sees why.
- The same tool name declared by two modules is a `:configuration` error before
  the first request. Silently picking one would make the transcript unreplayable.
- A module that does not `use ToolCall`, a malformed entry, or a `describe/2`
  raise is a `:configuration` error before the first request, not a `:validation`
  error attributed to a codec.

## 12. Tool results and failure handling

| Situation | Behaviour |
| --- | --- |
| The `run/3` request's exact shape, nested message/tool structs, a `{module, opts}` entry whose opts are not the codec's (`strict:` boolean or `nil`), or improper `messages`/`tools` lists are malformed | `{:error, %Error{kind: :configuration}}` before `:run_started`; no request. The check covers field *types*; a `%LlmCall.ToolSpec{}` whose *values* one dialect refuses is that dialect's `:llm` error, because the rule is protocol-specific — `kind: :builtin` is legal on Anthropic and Gemini and refused by OpenAI Chat, so refusing it earlier would be a provider branch here. A non-string `provider_options` key and a non-JSON `parameters` value are the same case. |
| Context policy returns `{:cont, messages}` with a different list | Send the new list; emit `:context_updated`; the transcript becomes the model-visible context. |
| Context policy returns `{:stop, reason}` | `{:exhausted, %Result{halt_reason: {:context, reason}}}`; no request is made. `response` is `nil` if no turn ran. |
| Context policy raises or returns a bad shape | `{:error, %Error{kind: :configuration}}`; the loop does not crash on caller code. |
| Context policy returns messages that break tool pairing | The next `llm_call` request returns `:llm`; the loop does not repair it. |
| A marked input-tool call has `arguments_error` | No pause; `is_error` result naming the invalid arguments. |
| `prompt:` raises, throws, exits or returns a bad shape | `{:error, %Error{kind: :configuration}}`; the loop does not crash on caller code. |
| An input `{:cancel, reason}` | Tool target: `is_error` result; turn target: `{:exhausted, halt_reason: {:input, reason}}`. |
| The provider rejects a request the policy allowed | `{:error, %Error{kind: :llm}}`; no retry; the policy is the prevention. |
| `call.arguments_error` is set | Do not call the tool. Send a `ToolResult` (`is_error: true`) naming the reason, so the model can repair. |
| Tool returns `{:ok, value}` | `ToolResult` with `format_result(value)`, capped at `max_result_bytes:`. |
| Rendered result is empty or whitespace-only | Substitute `"(no output)"`. Anthropic rejects a `tool_result` whose text block is empty *or* whitespace-only, so passing an empty string through would fail one codec and pass three. |
| Tool returns `{:error, reason}` | `ToolResult` with `is_error: true` and `inspect(reason)`; the turn continues. |
| Tool returns `{:pending, req}` | Stop. Return `{:pending, %Pending{}}` with positional `results` slots and `remaining`; a parallel batch keeps results completed after an earlier pause. `resume/3` continues. |
| `cancel_when:` returns `{:cancel, reason}` at `:turn` | `{:exhausted, %Result{halt_reason: {:cancelled, reason}}}`; no request and no tool. `response`/`stop_reason` are nil before the first turn and the last turn's after one. |
| `cancel_when:` returns `{:cancel, reason}` at `:tools` | `{:exhausted, %Result{halt_reason: {:cancelled, reason}}}`; the assistant turn is in the transcript and no call runs. The check is before the budget guard, so a cancel wins over an equally due `:budget` stop. |
| `cancel_when:` raises, throws, exits or returns a bad shape | `{:error, %Error{kind: :configuration}}`; no crash and no request/tool at that boundary. |
| A tool-target pause resumes with a `Pending` whose top-level shape, transcript, `results` slots, `remaining`, `run_id`, usage values, `ToolResult` content/is_error, a `Content` field, request fields or `ToolCall`/`ToolSpec` fields are malformed | `:configuration` error before any call runs. `Input.source` must be `:model` or `:policy`, and `Request.stream` must be boolean. A nil `run_id` is normalized to a generated id. The slots and remaining calls must describe the paused turn in call order. `ToolResult`/`ToolCall` identifiers are nullable; the adapter decides which one it needs. Every transcript element must be a valid `%LlmCall.Message{}` with content parts. Request `output/modalities/reasoning/params` and all `ToolSpec` fields are checked. |
| A parallel tool task exits abnormally | The started span may have no stop; the run records the exit as `{:error, %Error{kind: :tool}}` and does not fabricate a result. |
| A telemetry handler raises | `:telemetry` catches it; the run's outcome and events are unchanged. |
| Tool raises or exits | Rescued (or caught on exit), recorded as an `is_error` result naming the exception. A loop that dies on one bad tool is not worth its API. |
| The model calls a name no declared module provides | `is_error` result naming the name and the names that exist. The model hallucinated a tool; the loop tells it so. |
| A declared `%LlmCall.ToolSpec{}` has no runner | `is_error` result naming the tool and the missing runner. |
| `tool_opts:` is not a keyword list | `{:error, %Error{kind: :configuration}}` at the option layer; it is a caller input, not a tool result. |
| A `tool_opts:` value `ToolCall.run/4` rejects, a renderer raises, throws or exits, or `resolve` itself raises | `{:error, %Error{kind: :tool}}`. The dispatcher is broken, not the tool. |
| `resume/3` given a `Pending` whose head call no longer matches its approval/input, or whose positional results do not describe the paused turn | `:configuration` error before any call runs. |
| `LlmCall.complete/3` returns `{:error, err}` | `{:error, %Error{kind: :llm, cause: err}}`. No retry. |
| Streaming raises `LlmCall.HTTP.Error` | Rescued and mapped to `{:error, %Error{kind: :llm, cause: err}}`; stream mode and complete mode report the same outcome type. The stream telemetry span emits `:exception` and no `:stop`. |
| `max_steps` reached with calls pending | `{:exhausted, _}` with `halt_reason: :budget`; the calls do not run. The caller's budget is not a normal finish. |
| Rendered result exceeds the cap | Truncate and say so in the content — the marker is part of the text the model sees. |

Truncation and `is_error` both land in the content text because OpenAI has no
error flag and no other channel; that is `llm_call`'s documented drop. The exact
wording of the truncation marker, the missing-runner text and the invalid-argument
reason is the builder's.

## 13. Streaming

With `stream: true`, each turn is `LlmCall.stream/3` folded by the loop itself.
The context policy runs before the stream is started, so it sees and may replace
the messages that are streamed. `%LlmCall.StreamAssembler{}` supplies **only**
the tool calls — `feed/2` handles tool-call and stop events and ignores
everything else — so text, thinking, `Raw` parts, usage and the stop reason are
this library's accumulator. The contract has to be written down or the two
reading modes disagree:

| Part | Folded from |
| --- | --- |
| `Content.Text` | `:text_delta`, in provider order; consecutive deltas form one block and a delta after another text or thinking part opens a new one |
| `Content.Thinking` | `:thinking_delta` text + signature, **paired**. A delta joins the block it opened only while that block is open: any other stream event (a content or tool-call boundary, a text delta, a terminal delta) closes it. A later thinking block therefore appends a new `Content.Thinking{}`, and its signature signs that block; a signature with no open block is dropped rather than attached to an earlier block. An unsigned thinking block is rejected by Anthropic and OpenAI. |
| `Content.Raw` | provider events the codec did not map; `data` is the stream event, not the complete-mode block |
| `ToolCall` | `StreamAssembler.feed/2` + `finish/1`, in `index` order, **appended after** every text, thinking and `Raw` part |
| `usage`, `stop_reason` | the terminal event; never synthesized |
| `response.id`, `response.model`, `response.raw` | **not recoverable** — `nil` in stream mode, documented rather than faked |

Text and thinking keep the order the provider emitted them in. Tool calls keep
`index` order among themselves, but a stream does not place them at their
provider position: in 0.1 they follow the text and thinking parts, so a turn
that interleaves calls between those parts has a different part order from
`complete/3`. `finish/1` closes any call still open when the stream ends.

A `Content.Raw` part is the event the codec could not map, so its `data` can
differ between the two reading modes for the same provider content; it is a
passthrough, not a parity guarantee.

The assembler is built with the client's resolved JSON module
(`client.config.json`) as its `json_decoder:`. Without it, every streamed call
would arrive with `arguments_error: :no_json_decoder` and be reported as invalid
arguments the model never produced. With it, streamed arguments decode exactly as
they do over `complete/3`, and a genuinely malformed fragment still reaches the
repair path.

`finish/1` is mandatory: a stream that ends without it is how truncated arguments
get reported as complete. A stream that ends without its protocol terminator is a
`:llm` error, not a synthesized stop — `llm_call` raises `LlmCall.HTTP.Error` for
it, and the loop maps that exception rather than inventing a terminal event.
`finish/1` also closes the step: no `:step_finished` is emitted before it.

The loop returns `{:ok, _}` or `{:exhausted, _}` with the same shape either way;
only the response fields the stream cannot recover (`id`, `model`, `raw`) are
`nil`. A caller can switch `stream:` on without changing anything else it does.
With `stream: true` the fold reports text and thinking as `:text_delta` /
`:thinking_delta` events (§9.6); with `stream: false` those events do not exist
and `:step_finished` carries the whole response. There is still no second return
type.

## 14. Usage accounting

`%LlmCall.Usage{}` uses `nil` per field to mean "not reported". Summing must
therefore skip `nil` rather than coerce it to `0`: a run where one step reported
no cache reads and another reported 40 has 40, not 40-by-assumption. A field that
is `nil` in every step stays `nil` in the total, and a run where no step reported
usage has `usage: nil`, not a zeroed struct.

## 15. Module layout

`lib/agent_call.ex` holds `run/3`, `resume/3`, `resume_checkpoint/3` and the
outcome types. `lib/agent_call/result.ex`, `pending.ex`, `error.ex`, `event.ex`
and `input.ex` hold the public structs; `context.ex` and `cancel.ex` hold the
`AgentCall.Context` and `AgentCall.Cancel` policy types; `input.ex` also holds
the `use AgentCall.Input` macro and the prompt-policy types; `agent_tool.ex`
holds `AgentCall.AgentTool.run/4` and its types; `checkpoint.ex` holds
`AgentCall.Checkpoint` and its versioned envelope; `thread.ex` holds the
`AgentCall.Thread` behaviour and its types.
The loop, the dispatch map, the result renderer and the stream accumulator are
internal modules; their names and boundaries are the builder's, and nothing
outside the package may depend on them.

`test/support/` holds the fixture HTTP server and the stub tool modules; they are
test support, not part of the design. There is no configuration file, no
application callback module, and no supervision tree.

## 16. Testing

The suite must not need a live API. A local fixture server per codec, as
`llm_call` does with `test/support/test_http_server.ex`, answers
`complete/3` and `stream/3`; the protocol layer is never mocked.

- **One test per row of §12**, each asserting the exact `ToolResult` the model
  would see — not just the return value.
- **Event sequences:** one test per outcome (`:ok`, `:exhausted`, `:pending`,
  `:error`) asserting the exact ordered event list, that `:run_started` is first,
  and that `:finished` appears once and last.
- **Observer safety:** an `on_event:` function that raises does not change the
  outcome, and a stub tool records its invocation to prove
  `:tool_call_started` arrives before the side effect.
- **Delta gating:** no `:text_delta` or `:thinking_delta` with `stream: false`;
  deltas arrive in order with `stream: true`.
- **Resume events:** `:run_started` carries `resumed?: true`, step numbering
  continues from `pending.steps`, and the paused head is announced again.
- **Context policy:** a pass-through returns the same list and emits no
  `:context_updated`; a compaction sends the compacted messages to the fixture
  server, emits `:context_updated`, and replaces `Result.transcript`; a stop at
  step 1 returns `{:exhausted, %Result{response: nil, steps: 0, halt_reason: ...}}`;
  a stop after a turn keeps the last response; a raise or bad return is a
  `:configuration` error; a pairing-breaking return is an `:llm` error.
- **Context inputs and resume:** `info.step`, `info.max_steps` and `info.usage`
  follow §9.7 (usage is nil on the first request), the policy is not called when
  the step budget is already exhausted, and `resume/3` re-supplies `context:`
  before the resumed request.
- **Input and prompts:** a marked input module pauses with `source: :model` and
  its answer/cancel; a turn prompt answer is a user message and a cancel is
  `{:exhausted, halt_reason: {:input, _}}`; a tool prompt answer is a result and
  a cancel is `is_error`; the input-tool check wins over the prompt policy;
  ordering with approval; `Pending` serialization for both kinds; no schema
  validation beyond rendering. §22.10 is the full matrix.
- **Honesty tests:** `{:exhausted, _}` is never `{:ok, _}`; `{:pending, _}` is
  never `{:ok, _}`; a truncated result says so; a `:max_tokens` finish surfaces in
  `stop_reason` rather than as a plain success; a stream without `finish/1` cannot
  report complete.
- **A replay test per codec:** the transcript `run/3` builds must encode again
  through `LlmCall.encode(codec, %{request | messages: transcript}, config)` for
  the four bundled dialects. `Codec.Conformance.assert_replays/3` builds its own
  assistant fixtures and cannot consume a transcript, so it is the wrong tool
  here.
- **A multi-call pause test:** three calls, the second needs approval — the
  resumed run sends one user turn with three results in call order, and the first
  result is not re-executed. The parallel version repeats it with the first pause
  at index 1 and a later call in a wave.
- **Cancellation:** a `:turn` cancel sends no request and a `:tools` cancel runs
  no tool; response/stop_reason are nil only when no turn completed; a policy
  error at either boundary is `:configuration`; a cancel wins over an equally
  due budget stop; a resumed run checks `cancel_when:` at new turn entries and
  before a new tool batch, never before the paused batch it re-dispatches.
- **Parallel slots:** ordered results, a pause at index 0 and at index > 0,
  later completed results kept, multiple pauses/re-pause, one user turn in call
  order, counters/`last_usage`, input/approval/tool-prompt combinations,
  `max_concurrency: 1` preserving serial behavior, and a dispatcher error
  aborting without a fabricated result.
- **`run_id`:** supplied and generated ids on `Result`/`Pending`/`Event`;
  `resume/3` keeps the pending id and normalizes a nil one; an empty supplied id
  is a `:configuration` error; `term_to_binary` round trip.
- **Telemetry:** run/turn/tool/stream start/stop; tool outcomes including an
  `is_error` result as `:error`; a failed stream's `:exception` with no stop; a
  resumed approval/tool-input/turn-input span at the right step; durations; no
  messages/args/results in metadata; a raising handler cannot change the
  outcome. Handlers attach in `setup` and detach on exit.
- **A serialization test:** `Pending` survives `:erlang.term_to_binary/1` and
  `binary_to_term/1` and resumes with the same counters.
- **A checkpoint test:** `Checkpoint.dump/1`/`load/1` for `Pending` and
  `Checkpoint`; version/type/invalid payload; a `:checkpoint` event after a
  completed tool turn (not at a pause or a no-tool final); `resume_checkpoint/3`
  with no completed tool re-run; the checkpoint options, a pending after resume,
  a budget stop, a stream failure, and the fake-store journal/`cancel_when`
  failure seam.
- **A streaming parity test:** the same provider content read through
  `complete/3` and `stream/3` produces the same transcript, including thinking
  signatures.
- **Termination:** no input reaches step `max_steps + 1`, and a turn at the budget
  runs no tool.
- **Usage:** nil fields are skipped, not zeroed.

`mix ci` must be green with `ex_dna` at zero clones — a duplicated stop clause is a
gate failure, by design.

## 17. Compatibility and release policy

- The project is 0.x. This design is the contract; internals may change in a
  minor release without a shim. No compatibility layer is added for code this
  package just wrote.
- `Result`, `Pending`, `Error`, `Event` and `Checkpoint` are the public structs.
  Adding a field to `Result` or `Error` is additive; adding one to `Pending` or
  `Checkpoint` crosses a serialization boundary and is noted in the changelog.
- A `Pending` is data, not a session. It is guaranteed to resume with the release
  that produced it; cross-version resumption is not promised while 0.x.
- A `Checkpoint` is data, not a session. It is a completed-tool-turn state; the
  envelope version is `1`; a new field crosses the serialization boundary and is
  noted in the changelog; cross-version resumption is not promised while 0.x.
- `AgentCall.Thread` is a public behaviour, not a struct. Its `load/1` and
  `append/2` callbacks, the snapshot map fields and the record union are public;
  adding a callback is breaking for a module that declares the behaviour, and a
  new record type is additive while 0.x.
- `AgentCall.Event` is public. A new event type can appear in a minor release, so
  a consumer needs a catch-all clause; removing or renaming an event type is
  breaking. The first release adds the `run_id` field and `:checkpoint`; every
  event carries `run_id`.
- `AgentCall.Context` is a public type. A new `decision` variant is breaking;
  `Result.halt_reason` and the nilable `response` are additive, but a consumer
  must handle a policy stop.
- A context policy is code, not data: it is not stored in `Pending`, so a resumed
  run must supply it again.
- The first release adds `AgentCall.Input`, `Pending.kind`/`input`, `resume input:`, the
  `prompt:` option, `:input_required`, and `halt_reason {:input, _}`. It also
  adds cancellation (`cancel_when:`, `halt_reason {:cancelled, _}`), parallel
  tools (`max_concurrency:`, positional `Pending.results` slots), `run_id` on
  `Result`/`Pending`/`Event`, and `:telemetry` spans. It adds the checkpoint
  seam (`AgentCall.Checkpoint`, `resume_checkpoint/3`, the `:checkpoint` event,
  the versioned `Pending` envelope). A `Pending`/`Checkpoint` is not promised to
  resume across releases while 0.x.
- The package version stays **0.1.0** for all of the first release. The internal
  "P0" phase is not a package version; no later package version is published or
  implied.
- `:telemetry ~> 1.0` becomes a direct runtime dependency; it was already
  transitive through the transport. Telemetry is additive and carries no
  payloads; a handler failure cannot change a run.
- The transcript is `llm_call`'s canonical message form. An `llm_call` breaking
  change to that form is a breaking dependency bump here.
- An unknown option is rejected, so a new option is additive. A new outcome
  variant would be breaking.
- `%ToolCall.Approval.Request{}` is part of the public `Pending` type; a change to
  its serializable fields is breaking here too.
- Retry, persistence and provider routing are caller policy. Nothing in this
  library stores or retries anything.

## 18. Anti-goals

If any of these appear, the design has drifted:

- a process per conversation, a supervision tree, or a GenServer
- a conversation store, ETS table, or Ecto schema
- a library thread/session store, GenServer, or automatic thread load/append;
  `AgentCall.Thread` is a caller-implemented contract only
- a second context API, implicit thread, memory or RAG runtime
- re-implementing protocol, transport, JSON, or schema logic
- swallowing `{:pending, _}`, `arguments_error`, a tool error, or truncation
- inventing a canonical type that `llm_call` already owns
- provider-specific branches anywhere in this library
- a second `tools:` option that can disagree with `request.tools`
- a retry loop or a backoff policy
- an observer callback that can change control flow; the only control callbacks
  are the explicit `context:`, `prompt:` and `cancel_when:` policies, plus the
  caller-owned `on_pending:` of the §24 helper, which runs outside the inner
  loop
- an input pause that runs the tool; an input is a result, not an execution
- a JSON Schema validator or a prompt UI in the library
- a blocking callback that waits for the user inside the loop; §24's
  `on_pending:` may block in the outer tool task, bounded by the outer tool
  timeout, but it is not an inner-loop callback
- an implicit or default context policy: the loop never trims on its own
- in-library token counting, window lookup, trimming or summarization
- a transcript that drops messages without a context policy
- events that carry client credentials, headers or provider payloads
- telemetry metadata that carries messages, arguments, results, headers or
  credentials, or a telemetry handler that can change a run
- a mid-tool kill or a fabricated partial tool result
- a completion-order result list instead of positional slots, or a parallel
  default that changes the serial contract
- a checkpoint store, expiry, retention or automatic checkpoint
- a checkpoint after a partial stream, or a re-run of a completed tool
- an `on_checkpoint` control callback; the `:checkpoint` event plus the caller's
  `cancel_when` is the failure seam
- an `AgentCall.Journal` server or behaviour in 0.1
- an event history kept by the library
- a fifth outcome variant
- a version bump for a runtime control that is part of the first release

## 19. Decisions

Settled:

1. **A1, one-shot `run/3`.** A step machine is not public; approval and input
   are data plus `resume/3`. The second pause type did not change that; reopen
   only if a pause needs to inspect a running computation between steps.
2. **`Pending` carries the request.** `resume/3` has no request argument, and
   needs the model, params and tools to continue; this is a requirement, not a
   convenience.
3. **Parallel tools are opt-in.** `max_concurrency:` defaults to `1`, so order
   stays the transcript contract and the serial approval/input flow is unchanged.
   A larger value runs ordered waves and accepts that a non-gated call can run
   before a gated call's approval; strict pre-approval ordering uses `1`.
4. **Streaming is assembled internally.** The accumulator lives here because
   `StreamAssembler` only owns tool calls; its JSON decoder comes from the
   client's config.
5. **Stream failures are `:llm` errors.** `LlmCall.HTTP.Error` is rescued so both
   reading modes return the same outcome type.
6. **The budget guards side effects.** Entry and pre-dispatch checks; a turn at
   the budget answers but does not run tools.
7. **Tool results are a user turn.** That is `llm_call`'s canonical form, not a
   choice.
8. **`tool_call` is a direct dependency.** Its approval request is in the public
   type.
9. **Only `codec:` and `headers:` are forwarded.** Everything else is either this
   library's option or an error.
10. **Live observation is a 0.1 feature.** `on_event:` is typed and observe-only;
    token deltas exist only with `stream: true`; a run cannot be stopped by an
    observer return.
11. **Context is a caller policy.** `context:` runs after the budget check and
    before each request; it may pass through, compact or stop. A stop is
    `:exhausted` with `halt_reason: {:context, reason}`. The transcript is
    model-visible, the event stream is the full history, and the library owns no
    tokenizer, model window, trimming or summary.
12. **Input is a second pause kind.** `Pending.kind` is `:approval | :input`;
    `resume/3` takes exactly one of `approval:`/`input:`; the four outcomes stay.
13. **Two input sources, one payload.** A `use AgentCall.Input` module
    (model-initiated) or a `prompt:` policy (caller/policy-initiated) produces
    `AgentCall.Input`; tool targets answer with a tool result, turn targets with
    a user message; cancels are `is_error` (tool) or `:exhausted` with
    `{:input, reason}` (turn). 0.1.0.
14. **Cancellation is safe-boundary only.** `cancel_when:` runs at `:turn` and
    `:tools`; no mid-tool kill and no partial results. A cancel is terminal
    (`{:exhausted, halt_reason: {:cancelled, reason}}`), a `:tools` cancel wins
    over an equally due budget stop, and a resumed paused batch is not checked
    again. 0.1.0.
15. **Sparse result slots.** `Pending.results` is positional, one slot per
    assistant call; the final user turn filters nils and keeps call order. This
    is the only representation, serial and parallel. 0.1.0.
16. **`run_id` and additive telemetry.** `run_id:` correlates `Result`,
    `Pending`, `Event` and `:telemetry` metadata; telemetry carries no payloads
    and a handler failure cannot change the run. `on_event:` remains the UI
    surface. 0.1.0.
17. **The first release is 0.1.0.** P0 is a phase name, not a package version;
    no later package version is published or implied, and release stops before
    publishing.
18. **A checkpoint is data, not a session.** `Checkpoint`/`Pending` use a
    versioned binary envelope; the `:checkpoint` event hands the completed-tool
    state out; `resume_checkpoint/3` continues at the next turn. The caller
    stores; no mid-stream checkpoint, no completed-tool re-run and no library
    store. 0.1.0.
19. **A thread is caller-owned.** `AgentCall.Thread` is a behaviour with
    `load/1` and `append/2`; the caller owns the store and messages. The library
    never loads or appends, and adds no thread process/table/schema. Pending
    wins over checkpoint; the terminal result is appended after the outcome.
    0.1.0.

## 20. Design success criteria

This design is working if:

- A caller can run a complete tool loop with one function call, without writing
  the transcript, result and stop logic by hand.
- Every hard edge has a test that asserts the exact tool result the model would
  see, not just a return value.
- `{:ok, _}` never hides a budget stop, an approval pause, or a provider
  truncation.
- A transcript built by `run/3` replays through all four bundled codecs without
  repair.
- Streamed and non-streamed runs reconstruct the same text, thinking blocks with
  their signatures, and tool calls from the same provider content. In 0.1,
  `response.raw` is not captured in stream mode, and a tool call the provider
  interleaved between text or thinking parts is assembled after them, so the
  transcript's part order can differ.
- A product can render a run live — step, token, tool and approval boundaries —
  without the library owning a process or a store.
- A bug in the observer or a telemetry handler cannot change the run's outcome.
- A cancel at `:turn` sends no request and at `:tools` runs no tool; the
  cancellation is honest in `halt_reason` and cannot be resumed.
- Parallel results keep call-order slots, a pause stops later waves, and the final
  user turn is one message in call order; `max_concurrency: 1` remains the serial
  contract.
- A run id is on `Result`, `Pending`, `Event` and telemetry, and a resumed run
  keeps it; a paused batch resumed without `max_concurrency:` still works
  serially.
- Telemetry carries no messages, arguments, results or credentials, and the
  package stays 0.1.0 for all of P0.
- A caller can compact, pass through or stop a run before a request without the
  library owning a tokenizer or a model window.
- No message is dropped without a context policy, and a policy stop is never
  `:ok`; `halt_reason` says whether the budget or the policy stopped the run.
- A model can ask through a marked input module and a caller can ask through
  `prompt:`; both resume with one `input:` option and keep the four outcomes.
- A tool input answer is a result and a turn input answer is a user message; a
  cancel is honest (`is_error` for a tool, `{:input, _}` for a turn).
- The input surface adds no process, store, schema dependency or application
  config.
- A `Pending` can be persisted as a binary and resumed without re-running a
  completed call.
- A `Checkpoint` can be persisted and resumed at the next turn; completed tools
  do not re-run, no mid-stream state is promised, and the library stores
  nothing.
- A caller can implement `AgentCall.Thread`, load messages/pending/checkpoint,
  choose the matching run/resume path, and append records without the library
  owning a store or process.
- Adding a tool module requires no `AgentCall` change, and adding a provider
  requires no branch here.
- The package has no process, no store, no application config and no global state.
- The core has no retry, routing, memory or orchestration layer.

## 21. Builder's latitude

Naming and defaults are settled above only where a wrong guess changes the API.
The rest is the builder's:

- Internal module names and boundaries: loop, dispatch, renderer, accumulator.
- The exact wording of truncation, missing-runner, invalid-argument and
  hallucinated-name content.
- `default_format/1` and `default_format/2` beyond their pinned rules: binaries
  verbatim (empty and whitespace-only handled per §12), everything else inspected
  without printable limits, and `default_format/2` bounding its collection walk
  by the byte budget.
- Test strategy details beyond the required cases: the fixture server shape, the
  stub tool modules (ok, error, raise, pending, invalid arguments, empty,
  oversized), and fixture layout.
- Where inside each step the delta events are emitted, provided §9.6's order and
  the start/result pairing hold.
- A reference compaction policy or example (not shipped); the `decision` union
  and the `info` map are pinned.
- The prompt payload shape, the UI, and a reference input module or prompt
  policy example (not shipped); the `Input` fields and the prompt `info` keys are
  pinned.
- The checkpoint envelope's internal layout, the `:checkpoint` event data key,
  the journal guide/example storage, and the exact malformed-checkpoint
  messages.
- The thread example adapter's storage, its exact snapshot map extras, and the
  README guide wording, while the callbacks, snapshot fields and record union
  are pinned.
- Project scaffolding, `mix ci` wiring, CI workflow, README and Hex metadata.

## 22. Input and prompt control surface (0.1.0)

Status: first-release extension, approved 2026-11-25. This section extends §9.1, §9.2,
§9.3, §9.5, §9.6, §10, §12, §15, §16, §17, §18, §19, §20 and §21. Where they
conflict, this section wins for the first release.

### 22.1 Why

Approval is a binary decision about a tool the model already asked for, and the
tool runs with the model's arguments. It cannot express "choose one of these" or
"supply the missing value". Both are common product requirements, so the first release adds an
input pause with two sources:

- **model-initiated** through a marked input-tool module;
- **caller/policy-initiated** through a `prompt:` policy at a turn or tool
  boundary.

Both are still data plus one `resume/3`: the four outcomes do not change, and no
step machine is introduced.

### 22.2 Types

`AgentCall.Input` is the public pause payload and the `use` macro for input-tool
modules:

```elixir
defmodule AgentCall.Input do
  defstruct [:source, :target, :call, :spec, :prompt, :inserted_at]

  @type source :: :model | :policy
  @type target :: :turn | {:tool, LlmCall.ToolCall.t()}

  @type t :: %__MODULE__{
          source: source(),
          target: target(),
          call: LlmCall.ToolCall.t() | nil,
          spec: LlmCall.ToolSpec.t() | nil,
          prompt: term(),
          inserted_at: DateTime.t()
        }

  defmacro __using__(opts) do
    quote do
      use ToolCall, unquote(opts)
      def __agent_call_input__, do: true
    end
  end
end
```

`Pending` has the canonical §9.3 shape, discriminated by `kind`:

```elixir
defstruct [:kind, :request, :approval, :input, :run_id, :transcript, :results, :remaining, :steps, :tool_calls, :usage, :last_usage]

@type t :: %__MODULE__{
        kind: :approval | :input,
        request: LlmCall.Request.t(),
        approval: ToolCall.Approval.Request.t() | nil,
        input: AgentCall.Input.t() | nil,
        run_id: String.t(),
        transcript: [LlmCall.Message.t()],
        results: [LlmCall.ToolResult.t() | nil],
        remaining: [LlmCall.ToolCall.t()],
        steps: non_neg_integer(),
        tool_calls: non_neg_integer(),
        usage: LlmCall.Usage.t() | nil,
        last_usage: LlmCall.Usage.t() | nil
      }
```

An approval pause is `kind: :approval`, `input: nil`; an input pause is
`kind: :input`, `approval: nil`. `request`, `transcript`, positional `results`,
`remaining`, `run_id`, the counters and `last_usage` keep their §9.3 meaning. The
pause kind is data; a consumer that switches on `Pending.kind` sees both.

`resume/3` takes exactly one of:

```elixir
approval: :granted | :denied
input: {:answer, term()} | {:cancel, term()}
```

The option must match `pending.kind`; missing, both, or the wrong kind is a
`:configuration` error before anything runs. `prompt:`, `context:`, `on_event:`,
`tool_opts:`, the step/result/stream options and `codec:`/`headers:` are
re-supplied as in §9.5. There is no `input_tool:` option: the marked module in
`request.tools` is the identity.

`Result.halt_reason` gains `{:input, term()}`:

```elixir
@type halt_reason :: nil | :budget | {:context, term()} | {:input, term()}
```

`{:exhausted, _}` with `halt_reason: {:input, reason}` is a turn-phase prompt the
user cancelled. It is not an `:ok` run and not an `:llm` error.

### 22.3 Model-initiated input tools

An input tool is a module that uses `AgentCall.Input`:

```elixir
defmodule MyApp.AskUser do
  use AgentCall.Input

  @doc """
  Ask the user to choose.

  ## Parameters
    * `question` - the question
    * `options` - the choices
  """
  @spec ask(question :: String.t(), options :: [String.t()]) :: term()
  def ask(_question, _options), do: :ok
end
```

`use AgentCall.Input` performs `use ToolCall`, so `request.tools` accepts the
module as usual and `llm_call` projects the `@doc`/`@spec` schema for the codec.
The marker `__agent_call_input__/0` makes `Dispatch` treat every tool in that
module as an input tool: the function is never invoked, and a call to it pauses.
A dedicated module is expected; every tool it declares is an input tool.

A call to an input tool pauses with:

```elixir
%Pending{
  kind: :input,
  input: %Input{
    source: :model,
    target: {:tool, call},
    call: call,
    spec: spec,
    prompt: nil,
    inserted_at: DateTime.utc_now()
  },
  transcript: messages ++ [assistant],
  results: results_so_far,
  remaining: [call | rest],
  ...
}
```

The question and options are `call.arguments`; `Input.spec` is the
`%LlmCall.ToolSpec{}` derived for that tool, so a UI can render both without a
second description. If the call has `arguments_error`, the loop does **not**
pause: it sends the normal `is_error` tool result naming the invalid arguments so
the model can repair it.

A module that uses `AgentCall.Input` but is never called is inert. Using one
outside `AgentCall` calls its function normally; the marker only changes this
library's dispatch.

### 22.4 Caller and policy initiated prompts

`prompt:` is a 1-arity function or `nil`. It is called with the `info` map as
its only argument at two phases:

```elixir
%{
  phase: :turn | {:tool, LlmCall.ToolCall.t()},
  step: pos_integer(),
  max_steps: pos_integer(),
  usage: LlmCall.Usage.t() | nil,
  request: LlmCall.Request.t(),
  messages: [LlmCall.Message.t()],
  module: module() | nil,
  spec: LlmCall.ToolSpec.t() | nil
}
```

It returns `:cont` or `{:ask, payload}`. `payload` is caller data for the UI
(question, options, a form description, anything serializable). The policy does
not deny or stop; approval and `context:` already cover those. A raise, throw,
exit or malformed return is a `:configuration` error; the loop does not crash.

- `phase: :turn` runs after the budget check and the context policy, before
  `:step_started`. `{:ask, payload}` pauses with `target: :turn`,
  `source: :policy`, `call: nil`, `spec: nil`, `prompt: payload`.
- `phase: {:tool, call}` runs immediately before that call is dispatched, after
  the input-tool check and before `ToolCall.run/4`/approval. `{:ask, payload}`
  pauses with `target: {:tool, call}`, `source: :policy`, the call and its spec,
  and `prompt: payload`.

The policy runs again after a resume (the answer is a user message for `:turn`
and a result for `{:tool, _}`); it must inspect `info.messages` or the results and
return `:cont` once it has asked. The library keeps no "already asked" state.

### 22.5 Pending and resume

**Tool target** (`source: :model | :policy`, `target: {:tool, call}`):

- The paused call is the head of `remaining`; the tool never ran. The answer is
  rendered with `format_result`, capped by `max_result_bytes`, and substituted
  with `"(no output)"` when empty, exactly like a normal result. It becomes a
  `%LlmCall.ToolResult{call_id: call.id, name: call.name, is_error: false}`.
- `{:cancel, reason}` becomes an `is_error` result naming the cancellation; the
  turn continues. The model sees the refusal.
- `resume/3` checks the head call against `pending.input.call` by `call_id`, name
  and arguments before any call runs; a mismatch is `:configuration`.
- The rest of `remaining` runs in call order (in ordered waves when
  `max_concurrency:` is greater than `1`), then one user turn of the filled
  `pending.results` slots; the next model turn is `pending.steps + 1`. A later
  input or approval can pause again with a new `Pending`.

**Turn target** (`source: :policy`, `target: :turn`):

- The pause happens before the request; `transcript` is the current messages,
  `results: []`, `remaining: []`, `steps` is the completed turns.
- `{:answer, value}` is rendered and appended as
  `%LlmCall.Message{role: :user, content: [%LlmCall.Content.Text{text: rendered}]}`;
  the loop continues the same model turn (`pending.steps + 1`). The context and
  prompt policies run again before the request; the prompt policy is responsible
  for not asking twice.
- `{:cancel, reason}` returns
  `{:exhausted, %Result{halt_reason: {:input, reason}, transcript: messages,
  steps: pending.steps, response: nil, stop_reason: nil}}` and sends no request.

A turn prompt can occur after N turns; its `Pending` does not store the paused
turn's response, so a cancel reports `response: nil`/`stop_reason: nil` rather
than an invented one. The transcript still carries the prior turns.

### 22.6 Ordering

```text
turn: budget -> context -> prompt(:turn) -> :step_started -> request -> :step_finished -> tools

tools, per call in order:
  marked input module?  -> :input_required (source :model)
  prompt({:tool, call}) -> {:ask, _} -> :input_required (source :policy)
  otherwise             -> ToolCall.run/4 (approval) -> run/result
```

The input-tool check precedes the prompt policy, so one call cannot be both. A
tool-phase prompt precedes approval; an ask there never reaches approval. In a
parallel wave, several calls can pause; the first pause in call order wins and
the later paused calls stay in `remaining`. `resume/3` continues from the first
and may pause again. An approval-resumed head is re-dispatched, so the tool-phase
prompt policy runs for it again; an input answer consumes its head without
dispatching it, so that call is not re-offered to the policy.

### 22.7 Events

- `:input_required` is added to the event type union. It is emitted when an input
  pause is built, after `:run_started` and before `:finished(:pending)`, with
  `%{pending: %AgentCall.Pending{}}`.
- `:run_started` adds `prompt?: boolean` and `input_tools: [String.t()]` (the
  names of the marked input tools in `request.tools`). The P0 controls also add
  `cancel?: boolean` and `max_concurrency: pos_integer`; `run_id` is the event
  field, not a data key (§9.6, §23.3).
- `:finished` keeps `status: :pending` for both pause kinds; `halt_reason` can be
  `{:input, reason}` for a turn-phase cancel.
- `Pending.kind` and `Input.source` are the UI's discriminator. No event carries
  a client, header, credential or provider payload.

### 22.8 Rendering, cap and validation

The input answer is rendered with `format_result`, capped by
`max_result_bytes`, and uses `"(no output)"` for empty/whitespace content. A
renderer that raises/throws/exits on an input answer is a `:tool` error, matching
§9.4. The library does **not** validate the answer against a JSON Schema: it has
no schema validator and does not add one; the caller's prompt UI validates. The
`Input` struct contains only serializable data; the caller's `prompt` payload and
answer must be serializable when the caller persists a `Pending` or an answer.

### 22.9 Failure handling

| Situation | Behaviour |
| --- | --- |
| A marked input module is not in `request.tools` | It cannot be called; no pause. |
| A call to a marked input tool has `arguments_error` | No pause; `is_error` result naming the invalid arguments. |
| `prompt:` raises, throws, exits or returns malformed | `{:error, %Error{kind: :configuration}}`; `:finished(:error)` if `:run_started` was emitted. |
| `resume/3` gives neither or both of `approval:`/`input:` | `:configuration` before anything runs. |
| `resume/3` kind does not match `Pending.kind` | `:configuration` before anything runs. |
| Tool-target head call differs from `Pending.input.call` | `:configuration`; no call runs. |
| `{:cancel, reason}` on a turn target | `{:exhausted, halt_reason: {:input, reason}}`; no request. |
| `{:cancel, reason}` on a tool target | `is_error` tool result; the turn continues. |
| Empty/whitespace input answer | `"(no output)"`. |
| Oversized input answer | Truncate and mark. |
| Renderer raises on the answer | `{:error, %Error{kind: :tool}}`. |
| Answer does not match the caller's UI schema | The library accepts it; the caller's UI validates before `resume/3`. |

### 22.10 Testing

- A marked input module's schema appears through `ToolCall.describe/2`; its function is never called; a call pauses with `source: :model`; the answer becomes its result; cancel is `is_error`; invalid arguments do not pause.
- A turn `prompt:` asks, the answer is a user message, the request follows; cancel is `:exhausted` with `{:input, _}`; the policy is not asked twice when it inspects the transcript.
- A tool `prompt:` asks before approval, the answer is the call's result, the tool does not run; a `:cont` decision still reaches approval; the input-tool check wins over the policy.
- `Pending` serialization with both kinds; resume mismatch; head match; counters/`last_usage`; multiple pauses; budget and context interaction; events and ordering; streaming turns that call an input tool; replay of an input result through all four codecs.
- No schema validation test beyond "any term is accepted and rendered".

### 22.11 Compatibility

- The input surface is additive to the approval flow in the first release. `Pending` gains `kind` and `input`;
  `approval` becomes nilable. A `Pending` serialized by 0.1 is not promised to
  resume across releases while 0.x.
- `resume/3` gains `input:`; the event union gains `:input_required`;
  `halt_reason` gains `{:input, term}`; consumers need a catch-all for the event.
- `AgentCall.Input` and `use AgentCall.Input` are public. A marked module is not
  a normal runnable tool inside `AgentCall`; the marker is the contract.
- The input surface adds no new runtime dependency, process, store or application config.

### 22.12 Decisions

1. **Both sources.** Model-initiated through a marked module; caller/policy-initiated through `prompt:`.
2. **No name string.** `use AgentCall.Input` marks the module; no `input_tool:`, no reserved name.
3. **One pause kind.** `Pending.kind` is `:approval | :input`; the outcome union stays four values.
4. **Turn answers are user messages; tool answers are tool results.** The model-visible shape follows what the pause replaced.
5. **Cancel is honest.** A tool cancel is an `is_error` result; a turn cancel is `:exhausted` with `{:input, reason}`.
6. **No schema validation in the library.** The caller's UI validates the answer; the library renders and caps it.
7. **0.1.0.** This is the first release; the input surface is part of it.

### 22.13 Builder's latitude

- Internal module names and boundaries for the input dispatch and prompt call sites.
- The exact `Input.spec` derivation for a marked module (the `%LlmCall.ToolSpec{}` shape from `ToolCall.describe/2`).
- The exact prompt `info` map beyond the pinned keys, the rendering of cancellation text and the prompt payload shape.
- A reference input module or prompt policy example (not shipped) and the UI.

## 23. P0 runtime controls (0.1.0; internal 0.3 plan)

Status: first-release extension, approved 2026-11-25. The package version stays
0.1.0; "P0" / "0.3 plan" is an internal phase name, not a version. This section
extends §9.1, §9.2, §9.3, §9.5, §9.6, §10, §12, §15, §16, §17, §18, §19, §20
and §21. Where they conflict, this section wins for the first release.

### 23.1 Cancellation

`cancel_when:` is a 1-arity function or `nil`:

```elixir
@type info :: %{
        phase: :turn | :tools,
        step: pos_integer(),
        max_steps: pos_integer(),
        usage: LlmCall.Usage.t() | nil,
        request: LlmCall.Request.t(),
        messages: [LlmCall.Message.t()],
        calls: [LlmCall.ToolCall.t()] | nil
      }

@type decision :: :cont | {:cancel, term()}
```

It is checked at **safe boundaries only**:

- `phase: :turn` after the budget and context policy, before the turn prompt and
the model request; `calls` is `nil`.
- `phase: :tools` after the assistant response and before any tool in that turn
starts; `calls` is the whole batch.

A cancel set while tools are running is observed at the next turn entry; the
library does not kill tasks, and long tools are bounded by `tool_call`'s own
timeouts. This keeps the turn free of partial tool results: when the loop stops
at `:tools`, no call has run.

`{:cancel, reason}` returns
`{:exhausted, %Result{halt_reason: {:cancelled, reason}}}` and sends no request
and runs no tool. At `:turn` before the first request, `response`/`stop_reason`
are `nil`; after a completed turn they are that turn's response/reason. At
`:tools`, the assistant turn is in the transcript and no tool result is. The
cancel is terminal; there is no `resume/3` for it. A raise/throw/exit/malformed
return is a `:configuration` error.

The `:tools` check runs before the budget guard, so a turn that is both at
`max_steps:` and cancelled reports `{:cancelled, reason}`, not `:budget`; no call
runs either way. This precedence is pinned by a test.

`cancel_when:` is re-supplied on resume. It is checked at each new turn entry and
before a new tool batch, not before the paused batch `resume/3` re-dispatches:
that batch was already admitted by the original run and runs under the explicit
approval/input decision. A resumed run that re-pauses checks the policy again
only when it starts a new turn or a new batch.

`Result.halt_reason` gains `{:cancelled, term()}`. The run emits
`:finished(:exhausted)`; no new event is needed. `:run_started` adds
`cancel?: boolean`.

### 23.2 Parallel tool execution

`max_concurrency:` is a positive integer, default `1`. The turn's calls run in
call order through `Task.async_stream(..., ordered: true, max_concurrency: n)`
when it is greater than 1; each task calls one `ToolCall.run/4`. The tasks are
ephemeral; the library still owns no long-lived process, store or pool.

`max_concurrency:` is a **wave size**, not a sliding window. A turn's calls are
split into ordered waves of at most that many; a later wave waits for every call
in the previous wave, and a pause stops all later waves. Calls in later waves
were never started, so they keep `nil` slots and stay in `remaining`. The
default `1` is the serial walk. A parallel pause resumed without
`max_concurrency:` runs serially, because the option is re-supplied and is not
stored in `Pending`.

With `max_concurrency > 1`, the tool-phase `prompt:` policy and the
`format_result:` renderer run in the worker task for their call. A policy or
renderer that relies on process-local state (`Process.put/2`, a process
dictionary, a caller-owned `Agent` lookup that assumes the loop process) is the
caller's responsibility. `on_event:` stays in the loop's process and keeps its
order.

**Pause representation.** `Pending.results` becomes a list of slots in call
order, `[LlmCall.ToolResult.t() | nil]`, one per assistant tool call. A completed
call has its result at its index; a call that paused or has not run has `nil`.
`remaining` is the calls with `nil` slots, in call order; its head is the paused
call a resume answers. `tool_calls` is the run's completed tool-result total:
previous turns plus the non-`nil` slots of this pause.

When a parallel batch contains a pause, every started call finishes before the
loop returns `{:pending, %Pending{}}`; results for the non-paused calls are kept
in their slots. The first pause in call order is the `Pending` payload; any later
paused calls are in `remaining` and are re-dispatched with fresh approval/input
requests on resume. The final user turn is sent only when no slot is `nil`; it
filters the nils and keeps call order. A pause can re-pause; counters and
`last_usage` carry across.

Serial execution is `max_concurrency: 1` with the same slot representation: a
serial pause has its result slot and the rest `nil`. The behavior of the 0.1
approval/input flow is otherwise unchanged.

**Tradeoff.** With `max_concurrency > 1`, a non-gated call can run before a
gated call's approval; the library does not pre-check a policy. A caller that
needs strict pre-approval ordering uses `1`. A `:tool` dispatcher error (invalid
`tool_opts`, a renderer raise) aborts the run; results already produced are not
invented into a success.

`Pending` also gains `run_id`. `:run_started`'s `data` adds
`max_concurrency:` and `cancel?:`; `run_id` is the `Event` field, not duplicated
in that payload. The `:tool_call_started` / `:tool_result` events keep their
order, with a result for every completed call whether the batch is serial or
parallel.

### 23.3 Telemetry and `run_id`

`run/3` accepts `run_id:` (a non-empty string, or nil to generate one). The id
is stored on `Result`, `Pending` and `Event`, and is the correlation key for
external durable/observability layers. `resume/3` uses the `Pending`'s `run_id`;
a nil id on a hand-built `Pending` is normalized to a generated one, and any
other malformed id is a `:configuration` error. Every event carries the same id.
The id is the `Event` field, not a key of `:run_started.data`; `max_concurrency:`
and `cancel?:` are data keys.

The library emits `:telemetry` spans; it declares `:telemetry ~> 1.0` directly
(it is already transitive through the transport). The events are:

- `[:agent_call, :run, :start | :stop | :exception]` — `%{run_id, max_steps, stream?, max_concurrency, cancel?}`.
- `[:agent_call, :turn, ...]` — `%{run_id, step, stream?}`.
- `[:agent_call, :tool, ...]` — `%{run_id, step, tool, module}`; the stop metadata carries the outcome: `:ok` only for a non-error `%LlmCall.ToolResult{}`, `:error` for an `is_error` result or a dispatcher failure, and `:pending` for an input/approval pause.
- `[:agent_call, :stream, ...]` — `%{run_id, step}` around a streamed turn's read and fold. A stream that fails while it is being read emits the span's `:exception` and no `:stop`; the run returns the unchanged `{:error, %Error{kind: :llm}}`.

Metadata never contains messages, tool arguments, results, client headers or
credentials. `:telemetry` handler failures never change the run. `on_event`
remains the per-run UI surface; telemetry is the process-global ops surface. The
`run` span brackets the whole run; turn and tool spans bracket their units. A
resumed `run/3`/`resume/3` invocation emits its own `:run` span with the same
`run_id`. A tool-target input answer is not a new `run_one`, so its only tool
span is the `:pending` span from the pause. A parallel tool task that exits
abnormally can leave a started span without a stop, because the process that
would emit it is gone; the run records the exit as a `:tool` error. No handlers
are required.

### 23.4 Version and release

The first release is **0.1.0**, including the input surface (§22) and these P0
controls. The internal plan name is a phase name, not a package version;
`mix.exs` stays `0.1.0`. No later package version is published or implied. The
CHANGELOG 0.1.0 entry, README, design and roadmap describe all of it. Publishing
is a separate, explicit step; the release task stops at `mix hex.build` /
`mix hex.publish --dry-run`.

### 23.5 Deferred (not part of P0)

- **Durable run.** The loop has no durable execution. §25 adds the
  checkpoint/journal seam: an external layer persists/reloads a run; the
  library stores nothing. Checkpoints are only at completed tool turns.
- **Agent-as-tool.** Delivered in §24.
- **Thread, memory and context.** §26 defines the caller-owned
  `AgentCall.Thread` behaviour and guide; the library stores nothing. Memory/RAG
  and the thread store remain external.
- **Checkpoint/resume + streaming.** Delivered in §25. No mid-stream resume; a
  stream failure discards that turn's partial content and the turn is retried;
  completed tools are not re-run. The safe checkpoint is after a completed tool
  turn.

### 23.6 Testing

- Cancellation at `:turn` and `:tools`, before/after a turn, with `response`
  nil/non-nil; no request or tool ran; policy errors at both boundaries;
  `:run_started.cancel?` true on a resumed run with a re-supplied policy; a
  `:tools` cancel wins over an equally due budget stop; a resumed run checks
  `cancel_when:` at new turn entries and before a new batch, never before the
  re-dispatched paused batch.
- Parallel: ordered results, sparse slots, a first pause at index 0 and at
  index > 0, a pause with later completed calls, multiple pauses, re-pause, one
  user turn in call order, counters/`last_usage`, input/approval/tool-prompt
  combinations, `max_concurrency: 1` preserves serial behavior, and a dispatcher
  error aborts. A wave-sized batch stops later waves; a resume without
  `max_concurrency:` runs serially.
- `run_id` on `Result`/`Pending`/`Event`; supplied vs generated; an empty
  supplied id is a `:configuration` error; resume uses the pending id or
  normalizes a nil one; `term_to_binary`.
- Telemetry: attach handlers for run/turn/tool/stream, assert start/stop and
  outcomes (including an `is_error` result as `:error`), a failed stream's
  `:exception` with no stop, resumed input/turn steps, durations, no
  messages/args, and that a handler failure cannot change the outcome. Detach
  after each test.
- The full suite and `mix ci`; docs and `mix hex.build` at 0.1.0.

### 23.7 Decisions

1. **Safe-boundary cancellation.** No mid-tool kill, no partial tool results; a
   cancel after tools start is observed at the next turn.
2. **Sparse slots.** `Pending.results` is positional; the final user turn filters
   nils. No completion-order ambiguity, including Gemini calls without ids.
3. **Parallel is opt-in.** `max_concurrency: 1` is the default and preserves the
   serial contract; >1 accepts the pre-approval side-effect tradeoff.
4. **Telemetry is additive.** `:telemetry` plus `run_id`; `on_event` remains the
   UI observer. No handler dependency.
5. **The first release is 0.1.0.** P0 is not a package version; no later
   package version is published or implied.

### 23.8 Builder's latitude

The internal modules for the cancel call site, the parallel batch, and the
telemetry spans; the exact span names beyond the four prefixes; the generated
`run_id` format; and the order of the per-call telemetry metadata fields.

## 24. Agent as a tool (0.1.0)

Status: first-release extension, approved 2026-11-25. Part of `0.1.0`; no version
bump and no publish. This section extends §9, §15–§21.

### 24.1 Intent

An agent often needs a sub-agent: the outer model calls one tool, that tool runs
a complete inner `AgentCall.run/3`, and the inner final answer comes back as the
outer tool result. The helper is a function, not a process and not a second
runtime. The inner run executes synchronously in the outer tool's task; the outer
loop still returns its four outcomes.

### 24.2 API

```elixir
@type input :: String.t() | [LlmCall.Message.t()]

@type pending_decision ::
        {:approval, :granted | :denied}
        | {:input, {:answer, term()} | {:cancel, term()}}
        | {:error, term()}

@spec AgentCall.AgentTool.run(
        LlmCall.Client.t(),
        LlmCall.Request.t(),
        input(),
        keyword()
      ) :: {:ok, String.t()} | {:error, term()}
```

`input` is a string, which becomes one user `LlmCall.Message`, or a list of
messages appended to `request.messages`. The helper copies the request; it does
not mutate the caller's struct. The inner request keeps its system prompt, model
and tools; the caller decides whether it starts from an empty history.

`opts` are the inner `AgentCall.run/3` options (`max_steps:`, `stream:`,
`tool_opts:`, `max_result_bytes:`, `format_result:`, `context:`, `prompt:`,
`on_event:`, `cancel_when:`, `max_concurrency:`, `codec:`, `headers:`,
`run_id:`), plus two helper-only keys:

- `on_pending:` — a 1-arity control callback or `nil`; see §24.3.
- `on_result:` — a 1-arity observation callback for the inner terminal
  `AgentCall.Result`, or `nil`; see §24.4.

The helper-only keys are not forwarded to `AgentCall.run/3`. `run_id:` is
forwarded only to the first run; `resume/3` uses the pending id. `on_event:`,
`context:`, `prompt:`, `cancel_when:`, `tool_opts:`, `format_result:`,
`max_result_bytes:`, the step/stream/parallel options and `codec:`/`headers:`
are re-supplied on every inner resume.

A tool module is ordinary `ToolCall` code:

```elixir
defmodule MyApp.Tools.Research do
  use ToolCall

  @doc """
  Research a topic.

  ## Parameters
    * `topic` - the topic
  """
  @spec research(topic :: String.t()) :: {:ok, String.t()} | {:error, term()}
  def research(topic) do
    AgentCall.AgentTool.run(
      MyApp.client(),
      %LlmCall.Request{
        model: "fast",
        system: "You are a researcher.",
        tools: [MyApp.ResearchTools]
      },
      "Research: #{topic}",
      max_steps: 4,
      tool_opts: [approval: :granted],
      on_pending: fn
        %AgentCall.Pending{kind: :approval} -> {:approval, :granted}
        _ -> {:error, :needs_human}
      end,
      on_event: &MyApp.SubAgentUI.event/1,
      on_result: &MyApp.Metrics.record/1
    )
  end
end
```

The outer request lists `MyApp.Tools.Research`; the outer model calls it; the
inner loop runs; the outer tool result is the inner final text.

### 24.3 Nested pauses

The outer loop understands only its own `Pending`; the helper does not propagate
an inner approval/input pause to the outer loop or outer human. Instead:

- If `on_pending:` is `nil`, an inner `{:pending, %Pending{}}` returns
  `{:error, {:pending, pending.kind}}`. The outer model sees an `is_error` tool
  result; the inner run is not resumed.
- If `on_pending:` is set, the helper calls it with the inner `%Pending{}` and
  expects `{:approval, :granted | :denied}`, `{:input, {:answer, term} |
  {:cancel, term}}`, or `{:error, reason}`. It validates the decision against
  `pending.kind`, calls `AgentCall.resume/3` with that decision and the inner
  options, and handles the next outcome. A callback may run for several pauses;
  the inner `max_steps:`/budget remains the termination bound.
- A callback raise/throw/exit or malformed return is `{:error, {:on_pending,
  reason}}`; a kind mismatch is `{:error, {:on_pending, :kind_mismatch}}`.
  `{:error, reason}` is returned as `{:error, reason}`.
- A malformed `on_pending:` or `on_result:` **option** — neither a 1-arity
  function nor `nil` — is an inner `:configuration` error before the inner run.
- The callback is a **control** callback, unlike `on_event`; it runs
  synchronously in the outer tool's process/task and may block (for example on a
  parent UI process). The caller owns that blocking and the outer `tool_opts:`
  timeout still bounds the tool call.

The inner `Pending` is data; the callback can inspect its request, transcript,
approval/input payload and counters, and may store it. It is not the outer
`Pending`.

### 24.4 Result and observation

| Inner outcome | Helper |
| --- | --- |
| `{:ok, result}` | `{:ok, LlmCall.Response.text(result.response)}`; empty text is `""` and the outer renderer substitutes `"(no output)"` |
| `{:exhausted, result}` | `{:error, {:exhausted, result.halt_reason, text}}`; text is `""` when there is no response |
| `{:pending, pending}` with no resolver, or a resolver `{:error, reason}` | `{:error, {:pending, pending.kind}}` / `{:error, reason}` |
| `{:error, %AgentCall.Error{}}` | `{:error, {:inner, error.kind, error.message}}` |
| callback failure | `{:error, {:on_pending, reason}}` |

`on_result:` is called for an inner `{:ok, _}` or `{:exhausted, _}` with the
inner `%AgentCall.Result{}`. It is observation-only: a raise/throw/exit is caught
and ignored, and it never changes the helper's return. It is not called for an
unresolved pending or an error, which have no `Result`; those are visible through
the helper's return and the inner `on_event:`/telemetry.

`on_event:` is forwarded to the inner run/resume, so the caller can display the
sub-agent (including its `:approval_required`/`:input_required`). It is not
merged into the outer observer; the outer model sees only the final text. The
inner telemetry spans carry the inner `run_id`; the outer `:tool` span carries
the outer run id. A caller that wants correlation passes a derived `run_id:` to
the helper.

### 24.5 Boundaries

- No process, pool, store, application config or global state. The inner run is
  synchronous in the outer tool task; the outer `tool_opts[:timeout]` bounds it,
  and inner `tool_opts[:timeout]` bounds its tools.
- No nested `Pending` propagation to the outer loop, outer `resume/3` or outer
  model. `on_pending:` is the explicit seam; without it an inner pause is an
  error.
- No depth or cycle guard. Composition (a sub-agent tool calling another) is the
  caller's; `max_steps:`, outer tool timeouts and the inner options bound it.
- No model routing or provider selection; the inner client and request are the
  caller's.
- The outer tool schema is the caller's `ToolCall` module's `@doc`/`@spec`; the
  helper derives no schema and adds no tool definition.
- The outer tool result is the inner final text, not the inner transcript,
  usage, tool results or `AgentCall.Result`; those are observation/telemetry
  surfaces.
- No mid-stream resume; inner `stream: true` follows the inner streaming rules.

### 24.6 Testing

- Inner text-only run, one inner tool run, inner `:exhausted`, inner `:error`,
  and an unresolved inner approval/input: the helper returns the mapped value
  and the inner tool was not run where it should not be.
- `on_pending:` grant, deny, input answer, input cancel, several pauses, a
  raise/throw/exit, a malformed return and a kind mismatch; the outer model sees
  an `is_error` tool result for an unresolved/denied/failed inner run where
  applicable.
- `on_result:` receives the inner `Result` for `:ok`/`:exhausted` and a raising
  callback cannot change the helper result. `on_event:` receives the inner
  events and the inner `run_id`.
- Input as a string and as a message list; the caller's request is not mutated;
  a bad input is `{:error, {:input, _}}`.
- Outer integration: a normal `ToolCall` module calls the helper; the outer
  `AgentCall.run/3` dispatches it; the outer transcript has the tool result; the
  outer telemetry tool span and the inner spans share no run id unless supplied.
- No process, store or schema dependency added; the full suite and `mix ci` are
  green at `0.1.0`; no publish.

### 24.7 Decisions

1. **A thin function, not a macro or process.** The caller writes an ordinary
   `ToolCall` module; the helper runs the inner agent.
2. **`on_pending:` is the nested-pause seam.** Default is an error; the callback
   is explicit control, not observation. No outer `Pending` propagation.
3. **`on_event:`/`on_result:` observe; they never change the result.**
4. **The tool result is the inner final text.** Full inner data is available
   through callbacks, events and telemetry, not the outer model.
5. **The first release stays 0.1.0.** The helper is part of it; no version bump,
   no publish.

### 24.8 Builder's latitude

The exact error-reason wording; the generated inner `run_id` correlation format;
whether `on_result:` is called before or after the helper maps the text (it is
called once per terminal result); and internal helper modules.

## 25. Checkpoint and journal seam (0.1.0)

Status: first-release extension, approved 2026-11-25. Part of `0.1.0`; no version
bump and no publish. This section extends §9, §15–§21.

### 25.1 Intent

A caller must be able to persist a run at a safe boundary and reload it after
the BEAM, a job or a product process is gone. The library defines the record and
the resume entry point; it does not own a store, a process, expiry or retention.
The journal is the caller's append-only log of the records the library emits.

### 25.2 Terms

- **Pause checkpoint** — an existing `%AgentCall.Pending{}`: an approval/input
  pause plus its decision. Already serializable; now versioned by the envelope.
- **Turn checkpoint** — a new `%AgentCall.Checkpoint{}` after a completed tool
  turn, before the next model request.
- **Envelope** — a versioned binary wrapper around a `Pending` or `Checkpoint`,
  written and read by `AgentCall.Checkpoint.dump/1` / `load/1`.
- **Journal** — the caller's append-only log of checkpoint/pending/result
  records. Not a library module in this release.

### 25.3 Public data

`AgentCall.Pending` is unchanged. A pause is still resumed with `resume/3` and
an approval/input decision.

The new public struct is the state after a completed **tool** turn:

```elixir
defmodule AgentCall.Checkpoint do
  defstruct [
    :version,
    :run_id,
    :request,
    :transcript,
    :steps,
    :tool_calls,
    :usage,
    :last_usage
  ]

  @type t :: %__MODULE__{
          version: pos_integer(),
          run_id: String.t(),
          request: LlmCall.Request.t(),
          transcript: [LlmCall.Message.t()],
          steps: non_neg_integer(),
          tool_calls: non_neg_integer(),
          usage: LlmCall.Usage.t() | nil,
          last_usage: LlmCall.Usage.t() | nil
        }
end
```

- `version` is `1`; the envelope carries the same version.
- `request` is the request being run (model, system, tools and its original
  messages); `transcript` is the model-visible context after the turn's tool
  results.
- `steps` is the number of completed model turns; the next request is step
  `steps + 1`. `tool_calls` is the completed total; `usage` is the accumulated
  total; `last_usage` is the completed turn's own usage for the context policy.
- There is no `approval`/`input`, no `remaining`/`results`, no response and no
  outcome. A pause is a `Pending`; a final answer is a `Result`.

The envelope:

```elixir
@spec dump(AgentCall.Pending.t() | AgentCall.Checkpoint.t()) :: binary()
@spec dump(AgentCall.Pending.t() | AgentCall.Checkpoint.t(), keyword()) :: binary()
@spec load(binary()) ::
        {:ok, AgentCall.Pending.t() | AgentCall.Checkpoint.t()}
        | {:error, :invalid | :unsupported_version}
```

`dump/1` wraps `%{version: 1, type: :pending | :checkpoint, payload: term}` with
`:erlang.term_to_binary/2`; `dump/2` takes `compress:` to choose the encoding.
`load/1` uses
`:erlang.binary_to_term(binary, [:safe])`, checks the envelope version and type,
and returns the struct. A `Pending`/`Checkpoint` whose payload is not
serializable/portable (a fun, pid, port or reference) fails `load/1`, as does a
nested struct with missing or extra fields, a `Usage` field that is not `nil`
or a non-negative integer, a `ToolResult` whose content is not text or whose
`is_error` is not a boolean, a `Message` with invalid role/content, an invalid
`Content` field (`Text.text`, media source, `Thinking.text/signature`, `Raw`
data), invalid request fields (`model/provider_options/system/tool_choice/
output/modalities/reasoning/params/stream`), invalid `ToolSpec` fields,
invalid tool-target `Input.source/spec(call-name)/inserted_at`, an
`Approval.Request` with invalid `id/module/tool/args/inserted_at`, invalid
input source/spec/prompt combinations, or a `ToolCall` with invalid nullable
fields; `ToolResult`/`ToolCall` identifiers may be `nil` because the protocol
adapter chooses the identifier; the input/prompt
payload contract already requires serializable data. There is no JSON or map
codec: the record contains `LlmCall`/`ToolCall` structs, and a full external codec
would be a larger surface than the seam needs. A persisted record is guaranteed
to load and resume within the release that wrote it; cross-version resumption is
not promised while `0.x`.

Compression is chosen per record, because the two kinds of payload have opposite
economics. A text transcript deflates by two orders of magnitude for well under
a millisecond, so it is compressed. A transcript carrying a media source
(`Content.Image`, `Content.File`, `Content.Video`) is base64 over bytes the
provider already compressed: deflating a 2.6 MB record costs ~66 ms and saves
~23%, and a run that checkpoints every turn pays that on every turn. Such a
record is written uncompressed, in ~0.2 ms. `dump/2`'s `compress:` overrides the
choice: `:auto` (the default), `false`, `true`, or a zlib level `1..9`. The
choice is not recorded in the envelope, so `load/1` reads either encoding.

### 25.4 Checkpoint event

After every completed **tool** turn, the loop emits one `:checkpoint` event
before the next turn entry:

```elixir
%AgentCall.Event{
  type: :checkpoint,
  step: 2,
  run_id: "...",
  data: %{checkpoint: %AgentCall.Checkpoint{}}
}
```

Event order for a tool turn:

```text
:step_started N
:step_finished N
:tool_call_started / :tool_result ...   (all calls in the turn)
:checkpoint N                          (new)
:context_updated? / :step_started N+1  (next turn)
```

- `:checkpoint` comes after all `:tool_result` events for the turn and before
  the next `:context_updated` / `:step_started`. It is not emitted at a pause
  (the `:approval_required`/`:input_required` `Pending` is the state), not after
  a no-tool final answer (the `:finished`/`Result` is terminal), and not after a
  partial stream (no turn completed).
- The event's `step` and the checkpoint's `steps` are the completed turn.
- It is emitted even when the next turn will stop at the budget, context,
  cancel or input policy: the checkpoint is the last safe completed turn.
- `:checkpoint` is a new event type; it is additive, so a consumer needs a
  catch-all clause. The event is observe-only and carries the checkpoint data;
  the library stores no event history.
- The event data includes the request/transcript, but not the client, headers or
  credentials. The existing `:approval_required`/`:input_required` events already
  carry the `Pending` request/transcript.

### 25.5 Resume from a checkpoint

```elixir
@spec AgentCall.resume_checkpoint(
        LlmCall.Client.t(),
        AgentCall.Checkpoint.t(),
        keyword()
      ) :: AgentCall.outcome()
```

`resume_checkpoint/3` accepts the same options as `run/3` except `run_id:` and
without any approval/input decision. It validates the checkpoint shape, the
request and the tool map before emitting any event; a malformed checkpoint is a
`:configuration` error. The run continues at `checkpoint.steps + 1`.

- `run_id` is the checkpoint's id; a supplied `run_id:` is rejected. The resumed
  run emits `:run_started(resumed?: true)` with the same shape as `run/3`, and
  its `Result`/`Event`s carry the checkpoint's `run_id`.
- `context:`, `prompt:`, `cancel_when:`, `max_steps:`, `stream:`, `tool_opts:`,
  `max_result_bytes:`, `format_result:`, `max_concurrency:`, `codec:`,
  `headers:` and `on_event:` are re-supplied; none is stored in the checkpoint.
  The context policy runs before the next request; the prompt policy can pause;
  the cancel policy is checked at the next turn entry.
- The next request uses `checkpoint.transcript`; the completed tool results are
  not re-run. `steps`, `tool_calls`, `usage` and `last_usage` carry forward.
- The budget is checked against `checkpoint.steps`. If it already stopped, the
  run returns `{:exhausted, result}` with `response: nil`, `stop_reason: nil`,
  `halt_reason: :budget`, the checkpoint transcript/counters/usage and the
  checkpoint's `run_id`; no request is sent.
- A `Pending` produced after a resume is the normal pause: the caller takes the
  decision with `resume/3`, and the next completed tool turn emits a new
  `:checkpoint`.
- A streamed completed turn emits a checkpoint; a stream failure still discards
  that turn's partial content, emits no checkpoint and returns the existing
  `:llm` error. The last checkpoint is the retry point; completed tools are not
  re-run. There is no mid-stream checkpoint.
- A checkpoint after a completed tool turn does not imply a final answer. The
  final no-tool turn returns `Result`; `:finished(:ok)` is the terminal. The
  checkpoint before it remains a valid resume point, but the result is the
  caller's terminal record.

### 25.6 Journal

The journal is the caller's append-only log:

```text
run_id, seq, type, payload
```

The library supplies records, not storage. A typical `on_event:` observer appends:

- `:checkpoint` — `Checkpoint.dump(checkpoint)`;
- `:approval_required` / `:input_required` — `Checkpoint.dump(pending)`;
- the terminal `:finished` — the caller appends the `Result` it receives from
  `run/3`/`resume/3`/`resume_checkpoint/3` (the event data is not a full result).

The latest record per `run_id` is the resume point: `load/1` then
`resume_checkpoint/3` for a checkpoint, `resume/3` for a pending. Older records
are the audit/replay history.

The event is observe-only. A store write happens in the caller's `on_event:`
callback, synchronously in the loop's process, so a slow store slows the loop.
If the write fails, the callback catches it, sets the caller's flag, and the
existing `cancel_when:` policy returns `{:cancel, :checkpoint_store_failed}` at
the next safe boundary. The run returns `{:exhausted, result}`, the last
successfully persisted checkpoint is still the resume point, and no new
control callback or error kind is added. The alternative — a controlling
`on_checkpoint:` that can stop the run with an ack — is deliberately not part of
this release.

No `AgentCall.Journal` behaviour is added in 0.1. The journal is an application
adapter/guide (Ecto, Redis, a file, a queue); the fake-store integration test
proves the pattern.

### 25.7 Boundaries

- No store, ETS, Ecto, GenServer, supervision tree, application config or
  schema. The library never writes, expires or retains a checkpoint.
- No automatic checkpoint; the caller decides whether to persist the emitted
  record.
- No mid-stream or partial-turn checkpoint; no completed tool re-run; the safe
  boundary is after a completed tool turn.
- No checkpoint at a pause or after a no-tool final answer; `Pending` and
  `Result` are those records.
- No `on_checkpoint` control callback; the `:checkpoint` event plus the caller's
  `cancel_when` is the failure seam.
- No JSON/map codec; the envelope is the versioned binary boundary. Cross-version
  resume is not promised while `0.x`.
- No event history, journal server or retention policy; the event stream remains
  observe-only.
- The first release stays `0.1.0`; no publish.

### 25.8 Testing

- `Checkpoint.dump/1` / `load/1` round-trip for a `Pending` and a `Checkpoint`;
  envelope version and type rejection; an invalid payload; a non-serializable
  input/prompt value rejected by the `:safe` load; the `Pending` fields unchanged.
- `:checkpoint` after a completed tool turn: exact event order, `step`/`run_id`,
  the four checkpoint fields; not at a pause, not after a no-tool final, not
  after a stream failure; a checkpoint before a budget/context/cancel stop; a
  resumed run emits its own checkpoints.
- `resume_checkpoint/3`: from a step-2 checkpoint, no completed tool re-runs;
  the next request carries the transcript; `:run_started(resumed?: true)`; a
  pending after the resume; the final result; counters/usage/last_usage; a
  budget stop with `response: nil`; `context:`/`prompt:`/`cancel_when:`/`stream:`
  re-supplied; a supplied `run_id:` rejected; a malformed checkpoint is a
  `:configuration` error before any event.
- A stream failure after a checkpoint: no partial checkpoint, the same `:llm`
  error, the last checkpoint retries the turn, completed tools do not re-run.
- The journal fake store: `on_event` appends checkpoint/pending records; a store
  failure sets the flag, `cancel_when:` stops at the next boundary, the last
  checkpoint resumes; the terminal result is appended.
- The full suite and `mix ci`; docs and `mix hex.build` at `0.1.0`; no publish.

### 25.9 Decisions

1. **Checkpoint at completed tool turns only.** No mid-stream, no partial turn,
   no tool re-run; the stream failure retries the turn from the last checkpoint.
2. **The `:checkpoint` event is the seam.** No `on_checkpoint` control callback;
   a store failure is the caller's `cancel_when` policy, so the observe-only
   contract and the four outcomes do not change.
3. **The envelope is versioned binary.** `Checkpoint.dump/1`/`load/1`; no
   JSON/map codec; `:safe` load; no cross-version promise while `0.x`.
4. **`resume_checkpoint/3` is separate.** `resume/3` keeps the pause/decision
   contract; the two resume meanings do not share a function.
5. **The journal is external.** The library emits records; no `AgentCall.Journal`
   behaviour or storage in 0.1; a guide and fake-store test prove the adapter.
6. **The `Pending` envelope is included.** Approval/input waits become durable
   with the same versioned envelope; `Pending` fields do not change.
7. **The first release stays 0.1.0.** No version bump, no publish.

### 25.10 Builder's latitude

The exact `Checkpoint`/envelope module layout; the `:checkpoint` event data key;
whether `dump/1` compresses; the internal `Loop`/`Options` entry; the journal
guide/example storage; and the exact error messages for a malformed checkpoint.

## 26. Thread and context adapter (0.1.0)

Status: first-release extension, approved 2026-11-27 and implemented in
`0.1.0`; no version bump and no publish. This section extends §9, §15–§21 and
§25.

### 26.1 Intent

A caller that keeps a conversation needs to load its thread, choose between a
fresh run, a paused run and a completed-turn checkpoint, and persist the records
the loop emits. The library defines that contract; the caller owns the store and
the messages. The library never loads or appends a thread and owns no process,
table or schema.

### 26.2 Public contract

```elixir
defmodule AgentCall.Thread do
  @type thread_record ::
          AgentCall.Checkpoint.t()
          | AgentCall.Pending.t()
          | AgentCall.Result.t()
          | AgentCall.Event.t()

  @type snapshot :: %{
          messages: [LlmCall.Message.t()],
          checkpoint: AgentCall.Checkpoint.t() | nil,
          pending: AgentCall.Pending.t() | nil,
          result: AgentCall.Result.t() | nil
        }

  @callback load(thread_id :: term()) :: {:ok, snapshot()} | {:error, term()}
  @callback append(thread_id :: term(), thread_record()) :: :ok | {:error, term()}
end
```

- `load/1` returns the thread's current model-visible messages and the latest
  `checkpoint`/`pending`/`result`, if any. The caller derives them from its own
  store; no library code reads the store.
- `append/2` receives the records the caller chooses to persist: the
  `:checkpoint`/`:approval_required`/`:input_required` events, the terminal
  `Result`, or the `Checkpoint`/`Pending` directly. The caller's store decides
  how to index, retain and query them.
- The behaviour is a contract, not an implementation: there is no
  `AgentCall.Thread` store, GenServer, table or default adapter. The library
  never calls `load/1` or `append/2`; the caller does, in its `on_event:` and
  between runs.
- `thread_id` is the caller's opaque key (`term()`); no library-generated id is
  added. The run's `run_id` travels on the `Checkpoint`/`Pending`/`Result`.

### 26.3 Caller flow

The caller chooses the resume path from the snapshot:

```elixir
{:ok, snapshot} = MyApp.ThreadStore.load(thread_id)
on_event = fn event -> MyApp.ThreadStore.append(thread_id, event) end

outcome =
  case snapshot do
    %{pending: %AgentCall.Pending{} = pending} ->
      AgentCall.resume(
        client,
        pending,
        # Exactly one decision, matching `Pending.kind`: approval: or input:.
        approval: :granted,
        on_event: on_event,
        context: context,
        ...
      )

    %{checkpoint: %AgentCall.Checkpoint{} = checkpoint} ->
      AgentCall.resume_checkpoint(client, checkpoint, on_event: on_event, context: context, ...)

    %{messages: messages} ->
      AgentCall.run(
        client,
        %LlmCall.Request{messages: messages, ...},
        on_event: on_event,
        context: context,
        ...
      )
  end
```

- `pending` wins over `checkpoint`: the checkpoint is the last completed tool
  turn, while the pending is the live pause that must be answered. A thread with
  both resumes the pending; the next completed tool turn emits a new checkpoint.
- The pending path carries exactly one decision matching `Pending.kind`:
  `approval:` (`:granted` or `:denied`) for an approval pause, `input:`
  (`{:answer, term}` or `{:cancel, term}`) for an input pause. `resume/3`
  refuses none, both or the wrong kind; the checkpoint and messages paths take
  no decision.
- No pending and a checkpoint means `resume_checkpoint/3`; the completed tools
  are not re-run.
- Only messages means a fresh `run/3` with the thread's model-visible messages;
  the caller supplies the system prompt, tools and run options.
- The caller appends the terminal `Result` it receives from the outcome; the
  `:finished` event is not a full `Result`. The `append/2` record type includes
  both, so a store may keep the event stream and the result separately.
- `on_event:` remains observe-only. The caller's store append runs synchronously;
  a failure must be caught by the caller (including an `:exit` from a dead
  store), the caller sets its own flag, and the existing `cancel_when:` stops at
  the next safe boundary. The last persisted checkpoint remains the resume
  point. The library adds no thread-specific callback, error kind or outcome.
- `context:` is still the caller's policy: a thread-aware policy can trim,
  summarize or pass through `messages`; the library never trims or loads a
  thread implicitly.

### 26.4 Example adapter and guide

`examples/agent_call_example.ex` contains a small caller-owned adapter (an
`Agent`) implementing `AgentCall.Thread`, with `thread/1` that starts and stops
its own store and resumes the example's approval-gated pause once, and
`resume_thread/2` that takes the caller's store and forwards the decision to
`resume/3`, plus the `run`/`resume`/`resume_checkpoint` selection above.
`test/support/` contains a test-only adapter and an integration test:

- fresh run from messages;
- pending → `resume/3`;
- checkpoint → `resume_checkpoint/3` with no completed-tool re-run;
- the `on_event` appender; a store failure and the `cancel_when` stop;
- a thread-aware `context:` policy;
- the terminal result appended after the outcome;
- no library process, table or schema.

The README's “Thread and context” section documents the behaviour, the
selection rule and the example. The design and roadmap carry the contract; the
CHANGELOG records it in the 0.1.0 entry.

### 26.5 Boundaries

- No library thread/session store, ETS, Ecto, GenServer, supervision tree or
  application config. No `AgentCall.Thread` implementation is shipped.
- No automatic load or append; the caller decides what to persist and when.
- No retention, expiry, multi-tenancy, sharing or migration.
- No memory/RAG, prompt templates, summarization or token counting; the
  caller's adapter/policy owns them.
- No second context API: `context:` remains the only context seam.
- No new outcome, error kind or event type; the thread contract reuses
  `Checkpoint`, `Pending`, `Result` and `Event`.
- The library never calls the `AgentCall.Thread` `load/1` or `append/2`
  callbacks; the behaviour is a compile-time contract for the caller.
- The first release stays `0.1.0`; no publish.

### 26.6 Testing

- The test adapter implements both callbacks; the compiler enforces the
  `@behaviour`; `load/1` returns an empty or populated snapshot; `append/2`
  accepts a checkpoint, pending, result and event.
- The integration test runs the three paths (messages, pending, checkpoint),
  asserts the on_event appends, the terminal result, the thread-aware context,
  the store failure + `cancel_when` stop, the last-checkpoint resume, and no
  completed-tool re-run.
- The example adapter compiles and is never invoked; no library module starts a
  process or table.
- The full suite and `mix ci`; docs and `mix hex.build` at `0.1.0`; no publish.

### 26.7 Decisions

1. **The thread is caller-owned.** The library defines only a behaviour and
   types; no store/process.
2. **The snapshot is `messages/checkpoint/pending/result`.** The caller derives
   it; the library never reads it.
3. **`append/2` accepts checkpoint/pending/result/event.** The caller's store
   decides indexing and retention; the event stream and the result are separate
   records.
4. **The existing `context:` is the context adapter.** No new context callback,
   thread trimming or implicit history.
5. **Pending wins over checkpoint in the guide.** The pending is the live pause;
   the checkpoint is the last completed turn.
6. **The first release stays 0.1.0.** No version bump, no publish.

### 26.8 Builder's latitude

The example adapter's storage (Agent, file, map); the exact snapshot map extras
(metadata, timestamps) in the example; the README guide wording; and the test
adapter's shape, while the two callbacks, the snapshot fields and the record
union are pinned.

## 27. Performance baseline

Overhead that regresses by shape — a redundant walk, a full render that is then
capped, a compression choice that stops paying — does not show up in a
correctness test. It is measured in two places:

- `mix bench` (`bench/run.exs`) prints medians and minimums for the four
  scenarios whose cost is easy to move without noticing: dumping a checkpoint
  once per completed turn with and without a media source; rendering a tool
  result that will be capped; one request and one resume over a transcript of
  100 to 3,000 messages; and a streamed turn of 500 to 8,000 deltas. A fixture
  HTTP server stands in for the provider, so the numbers are the library's own
  overhead and not network latency.
- `test/agent_call/dispatch_map_property_test.exs` states what `Dispatch.map/1`
  must do with any tool list: return a dispatch map or a `:configuration` error,
  never raise; keep every declared tool exactly once under the name its spec
  carries; and keep `input_tools/1` and `module/2` in agreement with it. The
  generator draws from malformed shapes as well as valid ones — improper lists,
  entries that are not modules, specs without a name, a describe that raises —
  and includes a module declaring two tools, without which a dispatcher that
  kept only the first would pass.
- `test/agent_call/renderable_property_test.exs` states the render chain's rules
  as properties over generated cases: any renderer output and any cap yields
  valid UTF-8 or a `:tool` error, a truncated result is a prefix of what the
  renderer returned, text that fits is unchanged, and the `(no output)`
  placeholder is the one documented exemption from the size bound. The generator
  is seeded and prints its seed on failure, so `PROP_SEED=<seed>` reproduces a
  failure exactly; `PROP_CASES` raises the case count for a longer run.
- `test/agent_call/performance_test.exs` is what CI enforces. Each test compares
  two measurements taken on the same machine in the same run, so the assertion
  is a ratio and never a wall-clock budget: a CI runner is not the machine the
  baseline was taken on, and a fixed budget would either be uselessly loose or
  flaky.

The baseline is not part of `mix ci` because absolute times track the machine.
It is deliberately a floor, not a target: a failure means a cost changed shape,
and `mix bench` is what shows which row moved.
