# Changelog

All notable changes to this project are documented here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

## 0.1.0 - 2026-11-30

### Added

- `AgentCall.run/3`: one call runs the tool loop over `llm_call`.
  `request.tools` is the only tool list, and each call it produces goes through
  `ToolCall.run/4`.
- Four outcomes: `{:ok, Result.t()}`, `{:exhausted, Result.t()}`,
  `{:pending, Pending.t()}` and `{:error, Error.t()}`. `{:ok, _}` means the model
  asked for no more tools; a `:max_tokens` finish stays visible in
  `Result.stop_reason` instead of being flattened into success.
- `AgentCall.resume/3`: continues a paused turn. It takes exactly one of
  `approval:` (`:granted | :denied`) or `input:` (`{:answer, term}` or
  `{:cancel, term}`), matching `Pending.kind`.
- `AgentCall.Pending`: serializable pause data carrying the request, the pause
  payload, the transcript, positional `results` slots, the remaining calls and
  the counters. `kind` is `:approval | :input`; `approval` and `input` are
  mutually exclusive. `results` has one `%LlmCall.ToolResult{}` or `nil` per
  assistant tool call, in call order, and `remaining` is the calls with a `nil`
  slot. It survives `:erlang.term_to_binary/1` and resumes with its counters and
  last usage.
- `AgentCall.Checkpoint` and the versioned envelope: the state after a completed
  tool turn (`version`, `run_id`, `request`, `transcript`, `steps`, `tool_calls`,
  `usage`, `last_usage`). `Checkpoint.dump/1` wraps a `Checkpoint` or a `Pending`
  in a versioned binary; `load/1` uses a `:safe` decode and checks the
  envelope version, type and portable payload. Another version is
  `{:error, :unsupported_version}` and anything else malformed is
  `{:error, :invalid}`. Cross-version resume is not promised while the package
  is `0.x`.
- `:checkpoint` event after every completed tool turn, before the next request,
  and `AgentCall.resume_checkpoint/3`: it continues at `checkpoint.steps + 1`
  with the checkpoint transcript and does not re-run a completed tool. A pause
  is still a `Pending` resumed with `resume/3`; a no-tool final answer is the
  terminal `Result`. There is no mid-stream or partial-turn checkpoint; a stream
  failure discards that turn's partial content and the last checkpoint retries
  it.
- The caller-owned journal pattern: append `Checkpoint.dump/1` checkpoint and
  pending records from `on_event:` and append the terminal `Result` the run
  returns. The library adds no `AgentCall.Journal` behaviour, store, ETS table or
  process; a failed store write is caught by the caller and its `cancel_when:`
  stops the run at the next safe boundary.
- `AgentCall.Thread`: the caller-owned thread contract. `load/1` returns the
  thread snapshot (`messages` and the latest `checkpoint`/`pending`/`result`) and
  `append/2` accepts a `Checkpoint`, `Pending`, `Result` or `Event`; `thread_id`
  is the caller's opaque key. The library calls neither callback and ships no
  store, process, table or schema. The guide resumes a pending before a
  checkpoint, appends the terminal `Result` after the outcome, and catches a
  store failure for the existing `cancel_when:`.
- `AgentCall.Input` and `use AgentCall.Input`: the input-pause payload and the
  marker for model-initiated input tools. Every tool a marked module declares is
  an input tool: its schema reaches the model through `ToolCall.describe/2`, but
  inside `AgentCall` the function is never invoked and a call pauses with the
  assembled call and its spec.
- `prompt:`: a one-arity caller policy at `:turn` and `{:tool, call}` boundaries.
  It returns `:cont` or `{:ask, payload}`; an ask pauses as an input pause with
  `source: :policy`. It runs again after a resume and must inspect the transcript
  or results. A raise, throw, exit or malformed return is a `:configuration`
  error.
- `:input_required` in the event union; `:run_started` reports `prompt?:` and
  `input_tools:`. Approval and input both finish as `:pending`, discriminated by
  `Pending.kind`.
- A marked input tool's call is checked before the `prompt:` policy, and the
  tool-phase policy before approval; an `arguments_error` still becomes an
  `is_error` result instead of a pause.
- `max_steps:`: budget guards at turn entry and before dispatch. A turn at the
  budget still receives its answer; its tools do not run, and `{:exhausted, _}`
  reports `halt_reason: :budget`.
- `cancel_when:`: a caller policy checked at `:turn` (after the budget/context
  check, before the request) and `:tools` (after the response, before any call).
  A cancel is terminal: `{:exhausted, result}` with
  `halt_reason: {:cancelled, reason}`, no request at `:turn` and no tool at
  `:tools`. A `:tools` cancel wins over an equally due budget stop. The policy
  is re-supplied on resume and is not checked before the paused batch a resume
  re-dispatches.
- `max_concurrency:`: opt-in parallel tool execution in ordered waves of at most
  that many calls. Results keep their call-order slots; a pause stops later
  waves and preserves results completed after an earlier pause; the final user
  turn filters the `nil` slots and keeps call order. `1` is the default and
  keeps the serial contract. A parallel pause must re-supply the option on
  resume.
- `run_id:`: a non-empty correlation id, generated when omitted, on `Result`,
  `Pending` and every `Event`. `resume/3` keeps the pending id; an empty supplied
  id is a `:configuration` error, and a hand-built `Pending` with a nil id is
  normalized on resume.
- `:telemetry` spans for runs, turns, tool calls and streamed turns:
  `[:agent_call, :run | :turn | :tool | :stream, :start | :stop | :exception]`,
  with `run_id` metadata and no messages, arguments, results, headers or
  credentials. A tool stop reports `outcome: :ok | :error | :pending`; an
  `is_error` tool result is `:error`. A raising handler cannot change a run.
- `context:`: a caller policy before every request that may pass the transcript
  through, replace it with a compacted one, or stop the run. A stop returns
  `{:exhausted, _}` with `halt_reason: {:context, reason}`; the library owns no
  tokenizer, model window, trimming or summary.
- `on_event:`: observe-only events for run, context, step, tool, checkpoint,
  approval, input and delta boundaries. `:run_started` is first and `:finished`
  is last, and an observer that raises cannot change the outcome.
- `stream: true`: each turn is read through `LlmCall.stream/3` and assembled
  internally — text, thinking with the signature that follows its block,
  `Content.Raw` parts and tool calls — with `:text_delta` and
  `:thinking_delta` events. The outcome shape is unchanged, but streamed
  responses do not fully match `complete/3`: `response.id`, `response.model`
  and `response.raw` stay `nil`, and tool calls are appended after text and
  thinking instead of at their provider position.
- `tool_opts:`, `max_result_bytes:` and `format_result:` for dispatch and result
  rendering, plus `codec:` and `headers:` forwarded to `llm_call`.
  `format_result:` accepts a two-arity renderer that also receives the byte
  budget, and `AgentCall.default_format/2` is the default: it bounds its own
  collection walk instead of rendering a value that would be truncated.
- `Checkpoint.dump/2` with `compress:`, and a per-record compression default:
  a text transcript is written compressed, a transcript carrying an image, file
  or video source is written uncompressed, because deflating base64 media costs
  proportional time for a fraction of the bytes.
- `AgentCall.AgentTool.run/4`: runs a complete inner agent from an ordinary
  `ToolCall` module and returns its final text as the outer tool result. `input`
  is a string or a message list; the helper copies the request and never mutates
  it. The inner request keeps its model, system prompt and tools, and the outer
  tool's timeout bounds the whole inner run. `on_pending:` resolves an inner
  approval/input pause — without it the pause is `{:error, {:pending, kind}}`
  and never becomes an outer `Pending`; a callback failure or an
  `{:error, reason}` decision is terminal. `on_result:` observes the inner
  terminal `Result` and cannot change the result; `on_event:` is forwarded to
  every inner run and resume. An empty inner answer is `""`, which the outer
  renderer turns into `"(no output)"`; an inner `:exhausted` is `{:error,
  {:exhausted, halt_reason, text}}` and an inner error is `{:error, {:inner,
  kind, message}}`. No process, store, schema or nested-`Pending` propagation.
- Public data and types: `AgentCall.Result`, `AgentCall.Pending`,
  `AgentCall.Checkpoint`, `AgentCall.Error`, `AgentCall.Event`,
  `AgentCall.Context`, `AgentCall.Cancel`, `AgentCall.Input`,
  `AgentCall.AgentTool` and `AgentCall.Thread`.
- `context:` may return `{:cont, messages, tools}` to replace the tool set for
  that turn and every later one, so a single run can grant tools progressively.
  The narrowed set is both what the model is offered and what the loop
  dispatches, and it travels on `Pending` and `Checkpoint` so a resume keeps it.
  `:step_started` reports each turn's set.
### Changed

- A malformed tool entry is a `:configuration` error before the first event when
  the problem is the entry's shape or options. A `%LlmCall.ToolSpec{}` whose
  *values* one dialect refuses stays that codec's `:llm` error, because the rule
  is protocol-specific: `kind: :builtin` is legal on Anthropic and Gemini and
  refused by OpenAI Chat, and a non-string `provider_options` key or a non-JSON
  `parameters` value is the same case.

### Fixed

- A `{module, opts}` tool entry whose options the codec cannot take is now a
  `:configuration` error before the first event. The entry is forwarded to
  `llm_call` verbatim, so `strict: :fine_tuned` (a `tool_call` render mode, not a
  codec option) and any unknown key used to reach the codec and come back as an
  `:llm` error attributed to the provider, after `:run_started`, with no
  `:configuration` error to point at the entry. The accepted set is `strict:` with
  a boolean or `nil`.

- `Dispatch.map/1` reports an improper `tools` list as a `:configuration` error
  instead of raising `FunctionClauseError` from inside `Enumerable`. `is_list/1`
  accepts an improper list, so the reduce walked into a clause it has no clause
  for; every other malformed list was already a `:configuration` error.

- `Checkpoint` record validation compares a struct's field set without sorting
  both key lists. Every `Message` and content part goes through it, so a
  3,000-message record validated in 1.74 ms instead of 0.90 ms; the field set is
  still matched exactly, so a struct with one field too many or too few is
  still refused.

- A rendered tool result is now checked for valid UTF-8. A renderer returning
  invalid bytes used to reach the model and fail as an `:llm` error on the *next*
  request ("request body is not JSON-encodable"), which reads as a transport
  problem; it is a `:tool` error naming the renderer instead. The check covers
  the text that is sent, so a capped result costs the cap rather than the
  renderer's output, and it applies to a turn answer as well as a tool result —
  the message names which one.
- A renderer result that is not valid UTF-8 is now refused at every size. Over
  the cap, truncation backed off one byte at a time until the prefix validated,
  which for bytes that were never UTF-8 meant backing off to nothing: a 100 KB
  malformed result reached the model as `"(no output)"` instead of an error, and
  the back-off rescanned the prefix at every step. `default_format/2` now formats
  without truncating, so the dispatch step cuts once, and the UTF-8 check refuses
  the value consistently.

- Resume records are checked before a run: a malformed top-level `Pending`,
  positional results/remaining mismatch, a `Usage` field that is not `nil` or a
  non-negative integer, a `ToolResult` with non-text content or a non-boolean
  `is_error`, a transcript with a non-`Message` entry or invalid `Message`
  role/content, an invalid `Content` field (`Text.text`, media source,
  `Thinking.text/signature`, `Raw` data), invalid request
  `model/provider_options/system/tool_choice/output/modalities/reasoning/params/
  stream`, invalid `ToolSpec` fields, and a `ToolCall` with invalid nullable
  fields are `:configuration` errors. A tool-target `Input.source` must be
  `:model` or `:policy`; `spec` must be a `ToolSpec` or `nil` and its name must
  match the paused call, `inserted_at` a `DateTime`, and
  `Approval.Request.id/module/tool/args/inserted_at` have their declared types.
  A model-source tool input requires a spec and a nil prompt. `ToolResult`/`ToolCall` identifiers remain nullable, as the dependency
  contract allows. A malformed `run/3` request, including improper
  `messages`/`tools` lists, non-`Message` entries and fake nested structs, is
  rejected the same way instead of crashing in the loop; live requests are not
  required to be portable. A turn-input resume checks the budget before
  rendering the answer.

- The README's examples use DeepSeek: the Quick start, usage, approval, input,
  thread and agent-tool snippets use `MyApp.DeepSeek`, `deepseek-chat` and
  `DEEPSEEK_API_KEY`, and the compiled example's default client matches.
- The guide's example context policy no longer keeps a tail that starts with a
  tool result; it drops to a clean user turn or keeps the whole transcript. The
  example thread, journal and Research flows accept an injected client, the
  example stores cap their history, and `Journal.latest_checkpoint/2` filters by
  `run_id`.

### Compatibility

- Elixir 1.18+. Runtime dependencies are `llm_call ~> 0.4.0`, `tool_call ~> 0.4`
  and `:telemetry ~> 1.0`.
- A persisted `Checkpoint` or `Pending` is guaranteed to load in the release that
  wrote it; cross-version resume is not promised while the package is `0.x`.
