# AgentCall

[![CI](https://github.com/gilbertwong96/agent_call/actions/workflows/ci.yml/badge.svg)](https://github.com/gilbertwong96/agent_call/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/gilbertwong96/agent_call/graph/badge.svg)](https://codecov.io/gh/gilbertwong96/agent_call)
[![Elixir](https://img.shields.io/badge/elixir-1.18+-purple.svg)](https://elixir-lang.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![Hex.pm](https://img.shields.io/hexpm/v/agent_call.svg)](https://hex.pm/packages/agent_call)

Run the tool loop `llm_call` leaves to the caller. `AgentCall` sends the request,
runs the tool calls the model asks for with `tool_call`, appends their results,
and repeats until the model asks for no more tools or `max_steps:` is spent. It
can pause for approval or for input and resume from data. It is a small data
API with three entry points: no process, no store, no application config, no
global state.

## Installation

```elixir
def deps do
  [{:agent_call, "~> 0.1.0"}]
end
```

Requires Elixir 1.18+. Runtime dependencies are `llm_call`, `tool_call` and
`:telemetry`.

## Quick start

The smallest runnable example: one tool, one loop, DeepSeek as the provider.
Paste it into `iex -S mix` with `DEEPSEEK_API_KEY` set; it is documentation, not
compiled into the package.

```elixir
defmodule BasicExample.Weather do
  use ToolCall

  @doc """
  Get the forecast for a city.

  ## Parameters
    * `city` - city name
  """
  @spec get_weather(city :: String.t()) :: {:ok, %{city: String.t(), temp: float()}}
  def get_weather(city), do: {:ok, %{city: city, temp: 21.5}}
end

defmodule BasicExample.DeepSeek do
  use LlmCall.Provider,
    base_url: "https://api.deepseek.com",
    auth: :bearer,
    codecs: [chat: LlmCall.Dialect.OpenAI.Chat]
end

defmodule BasicExample do
  def ask(question) when is_binary(question) do
    client = BasicExample.DeepSeek.client(api_key: System.fetch_env!("DEEPSEEK_API_KEY"))

    request = %LlmCall.Request{
      model: "deepseek-chat",
      messages: [
        %LlmCall.Message{role: :user, content: [%LlmCall.Content.Text{text: question}]}
      ],
      tools: [BasicExample.Weather]
    }

    AgentCall.run(client, request, max_steps: 4)
  end
end
```

```elixir
iex> {:ok, result} = BasicExample.ask("What is the weather in Oslo?")
{:ok, %AgentCall.Result{...}}
iex> LlmCall.Response.text(result.response)
"The weather in Oslo is 21.5°C."
iex> result.tool_calls
1
iex> result.halt_reason
nil
```

`ask/1` returns the raw outcome; `result.transcript` holds the assistant's tool
call and the tool result the loop appended. `deepseek-chat` speaks OpenAI Chat
Completions, so the codec is `LlmCall.Dialect.OpenAI.Chat`; another
OpenAI-compatible endpoint needs only a different `base_url` and `model`.

## Usage

`run/3` takes an `LlmCall` client, a canonical request and options. `request.tools`
is the only tool list: the loop dispatches the tools the model may call, and a
marked input tool pauses instead of running.

```elixir
defmodule MyApp.Approval do
  @moduledoc false

  @behaviour ToolCall.Approval

  @impl true
  def check(_tool, _args, _context), do: {:required, :human}
end

defmodule MyApp.Weather do
  use ToolCall, approval: MyApp.Approval

  @doc """
  Get the forecast for a city.

  ## Parameters
    * `city` - city name
  """
  @spec get_weather(city :: String.t()) :: {:ok, %{city: String.t(), temp: float()}}
  def get_weather(city), do: {:ok, %{city: city, temp: 21.5}}
end

defmodule MyApp.AskUser do
  use AgentCall.Input

  @doc """
  Ask the user to choose an environment.

  ## Parameters
    * `question` - the question to show
  """
  @spec choose(question :: String.t()) :: {:ok, String.t()}
  def choose(question), do: {:ok, question}
end

defmodule MyApp.DeepSeek do
  use LlmCall.Provider,
    base_url: "https://api.deepseek.com",
    auth: :bearer,
    codecs: [chat: LlmCall.Dialect.OpenAI.Chat]
end

defmodule MyApp.Assistant do
  def ask(question) do
    client = MyApp.DeepSeek.client(api_key: System.fetch_env!("DEEPSEEK_API_KEY"))

    request = %LlmCall.Request{
      model: "deepseek-chat",
      messages: [
        %LlmCall.Message{
          role: :user,
          content: [%LlmCall.Content.Text{text: question}]
        }
      ],
      tools: [MyApp.Weather, MyApp.AskUser]
    }

    AgentCall.run(client, request, max_steps: 6)
  end
end
```

The example is compiled in `:dev` and `:test` in
[`examples/agent_call_example.ex`](https://github.com/gilbertwong96/agent_call/blob/main/examples/agent_call_example.ex),
so it cannot rot; it makes no call on its own.

`run/3`, `resume/3` and `resume_checkpoint/3` end in one of four outcomes:

| Outcome | Meaning |
| --- | --- |
| `{:ok, result}` | The model asked for no more tools. `result.stop_reason` still reports the provider's finish, for example `:max_tokens` or `:content_filter`. |
| `{:exhausted, result}` | The run did not finish normally: `result.halt_reason` is `:budget`, `{:context, reason}`, `{:input, reason}` or `{:cancelled, reason}`, and `result.transcript` holds what the model asked for. For `{:input, _}`, the cancelled turn was never sent, so the transcript ends at the pause. A cancellation is terminal; there is no resume for it. |
| `{:pending, pending}` | A call needs approval or input. `pending.kind` says which; `pending` is data: store it and resume later. |
| `{:error, error}` | The run failed. `error.kind` is `:configuration`, `:llm` or `:tool`; an `:llm` error carries the `%LlmCall.Error{}` in `cause`. |

### Approval

Approval is `tool_call`'s policy. A tool that declares one
(`use ToolCall, approval: MyApp.Approval`) can pause the run: `run/3` returns a
`%AgentCall.Pending{}` before the call is invoked. `resume/3` re-dispatches that
call with the decision, runs the rest of the turn in call order, and sends one
user turn of results:

```elixir
client = MyApp.DeepSeek.client(api_key: System.fetch_env!("DEEPSEEK_API_KEY"))
{:pending, pending} = MyApp.Assistant.ask("Weather in Oslo?")

# Persist `pending`, ask the human, then resume in a later request:
{:ok, result} = AgentCall.resume(client, pending, approval: :granted)
```

A denial (`approval: :denied`) becomes an `is_error` result the model reads, not
an abort. `Pending` is serializable, and `resume/3` takes the same options as
`run/3`; `max_concurrency:` and `cancel_when:` are re-supplied rather than stored.

### Input

A module that `use AgentCall.Input` marks every tool it declares as an input
tool. The schema is still derived from `@doc`/`@spec` and offered to the model,
but inside `AgentCall` the function never runs: a call pauses with the assembled
call, its spec, and `source: :model`. In the usage example above, `MyApp.AskUser`
is marked; a call to its `choose` tool pauses like this:

```elixir
request = %LlmCall.Request{
  model: "deepseek-chat",
  messages: [
    %LlmCall.Message{
      role: :user,
      content: [%LlmCall.Content.Text{text: "Deploy which environment?"}]
    }
  ],
  tools: [MyApp.Weather, MyApp.AskUser]
}

{:pending, %AgentCall.Pending{kind: :input} = pending} =
  AgentCall.run(client, request, max_steps: 6)

# The question and options are `pending.input.call.arguments`; the UI asks,
# then the answer becomes that call's result:
{:ok, result} = AgentCall.resume(client, pending, input: {:answer, "staging"})
```

`use AgentCall.Input` is the identity: there is no `input_tool:` option and no
reserved name. A module can declare several tools; every one of them is an
input tool. A marked module used outside `AgentCall` calls its functions
normally.

A caller or policy can also ask at a boundary with `prompt:`. It is a one-arity
function over the current `AgentCall.Input.info()` and returns `:cont` or
`{:ask, payload}`; a raise, throw, exit or malformed return is a
`:configuration` error:

```elixir
prompt = fn info ->
  case info.phase do
    :turn -> :cont
    {:tool, %LlmCall.ToolCall{name: "get_weather"}} -> {:ask, %{question: "Which city?"}}
    {:tool, _call} -> :cont
  end
end

AgentCall.run(client, request, prompt: prompt)
```

A turn-phase ask pauses before the request; a tool-phase ask pauses before
`ToolCall.run/4`, so it wins over approval. The input-tool marker wins over the
policy, and the policy sees `phase`, `step`, `max_steps:`, the last response's
`usage`, the `request`, the `messages`, and the call's `module`/`spec` where
applicable. It runs again after a resume, so it must inspect `info.messages` (or
the results) and return `:cont` once it has asked; the library keeps no
already-asked state.

`resume/3` takes `input:` for an input pause:

- `{:answer, value}` is rendered with `format_result:` and capped by
  `max_result_bytes:`. For a tool target it becomes that call's result, exactly
  as if the tool had returned it; for a turn target it becomes one user message
  and the same model turn continues.
- `{:cancel, reason}` is an `is_error` result for a tool target (the turn
  continues and the model reads the refusal), or `{:exhausted, result}` with
  `halt_reason: {:input, reason}` for a turn target (no request is sent).

An empty or whitespace answer becomes `"(no output)"`. The library does not
validate an answer against the tool's JSON schema; the caller's UI owns that and
any term is rendered. `Pending` is still the whole state: a turn with several
calls can pause more than once, and every pause serializes with
`:erlang.term_to_binary/1`.

### Events

`on_event:` observes a run without changing it. The function runs synchronously
in the loop's process, its return value is ignored, and a raise, throw or exit
in it is caught. The event types are `:run_started`, `:context_updated`,
`:step_started`, `:text_delta`, `:thinking_delta`, `:tool_call_started`,
`:tool_result`, `:checkpoint`, `:step_finished`, `:approval_required`,
`:input_required` and `:finished`. `:run_started` is first and `:finished` is
last. Every event has a `run_id` field; it is not duplicated in an event's
`data`. Approval and input both finish as `:pending`, discriminated by
`Pending.kind`; `:checkpoint` is the completed-tool-turn boundary described in
[Checkpoint and journal](#checkpoint-and-journal); `:run_started` also reports
`prompt?:`, `cancel?:`, `max_concurrency:` and the marked `input_tools:`.

```elixir
AgentCall.run(client, request, on_event: fn event -> IO.inspect(event.type) end)
```

With `stream: true`, each turn is read through `LlmCall.stream/3` and assembled
internally; `:text_delta` and `:thinking_delta` report text as it arrives. Text
and thinking keep provider order; tool calls are appended after them in index
order, so a turn that interleaves calls between those parts has a different part
order from `complete/3`. The outcome keeps its four shapes; `response.id`,
`response.model` and `response.raw` are `nil` because a stream does not carry
them.

### Context

`context:` runs before every request, after the step-budget check. It may pass the
transcript through, replace it with a compacted list, or stop the run:

```elixir
AgentCall.run(client, request,
  context: fn messages, info ->
    if length(messages) > 20 do
      {:stop, {:too_many_messages, info.step}}
    else
      {:cont, messages}
    end
  end
)
```

A stop returns `{:exhausted, result}` with `halt_reason: {:context, reason}` and
makes no request. `Result.transcript` is the context the model actually saw; the
event stream is the full history.

A third element replaces the tool set for this turn and every later one — the
way to grant tools progressively inside one run:

```elixir
AgentCall.run(client, request,
  context: fn messages, %{step: step} ->
    tools =
      if step < 3,
        do: [MyApp.Tools.Search],
        else: [MyApp.Tools.Search, MyApp.Tools.Deploy]

    {:cont, messages, tools}
  end
)
```

The narrowed set is both what the model is offered and what the loop dispatches:
a removed name is answered with `"no tool named ..."`, never run. It travels on
`Pending` and `Checkpoint`, so a resume keeps it instead of restoring the run's
original set. An empty list is legal, `nil` leaves the set alone, and
`:step_started` reports each turn's set as `data: %{tools: [...]}`.

### Runtime controls

Three options extend the same loop without a new outcome:

- `cancel_when:` is a one-arity policy checked at two safe boundaries: after the
  budget/context check and before a turn's request (`phase: :turn`), and after
  the assistant response and before any of its tools starts (`phase: :tools`).
  It returns `:cont` or `{:cancel, reason}`. A cancel is
  `{:exhausted, result}` with `result.halt_reason == {:cancelled, reason}`; no
  request or tool runs at that boundary. A cancel set while tools are already
  running is observed at the next turn. A raise, throw, exit or bad return is a
  `:configuration` error.

  ```elixir
  cancel_when = fn
    %{phase: :turn, usage: %{total_tokens: tokens}}
    when is_integer(tokens) and tokens > 100_000 ->
      {:cancel, :token_budget}

    %{phase: :tools, calls: calls} ->
      if Enum.any?(calls, &(&1.name == "deploy")), do: {:cancel, :needs_human}, else: :cont

    _info ->
      :cont
  end

  AgentCall.run(client, request, cancel_when: cancel_when, run_id: "deploy-42")
  ```

  `cancel_when:` is re-supplied on resume. It is checked at new turn entries and
  before a new tool batch, not before the paused batch `resume/3` re-dispatches:
  that batch runs under the explicit approval/input decision. A `:tools` cancel
  wins over an equally due budget stop.

- `max_concurrency:` is a positive integer, default `1`. A turn's calls run in
  ordered waves of at most that size: a later wave waits for the previous one,
  and a pause stops all later waves. `Pending.results` is positional either way,
  one slot per assistant call, with `nil` for a paused or unstarted call; the
  final user turn filters the nils and keeps call order. With `max_concurrency >
  1`, a tool can start before an earlier gated call's approval; use `1` when
  strict pre-approval ordering matters. The tool-phase `prompt:` and
  `format_result:` run in worker tasks in that mode, so process-local state in
  them is the caller's responsibility; `on_event:` stays in the loop process.
  A parallel pause resumed without `max_concurrency:` runs serially.

  ```elixir
  {:pending, pending} =
    AgentCall.run(client, request, max_concurrency: 4, max_steps: 6)

  # Persist `pending`, ask the human, then resume with the batch size again:
  {:ok, result} =
    AgentCall.resume(client, pending, approval: :granted, max_concurrency: 4)
  ```

- `run_id:` is a non-empty correlation string, generated when omitted. It is on
  `Result`, `Pending` and every `Event`, and is the `run_id` in telemetry
  metadata. `resume/3` keeps the `Pending`'s id; it does not take `run_id:`.

- `format_result:` renders a tool's return value as the text the model sees,
  capped by `max_result_bytes:` (default 8 KiB). The default is
  `AgentCall.default_format/2`, a two-arity renderer that also receives the
  byte budget and bounds its own walk instead of building a string that would be
  truncated. It formats; it does not truncate — the cap and the truncation
  marker are applied once, by the dispatch step. A one-arity renderer is still accepted and renders the whole value;
  the result is truncated afterwards either way. Both forms must return a
  binary: a renderer that returns something else, returns bytes that are not
  valid UTF-8, raises, throws or exits after the tool ran is a `:tool` error
  rather than a silent `inspect/1` — a model cannot read invalid UTF-8, and the
  next request's JSON encoder would refuse it.

  ```elixir
  AgentCall.run(client, request, max_result_bytes: 4_096)

  # A renderer that knows the budget: emit JSON up to the cap, not 40 MB of it.
  AgentCall.run(client, request,
    format_result: fn value, max_bytes -> MyApp.JSON.render(value, max_bytes) end
  )
  ```

Telemetry is additive and needs no handler. The library emits
`[:agent_call, :run | :turn | :tool | :stream, :start | :stop | :exception]`
spans with `run_id`, step and shape metadata; a tool stop adds `outcome: :ok |
:error | :pending`, where an `is_error` tool result is `:error`. Metadata never
contains messages, tool arguments, results, headers or credentials, and a
raising handler cannot change the run. A stream that fails while it is being
read emits `:exception` and no `:stop`; a tool-target input answer's only tool
span is its original `:pending` span.

```elixir
:telemetry.attach_many(
  "agent-call-logger",
  [
    [:agent_call, :run, :stop],
    [:agent_call, :tool, :stop],
    [:agent_call, :stream, :exception]
  ],
  fn event, measurements, metadata, _config ->
    Logger.info("#{inspect(event)} #{inspect(metadata)} #{measurements.duration}")
  end,
  nil
)
```

### Checkpoint and journal

After every completed **tool** turn the loop emits one `:checkpoint` event
before the next request. Its data is `%{checkpoint: %AgentCall.Checkpoint{}}`:
the request, the model-visible transcript after that turn's tool results, the
completed `steps` and `tool_calls`, and the accumulated and last-turn usage.
`AgentCall.Checkpoint.dump/1` wraps a `Checkpoint` (or a `Pending`) in a
versioned binary envelope; `load/1` checks the version, type and payload:

```elixir
%AgentCall.Event{type: :checkpoint, data: %{checkpoint: checkpoint}} = event
binary = AgentCall.Checkpoint.dump(checkpoint)
{:ok, ^checkpoint} = AgentCall.Checkpoint.load(binary)
```

`dump/1` compresses a text transcript and writes a transcript carrying an image,
file or video source uncompressed: base64 media is already transparent to
deflate, where compressing it costs hundreds of milliseconds per checkpoint to
save a fraction. `dump/2` takes `compress:` (`:auto`, `false`, `true` or a zlib
level `1..9`) to decide for a specific record.

`load/1` validates the record recursively and returns `{:error, :invalid}` for
a malformed envelope, a malformed nested struct, a `Usage` field that is not
`nil` or a non-negative integer, `ToolResult` content that is not text, a
`ToolResult.is_error` that is not a boolean, a message with an invalid role or
content, an invalid `Content` field (`Text.text`, media source,
`Thinking.text/signature`, `Raw` data), an invalid request
`model/provider_options/system/tool_choice/output/modalities/reasoning/params/
stream` or `ToolSpec` field, a `ToolCall` with invalid nullable fields, a
tool-target `Input.source/spec(call-name)/inserted_at`, a model-source input
without a spec or with a prompt, an `Approval.Request` with invalid
`id/module/tool/args/inserted_at`, or a non-portable payload (a fun, pid, port
or reference); `ToolResult`/`ToolCall` identifiers may be `nil`,
because the protocol adapter decides which identifier it needs. `{:error,
:unsupported_version}` is for an envelope this release does not know. A record is guaranteed to load in the release that wrote
it; cross-version resumption is not promised while the package is `0.x`.

The journal is the caller's append-only log, not a library feature. Append the
records `on_event:` delivers, keyed by `run_id`:

| Event | Record |
| --- | --- |
| `:checkpoint` | `Checkpoint.dump(checkpoint)` |
| `:approval_required`, `:input_required` | `Checkpoint.dump(pending)` |

The terminal record is not an event: append the `%AgentCall.Result{}` that
`run/3`, `resume/3` or `resume_checkpoint/3` returns (the `:finished` event data
is not a full result).

```elixir
on_event = fn
  %AgentCall.Event{type: :checkpoint, data: %{checkpoint: checkpoint}} ->
    MyApp.Journal.append(store, %{
      run_id: checkpoint.run_id,
      type: :checkpoint,
      payload: AgentCall.Checkpoint.dump(checkpoint)
    })

  %AgentCall.Event{type: type, data: %{pending: pending}}
  when type in [:approval_required, :input_required] ->
    MyApp.Journal.append(store, %{
      run_id: pending.run_id,
      type: :pending,
      payload: AgentCall.Checkpoint.dump(pending)
    })

  _event ->
    :ok
end
```

The latest `:checkpoint` for a run is its resume point; a real adapter queries
by `run_id`. `resume_checkpoint/3` takes the same options as `run/3` except
`run_id:` and no approval/input decision; it starts at `checkpoint.steps + 1`,
sends the checkpoint transcript, and does not re-run a completed tool. The
resumed run re-supplies the journal observer, and its terminal record is the
`Result` it returns:

```elixir
# `on_event` is the journal observer above; re-supply it to the resumed run.
%{payload: binary} = MyApp.Journal.latest_checkpoint(store)
{:ok, checkpoint} = AgentCall.Checkpoint.load(binary)

case AgentCall.resume_checkpoint(client, checkpoint, max_steps: 6, on_event: on_event) do
  {:ok, %AgentCall.Result{} = result} ->
    MyApp.Journal.append(store, %{run_id: result.run_id, type: :result, payload: result})

  {:exhausted, %AgentCall.Result{} = result} ->
    MyApp.Journal.append(store, %{run_id: result.run_id, type: :result, payload: result})

  {:pending, %AgentCall.Pending{} = pending} ->
    MyApp.Journal.append(store, %{
      run_id: pending.run_id,
      type: :pending,
      payload: AgentCall.Checkpoint.dump(pending)
    })

  {:error, %AgentCall.Error{} = error} ->
    error
end
```

A failed `:approval_required`/`:input_required` append is not recoverable by
`cancel_when:`: the run has already returned the pause, so there is no next
boundary. Catch the failure and persist or retry the returned `Pending`; the
caller's store is the only durable copy.

A `%AgentCall.Pending{}` is loaded and resumed with `resume/3` and its decision;
the envelope does not change the pause. The safe boundary is a completed tool
turn: there is no mid-stream or partial checkpoint. A streamed completed turn
checkpoints; a stream failure discards that turn's partial content, emits no
checkpoint and returns the existing `:llm` error, so the last checkpoint retries
the turn. A checkpoint does not mean the model finished: a no-tool final answer
is the terminal `Result`, and the checkpoint before it stays resumable.

A store write runs synchronously in `on_event:`. If it fails, catch the raise,
throw or exit, set a caller flag, and let `cancel_when:` stop at the next safe
boundary; the library adds no callback and no outcome:

```elixir
failure = :atomics.new(1, [])

on_event = fn
  %AgentCall.Event{type: :checkpoint, data: %{checkpoint: checkpoint}} ->
    try do
      MyApp.Journal.append(store, %{
        run_id: checkpoint.run_id,
        type: :checkpoint,
        payload: AgentCall.Checkpoint.dump(checkpoint)
      })
    rescue
      _exception -> :atomics.put(failure, 1, 1)
    catch
      :exit, _reason -> :atomics.put(failure, 1, 1)
      :throw, _value -> :atomics.put(failure, 1, 1)
    end

  _event ->
    :ok
end

cancel_when = fn _info ->
  if :atomics.get(failure, 1) == 1,
    do: {:cancel, :checkpoint_store_failed},
    else: :cont
end

AgentCall.run(client, request, on_event: on_event, cancel_when: cancel_when)
```

At the next turn entry the run returns `{:exhausted, result}` with
`halt_reason: {:cancelled, :checkpoint_store_failed}`. That entry's budget check
and context policy run before `cancel_when:`, so if either stops first, the
outcome is `:budget` or `{:context, reason}` instead. The last successfully
persisted checkpoint is still the resume point; a turn that completed after it
is replayed, because the store never acknowledged it. There is no
`AgentCall.Journal` behaviour, store, ETS table or process in the library;
`MyApp.Journal` is your adapter, and its failure policy is yours.

### Thread and context

The journal answers where a completed turn resumes; a thread answers what the
whole conversation is. `AgentCall.Thread` is a behaviour, not a store: the
caller owns the thread records, the model-visible messages and the store that
persists them. The library never calls `load/1` or `append/2` and ships no
thread store, process, ETS table, schema or application config.

```elixir
defmodule MyApp.ThreadStore do
  @behaviour AgentCall.Thread

  @impl true
  def load(thread_id), do: MyApp.Store.load_thread(thread_id)

  @impl true
  def append(thread_id, record), do: MyApp.Store.append_thread(thread_id, record)
end
```

`load/1` returns `{:ok, snapshot}` or `{:error, reason}`. The snapshot has four
fields:

| Field | Meaning |
| --- | --- |
| `messages` | The model-visible messages the next request starts from. |
| `checkpoint` | The last completed tool turn, or `nil`; see [Checkpoint and journal](#checkpoint-and-journal). |
| `pending` | The live approval/input pause, or `nil`. |
| `result` | The last terminal `Result`, or `nil`. |

`append/2` receives a `%AgentCall.Checkpoint{}`, `%AgentCall.Pending{}`,
`%AgentCall.Result{}` or `%AgentCall.Event{}`; the store decides what to index,
retain and query. `thread_id` is the caller's opaque key; the run's `run_id`
travels on the records. A failed `load/1` leaves the run's start to the caller.

The caller loads the snapshot and chooses one of three paths:

```elixir
{:ok, snapshot} = MyApp.ThreadStore.load(thread_id)
on_event = fn event -> MyApp.ThreadStore.append(thread_id, event) end
context = &MyApp.Threads.fit/2

# The decision answers the pause and must match `Pending.kind`: `approval:`
# (`:granted` or `:denied`) for an approval pause, `input:` (`{:answer, term}`
# or `{:cancel, term}`) for an input pause.
decision = [approval: :granted]  # only for :approval; input: for :input

outcome =
  case snapshot do
    %{pending: %AgentCall.Pending{} = pending} ->
      AgentCall.resume(client, pending, [on_event: on_event, context: context] ++ decision)

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

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

A pending wins over a checkpoint: the pending is the live pause that must be
answered, while the checkpoint is the last completed tool turn. A thread with
both resumes the pending; the next completed tool turn emits a new checkpoint.
A pending resume carries exactly one decision matching `Pending.kind`; the
checkpoint and messages paths take none.
With no pending, a checkpoint resumes at the next turn and does not re-run a
completed tool. Only messages means a fresh `run/3` from the loaded messages;
the caller supplies the system prompt, tools and run options. Re-supply the
observer, `context:` and `cancel_when:` on every run and resume: they are
policies, not data in the records.

The terminal `Result` is appended after the outcome. The event stream and the
result are separate records; the `:finished` event is not a full `Result`. A
failed terminal append returns the outcome unchanged; no boundary follows it:

```elixir
case outcome do
  {status, %AgentCall.Result{} = result} when status in [:ok, :exhausted] ->
    MyApp.ThreadStore.append(thread_id, result)

  _other ->
    :ok
end
```

A pause arrives through the `:approval_required` or `:input_required` event, so
the observer above already appended its `Pending` when it appended every event.
If the store keeps only records, extract `checkpoint`/`pending` from the event
data instead; the observer must be re-supplied to the resumed run either way.

A store write runs synchronously in `on_event:`. Handle the behaviour's
`{:error, reason}` return and catch a raise, throw or exit from a store that
fails differently, set a caller flag, and let the existing `cancel_when:` stop
at the next safe boundary:

```elixir
failure = :atomics.new(1, [])

append = fn record ->
  try do
    case MyApp.ThreadStore.append(thread_id, record) do
      :ok -> :ok
      {:error, _reason} -> :atomics.put(failure, 1, 1)
    end
  rescue
    _exception -> :atomics.put(failure, 1, 1)
  catch
    :exit, _reason -> :atomics.put(failure, 1, 1)
    :throw, _value -> :atomics.put(failure, 1, 1)
  end
end

cancel_when = fn _info ->
  if :atomics.get(failure, 1) == 1,
    do: {:cancel, :thread_store_failed},
    else: :cont
end

# `append` is the `on_event:` for run/3, resume/3 or resume_checkpoint/3.
AgentCall.run(client, request, on_event: append, cancel_when: cancel_when)
```

The run stops at its next safe boundary and returns `{:exhausted, result}` with
`halt_reason: {:cancelled, :thread_store_failed}`. The last successfully
persisted checkpoint remains the resume point; a turn whose checkpoint was not
acknowledged is replayed. A failed pause append cannot be cancelled this way:
the run has already returned that `Pending`, so persist or retry it before
dropping it. A failed `:finished` append cannot be cancelled either: it is the
last event and no boundary follows, so the run returns its outcome as-is. The
library adds no thread-specific error kind or outcome.

`context:` remains the only context seam. A thread-aware policy sees the loaded
messages and may trim, summarize or replace them; the library never loads or
trims a thread implicitly:

```elixir
context = &AgentCall.Example.thread_context/2
```

The example policy keeps a recent tail only when it starts at a clean user
turn; a suffix beginning with a tool result cannot be replayed without the
assistant call it answers.

The compiled example has a caller-owned `Agent` store implementing the
behaviour. Its `thread/2` starts and stops the store it uses and grants
approval pauses up to its attempt limit; `thread/3` exposes that limit. Its
`resume_thread/3` takes a store the caller keeps, the decision to forward to
`resume/3` and an optional client. Both stores cap their history (100 thread
events, 1,000 journal entries) and expose `fail_next/2` and `fail_next/1`, so
the failure policies above are exercisable; `Journal.latest_checkpoint/2`
filters by `run_id`. `journal/3` likewise accepts an injected client, and
`Research.research/3` accepts one plus extra inner options. The optional
clients are what the runtime tests inject; production calls use DeepSeek.
Neither adds a library process or schema.

### Agents as tools

`AgentCall.AgentTool.run/4` runs a complete inner agent and returns its final
text as one tool result. The caller writes an ordinary `ToolCall` module; the
outer `request.tools` lists it like any other tool. The helper is a synchronous
function: no process, no store, no second runtime, and it derives no schema.

```elixir
defmodule MyApp.Research do
  use ToolCall

  @doc """
  Research a topic with a sub-agent.

  ## Parameters
    * `topic` - the topic to research
  """
  @spec research(topic :: String.t()) :: {:ok, String.t()} | {:error, tuple()}
  def research(topic) do
    AgentCall.AgentTool.run(
      MyApp.DeepSeek.client(api_key: System.fetch_env!("DEEPSEEK_API_KEY")),
      %LlmCall.Request{
        model: "deepseek-chat",
        messages: [],
        tools: [MyApp.Weather]
      },
      "Research: " <> topic,
      max_steps: 4,
      on_pending: fn
        %AgentCall.Pending{kind: :approval} -> {:approval, :granted}
        %AgentCall.Pending{kind: :input} -> {:input, {:cancel, :not_supported}}
      end,
      on_event: fn event -> IO.inspect(event.type) end,
      on_result: fn result -> IO.inspect(result.run_id) end
    )
  end
end
```

When the outer model calls `MyApp.Research`, the inner run happens inside the
outer tool's task and the inner final text becomes the outer tool result; an
empty inner answer becomes `"(no output)"` like any other blank tool result.
`input` is a string (one user message) or a list of messages appended to the
inner request. The helper copies the request, keeps its model, system prompt
and tools, and takes every `AgentCall.run/3` option plus two helper-only keys:

- `on_pending:` is the nested-pause seam: a 1-arity control callback that gets
  the inner `%AgentCall.Pending{}` and returns the decision to resume with
  (`{:approval, :granted | :denied}`, `{:input, {:answer, term} | {:cancel,
  term}}`) or `{:error, reason}`. Without it, an inner pause is `{:error,
  {:pending, kind}}`. A callback failure or an `{:error, reason}` decision is
  terminal. The callback runs synchronously in the outer tool's process and may
  block; the outer `tool_opts: [timeout: ...]` still bounds the inner run.
- `on_result:` observes the inner terminal `%AgentCall.Result{}` for an `:ok` or
  `:exhausted` inner run. Its failure is ignored and it never changes the result.

The snippet's `{:error, tuple()}` is a narrow `ToolCall`-friendly result type;
the helper itself returns `{:error, term()}`, and an `on_pending:` error
decision is passed through as `{:error, reason}` unchanged.

The outer loop only ever sees a tool result: an inner pause is resolved by
`on_pending:` or becomes an `is_error` result, and an inner `:exhausted` is
`{:error, {:exhausted, halt_reason, text}}` while an inner error is `{:error,
{:inner, kind, message}}`. The inner transcript, usage and `Result` are
available through `on_event:`, `on_result:` and telemetry, not to the outer
model. Inner telemetry spans carry the inner `run_id`; the outer `:tool` span
carries the outer run id, so pass a derived `run_id:` to the helper when you
want to correlate them. There is no depth or cycle guard: `max_steps:`, the
outer tool timeout and the inner options bound composition, and a sub-agent tool
calling another is the caller's decision.

## Non-goals

Not a framework, an orchestration runtime, a conversation store, a provider layer,
a retry policy, a tool framework, a streaming API or an event bus. Approvals,
audits and timeouts stay in `tool_call`; protocol, transport, codecs and JSON stay
in `llm_call`; schema derivation stays in `tool_call`. Retry, persistence and
provider routing are caller policy.

## Benchmarking

`mix bench` prints a baseline for the costs that regress as a cliff rather than
a slope: dumping a checkpoint once per completed turn, rendering a tool result
that will be capped anyway, running and resuming over a long transcript, and
folding a streamed turn. A fixture HTTP server stands in for the provider, so
each number is the library's own overhead.

```bash
mix bench
```

The numbers track the machine, so compare two runs of the same script rather
than two machines. `test/agent_call/performance_test.exs` is what CI enforces:
each test compares two things measured on the same machine in the same run, so
a ratio — not a wall-clock budget — is the assertion. When one fails, `mix bench`
shows which row moved.

## Documentation

[`docs/design.md`](docs/design.md) is the contract,
[`docs/roadmap.md`](docs/roadmap.md) is the plan, and
[`CHANGELOG.md`](CHANGELOG.md) records releases.

## License

MIT
