# ExAgent 3.0.0 — LLM Reference Bundle Stable APIs follow the published compatibility contract. Candidate APIs and options can change in minor releases. Check the member and option tier as well as the module tier. This single-fetch bundle includes the coding-agent manual, usage rules, all 11 skills, both detailed contract sheets, and the support/limits contract sections. It does not inline per-function module documentation or full human tutorials — use [llms.txt](llms.txt) to locate and fetch individual `.md` or guide `.md` pages. ## Contents - [Coding agent manual](#coding-agent-manual) - [Usage rules](#usage-rules) - [Skills](#skills) - [Detailed contracts](#detailed-contracts) - [Support and limits](#support-and-limits) ## Coding agent manual ### Integration notes for coding agents #### Read only what the task needs | Access | Entry | |---|---| | Lowest context (recommended) | Start here (`agents.md`), then load `usage-rules.md` and only the matching skill/contract sheet below. | | Select pages & module index | [Markdown index](https://hexdocs.pm/exagent/3.0.0/llms.txt) | | Fetch one module or guide | Use the page's `.md` sibling, e.g. `ExAgent.Server.md` or [Getting started Markdown](https://hexdocs.pm/exagent/3.0.0/getting-started.md). | | Optional single-fetch bundle | [ExAgent 3.0.0 LLM reference bundle](https://hexdocs.pm/exagent/3.0.0/llms-full.txt) (manual + rules + 11 skills + detailed contracts + support/limits; fetch `.md` for per-function specs and guides for full tutorials). | | Installed dependency | Run `mix run --no-start -e 'IO.puts(Path.expand(Map.fetch!(Mix.Project.deps_paths(), :exagent)))'`. Load `usage-rules.md` and `usage-rules/skills//SKILL.md` there. Sync a configured host with `mix usage_rules.sync`. | | API tier and backend support | `priv/api-stability.exs` lists Stable modules and their member/option tiers; check module docs for Candidate modules (such as `ExAgent.Coordination.Flow`) and [Supported features and limits](status.md). | | Limits of the contract | [Known limits](known-limits.md) | **Stable** means strict SemVer. Public **Candidate** modules, functions, options and variants can change in a minor release. A stable module can contain candidate members. Confirm the installed version and tier before copying a call. #### API map Contract keys **Tools** and **Runtime** identify the two detailed contract pages: [Tools and models contracts](tools-and-models-contracts.md) and [Runtime and operations contracts](runtime-and-ops-contracts.md) (in the dependency: `docs/guides/llm/tools-and-models-contracts.md` and `docs/guides/llm/runtime-and-ops-contracts.md`). | Task | Stable | Candidate | Skill | Contract | |---|---|---|---|---| | Run once, stream or continue message history | `ExAgent.new/1`, `ExAgent.run/3`, `ExAgent.run_stream/3` | Per-call `:usage_limits` | `exagent-run-agent` | Runtime · [Getting started](getting-started.md) | | Call a tool, validate typed output, restrict effects | `Tool.new/1`, `Tools.deftool/3`, `Permissions.new!/1`, `output:`, `output_mode:` | Argument predicates, `Tool.CodeMode`, `Sandbox.tools/2` | `exagent-tools` | Tools · [Tools and output](tools-and-output.md) | | Attach host instructions or runtime skills | `instructions:`, `capabilities:`, `Skill.new/1`, `Skills.from_dir!/2` | Candidate capability integrations retain their tier | `exagent-tools` | Tools · [Skills](skills.md) | | Connect a model, fail over, manage quota and spend | `Model.resolve/2`, `Models.ReqLLM.new/1`, `Models.Fallback.new/1`, `UsageLimits`, `UsageLimits.Budget`, `RateLimiter` | `:spend_budget`, `Compaction`, `mix exagent.qualify` | `exagent-models` | Tools · [Models and limits](models-and-limits.md) | | Supervise chat, admit a turn, consume events | `Conversations`, `Server.chat/3`, `Server.send_message/3`, `Server.receipt/3`, `Chat.Reader`, `Server.attach/3`, `Server.events_since/3`, `Server.ack_events/4` | `Server.steer_run/3`, `:observability` | `exagent-server` | Runtime · [Runtime and events](runtime-and-events.md) | | Review, supply or resume a persisted run | `Continuation.pending/2`, `Continuation.decide/4`, `Continuation.supply_result/4`, `Server.resume/3`, `ExAgent.resume/3` | Input and timer deferral variants, delegated Frame3 pause paths | `exagent-store`, `exagent-server` | Runtime · [Durability and approvals](durability-and-approvals.md) | | Snapshot, restore, migrate, reconcile | `Store.ETS`, `Store.Postgres`, `Store.scoped/2`, `Store.namespace/1`, `Catalog.cast/1`, `Continuation.reconcile_tool/4`, `Migration.up/1`, `Migration.down/1` | `mix exagent.upgrade`, `Continuation.get/3` with `timeline: true` | `exagent-store` | Runtime · [Migration](migration.md) | | Background agents and tools | `Jobs.background/2`, `Jobs.agent_tool/1`, `Jobs.tools/2`, `c:ExAgent.Jobs.Durable.recovery/2` | `c:ExAgent.Jobs.Durable.definition/1`, `c:ExAgent.Jobs.Durable.delivery_queue/2` | `exagent-jobs` | Runtime · [Continuation jobs](continuation-jobs.md) | | Delegate, transfer or orchestrate multiple steps | `Coordination.delegation_tool/2`, `ExAgent.run_child/4` | `Handoff`, `Coordination.Composition`, `Coordination.Flow` | `exagent-coordination` | Runtime · [Coordination](coordination.md) | | Drive participants with shared state | `Session.take_turn/4`, `Session.chat/4`, `Session.SharedState`, `Session.StateCodec` | Model-directed `Handoff` for a supported Session | `exagent-session` | Runtime · [Coordination](coordination.md) | | Test model/tool behavior and replay cases | `Models.Test`, `Fixture`, `Eval.run/3`, `mix exagent.eval` | `Eval.Suite.capture/1`, `mix exagent.eval.capture` | `exagent-test` | Runtime · [Testing](testing.md) | | Import, serve or rebind MCP tools | `MCP.Client.tools/1`, `MCP.Client.call_tool/3`, `MCP.Server.handle/4` | `pinned:`, `on_drift:`, `connect_on_start:`, `tasks:`, input forms, protected resources | `exagent-mcp` | Tools · [MCP](mcp.md) | | Diagnose, trace, bound export and grade terminals | `Telemetry`, `Observability.OpenTelemetry`, `Observability.BoundedProcessor`, `Eval.Online`, `mix exagent.doctor` | `Observability.ReqLLM`, `:metrics`, `Eval.Online.Durable` | `exagent-observability` | Runtime · [Observability](observability.md) | | Read memory or integrate retrieval | `Memory.tool/2`, `Memory.preload/3` with a host store, or a host `Tool` | Additional per-call accounting and retrieval adapters | `exagent-tools`, `exagent-store` | Tools · [Memory](memory.md) · [External retrieval](external-retrieval.md) | #### Results, streams, events and errors | Boundary | Observable form | Caller action | |---|---|---| | Accepted run terminal | `{:ok, %ExAgent.Result{status: :succeeded, output: output}}` | Deliver the validated answer. | | Persisted pause | `{:ok, %ExAgent.Result{status: :paused, continuation: ref}}` | Store the reference and project pending review. A decision or deferred result supplies a new reference if ready. | | Execution failure | `{:error, %ExAgent.RunError{reason: reason, partial: partial}}` | Inspect confirmed progress. The partial status is `:failed` or `:cancelled`. `pending_response` is diagnostic and can contain incomplete provider content. | | Bang form | `ExAgent.run!/3` returns accepted output, or raises the `RunError` or `RunPaused` | Prefer tagged results where a pause is expected. | | Configuration | `ArgumentError` for invalid configuration at construction or public call admission | Fix the definition or options before dispatch. Check the boundary's documented returned errors for invalid operational input. | | Model adapter | `{:error, %ExAgent.RequestError{}}` at dispatch. In a run, usually `RunError.reason = {:model_request_failed, request_error}` | Inspect `provider`, `reason`, `status`, `transport` and `retry_after_ms` where populated. A confirmed incomplete terminal uses `{:incomplete_response, finish_reason}` as the run reason. The partial owns live model state. | | State checkpoint | `{:error, %ExAgent.CheckpointError{operation: op, reason: reason, result: outcome, revision: revision}}` | Keep the live owner and retry its save. An unconfirmed save may already have committed. | | OTP boundary | `:busy`, `:continuation_pending`, `:checkpoint_pending`, `:unavailable`, `{:delivery_unconfirmed, request_id}` or `:result_unconfirmed`, inside `{:error, ...}` | Identify the original operation and classify confirmed refusal versus missing acknowledgement. Query its receipt, journal or correlated events. | | One-shot stream | `{type, data}`, optional `{:child, lineage, element}` with `child_events: :all`, then one `{:result, result}` or `{:error, %ExAgent.RunError{}}` when fully consumed | Enumerate once with a catch-all. Close a suspended continuation on disconnect. Deltas and `:output_partial` are drafts. | | Server/Session subscription | PubSub messages `{:exagent_event, %ExAgent.Event{version: 2, source: source, type: type, payload: payload}}`. Server demand delivery uses `{:exagent_events_ready, server_pid, notice}`. | Match owner and namespace, then run and request IDs. Apply a batch before ACK. Keep the cursor opaque. Rebuild from an authorized history page on expiry. | | Stream element | Data keys | |---|---| | `:run_started` | `run_id`, `root_run_id`, `parent_run_id`, `attempt_id` | | `:run_step_started` / `:run_step_finished` | `step`, plus `outcome` on finish (`:continued`, `:retry`, `:succeeded`, `:paused` or `:failed`) | | `:text_delta`, `:commentary_delta`, `:thinking_delta` | `step`, `text`. Guarded text or commentary can carry `stream_checked?: true`. | | `:tool_call_delta` / `:output_partial` | `step` and `index`, `tool`, `fragment` with `tool_call_deltas: true`, or `step` and draft `output` | | `:model_response` | `step`, accepted `response` | | `:tool_call_started` / `:tool_call_finished` | `step`, `tool`, `call_ref`. Start carries `call` and `args_source`. Finish carries `return`, `duration_ms` and `duration_measured`. | | `:tool_data` | `step`, `call_ref`, `tool`, `part_id`, `name`, `data`, `transient` | | `:approval_requested` | `continuation`, `pending` | | `:guardrail_tripped` | `step`, `name`, `stage` | | `:run_handoff`, `:context_compacted`, `:steering_applied` | Candidate integrations can add progress events. Use the catch-all for consumers that do not implement them. | Event v2 adds `id`, `emitter_id`, `seq`, `occurred_at`, scoped runtime IDs, run lineage and JSON `payload`/`metadata`. `seq` is local to an emitter. Run terminals delivered this way are `:run_finished`, `:run_paused` and `:run_failed`. They include `payload.persistence`. On `:server_request_cancelled`, read `payload.status` (`:cancelled_before_start`, `:cancelled` or `:uncertain`) and the persistence state before offering it to Eval. Reconcile an uncertain cancellation. #### Preserve these contracts - **Durability.** A snapshot restores state. A C7 journal fences admitted effects and binds exact revisions. ETS survives owner replacement within the VM. Use PostgreSQL with a pinned unified migration when the VM must restart. Commit a save before treating its state transition as acknowledged. - **Reconciliation.** An external write can succeed while its receipt is lost. Read the authorized journal. Use a declared read-only reconciler or explicit evidence before another effect is admitted. An authorized retry binds the exact stored intent. A confirmed result is replayed as data. - **Mandatory tool argument envelope.** Stock ReqLLM wire calls carry a unique `"arguments"` object field. Invalid envelopes block the entire batch. Correct complete object shapes only within the allowed budget. Reject incomplete, unparseable or non-object payloads and stock argument errors. Duplicate-key rejection needs the original JSON from the adapter. Persist and replay accepted history with the per-call codec intact. - **Authority.** Host auth supplies namespace, actor and policy. Use a versioned catalogue, Store scope and matching topic. Children inherit ancestor budgets and permissions. A Session state codec is selected by the host on every start. - **Accounting.** Requests and tool dispatches are host counts. Provider token dimensions and cost carry their coverage/quality. Parent totals include descendants once. Preserve unknown separately from measured zero. - **Observability.** Events can carry content within the host. Apply `Event.strip_content/1` before export. Telemetry and OTel omit content by default. Bound queue, batch, exporter wait and retries. The host owns SDK and exporter lifetime. Spans and exporter callbacks are operational evidence. #### Common anti-patterns | Error | Correct call or handling | |---|---| | `Tool.new(callable: fn args -> ... end)` | Use `call: fn %{"sku" => sku} -> ... end` with `takes_ctx: false` and an object schema. Pure tools declare `effect: :read`. | | Match `{:ok, result}` and publish output unconditionally | Match `%ExAgent.Result{status: :succeeded}`. Route `:paused` to the approval/deferral workflow. | | Resume the original pause after approval | Match `{:ok, %{continuation: ref}}` from the confirmed current decision. Resume only when `ref` is actionable and use it unchanged. | | Retry a failed/uncertain write, lost admission or lost checkpoint | Reconcile the journal, read the original admission key, or retry the save at the affected boundary. | | Use one TestModel item for a tool followed by typed output | Script the tool response and a second `final_result` tool call in `:tool` mode. | | Hard-code API struct internals or infer provider support from a name | Use public constructors and accessors. Read the model's profile and qualify the exact backend and mode separately. | | Infer completion from a draft, admitted receipt or a repaired subscription | Match a confirmed terminal. Rebuild the UI from its authorized history projection when a cursor expires. | | Trust a prompt or a persisted config map to grant access | Derive scope, actor and definition from the host. Use the saved reference to select exact trusted bindings. | #### Verify the relevant boundary - Script the public sequence offline with `%ExAgent.Models.Test{}`. Assert terminal status, matched tool returns and host side effects. - In persistence tests, assert exact revision, committed receipt and behavior after duplicate delivery, owner replacement or lost ACK. - Check the application's installed API tier and run its tests. Real-provider and backend qualification require explicit opt-in and separate evidence. - When upgrading, use the [Migration guide](migration.md). --- ## Usage rules ### Using ExAgent in an application #### Dependency resolution From the consuming Mix project run `mix run --no-start -e 'IO.puts(Path.expand(Map.fetch!(Mix.Project.deps_paths(), :exagent)))'`. Resolve all package paths below from that directory. For a host configured with UsageRules, run `mix usage_rules.sync` after changing the dependency version. Start with `docs/guides/agents.md`. Check `priv/api-stability.exs` and the installed module docs before using a member, option, field, variant or Mix switch. #### Skill router | Task | Load `usage-rules/skills//SKILL.md` | |---|---| | One-shot execution, result handling, lazy stream | `exagent-run-agent` | | Tool schema and callback, permissions, typed output | `exagent-tools` | | Cloud or local models, retries, quotas, spend and context | `exagent-models` | | Stateful chat, admission, demand events, approval UI | `exagent-server` | | Background work, notices, Oban recovery | `exagent-jobs` | | Store, migrations, persisted continuations, dirty saves | `exagent-store` | | Delegated agent, scoped child, handoff, durable workflow | `exagent-coordination` | | Participant turns, shared state, state codec | `exagent-session` | | TestModel, ExUnit, Eval fixtures, replay | `exagent-test` | | MCP clients, tools, protocol, durable identity | `exagent-mcp` | | Telemetry, OpenTelemetry, bounded export, online Eval | `exagent-observability` | #### Hard API contracts and return shapes | Call | Contract | |---|---| | `ExAgent.new/1` | Keyword configuration → agent struct. Invalid definitions and impossible profile combinations raise `ArgumentError` before IO. | | `ExAgent.run/3` | `{:ok, %ExAgent.Result{status: :succeeded, output: output}}`, `{:ok, %ExAgent.Result{status: :paused, continuation: ref}}`, or `{:error, %ExAgent.RunError{reason: reason, partial: partial}}` after valid configuration. | | `ExAgent.run!/3` | Returns accepted output. Raises the run error or `ExAgent.RunPaused`. | | `ExAgent.run_stream/3` | Lazy enumerable. Consume once. Deltas and drafts are provisional. Full consumption ends with one `{:result, result}` or `{:error, error}`. Pass along unknown element types with a catch-all. | | `ExAgent.Server.chat/3`, `ExAgent.Server.resume/3` | `{:ok, result}` or `{:error, reason}`. An error may be a boundary reason, a run error or `%ExAgent.CheckpointError{}`. `:result_unconfirmed` requires a read of the original operation. | | `ExAgent.Server.send_message/3`, `ExAgent.Server.receipt/3` | `{:ok, receipt}` or `{:error, reason}`. Keep the admission key, run ID and request ID. `{:delivery_unconfirmed, request_id}` means lookup the same key and correlate the original request. Admission can precede dispatch. | | `ExAgent.Server.attach/3`, `ExAgent.Server.events_since/3`, `ExAgent.Server.ack_events/4` | Attach with `delivery: :demand` before taking the history page. Read `{:ok, %{items: events, cursor: cursor}}` with the notice. Apply the batch before acknowledging that notice and cursor. | | `ExAgent.Continuation.get/2`, `ExAgent.Continuation.pending/2` | `{:ok, details}` or `{:ok, items}` respectively, or `{:error, reason}`. `ExAgent.Continuation.get(store, id, diagnostics: true)` can include the stored body. | | `ExAgent.Continuation.decide/4`, `ExAgent.Server.decide/4`, `ExAgent.Continuation.supply_result/4` | `{:ok, reply}` or `{:error, reason}`. The reply has `:revision`, `:status`, `:pending`, `:replayed` and `:continuation`. An actionable decision or supply returns a new exact reference. Nil means this reply grants no resume. | | `ExAgent.resume/3` | `ExAgent.resume(agent_or_catalog, ref, continuation: config)` returns the same result shape as a run. Bind the trusted definition, policy and model to the authorized Store and revision. | | `ExAgent.Store.scoped/2`, `ExAgent.Store.namespace/1` | Scope the backend with a host-owned nonempty UTF-8 namespace. Read the namespace from the opaque scoped value. A nil namespace uses legacy unscoped keys. | | `ExAgent.Catalog.new/1`, `ExAgent.Catalog.cast/1`, `ExAgent.Catalog.resolve/2` | Build from versioned host entries. Cast returns `{:ok, catalog}` or `:error`. Resolve a saved identity to `{:ok, entry}` or `{:error, reason}`. | | `ExAgent.Migration.up/1`, `ExAgent.Migration.down/1` | In a host Ecto migration, pin `version: 1` up and `version: 0` down for a fresh or 2.x install. Both return `:ok` when queued in the migration. | #### Common LLM traps | DO | DO NOT | |---|---| | Use `Tool.new/1` with `call:`. Set `takes_ctx: false` for `fn args -> ... end`. Match JSON string keys. Declare `effect: :read` for pure reads or calculations. | Use `callable:`, assume atom keys, use unary callbacks with the default context, or assume tools default to read. The default is `effect: :write`. | | Deliver `result.output` only after matching `status: :succeeded`. Persist a paused reference as pending work. | Treat every `{:ok, result}` or stream draft as a delivered answer. | | Queue the exact `:continuation` from the confirmed decision or result-supply reply. Replaying the same command can recover its receipt. | Resume with the replaced pause reference, synthesize a reference from three keys, or upgrade a delayed job to the latest revision. | | Inspect the run error's `:partial` and authorized effect journal after failure. On `:execution_uncertain` or an `:unknown` write, reconcile via a declared read-only lookup such as `Continuation.reconcile_tool/4`. | Resubmit a write on timeout, restart, worker failure, cancellation or a lost acknowledgement. | | Retry the save via `Server.checkpoint/1` or `Session.checkpoint/1` when the owner is dirty. | Replay the prompt, tool or state callback to obtain an acknowledged save. | | Script one response for every model request in `%ExAgent.Models.Test{script: [...]}`. Include the turn after a tool and the final output-tool call (usually `final_result`) with typed `:tool` output. | Script only the first tool call or send final text for a required output tool. The script cannot supply an extra turn after exhaustion. | | Send stock ReqLLM wire tool arguments as a one-field object `{"arguments": {...}}`. Empty arguments use `{"arguments": {}}`. For logical `ToolCall` args and Elixir callbacks, use the inner map. | Dispatch any sibling of a rejected batch, guess missing JSON, or wrap an already decoded TestModel call. | | Use `ollama:`, `vllm:` or `lmstudio:` for local `:chat_tools_v1` routes with plain thinking and `:tool`/`:prompted` output (use `vllm:` + `base_url:` for llama.cpp). | Assume local `:chat_tools_v1` supports `:native` structured output or replays plain thinking in history. | | On any stock ReqLLM route (live or Frame 3), complete JSON objects with unique keys and no stock argument error auto-retry envelope shape mismatches — spending `max_retries` per distinct function tool or `output_retries` once for a batch with an output tool. | Retry truncation, non-object or unparseable JSON, stock argument errors, observable duplicate keys, zero/exhausted budgets, or malformed envelopes in Frame 10/11. Some stock routes normalize duplicates before ExAgent can see them. | | Derive namespace, actor, tool permissions and versioned bindings from authenticated host state. Apply ancestor limits to children. Use explicit allowlists via `Permissions.new!/1`. | Accept actor, scope, authority or a callable supplied by prompt, deferral, receipt or restored data. | | Keep exact dispatch counters, qualified token/cost fields and lower-bound subtotals distinct. Use the content-free event/Telemetry projections at external boundaries. | Turn missing usage into zero or serialize live results, tools and model structs for logs. | #### Durable operations - Preserve the exact version 1 continuation reference, including `:version`, `:id`, `:record_id`, `:revision`, `:run_id` and any `:attempt_id`. To restore a legacy three-key reference, look up its authorized revision and verify the originating decision before scheduling delivery. - Give each scope its own Jobs owner. Bind `Jobs.tools/2` to that owner. Route volatile job notices to the authorized `Conversations.via/2` address. Use `job_status` on the same scope to read the result. - Use stable `Catalog` bindings with `Continuation.census/2` and `Continuation.adopt/4` when replacing an in-use definition version. Reconcile uncertain effects first. Bind the original admission key when reopening an owner after unconfirmed `Conversations.stop/3`. - For PostgreSQL, `mix exagent.upgrade --yes` (candidate) generates the pinned host migration. Review, then apply with `mix ecto.migrate`. Unified version 1 includes C7 run headers, keyed turn receipts, segmented snapshots, the pending timer index, Budget attribution and thresholds, and scheduled follow-ups. Rebuild and verify run headers on each enrolled table with 2.x C7 journals before enabling writers or Recovery. Opt into fragmented writes with `segments: true`. Retain the per-adapter helpers for historical migrations. - Offer confirmed terminals to `Eval.Online`. For C7, bind the authorized source Store. For durable grading, bind the effective evaluator version with `Eval.Online.Durable` (candidate). Treat a confirmed cancellation and an uncertain cancellation as different evidence. --- ## Skills ### Skill: `exagent-coordination` > Use this skill when an ExAgent 3.0 agent calls a specialist, runs a scoped child from a tool, transfers the answer, or orchestrates durable serial, routed, parallel or manifest-based work. #### Coordinate agent executions ##### When to use | Need | Entry | |---|---| | Parent tool call gets a specialist's output and continues | `Coordination.delegation_tool/2` | | Host-written callable needs a scoped sub-run | `ExAgent.run_child/4` with the live parent context | | Model selects who answers the current turn | `Handoff.new/1` (candidate) and agent `:handoffs` (candidate) | | Host-owned versioned fail-fast sequence | `Coordination.Composition` (candidate) | | Host selector, bounded parallelism, or repeated template | `Coordination.Flow` (candidate) | | Shared participant state or detached work | Load `exagent-session` or `exagent-jobs` | ##### Exact APIs - `Coordination.delegation_tool(delegate, opts)` returns a tool. The delegate is an agent or a two-argument builder `fn ctx, args -> agent end`. Set `name:` and optionally `prompt_arg:` (default `"prompt"`). - `ExAgent.run_child(ctx, child, prompt, opts)` returns the standard run result or error with the parent's live execution scope. - `Handoff.new(id: "claims", description: description, agent: specialist)` (candidate) generates `transfer_to_claims` via `:handoffs` (candidate). Its optional `note` is model data. The last target is `result.handoff_target`. - `Coordination.Composition.new(id: id, version: version, steps: steps)` (candidate) declares a sequence. Each step needs `:id`, `:agent`, `:definition`, `:policy`, `:model_ref`, `:output_ref` and `:model_codec`. - `Coordination.Flow.new/1` (candidate) accepts `kind: :router`, `:parallel` or `:map`. Router takes `select:`/`select_version:` and `steps:`. Parallel takes `steps:`. Map takes `template:` and a manifest of unique string IDs with JSON inputs. Version a custom `merge:` with `merge_version:`. - `Coordination.Composition.run/3` (candidate) and `Coordination.Flow.run/3` (candidate) take the definition, input and `continuation: config`. Their `Coordination.Composition.resume/3` (candidate) and `Coordination.Flow.resume/3` (candidate) take the same definition, the exact reference and opts with the continuation configuration. Handle `{:ok, result}` with `Coordination.Result` (candidate) or `{:error, %ExAgent.RunError{}}`. ##### Canonical complete snippet ```elixir alias ExAgent.{Coordination, Message, Models.Test, Result} alias ExAgent.Message.Part.{ToolCall, ToolReturn} specialist = ExAgent.new(model: %Test{script: ["Send the replacement to the original address."]}) consult = Coordination.delegation_tool(specialist, name: "resolve_delivery") call = %ToolCall{ tool_name: "resolve_delivery", tool_call_id: "delivery-1", args: %{"prompt" => "Which address should receive the replacement?"} } controller = ExAgent.new( model: %Test{script: [{:tool_calls, [call]}, "Use the original address."]}, tools: [consult] ) {:ok, %Result{status: :succeeded, output: "Use the original address.", request_count: 3} = result} = ExAgent.run(controller, "Resolve the delivery issue.", []) true = Enum.any?(Message.parts(result.new_messages), fn %ToolReturn{tool_call_id: "delivery-1", status: :succeeded} -> true _ -> false end) ``` ##### Hard invariants & pitfalls - Use the live context for child work. Every ancestor constrains authority, limits and deadlines. Parent usage includes child usage once. - Transfer preserves root IDs and the remaining limits, and the chosen specialist supplies the answer. Competing transfers fail before batch IO with `:multiple_handoffs`. The transfer view is bounded and drops opaque reasoning by default. Attachment sharing requires explicit grants and a capable destination. - Durable workflows store a portable binding and confirmed steps. Rebuild the same trusted versioned code, codec, policies and mappings. Resume a matching ready revision; reconcile unknown effects before dispatch. - Flow `:collect` keeps confirmed failed branches in ordered outcomes. `:fail_fast` stops new admissions. Inspect `error_phase`/`error_step_id` on workflow failure. Reported checkpoint failure can retain a save-only token. ##### Verify Test parent and child call counts, denied authority, and the confirmed tool receipt offline. For handoff and workflow fixtures, use `docs/guides/coordination.md` and `examples/coordination_workflows.exs`. --- ### Skill: `exagent-jobs` > Use this skill when running a long tool or background agent in ExAgent 3.0, retrieving a job result, routing completion notices, or choosing a durable job with Oban and continuation recovery. #### Run a background agent ##### When to use | Need | Boundary | |---|---| | Bounded work that may disappear with the owner | Supervised `ExAgent.Jobs` per authorized scope | | Queue delivery and persisted approvals across VM restarts | `ExAgent.Jobs.Durable` with a trusted Store and host queue | | Inline child whose work counts in the parent's scope | Load `exagent-coordination` | ##### Exact APIs - `Jobs.start_link/1` starts a volatile owner. `Jobs.start/4` returns `{:ok, job}` on admission or `{:error, reason}`. A lost reply can carry `{:delivery_unconfirmed, id}`. - `Jobs.background/2` wraps an eligible local function tool. `Jobs.agent_tool/1` takes `jobs:`, `name:`, `description:` and `agent:`. Provide `run_opts:` as a keyword list or a function from context to keyword options. - `Jobs.tools/2` returns the same owner's `job_status`, `wait_job` and `cancel_job` tools. Model tool wait uses seconds (`max_wait_seconds:`). - `Jobs.status/2` and `Jobs.wait/3` return `{:ok, job}` or `{:error, reason}`. Host waits use milliseconds and may return while the job is still running. - `Jobs.notify_server/2` routes a finished volatile job to an authorized `Conversations.via/2` address. For Oban Lifeline recovery, implement the optional `c:ExAgent.Jobs.Durable.recovery/2` callback on the host worker. ##### Canonical complete snippet ```elixir alias ExAgent.{Jobs, Message, Models.Test, Result} alias ExAgent.Message.Part.{ToolCall, ToolReturn} {:ok, jobs} = Jobs.start_link([]) worker = ExAgent.new(model: %Test{script: ["The delivery was rescheduled."]}) summarize = Jobs.agent_tool( name: "summarize", description: "Summarize a delivery note in the background.", jobs: jobs, agent: worker ) call = %ToolCall{ tool_name: "summarize", tool_call_id: "summary-1", args: %{"prompt" => "Summarize the updated delivery note."} } agent = ExAgent.new( model: %Test{script: [{:tool_calls, [call]}, "Summary requested."]}, tools: [summarize | Jobs.tools(jobs, max_wait_seconds: 5)] ) {:ok, %Result{status: :succeeded} = result} = ExAgent.run(agent, "Summarize this note.") %ToolReturn{content: %{"job_id" => id}} = Enum.find(Message.parts(result.new_messages), &match?(%ToolReturn{status: :succeeded}, &1)) {:ok, %{status: :succeeded, result: "The delivery was rescheduled."}} = Jobs.wait(jobs, id, 5_000) :ok = GenServer.stop(jobs) ``` ##### Hard invariants & pitfalls - Admission, completion and notice delivery are separate. Fetch the result from the original scope. A notice identifies a job and status. - After an unconfirmed start, read the original job ID and reconcile before resubmitting. A wait timeout says nothing about completion or cancellation. - A volatile agent tool's pause becomes a failed job. Review and resume its stored continuation through the host. Its model usage is separate from the parent. Use durable Jobs for restart-safe ownership. - Bind recovery to the saved version and exact ready reference. Host retries can repeat queue delivery. Reconcile uncertain external effects before retrying work. ##### Verify Assert the worker's output from the owner and scope isolation. Exercise duplicate delivery and recovery in the durable path. Read `docs/guides/runtime-and-events.md` and `docs/guides/recipes/continuation-jobs.md`. --- ### Skill: `exagent-mcp` > Use this skill when importing or publishing an ExAgent 3.0 MCP tool over stdio or HTTP, negotiating a session, validating structuredContent, or binding a remote write to a persisted continuation. #### Connect or publish MCP tools ##### When to use | Need | Entry | |---|---| | Discover remote tools for an agent | `MCP.Client.tools/1` | | Serve host tools with JSON-RPC | `MCP.Server.handle/4` or host HTTP with `MCP.Server.Plug` | | Pin a remote tool catalogue | `MCP.Client.snapshot/1` (candidate) and `:pinned` (candidate) | ##### Exact APIs | Client constructor (`MCP.Client.start_link/1`) | Required options | Revision pin location | |---|---|---| | Stdio | `command:` (plus optional `args:`, `env:`, `cd:`) | Inside `continuation_binding: %{..., protocol_version: "2025-06-18"}` (no top-level `:protocol_version`). | | Streamable HTTP (Finch) | `transport: :streamable_http`, `url:`, `finch:` (HTTP/1.1-only pool) | Top-level `protocol_version:` (default probes `2026-07-28`, falls back to legacy). | | Streamable HTTP (dynamic auth) | `transport: :streamable_http`, `url:`, `headers_provider:` (Mint; omit `:finch` and `:headers`) | Top-level `protocol_version:`. | - `MCP.Client.tools/1` returns `{:ok, tools}` or `{:error, reason}`. Close with `MCP.Client.close/1`. Invalid options raise `ArgumentError`; startup failures return `{:error, reason}`. - `MCP.Client.call_tool/3` returns `{:ok, text}`, `{:content, parts}`, `{:tool_error, message}` or `{:error, reason}`. Imported tools can instead yield a validated map when the declared output schema is an object. - `MCP.Server.start_link/1` requires `tools:`. `MCP.Server.handle/4` takes owner, session ID (nil for initialize), decoded message and host actor. It returns `{:ok, session_id, response_or_nil}` or `{:error, reason}`. ##### Canonical complete snippet ```elixir alias ExAgent.MCP.Server alias ExAgent.Tool schema = %{ "type" => "object", "properties" => %{"text" => %{"type" => "string"}}, "required" => ["text"], "additionalProperties" => false } echo = Tool.new( name: "echo", description: "Return the supplied text.", parameters_json_schema: schema, result_schema: schema, effect: :read, takes_ctx: false, call: fn %{"text" => text} -> %{"text" => text} end ) {:ok, server} = Server.start_link(tools: [echo]) actor = "test-reader" request = fn id, method, params -> %{"jsonrpc" => "2.0", "id" => id, "method" => method, "params" => params} end init = request.(1, "initialize", %{ "protocolVersion" => "2025-06-18", "clientInfo" => %{"name" => "offline-test", "version" => "1"}, "capabilities" => %{} }) {:ok, sid, %{"result" => %{"protocolVersion" => "2025-06-18"}}} = Server.handle(server, nil, init, actor) notice = %{"jsonrpc" => "2.0", "method" => "notifications/initialized"} {:ok, ^sid, nil} = Server.handle(server, sid, notice, actor) list = request.(2, "tools/list", %{}) {:ok, ^sid, %{"result" => %{"tools" => [%{"name" => "echo", "outputSchema" => ^schema}]}}} = Server.handle(server, sid, list, actor) call = request.(3, "tools/call", %{"name" => "echo", "arguments" => %{"text" => "ready"}}) {:ok, ^sid, %{"result" => %{"structuredContent" => %{"text" => "ready"}}}} = Server.handle(server, sid, call, actor) :ok = Server.close(server, sid, actor) :ok = GenServer.stop(server) ``` ##### Hard invariants & pitfalls - Authenticate the actor in the host and keep it fixed for the session. Put `MCP.Server.Plug` before body parsing. Enforce origins and catalogue scope. - A pinned client verifies peer declarations before tool use and after restart. Set `continuation_binding:` with the trusted endpoint and principal versioned references. Preserve those bindings and the lock on resume. Apply local approval to imported writes. - For a deferred MCP input form (candidate), project the authorized pending item with `Chat.InputForm.present/2` and pass the response through the host. - A complete but invalid structured result is a confirmed `:tool_error`. Loss after dispatch means the outcome may be unknown. Reconcile before retrying. A cancellation acknowledgement alone does not settle the effect. - Match remote result parts by call ID and status. Treat remote descriptions, arguments and returned data as untrusted. ##### Verify Run initialize, initialized, list and call offline. Assert the advertised schema, rejection of invalid arguments and isolation of another actor. Read `docs/guides/mcp.md` and `docs/guides/recipes/mcp-continuation-binding.md`. --- ### Skill: `exagent-models` > Use this skill when selecting an ExAgent 3.0 cloud or local model, connecting stock ReqLLM, diagnosing tool argument rejections, or configuring fallback, quotas, spend budgets and context handling. #### Select models and bound their use ##### When to use | Need | Entry | |---|---| | Catalogue provider and model | `"provider:id"` as `model:`, or `Model.resolve/2` | | Local OpenAI-compatible tool endpoint | `ollama:`, `vllm:`, or `lmstudio:` with the deployed ID | | Instance credentials or a custom endpoint | `Models.ReqLLM.new/1` | | Retry a transient failure or choose a backup | `Models.Fallback.new/1` | | Bound one execution, a shared quota, or a spend account | `UsageLimits`, `RateLimiter`, or `UsageLimits.Budget` respectively | | Reduce request context | `Compaction.capability/2` (candidate) | ##### Exact APIs - `Model.resolve(spec, opts)` returns `{:ok, model}` or `{:error, reason}`. Use `Model.profile/1` to read the model's declared capabilities. - `Models.ReqLLM.new(model: spec, base_url: url, api_key: key)` returns the stock adapter configuration. For uncatalogued protocols, pass an explicit model spec with a wire surface/capabilities or a matching profile. - `Models.Fallback.new(models: models, max_retries: retries)` accepts a list of resolved model instances. `Models.Fallback.codec/1` binds resumable state to the configured leaf codecs. - Pass `%UsageLimits{}` as `usage_limits:` at agent construction. The `:usage_limits` call override is candidate. Pass `rate_limiter:` with a supervised `RateLimiter.start_link/1` owner. - `UsageLimits.Budget.new(adapter: adapter, reservation_cents: cents)` returns a budget handle. Attach through `:spend_budget` (candidate). Read `UsageLimits.Budget.balance/2` and settle authorized verified billing with `UsageLimits.Budget.reconcile/3`. - `Compaction.capability(compactor, opts)` (candidate) returns an agent capability for `capabilities:`. Preserve signed prefix and tool pairing. ##### Canonical complete snippet ```elixir alias ExAgent.{Model, Models.Fallback, Models.Test, RateLimiter, Result, UsageLimits} {:ok, primary} = Model.resolve("test:Order 94 is packed.", []) backup = %Test{label: "Use backup order data."} model = Fallback.new(models: [primary, backup], max_retries: 0) {:ok, quota} = RateLimiter.start_link( name: Example.ModelQuota, limits: %{"test" => [rpm: 30, tpm: 30_000, concurrency: 2]} ) agent = ExAgent.new( model: model, rate_limiter: quota, usage_limits: %UsageLimits{request_limit: 2}, model_settings: [max_tokens: 128] ) {:ok, %Result{status: :succeeded, output: "Order 94 is packed.", request_count: 1}} = ExAgent.run(agent, "What is the status of order 94?") :ok = GenServer.stop(quota) ``` ##### Hard invariants & pitfalls - Use stock ReqLLM. Catalogue configuration resolves without provider IO. Provider keys resolve through host config/environment or explicit instance credentials. Keep keys out of persisted bindings and logs. - Local routes use `:chat_tools_v1` and admit unlisted IDs with tools unless catalogue metadata opts out. They support plain thinking and `:tool` or `:prompted` output. Plain thinking is omitted when sending history. Ollama normally needs no key. LM Studio and vLLM use `LMSTUDIO_API_KEY` and `OPENAI_API_KEY` respectively unless supplied explicitly. - Require `{"arguments": {...}}` before tool admission. A recoverable complete object with unique keys and no stock argument error consumes `max_retries` per function tool name or one `output_retries` for a batch with an output tool. Truncated, unparseable or non-object JSON, observable duplicates, exhausted budgets and malformed envelopes in Frame 10/11 fail at the request boundary. Stock paths can normalize duplicates before ExAgent sees them. - Fallback preflights every leaf. Default transient status retries apply before streaming data (a usage event commits the stream). Transport retry requires `retry_transport: true` and can incur another charge. - Quota estimate/reservation, confirmed request counts and qualified actual usage are separate. Partial reports can leave a quota or spend hold in place. Unknown cost requires reconciliation, including before settling zero. ##### Verify Run `mix exagent.doctor --model PROVIDER:ID` for offline configuration. `mix exagent.doctor --base-url URL` (candidate) is available for explicit endpoints. Use `mix exagent.qualify --model PROVIDER:ID` (candidate) only for authorized acceptance of the deployed tool/stream/output combination. Read `docs/guides/models-and-limits.md` and the tools/model contract page. --- ### Skill: `exagent-observability` > Use this skill when instrumenting ExAgent 3.0, correlating Telemetry and OpenTelemetry traces, bounding exporters, combining ReqLLM traces, or evaluating confirmed production terminals. #### Observe and evaluate confirmed execution ##### When to use | Need | Entry | |---|---| | Local operational measurements | `Telemetry` event catalogue and `:telemetry.attach/4` | | Traces and context propagation | `Observability.OpenTelemetry` plus host-owned SDK | | Bounded export and loss counters | `Observability.BoundedProcessor` | | Shared tracing with standalone ReqLLM | `Observability.ReqLLM` (candidate) | | Sample a confirmed terminal | `Eval.Online` | | Durable grading Jobs | `Eval.Online.Durable` (candidate) | ##### Exact APIs - Subscribe to `[:exagent, :run, :stop]` for successful or paused attempts, and `[:exagent, :run, :exception]` for failures. Correlate run/root/parent IDs and attempt ID. Timings from Telemetry use native time units. - `Observability.OpenTelemetry.new/1` returns instrumentation configuration. Pass `observability:` (candidate) to the agent, run or Server. Use `Observability.OpenTelemetry.capture_context/0` and `Observability.OpenTelemetry.with_context/2` across owned workers. - Configure `Observability.BoundedProcessor` as the SDK processor. `Observability.BoundedProcessor.stats/1` reads a snapshot or `{:error, :unavailable}`. `Observability.BoundedProcessor.force_flush/1` requests async export. `Observability.BoundedProcessor.shutdown/2` discards pending work and returns final stats or a boundary error. - `Observability.ReqLLM.attach/1` (candidate) registers the integrated handler. Run it once after SDK setup. Use `Observability.ReqLLM.Maintenance` (candidate) or `Observability.ReqLLM.prune_stale_spans/1` (candidate) for tracking cleanup. - `Eval.Online.handle/1` returns the queue handle. `Eval.Online.offer/3` returns `{:ok, :enqueued | :not_sampled | :duplicate}` or `{:error, reason}`. Use `:grading_backend` (candidate) and `Eval.Online.Durable.resolve/5` (candidate) with matching evaluator version, policy and grading limits. ##### Canonical complete snippet The host can start its SDK separately. This fixture asserts the local run event without a network exporter. **Candidate API.** The example uses the agent's instrumentation option. ```elixir alias ExAgent.{Models.Test, Observability.OpenTelemetry, Result} defmodule Example.RunObserver do def handle(_event, measurements, metadata, owner) do send(owner, {:observed_run, measurements, metadata}) end end handler = "example-exagent-run-stop" event = [:exagent, :run, :stop] :ok = :telemetry.attach(handler, event, &Example.RunObserver.handle/4, self()) try do agent = ExAgent.new( model: %Test{script: ["Ready."]}, observability: OpenTelemetry.new() ) {:ok, %Result{run_id: run_id, status: :succeeded, output: "Ready."}} = ExAgent.run(agent, "Check readiness.") receive do {:observed_run, %{duration: duration}, %{run_id: ^run_id, status: :succeeded}} when is_integer(duration) -> :ok after 1_000 -> raise "run stop event missing" end after :ok = :telemetry.detach(handler) end ``` ##### Hard invariants & pitfalls - Metadata is the default. Enable trace content only with explicit bounds and a redactor. Own ReqLLM logs, sampling and exporter settings in the host. - Run, logical model request and dispatched attempt have different scopes. Preserve usage quality and omit unknown measurements. The `:metrics` option (candidate) requires experimental OTel API/SDK 0.6, bounded allowlists and a host-owned reader. - For mixed ReqLLM calls, use one bridge. It enriches existing model spans. Use a maintenance TTL longer than every permitted live request. A default tracer resolves the active SDK; rebind any explicit tracer on replacement. - The processor bounds slots, batches and workers and sheds on saturation. Flush, enqueue and successful callback are distinct from durable transport acceptance. A finite restart budget applies per instance. - Offer confirmed terminals to online grading. For C7, bind the authorized source Store and an exact revision. Unconfirmed cancellations and pauses are not grading inputs. ##### Verify Run `mix exagent.doctor` for host checks. Test metadata and privacy with a local sink. Check exporter saturation and loss separately from event emission. Read `docs/guides/observability.md` and `docs/guides/testing.md`. --- ### Skill: `exagent-run-agent` > Use this skill when building or debugging an ExAgent 3.0 one-shot agent, validating the result or consuming a lazy stream in an Elixir application. Covers model state, prompt admission, output, pauses and operational errors. #### Run an ExAgent agent ##### When to use | Need | Entry | |---|---| | One request lifecycle | `ExAgent.run/3` | | Progressive response or cancellation on disconnect | `ExAgent.run_stream/3` | | Restore an approved revision | `ExAgent.resume/3` or `ExAgent.resume_stream/3` | | Authoritative conversation owner | Load `exagent-server` | | Provider or credential selection | Load `exagent-models` | ##### Exact APIs - `ExAgent.new/1` takes keyword options. Set `model:` and optionally `instructions:`, `tools:`, `output:` or `model_settings:`. Invalid configuration raises `ArgumentError` before IO. Merge overlays with `Keyword.merge/2`. - `ExAgent.run(agent, prompt, opts)` accepts text or a supported list of user parts. It returns `{:ok, %ExAgent.Result{}}` or `{:error, %ExAgent.RunError{}}`. - `ExAgent.run!/3` returns the accepted output or raises `ExAgent.RunError` or `ExAgent.RunPaused`. - `ExAgent.resume(agent_or_catalog, ref, continuation: config)` accepts the exact authorized reference from the decision, supply or recovery reply. - For a one-shot follow-up, thread `%{agent | model: result.model}` and pass `message_history: result.messages` after a successful turn. ##### Canonical complete snippet ```elixir alias ExAgent.{Models.Test, Result, RunError} agent = ExAgent.new( model: %Test{script: ["Order 94 is packed.", "It ships today."]}, instructions: "Give the verified order status in one sentence.", model_settings: [max_tokens: 128, temperature: 0.0] ) {:ok, %Result{status: :succeeded, output: "Order 94 is packed."} = first} = ExAgent.run(agent, "What is the status of order 94?", []) next = ExAgent.run_stream(%{agent | model: first.model}, "When will it ship?", message_history: first.messages ) Enum.reduce(next, nil, fn {:result, %Result{status: :succeeded, output: output}}, _ -> {:answer, output} {:result, %Result{status: :paused, continuation: ref}}, _ -> {:pending, ref} {:error, %RunError{reason: reason, partial: partial}}, _ -> {:failed, reason, partial} _event, outcome -> outcome end) ``` Expected terminal is `{:answer, "It ships today."}`. The error branch is an in-process value. Project it before external logging or delivery. ##### Hard invariants & pitfalls - Deliver only `:succeeded` output. Preserve `:paused` as work awaiting host action. Reconcile unknown effects before submitting a new write. - Constructing a stream is lazy. Enumerate once. Deltas and `:output_partial` are provisional. Cancel or close suspended enumeration on disconnect. - A fully consumed stream produces one `{:result, result}` or `{:error, error}`. Allow a catch-all for progress and new types. Keep incomplete provider diagnostics out of future history. - Carry TestModel state between turns when using a script. Include every expected request and preserve verified history only. - Treat live result/model and errors as potentially sensitive. Use the message and event projections when exporting data. ##### Verify Run the snippet in the app's test environment. Assert both accepted outputs and an error or pause branch. Read `docs/guides/getting-started.md` and `docs/guides/runtime-and-events.md` from the dependency root. --- ### Skill: `exagent-server` > Use this skill when building an ExAgent 3.0 conversation or Phoenix LiveView, recovering asynchronous admission, driving demand events, or exposing a persisted human review and exact-reference resume. #### Build a conversation with approval ##### When to use - Use `Conversations` for routing and activation by authorized namespace and conversation ID. Use `Chat` and `Chat.Reader` for authorized views. - For a Phoenix PostgreSQL starter, run `mix igniter.install exagent --chat --yes` in the host, apply its migrations and exercise its generated tests. ##### Exact APIs | Call | Return | |---|---| | `Server.chat/3` | `{:ok, result}` or `{:error, reason}`. Handle paused status and checkpoint failure. | | `Server.send_message/3` | `{:ok, receipt}` with `run_id` and `request_id`, or `{:error, reason}`. | | `Server.receipt/3` | Read the admission receipt by the original key within its retention window. | | `Server.pending/1` | `{:ok, items}` from one revision or `{:error, reason}`. | | `Server.decide/4` | `{:ok, reply}` with the new actionable `:continuation` or nil, or `{:error, reason}`. | | `Server.resume/3` | `{:ok, result}` or `{:error, reason}`. Use the decision's exact reference. | | `ExAgent.Chat.Reader.notice/3` + `Server.ack_events/4` | `Reader.notice/3` reads and reduces into `{:ok, chat, rows_or_nil, events_or_replay}` while leaving the notice pending; always call `Server.ack_events(server, notice, chat.cursor)` after applying. | ##### Canonical complete snippet ```elixir alias ExAgent.{Models.Test, Permissions, Result, Server, Tool} alias ExAgent.Continuation.ApprovalRequest alias ExAgent.Message.Part.ToolCall owner = self() tool = Tool.new( name: "publish", description: "Publish a prepared note after review.", parameters_json_schema: %{type: "object", additionalProperties: false}, requires_approval: true, takes_ctx: false, call: fn _args -> send(owner, :note_published) "published" end ) call = %ToolCall{tool_name: "publish", tool_call_id: "publish-1", args: %{}} model = %Test{script: [{:tool_calls, [call]}, "Published."]} ref = fn id -> %{"id" => id, "version" => "1"} end options = [ agent: ExAgent.new(model: model, tools: [tool]), namespace: "editorial", agent_id: "note-17", store: :ets, continuation: %{ durability: :ephemeral, expires_at: nil, lease_ms: 30_000, definition: ref.("review-chat"), policy: ref.("editor-only"), model_ref: ref.("test"), model_codec: %{ dump: fn %Test{index: index} -> {:ok, %{"index" => index}} end, load: fn %Test{} = model, %{"index" => index} -> {:ok, %{model | index: index}} end } } ] {:ok, server} = Server.start_link(options) permissions = Permissions.new!(default: :deny, rules: [{"publish", :allow}]) {:ok, %Result{status: :paused}} = Server.chat(server, "Publish the note.", permissions: permissions) :ok = GenServer.stop(server) {:ok, server} = Server.start_link(options) {:ok, [%ApprovalRequest{} = request]} = Server.pending(server) authorize = fn "editor", :approve, %{tool_name: "publish"} -> {:ok, "editor"} _, _, _ -> {:error, :unauthorized} end {:ok, %{continuation: approved}} = Server.decide(server, request, :approve, actor: "editor", authorize: authorize) {:ok, %Result{status: :succeeded, output: "Published."}} = Server.resume(server, approved) :ok = GenServer.stop(server) ``` ##### Hard invariants & pitfalls - Authorize and attach with `Server.attach/3` and `delivery: :demand` before the initial `Server.history_page/2`. On `{:exagent_events_ready, pid, notice}` read with `Server.events_since/3` and `notice: notice`. Apply before calling `Server.ack_events/4`. Retry a lost ACK with the same notice and cursor. - Keep and reuse the original admission key. Correlate namespace, owner, run and request. Rebuild the page on cursor expiry. Enable `stream_text: true` for provisional UI text. - Treat `:result_unconfirmed` as unresolved. When the owner is dirty, retry `Server.checkpoint/1`. Keep the new reference from an approved decision. ##### Verify In ExUnit, assert one `:note_published` only after the resume. Repeat the decision to test its receipt. Test a lost admission and cursor expiry. Use `docs/guides/runtime-and-events.md` and `docs/guides/durability-and-approvals.md`. --- ### Skill: `exagent-session` > Use this skill when several ExAgent 3.0 participants need one shared-state owner, a turn policy, or an authorized SharedState handle. Covers pure changes, supervised Session turns and snapshot restoration. #### Coordinate participants over shared state ##### When to use | Requirement | Entry | |---|---| | One writer and several participants | `Session` with a roster and `TurnPolicy` | | Chat through the active volatile agent participant | `Session.chat/4` with its trusted definition as `:ref` | | Child output fed back to one parent | Load `exagent-coordination` | | Queue or workflow ownership | Load `exagent-jobs` or `exagent-coordination` | ##### Exact APIs - `Session.start_link/1` accepts `session_id:`, `participants:`, `shared_state:` and `policy:`. Build participants with `Participant.new/1`. - `Session.start/1` returns `{:ok, current_id_or_done}` or `{:error, reason}`. Call it before offering turns. `Session.current/2` reads the current ID. - `Session.take_turn/4` applies a pure change and advances under one owner command. It returns `{:ok, new_state, next_id_or_done}` or `{:error, reason}`. - `SharedState.new/2` binds an owner and participant; `SharedState.propose_change/2` returns `{:ok, new_state}` or `{:error, reason}`. Advance separately with `Session.end_turn/3`. - `Session.checkpoint/1` retries an unconfirmed save. Configure `shared_state_codec:` with a host `Session.StateCodec` for typed state. ##### Canonical complete snippet ```elixir alias ExAgent.Session alias ExAgent.Session.{Participant, SharedState} {:ok, session} = Session.start_link( session_id: "review-note", shared_state: %{"notes" => []}, policy: :round_robin, participants: [ Participant.new(id: "author", kind: :human), Participant.new(id: "editor", kind: :human) ] ) {:ok, "author"} = Session.start(session) {:ok, %{"notes" => ["submitted"]}, "editor"} = Session.take_turn(session, "author", fn state -> {:ok, Map.update!(state, "notes", &["submitted" | &1])} end) editor = SharedState.new(session, "editor") {:ok, %{"notes" => ["reviewed", "submitted"]}} = SharedState.propose_change(editor, fn state -> {:ok, Map.update!(state, "notes", &["reviewed" | &1])} end) {:ok, "author"} = Session.end_turn(session, "editor") :ok = GenServer.stop(session) ``` ##### Hard invariants & pitfalls - Only the active participant mutates state. Bind handles from trusted host state, for example in a tool's dependencies. Reject stale participation. - Keep change functions and state codecs pure. A dirty checkpoint blocks mutations. Retry the save without rerunning the change. - Use JSON-portable state or supply the same trusted codec on every start. Rebind live participant references through the host after restore. - `Session.chat/4` needs a volatile Session without a Store or continuation binding. Advance the policy explicitly after chat. A lost reply is unconfirmed, so inspect the owner's status before taking further action. ##### Verify Assert the updated state and next participant after each turn. Exercise a wrong-participant update and a save retry in the app. Read `docs/guides/coordination.md` and `docs/guides/durability-and-approvals.md`. --- ### Skill: `exagent-store` > Use this skill when migrating PostgreSQL, restoring an ExAgent 3.0 Server or Session snapshot, resuming a persisted revision, or reconciling an unconfirmed save or write. #### Persist conversations and recover executions ##### When to use | Need | Store | |---|---| | Reopen an OTP owner within one VM | `Store.ETS` (`store: :ets` on an owner) | | Restore after a VM restart | `Store.Postgres` with host Ecto SQL, Postgrex and unified migration | | Resume effects across a pause or crash | Scoped atomic Store and trusted continuation configuration | ##### Exact APIs - `Store.scoped(backend, namespace)` constructs the opaque scoped value. `Store.namespace/1` reads its non-nil namespace. Derive it from host auth. - `Catalog.new/1` builds trusted versioned entries. `Catalog.cast/1` returns `{:ok, catalog}` or `:error`. `Catalog.resolve/2` checks a stored identity. - `Continuation.get/2` reads `{:ok, details}`. `Continuation.pending/2` reads `{:ok, items}`. Both can return `{:error, reason}`. - `Continuation.decide(store, request, :approve, actor: actor, authorize: authorize)` returns `{:ok, %{continuation: reference_or_nil, revision: revision, status: status, pending: count, replayed: boolean}}` or `{:error, reason}`. Resume with the actionable reference and trusted bindings. - `Continuation.reconcile_tool/4` takes the scoped Store, run ID, effect ID and the trusted tool plus recovery options. Recover an expired claim first. An unknown or failed lookup leaves the journal unchanged. - `Migration.up/1` and `Migration.down/1` return `:ok` inside a host Ecto migration. ##### Canonical complete snippet In an Ecto host, pin both directions for a new or legacy 2.x schema: ```elixir defmodule Example.Repo.Migrations.InstallExAgent do use Ecto.Migration def up, do: ExAgent.Migration.up(version: 1) def down, do: ExAgent.Migration.down(version: 0) end ``` Exercise the same scoping and trusted definitions with an offline Store: ```elixir alias ExAgent.{Catalog, Continuation, Models.Test, Store} {:ok, store} = Store.ETS.start_link(name: Example.ReviewStore) scoped = Store.scoped({Store.ETS, Example.ReviewStore}, "editorial") "editorial" = Store.namespace(scoped) ref = fn id -> %{"id" => id, "version" => "1"} end agent = ExAgent.new(model: %Test{label: "Review complete."}) binding = %{ definition: ref.("review"), policy: ref.("editor-policy"), model_ref: ref.("review-model"), model_codec: %{ dump: fn %Test{index: index} -> {:ok, %{"index" => index}} end, load: fn %Test{} = model, %{"index" => index} -> {:ok, %{model | index: index}} end } } {:ok, catalog} = Catalog.cast(Catalog.new([{binding.definition, agent, binding}])) config = Map.merge(binding, %{ store: scoped, id: "doc-7", durability: :ephemeral, expires_at: nil, lease_ms: 30_000 }) {:ok, %{status: :succeeded}} = ExAgent.run(agent, "Review doc 7.", continuation: config) {:ok, %{status: :completed} = details} = Continuation.get(scoped, "doc-7") {:ok, %{kind: :agent}} = Catalog.resolve(catalog, details) :ok = GenServer.stop(store) ``` ##### Hard invariants & pitfalls - Snapshot state and C7 effect evidence have different recovery paths. For a dirty owner, use `Server.checkpoint/1` or `Session.checkpoint/1` to save only. - Do not replay an uncertain effect. Bind the exact record lifetime and revision with trusted code and versioned policy, model and output references. - Unified version 1 includes C7 run headers and keyed receipts. For 2.x journals, run `Store.Postgres.rebuild_run_headers/1` and `Store.Postgres.verify_run_headers/1` on each enrolled table before writers and Recovery. `mix exagent.upgrade --yes` (candidate) prepares pinned files. - A custom Store uses the public snapshot codecs and exact physical callback keys. Confirm an inventory is empty before returning `{:ok, []}`. ##### Verify Test owner replacement and a lost save, stale reference and reconciled write. Read `docs/guides/durability-and-approvals.md` and `docs/guides/migration.md`. --- ### Skill: `exagent-test` > Use this skill when testing an ExAgent 3.0 app offline with scripted model turns, stream terminals or tool receipts, or replaying a deterministic Eval regression case in ExUnit or CI. #### Test an ExAgent integration ##### When to use | Need | Entry | |---|---| | Exercise a model/tool loop offline | `%ExAgent.Models.Test{script: [...]}` | | Control stream chunks, usage and terminal | `ExAgent.Models.Test.stream/2` | | Score a portable regression case | `Eval.Case.new/3` and `Eval.run/3` | | Replay deterministic provider fixtures | `ExAgent.Fixture` and `mix exagent.eval` | ##### Exact APIs - Script items are text, `{:tool_calls, [%ExAgent.Message.Part.ToolCall{}]}`, a `Message.Response`, a stream fixture, or a two-argument function of messages and parameters that returns an item. - `ExAgent.Models.Test.stream(events, terminal)` ends with `{:finish, response}` or `{:error, %ExAgent.RequestError{}}`. Supply a successful finish of `:stop` or `:tool_calls`. - `Eval.run(target, cases, evaluators: evaluators)` returns an `%ExAgent.Eval.Report{}`. Target is an agent or a two-argument function. `Eval.equals/0` grades expected output. `Eval.tool_called/2` can check `status: :succeeded` and `args: predicate`. - Capture an authorized persisted turn with `mix exagent.eval.capture` (candidate) after enabling and reviewing redacted retained evidence. ##### Canonical complete snippet ```elixir alias ExAgent.{Eval, Models.Test} cases = [ Eval.Case.new("pending-order", "What is the status of order 9?", expected: "pending") ] evaluate = fn answer -> target = ExAgent.new(model: %Test{script: [answer]}) Eval.run(target, cases, evaluators: [Eval.equals()]) end %{passed: 1, errors: 0, grading_error_runs: 0, grading_coverage: %{scored: 1}} = evaluate.("pending").summary %{passed: 0, errors: 0, grading_error_runs: 0, grading_coverage: %{scored: 1}} = evaluate.("shipped").summary ``` ##### Hard invariants & pitfalls - A nonempty script needs one item per model request, including the follow-up after a tool, any correction and the `final_result` call in `:tool` mode. Exhaustion fails. Use `"test"` for a fixed generic response. - Assert terminal status and the matching `Message.Part.ToolReturn` call ID and status in `result.new_messages`. Assert business effects in the host. Consume streams once and check both drafts and the final terminal. - Disable ReqLLM dotenv loading before app startup with `config :req_llm, load_dotenv: false` in test. Keep live-provider cases opt-in. - Check target errors, grading errors and scored coverage before gating on pass rate. Replay a versioned case with its matching cassette. Stub the tool effects explicitly. ##### Verify Run the app's ExUnit suite with offline fixtures. Force an incorrect answer and assert a scored failure. For cassette replay and redacted capture, read `docs/guides/testing.md` from the dependency root. --- ### Skill: `exagent-tools` > Use this skill when defining ExAgent 3.0 tools, host permissions, argument or result schemas, tool retries, or a validated final answer from JSON Schema or an Ecto changeset. #### Define tools and return typed output ```elixir ExAgent.Tool.new( name: "normalize_sku", description: "Convert a stock-keeping unit to uppercase.", effect: :read, takes_ctx: false, parameters_json_schema: %{ "type" => "object", "properties" => %{"sku" => %{"type" => "string"}}, "required" => ["sku"], "additionalProperties" => false }, call: fn %{"sku" => sku} -> String.upcase(sku) end ) ``` ##### When to use | Need | Selection | |---|---| | Register an explicit callback and schema | `Tool.new/1` | | Infer the schema from annotated Elixir arguments | `Tools.tool_plain/2` or `Tools.deftool/3` | | Access trusted dependencies and effect identity | Use `RunContext` in the contextual callback | | Return a validated answer | Set `output:` to an object schema or supported Ecto module | ##### Exact APIs - `Tool.new/1` takes `call:` with `fn ctx, args -> value end` by default. Use `takes_ctx: false` for `fn args -> value end`. Match string keys. - `use ExAgent.Tools` exports `tools/0` on the declaring module. Put `@doc` before the macro and annotate every argument. `Tools.deftool/3` accepts `effect:`. Set the effect on a `tool_plain` declaration's returned struct. - `Tool.validate_args/2` and `Tool.validate_result/2` enforce declared schemas. Object result schemas validate the tool return separately from final output. - `ExAgent.new/1` accepts `output_mode: :tool`, `:native` or `:prompted` for structured output. Default `:tool` uses an output tool such as `final_result`. Derive an Ecto output from an `embedded_schema` with `changeset/2`. ##### Canonical complete snippet ```elixir defmodule Example.Distance do use ExAgent.Tools @doc "Convert whole kilometres to metres." tool_plain convert(kilometres :: integer()) do {:ok, kilometres * 1_000} end end alias ExAgent.{Message, Models.Test, Result} alias ExAgent.Message.Part.{ToolCall, ToolReturn} [convert] = Example.Distance.tools() schema = %{ type: "object", properties: %{metres: %{type: "integer"}}, required: ["metres"], additionalProperties: false } convert_call = %ToolCall{tool_name: "convert", tool_call_id: "convert-1", args: %{"kilometres" => 3}} answer_call = %ToolCall{tool_name: "final_result", tool_call_id: "answer-1", args: %{"metres" => 3_000}} agent = ExAgent.new( model: %Test{script: [{:tool_calls, [convert_call]}, {:tool_calls, [answer_call]}]}, tools: [%{convert | effect: :read}], output: schema, output_mode: :tool ) {:ok, %Result{status: :succeeded, output: %{"metres" => 3_000}} = result} = ExAgent.run(agent, "Convert 3 kilometres to metres.") true = Enum.any?(Message.parts(result.new_messages), fn %ToolReturn{tool_call_id: "convert-1", status: :succeeded, content: 3_000} -> true _ -> false end) ``` ##### Hard invariants & pitfalls - Use `call:` and never `callable:`. Default effect is `:write`. Declare pure reads explicitly. Use JSON-portable values for ordinary and durable effects. - Return `{:retry, message}` for correctable failures before any effect. `{:error, reason}` fails the run. A write can succeed despite timeout or crash. Declare a read-only `reconcile:` lookup and reconcile before retrying it. - Use host allowlists via `Permissions.new!/1` and require approval for selected effects. Arguments from the model carry zero authority. - Stock wire calls use the mandatory `{"arguments": {...}}` envelope before validation. TestModel and callbacks see the decoded inner string-keyed map. - An invalid declared schema fails admission. A value rejected by a valid result schema produces a confirmed `:tool_error`. Inspect the actual receipt. ##### Verify Execute each snippet offline. Assert missing required arguments, the tool return and the accepted typed result separately. Read `docs/guides/tools-and-output.md` and `docs/guides/llm/tools-and-models-contracts.md` from the dependency root. --- ## Detailed contracts ### Runtime and operations contracts for coding agents ExAgent 3.0.0. Names are relative to `ExAgent` unless qualified. C7 denotes persisted approval and continuation. Candidate marks APIs that can change across releases. Namespaces, subjects, stores, dependency context and authorization come from the host. #### Streaming, Server, conversations and events ##### Lazy streams `ExAgent.run_stream(agent, prompt, opts \\ [])` returns an Enumerable. `ExAgent.resume_stream(agent_or_catalog, ready_ref, opts)` starts a fresh enumeration for a saved continuation. Construction checks options/definition, each enumeration starts work anew, and all deltas remain provisional. Consume one terminal `{:result, %Result{}}` (including `status: :paused`) or `{:error, %RunError{}}`. Accept deliverable output only on `:succeeded`. Unknown event types are additive. | Stream element | Data | | --- | --- | | `{:run_started, data}` | `run_id, root_run_id, parent_run_id, attempt_id` | | `{:run_step_started, data}` | `step` | | `{:steering_applied, data}`, `{:run_handoff, data}` | `step, correction_id` or `step, from, to, call_ref` | | `{:text_delta, data}`, `{:commentary_delta, data}`, `{:thinking_delta, data}` | `step, text`, distinct channels. Reviewed text/commentary adds `stream_checked?: true`. | | `{:tool_call_delta, data}` | `step, index, tool, fragment`, opt-in `tool_call_deltas: true` | | `{:output_partial, data}`, `{:model_response, data}` | `step, output` (provisional map/Ecto struct) or `step, response` (admitted normalized response) | | `{:tool_call_started, data}` | `step, tool, call_ref, call, args_source` where `call` is admitted `%Message.Part.ToolCall{}`, source `:model`/`:reviewer` | | `{:tool_call_finished, data}` | `step, tool, call_ref, return, duration_ms, duration_measured`, `return` is `%Message.Part.ToolReturn{}` | | `{:tool_data, data}` | `step, call_ref, tool, part_id, name, data, transient` | | `{:guardrail_tripped, data}` | `step, name, stage` | | `{:context_compacted, data}` | `step, reason: :context_overflow, estimated_tokens_saved` | | `{:approval_requested, data}` | `continuation, pending` with identifiers, optional permission rule and candidate deferral/delegation fields | | `{:run_step_finished, data}` | `step, outcome`, one of `:continued`/`:retry`/`:succeeded`/`:paused`/`:failed` | | `{:child, %{run_id: id, parent_run_id: parent, root_run_id: root}, element}` | Child progress once at any depth with `child_events: :all`. Root terminal closes stream. | - Each started step closes once before terminal (abrupt kill can emit terminal alone). Calls waiting for approval finish on the executing attempt. Nested CodeMode calls add candidate `program_call_ref`, one-based `program_step` and `effect`. `RunContext.emit(ctx, name, data, opts)` uses `id:` to upsert one part, `transient: true` to skip replay, ≤256 emissions per call then `{:error, :tool_data_limit}`. It is synchronous and uses tool time. - Synchronous demand keeps one element outstanding per producer and leaves stock backend buffers independent. Worker+guardian are closed before terminal delivery, even when reducer suspends on it. On unresponsive guardian, allow up to 1s before force shutdown. Halting/owner death releases owned resources. A suspended Enumerable continuation must be resumed or halted by the enumeration owner. Wrong process raises `ArgumentError`. Halting after a dispatch can leave effects/C7 model intent uncertain. Re-enumeration starts a new run with fresh effects. - Up to 4,096 text/commentary/thinking fragments per request, separate from usage and argument previews. Acknowledge progress before delivery, so kill can reconstruct accepted prefix in `RunError.partial.pending_response`. Cumulative `:usage` replaces prior snapshots per direction. `on_progress:` receives full binary prefixes. `stream_text:` enables actual adapter streaming. Model and run deadlines remain active. - Structured previews sample first argument/text fragment, then every 16 fragments or 1,024 new bytes and flush before model response. One offered output branch/index. 32 distinct updates, up to 4,096 fragments and `min(max_payload_bytes, 65_536)` bytes of input, draft and serialized event including step. Model-valid completed members use JSON Schema with required disabled or Ecto partial cast incl. advertised virtuals/embeds/defaults. Full changeset, validators, function and final guardrail run only on complete output. Retry creates a new draft on the next step. - POSIX Ctrl-C recipe `examples/cancellable_batch.exs` starts Mix in a new session, translates SIGINT to SIGUSR2 for `System.trap_signal/2`, and supervises enumeration. Caller/runs share absolute monotonic deadline. Ctrl-C exits 130, deadline 124. Write successful rows to a staging file and rename only after the final cancellation/deadline check. ##### Process ownership and conversation activation - `AgentSupervisor.start_agent/1` starts a Server via a DynamicSupervisor. `AgentSupervisor.stop_agent/1` terminates it. `Server.child_spec/1` ID `{:exagent_server, agent_id_or_name_or_unique_ref}`. A restart from the same spec keeps generated agent ID and topic, gets new emitter ID and restores confirmed data. A fresh start call creates a new spec, so supply stable `agent_id:`. Registered local or `{:via, Registry, {...}}` names fence simultaneous local startups (second gets `{:error, {:already_started, pid}}`). Tests can supply child ID through `start_supervised!/2`. - `Server.start_link/1` requires `agent:`. Keys `agent_id, name, store, pubsub, namespace, metadata, continuation, catalog, observability` (candidate), `event_buffer, idle_timeout, hibernate_after, missing, max_pending, max_input_bytes, max_pending_bytes, max_history_bytes, max_admission_receipts`. Defaults `max_pending: 8`, input 1 MiB, pending/history 8 MiB each (byte ranges 1–64 MiB ETF). Enforce queue/input limits again when dequeued and intersect agent/server history bounds. Only Store `:not_found` can create a fresh owner. `missing: :error` refuses. Invalid configuration raises `ArgumentError`, load/deserialize mismatch gives `{:error, {:restore_failed, reason}}`. Metadata with a Store must encode as a JSON object up front. Events use original map, snapshot uses encoding. Without Store the runtime accepts arbitrary map. CodeMode+C7 startup returns `{:error, {:unsupported, {:code_mode, :continuation}}}`. - `Conversations.start_link(name: local_atom, server: factory, ...)`. `partitions:` defaults to online schedulers, `registry: :local`. Key `{namespace, agent_id}` from trusted host. Factory is unary or `{m, f, args}` prepending key and must supply matching scope/ID. `ensure(name, key, opts \\ [])`, `whereis/2`, `via/2`, `call(name, key, unary, opts \\ [])`. Warm lookup first. `max_activations: 16` distinct cold keys and `max_activation_waiters: 128` per key incl. first, both 1–1,024. Errors `{:start_failed, :activation_capacity}`/`{:start_failed, :activation_queue_full}`. Same key shares activation. `create: false` permits restore only. `factory_timeout: 5000` ms range 1–4,294,967,295 stops option-builder worker and yields `{:start_failed, :factory_timeout}` before Store restore. Lost start ack keeps reservation and observes in-progress registry owner. - Activation `timeout: 5000` covers lookup and replacement waits. `ensure/3` expiry returns `:result_unconfirmed` and releases waiter. `call/4` maps that unconfirmed activation to unavailable because callback never ran. One Server operation per callback. Can retry once after explicit nondelivery or pre-execution fence. An unconfirmed operation must be reconciled, including snapshot conflict. Callback operation has separate wait. - Manager defaults `idle_timeout: 900_000` and `hibernate_after: 15_000` ms, standalone Server both infinity. Finite eviction requires Store and only idle/paused confirmed state, empty mailbox/queue and no attachment. Reads don't renew idle. Emits `:server_stopped` with `:idle` and exits `{:shutdown, :idle}`. Viewers cap 1,024 PIDs, death detaches. Runtime exposes elapsed idle and attachment count. - `registry: :global` gives cluster lookup on connected nodes. Requires atomic durable Store and C7 `durability: :durable`. Invalid config raises in activation. Partitions can create two owners and Store fence admits at most one fresh turn. Superseded owner rejects prior to C7 IO, emits cancellation and stops. Snapshot-only owner can detect conflict at checkpoint via `CheckpointError`. After reconnect, global keeps the first node name, displaced owner closes current work and cancels queue. Surviving owner may reopen if another committed newer state. Custom registry `{module, opts}` implements `Conversations.Registry`. - `Conversations.stop(name, key, reason: {:shutdown, :stopped}, timeout: 5000)` interrupts owned work, sends unconfirmed active synchronous reply, emits per-turn cancellation then stopped. `:ok` confirms exit and keyed cancellation receipts. Otherwise it exits with unconfirmed event and `{:error, :result_unconfirmed}`. Unread discarded mailbox commands explicitly return unavailable. Ordinary postdispatch death is uncertain. `Conversations.drain(name, timeout: 5000)` fences local admissions including with shared registry, lets current turn reach normal persistence boundary, cancels queue, confirms exits. Continues after caller timeout. Repeat to await same drain. Restart manager to reopen. ##### Server admissions, control and reads | Call | Options, return and decision | | --- | --- | | `Server.chat(server, prompt, opts \\ [])` | Synchronous outcome `{:ok, %Result{}}` or error, `timeout: :infinity`, `request_id:` and `message_history:` plus run options. Current active turn yields `:busy`. Reply loss `:result_unconfirmed`, work can continue. | | `Server.send_message(server, prompt, opts \\ [])` | `timeout: 5000`, `queue: true`, chat run options plus `idempotency_key:`. Queue back. `queue: false` uses synchronous admission rules without waiting for outcome. Receipt `{:ok, %{status: :admitted, run_id: run, request_id: req}}`. Lost ack `{:error, {:delivery_unconfirmed, request_id}}`. | | `Server.steer/3` | Same asynchronous controls minus `:queue`, priority/front separate turn. | | `Server.steer_run(server, run_id, text)` | Candidate, volatile runs only (`{:unsupported, :continuation_steering}` on C7). Corrects the active live root at the next step boundary. `{:ok, %{step: step, correction_id: id}}` after history apply. Terminal first gives `:run_not_active`, handle lookup loss unavailable. | | `Server.resume(server, ready_ref, opts \\ [])` | `timeout: :infinity` and applicable run options. Uses stored request ID/history and checks lifetime/run/revision. Rejects `message_history`, `request_id` and `idempotency_key`. C7 uses `Server.decide/4` rather than synchronous approver. | | `Server.abort(server, opts \\ [])`, `abort_run(server, run_id, opts \\ [])` | Current work vs exact run ID (incl. queue). `timeout: 5000`. Candidate `abort/2` option `cancel_follow_ups: false`. `:run_not_active` if exact target no longer cancellable. Observed run/lifetime/revision conflict `:continuation_abort_conflict`. | | `Server.receipt(server, key, opts \\ [])`, `turns(server, opts \\ [])` | `timeout: 5000`. Receipt gives original admission or `:cancelled_before_start` incl. revision. Turns gives root and queue order, up to `max_pending + 1`, `run_id, request_id, admission_key, status` incl. `:cancellation_unconfirmed`. | | `Server.health/2`, `history/2`, `history_page/2`, `usage/2`, `pending/2`, `continuation/2` | Reads `{:ok, value}` or `{:error, :unavailable}` and applicable Store/config errors. Default wait 5000 ms. | | `Server.reset/2`, `set_model/3`, `checkpoint/2` | `timeout: 5000` (checkpoint infinity). Retry checkpoint saves exact outstanding transition. Confirmation may reveal previously hidden accepted rows and expire cursors. | - Forwarded options `deps, model_settings, stream_text, tool_call_deltas, child_events, estimate_cost, deadline, max_concurrent_requests, max_concurrent_tools, permissions, approve, observability, trace_context, usage_limits`. Candidate options include observability and per-turn limits. Startup/submission rejects invalid unknown/repeated keys. `timeout` controls caller wait (0–4,294,967,295 ms or infinity for control/turn calls) and `deadline` controls work separately. Remote name/PID lookup on owning node ≤5 s and remaining wait, then dispatch to resolved PID. `{:error, :unavailable}` proves command wasn't dispatched or was explicitly discarded unread. `:result_unconfirmed` is ambiguous. Reads return unavailable when no reply. - Request ID UTF-8 1–512 bytes, nil/false generate, invalid gives `:invalid_request_id`. Prompt check early `:invalid_prompt`/`{:invalid_prompt_part, zero_based_index}`. Queue count/bytes excess `:queue_full`. Status `:idle`→admission, `:running` owns one worker (sync chat/model/reset busy), `:paused` inbox, `:blocked` claim/uncertainty, `:reset_required` terminal unanswered tool batch. In last three, sync chat/model refuse `:continuation_pending` and reset allowed only for reset-required. `:checkpoint_pending` fences persistence mutations until exact checkpoint ack. Paused/blocked/reset-required owner periodically checks fence with finite idle, otherwise checks before async unkeyed admission. Superseded owner stops. It can adopt a snapshot advanced by its own same-record/run/attempt. - `Server.new_admission_key(ttl_ms \\ 900_000)`, TTL 1–4,294,967,295 ms. Key immutable absolute UTC expiry and client ID UTF-8 1–512 bytes. `encode_admission_key/1`/`decode_admission_key/1` roundtrip URL-safe token, with authorization required separately. New receipt horizon 4,381,367,295 ms beyond clock (Store clock for C7). Fingerprint binds admission mode, exact input and ordered explicit options. Excludes timeouts, observability/tracing, request ID and key. New closure/PID can conflict. Preserve original inputs, key and request ID. Different fingerprint `:idempotency_conflict`, expired `:idempotency_expired`, too far `:idempotency_expiry_out_of_range`, 256 live cap (1–256) `:receipt_limit`. Live keys still resolve at capacity unless resend fails input bound. Reads without resend save input budget. Successful admission/cancellation/expiry checks atomically advance clock watermark, prune expired keys and resist clock rollback. - C7 commits scoped receipt before queue/dispatch (SQL 5 and one bounded admission row per conversation). Only fresh claimant dispatches. Lost owner can leave admitted receipt without execution. Restore never replays admission. `:not_found` can race a still-pending commit. Same retained key is the lookup/retry identity. Without C7 even snapshot-backed receipts live only in owner, missing `:receipt_not_durable`. Resend after replacement may execute again. Read Jobs notices from destination Server's receipt independently of job state. Generated chat persists key/expiry, no prompt, in sessionStorage before send, uses pending URL recovery and keeps Send disabled until receipt or correlated retained terminal resolves. - `payload.persistence` and health share `%{mode: :disabled | :snapshot | :atomic, status: :confirmed | :unconfirmed, revision: rev, error: error}`. Error `%{type: :checkpoint, operation: operation, reason: reason, revision: rev}`. Queued cancellation CAS is admission revision, persists keyed terminal, releases queue bytes and fences ambiguous writes. Repeated same abort or original receipt read can reconcile. Active/paused C7 abort CAS orders against finish and observed attempt, can leave `:uncertain` for tool/callback or external deferral. Confirmed cancellation rolls back only unfinished canonical turn and retains prior accepted history, journal usage and effect evidence. An unresolved model intent can keep unknown cost. Supply confirmed deferral then one `:deferred_result_supplied` and one final cancellation event at reconciliation revision. External cancel/reconcile is reflected by owner at lease/worker check. Check expired lease horizon before untargeted retry. Repeat `abort/2` can cancel a later queued turn. Cancellation stops owned task and waits locally, external IO may continue. - Live steering takes FIFO batch of ≤8 outstanding nonempty UTF-8 corrections (each ≤16 KiB and run payload cap, plus Server input ETF cap). One request with a user part per correction, before model hooks and after tool exchanges. Guardrails check each and retention can reject whole batch. `:queue_full`, `:invalid_prompt`, `{:input_too_large, %{bytes: b, limit: n}}`, ambiguous apply `:result_unconfirmed`. Direct `on_steering: fn handle -> ... end` (candidate) and `Steering.correct(handle, text)` from another process while keeping demand active. Each child has separate handle, root correction cannot address child. `{:unsupported, :continuation_steering}` on C7 and durable workflows exclude the option. ##### History, forks and display state - `Server.history_page/2` accepts `before:`, `since:`, `limit: 40` (1–1,024), `max_bytes: 65_536` (64–67,108,864), `projection: :messages | :visible_text | :chat`, `include_draft: false` and `timeout: 5000`. Chronological `items`, `start` zero-based, `total`, `revision`, `before`/`head`. Cursor valid across append, expired by reset/replacement/projection rewrite/owner restart. `:omitted` preserves one item position on overflow. An incremental start beyond prior count requires replacing the displayed window. - `:messages` canonical terms. `:visible_text` display string, nil hidden or omission. `:chat` adds `{:job_notice, %Message.Part.JobNotice{}}`, latest owner failure and candidate activities. Page includes same-instant `event_cursor`, `checkpoint_pending?` and active root ID with chat/draft. `include_draft: true` includes `draft`/`commentary`, `stream_checked?` and `draft_limit`. Each channel is capped at 1 MiB and can be `:omitted`. Guarded drafts only reviewed deltas. Nil outside active run or with replay disabled. A missing historical failure terminal can remain unknown after buffer eviction. - `output_guarded?` on structured output, stream/final guard, validator or handoff catalogue. Display accepted terminal only, hiding rejected/imported unverified output. Ecto accepted projection uses Jason then embedded dump fallback, bounded by payload limit and owner history. Store checkpoints accepted view and policy with history. C7 may omit view values to fit checkpoint. Unknown old snapshot policy also hides unproven assistant rows. Reset adopts active policy. Binary slices detach for safe page/event retention. Live guarded failures preserve accepted history, while failure/debug partial keeps separate outcomes. - `Conversations.fork(source, new_id, at: root_run_id, timeout: 5000)` accepts live Server or `{scoped_store, source_id}`. Same scope/Store, fresh stable ID, includes selected settled turn and closed prior prefix. `Server.regenerate(server, destination: {manager, new_id}, at: ..., prompt: ..., run_options: ..., admit: ..., timeout: 5000)` forks before last/selected settled user turn and sends original or replacement with queue disabled. Reject `message_history`/`queue` in run options. Admit callback checks branch key/prompt after creation. `Server.regeneration_target/2` reads latest confirmed `turn_ref` and original `prompt`. Unsupported Store, pending checkpoint, busy active target, absent target, unsettled turn and open effect report `:unsupported_store_capability`, `:checkpoint_pending`, `:busy`, `:turn_not_found`, `:turn_not_closed`, `:open_effects`. - Branch has zero current usage, independent new journal and `forked_from` metadata. Retire signed Claude/encrypted Responses reasoning, preserve historical settled calls/results. Snapshot-only can retain older historical unknown return. Limit 64 branches/family, `:fork_limit`. Existing destination `:destination_exists`. Unavailable manager refused before branch. Confirmed admission refusal releases/seals eligible seed. Retained branch on error returns `{:error, {:branch_created, branch, reason}}`. On lost ack find original destination ID and admission key. `Conversations.discard_fork(store, id)` requires quiescent unused branch with no admissions/owner and no unique inventory ref. All retained family members participate in subject inventory/erasure. ##### Event v2 and demand delivery - `%Event{version: 2, id: "evt_...", seq: seq, emitter_id: id, type: type, source: source, occurred_at: utc, request_id: req, agent_id: agent, session_id: session, participant_id: participant, run_id: run, root_run_id: root, parent_run_id: parent, namespace: ns, payload: map, metadata: map}`. Emitter-local monotonic sequence resets on owner restart. Manual no-emitter cursor nil. Source `:run`/`:server`/`:session`. Root ID equals run ID, parent nil. Queue/cancellation use reserved IDs. Child progress has its lineage. Producer delivers `{:exagent_event, event}` on `Event.agent_topic/2` or `session_topic/2` (nil preserves legacy topic). Match scope, conversation, request and emitter before applying. - `Event.payload/2` projects stream data. Terminals `:run_finished`/`:run_paused` carry `new_messages` and accepted result fields outside whole history/steps. `:run_failed`/`:server_request_cancelled` carry error/partial. Selected `output_name` and optional `handoff_target`/`citations`. Output projection `output`/`output_text` may return `%{serialization_error: true}` and nil text. Failed history/usage conversion becomes nil. Tool finish contains `status, content, content_withheld, usage, duration_ms`. Declared `tool` or `"unknown_tool"`/nil preview. Opaque `call_ref` matches one invocation, stable across resume, separate from provider IDs. Durable Frame 3 child start and candidate `:child_run_stopped` are live observed only. Child drafts/steps stay private. Candidate `:job_started` acks known background submission. `:server_request_queued` carries `position: :front | :back`. - Server source also `:server_stopped`, `:approval_decided`, `:deferred_result_supplied`. Session source `:session_started`, `:session_paused`, `:session_resumed`, `:session_done`, `:session_closed`, `:participant_joined`/`:participant_left`, `:session_turn_changed` and `:shared_state_updated`. Participant ID refers to changed/receiving participant, nil for lifecycle. Persisted state and following turn change can share revision. `:session_done` leaves owner running. - `Event.strip_content/1,2` nulls trusted application content and replaces error reason with diagnostic, keeps named scalar/control fields incl. `output_name`, clears metadata by default and unknown type payload entirely. Atom/string keys supported. Opted-in top-level metadata values travel whole, including nested values. Never export raw reason, tool/prompt/citation content by default. Telemetry is a separate content-free contract. PubSub broadcasts synchronously, failure logs without ending run. Subscribe before admission/replay, filter duplicates with `Event.after?/2`. `{:pubsub_subscription_unconfirmed, operation, module}` can mean membership changed. Confirm unsubscribe from same process then subscribe and refresh. Direct bus has unbounded reader mailbox. - Server replay default `event_buffer: [max_events: 1024, max_bytes: 524_288]` (1–65,536 events, 1–67,108,864 per combined event ETF bound), or false. Oldest evict first. Overlarge event not retained. Works without PubSub and indexes after 32 retained events. Session default disabled. Transient tool data not buffered. `events_since(server, cursor, opts)` with nil oldest, chronological sequence, empty page advances to head. `limit` 1–65,536, `max_bytes` 64–67,108,870 ETF items, ordinary default all retained. Unknown emitter, ahead or evicted cursor `{:error, {:cursor_expired, current}}`. - `Server.attach(server, reader_pid, delivery: :demand, timeout: 5000)` (default `:none`) is idempotent, needs buffer for demand. Notice `{:exagent_events_ready, server_pid, notice_ref}`, at most one pending per reader. `events_since/3` with `notice: ref` defaults 64 events/262,144 bytes, read leaves notice pending. `{:event_too_large, required_bytes}` page can retry same notice with higher cap. `Server.ack_events(server, notice, applied_cursor, opts)` rearms or emits another notice, same last ACK idempotent. Wrong reader/obsolete `:stale_notice`. On replay gap rebuild chat history including draft, ACK page cursor. ACK cannot precede last ack or exceed head. `detach/3` also idempotent, old notice may remain in mailbox. Default first/ack/detach timeout 5s with nondelivery vs unconfirmed distinction. - `Runtime.list/1` filters `kind:` (`:server`, `:session`, `:jobs` or list, defaults all), `namespace:`, `node: node()`, `limit: 500` (1–10,000), `timeout: 1_000`. Version 1 rows `kind, pid, node, namespace, id, started_at` (Unix ms). `Runtime.info(pid, events: 0, after: nil, content: false, timeout: 1_000)` supports 0–256 events, reports cursor expiry. `Runtime.pending(pid, content: false, timeout: 1_000)` reads open Store items incl. ID, tool, call ref, new operation ID, decisions, expiry and `:redacted` args. Trusted `content: {:redact, {m, f, args}}` runs on owner node by field, callback failure `:redaction_failed`. Approval uses authoritative `Server.pending/2` or `Continuation.pending/2`. `exagent_dashboard` projects these read-only queries, content-free cursor pages and authorized Store inventory behind host authentication. A changed namespace resets pagination and one-second budget is shared across a refresh. OTP status hides content and privileged tracing or `:sys.get_state/1` can read it. ##### Chat and streaming transport projections - `Chat.new(namespace, id)`, `apply_page(chat, page, mode \\ :latest)`, `reduce(chat, %{items: events, cursor: cursor})`, `put_controls(chat, turns, pending, blockage)`, `draft(chat, :answer | :commentary)`. Row updates `{:reset | :append | :prepend, rows}` with stable offsets within revision. Same-owner root terminals trigger history refresh. Controls use content-free IDs, deferral kind/wake/delegation path. Observed failure projects as failed on idle owner and blocked stays blocked. Activity (candidate) ≤256 latest same-attempt child/job statuses sorted newest, open child unknown on root terminal. Refresh transcript from history rather than promoting raw drafts. - `Chat.Reader.history/3` latest/older/reload, `notice/3` reads and reduces the batch into `{:ok, chat, rows_or_nil, events_or_replay}` (leaving the notice pending until the caller calls `Server.ack_events/4` with `chat.cursor`), `approvals/2` reads controls, `admission/5` and `cancellation/5` combine scoped receipt and terminal evidence. Require authorized owner, correct emitter and run IDs. `Chat.InputForm.present(deferred, agent)` uses exact saved tool definition (child for delegated input) and tool-output guards, returns `id/message/fields`, no opaque peer state or raw args. Flat primitive fields string/integer/number/boolean, errors `:unsupported_mcp_form`/`:input_form_withheld`. `responses(call, forms, submitted_map)` parses decimal zero-based form/field keys, validates schema, omits empty optional fields and produces MCP answers or `:invalid_mcp_input`. Keep original call server-side. - `Chat.SSE` (candidate Plug) requires `authorize: fn conn -> {:ok, owner_pid} | {:error, :unauthorized | :forbidden | :not_found | :unavailable} end`. Optional `run_options: fn conn -> opts end`, defaults `heartbeat_ms: 15_000`, `stream_timeout: 300_000`, `max_body_bytes: 1_048_576`. GET SSE with `Last-Event-ID`, snapshot at initial/gap/control/transcript refresh, replay retained suffix and `cursor` events. POST object string `"prompt"` + encoded `Idempotency-Key`, GET with same key receipt, DELETE `run_id` asks abort, acknowledgement separate from terminal. Host owns CSRF/auth/decision endpoints and upstream parsed-body limit. Disconnect, owner loss, write failure or timeout ends reader while admitted turn survives. - `Chat.AISDK.new(chat, run_id, opts)` (candidate) AI SDK 7 UI Message Stream v1, `headers/0`, `push/2`→`{encoder, iodata}`, `finished?/1`. Replay ordered start-to-terminal from one emitter. Root run ID is chat message ID across attempts. Commentary as transient `data-exagent-commentary` with cursor ID, status as `data-exagent-status`, stable tool refs including review stubs/withheld output. Accepted output replaces draft. `resume_after: pause_cursor` requires entire retained prefix to rebuild and stops at next pause/terminal. `regenerate/3` maps authorized `"regenerate-message"` request to Server regenerate. Reload authorized history when original prefix incomplete. - `Chat.AGUI.new(chat, server_run_id, opts)` (candidate) AG-UI 1.0, optional `thread_id:` (agent ID), `run_id:` (fresh per attempt), `headers/0`, `push/2`→`{encoder, [event_maps]}`, `sse/1`, `finished?/1`. Per-step message and step JSON Patch, terminal result authoritative. `exagent.approval` requested items/decided action, `exagent.input` interrupt `input_required`, `exagent.timer` interrupt `timer_wait` with UTC `wakeAt`. Delegated path/activity message ID in `metadata.exagent`. Resume uses same Server run ID with fresh wire attempt and preceding decision events. `Chat.AGUI.Input.decode/2` handles answered client interrupts. Timers and effect reconciliation are host/Recovery actions. Candidate reasoning for both encoders opts into bounded provider summaries through `fn :reasoning_summary, text -> {:ok, text} | :drop end`. JSON bound 4,096 bytes, invalid/oversize/guarded suppression. [Runtime and events](runtime-and-events.md) · [Framework integration](framework-integrations.md) #### Background jobs ##### Volatile Jobs - `Jobs.start_link(opts \\ [])` accepts `:name`, `:namespace`, `max_running: 8`, `max_finished: 256`, `max_result_bytes: 65_536`, `timeout: 900_000` (ms). Results and error text are bounded. The supervised task and its finished receipt belong to this Jobs owner and disappear on owner loss. Starting a task is a tool effect. Subsequent execution has its own lifecycle and limits. Parent cancellation, request counts and deadline do not propagate. - `Jobs.start(jobs, name, fun/0, opts \\ [])` accepts `:id` (visible ASCII, 1–128 bytes), `:notify` (arity 1) and `:timeout` (ms). Returns `{:ok, %Jobs.Job{}}` or `{:error, :busy | :job_id_in_use | :unavailable | {:delivery_unconfirmed, id}}`. Inspect the original ID after ambiguous admission. `status/2` is one read. `wait/3` waits within `1..4_294_962_295` ms. `cancel/3` returns the confirmed job snapshot, with default `timeout: 5_000`. `list/2` filters by `:status` and `:limit`, newest `started_at` first. Statuses `:running`, `:succeeded`, `:failed`, `:timeout`, `:cancelled`. - `Jobs.background(tool, jobs: owner, timeout: ms, notify: fun/2)` keeps the function tool's input contract and runs with its original context. Notification receives the job and context with messages omitted. Only nondelegation function tools with ordinary return mode, concurrent execution allowed and `requires_deferral: false` qualify. `Jobs.agent_tool/1` requires `:jobs`, `:name`, `:description` and `:agent`. `:run_opts` can be a list or unary resolver. `:timeout` and `:notify` are optional. A paused child is a failed job with separately recoverable child state. - `Jobs.tools/2` returns `job_status`, `wait_job`, `cancel_job` (`job_id` required for each, `seconds` required for wait). Durable query tools expose status and wait. `max_wait_seconds: 60` in `1..4_294_962` and an extra 5,000 ms on the wait tool timeout. Tool JSON carries `job_id`, `name`, `status`, optional `result`, `error` and `notification`. Lookup failures carry `status: "unknown"`, `code` and `message`. A notification slot is reserved with start. Callback return is ignored. `Jobs.notify_server/2` admits a `JobNotice` with `job_id`, `status`, `tool_name` and candidate `follow_up`, using the job ID as `request_id`. `Jobs.notification_key/1` for finished volatile jobs expires 24 h after finish. Observe the destination receipt to resolve acknowledgement loss. ##### Durable Jobs - `use ExAgent.Jobs.Durable, ...` uses Oban and a single PostgreSQL Repo and prefix. Run the ExAgent and Oban migrations in that schema. `segments: false` selects new journal writes. Both configurations read supported inline and segmented journals. `new(worker, namespace, oban: Oban)` builds the scoped handle. `store/1` exposes its Store. `new_id(ttl_ms \\ 86_400_000)` embeds immutable expiry, range `1..4_294_967_295` ms. - `start(handle, id, definition_ref, prompt, opts \\ [])` commits the receipt and first queue delivery in one database transaction. JSON-safe versioned reference, UTF-8 prompt ≤1 MiB. `request_limit: 50`, `active_time_limit_ms: nil`, `lease_ms: 60_000`. Non-nil values are integers `1..4_294_967_295`. Execution limits can only tighten the resolved agent. Identical input returns the same ID, changed input `{:error, :conflict}`. Queue args are namespace and ID. Receipts remain readable while Oban restarts. Delivery requires the configured Repo and prefix. Inline delivery and delivery inside a Repo transaction can return `{:unsupported, :inline_delivery}` and `{:unsupported, :transactional_delivery}`. `wake/2` enqueues the same ID. For operator decisions, commit the decision and wake together when sharing the Repo. - The host resolves `resolve(namespace, ref) → {:ok, agent, binding, run_opts} | {:error, reason}` or candidate `definition(namespace) → catalog | {catalog, run_opts}`. Candidate `delivery_queue(namespace, ref)` selects an existing Oban queue. `server(namespace, id)` gives a stable destination address without activating the owner or `nil` to disable. Delivery retries owner unavailability. `Jobs.Durable.tool(ref, tool, policy, opts \\ [])` resolves a nondelegation function tool as a Frame 3 agent with JSON-object text input, two local model steps and confirmed tool status/content as JSON. Normal permission, schema, approval and reconciliation rules apply. - `recovery(namespace, ref)` defaults to `:manual`. Opt in with `actor:`, `authorize:` (arity 3), `model: :cancel | :leave | :retry` (`:cancel` default). Automatic recovery is scoped to matched static Frame 3 definitions and the saved references. Pure validators and guards are allowed. Custom lifecycle/progress/approval hooks, dynamic instructions, custom cost estimator, delegation, handoff and rehydrated tools require operator recovery. Oban redelivery or Lifeline can deliver after owner loss. An existing C7 lease/effect still gates entry. When an initial job reservation remains after an expired lease, `retire_start/2` retires only a start without C7 proof. - `status/2 → {:ok, %Jobs.Job{}} | {:error, reason}`, `wait/3` polls committed state through the same bounded pool and read horizon, stopping at terminal/operator boundary and returning the last confirmed snapshot at timeout (or `{:error, :timeout}` with none). States `:queued`, `:starting`, `:running`, `:pending`, `:approved`, `:ready`, `:blocked`, `:recovery_required`, `:expiry_due`, `:succeeded`, `:failed`, `:denied`, `:expired`, `:cancelled`. Durable terminal result ≤64 KiB, usage qualified, diagnostic bounded. `retry_at` is UTC `DateTime` when a ready safe wait or pending timer has a known horizon. Status can return `:missing_exagent_jobs_table`, `:jobs_migration_required`, `:missing_exagent_snapshots_table` or `:unavailable`. Apply the unified migration on the configured Repo. - A confirmed first provider/quota/budget admission refusal can preserve the initial request for retry before dispatch. Known wait uses its horizon, unknown spend uses 5 s, queue pressure 1 s. Unknown quota horizon and missing schema retain the claim. Unbounded wait remains subject to expiry. Queue snooze rounds up to seconds and is capped by one day and the earlier deadline/ID expiry. Snooze preserves request and active-time allowances. Unavailable definitions can snooze, incompatible bindings require review. Pending timer wakes at the earliest wake/expiry. Operator review remains required when effects are open. - Final notices use one durable sending claim and a scoped, idempotent Server receipt. `notification_key(handle, id)` expires 24 h after ID expiry. `reconcile_notice(handle, id, :admitted | :abandon)` settles ambiguous notice delivery from destination evidence without an additional send. A lost acknowledgement leaves delivery unconfirmed. `prune(handle, id)` requires expiry and settled evidence. Retired ordinary IDs can condense into a Store watermark. Legacy and Eval IDs retain individual fences. After pruning, status may return `:not_found` and the original ID stays expired for admission. ##### Scheduled follow-ups - Candidate `Tool.FollowUp.tools(store, opts \\ [])` exposes `schedule_follow_up`, `list_follow_ups` and `cancel_follow_up`. `max_pending: 8` (`1..100`), `min_delay_ms: 1_000`, `max_delay_ms: 2_592_000_000` (ceiling `4_294_967_295`), `allow_chaining: false`. Scheduling takes ISO 8601 time with an offset (≤64 bytes) and UTF-8 topic 1–2,048 bytes. Only a live scoped durable root agent can use the effect. Catalogue stubs alone cannot schedule. The Store binds the schedule to the current effect key and atomically deduplicates it. The turn can complete while the follow-up stays pending. - Candidate `Jobs.Durable.FollowUps.list/2` and `cancel_all/2` expose scoped controls. `Server.abort(cancel_follow_ups: true)` also clears pending follow-ups. Recovery authorizes `:deliver_follow_up` with namespace, subject ID, follow-up ID and `retry_at`, with trusted run options supplied by the host. Restore an existing idle owner (`create: false`). At most one new C7 turn per schedule, with the current owner's policy and budget. Initial commit before first claim can deliver by the `on_ready` path. Safe terminal failure consumes delivery. Ambiguity requires reconciliation. [Continuation and queue recipes](continuation-jobs.md) · [Persisted scheduling](durability-and-approvals.md) #### Durability, Stores and C7 continuations ##### Snapshot Stores and migration - `Store.scoped(adapter_or_descriptor, namespace)` binds physical operations to an authorized scope. `Store.ETS.start_link(name: table)` owns a node-local named table (default `Store.ETS` in app supervisor). Reads use ETS and writes serialize through the owner. Snapshots survive Server restart while the table owner lives. `Store.Postgres` accepts the Repo or `{Repo, table: "exagent_snapshots", segments: true}`, with optional Ecto SQL/Postgrex dependencies. `segments: false` (default) writes inline. Either mode reads both formats. Segmentation keeps immutable content-addressed bodies and a compact mutable envelope. Readers reconstruct and validate before returning data. SQL snapshots survive VM restart. - Snapshot writes require fresh key, next revision, or byte-equivalent retry. Stale or competing writes return `:superseded`. Snapshots alone detect a conflict after unjournaled effects may have run. `Server.checkpoint/2` and `Session.checkpoint/2` retry the exact save after failure without effect replay. `CheckpointError` records operation and underlying cause. `checkpoint/2` can return `:busy` while active. Persistent failure blocks start of queued work until checkpoint or explicit administrative resolution. C7 checks Store identity and mutation authority before dispatch. - `Store.list_agent_snapshots(store)` loads and validates all agent snapshot bodies. `Store.list_agent_headers(store, opts)` returns `{:ok, %{items: headers, cursor: cursor_or_nil}}` with `agent_id`, `revision`, `updated_at` (UTC `DateTime`), physical-ID sort order, default `limit: 50` (1–100) and opaque scope-bound `after: cursor`, nil cursor at end. Invalid cursor returns `:invalid_scan`, missing header callback `:unsupported_store_capability`. C7 state is queried via `Continuation.list_runs/2`. Custom Store snapshot callbacks receive a namespace-encoded key and validated serialized snapshot data. `Store.agent_key_in_namespace?/2` checks ownership. Optional paginated header callback `list_agent_headers/4`. Use `Store.ContractCase` for the public snapshot contract. - `ExAgent.Migration.current_version/0 == 1`. In an Ecto migration call `up(version: 1)` / `down(version: 0)` under the transaction and configured prefix. `migrated_version(repo: repo, table: table)` reports 0 for an unenrolled legacy schema. Unified install includes Store SQL levels 1–7 (`4` run headers, `5` admissions, `6` recovery, `7` timers), tombstones, durable Jobs/follow-ups, memory, budget, quota and result stores. Store format version and migration version are independent. Custom snapshot table and default Jobs table layout are both enrolled if distinct. Downgrade requires settled timers/follow-ups and quiesced writers, preserves preexisting tables and rejects incompatible data. - `Store.Postgres.rebuild_run_headers(repo_or_descriptor)`, `verify_run_headers/1` validate or regenerate projections from imported persisted journals before starting owners. Each root is locked, current lease projection checked, body/revision/time unchanged by repair. Repeat per table. A missing projection is `{:run_header_missing, %{namespace: ns, id: id}}`. Named ETS has in-owner indexes. `Store.Postgres.Maintenance` requires `repo:`. `table: "exagent_snapshots"`, `interval_ms: 5_000` and `max_interval_ms: 60_000`. Bounded pages of 100 per table/store, exponential interval on no deletions and reset after deletion. Sweeps finite tombstones and expired job retirement data while retaining held evidence and permanent seals. Failure event `[:exagent, :store, :postgres, :maintenance_failed]`. ##### Frame binding, lease and effects - `ExAgent.run(agent, input, continuation: config)` takes only `:store`, `:id` (UTF-8), `:durability` (`:ephemeral` or `:durable` matching atomic Store), `:definition`, `:policy`, `:model_ref` (each `%{"id" => id, "version" => version}`), `:model_codec` (`%{dump: fun/1, load: fun/2}`), `:expires_at` (required nil or UTC ms), `:lease_ms` (positive ms), optional `:deadline_at`, `:active_time_limit_ms`, `:max_checkpoint_bytes` (1 byte–8 MiB, defaults to 8 MiB), `:rehydrate_tools` (arity one), candidate `retain_failed_turn: false`. Extra/malformed keys return `:invalid_continuation_configuration`. Store mismatch returns `:unsupported_store_capability`. Server takes binding without `:store` and `:id` (supplies its Store and agent ID) and raises `ArgumentError` for invalid/owned keys. References are `%{version: 1, id: ..., record_id: ..., revision: ..., run_id: ...}` with optional `attempt_id`. - Owner renews lease about halfway through. First renewal can be spread up to an eighth of the lease window before the midpoint, later ones at midpoint. Stop at earlier deadline or expiry. Retry definitely uncommitted renewals only while within the last confirmed horizon. Unconfirmed renewal stops use of the claim. `:continuation_lease_expired` / `:continuation_lease_unconfirmed` carry `hint: :recover_continuation_lease`. `lease_until` is authoritative UTC ms from the Store clock. Recover expired claims explicitly. A pre-provider budget/quota/deadline refusal can leave a claimed record with empty effect list because instructions, preflight, hooks and codecs may already have run. - Persist exact intent before effect, certify result and accepted projection before advancement. Lifecycle includes `:claimed`, `:pending` for approval/deferral, `:ready` after confirmed decisions/results, `:uncertain` when an effect remains open, terminal `:completed`, `:failed`, `:cancelled`, `:expired` and old `:denied` records. Public `get/2` / `list_runs/2` adds `:executing` for claimed intent/callback and `:approved` for ready from a decision or supply. Job, Server and Result each project the stored state. Resume rechecks fresh lease and exact record lifetime, revision, definition and binding. An unknown result keeps intent and unknown accounting. The operator reconciles, links an explicit retry, or cancels under the recorded constraints. - Frame 3 is root agent and durable delegate execution. It supports budgeted correction of a complete malformed tool argument envelope before any tool effect. Frame 10 Composition and Frame 11 Flow use structural step/branch state and fail that model attempt immediately. Unreadable/truncated/non-object/duplicate-visible-key/stock decode failure is fatal in every frame. Frame 10/11 record prepared args, supported hook/guard receipts and model response rejection. Only the live step/branch owner can certify a pre-dispatch admission refusal with verified step cursor, effect evidence and drained workers. A confirmed fatal tool result can close an agent with the existing effect log. Open effects and external deferrals retain recovery work. - For resume, tools must have unique names (`{:duplicate_tool_name, name}`), callable arity (`{:invalid_tool_callable, name}`) and valid controls (`{:invalid_tool_control, name, field}`). `rehydrate_tools.(%{name => schema_hash})` restores only current batch or persisted retry. Retry uses original settings, tool list and message projection. Later requests return to agent/capability inventory and saved run settings. The usual before-request hook can modify each newly dispatched request. Responses after hooks must be JSON-portable (`:invalid_checkpoint_response` before tools). Dump/load failures surface `:model_state_not_persistable` / `:model_state_not_restorable`. - Candidate `retain_failed_turn: true` preserves available failed-root bodies within the record bound for authorized Eval capture. Accepted history rolls back after failure or veto. Withheld output and rejected stream windows keep no rejected bodies. Restart preserves saved evidence. Confirmed new work replaces the prior journal. History reset clears opted-in failed-turn bodies and accepted history where safe. Retention erases journal bodies only after settling evidence. - Guardrail policy and prepared tool-input values are certified in C7. Mismatches can return `:continuation_guardrail_policy_changed`. Ambiguous certification returns `:continuation_guardrail_control_unconfirmed`. Tool outcomes are journaled before post-dispatch checks. The final gate and accepted history share a CAS. A rejected stream retains its control and qualified usage, not rejected contents. A persisted handoff uses the saved authorization/view with fresh binding checks. `:continuation_handoff_control_unconfirmed` requires reading current evidence before recovery. Review/open effect protection applies across the delegation path. ##### Catalogue, reads and approval - `Catalog.new([{ref, agent_or_workflow, binding}, {ref, agent, binding, tools}, ...])`. `Catalog.cast/1 → {:ok, catalog} | :error` accepts the struct. `resolve/2` exact reference or identity. `fingerprint/1` canonical SHA binding over `id:`, `agent:`, `policy:`, `model_ref:`, `model_codec:` and optional `permissions:`, `rehydrate_tools:`. Includes effective model endpoint, tool schemas and relevant options and callback identities. Host version references cover behavior or captures beyond fingerprint evidence. `mix exagent.catalog.lock [--check]` consumes `:exagent_catalog_lock` MFA returning `{active_ref, catalog}` and generated `:exagent_background_catalogs`. It keeps historical binding entries, warns when MCP is unpinned and starts no host processes or dotenv loading. `{:definition_unavailable, ref}` / `{:definition_incompatible, field}` distinguish missing and mismatched bindings. `Continuation.adopt(store, id, catalog, opts)` takes `recover/3` options plus target `definition:`. Only settled agent history with closed tool batches/effects. Preserves snapshot and journal, changes authority for next turn. Stop old owner and reopen using adopted binding. - `Continuation.get(store, id, opts \\ [])` returns metadata with kind, revision/lease, definition/policy/model identity, bounded effect descriptors, retry bindings and unresolved/history evidence. `timeline: true` (candidate) adds bounded run/attempt/effect/child/usage and reconciliation summaries. `timeline: {:redact, {m, f, extra}}` can expose bounded redacted history/args/content. `diagnostics: true` adds internal `:record` (admin writes also `:receipt`). Raw diagnostic layout is private. `list_runs/2` accepts `limit: 50` (1–100), `status:` (including `:executing` for unresolved claimed intent), `after:`. Empty filtered page can have a cursor. `{:store_migration_required, 4}` for missing SQL 4 column/index, `:run_header_missing` for missing projection. `census(store_or_scopes, page_size: 50, include_closed: false)` groups by kind/definition/policy/model/status including unclassified evidence. Inspect unclaimed Jobs separately. - `Continuation.pending(store, id)` reads the authoritative same-revision inbox including `ApprovalRequest` and `DeferredCall`. Delegated entries keep the root reference and `delegation_path` entries `%{parent_run_id: ..., run_id: ..., call_ref: ..., call_id: ..., tool_name: ...}` identifying the leaf. Use its saved definition and the current authorized subject. Both structs include `id, namespace, record_id, revision, expires_at, operation_id, run_id, call_id, call_ref, tool_name, args, definition, delegation_path`. Approval adds `approval_id, payload_hash, permission_rule, decisions`. Deferral adds `deferral_id, deferred_hash, kind, wake_at, meta`. One read's siblings can be decided in any order. Bind each to lifetime, item/hash and its actual CAS revision. - `decide(store, request, decision, opts)` decisions `:approve`, `{:approve, args: map}`, `:deny`, `{:deny, message: text}`, `:cancel`. `actor:` and `authorize: fun/3` required, authorizer returns `{:ok, actor_id}` for permission. `tool:` or `catalog:` binds edit validation, plus optional `diagnostics: true`. `decide(store, id, :cancel | :expire, opts)` uses the record/revision operation binding. Approval changes state only. Denial supplies status `:denied` and message 1–4,096 bytes (default `"The reviewer denied this tool call."`). Cancel is run-wide and omitted from per-call decisions. - Edit is allowed in Frame 3 and a Frame 10/11 Plan checklist with neither before-tool preparation hook nor tool-input guard. Workflow approval of a prepared call dispatches saved args without rerunning preparation. Edit validates matching name/schema, input schema and payload byte cap. Authorizer sees `:edit` with `original_args` and `args`. The original model call remains in history. Errors `:tool_mismatch`, `{:invalid_args, errors}`, `{:permission_rule_changed, %{permission_rule: rule_or_nil}}` or `:unsupported_decision` leave request pending. - Approvals bind an ID and payload hash to a record lifetime. Admin `{:ok, %{status: status, revision: rev, replayed: bool, continuation: ref_or_nil, pending: count}}`. Status/pending describe current record, revision is original mutation on replay. Ref only for exact still-current ready/approved transition. Identical operation can return stored receipt (`replayed: true`). `:stale_request`, `:record_mismatch`, `:decision_conflict`, `:expired` and `:invalid_transition` protect current state. Server decision loss may return `:result_unconfirmed`, so retry the exact operation or inspect `get/2` and `pending/2`. Unknown, missing and duplicate options raise before loading or authorizing. Confirm decision and (when possible) enqueue wake in one Repo transaction. Pruning removes the delivery fence, so retire queue references first. `prune_page/4` uses cutoff, actor and per-record revision checks. Retry changed records from a fresh scan. - Candidate `Judge.Approval.review/3`, `commit/3`, `evidence/2` and `usage/1`. Host authorizes `:review` before classifier/model inference. Stable version and actor IDs are 1–64 bytes in `[A-Za-z0-9_.-]`. Bounded by inbox expiry and review timeout. Approve/deny commit under the exact request binding and actor. Abstention, unknown and failure leave the request pending. Review never bypasses authorization, permissions or the original tool guard. - Administrative `authorize.(actor, operation, target)` accepts only `{:ok, actor_id}` (any other return/exception is `:unauthorized`). It receives actual Store values including `id, record_id, revision, operation_id, run_id, call_id, tool_name, definition, policy, leaf, permission_rule, original_args, args, message, result` (nil as inapplicable), plus `payload` on recovery and optional delegated path. Only bounded actor ID is persisted. Effect `leaf.path` starts with step/branch if any, then ordered delegation names. Root path `[]`. Same path invocations have distinct run IDs. ##### Deferral and reconciliation - External deferral `{:defer, meta}`. Timer `{:defer, meta, kind: :timer, wake_at: utc_ms}`, keyword order arbitrary, declaration `requires_deferral: true` and SQL 7 verified before effect. Deferral and approval each expose exact record/revision binding. Live candidate `on_input: fun/1` can answer MCP requests before answer dispatch (including repeated rounds). With a scoped continuation the MCP call pauses for `supply_result/4` instead. - `supply_result(store, deferred_call, outcome, tool: bound_tool, actor: actor, authorize: auth)` (optional `diagnostics:`) supports `{:succeeded, json_or_tool_content}` and `{:failed | :denied | :not_executed, content}`. MCP candidate `{:input, responses}` validates the saved request and issues the continuation command. A fabricated external outcome for an open input deferral returns `:mcp_input_required`. Local denial or nonexecution can close it. Validate tool identity/deferral hash before recording. Pre-hook content must fit the saved tool-return/checkpoint slot and hard journal bound 8 MiB, else `{:error, {:invalid_result, {:retention_limit_exceeded, details}}}` or `{:error, {:invalid_result, :record_limit}}`, no transition. Resume runs result hooks then result schema. A denied or skipped outcome does not trigger execution. For an elapsed timer the Store supplies `:not_executed` with `"The deferred timer elapsed."` after rechecking its clock. External deferred effects retain their evidence after expire/cancel. Input and timer holds can be safely closed locally. - `recover(store, id, record_id: rid, revision: rev, operation_id: op, actor: actor, authorize: auth)` revokes an expired claim with CAS, leaving current work ready, pending or uncertain as appropriate. Admin operation IDs are UTF-8 1–512 bytes. `reconcile(store, id, effect_id, %{"status" => status, "data" => data}, opts)` is manual confirmed Frame 3 tool evidence (statuses `"succeeded"`, `"tool_error"`, `"validation_error"`, `"denied"`, `"failed"`, `"not_executed"`). Resume applies normal result-constraint and output gates. In workflow steps use matching declared reconciliation or an eligible linked read retry. Confirmation of a schema-mismatched succeeded receipt is a tool error, never a second dispatch. - `reconcile_tool(store, id, effect_id, opts)` takes `recover/3` options plus required `tool:` matching exact persisted leaf (resolve it from trusted catalogue if needed). Recover expired claim first. Authorize `:reconcile_tool` before calling `reconcile.(original_key)` (arity 2 with saved external deferral metadata). The Store rechecks its hash. Accepted outcomes `{:confirmed, %{"status" => ..., "data" => ...}}`, `:not_executed` and `:unknown`. Lookup timeout is tool timeout or 5,000 ms default. `:execution_uncertain` on unknown/timeout/crash, `:invalid_reconciliation` on invalid return, `:no_reconciler` without declared support. Concurrent authorized lookups race one CAS. Repeat same revision, actor and operation ID to get a confirmed receipt without a second lookup. - `retry_effect(store, id, saved_binding, opts)` records a linked attempt. Binding `%{version: 1, record_id: ..., revision: ..., run_id: ..., node_id: ..., effect_id: ..., intent_hash: ...}` from `get/2`. Required `operation_id:`, `actor:`, `authorize:`. Read retries use exact persisted args/key and current permissions/budgets, with prior evidence preserved. Model retry can duplicate provider spend. Model or eligible context-aware write without a reconciler requires `accept_duplicate_risk: true`. Use original `idempotency_key:` or supply new visible ASCII 1–512 bytes only if none was recorded. Invalid binding/key/acceptance `:invalid_effect_retry`. Model uses fresh admission/preflight and either trusted `agent:`/`continuation:` or `catalog:`. Frame 10/11 read retry limited to matching active pending dispatch where the step remains runnable and no fatal/blocked branch prevents it. Frame 11 can retry an active branch's model effect, Frame 10 requires model reconciliation. Prior failed intent and any unknown usage remain recorded. - `reconcile_model(store, id, effect_id, %{response: response, model_data: data, accounting: accounting}, opts)` accepts independently confirmed stopping or tool-call model evidence, with distinct IDs and correct binding/codec. Agent-only optional `:accounting` contains qualified Usage maps for exact ancestor IDs. Workflows derive usage from response. Supply `recover/3` options and either leaf `agent:`/`continuation:` or candidate `catalog:`. Check portable shape, auth, then codec/preflight, including distinct UTF-8 call IDs of 1–512 bytes. Invalid/retired evidence `:invalid_model_reconciliation`, incomplete terminal `{:incomplete_response, finish_reason}`. Frame 10/11 requires explicit authorized recovery. Retried or settled attempts cannot overwrite active results. No automatic repeat of request/tool callbacks from a manually confirmed effect. At most 1,024 operation receipts per run and highest retained operation evidence for 64 previous runs, with superseded IDs fenced. ##### Recovery supervision and subject retention - `Continuation.Recovery.start_link/1` options `store:`, `actor:`, `authorize:` required, optional `name:`, `policy:`, `namespaces: nil` (trusted list or arity-zero resolver for unscoped Store), `on_ready: nil`, `follow_ups: nil`, `interval_ms: 5_000` and `page_size: 50` (1–100). One page/namespace/rotation, indexed by Store clock. Authorized CAS binds record revision and policy version. SQL 6 index supports recovery and SQL 7 timer index. A missing timer index reports `%{reason: :store_migration_required, version: 7}` in `issues` while visiting other candidates. - `Continuation.Recovery.Policy.default/1` v1 defaults to cancellation of model-only uncertainty, preserving original intent and usage. Alternative `model: :leave` / `model: {:retry, resolver}`. At most one linked retry for a declared read. Writes require matching declared reconciler and confirmed result. Resolver receives saved effect and namespace, or use `Catalog`. `Continuation.Recovery.Policy.new(ref, decide)` can select authorized custom operations/model evidence. Recovery revokes lease then selects one mutation per visit. - With `on_ready:`, authorize `:resume` then pass exact ready reference, including a committed initial Frame 3 request before its first claim. Callback `:ok` confirms delivery, `:leave` leaves operator work, error can be retried. Same ready revision may be delivered again. Deduplicate by reference and recheck at `Server.resume/3`. Timer handling authorizes `:wake_timer` before committing local result, then resumes by exact ready reference. Follow-ups use separate `:deliver_follow_up` authority. `Recovery.sweep/2` reports `:applied` and `:replayed` independently of `:woken`, `:left` and `:rejected`, with bounded issues. Telemetry `[:exagent, :continuation, :recovery]` carries status/operation only. - `Retention.inventory(store, id: id, kind: :agent, limit: 50, after: cursor)` pages 1–100 bounded entries from still-retained snapshot/journal, open deferrals (candidate input/timer including UTC wake), run, conversation family and job IDs, offloaded results and provider copies. Cursor binds query and expires on inventory change. Host maps external IDs to authorized stores. - `Retention.erase(store, id, opts)` supports kind `:agent` (default), `:session`, `:composition`, `:flow`, `owners: []` for known remote PIDs, `timeout: 5_000`, `tombstone_ttl: :infinity` or 1–4,294,967,295 ms after deletion confirmation. Ordered receipt keys `snapshot`, `journal`, `admission_receipts`, `event_buffer`, `jobs`, `follow_ups`, `memory`, `result_store`, `eval`, `provider_copies`, `tombstone`. Outcomes `:deleted` (includes absent), `:unsupported`, `{:retained, reason}` and tombstone `:closing` / `:sealed`. Fences new admissions, drains owners, then erases current subject/fork family. Active/uncertain/open external work retains family evidence until settled and permits administrative closure. Open local input/timer waits can be erased. Permanent seals and unconfirmed evidence do not expire. - Dependent keyword options `:jobs`, `:memory`, `:result_store`, candidate `:eval` use ordered `{descriptor, key}` associations. Jobs descriptors `{:volatile, server}` / `{Jobs.Durable, handle}`. Eval descriptor `{Eval.Online.Durable, {handle, evaluator_name, evaluator_version}}`. Dependents wait while primary is retained. Memory/result store also wait on Jobs/eval. `:follow_ups` returns sorted IDs deleted by this invocation, or unsupported/retained fence outcome. Provider refs `%{kind: :file | :response, provider: ..., id: ...}` remain for authorized host deletion, along with supplied `provider_copies:`. Failed reference read is `:provider_inventory_unconfirmed`. [Durability and approvals](durability-and-approvals.md) · [Migration and limits](migration.md) · [Continuation jobs](continuation-jobs.md) #### Coordination and workflows `Composition` and `Flow` in this section mean `Coordination.Composition` and `Coordination.Flow`. ##### Delegation and handoff - `Coordination.delegation_tool(agent_or_builder/2, opts \\ [])` accepts an `ExAgent` or `fn ctx, args -> agent end`. Options `name: "delegate"`, `description:` (derived if omitted), `max_retries: 1`, `prompt_arg: "prompt"` (nonempty string), `result_schema:`, `continuation:`, `permissions:`, `approve:`, `deadline:`, `max_concurrent_requests:`, `estimate_cost:`. Request contains one required string prompt under the selected name. Ancestor permissions/deadline/counters/pricing authority apply to admitted child operations, including failed children. Aggregate usage once. Validation of builder, child policy and capability/tool inventory precedes execution. - `ExAgent.run_child(parent_ctx_or_capability_state, agent, prompt, opts \\ [])` shares scope with the parent, inherits deps unless overridden and fixes ancestry/tracing/observability after caller options. Can pass trusted attachment parts via a host tool. Child progress and history have their own lineage (`child_events: :all` for full projections). Propagate child failure as `{:tool_execution_failed, name, child_reason}` under the error byte cap and use fixed notice in parent history. Visible child `:unknown` can mark delegation outcome unknown. Retention omission does not prove safety to repeat. - In a persisted scope, `run_child/4` without a durable descriptor returns `:continuation_child_descriptor_required` before dispatch, even with a context copy lacking `:continuation`. Durable `delegation_tool/2` binds `:definition`, `:policy`, `:model_ref`, `:model_codec` and trusted loader for dynamic children. Restore the exact child definition, codec and settings at the saved path. Include child entries in the catalogue used by Server, recovery and Doctor. `:execution_uncertain` requires reading/reconciling the root's journal. - Candidate `Handoff.new(id: id, agent: agent, description: description, ...)`. ID ASCII `[A-Za-z0-9_-]{1,48}`, UTF-8 description 1–512 bytes. Max 32 distinct destinations with noncolliding tool names. `max_history_bytes: 65_536`, range 256–1,048,576. `policy: nil` or exact string reference. Default false for each of `share_images:`, `share_audio:`, `share_file_references:`. Generates `transfer_to_` (`Handoff.tool/1`) with optional `note` ≤1,000 characters. Normal permissions, guardrails and approvals (including supported edit) apply. `:multiple_handoffs` before any batch effect when two transfers requested. Normal output-tool precedence with a single transfer. Move after settled nonfatal batch. - Handoff keeps root identity, ledger, deadlines and approvals. New model makes the next request and uses its own output schema and tighter limits. Accumulated validators and tool/output guardrails apply. Terminal `handoff_target` is last destination. `:run_handoff` carries destination, optional predecessor, step and opaque call reference. Later Server turns start with source agent. Canonical history stays with host. Model sees bounded provider-neutral transcript with fixed refusal notices, no tool arguments, provider IDs, hidden reasoning or signatures. Prior turns on the source are text-projected as well. - View capped by destination and run retention, with attachments using at most half the effective view budget (encoded ExAgent term size). Image grant covers images on latest user input and typed returns from this batch. Audio grant covers portable `audio/*` file parts from latest input only, no tool audio or filenames. Render audio as `[audio attachment]`. File reference grant covers current input provider refs, text `[file attachment]`. Each hop requires its own grant and can share only received parts. Fit images then audio then references, skipping oversized items. After request hooks check all effective Fallback leaves for image/audio/reference support, provider and MIME. Unsupported audio `{:unsupported, :handoff_audio_input}`. Host checks destination credential permission and file expiry. Later requests can reuse the admitted attachments. - Persisted transfer is supported for Frame 3 root, Server and Jobs.Durable. Catalogue binds ≤16 levels of destination paths, static tools and matched effective arguments/batch/state/policy/grants. Context overflow recovery, tool rehydration and durable delegation are excluded in a C7 handoff catalogue. Default destination policy is the root policy reference even for nested entries. Composition, Flow and persisted Session chat reject it. Persist the exact bounded view before successor dispatch, use a codec covering each model, and resume successor without recomputing the view. `Continuation.retry_checkpoint/2` for ambiguous checkpoint. Edits can supply `tool: Handoff.tool(destination)`. `:continuation_handoff_catalog_changed` or `:continuation_guardrail_policy_changed` before claim under a changed binding. - Volatile `Session.chat/4` verifies source and destination roster IDs and exact agent refs, checks policy's `handoff/3` at the batch boundary. Current participant changes before successor runs. Event `:session_turn_changed` with `via: :model_handoff`. Finish advancement with `Session.end_turn/3`. ##### Session and shared state - `Session.start_link/1` accepts `:name`, `:policy`, `:participants`, `:session_id`, `:namespace`, `:shared_state`, `:shared_state_codec`, `:observability`, `:pubsub`, `:metadata`, `:continuations`, `:store`, `:event_buffer`. Namespace must match Store scope. Session serializes shared mutations, participant Servers own message histories. `Participant.new(id: id, kind: :human, ref: ref, metadata: %{})` also supports `:agent`. Volatile IDs are any non-nil term with exact identity. With Store, IDs integer or UTF-8 string and metadata portable JSON object. Invalid startup options raise `ArgumentError`. Invalid join returns `:invalid_participants` before mutation. - `Session.child_spec/1` uses `{:exagent_session, session_id}`, `restart: :transient` and fixes a generated ID for restarts of that spec. Supply explicit ID across supervision-tree/VM recreation. Confirmed snapshot determines saved roster/status/policy, does not resolve processes or issue replay events. Startup roster reattaches trusted refs/metadata to matching IDs/kinds. Left stays left and previously added stays present. `join/3` can attach fresh refs. Mismatched kind or configured bound absent member gives `{:restore_failed, :snapshot_roster_mismatch}`. Detach bound member only when continuation is absent and has no local pending evidence, else `:continuation_binding_retained`. - `Session.StateCodec.encode/1` / `decode/1` → `{:ok, state_or_json} | {:error, reason}`. Snapshot structure, identity, roster, policy identity and bound continuations validated before application decode, followed by policy restoration. Host supplies same trusted module. Without codec, shared state is JSON. An encoding failure retains current state in memory and blocks turns with fixed checkpoint diagnostic. Retry `Session.checkpoint/2`. Restart before save uses last confirmed revision. Keep computations pure. - Read `current/2`, `participants/2`, `status/2`, `read_state/2` and `health/2` (identity/emitter/namespace/status/persistence/continuation blockage). Start/join/leave/handoff/pause/resume/close with scope owner and authorized participant. `take_turn(session,id,change,opts)` atomically computes new state and next participant, `{:ok, state, next_id_or_done}`. `update_state/4` keeps turn, `end_turn/3` advances. `SharedState.new(session, participant_id)` for tools, `read/2`, `propose_change/2`. Check expected application version inside a pure update to avoid stale review on the same participant's next turn. `:not_a_participant` versus `:not_your_turn`. `:checkpoint_pending` prevents further mutation. - `TurnPolicy` callbacks `init/1`, `next_participant/2` (returns `{:ok, id, state} | {:done, state}`), `can_act?/3`, optional `participant_joined/2`, `participant_left/2`, `handoff/3` and custom persistence `snapshot/1` / `restore_snapshot/3`. Roster order from initial options, later context roster unordered. Eligibility check can repeat within one turn. Advance cursor in `next_participant/2`. RoundRobin (`:round_robin`) cycles original order. Initiative (`{:initiative, order: ids}`) uses deduped known explicit order then remaining insertion order. Supervisor (`{:supervisor, supervisor: id, workers: ids}`) alternates supervisor then each worker, defaults first and all others, distinct members from initial roster, `workers: []` permits supervisor alone, observers may be excluded, joins append. Explicit `Session.handoff/3` applies policy, preserves schedule cursor and emits `via: :handoff`. - Local subscription before `Session.start/2` sees first event. Empty roster `:no_participants` keeps `:created` with no checkpoint. Policy returns no turn: `{:ok, :done}`, publish `:session_started` then `:session_done`, `payload.persistence` reports save evidence. Done process remains available until close. Volatile `chat/4` takes run options plus `timeout: 5_000` for reply, explicit `message_history` if needed, separate execution `deadline`. Other mutations during chat `:turn_in_progress`. Requires no Store nor bound continuations. - Up to 64 configured continuation bindings. `Session.continuation/3` reads bound participant evidence. `complete_turn/5` requires exact terminal ref, pure state update and same lifetime/run, rechecks after callback and commits once. `reconcile_turn/4` acknowledges exact local diagnostic without callback/advancement. Block `:continuation_pending` until settled. `health.continuation_blocked` has participant and `:completion_required`, `:unavailable`, `:identity_changed`, `:result_not_final` or `:changed_during_callback`. Native participant execution and bound turn transitions are separate calls. - Mutations except chat accept only trailing `:timeout`. Default 5,000 ms, `:infinity` for checkpoint/complete/reconcile. `:unavailable` indicates no destination at send. `:result_unconfirmed` after call exit can mean mutation committed. Check exact state/revision before retry. Linked callers must trap abnormal exits to receive the tuple. Calling the same Session from inside its callback is erroneous. A version-checked retry preserves original expected version. ##### Composition and Flow - Candidate `Composition.new/1` requires `:id`, `:version` (nonempty UTF-8 up to 512 bytes) and 1–255 steps, distinct IDs. Only `kind: :sequence` and `failure_policy: :fail_fast`. Each atom-keyed step `%{id: ..., agent: ..., definition: ..., policy: ..., model_ref: ..., model_codec: %{dump: fun/1, load: fun/2}, output_ref: ...}`. Version refs accept atom/string keys. Optional pair `input: fun/2` and `input_version:` maps initial input and confirmed outputs by step ID. Default first input is root input, successors use previous output. Pure mapper may be invoked again if inputs were unconfirmed. - Candidate `Flow.new/1` requires `id:`, `version:`, `kind: :router | :parallel | :map`. Router/parallel take 1–32 steps without mappers. Router `select: fun/1` and `select_version:` choose declared ID. Map `template: step` and `max_items: 32` (1–32). All take optional `merge: fun/1` and matching `merge_version:`. `max_concurrency: 4` (1–32). `max_result_bytes: 65_536` and `max_branch_result_bytes: 65_536`, each 1–65,536 JSON bytes. Failure policy defaults `:fail_fast` for router/parallel, `:collect` for map. Router/parallel inputs are root input. Merge receives portable ordered outcomes including confirmed failures under collect. Default output is outcomes. Selection/merge pure and checkpointed. Uncertain callback requires explicit recovery. - Map manifest ordered `[%{id: id, input: json}]` (string keys also valid), UTF-8 unique IDs 1–512 bytes, zero items valid, encoded JSON ≤65,536 bytes. String inputs pass verbatim, other JSON values canonical text. Create CAS commits manifest before claim. Resume reads it, preserves item IDs for outcomes/cassette paths. `{:flow_manifest_limit, limit}`, `{:flow_manifest_bytes_limit, 65_536}`, `{:invalid_flow_manifest, :invalid_list | {:duplicate_id, index} | {:invalid_item, index}}` before creation. `step_options` keyed by template ID. - `Composition.run(definition, input, opts)` / `resume(definition, ref, opts)` and Flow equivalents require Writer `:continuation`, allow `:root_options`, `:step_options`, `:delegate_definitions`, `:observability`, `:trace_context`. Wrong entry point raises `ArgumentError`. `binding/1` emits versioned portable identity/fingerprint ≤64 KiB, no code or credentials. `validate_binding/2` errors `:invalid_composition_binding` / `:composition_definition_changed`. Host versions instructions, model/codec, policy, tools, output and callback behavior. Resume needs trusted definition and matching saved bindings, `:continuation_conflict` for stale ref, `{:continuation_not_ready, status}` for blocked state. Resume does not recover claims implicitly. - Root scope options `:usage_limits`, `:permissions`, `:approve`, `:estimate_cost`, `:deadline`, `:max_concurrent_requests`, `:permission_floor`, `:permission_floors`, `:fixture` (re-pass open fixture on resume). `step_options` by declared ID covers `:deps`, `:model_settings`, `:max_payload_bytes`, `:max_history_bytes`, `:on_progress`, `:permissions`, `:approve`, `:estimate_cost`, `:deadline`, `:max_concurrent_requests`, `:max_concurrent_tools`. Same leaf controls from delegate `load/2`, unknown value `:invalid_delegation_definition`. Continuation/input history/streaming/tracing owned by workflow. All direct steps validated before IO, including skipped/completed. Payload/history 1 byte–64 MiB, explicit nil invalid, limits nil inherits or validated `UsageLimits`. Zero request budget stops on admission, negative rejects definition. Dynamic child validated at load without clearing confirmed parent steps. - Structural requests require fixed tools/settings and admitted history. Request projection (dynamic instructions, memory preload, compaction or `on_max_steps: :final` notice) can return `{:unsupported, :composition_request_projection}`. Changed tools/settings (`Tool.Search`, rewriting capability) `{:unsupported, :composition_request_change}`. Observe hooks or identity transform allowed when frame supports the feature. Invalid capability declarations fail agent validation (legacy hooks, stale/conflicting contributed tools). Pre-IO failures can leave claimed state without request intent. - Before a tool batch reserves result copies, error controls and cleanup receipts within the same journal ceiling (8 MiB) and concurrent branch/history reservations. Slot at most 64 KiB and can shrink for payload/history. `{:workflow_tool_batch_checkpoint_limit, required_bytes, limit_bytes}` before dispatch. `max_concurrent_tools` limits leaf dispatch, `max_concurrency` controls overlapping branch reservations. External cancel winning CAS returns `RunError.reason: :cancelled` with confirmed partial, completed steps retained and queued steps `:not_started`. - `Coordination.Result` status `:succeeded | :failed | :paused | :cancelled`. Fields `output`, `output_omitted`, `steps`, `run_id`/`root_run_id`/`attempt_id`, qualified `usage`/`usage_status`/`cost_cents`/`cost_status`, `request_count`/`tool_calls`/`effect_attempts`, `continuation`/`continuation_checkpoint`/`continuation_retention`/`max_checkpoint_bytes`/`historical_uncertainty`, `error_step_id`/`error_phase`. Step `id,index,run_id,input,output,output_name,output_omitted,error,messages,status` (`:not_started | :running | :paused | :succeeded | :failed | :cancelled`). Selected output tool name otherwise nil. Root has no model request or direct message evidence. Inspect step messages for Eval. Missing price gives unknown total with known cost subtotal in `usage.accounting["cost"]["subtotal_cents"]`. Token coverage independent by direction. - Confirmed failure at safe model admission boundaries (limit/deadline/quota/max steps) records failed branch once workers drain and earlier effects settle. Live reason exact (e.g. `{:usage_limit_exceeded, :requests, 0}`), resumed terminal `{:workflow_failed, portable_error}`. `step.error["details"]["reason"]` values `"usage_limit_exceeded"` (includes `"limit"`), `"deadline_exceeded"`, `"rate_limited"`, `"max_steps_exceeded"`. Flow collect runs eligible branches and includes failed nil output. Fail-fast stops new admissions, keeps completed sibling effects. Unknown effect blocks either policy. - Direct Flow structured output veto is certifiable only if all validators declare pure and chain version bound in `output_ref`. `{:retry, message}` consumes ordinary output retry. Certified `{:error, reason}` becomes `{:output_validation_failed, reason}` and branch `"output_validation_failed"` diagnostic with `"validator_reason"` only for ASCII atom `[A-Za-z0-9_.-]{1,64}`. Restore closes certified veto before callbacks. Uncertified veto holds claim even under collect with `hint: :flow_output_veto_requires_pure_validators`. Callback phases `:mapping | :select | :merge` return `{:ok, value} | {:error, reason}` with failure `{:callback_failed, phase, reason}`. Other error phases `:open | :prepare | :execute | :checkpoint`. Resolve a checkpoint retry token before attributing failure to callback. - Completed steps are data. Resume ready before first step, between confirmed steps, or at saved leaf boundary. Use original scope and exact ref after explicit `recover/3`. Use `effect.leaf` for confirmed model evidence or authorized Flow model retry from current allowed branch. Retired original provider attempt remains charged to request count, cost unknown. `Continuation.acknowledge_history(store, id, opts)` uses recovery binding, `evidence_hash:` and `allow_evidence_deletion: true` to authorize later pruning/replacement of that terminal evidence. Cancel/expire can close model-only uncertainty (expire requires elapsed deadline). Terminal resume preserves partial outputs and settled accounting. Started unfinished steps become cancelled. [Coordination](coordination.md) · [Workflow recipes](coordination-recipes.md) #### Testing and evaluation ##### Local scripts, assertions and fixtures - `use ExAgent.Case` passes options to ExUnit and imports helpers. `test_model/1` needs a nonempty proper script list. `assert_output/2` requires succeeded accepted output with `===`, `assert_tool_called/3` supports `times:`, `status:`, `args:`, `assert_usage/2` supports `input:`/`output:` as `{:complete | :partial, n} | {:unknown, nil}` and `quality:`, `assert_cost/2` accepts `{:estimated | :partial, cents} | :unknown`, `assert_event(events, type, predicate \\ fun)` returns first match from Event or stream elements (child predicate receives lineage and element). Assertions work on terminal tuples or structs including partial results. Capture the stream once. - `%Models.Test{system: nil, model_name: nil, label: nil, script: [], index: 0, profile: nil, usage: :unknown}`. Identity defaults `"test"` for model and system (separate quota keys). Default profile supports tools, image input and image tool results. Override any declared capability using a `ModelProfile`, including audio or exact provider/MIME file refs. Test continuation preflight accepts trusted model profile/template for restored index. An adapter missing preflight gives `:model_continuation_preflight_required` and hint for `validate_resume/4`. - Initially empty script uses label or generic text. Nonempty script consumes a text string, `Message.Response`, `{:tool_calls, calls}`, `Test.stream/2` or `fn messages, params -> item end` per request, including corrective retries. Exhaustion/invalid item `%RequestError{provider: :test, reason: exception}`. Shorthand usage from struct, explicit response owns its usage. Optional `%Message.Usage{cost_cents: ...}` with complete simulated price can settle development Budget even with unknown tokens. Ecto Sandbox retains advisory locks for test transaction, bypasses local write queues. Unrelated tests use distinct accounts. Explicit Repo transactions reject Budget writes. - `Models.Test.stream(events, terminal)` accepts UTF-8 `{:text_delta | :commentary_delta | :thinking_delta, chunk}`, `{:tool_call_delta, %{index: nonneg, fragment: utf8, name: optional}}`, `{:usage, usage | :unknown}` cumulative, `{:await, fun/0}` barriers. Terminal `{:finish, %Message.Response{finish_reason: :stop | :tool_calls}}` or `{:error, %RequestError{}}`, including before first chunk. Explicit finish parts authoritative. Latest snapshot supplies usage if terminal omits it, unknown alone leaves a bare error. Dispatched terminal advances index even on retryable error. Buffer ignores previews/barriers, streamed halt skips future barriers. Request tool fragments with `tool_call_deltas: true`. - `Fixture.open(path, opts \\ [])` (cassette v1). `mode: :replay` default, `:record` replaces on successful close, `:record_missing` uses existing entries and records unmatched, prunes unused. `case: Path.basename(path)` valid UTF-8 and matches file. `store_requests: false` fingerprints only, true stores canonical redacted request and allows first changed JSON Pointer diagnostic. `redact_request: fun/1` filters canonical hash in all modes. `redact_response: fun/1` changes complete response delivered to the run, preserves actual finish, clears inherited citation excerpts/ranges before callback. Safe replacements may explicitly set excerpts/ranges. Incomplete finish aborts recording. Failed/incomplete recording retains previous file. - `stream_events: :verbatim` saves exact normalized chunk sequence, including commentary, thinking, tool fragments and cumulative usage. Unary policy returns matching event type or `:drop` and recording run receives the same result. With response redactor, stream policy requires callback, including omission of all fragments carrying sensitive text. Existing `:record_missing` hits keep old events. Absent event array replays synthesized deltas, empty array goes straight to terminal. Each capture ≤4,096 provisional events counted before redaction and ≤1 MiB retained event JSON, file ≤32 MiB, ≤1,024 requests/attempt. Errors `{:fixture_limit, :stream_events | :stream_bytes | :bytes | :interactions}`, `:invalid_fixture_stream_event`, `:fixture_missing`, `:invalid_fixture`, `{:unsupported_fixture_version, v}`. Barrier/transport failure timing belongs to Test scripts. - Match path + canonical request fingerprint + 1-based occurrence of that fingerprint on path, independent of concurrent completion order. Bind model identity/config, messages/instructions, tools, output and settings except timeout. Workflow path includes ID/version/step or manifest item and survives resume with open fixture. `Fixture.with_label/2` on independent roots or siblings (inside tools use `RunContext.fixture/1`). Views share cursor/lifetime. Same-path overlap/indistinguishable admissions `:fixture_ambiguous`, no matching request `:fixture_miss`. Use fresh `:record` after changing paths. `Fixture.close/1` confirms completed write. Offloaded result refs normalized by first occurrence order in tool-return headers, preview/bytes/reader args kept. Built-in `read_result`/`grep_result` resolve live reference by index. Other refs/prose literal. - `tool_stubs: %{offered_name => fun}` or `Testing.with_tool_stubs(fixture, stubs)` returns strict view of same cursor. Per-call validated args or `fun.(ctx, args)`, normal tool result. Missing admitted name `{:tool_execution_failed, name, :missing_tool_stub}`, `%{}` asserts zero dispatch. Normal permission/approval/schema path still runs. Output-function stub receives validated output and optional ctx in that order. Plain schema has no callback. Volatile delegate can substitute callback and child inherits fixture. Durable delegate needs `"delegate" => :delegate` plus matching real descriptor/loader, otherwise `:invalid_delegate_stub`. Host capabilities, approvals, validators, loaders and evaluators still execute. - Use independent scoped Store/record/definition per durable test. Re-pass fixture on resume (`root_options` for workflows). Strict inventory and trusted policy jointly bind reserved `exagent.strict_tools` reference. Changed or omitted inventory rejects restore. Observe actual tool admissions/effects and checkpoint writes rather than time sleeps. Local verification covers runtime contracts. Real endpoints, PostgreSQL, MCP, reconnect/delivery and exporter ingestion use explicitly selected external tests (ExUnit `:integration` exclude/only/include). ##### Case capture, scenarios and simulators - `Eval.Case.new(name, input, expected: ..., metadata: ..., run_opts: ..., version: ...)`, unique binary name. `to_map/1` / `from_map/1` (also `ExAgent.Case`) portable case v1 omits execution options. Schema rejects invalid/unsupported version. Candidate `Eval.Case.from_run(source, opts)` accepts settled run/stream terminal, trusted C7 read or authorized Online sample. Required `name:` and `redact: fun/2` with field/value (`:input | :expected | :output`) and `{:ok, replacement} | :drop`. Options `input:`, `expected:`, `version:`. Input valid prompt, outputs JSON. Source/status and observed replacement in metadata. Provide prompt if missing. C7 diagnostic accepted display can be text-encoded structured output. No receipt, callback, transcript or model is saved. Errors `:missing_input`, `:unconfirmed_terminal`, `{:redaction_failed, field}`, `{:unsupported, :continuation_workflow}`. - Candidate `Eval.Capture.from_run(details, test_agent, opts)` accepts authorized `Continuation.get(..., diagnostics: true)` for settled root. Required `name:`, `suite:`, `redact:`. Optional `dir: "evals/fixtures"`, `run_opts:`, `input:`, `expected:`, `version:`. Redact model text/name/args/result/denial alongside case fields. Synthetic UTF-8 prompt and prefix allowed. Omit provider refs, reasoning, citations, reviewer identity and raw requests. Uses isolated ETS, TestModel, strict substitutions, actual test hooks/validators. `:completed` or settled `:failed | :denied | :cancelled | :expired` if replayable (failed bodies need candidate `retain_failed_turn: true`). Captures per-call root approval and reproducible guard veto, fatal tool gets `:captured_tool_failure`. Reject resolved deferrals, nested runs, workflows and unsettled effects. `{:capture_body_unavailable, body, cause}` for missing evidence. Emit paired `case.json` (≤8 MiB) and `fixture.json` without replacing an existing pair. Candidate `mix exagent.eval.capture --suite NAME --run ID [--fixtures DIR]` uses `Eval.Suite.capture/1` for authorized lookup. Config/capture failure exit 2. - Candidate `Eval.Scenario.new(turns, max_turns: 16, reviewer: [actor: actor, authorize: fun/3])`. 1 through cap, UTF-8 strings or `{prompt, actions}`. Next turn inherits confirmed history/model. Actions in order `{:approve | :deny, selector}`, `{:deny, selector, text}`, `{:edit, selector, map}`, `:resume`. Selector name or `{name, call_id}`. Requires host reviewer for actions and scoped `run_opts[:continuation]` without ID. Fresh ID per user turn/repeat/replay. Root approvals only, first action uses exact paused revision, later actions bind same batch. Resume consumes ready ref. Script can end paused. Trajectory includes prompt, actions, IDs, final status/output, new messages, qualified usage, counts/effect attempts. One timeout/repeat/comparison observation covers all turns, completed turns' subtotals survive an incomplete turn, price stays unknown. Resumed usage counted once. - Candidate `Eval.Simulator.new/1` requires `model:` and nonblank UTF-8 `persona:`, `objective:`, `stop_when:` (each ≤4,096 bytes). `max_turns: 8`, `model_settings:` defaults 256 output tokens, `usage_limits: %UsageLimits{}`, `estimate_cost:`, `allow_live: false`. `Eval.Scenario.simulated/1` drives one bounded simulator request per user decision, first prompt from simulator, sees recent exchanges, `"[STOP]"` signal or cap/pause stops. No reviewer actions. Separate simulator ledger limits reduce further requests using observed usage. No fixture requires explicit allow-live. Replay records both roles. `outcome.simulation.stop` and separate coverage/accounting available. ##### Evals, reports and gates - `Eval.evaluator(name, fun/1, threshold: 1.0, model: ..., version: ...)`. Score boolean, 0–1, `:skip`, pairs with optional reason text, triples with one/batch usage/result/error, `{:error, reason}` or usage triple. Invalid return/error/timeout yields synthetic failure score 0 irrespective of threshold. A version is non-secret UTF-8 1–512 bytes, required for verified opaque evaluator data and Online identity. Declared `model:` resolves at construction. Absent usage/exception/timeout leaves grading unknown. Report stores grading separately and can warn `{:judge_same_model, name}`. - `Eval.run(target, cases, opts \\ []) → %Eval.Report{}`. Target `ExAgent` or `fun.(input, merged_run_opts)`, success with `%{output: value}` and `new_messages:` for evidence. `evaluators: []`, `concurrency: 4`, `timeout: 120_000`, `evaluator_timeout: 120_000`, `repeat: 1`, `fixtures:` (requires `dir:` and accepts cassette options), `run_opts:`. Timeout ranges 1–4,294,967,295 ms. Each grader budget covers all criteria for one attempt and excludes target duration. Validate all cases, unique case/evaluator names, effective agent run options before executing. Case opts override suite. Grade after target runs and release dropped retained fields. Exceptions/exits/throws produce bounded failures. - `Eval.equals/1` exact expected (trim true, case-sensitive true, optional Unicode case-folding), `contains/1` fraction of nonempty string/number terms (trim true and case-sensitive false), `matches/2` regex. Nil expected skips equals/contains. `tool_called(name, opts)` counts emitted calls, malformed included if no args filter. Options `:name`, `:times` exact nonnegative or nil for presence, `:status` first matching tool return in same batch, `:args` (original decoded map, absent args `%{}`), `:version`, candidate `:step`. Retry prompts consume reply without status and user part closes batch. Omitted parts give lower bound. Sufficient evidence for presence/exceeded count, otherwise error. Workflow requires explicit direct step ID and retained messages. Unstarted has zero, missing/ambiguous or invalid history errors even for `times: 0`. Nested delegate evidence belongs to child. - `tool_arguments(name: ..., threshold: 1.0, step: ...)` pairs by tool name/occurrence with `case.metadata["expected_tool_calls"]` entries `%{"tool" => name, "args" => map}`. Absent expectation skips, empty asserts no calls, exclude output submissions. Exact field 1, normalized/trimmed/case-folded or equal JSON number 0.5, missing/extra/wrong/invalid 0. Argument-free matching call earns 1. Reason names fields/outcomes without values. Insufficient retained parts or Online argument-free observations fail grading. - `Eval.judge/1` requires `model:`, `criteria:`. Options `model_settings:`, `max_transcript_bytes: 16_000` (min 1,024), `step:`, `name: "judge"`, `reasoning: true`, `version:`. Bounded transcript/answer/task/expected, step evidence for workflow, entire script for scenario. Reasoning mode final nonempty line `VERDICT: PASS`/`FAIL` with case/emphasis/final period allowed, label-first with reasoning false. Failed format can get reminder. Reviewer process name `"exagent.eval.judge"`. Count all reviewer runs/cost independent of target. `Eval.calibration(report, evaluator_name, labels)` case or `{case, attempt}` boolean labels. Metrics with 95% `Beta(1 + hits, 1 + misses)` bounds. - Pass requires no target/grading error, at least one emitted grade and all non-abstaining criteria pass. Wrong scored answer adds coverage. All abstentions or no graders give no numeric evidence and `passed: false`. Error gets synthetic 0 and increments errors without coverage. Report summary includes target errors, grading errors, paused and all-skipped runs, scored/total coverage, per-evaluator evidence and separate target, grading and simulation usage. Token directions, requests/tool calls have complete/partial/unknown coverage. Numeric unknown placeholder 0 in aggregate is missing data. Total `cost_cents` only if all priced, `known_cost_cents` subtotal. Repeated paused attempts need distinct C7 IDs and same-run resume after reporting leaves the original score fixed. - Reliability at shared `k` across repeats draws without replacement: `pass_at_k = 1 - choose(n-c,k)/choose(n,k)`, `pass_all_k = choose(c,k)/choose(n,k)` for `c` successes, with per-case and suite means. `Eval.Report.compare/2` matches same case name and verified digest of input/expected/metadata/opts/timeouts/evaluators/scenario, compares different target definitions and repeats. Version opaque callbacks/options. Reports `added`, `removed`, `changed_cases`, `unverified_cases`, `ungraded_cases`, `comparable_case_count`, observed overall and equally weighted shared-case rate delta. Paired evidence includes target errors as failures, excludes attempts with grading errors or only abstentions/no evaluators. - `compare/2` point lists `regressed`/`improved` plus `"beta_paired_v1"`: independent `Beta(1+c,1+n-c)` per case and report, 95% interval for mean paired change, `:regressed` below 0, `:improved` above 0, `:inconclusive` otherwise. `:no_common_cases` / `:no_comparable_cases` give nil interval. `significant_regressions` entries with probability ≥0.95, exact per-case probabilities (1/1 → 0/1 gives 5/6, 3/3 → 0/3 gives 69/70). Evidence is for the fixed suite. - `Eval.Suite` uses named `target/1`, `cases/0`, `evaluators/0`, optional `options/0`, candidate `labels/0` and `capture/1`. `mix exagent.eval` discovers `evals/**/*_eval.exs`. Switches `--suite NAME`, `--only CASE`, `--repeat N`, `--fixtures DIR` (default `evals/fixtures`), one of `--record`/`--record-missing`/`--live` (replay default), `--allow-ci-record`, `--save PATH`, `--output PATH`, `--include-content`, `--baseline PATH`, `--min-pass-rate FLOAT`, `--min-pass-all FLOAT`, `--[no-]fail-on-regression`, `--format text|json|junit`. Duplicates/unknown/positionals exit 2. Distinct baselines/output/save include symlink/hardlink collisions. Replay checks cassettes before attempts, denies live dispatch VM-wide including nested graders, default allow local Test/Fallback adapters. Record in `CI=true` requires explicit override. Simulated suites and pass-all gate require replay in CI. - Exit 0 gates pass, 1 enabled threshold not met, regressed comparable verdict or significant regression, 2 missing evidence for enabled gate, config/path/fixture/match/write error or live dispatch denied by replay guard. Default min pass-rate 1.0 with neither threshold. Pass-all uses largest shared k. `--no-fail-on-regression` disables baseline gate. Matching diagnostics include case/attempt in stderr (and portable text/JUnit). Target JSON `error` or grader `diagnostic`. JUnit abstentions skip, grader errors fail, gate verdict is exit status. JSON/JUnit stdout only report unless `--output`, host/logs/diagnostics stderr. JSON v1 persistent attempts/provenance/reliability, recomputes summary, repeated key `{:duplicate_attempt, {case, attempt}}`. `Eval.Report.to_map/2` returns `{:ok, map}` and content opt-in (`:output_preview`, `:reasons`). Content-free output drops previews/reasons. Identifiers are still visible. ##### Online and durable evaluation - `Eval.Online.start_link/1` requires `scope:` and `evaluator:`, optional `version:` (criterion version), `name:`, `sample_rate: 0.01`, `capacity: 64` including active, `seen_capacity: 4_096`, `timeout_ms: 5_000`, `judge_max_tokens: 512`, `content: false`, `max_content_bytes: 16_384` combined, `store: nil`, `grading_backend: :memory`, `otel: nil`. `handle/1` local ETS handle renewed on restart. `offer(handle, terminal, opts)` checks free slot without owner/Store call, `{:ok, :enqueued | :not_sampled | :duplicate}` or `{:error, :full | :unconfirmed_terminal | reason}`. Background grading receives bounded view and never resumes target or runs target tools. - Authorized terminal forms `{:run, outcome}` (stream result → `{:ok, result}`), `{:server, outcome_or_confirmed_event_or_cancelled_receipt}`, `{:session, chat_outcome}` or `{:session, turn_ack, outcome_or_continuation}`, `{:continuation, exact_ref}`. C7 reads authorized Store and exact lifetime/run/revision with settled effects. Confirmed `:cancelled_before_start` receipt deduped with event by run ID. Active cancel needs confirmed `:server_request_cancelled` (persistence and `payload.status: :cancelled`), partial active caller only proves interruption. Post-checkpoint claim can use original confirmed result. Scope-check Server/Store and supplied Events, host binds native results/unscoped stop telemetry. - Offer opts `content: %{input: ..., output: ..., expected: ..., transcript: ...}` explicitly approved UTF-8 with opt-in, `tools: {:complete | :partial, events}` first 64 observations, `trace_context:`, `response_id:` authorized. Tools use name, status, opaque call ref. C7 journal partial proof deduped by same invocation ref. Exact count requires sufficient evidence. No online args or step predicates. Built-in judge skips absent approved output, one reviewer attempt/time/output limit (Fallback may make several provider attempts). Fixed grading error label and nil score, unknown usage nil. - `:otel` callback receives OTLP/HTTP JSON log `gen_ai.evaluation.result` with optional trace/span from evaluated context, score/error, safe tool evidence, qualified grading, evaluator/version and independent integer `exagent.evaluation.projection_version: 1`. Add resource/service name in exporter/Collector. Capture context inside operation, correlate Server root stop to persistence by run ID. Return `:ok` on acknowledged dispatch. `[:exagent, :eval, :online, :result | :delivery | :discard]` correlates evaluation ID. Delivery status `:dispatched` or `:delivery_unconfirmed`, measurements count 1 for discard/delivery, native duration/system time for results. A crash before export can get one fallback report within export deadline. Receiver HTTP 200 alone may include OTLP partial success. - Candidate `grading_backend: {:durable, jobs, expires_at_ms}` with trusted queue scope matching Jobs namespace, absolute expiry, Oban plus Jobs export-marker migration. Dedicated worker resolves matching name/version via `Eval.Online.Durable.resolve(namespace, ref, evaluator, policy, scoring_opts)`. Match content/byte/time/token config on both sides. One outstanding grading job per worker/namespace, READ COMMITTED. Stable identity scope/run/evaluator/version, first reservation fixes job ID, payload and deadline. Re-offer same receipt after local queue loss. Expired/tombstoned reservation forbids another job. Full queue can discard. - Confirmed portable job result feeds export. Competing collectors require one committed export claim, `result_export` `"sending"` before telemetry/optional OTLP, `"dispatched"` after acknowledgement. Identity and `exagent.evaluation.id` stable. Existing export mark fences old duplicate reservations, otherwise follow earliest reserved deadline. Ambiguous/failed emission leaves claim, no automatic replay, `:delivery_unconfirmed` or `:job_failed` discard as appropriate. Bounded local dedupe supplements durable fence. Subject erasure uses `Retention.erase/3` with authorized Eval descriptor. [Testing and evaluation](testing.md) · [External boundary support](status.md) #### Observability and telemetry ##### Host telemetry and metrics All paths below prefixed with `[:exagent]`. `system_time` is native-unit Unix time (`DateTime.from_unix!(time, :native)`). `duration` is monotonic native elapsed time. Event metadata is content-free. Run lineage is `run_id, root_run_id, parent_run_id, attempt_id`. Run and logical-request `namespace` is UTF-8 ≤512 bytes or nil. Pair emissions by opaque `telemetry_span_context` (fresh for concurrent calls and resume). Keep high-cardinality IDs outside metric tags. | Suffix | Boundary, measurements and selected metadata | | --- | --- | | `:run, :start / :stop / :exception` | Start system time. Terminal duration, `agent` and lineage. Stop `status, usage, steps`. Exception bounded `reason: %{type: ..., provider: ..., status: ...}` when known. Both carry usage/cost evidence. Stop includes confirmed pause (`:paused`) and success (`:succeeded`). Failed pause save is exception. Counts/usage cumulative across attempts. | | `:model, :request, :start / :stop / :exception` | One admitted logical request, including retry or replay. `agent, run_id, root_run_id, model_request_id, step, model, provider, stream, fixture`. Terminal `usage_status`, `usage_quality`, `cost_status`, estimated `cost_cents` or `cost_subtotal_cents`. Stop `finish_reason`, exception bounded `reason`. Incomplete provider finish is a stop while run fails `{:incomplete_response, finish}`. Known `input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens` appear only as evidenced. | | `:model, :attempt, :start / :stop` | Physical callback entry and return/cleanup per direct dispatch or Fallback leaf/retry. Join `telemetry_span_context` to span `exagent.attempt.id` and logical `model_request_id`. `conversation_compacted` candidate true with proof, else nil, `operation: "chat"`, model/provider labels ≤256 bytes or `"other"`, `source: :test` or `:adapter`, `fixture: :record` or nil. Stop includes duration, usage/cost coverage and available token counts, outcome `:succeeded / :failed / :incomplete / :cancelled`, finish and HTTP status. Kill may orphan start. Quota/preflight skips and replay produce zero attempts. A callback can fail before network IO. | | `:model, :retry` | Fallback scheduled `attempt, delay_ms` and `model, status, fallback`. | | `:model, :reasoning_prefix, :reset` | Candidate `dropped_blocks`, model/provider/reasons plus logical IDs when available. Reasons `:system_changed`, `:tools_changed`, `:output_format_changed`, `:history_changed`, `:reasoning_chain_changed`, `:unverified_history`, `:unreplayable_reasoning`, `:projection_removed`, `:foreign_history`, `:provider_prefix_mismatch`. Capability plus leaf can each report. Preflight/replay emit no adapter reset. | | `:tool, :stop` | Duration, agent/run, declared name or `"unknown_tool"`, return status/success, opaque `call_ref`, `duration_measured` true for worker time and false for elapsed batch when no worker report. Candidate CodeMode adds `program_call_ref, program_step` (1-based), `effect`. | | `:embeddings, :request, :start / :stop` and `:media, :request, :start / :stop` | Admitted embedding/rerank or media operation with provider/model, run/call ref, `telemetry_span_context` (span `exagent.request_id`). Embeddings includes `input_items` and available `rerank_search_units`. Stop duration, outcome, qualified usage/cost, known token/media counts and HTTP status. No text/vectors/documents/scores/media bytes/URLs. | | `:guardrail, :tripped` / `:output, :partial` / `:judge, :verdict` | Count 1, respectively `name, stage, run_id, root_run_id, attempt_id` / `mode` / `kind, verdict`. | | `:rate_limiter, :wait / :reject / :cooldown / :settlement_retry` | Count 1 and known `wait_ms` (settlement retry `delay_ms`, zero for single late report). Configured quota `key`. | | `:usage_limits, :budget, :settlement` | Count 1, available reservation, full charge or subtotal. `reservation_id, labels, source` (`:runtime / :reconciliation`), `coverage` (`:available / :partial / :unavailable`), `outcome` (`:priced / :unused / :held`). Duplicate reconciliation may repeat ID. Append `:unconfirmed` for failed settlement retry, `%{count: 1}` and empty metadata. | | `:usage_limits, :budget, :threshold` | Count 1, charged/limit cents, `window_start` UTC ms, integer percent `threshold`, ETS account name/PG scope digest. Best effort, one claim per window. | | `:conversations, :activation` | Count 1, `status` `:waiting / :queue_full / :capacity / :wait_timeout / :factory_timeout / :start_unconfirmed / :reconciled`. | | `:job, :start / :stop` | Volatile, job ID/name, start system time, stop duration and status. Duration admission to Jobs owner processing completion includes start handlers and mailbox. Durable delivery timing from `[:oban, :job, :stop]` / `:exception` and true job/notice state via `Jobs.Durable.status/2`. | | `:memory, :command` / `:compaction, :stop` | Memory count 1, command/status (including `:preload`). Compaction duration, input/output message counts, known estimated tokens saved, agent/run/step/compactor/status/error. `:compacted / :no_change / :error`. Error keeps incoming projection. | | `:continuation, :recovery` / `:store, :postgres, :maintenance_failed` / `:chat, :checkpoint_wait_expired` | Count 1, respectively operation/status, Repo/table/content-free error type, or generated resume job ID after checkpoint wait cancellation. | | `:mcp, :catalogue, :drift` / `:mcp, :validation_error` | Added/removed/changed counts and revision/drift rule. Validation count and `rewritten`, no values. | | `:eval, :online, :result / :delivery / :discard` | Projection v1, scope/run/source/criterion/version and correlated ID for result/delivery. Result `count, duration, system_time` plus run status, event name, trace, optional response ID, safe tools/completeness and label/score/error/qualified grading. Delivery/discard count 1 with status/reason. | | `:observability, :failure / :content_dropped / :processor` | Fixed stage/count or bounded exporter processor diagnostics, no raw exporter errors. | - `ExAgent.Telemetry.metrics/0` available when compiled with optional `telemetry_metrics ~> 1.1`. Phoenix `live_dashboard ..., metrics: ExAgent.Telemetry` or append definitions. Duration summaries ms. Request/attempt stops token sums quality/coverage, per-tool measurement flag, guardrail/structured preview counters, compaction estimated tokens, quota wait/backoff ms grouped by configured quota key. Fixed tags exclude IDs, prompt/tool content, agent and model names (quota key may encode provider/model). Run/request error tags retain known top-level diagnostic type and collapse custom types to `"other"`. Includes `"store_migration_required"`, `"rate_limiter_migration_required"`, `"continuation_handoff_catalog_changed"`, `"tool_requires_deferral"`. LiveDashboard reports only the chosen series and cannot infer missing terminal/effect evidence. - Logical request and attempt series overlap. One Fallback logical request with 3 dispatched leaves emits 6 physical attempt events. Use request for admission/qualified aggregate, attempt for callback latency/usage, and ReqLLM timing for streaming. Cost estimated and subtotal qualified. Unknown counters absent. Handler runs synchronously. Use finite aggregators, no unbounded mailbox fanout. Resume cumulative usage is not additive across attempts or again with child totals. ##### OpenTelemetry, privacy and ReqLLM bridge - Host owns SDK, sampler, processors, resource and exporter. API `~> 1.5.0`, SDK `~> 1.7.0`, exporter `~> 1.11.0` are the documented native setup. API without SDK is no-op. `ExAgent.Observability.OpenTelemetry.new/1` options `content: false`, `redact: nil` (arity 2 required with content), `max_content_bytes: 4_096` (1–65,536), `max_content_input_bytes: 65_536` (1–1,048,576), `tracer: nil` (native tuple for explicit tracer), candidate `metrics: false`, `link_continuations: false`, candidate `service_tier: false`. Pass `observability:` to agent/run/Server/Session/workflow. Default tracer resolves current provider per span. Refresh explicit named tracer after recreating provider. Server run span includes checkpoint and ends per turn/attempt. - Profile `exagent.gen_ai.v3` and `exagent.gen_ai.revision` `d0e74ba6c48bcc4ded473b1828a8212f06b23753` (GenAI v0.1.0). Spans `invoke_agent {agent}`, `invoke_workflow {definition_id}`, `chat {model}`, `execute_tool {tool}`, `plan {agent}`, `search_memory / create_memory / upsert_memory / update_memory / delete_memory`. Memory count known files (preload before prompt cap). Paths/scopes private. Internal delegation/compactor/checkpoint spans `exagent.*`. `embeddings {model}`, `exagent.rerank {model}`, `exagent.media.{operation} {model}` include bounded metadata with qualified dimensions. CodeMode child span attrs `exagent.tool.program_call_ref`, `exagent.tool.program_step`, `exagent.tool.effect`. Invocation `exagent.call_ref` matches Event and pending records. - Direct client span ends before after-request hook/tool IO. Fallback has parent `exagent.model_request` and leaf client spans. Replay uses internal model request span. `exagent.attempt.dispatched=true` only on callback entry, false if redactor exhausts deadline before dispatch. `gen_ai.conversation.compacted=true` only if proved. `gen_ai.usage.*` known client dimensions, `exagent.usage.*` logical/inclusive scope totals. Chat/OpenRouter/Responses input includes cached tokens. Anthropic adds cache input read/write when both reported. Unknown semantic profile omits GenAI total. Qualify/usage evidence retains reported figure separately. Normalize stock counters only with presence evidence or positive cache. Reasoning output subset is excluded from any additive total. Estimated cents and partial subtotals `exagent.cost.*` reuse ledger. OpenRouter reported charge can be complete. Native service-tier opt-in exports known response tier. - `capture_context/0` and `with_context/2` propagate span context/config only and restore previous OTel/Logger span keys after callback. Explicit `trace_context:` across application task boundaries. Server captures at queue admission, lazy stream at enumeration absent override. SDK and per-operation watcher give idempotent span close on worker death, without recovering missing usage. SDK/VM failure may lose spans. `link_continuations: true` on both attempts retains one fixed-width lowercase hex trace/span pair at confirmed recording pause until next claim/cancel/expiry, with no actor/payload/token. Resume creates new span with link to pause and parent from current context. Same run/record ID, new attempt ID. Unavailable/legacy/no-room pause link falls back to ID correlation. - Opt-in `redact.(field, data) → {:ok, replacement} | :drop`. Field/attribute suffix under `exagent.content.*` is `system_instructions` (parts), `input_messages`/`output_messages` (messages), `tool_arguments`/`tool_result` (JSON effective args/visible success). Messages `%{"role" => role, "parts" => parts}`, parts type `text` with `content`, `tool_call` with `id/name/arguments`, `tool_call_response` with `id/response`. Bounded plain data only, no hidden reasoning, structs or opaque values. Oversize before callback and invalid shape/oversize JSON after callback drop whole field, with `content_dropped`. Max three attribute fields per span, redacted JSON string (Erlang scalar/array attrs). Withheld result retains effect status and `exagent.tool.content_withheld=true`. Synchronous host redactor time counts. Exporter/log handlers have independent privacy boundaries. - `Observability.ReqLLM.attach(opts \\ [])` options `:content`, `:langfuse`, `:metrics`. Single integrated adapter after SDK configured, foreign bridge gives `:conflicting_req_llm_bridge` and observed model call `{:observability_conflict, :req_llm_bridge}` before IO. Enrich active native model/leaf with bounded `exagent.req_llm.request_id`, `gen_ai.response.id` (bridge source), response model, server port/address, max tokens, top-k, stream flag and first chunk seconds. ExAgent retains status/accounting/content authority. Standalone ReqLLM spans remain and optional content uses `exagent.req_llm.content.*` namespace. `detach/0` and `prune_stale_spans/1` only affect this handler. - Metadata-only `telemetry: [payloads: :none]` in ReqLLM still leaves `[:req_llm, :request, :exception]` upstream errors (body/headers observed). ReqLLM 1.31.0's streaming failure module (`{ReqLLM.Streaming.Failure, _, _}` MFA) can log them. App per-handler OTP Logger filter for that MFA or use `Logger.put_module_level(..., :error | :none)` and keep `config :req_llm, debug: true` / `REQ_LLM_DEBUG=1` off for content-free logs. Finch request/send/recv/queue telemetry can include static MCP/other request headers and response headers/trailers. `:headers_provider` uses Mint path, so Finch does not receive those dynamic credentials. - Candidate native metric opt-in `[models: [], agents: [], tools: []]` each up to 32 unique labels and empty default. Model unknown → `"other"`, unlisted agent/tool omitted. Experimental OTel API and SDK `~> 0.6.0` with host readers. Native meter `:exagent` measures `gen_ai.invoke_agent.duration`, `gen_ai.execute_tool.duration`, `gen_ai.client.inference.duration`, `gen_ai.client.inference.operation.input_tokens`/`output_tokens`, `gen_ai.client.embeddings.duration`/`operation.input_tokens`. Seconds and `{token}`, failed dispatch duration, qualified evidenced token totals only (including evidenced zeros). No SDK drops measurements. No retained instrument cache after SDK restart. - Candidate `Observability.ReqLLM.Metrics` via `ReqLLM.attach(metrics: [models: labels])` accepts 1–32 unique models, false default. `:exagent_req_llm` meter uses inference/embedding duration and positive normalized token counters, suppressed when native attempt metrics already account for request. Stream `gen_ai.client.inference.time_to_first_chunk` and `exagent.req_llm.stream.estimated_seconds_per_output_token` supplement native series. Stock timing divides by tokens and lacks per-chunk intervals. Bounded dimensions and error code labels. - Candidate `Observability.ReqLLM.Maintenance.start_link(ttl_ms: ..., interval_ms: ..., name: ...)` after attach. Positive TTL longer than allowed standalone and agent streams/retries, interval 1–4,294,967,295 ms, local atom name defaults module. One age-based pass per interval, dormant if handler absent. `stats/0` default instance `ticks, passes, pruned_entries, last_pruned_entries, status` (`:waiting / :active / :detached`) or `:unavailable` at 5 s. Never closes spans. Span watcher owns that. Tracking scan/table allocations lack a fixed byte cap. No automatic child installation. ##### Bounded export, transport and measurement - `BoundedProcessor` SDK extension config map requires `exporter: {Module, opts}`. Defaults `name: __MODULE__` (atom, string/charlist 1–256), `resource: nil` (SDK detector), `max_queue_size: 2_048` (1–65,536 queued + in flight), `max_export_batch_size: 256` (1..queue), `scheduled_delay_ms: 1_000`, `exporting_timeout_ms: 2_000` (both 1–60,000), `shutdown_timeout_ms: 1_000` (1–4,000), `max_exporter_restarts: :infinity` or nonnegative. Zero allows initial worker only. One worker, drop saturation/failed batch without implicit retry, restart exhaustion keeps instance unavailable and discards queue. Slot count doesn't limit arbitrary bytes or guarantee order. Node-qualified stable registration. Errors `:sdk_unavailable` / `:invalid_config`. Separate processor keys for multiple routes. SDK 1.7 short-circuits following processors when one drops. Configure ordering. - `stats/1` scalar counters/state/gauges, `accepted` enqueue, `exported` callback success, `retained` queue/in-flight and drop/loss/restart counters. `force_flush/1` asynchronous request. `shutdown(config, timeout \\ 5_000)` monotonic caller wait `:infinity` or 0–4,294,967,295 ms. Discards queued/in-flight and returns final snapshot after bounded stop. Invalid wait raises before send. `:unavailable` no instance, `:result_unconfirmed` after lost reply. Lifecycle replacement resets counters. SDK child may restart. Confirm application drain barrier before stopping when delivery is required. - Native HTTP/protobuf full trace path `otlp_traces_endpoint`, base `otlp_endpoint` appends `/v1/traces`. Headers via exporter env/app configuration, `OTEL_EXPORTER_OTLP_TRACES_HEADERS` comma-separated and `OTEL_SERVICE_NAME` resource. Keep secrets out of SDK/OTP bootstrap args that supervisors retain or log. Native HTTP timeout/shutdown can leave profiles/atoms/sockets. HTTP 2xx callback can discard OTLP `partial_success` evidence. Verification distinguishes enqueue, callback, peer status and durable backend ingestion. Example trace endpoints are Langfuse EU `https://cloud.langfuse.com/api/public/otel/v1/traces` (Basic + `x-langfuse-ingestion-version=4`) and Opik `https://www.comet.com/opik/api/v1/private/otel/v1/traces` (Authorization, projectName, Comet-Workspace). Use separate metric route. - Optional Linux isolated batch VM recipe `examples/otlp_transport/isolated_exporter.ex` + `vm_launcher.py` with HTTP `vm_http_worker.exs` or gRPC `vm_worker.exs`. Trusted physical BEAM code path and official APIs. Shared atomic gate one VM, 1–8 spans, 65,536 uncompressed ETF bytes, 4,096-byte receipts. Deadline 100–5,000 ms (2,000 default), owner wait deadline +1,500 ms, e.g. processor export timeout 4,000 ms with 2,000 deadline. Gate reopens only on verified child-group teardown, otherwise future batches drop. Resource cleanup targets only owned group and disposable VM. ETF input trusted/local. HTTP options endpoint/headers/compression/ssl, stock body acceptance unknown. gRPC uses public `otel_otlp_traces:to_proto/2` and generated `export/3`, optional trusted `request_profile.project/1` for bounded attribute remap (Opik example up to 64 attrs, preserves IDs/status/time). Partial response fails callback with known accepted/rejected counts when available. No automatic replay. - Optional Collector `examples/otlp_transport/collector.py` plus pinned official core 0.162.0 validated SHA256 on Linux amd64. App-owned loopback gRPC/metrics ports, packet4 JSON ready/`STOP\n`, explicit environment and private headers. Synchronous gRPC→HTTP pipeline: no async batching/queue/retry. Collector callback success can still have destination partial rejection, inspect `dropped_spans` warn logs (and metrics) beyond `sent_spans`. Transport timeout means acceptance unknown. Lifetime 100–30,000 ms (10,000 default), readiness 3 s, log cap 1 MiB ends collector, gRPC 1 MiB/one stream per connection. Owner-pipe closure/deadline/SIGTERM cleanup bounded to owned process group. Uncatchable owner kill requires external supervision. Limits are per transport/instance and post-conversion, no server-wide memory bound for unrelated traffic. [Isolated exporter VM](otlp-isolated-transport.md) · [Collector bridge](otlp-collector-transport.md) - Offline probes `EXAGENT_OFFLINE=1 MIX_ENV=test ERL_FLAGS="+S 4:4" mix run test/support/load_probe.exs` and `test/support/postgres_load_probe.exs` with disposable database, `--size`, `--concurrency`, `--pool`, `--headers`, `--turns`, `--segments`. Point measurements are fixture evidence, not production SLOs or provider compatibility; see [Observability](observability.md#performance-and-load-envelopes) for recorded baseline figures. #### MCP `Client` and `Server` in this section mean `MCP.Client` and `MCP.Server`. ##### Client configuration and wire negotiation - `ExAgent.MCP.Client.start_link/1` common opts `:name`, `:transport`, `timeout: 5_000` (1–4,294,967,295 ms), `max_pending: 128`, `max_frame_bytes: 8_388_608` excluding newline (positive, bounds partial frame), `continuation_binding: nil`, `image_tools: []`, `trace: false`, and candidate `:pinned`, `on_drift: :reject`, `connect_on_start: false`, `:tasks`. Per-transport options and values validated before startup. Unknown/duplicate/foreign/missing key raises `ArgumentError` naming key. Runtime spawn/handshake failure returns `{:stdio_spawn_failed, reason}` or protocol/transport reason. - Stdio opts `command: path` required, `args: []`, `env: []`, `cd:`, `environment_policy: :isolated`. Direct spawn. If needed resolve executable with `System.find_executable/1`. Default retains small OS runtime allowlist plus explicit pairs (binary/charlist names/values, false removes, later wins). `:inherit` keeps parent environment. Newly added variables between the captured parent environment and spawn can still be inherited. Executable/args/env and filesystem permissions are host authority. Test transport `{send_fun, ref}` sends iodata via arity-2 function and receives `{ref, {:data, binary}}`. - Stdio requests `2025-06-18` and unbound accepts it, `2025-03-26` or `2024-11-05`. Bound stdio revision pin in `continuation_binding.protocol_version` (no top-level key), exact reply required or `:mcp_protocol_binding_mismatch`. `initialize` result needs object `capabilities` and `serverInfo` string `name`/`version` else `:invalid_initialize`. Other revision `:unsupported_protocol_version`. Stdio and legacy SSE answer `ping` and respond `-32601` for other server requests. Non-object params or unusable ID `-32600`, correlate usable string/integer ID or use null. No response to valid notifications. - `transport: :streamable_http` requires `url:` (HTTP(S) ≤8,192 bytes with host, no userinfo/fragment) and exactly one of `finch: pool` or `headers_provider: fun/1`. Finch requires host-owned HTTP/1-only pool, `headers: []` static, default `nodelay: true`. Body callback separates header/body upload. HTTP/2 yields `:http_transport_error` for affected requests. Legacy server requests in SSE may need a second free connection for control POST. Static request headers and response headers/trailers may be in Finch telemetry. Dynamic credential mode uses direct Mint HTTP/1.1 per exchange (verified TLS defaults), omits `:finch` and `:headers`. - HTTP defaults `max_request_bytes: 1_048_576`, `max_response_bytes: 1_048_576`, `max_header_bytes: 16_384`, `max_session_bytes: 256`, `max_line_bytes: 65_536`, `max_event_bytes: 262_144`, `max_tools: 256`, `max_controls: 16`, `max_control_bytes: 65_536`, `max_control_workers: 4`, `control_timeout: 1_000` (same ms range as timeout, control POST/DELETE). Positive integer limits. Byte caps bound received/decoded retention. Informational 100/103 do not establish session or content type. Each header block counts names/values plus 3 bytes for status. Reject 101. - HTTP default probes `server/discover` at `2026-07-28`, falls back to `initialize` at supported legacy `2025-11-25`, `2025-06-18` or `2025-03-26` only on compatible legacy negotiation. Transport/auth errors propagate. Bad discovery `:invalid_discovery`, no supported rev `:unsupported_protocol_version`. Explicit `protocol_version:` restricts to it. Reconnect keeps negotiated version. July carries `params._meta` `io.modelcontextprotocol/protocolVersion`, `clientInfo` and `clientCapabilities` (same namespace), plus `Mcp-Method`, applicable `Mcp-Name`/`Mcp-Param-*` and `MCP-Protocol-Version`. July request-scoped SSE accepts responses/notifications but an incoming server request terminates exchange `:unexpected_server_request`. Unknown result type unconfirmed. ##### Catalogue, projection and C7 binding - `Client.tools/1 → {:ok, tools} | {:error, reason}` traverses ordered `tools/list` pages `nextCursor` up to 32. Empty page can carry cursor. Duplicate name/cursor, missing tools array or cap overrun `:invalid_tools` / `:discovery_limit`. Replacement named owner or reconnect between pages `:session_invalidated` before next page. Restart from first page or reconnect if unready. July invalid remote `x-mcp-header` declaration omits that tool. Literal `annotations.readOnlyHint: true` maps `effect: :read`, otherwise write. Other hints do not grant recovery authority. Host validates remote semantics. Local Toolset prefix/rename preserves transport names and required review, permissions match offered names. `Tool.Search` for large collections. - Discovered object `outputSchema` becomes `Tool.result_schema` with validator and saved result binding. `structuredContent` validated object → `{:ok, map}` regardless of accompanying text/image opt-in. Invalid advertised object schema `:invalid_tools`. Complete correlated schema mismatch/missing object → fixed `{:tool_error, notice}` without body/validation details. Legacy reply must include valid `content` (can be empty). Malformed content → unconfirmed. `Client.call_tool/3` projects by name without result schema, even after discovery. Valid `isError: true` → `{:tool_error, peer_text}`. - Plain projection prioritizes nonempty `content`, preserving text/embedded text resources and describing other image/audio/binary/linked resources by type/size/URI, even when audience is user-only. Empty content uses `structuredContent` JSON. Earlier protocols require object. July also supports array/scalar/null. `image_tools` successful text/image returns `{:content, parts}` and imports multimodal Tool. Incompatible mixed blocks/invalid image data unconfirmed. Server multimodal output maps `ImageContent` with `type`, `mimeType`, Base64 `data`, omits object result schema. - Unbound discovery and July routing can cache only full traversal with all pages positive integer `ttlMs` and same `cacheScope: "private" | "public"`. Earliest expiry, max one endpoint/revision/session catalogue with ≤256 declarations and ≤1 MiB external-term bytes. Same identity cold lookups can coalesce. Even public cache client-local. Resolve current credentials before reuse. Principal/headers change, confirmed unknown tool/params/method/header rejection or `notifications/tools/list_changed` invalidates. JSON-RPC v2 notification has string method, absent `id`, object params default `%{}`. One pre-upload routing refresh on staleness, second `:session_invalidated` without upload. Generated tools use declarations captured during discovery. No automatic repeat after upload. Bound unpinned discovery reads live tools for fingerprints. - Candidate `Client.snapshot/1` fetches live declarations bypassing TTL or returns existing pinned bytes. `MCP.Snapshot.decode/1` requires canonical JSON ≤8 MiB, unique keys and matching lowercase SHA-256 over `schema_version: 1`, `revision`, `tasks`, ordered `tools` with `name, description, inputSchema, outputSchema, annotations` when supported/present. Name unique UTF-8 1–128 bytes. Object keys sorted and schema/tool array order preserved. `:invalid_mcp_snapshot` on mismatch/malformed. `mix exagent.mcp.lock ENDPOINT` compiles with `:exagent_mcp_lock` map entry (opts or MFA), opens transport/lists/closes, writes `priv/exagent/mcp/.lock.json`. Can start temporary HTTP/1 Finch. Host stays stopped. Doctor `--check-mcp-lock` offline verifies configured locks. Use distinct lock per principal view. - Candidate `pinned: bytes` provides declarations offline, revision/Tasks opt-in fixed by lock (explicit pinned options must match). Tool-only client can omit transport config, `reconnect/1` then `:not_available`. Otherwise calls wait for verification. Default `connect_on_start: false` requires connection/verification on demand via `reconnect/1`, true verifies before startup reply. Exact comparison `:ok`. `{:mcp_catalogue_drift, %{added: ..., removed: ..., changed: ..., revision: ...}}` sorted names. Default `on_drift: :reject` → error/blocks catalogue. `:serve_pinned` → ok diagnostic, serves unchanged/description-only original declarations, blocks added/removed or changed schema/annotations including callbacks already obtained. Drift telemetry counts. Invalidation requires verification again. `:mcp_catalogue_unverified` / `:mcp_tool_not_pinned`. Explicit refresh checks silent peer changes. - `continuation_binding: %{endpoint: %{"id" => id, "version" => version}, principal: ref}` binds transport, protocol, host identifiers and (HTTP) SHA-256 of normalized public URL. URL forbids query in bound mode, host case/default port/empty path normalized, no DNS equivalence. Stdio endpoint ref versions command/args/env semantics. Persists no literals. Old stdio record can require `"2024-11-05"` inside binding. HTTP restore selects same revision top-level. Neither credentials, headers, names/PIDs, session ID nor human reviewer enter authority. Host verifies peer/principal. Missing binding gives `:tool_continuation_binding_required` before model/tool IO (claim may exist). Changed target/principal/protocol/result schema `:continuation_tools_changed`. Legacy no-schema bindings preserve old text/image projection. Historical unbound approval cannot acquire new authority. Authorize new execution if identity changed. - `Client.call_tool/3` and bare discovered callback are transport IO, no agent permission/review. Route through normal loop for both. Tool effects unresolved after transport loss require evidence of prior outcome. `Client.reconnect/1` performs fresh handshake/pin verification without replay. `Client.close/1` releases owned transport only. ##### Credentials, authorization and tracing - `headers_provider.(%{deadline: monotonic_ms, principal: expected_or_nil}) → {:ok, principal_ref, headers} | {:error, reason}` in exchange worker, same deadline as HTTP IO including handshake/control/DELETE. Case-insensitive unique HTTP token names and printable ASCII values within header cap. Reserved transport/routing/trace headers blocked. Exceptions/exits/throws unavailable. `{:mcp_headers, :unavailable | :invalid | :principal_mismatch}` or `:http_pre_dispatch_timeout` before tool upload proves no send. Once call may have been sent, control failure can make it unconfirmed. Rotate credentials for same verified principal only. Changed principal uses new binding. Failed approved resume can consume approval before upload, so fresh execution and fresh review when needed. - Valid 401/403 Bearer challenge → `{:error, {:authorization_required, %{resource_metadata: url_or_nil, scope: space_separated_or_nil, error: string_or_nil}}}`. Absent valid challenge `:unauthorized` / `:forbidden`. Parse each complete `WWW-Authenticate` field: ignore empty list elements within cap, support quoted commas, duplicate case-insensitive parameter or malformed suffix invalidates that field. On legacy SSE control POST/tasks poll, authorization failure nests under `:result_unconfirmed` for original call. Host checks protected resource URL/integrity and well-known discovery order, issues/refreshes token for exact resource/scopes and decides when to retry. Retry rejected pre-dispatch request once explicitly with new credential. If a task ID already exists, retry status only. - Candidate `MCP.OAuth.metadata_urls/1` returns RFC 8414 path insertion, OIDC path insertion, OIDC suffix in that order (deduped), issuer HTTPS without query/userinfo/fragment. `validate_metadata(issuer, document)` checks exact issuer, HTTPS endpoints, boolean issuer validation flag and string-list `code_challenge_methods_supported` containing `"S256"` (else `:pkce_unsupported`). `pkce_verifier/1` encodes random 32–96 bytes base64url unpadded, `pkce_challenge/1` requires 43–128 RFC 7636 chars and S256. `validate_issuer/2` checks `iss` on success/error before use, including `:issuer_mismatch`/`:missing_issuer`. Host owns trust, redirects, OAuth state, code exchange, credential custody and refresh. - Client `trace: true` captures caller span before worker and injects W3C `traceparent` and optional `tracestate` into `params._meta` on both transports. Server Plug `trace: false` default, `:local`, `:trusted` or authenticated actor predicate. Invalid/absent remote context uses local, no baggage. Scoped tool worker under server span. MCP semantic spans exclude headers/session IDs/peer string IDs/args/results/messages. Discovered schema error type `tool_result_schema_mismatch`, `mcp.tool.result_schema.reason` one of `missing_structured_content`, `invalid_structured_content`, `schema_mismatch`. Host HTTP triggers remain independent. ##### Multi-round forms, Tasks and uncertainty - July forms in bound Frame 3 (including delegates) advertise form elicitation on eligible tool. `resultType: "input_required"` with `inputRequests` object and optional opaque string `requestState` → `%Continuation.DeferredCall{kind: :input}`. Metadata ≤65,536 JSON bytes, round ≤10. Presentation supports at most 8 forms, 32 primitive fields/form (string/integer/number/boolean), flat object schemas, IDs/field names/titles ≤256 bytes, form message ≤4,096, field descriptions ≤2,048, string choice lists ≤32. Unsupported form fails presentation. Apply tool-output guards and use exact saved child tool/definition from root inbox. Keep original peer state and args server-side. - `Continuation.supply_result(store, call, {:input, responses}, opts)` expects one exact key per request ID, value `%{"action" => "accept", "content" => object}` validated against form schema or `%{"action" => "decline" | "cancel"}`. `:invalid_mcp_input` for invalid response. Commit answers without peer IO, resume once with same remote tool/args/state, fresh JSON-RPC ID, own effect ID and shared call ref. Pending sibling inbox entries gate resume. `{:denied, content}`/`{:not_executed, content}` settle locally, `:cancel` closes run via decision. Fabricated success/failure `:mcp_input_required` leaves pending. Candidate live `on_input: fun/1` gets `%{tool: name, call_ref: ref, forms: views}` after guards, returns response map or `:deny`. Worker handles rounds under original deadline. Unconfirmed reply still requires reconciliation. - Candidate `tasks: false` only advertised with `2026-07-28` and peer `io.modelcontextprotocol/tasks` support. Peer chooses immediate vs task. `MCP.Client.Tasks.start_tool(client,name,args)` returns ordinary projected reply or `{:task, map}` with private server `taskId` (UTF-8 1–512 bytes) and optional `pollIntervalMs` (at least 10 ms honored, default 500). `get_task/2` reads `"working"`, `"input_required"`, `"completed"` with result, `"failed"` with error code, `"cancelled"`. `cancel_task/2` `:ok` acknowledges command, confirm terminal with read. Invalid/forgotten/expired peer ID `-32602` → `:mcp_task_unknown`. Automatic polling from direct/live calls shares original deadline, projects final result, task input-required/unknown/poll loss unconfirmed. Known cancellation `:mcp_task_cancelled`. No task subscriptions/input exchange. - Eligible bound Frame 3 records creation as external deferral (write) with `task_id` and `poll_interval_ms` in root/leaf inbox. Structural workflow leaves use synchronous calls. Rebuild same bound tool on replacement ready client, authorize `Continuation.reconcile_tool/4` for one saved status read using original key + metadata. Confirmed terminal commits one outcome, unchanged original dispatch count and deduped operation. Working/missing/lost lookup `:execution_uncertain` keeps deferral, no durable task ID when creation ack lost and no client-key lookup. Use independent evidence of original write if task gone. `Retention.erase/3` keeps open task evidence (`{:retained, :open_external_deferral}`). Task IDs are in trusted inbox and `Mcp-Name` header for get/cancel, omitted from spans. Stock Server publishes synchronous calls. - Missing client before dispatch `{:error, :unavailable}`, including read/discovery owner loss. Saturation `{:error, :busy}` before send. Dispatched command acknowledgement loss `{:error, :result_unconfirmed}`, known cause `{:error, {:result_unconfirmed, cause}}` and imported tool `{:unknown, cause}`. Forwarding direct unknown receipt through a host tool records unknown. Causes include timeout, malformed/duplicate-key/correlated unreadable JSON-RPC, invalid result shape, EOF, stdio send failure, oversized frame, close, worker loss, 2xx unusable response/intermediary 5xx after possible upload. Stdio handles complete correlated replies in chunk first. 501/522 keep rejection receipts. Explicit pre-body connection refusal `:http_transport_error`. Finch `conn_max_idle_time` reduces stale pooled connections. Legacy request's own 404 `:session_expired`, other pending requests disrupted by invalidation `{:result_unconfirmed, :session_invalidated}`. Discovery and handshake report protocol errors directly. - Confirmed JSON-RPC rejection `{:error, {:jsonrpc_error, integer_code}}`. Legacy `-32004` or July `10001` yields effect unconfirmed on any transport. Confirmed `isError: true` produces `{:tool_error, text}`. Complete invalid discovered structured object yields fixed schema tool error. Wire malformed content `{:result_unconfirmed, :invalid_tool_result}`. Transport limits apply after decode/receive and do not cap arbitrary upstream traffic/mailbox. OTP status redacts state/message logs. Linked client exit can still reach caller. ##### Server, Plug and catalogue authorization - `MCP.Server.start_link/1` per static catalogue. Requires `tools:` function tools, opts `name:`, `capabilities: []`, `permissions: %Permissions{}`, `on_validation_error: nil` or arity 2 private audit, `elicitation: false`, `mrtr_approval: nil`, `resources: []`, `prompts: []`, `catalog_policy: nil`, `catalog_policy_timeout: 1_000`, `max_sessions: 128`, `session_ttl: 300_000`, `max_calls: 32`, `max_calls_per_minute: 120`, `timeout: 30_000`, `page_size: 64`, `max_payload_bytes: 1_048_576`. Limits positive 32-bit unsigned, except retention 1 byte–64 MiB. Exclusive requires idle owner. Legacy fixed 60 s per-session limit counts admitted tool workers and successful resource/prompt reads. Saturation worker/quota `-32000`. Per-replica limits, host implements shared authority. Call deadline min server/tool/remaining session lifetime. - `Server.agent_tool(agent, name: ..., description: ..., timeout: 30_000, permissions: ..., result_schema: ...)` accepts required string `prompt`, authenticated actor in `deps`. Inner agent usage limits apply, default request ceiling 8 absent finite bound, inner tool permissions explicit. Exported result schema requires object root. Eligible single output schema auto-infers absent output transformation/validators, unions/transform require explicit schema. Use Jason encoder if implemented or Ecto embedded JSON field dump. A structured success returns validated `structuredContent` and its JSON text, schema-free text/projection. Byte budgets checked with request ID, before and after result hooks. Use OutputLimit for schema-free output. - Prepare with `before_tool_call` then schema validation, tool-input guard and effective permissions/approval before execution. Tool-stage Guardrails only (model input/stream/final rules raise at startup). Input veto/arg error/denial/model retry/`{:tool_error, text}`/result schema mismatch → `isError: true` (mismatch fixed text). Result hook failure, withheld confirmed result or response retention overflow → `-32603`, effect retained. Unknown name/malformed params `-32602`. Deferral/uncertainty/lost worker or deadline after admission legacy `-32004` or July `10001`. Pre-invocation elicitation expiry legacy `-32603`. Validation audit callback receives tool+full diagnostic. Telemetry count+rewritten only. - `Server.handle(server, session_or_nil, decoded_message, actor) → {:ok, session, response_or_nil} | {:error, reason}` and `close(server, sid, actor, opts \\ [])` require authenticated actor. `timeout: 5_000` for explicit close includes lookup. Missing endpoint `:unavailable`, lost reply `:result_unconfirmed`, close can still apply. Plug 503 when owner unavailable, legacy RPC ack loss `-32004`, DELETE ack loss HTTP 500. Session expiration/owner restart removes session and workers. Host owns listener/TLS/parser, authenticates every operation including controls. - `Server.Plug` requires `server:` and `authorize: fun/1` → verified actor or error, opts `origins: []` exact HTTP(S) Origin values, no Origin allowed after auth, `max_body_bytes: 1_048_576` (1 byte–64 MiB), `trace: false`, `protected_resource: nil`, `protocol_version: "2025-06-18"` or `"2026-07-28"`. Mount before application body parser for raw-byte/duplicate-key checks (`-32700` on parse error). Separate mounts for revisions. POST responses `Cache-Control: no-store`. - Legacy initialize returns `Mcp-Session-Id` and negotiated revision for subsequent POSTs. Client sends `notifications/initialized` before list/call, Accept JSON + SSE, one JSON-RPC message. Progress token (string/integer) or live approval uses chunked SSE `message` event for each envelope including matching final. Other replies ordinary JSON. Notifications/elicitation replies empty 202. GET active/missing session 405, unknown/other actor 404. DELETE closes owned session. `notifications/cancelled` with original `requestId` stops matching call and final stream without result, POST 202. Disconnect doesn't cancel. Legacy sessions node-local and sticky. - Progress `params._meta.progressToken` echoed with count in `notifications/progress`, advances on tool entry, model step and `RunContext.emit/4`. Samples every 250 ms and final, milestones can coalesce. Legacy `elicitation: true` delegates approval trust to authenticated peer with form capability. `:ask`/required approval after arg/guard checks, deny always wins. `elicitation/create` fresh ID and required boolean `approve` with original tool args, same principal/session answers through separate POST. Only `accept` with JSON true grants one invocation, exact effective/original value and type equality mandatory. Decline/cancel/error/rewritten args/missing capability deny. One slot and original deadline include review. Stock Client does not approve remote live legacy forms. - July `server/discover`, stateless POST JSON responses, no session affinity. Requires coherent body request metadata and routing headers (`-32020` mismatch, `-32022` unsupported revision). Tool `"x-mcp-header" => "suffix"` on string/integer/boolean leaf through nested `properties` maps to `Mcp-Param-Suffix`. Suffix nonempty HTTP token unique case-insensitively across tool. Invalid declaration rejects startup. Check headers against authorized tool after visibility lookup. Discovery and catalogue cache hints `ttlMs: 0, cacheScope: "private"`. Host config matches order, page size, props and authority across replicas. - Candidate `mrtr_approval: [store: scope, id: endpoint, key: secret_bytes, ttl_ms: 300_000]`, TTL 1–3,600,000 ms, key ≥32 bytes, state token ≤1,024 bytes, HMAC SHA-256. Shared same scoped atomic turn-admission Store (SQL 5 for PG), endpoint/key across replicas. Original tool, method, args and stable principal bind `inputRequests`/signed `requestState`, follow-up fresh JSON-RPC ID and same principal. Approve/decline consumes one idempotent receipt until state expiry. Reused/invalid/expired `-32602`. Bound 256 live receipts/principal and 1,024/endpoint. Capacity response HTTP 400 + RPC `-32040` `data.scope` = `"principal"` or `"endpoint"`, `retryable: true`, state still unconsumed and tool undispatched. Client gets `{:error, {:jsonrpc_error, -32040}}`. Retry after capacity expires while signed state valid or request new form. - Publish static `resources/list`, `resources/read`, empty `resources/templates/list` if available, `prompts/list`/`prompts/get`. Exact registered URI and text/MIME default `text/plain`, no resource IO. Prompt returns ordered user/assistant text, absent/empty args only. Detach backing binaries. Page by registration order and external-term budget including actual ID/cursor, reject single oversize declaration on startup and request ID too large for one item `-32602`. Read/descriptors checked at startup and dispatch. - `catalog_policy.(%{principal: id, kind: :tools | :resources | :prompts, deadline: monotonic_ms}) → {:ok, selectors} | {:error, reason}`. Nonempty UTF-8 names/URIs, empty list denies whole kind, unknown/duplicate ignored, defaults to all. Each request resolves once under bounded off-owner check (legacy expiry may shorten 1,000 ms), separate max_calls pool `-32000` on saturation, error/timeout/bad output fixed `-32603`. Filter before pagination/target/header lookup. Common view order independent of callback order. Opaque cursor bound principal/protocol/ordered visible descriptors/method and works on another replica with same view. Stale/cross-principal `-32602`. Hidden tool/prompt indistinguishable from unknown (`-32602`), hidden resource legacy `-32002` or July `-32602`. Revocation affects subsequent ops, admitted effect can finish. Correlated rejection confirms no dispatch. Later revocation gives no evidence of lost reply. - Candidate `protected_resource: [resource: public_url, authorization_servers: [issuer, ...], scopes_supported: []]` on MCP and public `/.well-known/oauth-protected-resource[/endpoint_path]` GET path. HTTPS (loopback test HTTP), issuers no query. Metadata `resource`, `authorization_servers`, `bearer_methods_supported: ["header"]`, optional scopes. `authorize` validates Bearer issuer/audience/expiry/scopes and returns stable actor. `{:error, :unauthenticated}` and `:invalid_token` with optional required scope list → 401 Bearer challenge (invalid token parameter accordingly), `:insufficient_scope` optionally with list → 403 and required scopes. Authorization before dispatch and exact Origin allowlist. [MCP guide](mcp.md) · [Continuation binding recipe](mcp-continuation-binding.md) · [Support and limits](status.md) --- ### Tools and model contracts for coding agents ExAgent 3.0.0. Names are relative to `ExAgent` unless qualified. `Usage` means `Message.Usage`. Candidate APIs can change across releases. Run failures use `%RunError{}`. Provider admission and hosted-provider evidence are separate properties. #### Tools, Toolset and execution controls | API | Contract | | --- | --- | | `use Tools`, `Tools.deftool/2` and `Tools.deftool/3` | Defines a function plus a tool entry exposed by the host module's `tools/0`. The first parameter is `RunContext`. Remaining named parameters become JSON object properties. `@doc` supplies the trimmed description. Macro options are `effect: :write \| :read` and `requires_deferral: false \| true`. Invalid controls fail compilation. | | `Tools.tool_plain/2` | All parameters are tool arguments. Signature variables may be annotated with `::`. Patterns and defaults require a manual schema or matching inside the body. A `when` guard remains an Elixir guard. A schema-valid call can still raise `FunctionClauseError`. | | `Tool.new/1` | Builds a manual tool from a keyword list. Unknown or duplicate options, invalid names and invalid execution controls raise `ArgumentError`. `Tool.definition/1` projects `%{name: name, description: description, parameters: schema}`. `Tool.validate_args/2` and `Tool.validate_result/2` return `{:ok, original}` or `{:error, [%{path: json_pointer, keyword: keyword, message: message}]}`. Root pointer is `""`. Argument validation compares atom and string keys as JSON strings, rejects collisions, preserves the original representation, and applies neither coercion nor defaults. Result schema validation checks the JSON encoded by Jason, including encodable structs. | | `Tool.new/1` option | Default and constraints | | --- | --- | | `:name`, `:description` | Both `nil`. Constructor accepts a nil or nonempty name. Inventory requires a named tool, unique by final name, with the `final_result` prefix reserved. Use portable function names matching `^[A-Za-z_][A-Za-z0-9_-]{0,63}$`, required for names produced by `Toolset`. Output branch names match `^[A-Za-z0-9_-]{1,64}$` and must avoid collisions. | | `:parameters_json_schema` | `%{}`. JSON Schema map or boolean. Invocation still requires a JSON object. MCP export requires an explicit object schema. | | `:result_schema`, `:result_mode` | `nil` and `:json`. JSON Schema map or boolean runs after result hooks and before shortening/offload. `:multimodal` requires `result_schema: nil`. | | `:kind` | `:function`. Also accepts `:output` or `:external`. Ordinary application callbacks use `:function`. | | `:call`, `:takes_ctx` | `nil` and `true`. Callable arity 2 takes `(ctx, args)`. Set `takes_ctx: false` for arity 1 `(args)`. Invocation rejects a mismatched callback with `{:invalid_tool_callable, name}`. | | `:requires_approval`, `:requires_deferral` | Both `false` and boolean. Approval composes with permission rules. Set `requires_deferral: true` for tools requiring a durable inbox, including timers. Volatile runs and Frame 10/11 leaves reject before effect intent. Root and delegated Frame 3 support deferrals, with migration 1 on PostgreSQL. | | `:effect`, `:reconcile` | `:write` and `nil`. Authorized recovery can repeat an uncertain `:read`. A context-aware write can supply a read-only `fn key -> ... end` or `fn key, recorded_external_deferral_meta -> ... end` returning `{:confirmed, data} \| :not_executed \| :unknown`. `ctx.idempotency_key` is assigned before dispatch and reused across attempts. The external service owns deduplication. Effect, deferral and reconciliation declarations enter the continuation binding. | | `:timeout`, `:concurrency` | `nil` inherits agent `tool_timeout: 30_000` ms. Override with a positive integer. `:parallel` (default) groups adjacent calls and `:exclusive` waits for earlier calls and finishes before later ones. A paused call releases ordering within that attempt. Receipts preserve the model's call order. | | `:max_retries` | `1`, nonnegative integer. Consecutive retryable failures consume the tool budget. Zero fails on the first one. Success and confirmed domain errors reset it. | | `:max_heap_bytes` (candidate) | `nil` inherits the VM policy. Round down to BEAM words, bounded by the VM `:min_heap_size` and `(1 <<< (word_bytes * 8 - 5)) - 1` words. GC enforces the task heap threshold and counts shared binaries. A task kill with no timer expiry evidence reports `{:exit, :killed}` and preserves observed confirmation. Native allocations, ETS and other tasks have independent lifecycles. | | `:reservation_cents` (candidate) | `nil` or a positive host quote before dispatch. Applies to the current tool definition. Output, delegate and CodeMode tools cannot use it. Report price via `Usage.with_estimated_cost/2`. Unknown or partial charge leaves the outstanding hold for reconciliation. Internally priced Media tools need no duplicate quote. | - `Toolset.prefix(tools, prefix)` prepends the literal prefix including any separator. `Toolset.rename(tools, %{old => new})` renames simultaneously. `Toolset.filter(tools, selection)` preserves order. `Toolset.require_approval(tools, selection \\ :all)` forces review even on `:allow` and survives renames. Explicit selections take a name list, `{:except, names}`, or an arity-one predicate. Unknown names, output tools, collisions and reserved names raise. MCP renames preserve remote identity. Permissions, Search, RepeatGuard, OutputLimit, eval and telemetry use the final names. - Derived schema `Schema.from_type/1` supports `integer()`, `non_neg_integer()`, `pos_integer()`, `byte()` (0–255), literal ascending integer ranges, `float()`, `number()`, `boolean()`, `Binary.t()`, `String.t()`, `binary()`, `string()`, `atom()` (JSON string), `map()` (object), and nonempty literal atom-keyed object types with unique fields. Fields of those objects are required and additional properties are allowed. `list(t)`/`[t]` allow empty arrays, `nonempty_list(t)`/`[t, ...]` require one item, and `list()`, `[]`, `nonempty_list()`/`[...]` leave items unconstrained. Literal unions become `enum` (atoms stringify except booleans and nil). Typed unions become `anyOf`. Untyped, `any()` and unresolved forms produce `%{}`. `cursor :: String.t() | nil` requires the key and permits null. For omission, leave the property out of a manual schema's `required` and use `Map.get(args, "cursor", default)`. - `max_concurrent_tools: positive_integer` at run level overrides the agent's limit. Default group size is `System.schedulers_online()`. Slot wait consumes the run deadline. Admission (hooks, schema, permissions, synchronous `approve:`) and dispatched execution each have their own tool timeout capped by that deadline. Admission expiry is `:not_executed` with `{:tool_admission_timeout, name}`. Execution expiry is `:unknown` with `{:tool_execution_failed, name, {:exit, :timeout}}`. Approval raise/throw/exit records `:not_executed` and `:tool_approval_failed`. Resume uses current timeout, concurrency and heap controls. A stored run-level concurrency override remains effective unless superseded. - Validate offered tool definitions before effects. Invalid schemas give `{:invalid_tool_schema, name, errors}`. Schema-invalid args produce `:validation_error` with JSON pointers and skip invocation. Invalid rewrites by host hooks produce a fixed diagnostic. Regex backtracking exhaustion is `indeterminate_pattern` even inside `not`, `anyOf` and `patternProperties`. Unoffered tools give `{:unknown_tool, name}` with one correction, including a budget preserved on open durable workflow batches. Legacy batches opened with zero retain it. Durable schema diagnostics keep an ordered prefix and `truncated` count in at most 4,096 JSON bytes. - Post-decode retention measures uncompressed Erlang external terms. Defaults `max_payload_bytes: 1_048_576` and `max_history_bytes: 8_388_608`, each 1 byte–64 MiB. Every call reserves its return before dispatch, including a 4 KiB usage allowance plus identity and omission overhead (about 4.5 KiB for short names/IDs). Admission may fail at `:tool_return` or `:history`. Prepared arguments are bounded again before decode. If a return exceeds the slot after execution, the receipt retains identity/outcome with `payload_omitted` and the run fails. Hook shortening cannot recover it. Retained binary slices in text/lists/plain maps are detached with equal slices sharing one copy per result. Custom structs and other processes control their own references. - LangChain 0.15.8 text adapter pattern uses `LangChain.Function.execute(function, args, ctx.deps)` with the existing parameter schema or `FunctionParam.to_parameters_schema/1`. Map `async` to `:parallel` or `:exclusive`, keep text from `{:ok, text}` or `{:ok, text, processed}`, and map a confirmed text error to `{:tool_error, message}`. Preserve the host review policy and handle multimodal, interruption and unconfirmed effects separately. ##### Closed tool result vocabulary | Callable return | Receipt and run | | --- | --- | | JSON-portable `value`, `{:ok, value}`, `{:ok, value, %Usage{}}` | `:succeeded`, continues. Reset retry count. A declared schema mismatch gives a fixed `:tool_error`, preserving the effect and usage. The rejected value and JSV diagnostics stay host-side. | | `{:content, parts}` or `{:content, parts, %Usage{}}` | `:succeeded` with `result_mode: :multimodal` and a profile supporting image returns. See content contract below. | | `{:tool_error, message}` or `{:tool_error, message, %Usage{}}` | Confirmed `:tool_error`. Continues with a model-visible error and resets retries. Anthropic and Bedrock carry an error marker, Chat-compatible wire uses the text signal. | | `{:retry, message}` or `raise ExAgent.ModelRetry` | `:validation_error`, for corrections before any effect. Exhaustion is `:tool_retries_exhausted`. Messages must be UTF-8. | | `{:error, reason}` | `:failed` with fixed model notice “The tool failed.” Host error `{:tool_execution_failed, name, reason}`. | | `{:unknown, reason}`, `{:unknown, reason, %Usage{}}`, exception/throw/exit or unconfirmed checkpoint, Server/Jobs delivery, memory write or MCP result | `:unknown` with fixed “The tool did not return a confirmed result.” Host reconciles effect. The three-element form retains usage. | | Invalid shape, bare `:error`, returned `%ModelRetry{}` (also in `{:error, _}`), malformed message or nonportable schema-free result | `:unknown` with `{:invalid_tool_result, name, :unsupported_return}` or JSON errors for a nonportable value. | | `{:defer, meta}` or `{:defer, meta, kind: :external \| :input}` | `:deferred`, default kind `:external`. Metadata is a JSON object up to 64 KiB visible to the host. Without supported C7 this produces `:unknown` and `{:deferral_unsupported, name}`. Timer variant `{:defer, meta, kind: :timer, wake_at: utc_ms}` (candidate) also admits automatic expiry. | - Multimodal `parts` are string-keyed JSON maps with `%{"type" => "text", "text" => text}` or `%{"type" => "image", "media_type" => mime, "data" => padded_base64}` and at least one image. PNG, JPEG and WebP bytes must match their MIME signatures. Cap the tagged term at 1 MiB before base64 decode, including part overhead. General payload/history reservations also apply. A plain list/map success uses JSON text. `Tool.Content` retains the accepted parts for tool-output checks, actual result and C7. Events, transcript and telemetry use an image-count notice. Oversize OutputLimit replaces the content with that notice without text offload or truncation callback. - Domain errors still run applicable result hooks/guardrails, regardless of message text. Durable workflows retain effect receipts when checking/transforming a return fails and withhold unchecked content. Recovery of a confirmed raw result applies schema and OutputLimit, including offload, without rerunning host result hooks or `on_truncate`. [Tools guide](tools-and-output.md) · [Durability guide](durability-and-approvals.md) #### Structured output and validators | `output_mode:` | Request, local acceptance and limits | | --- | --- | | `:tool` (default) | `output: :text` (default) permits text with no output tool. A module, JSON object schema or `Output.tool(schema, name: ..., description: ...)` yields `final_result` for a single plain branch. A nonempty list can include distinct named branches and at most one `:text`. Defaults are `final_result_` or `final_result_json` in a union. A selected branch yields `Result.output_name` and the effective `output_mode`. Text has a nil branch. | | `:native` | One map or Ecto module, no function/union. OpenAI Chat `response_format` and Responses `text.format` project non-strict schemas. Anthropic catalogue `json.schema` uses `output_config.format` with closed declared objects and reduced constraints. Enumerate objects and array items. Dynamic map keys, free-form object fields and multi-branch `allOf` are refused on Anthropic. Projection keeps scalar enums/consts and omits unsupported bounds, lengths, patterns, `maxItems` and `minItems > 1`. Caps 24 optional properties and 16 union nodes. Full local validation still applies. Gemini has no native mode. Constructor rejects unsupported profiles and keywords such as external identifiers, dialects, `$ref` and `$defs`. Wire refusals only affect admission when exposed by stock ReqLLM. | | `:prompted` | One map or Ecto module. Adds a canonical JSON Schema system instruction after agent/capability instructions solely to the request. Adapter receives text mode. Entire answer or one Markdown fence must contain the JSON object. Leading/trailing explanatory text or invalid syntax yields correction. Works without native/tool support. | - JSON Schema output takes an explicit `type: "object"` map (including when a draft 7 root reference resolves differently), maximum 65,536 compact JSON bytes per branch including escaping. Atom/string definition keys may not normalize to the same name. JSV supports local refs in draft 2020-12 (default) and draft 7, with fetching and executable casts disabled. ReqLLM tool/native transports use a reference-free subset. Results retain JSON types and recursively string keys. Omitted optional keys stay absent. Repeated keys, including escaped equivalents in nested objects, give `uniqueKeys`. Exact decimal/exponent checks prevent rounded floats from passing the wrong constraint. Integer tokens retain precision. `minContains` and `maxContains` count matching items in tools, previews and final values. - Ecto is optional (`{:ecto, "~> 3.14 and >= 3.14.3"}` for an Ecto consumer). Use `embedded_schema` and optionally `changeset/2`. JSON Schema checks first, so casts such as `"7"` into integer do not bypass the contract. Without changeset, scalars and `embeds_one` are required and missing `embeds_many` defaults to `[]`. Child rules recurse. `validate_required/2` advertises required keys even with defaults. Omitted optional keys preserve defaults and explicit null needs its own policy. `{:map, :integer}` projects dynamic keys with integer or null values, including inside arrays. `Ecto.Enum` advertises dumped integer/string values and casts to the atom. Recognized metadata on `validate_change/4` can project constraints. Tightest number bounds win per keyword. Decimal bounds/choices remain exact in changesets. JSON Schema length counts codepoints, matched by `count: :codepoints`. `validate_subset/3` on arrays projects `items.enum` using declared enum storage values and permits repetitions. - Invalid output uses `output_retries: 1` by default. Zero fails the first invalid answer. Schema errors include pointer paths or Ecto paths such as `["items", 1, "name"]`. Exhaustion names the schema and attempts with up to five validation paths. `Server.chat/3` returns accepted `Result.output` inside `{:ok, %Result{}}`. Event/history projection uses Jason then Ecto embedded dump fallback under the payload bound. `:run_finished` may carry `output_name`. - `:output_validators` accepts ordered `fn output, ctx -> ... end` and `{:pure, fn output -> ... end}`. `:ok` accepts, `{:ok, value}` passes the replacement onward, `{:retry, message}` or raised `ModelRetry` spends the shared budget, `{:error, reason}` yields `{:output_validation_failed, reason}`. Other returns yield `{:output_validation_failed, {:invalid_validator_result, _}}`. Check deadline, limits and cancellation again after validators. A correction at the last step gives `{:max_steps_exceeded, max_steps}`. A pure declared chain on a direct durable Flow branch can certify a returned veto. Version its `output_ref`. Exceptions, malformed returns or context-aware validators do not certify one. Durable workflows reject validators with text/native path as `{:unsupported, :output_validators_without_output_tool}`. - `Output.function(name, schema, fun, opts \\ [])` adds an arity-two `fun.(validated_output, ctx)` after validators in tool mode. Option `:description`. `{:ok, value}` sets output and branch name. Retry uses the same budget. Failure is `{:output_function_failed, name, reason}`, including `{:raised, message}`/`{:invalid_result, inspected}`. Use pure or idempotent functions since a pre-checkpoint crash can repeat them. C7 requires exact JSON (string keys, no structs or non-JSON atoms) or `{:output_not_persistable, name}`. Final guardrails/evaluators see the transformed value. `MCP.Server.agent_tool/2` infers `outputSchema` only for one map branch without transforms or validators. Supply `result_schema:` for transformed or union values. - `{:output_partial, %{output: draft}}` carries completed valid members from streamed text or the first identified output-tool branch/index. Map preview disables `required` recursively, so other constraints still constrain preview eligibility. Ecto preview casts partials. Caps per model request are 32 distinct updates, `min(65_536, max_payload_bytes)` retained bytes and 4,096 nonempty fragments. These are provisional content events independent of accepted output, history, journal and tool execution. - Frame 3 binds the schema, mode, branch kind and function marker, supports approvals in all three modes, and rejects a changed binding with `:continuation_output_changed`. A resumed run does not revalidate an already accepted output. Frame 10/11 require tool certification for map output. Native map and a map union allowing text give `{:unsupported, :composition_json_output_without_tool}`. A direct prompted step gives `{:unsupported, :composition_request_projection}` before opening/claiming. A loaded delegate is checked as soon as its definition is available. ##### Model reviewers - `Judge.output_validator/1` (candidate) accepts `model:` and nonblank UTF-8 `criteria:`, optional `model_settings:`, `max_transcript_bytes: 24_000` (minimum 1,024), `on_error: :accept | :fail` (default `:accept`). PASS accepts, FAIL contributes retry feedback. An unrecognized verdict retries with a formatting reminder and updated model state once. Subreviews inherit live scope accounting. C7 uses a separate scoped deadline and rejects any model request/token/cost/model-concurrency limit on the run or ancestor with `{:output_validation_failed, {:judge_failed, :continuation_child_descriptor_required}}` before reviewer IO. Deadline, usage/concurrency, strict accounting, cancellation, fixture misses and denied live review fail despite `:accept`. - `Judge.approver/1` (candidate) accepts `model:` and nonblank UTF-8 `policy:`, optional `model_settings:`, `timeout: 20_000` and arity-one `escalate:`. ALLOW/DENY are explicit and ASK or reviewer failure escalates (default deny). Arguments exceeding 8,192 encoded bytes or unusable JSON go straight to escalation with the original call. It consumes the tool's admission time and runs with separate usage. A denied live review or replay miss in a fixture fails with `{:tool_approval_failed, name, {:exit, {:model_request_failed, %RequestError{provider: :fixture}}}}`. Both constructors can take `classifier:` in place of model/settings/criteria or policy. The classifier receives conversation/answer or tool_name/args JSON, uses labels `"allow"`, `"deny"` and optional `"ask"`, and is unsupported in chat cassettes. The classifier output validator additionally needs a live execution scope and rejects C7. - `Tool.Advisor.new/1` (candidate) requires `:model` plus optional `name: "consult_advisor"`, `description:`, `instructions:`, `model_settings: []`, `max_uses: 3`, `max_transcript_bytes: 32_000` (minimum 1,024) and `timeout: 120_000` ms. Wrapper timeout is reviewer timeout + 5,000 ms. Tool schema requires string `question`. Bounded plain transcript excludes signed replay. Uses count per user message, including failed consultation and limit notices. Earlier calls in the batch reserve places even if later rejected. Timeout/failure yields a recoverable `:tool_error` notice. Live scoped child usage counts once against the parent. With C7, any own/ancestor request, token, cost or model-concurrency limit gives unavailable before reviewer IO. With only tool limits or deadline, independent consultation inherits deadline and contributes reported tool usage outside the durable request count. #### Permissions, guardrails, capabilities, sandbox and large tool catalogues ##### Authorization and policy hooks - `Permissions.new!(rules: [], default: :allow)`. Set `default: :deny` for an allowlist. Actions `:allow | :ask | :deny`. Rule `{name_glob, action}` or `{name_glob, action, args: %{path => predicate}}` (candidate). `Permissions.decide/2` checks a name with empty args. `decide/3` and `match_rule/3` (candidate) use validated arguments. Last matching rule wins. Predicates in one rule are ANDed. Missing values skip the rule. Glob matches all bytes, including newlines, via `*` (zero or more) and `?` (one). Nested selectors are lists of JSON-key strings. A supplied malformed structured operand for that tool denies the call. - Structured comparators (candidate) use `{:command, argv_prefix}` for complete literal argv words (list or ASCII space/tab separated string). Reject shell syntax, non-ASCII whitespace, zero-width space and BOM. Executable identity is literal. `{:url, prefix}` requires absolute HTTP(S), compares normalized origin including effective port and path segments. DNS/IPv4 normalization uses optional `{:idna, "~> 8.0"}`. Prefix disallows query/fragment. Collapse repeated slashes and dot segments including encoded dots. Reject credentials and ambiguous or encoded separators. The callable owns query, DNS and redirect handling. `{:path, directory}` expands the configured root and compares case-sensitive normalized absolute paths. Filesystem containment and symlinks belong to the callable. URL/path accept nonempty lists with all members required for `:allow`/`:ask` and any for `:deny`. - `permissions:` and `approve:` are run controls. Permissions see prepared, schema-valid normalized args. Reviewer edits go through the schema and each policy again and must preserve each winning rule. `requires_approval: true` forces `:ask` when policy otherwise grants execution. Missing callback denies synchronous `:ask`. Argument rules persist as C7 policy version 2. Model-provided tier or other labels cannot establish authority without checking the underlying trusted constraint. | `Capability` callback (all optional) | Ordering, writable fields and result | | --- | --- | | `tools(cap)`, `settings(cap)`, `instructions(cap, ctx)`, `guardrails(cap)` | Identical tool entries deduplicate after agent tools. Same-name differences raise. Settings precedence is capability < agent < run < request hook. Instructions return nil/string/list once per attempt after agent instructions, only in the request projection. Guardrails kept in declaration order. | | `before_model_request(cap, %ModelRequest{}, ctx)` | List order, `{:ok, req} \| {:skip, response} \| {:error, reason}`. Writable `messages`, `tools`, `settings`, `model` only. Each request starts from the full inventory and current run settings. Offer only registered tools. | | `after_model_request(cap, response, request, ctx)` | Reverse order, `{:ok, response} \| {:error, reason}`. Can alter response parts only. Finish, usage and continuation remain adapter-owned. | | `on_model_request_error(cap, reason, request, ctx)` | Reverse order, `{:error, reason} \| {:recover, response}`. Skip/recovery response must be text-only with `finish_reason: :stop` and `continuation: nil`. Missing finish yields `{:invalid_field, :finish_reason}`. Skip makes zero requests with explicit zero usage. Recovery retains observed usage, accounting and `usage_status: :partial`. Post-hooks cannot add tool calls/thinking to either. C7 rejects `{:unsupported, {:capability_skip, :continuation}}` and `{:unsupported, {:capability_recover, :continuation}}`. | | `before_tool_call(cap, call, ctx)` | List order, `{:ok, call} \| {:skip, {:deny, message}} \| {:error, reason}`. Only `args` writable. A 1–4,096-byte denial yields `:denied` without dispatch or review. Root C7 reruns hooks after approval. A prepared Frame 10/11 call restores recorded effective args and skips preparation. | | `after_tool_call(cap, return, call, ctx)` | Reverse order, `{:ok, return} \| {:error, reason}`. Can modify content on `:succeeded`, `:tool_error` and `:validation_error` after effect confirmation. | | `after_run(cap, terminal)` | Once per admitted attempt such as pause or resume, reverse order. Input is `%Result{}` or `%RunError{}`. No observer for a pre-admission stale ref. Leaf agents observe their own terminals. Lazy stream starts observers after worker cleanup. Each gets a fresh monitored process, owner-led `:"$callers"` and 250 ms. Failures log bounded categories, timeouts kill the observer, and its return does not change the terminal. | - Hook error, exception, invalid return or read-only mutation gives `{:capability_failed, module, hook, reason}` with no dispatch before the corresponding boundary and any prior confirmation retained. `instructions:` also accepts arity-one functions returning nil/string/list of strings, in list order. Failure is `{:capability_failed, ExAgent, :instructions, reason}`. Dynamic instructions enter the persisted request, outside history. Frame 10/11 refuse request-only instruction functions. ##### Guardrails, receipts and C7 certification | Constructor | Value and stage | | --- | --- | | `Guardrail.input/2` | Normalized new user text or multipart input once per logical run before model IO and before opening C7. | | `Guardrail.stream/3` | `%{text: binary, commentary: binary}` disjoint UTF-8 windows before release on both channels. `max_bytes: 1024` (4–65,536), `max_ms: 50` (1–1,000). Smallest declared limits apply to all checks. Timer starts at first retained text. Review the last short window, oversized deltas split on codepoint boundaries, and terminal text differing from released deltas is reviewed. Buffered text uses byte windows. | | `Guardrail.tool_input/2` | Normalized `ToolCall` after preparation/schema. Live before approval and after edits. Root C7 checks approved args prior to effect intent. Host callable retains its original key representation. | | `Guardrail.tool_output/2` | Effective confirmed `ToolReturn` before further model IO. Sees checked schema-bound business value before OutputLimit. For schema-free offload it sees preview/reference, and each reader page undergoes its own check. | | `Guardrail.output/2` | Accepted candidate after schema, validators and output function. Veto ends delivery without retry. | - Check callbacks return `:ok | {:tripwire, info} | {:error, reason}`. `info` is nil or a content-free 1–64-character ASCII identifier using letters, digits, dots, underscores or hyphens, as are names. First non-`:ok` stops the chain. Error/exception/throw/exit/invalid return gives `{:capability_failed, ExAgent.Guardrail, stage, reason}`. Stream check failures use `:guardrail_check_failed`. A trip emits `{:guardrail_tripped, %{step: step, name: name, stage: stage}}` and a terminal error. Event and telemetry omit the checked content and diagnostic code. - Tool-output review withholds the return until verdict. Veto or unconfirmed review keeps receipt status/usage with `content_withheld: true`. Already-dispatched tasks can finish and closed admission marks waiting calls `:not_executed`. A trip discards the current window and leaves previously released text provisional. Missing provider terminal leaves cost unknown with observed usage partial. Live Server with guardrails advances history on accepted turns and retains failure effects in `RunError.partial`. - Root C7 binds all five stages with versioned `:policy`, ordered stages/names and stream limits. Persisted handoffs certify destination input and continue prior checks. Frame 3 delegated agents reject guardrails at `:agent_continuation_delegate`. Restrictions for tool guardrails plus durable delegation/custom rehydration use `:agent_continuation_delegation`/`:agent_continuation_rehydrate_tools`. Frame 10/11 certify tool guards through the journal and reject input/stream/final policies at `:composition`. - `Classifier.guardrail/4` (candidate) uses ordered policy labels and `allow:`. Tool-stage and stream classifiers require `input:` projector. Stream accepts the same window controls, and each nonempty window may consume a model slot while the source stream is in flight. First disallowed label trips. Backend/deadline/limit failure withholds content. Live guards use scoped request/quota accounting. C7 needs host admission or an explicit classifier tool effect. ##### OutputLimit, ResultStore, RepeatGuard and Search - `Tool.OutputLimit.new/1` (candidate) options `max_bytes: 32_768` (minimum 256), `keep: :head_tail | :head | :tail`, `tools: :all | [names] | {:except, names}`, one of `offload: {backend, handle}` or `on_truncate: fn %{tool_name: n, tool_call_id: id, content: value, bytes: bytes} -> hint_or_nil end` (both default nil). Shortens success/domain errors on UTF-8 boundaries using text or encoded JSON. Fatal and retry results retain their normal path. UTF-8 hints fit whole or are dropped. Oversize multimodal becomes an image-count notice. - Set OutputLimit earlier in the capability list than hooks that need full schema-free returns. Without offload, an in-flight checkpoint may keep raw content. With offload, schema-free live results project before confirmation/hooks. Schema-bound results validate first. Raw journal, delegated output and externally supplied results can still retain original sources. Preview begins with `[exagent-result ...]` ref and byte count. An oversize preview falls back to just the header. If the header fails the slot, normal retention failure applies. Storage failure marks unavailable. Filter data in the producing callable. - `Tool.ResultStore` (candidate) reader tools use the current run ID, separate from other runs, children and turns. `read_result(ref, offset, limit)` returns UTF-8 `text` and `next_offset`, zero-based byte offsets and nil at EOF, max page 4,096 bytes. `grep_result(ref, pattern, offset, limit, mode)` scans at most 65,536 starting byte positions, 64 nonoverlapping offsets, literal UTF-8 1–256 bytes. `mode: "regex"` supports up to 16 nonempty literal alternatives and takes the longest at the first matching position. Continue from `next_offset` even on an empty page. Foreign/evicted/expired refs share the recoverable missing result response. - `Tool.ResultStore.ETS.start_link/1` (candidate) local owner, optional `name:`, defaults 8 MiB, 256 entries, 300,000 ms TTL (max 4,294,967,295 ms). FIFO eviction and owner restart remove refs. `Tool.ResultStore.Postgres.new(repo, scope: scope, ...)` (candidate) same quota defaults, trusted scope, migration 1 creates `exagent_tool_results`. Writers in that scope share quotas and should use identical settings. SQL admission is READ COMMITTED, FIFO and DB-clock TTL. Duplicate ref returns `{:error, :unavailable}` preserving old data. Quota failure rolls back insertion. DB read failure differs from expiration. `cleanup_expired(repo, limit)` and `delete_run(handle, run_id, limit)` take 1–1,000 rows, return `{:ok, count} | {:error, :unavailable}` and skip locked rows. Erase abandoned data after its writers stop. - `Tool.RepeatGuard.new/1` (candidate) accepts `warn_at: 3`, `tools: :all` or name inclusion/exclusion. Counts identical calls (same tool and args) since last user turn. Adds a request-only reminder at the configured repetition threshold. Exclude polling and put it after compaction. It leaves permissions, history and events intact. - `Tool.Search.new/1` (candidate) requires a nonempty `deferred:` list of uniquely named function tools. Defaults `name: "search_tools"`, `max_results: 5` (1–50), `mode: :load`. Exact names separated by spaces/commas or ranked keyword terms from name/description/top-level parameters. A miss suggests up to 200 names. Load requests add matched tools from the next step, in history order, while inventory retains all. If a success is shortened, Search can replay its recorded query against the current catalogue. Place Search before compaction and request restriction hooks after Search. Avoid using skill gates for the same tools. Hiding tools does not grant or revoke permissions. - Search `mode: :bridge` (candidate) exposes fixed `search_tools`, `describe_tool` and `call_tool`. `describe_tool` returns `name`/`description`/`parameters`. `call_tool` takes `%{"name" => n, "arguments" => args}` under the outer mandatory wire envelope. Selected tool schema, rules, approval names and C7 identity apply. Reserve bridge names and start in bridge mode to keep the prefix fixed from the first request. ##### Tool programs and isolated execution - `Tool.CodeMode.new/1` (candidate) needs distinct `tools: [names]`. Defaults `name: "run_tool_program"`, `max_calls: 8` (1–32), `timeout: 5_000` ms per admission/execution, `max_heap_bytes: 8_388_608`. Exclusive wrapper accepts `%{"calls" => [%{"tool" => name, "args" => args, "bindings" => bindings}]}` with optional nested bindings for unset args. A leaf is `[earlier_zero_based_step, optional_string_keys_or_zero_based_indices...]`. Preflight all bindings and enrolled, directly offered ordinary JSON functions before effects. Deferred bridge dispatcher and declared deferral tools are ineligible. - Each step uses ordinary hooks, schemas, guardrails, budgets and sync approval. Wrapper uses one tool slot plus one per admitted step. First failure stops the sequence. Missing path/denial/retryable step rejection yields a step-specific tool error. Unexpected deferral after dispatch fails with an unknown outcome. The nested deadline caps each step and combined retained binding values share the wrapper's return slot (external term bytes). Release values after last use. Overflow is `{:retention_limit_exceeded, %{boundary: :tool_program, bytes: bytes, limit: limit}}`. Only the last accepted result returns to the model. - CodeMode nested receipts carry `call_ref`, `program_call_ref`, one-based `program_step`/`step` and effect. `RunError.confirmed_program_steps` keeps observed confirmations including withheld output. The transcript carries the wrapper call/return. C7 refuses CodeMode with `{:unsupported, {:code_mode, :continuation}}`. Expose ordinary tools across rounds for durable per-effect admissions. - `Sandbox.new/1` and `Sandbox.tools(sandbox, opts \\ [])` (candidate). Bind host `backend: {module, config}`, nonempty `scope:`, string-keyed `identity: %{"id" => id, "version" => version}`, optional read-only absolute host mounts at unique `/inputs/name`, `network: :none` and `limits:`. Code max 65,536 bytes. Limits default/range are `cpu_millicores: 500 / 10..4000`, `memory_bytes: 134_217_728 / 16_777_216..4_294_967_296`, `time_ms: 10_000 / 10..900_000`, `processes: 32 / 2..256`, `output_bytes: 16_384 / 1..65_536`, `capture_bytes: 262_144 / 1..524_288`, `scratch_bytes: 16_777_216 / 1_048_576..134_217_728`. Host chooses all limits/mounts. - `sandbox_execute` forces approval. `sandbox_read` returns bounded merged UTF-8 output. `model:` adds `sandbox_capture` for image tool returns, with active profile checked at call time. Docker runner reads regular PNG at `/tmp/capture.png`. `jobs:` adds approved `sandbox_start` for a same-scope Jobs owner, returns `"submitted"` and `operation_id` used as job ID. Jobs keeps the receipt and sandbox keeps the output. Cancellation of the job and adapter execution have separate lifecycles. Confirmations carry `operation_id`, `status`, `exit_code`, `truncated`. Confirmed `"timed_out"`/`"output_limit"` use null exit codes. Local defaults four running, 64 retained, ten-minute retention. - Sandbox reserves operation ID before dispatch. `Sandbox.new_id/0` makes a fresh ID for `execute/3`. `read/2`, `capture/2`, `destroy/2` operate on the same handle and operation ID. Reservation, unavailable lookup and uncertain outcomes use `{:operation_exists, id}`, `{:unavailable, id}`, `{:result_unconfirmed, id}` respectively inside `{:error, ...}`. Mutation lost acknowledgements become `:unknown`. Queries give fixed `:tool_error` messages and each takes at most 5,000 ms or half the remaining tool budget. Retained reservation is volatile unless the host supplies a durable backend. - C7 effect ID equals sandbox operation ID. Identity/version binds executor, scope, mounts and limits. `retry_effect/4` cannot repeat a sandbox operation. Reconcile execution against authoritative receipt with matching ID (drop `"text"` from a read result). Reconcile `sandbox_start` against original Jobs admission. Missing evidence leaves uncertainty. Durable Jobs can wrap a C7 sandbox call. - Docker uses Linux UID/GID 65534, dropped capabilities, no-new-privileges, no network, read-only root and binds, cgroups for CPU/memory/swap/PIDs and sized tmpfs. Guest and host CLI have separate wall/output bounds and logging is disabled. Host daemon/socket, image and shared kernel are trusted. Mount contents may be printed, so authenticate scopes and curate inputs. Startup `{:error, :docker_unavailable}` calls for verifying local socket access, `docker info` platform/controllers (`linux true true true true`), installed image `sha256:` ID, no declared volumes and `/usr/local/bin/python3`. Bind directories need search permission as viewed by mapped guest identity. Cleanup labels `io.exagent.sandbox.operation` and private `exagent-sandbox-*` directories identify residuals after daemon/VM loss. [Tool control and sandbox recipes](tools-and-output.md) · [Event and trace contracts](observability.md) #### Memory, skills, plan and workspace ##### Memory | API | Contract | | --- | --- | | `Memory.tool(backend, opts)` | Required trusted `scope:` string (1–200 bytes) or arity-one selector receiving `RunContext`. Default `name: "memory"`, optional `description:`, `read_only: false`, `overwrite_on_create: true`, `max_file_bytes: 32_000`, `max_total_bytes: 128_000` and `max_files: 100`. Scope function failures are `{:memory_scope_failed, exception_module \| :throw \| :exit}` before access. Read-only offers only `view` and ignores the overwrite switch. | | `Memory.capability(backend, opts)` | Same options plus `preload: false \| true \| [mode: mode, max_bytes: bytes, priority_paths: paths]`. True or `mode: :data` attaches an `exagent.memory` block to the active user turn. `mode: :system` requires read-only operator scope. Once per attempt before first fresh request, including approval resume and destination handoff. C7 saves the projected request and fixtures can capture it. Frame 10/11 reject preload with `{:unsupported, :composition_request_projection}`. | | `Memory.preload(backend, scope, opts \\ [])` | `{:ok, text} \| {:error, reason}`. `max_bytes: 8_000` covers framing, escapes, listings and notices for both forms of preload. Visit `priority_paths: []` in given order (skip missing/directory, reject normalized duplicates), then remaining paths in path order. At first oversized file switch to listing paths. Returns `{:ok, ""}` if framing/notice cannot fit. Fix a reviewed block in a versioned agent definition to keep it stable through pause. | | `Memory.files/2`, `Memory.update/3`, `Memory.clear/2` | Host reads `{:ok, files}` or error. Update callback takes file map and returns `{:ok, replacement} \| {:error, reason}`. Only returned `{:error, :conflict}` retries, maximum eight attempts. Compare the reviewed digest inside the callback and return `{:error, :stale}` on change. Callbacks may run repeatedly and host edits bypass tool quotas. | | `Memory.load/2`, `store/4`, `validate/1`, `erase_scope/2` (candidate callback) | Backend callbacks. Load returns `{:ok, version, files}` and uses `{:ok, 0, %{}}` for absence. Compare-and-swap store returns a fresh positive version even for identical files, or 0 when an empty scope is left absent. Versions cannot be reused after deletion. `validate/1` and `erase_scope/2` are optional. Erasure requires quiescent writers and returns `Retention.outcome()` or error. | - Commands under `/memories` are `view(path, view_range?)`, `create(path, file_text)`, `str_replace(path, old_str, new_str)`, `insert(path, insert_line, insert_text)`, `delete(path)` and `rename(old_path, new_path)`. Paths up to 255 bytes, segments up to 100 bytes. Ranged views are one-based, first line must exist, end may exceed length, `-1` means through EOF. Insert line 0 prepends, and insert scans bytes and preserves existing line endings. Replacement requires exactly one match counting overlaps. Ambiguity reports count and up to ten locations. Check insertion/replacement growth before assembly. A scope above quota accepts non-growing changes. Edits serialize and survive failed runs. `overwrite_on_create: false` makes creation exclusive even after retries, including existing empty files. A normal `create` can overwrite concurrent changes. - `:ets` means `{Memory.ETS, Memory.ETS}`, with scope versions protecting against a stale writer after owner replacement. PostgreSQL takes configured backend `{Memory.Postgres, ...}` and migration 1. SQL reads/writes suppress query telemetry and logs. `[:exagent, :memory, :command]` carries count 1 and command/status only. PostgreSQL rejects an unrepresentable expected bigint as `:conflict` after config validation, before encoding or SQL. - Invalid tool commands and unavailable reads yield confirmed `:tool_error`. A scope error in preload yields `{:capability_failed, ExAgent.Memory.Capability, hook, {:throw, {:memory_scope_failed, kind}}}` with `hook` `:preload` or `:instructions`. Backend preload failure emits `%{command: :preload, status: :unavailable}` and supplies a bounded notice when possible. Host callback throws return `{:error, {:memory_backend_throw, term}}` and malformed store replies `{:error, :invalid_memory_backend_result}`. An unconfirmed tool write yields `:unknown` with `:memory_write_unconfirmed` inside `:tool_execution_failed`. Confirm using effect-specific evidence if reads could show stale or identical content. ##### Skills and request projection - `Skills.from_dir(root, opts \\ [])` returns `{:ok, skills}` or error. `Skills.from_dir!/2` raises `ArgumentError` on error. Discover sorted immediate visible subdirectories with `SKILL.md`. Any invalid skill rejects the catalogue. `tools: %{skill_name => [tools]}` keys by normalized frontmatter name, including names different from directories. Unknown keys give `{:unknown_skill_tools, names}`. Unreadable root gives `{:invalid_skills_dir, root, reason}`. `Skill.from_dir/1,2` and `Skill.parse/1,2` parse UTF-8 metadata/body. `Skill.new/1` supports in-code content. A directory file with an invalid body may give `{:invalid_skill, path, :missing_content}`. - Name NFKC normalization, 1–64 codepoints, Unicode letters/numbers, lowercase cased letters and single internal hyphens. Duplicates after normalization collide. Description up to 1,024 characters. Required YAML `name`/`description` must use supported values. Other fields are best effort and `allowed-tools` is informational. `SKILL.md` body reloads on each invocation while catalogue changes require agent rebuild. Keep skills as trusted host instructions. Skill loading never runs its scripts. - `Skills.tools/2` and `Skills.capabilities/2` have only `max_file_bytes: 262_144`, a positive byte limit for the loaded instructions and each reference file. File listing/wrapper/tool names are additional. `load_skill` returns instructions and up to 200 file paths. Traversal examines up to 2,000 visible entries and descends up to eight directories. A truncated traversal adds `(list truncated)` even when no path was found. `read_skill_file` is supplied for directory-backed skills. It can read an omitted listed candidate by relative path. Reject absolute paths, hidden components, escapes through `..`/symlinks, non-UTF-8 and oversized files as correctable domain `:tool_error` without spending tool retries. - `:skills` installs `Skills.Gate` before application request hooks and `Skills.Restore` after them. Manual `Skills.capabilities(skills, opts)` returns `%{gate: gate, restore: restore}` for ordering around compaction. A skill tool stays in the inventory but is unavailable until successful load. Identical copies in `:tools` are also gated, different same-name tools and `load_skill`/`read_skill_file` name collisions raise. Later hooks can narrow or expand offered registered tools, so keep authorization in Permissions. An unavailable call receives ordinary `{:unknown_tool, name}` correction. `Skills.loaded(messages)` lists successful loads once in most-recent-load order, using call IDs to join parallel calls with returns. - Loads are ordinary history returns and survive subsequent turns/snapshots/C7. If compaction removes a load from the request, Restore inserts a user-level message with the recorded instructions after leading instructions-only messages, before the first combined instruction/prompt when applicable. It uses the recorded body, not an edited file, until another load. This request-only projection happens after compaction threshold evaluation. ##### Plan and workspace (candidate) - `Plan.capability/1` adds `write_todos` and `Result.plan`. Replace the whole checklist with unique stable item IDs and `pending`/`in_progress`/`completed` statuses. Empty clears. Defaults `max_items: 32` and `max_bytes: 8192` compact JSON (ranges 1–128 and 1–32,768). Request-only final-user reminder preserves signed prefix, history keeps call plus short ack. Fresh runs start fresh plans and workflow nodes own their own list. C7 re-derives per-request plan from confirmed effective args and checks the projection against journaled requests. Denials preserve the previous list. An approved edit uses `{:approve, args: %{"items" => items}}` where `request.decisions` includes `:edit`. Prepared Frame 10/11 steps with input guards or tool-preparation hooks only offer approval/denial of the saved args. - `Workspace.capability/1` mounts 1–32 `{"/name", backend, :read_only | :read_write}` tuples, default `{"/scratch", :scratch, :read_write}`. Paths are absolute virtual paths under one mount, with single slashes and no trailing slash, dot segments or hidden names. Options default/max are `max_file_bytes: 32_768/1_048_576`, `max_total_bytes: 131_072/8_388_608`, `max_entries: 128/1024`, `max_results: 32/128`. Minima 1. Limits count hidden/unlisted POSIX entries. Grep bounds backend reads by remaining byte budget and gives `:scan_limit` when an additional file exceeds it. - Workspace tools `ls(path)` (use `"/"` to discover mounts) returns sorted direct child paths. `read_file(path, offset?, limit?)` returns UTF-8 `text` and `next_offset` (nil at EOF), page limit 4–4,096 bytes. `write_file(path, text)` replaces file. `edit_file(path, old, new)` replaces exactly one occurrence, counting overlaps, and a concurrent change conflicts. Both mutations run exclusively. `glob(path, pattern)` matches descendant basenames with at most one `*`. `grep(path, pattern)` searches a literal. Listings/searches return `paths` and `truncated`. Scans over the entry cap fail explicitly. - Scratch lives in private run-node ETS, released at scope close. Scratch and Memory mounts make implicit directories. `Workspace.memory(backend, scope)` loads/validates the full host scope before workspace bounds. `Workspace.results(store)` is read-only and resolves known `/results/` in the originating run within file-size limits. It has no listing. The store owns TTL and PostgreSQL scope identity. C7 reconstructs plan/scratch from confirmed effective args in recorded order, detects an earlier pending update superseded by a later one, and never replays external writes. - `Workspace.directory(root)` binds a pre-existing POSIX root's device/inode. Rechecks root identity and `File.lstat/2` components. Accepts singly linked regular files. Host owns root, ancestors and contents. Hostile concurrent namespace swaps leave a TOCTOU window. Writers must honor `.exagent-write-lock`, verify expected text and quota under lock, close an exclusive private temp and atomically rename. On abrupt owner death, inspect destination and remove stale lock/temp only after verifying quiescence. Directory listing can materialize one directory before enforcing the scan cap. Casefold aliases count once using the resolved destination's size. All workspace backends use ordinary tool authorization/effect receipts. Unacknowledged writes require reconciliation and stable host mount bindings. Custom backends implement `Workspace.Backend`. [Memory guide](memory.md) · [Skills guide](skills.md) #### Models, provider profiles and wire contracts `Model.resolve/2` resolves the adapter and `Model.profile/1` describes admitted feature sets. `Models.ReqLLM.new/1` uses official stock ReqLLM `generate_text/3`, `stream_text/3` and `ReqLLM.StreamResponse.process_stream/2`. Local resolution does no request IO. Pass a catalogue string, `LLMDB.Model` or explicit map/stock model spec. Keep `provider`, `id`, `capabilities`, `modalities`, `limits`, `cost` and `extra.wire.protocol` true to the deployed backend. Local resolution or declaration alone gives no compatibility/price evidence. | Concrete profile | Resolution | Tools/stream | Native schema | Reasoning | | --- | --- | --- | --- | --- | | `:chat_tools_v1` | `:openai` wire `"openai_chat"` | Yes | Yes | `:disabled` | | `:chat_tools_v1` | `:ollama`, `:lmstudio`, `:vllm`, `:groq`, `:deepseek`, `:mistral`, `:xai` Chat Completions | Yes, loopback evidence | No | `:disabled` | | `:chat_tools_v1` | `:azure` Chat Completions incl. catalogue `"openai_completion"` | Yes, loopback evidence | No | `:disabled` | | `:openrouter_chat_tools_v1` | `:openrouter` Chat | Yes | No | Both | | `:openai_responses_v1` | `:openai` or `:azure` wire `"openai_responses"` | Yes (Azure loopback) | Yes | Both | | `:anthropic_messages_v1` | `:anthropic` Messages | Yes | Catalogue `json.schema` | Both | | `:anthropic_messages_v1` | `:google_vertex` Claude `rawPredict` or `:amazon_bedrock` Claude InvokeModel with catalogue tools | Yes, loopback evidence | No | Both | | `:gemini_v1` | `:google` Gemini API or `:google_vertex` Gemini `generateContent` | Yes (Vertex loopback) | No | Both | | `:text_v1` | Any other route, `:openai` with no wire, Cerebras, Bedrock Converse, or explicit downgrade | Buffered text | No | Catalogue default | - `profile: :auto` selects via ReqLLM-resolved wire/default. Explicit profile must equal the selected one or be `:text_v1`. Stock puts o-series, GPT-4o, GPT-4.1, GPT-5 and later on Responses for the corresponding resolved IDs. Tools require `tools.enabled` except for unlisted local Ollama/LM Studio/vLLM IDs. Chat rejects catalogue `tools.strict`. `ModelSpec` resolves those local IDs silently via stock inline specs, preserves existing catalogue metadata and stores a resolved `LLMDB.Model` on the instance. Use `Model.model_name/1` for the ID. Ollama endpoint defaults to `http://localhost:11434/v1`. Local models use tool/prompted output. All profiles receive prompted output as text with a request instruction. - Cerebras stays text-only because stock ReqLLM 1.31.0 strips wrapped constraints, including `minimum` on buffered/SSE. Bedrock Converse stock merges distinct IDs with identical args and loses `server_tool_use` ownership in buffered/chunk data. Tool requests reject before IO. Bedrock Claude InvokeModel retains IDs in loopback including AWS EventStream and ETS/SQL approval resume. Buffered/SSE normalization still hides wire duplicate keys there. Hosted Azure/Vertex/Bedrock and additional local/Chat routes need endpoint qualification. Tests of sample routes describe that deployment and SDK version. - `Models.ReqLLM.new/1` keys `model:` (required), `profile: :auto`, `api_key: nil`, `auth_token: nil`, `base_url: nil` (HTTP(S), no userinfo), `reasoning_mode: nil` (derived), `reasoning_effort: nil`, `total_timeout: 120_000` ms (1–300,000), `foreign_history: :reject`, `prompt_cache: nil`, `service_tier: nil` (candidate), `provider_options: []`, `http_options: []`. `http_options` allows `:receive_timeout` and a trusted `:adapter` for buffered transport. Reject nonempty provider defaults in app config or model `extra` as `{:unsupported_options, :provider_defaults}` before IO/C7 binding. - `ModelSettings.new/1` takes map/keyword/struct with `max_tokens` (positive integer), `temperature`, `top_p`, `presence_penalty`, `frequency_penalty` (numbers), `timeout` (positive ms or `:infinity`) and `extra` (map/keyword). Defaults nil except `extra: %{}`, with non-nil overrides and shallow extra merge. ReqLLM rejects nonempty extra and profile-incompatible controls. Receive inactivity precedence is request `timeout`, `http_options[:receive_timeout]`, 60,000 ms capped by run deadline. Stock pool checkout defaults derive from receive timeout. ExAgent owns a linked model worker under the minimum of operation/run deadlines. Stock total timeout is disabled inside it. Streaming requires a tool profile and no injected HTTP adapter, `max_tokens: 4096` by default, range 1–4,096. Post-decode cap 4,096 public chunks, 65,536 external-term bytes/chunk and 1,048,576 total. Halt, deadline, exception and owner death close backend and owned work. Pre-decode allocations remain with stock. - `ExAgent.new(model: "provider:id")` makes environment mode for a model without explicit credentials, resolving through `ReqLLM.Keys` each request (app config then provider env). `Models.ReqLLM.new/1` and `Model.resolve/2` with credentials use instance mode. Anthropic `auth_token:` OAuth overrides `api_key:`. Ollama is key-free, LM Studio uses `LMSTUDIO_API_KEY` and vLLM `OPENAI_API_KEY` through stock. Missing required key before IO gives `{:model_request_failed, %RequestError{reason: :missing_credentials}}` naming the env variable in `body`. Never persist live adapter credentials. Persisted identity includes effective endpoint even when inherited. Rotate credentials within the same trusted account/scope and requalify metadata/route changes. Library lock does not pin consumer `req_llm`/`llm_db` versions. | Cloud route | Identity and options | | --- | --- | | Azure | Env `AZURE_OPENAI_BASE_URL`/`AZURE_OPENAI_API_KEY` with `AZURE_BASE_URL`/`AZURE_API_KEY` fallbacks. `provider_options: [deployment: name, api_version: version]` as needed. Use Azure v1 or Foundry endpoint for named Responses deployment. Pass `api_key: "Bearer " <> token` for Entra. Effective resource/deployment/API version enter binding. | | Vertex AI | ADC or `auth_token: oauth_access_token` and `provider_options: [project_id: project, region: region]`. `GOOGLE_CLOUD_PROJECT`/`GOOGLE_CLOUD_REGION` and `:req_llm, :google_vertex` config for project, region, access token or service account JSON. Default region `"global"`. Identity binds project/region/API model. | | Bedrock | Env `AWS_BEARER_TOKEN_BEDROCK`, `AWS_REGION` default `"us-east-1"`. Explicit key requires `provider_options: [region: region]` (lowercase ASCII alphanumeric/hyphens, initial alphanumeric, 1–63 chars). Constructor raises for missing/invalid region. InvokeModel binds runtime path, region and model ID. Vertex and Bedrock reject request retry keys with `{:unsupported, :idempotency_transport}` because streaming transport drops custom headers. | ##### Mandatory tool argument envelope 1. Each ReqLLM tool schema is wrapped as `%{"type" => "object", "properties" => %{"arguments" => inner}, "required" => ["arguments"], "additionalProperties" => false}`. The request includes a backend-only instruction. Caller shape is exactly `{"arguments": {...}}`, including `{"arguments": {}}` for no args. Default `%{}` parameter schema accepts any inner object. Explicitly close a zero-arg schema to forbid its keys. ReqLLM requires an object/boolean schema root and its reference-free subset. Logical schema and offered-name checks follow envelope admission. 2. Complete objects with unique observable keys and no stock error can be corrected if any call fails the envelope shape. Invalidate the entire batch before hooks, permissions, approval or tool/output effects. Return one `Part.Retry` per call instructing the model to resend every call with the exact envelope. Charge once per distinct function tool name against its `max_retries` (ordinary unknown-name budget for unoffered name). If any output tool is present charge one `output_retries` instead. Retry uses another model step and normal request/usage limits. Live and Frame 3 (including delegates) can record and resume the correction without tool intent. Frame 10/11 rejects immediately. 3. `exagent.arguments/1` is the normal per-call codec. `exagent.raw_arguments/1` marks a malformed-shape call in `metadata["arguments_codec"]` and replays the original object shape without wrapping it. Correct siblings keep their own codec. JSON history and v5 continuation preserve both. Older readers cannot replay the raw codec. Loopback exercised hosted-protocol replay. Hosted provider acceptance remains separate. 4. Truncated/unreadable JSON, nonobject root, visible duplicate keys including escaped equivalents, stock `error`/`invalid_arguments` metadata, exhausted/zero retry budget or Frame 10/11 rejection return `{:model_request_failed, %RequestError{reason: :invalid_tool_arguments}}`. The fatal request emits `[:exagent, :model, :request, :exception]` before `on_model_request_error/4`. Live recovery is text-only per capability rules. C7 refuses hook recovery. In stock 1.31.0 only buffered OpenAI/Azure Responses preserves the original argument bytes on qualified routes. Other routes, including Responses SSE, normalize arguments and fixtures observed first-key retention upstream. The host cannot reject a duplicate that stock removed. 5. `strict: false` default. Responses qualifies strict mode when every object explicitly closes `additionalProperties: false` and declares every property required, including empty object schemas. Required nullable replaces omission when suitable. Strict subset `type`, `properties`, `required`, `additionalProperties`, `items`, `anyOf`, `enum`, `minItems`/`maxItems`, numeric bounds, `pattern`, `description`, `title`. Across the wrapped schema, max 5,000 properties, 10 nesting levels, 1,000 enum values and 120,000 characters of property names/enum strings. One enum over 250 entries may total up to 15,000 string characters. Exceeding a strict bound keeps non-strict wire and local checks. ##### Reasoning, history, caching and tiers - `reasoning_mode` is stored as `:disabled` when advertised off is available or reasoning absent, `:enabled` otherwise. Constructor rejects unsupported modes. Disabled sends the off control where declared and can still receive thinking. `reasoning_effort` requires enabled plus a supported catalogue string `"minimal"`/`"low"`/`"medium"`/`"high"`/`"xhigh"`/`"max"` with Gemini's narrower set. Reasoning can consume the output token budget. - Chat keeps unsigned plain text as `Part.Thinking` and sends provisional `{:thinking_delta, text}` on streaming. Replay omits it and rejects explicit `reasoning_details` or opaque/signed blocks. Derived unsigned SSE detail can describe the same text. OpenAI reasoning Chat uses `reasoning_effort: "none"`, `max_completion_tokens` 1–4,096 (default 4,096), nil temperature. DeepSeek uses `thinking.type: disabled` for reasoning models. Use buffered text profile where required reasoning cannot be disabled. - OpenAI Responses uses `store: false`, `include: ["reasoning.encrypted_content"]` and no `previous_response_id`. Replays encrypted reasoning locally. `max_completion_tokens` at least 16. Reject sampling parameters and penalties. Only provider `completed` authorizes completion. `failed`→`:error`, `cancelled`→`:cancelled`, other noncompleted success finishes→`:incomplete`. `provider_options[:reasoning_summary]` (candidate) accepts `:auto`/`:concise`/`:detailed` or matching strings in enabled mode outside the C7 binding. - Responses `Part.Text.phase` `:commentary | :final_answer | nil`. Commentary reported on its own stream channel, answer text drives `Message.Response.text/1`, output, previews and validation. A narration-only completed response advances within limits. Buffered progress emits a commentary delta per accepted part. ReqLLM late phase metadata can restore phase at terminal while earlier unlabelled SSE deltas appear provisionally as text. Buffered stock can collapse identical adjacent commentary/final into the final answer. Native history replays labels, portable foreign history drops commentary. Usage includes both. - Anthropic Messages replays signed `thinking` and `redacted_thinking` byte-for-byte with matching `tool_use.input`. Enabled thinking forces auto tool choice and output retries enforce required output. Fixed thinking budget beyond `max_tokens` gives `{:unsupported, :thinking_budget}`. Direct Messages options `anthropic_version: "2023-06-01"` and `stop_sequences:`. Text profile also admits `:anthropic_top_k` and `:store`, subject to adapter validation. - Gemini preserves signatures on each thought/text/function part. Changed/missing bound signature gives `:invalid_history`. Edited thought/text content loses its signature and unsigned thought is omitted. First function call must be signed in enabled mode, stock supplies its placeholder on the other parallel/portable calls. Call IDs aren't replayed on Gemini. Keep parallel result order to avoid stock 1.31.0 misassociation. `reasoning_effort` maps to Gemini 3 `thinkingLevel` or a 2.5 budget, only supported catalogue levels among minimal/low/medium/high, default allowed set low/medium/high if none listed. Only wire `STOP` admits tool/output. Missing finish or blocked prompt with no candidates maps incomplete. A named choice uses `ANY`/`allowedFunctionNames`. Penalties reject, stock removes `additionalProperties` from declarations and local validation still checks. - OpenRouter enabled replays `reasoning_details` unchanged and requests auto tool choice. Disabled reasoning needs off and effort `"none"` capabilities and uses one `max_tokens`. `provider_options: [openrouter_provider: routing, app_title: title, app_referer: referer]` where routing accepts `order`/`only`/`ignore` lists of 1–32 bounded IDs and `allow_fallbacks`/`require_parameters` booleans. Bind upstream route, mode, effort and attribution. Pin the actual upstream for native replay of its reasoning. OpenAI Chat gateway configuration can instead truthfully declare an explicit `:openai`/`"openai_chat"` model spec and bind its endpoint/key. - Native response continuation v5 binds profile, target, routing, mode, effort, codec, metadata and reasoning. Versions 1–4 remain readable. `foreign_history: :reject` (default) gives `{:continuation_mismatch, :target | :routing | :mode}` for foreign native history. Plain text without continuation is portable. `:portable` sends foreign text/tool exchanges without foreign reasoning/signatures and keeps file ownership checks. Custom adapter tool IDs should be distinct UTF-8 strings of 1–512 bytes per response or nil for host-generated IDs. Definition-incompatible features raise with profile/model at construction. Per-request incompatibility yields `%RequestError{reason: {:unsupported, what}}` before IO. - `Model.profile(model).reasoning_binding == :prefix` for Claude Fable/Mythos 5.1–5.2, Claude Opus/Sonnet/Haiku 5.5 Messages and GPT-6.2 onward Responses. Fallback exposes it if any leaf does. Adapter checks the effective projected instructions, tools, prior input and consecutive reasoning blocks. Retire through newest invalid block and retain compatible later chain where possible. Missing legacy fingerprint resets. History remains intact. Emit `[:exagent, :model, :reasoning_prefix, :reset]` for retired reasoning, including portable switches. Tool catalogue changes and temporary projections can invalidate. Prefix check covers the data supplied to stock, so maintain stable file content, credentials and endpoint. - `prompt_cache: true` or `[ttl: "5m" | "1h"]` on OpenRouter/Anthropic. OpenRouter marks last system/newest message. Anthropic stock marks last tool, last system block and newest message. OpenAI automatically caches eligible prefixes, accepts `true`/`[key: key]` and supported GPT-5.6+ policies `ttl: "30m"` (Responses also `"12h"`). Unknown rate for 12h write leaves partial estimate. Gemini implicit cache reports `cache_read`, rejects this option. Reads can appear in `usage.details["cached_tokens"]`. Tier and cache preferences do not change the C7 binding. - `service_tier:` (candidate) only direct OpenAI, accepts strings or atoms `auto/default/flex/priority/fast/ultrafast/scale`. Flex requires stock LLMDB eligibility for model and API. Ineligible constructor raises, invalid preflight gives `{:invalid_option, :service_tier}`. Price with `Usage.service_tier/1` returned level. Missing evidence of level-dependent rates can leave cost partial. Same-endpoint Flex→Default can continue native history, no same-candidate retry for immediate 429 fallback, reserve for Default pricing. Local catalogue warns about EU Priority retirement on GPT-5.2/GPT-5.4/GPT-5.4 mini scheduled January 11, 2027. See candidate Doctor switch below. ##### Multimodal input, tool images and attachments - Prompt is UTF-8 string or nonempty ordered list of maps canonicalized to string keys. Part types `text`, `image_url` (http/https/data), `image`, Base64 `file` and `file_reference`. Bad part `{:invalid_prompt_part, zero_based_index}`, empty/invalid prompt `:invalid_prompt`. Shape, Base64 and UTF-8 checks leave verification of media contents, raw size, image size and URL trust to host. Whole prompt incl. metadata/Base64 spends history limit, exceeding it gives `{:retention_limit_exceeded, %{boundary: :input, bytes: bytes, limit: limit}}`. Outputs/tool payloads spend per-payload and total history limits. - Images need `:image` input. PDF needs `:pdf` catalogue input and OpenRouter, Anthropic, Gemini or Responses transport (`input_file`). OpenAI Chat and OpenAI text profile only transport image attachments. `Model.profile(model).supports_image_tool_results` requires tools and image input (all fallback leaves). Unsupported offered multimodal or replayed tool images gives `{:unsupported, :image_tool_results}`. Responses `function_call_output.output` uses `input_text`/`input_image` data URLs. Messages `tool_result.content` uses text and a base64 source for original tool ID. Gemini 3+ uses `functionResponse.response.content` for captions and ordered `functionResponse.parts` images with stock `inline_data`/`mime_type`. Other profiles default unsupported. Buffered and fragmented SSE tool-image replay have offline public transport evidence. - `Message.Part.User.file_reference(provider, file_id, media_type, size_bytes)` (candidate) builds a v1 portable `type: "file_reference"` map with those fields. Opaque ID up to 2,048 UTF-8 bytes, positive size, MIME lowercase without parameters. Gemini PDF URI maps to `fileData`. Anthropic Files supports authorized catalogue PDF, text/plain and JPEG/PNG/GIF/WebP. `ModelProfile.file_references` defaults to `[]`, accepts `[{provider_string, media_type}]` and Fallback intersects. Owning provider mismatch gives `:file_reference_provider_mismatch`, unsupported pair `{:unsupported, :file_reference}`, both before intent/IO. Host verifies actual file access, ownership, size and validity across resume, fallback and handoff. The retained reference spends metadata bytes and does not embed the file. Trusted full history can expose IDs. Text export omits them. - Gemini inline audio input needs `:gemini_v1` and `:audio` catalogue input. Check `Model.profile(model).supports_audio_input`, false by default and all Fallback leaves required. Use `file` with optional filename, MIME `audio/wav`, `audio/mp3`, `audio/aiff`, `audio/aac`, `audio/ogg`, `audio/flac`, `audio/mpeg`, `audio/m4a`, `audio/l16`, `audio/opus`, `audio/alaw`, `audio/mulaw` or `audio/webm`. Validate encoded bound before decoding up to 1,048,576 bytes per clip. Oversize `{:attachment_limit, :audio}`, incompatible MIME/model `{:unsupported, :modality}`. Requests replay retained clips even in later text turns or restored Server. Host can supply filtered `message_history:` for a new turn. Resume uses saved history. Handoff requires explicit grant. ##### Media, embeddings, classifiers and citations (candidate) - `Media.transcribe/3`, `speak/3`, `generate_image/3`, `ocr/3` take model, input and options. Transcription/OCR use `{:binary, bytes, mime}` or `{:base64, encoded, mime}` from an authorized source. Speech/image take UTF-8 text. Typed `{:ok, result}` or `{:error, %Media.Error{}}`. OCR returns markdown/indexed pages. Images carry `data`/`media_type` or hosted `url`. Finalize open RIFF/WAVE lengths `0xffffffff` before returning/storing, preserving other layouts. - Media/Embeddings direct defaults `max_input_bytes: 1_048_576`, `max_output_bytes: 4_194_304`, `max_items: 64`, `timeout: 30_000`, `rate_limiter: nil`, `estimated_tokens: nil`, `spend_budget: nil`, `observability: nil` and `req_llm: []` for admitted stock options. Embeddings `max_items` ≤1,000. Bounds are on input and decoded/serialized output. Matching TPM requires a positive estimate and quota retains reservation when usage missing. HTTP 429 applies positive Retry-After or 1s cooldown. Media result is `%Media.Error{reason: :provider_rejected, status: 429}`. 5xx/ambiguous transport can yield `:result_unconfirmed` and durable uncertainty. Local cancellation/deadline stops its worker and provider receipt may still be unknown. Strict token limits fail before tool HTTP with `{:accounting_unavailable, dimension, :normalized_only}`. Estimated mode plus finite request limit permits qualified subtotals. - `Media.tools/1` takes configured `transcribe:`/`speak:`/`generate_image:`/`ocr:` keyword lists with `model:` and direct options, required `result_store:`, optional `requires_approval: false` and `resolve_input: fn ctx, ref -> {:ok, tagged_bytes} | {:error, reason} end` required for input references. Tools use `media_` prefixes and inherit rate/spend/tracing with configured defaults. Return `ref`/`bytes`. `Media.fetch(store, run_id, ref)` reads v1 `operation`/`result` JSON under original run ID, audio/inline images Base64. Invalid envelope `:invalid_media_reference`. `Media.preprocess_audio(target, prompt, transcription_model, opts)` uses direct options plus `max_clips: 4` under shared deadline/output bound. Keeps supported audio or transcribes in original part positions. Returns `{:ok, prompt, usage}` or error with prior observed usage. Host owns preprocessing accounting. - `Embeddings.embed(model, text_or_texts, opts)` returns ordered vectors and usage. `Embeddings.rerank(model, query, documents, opts)` returns descending relevance with zero-based document indices. One request per call. Input bound covers query+documents. Options `price_per_token_cents:` and `price_per_search_unit_cents:` price observed evidence. Stock rounded-zero estimate stays unknown. `Embeddings.tools/1` configures `embed:`/`rerank:` with model/options, store and optional approval. `Embeddings.fetch(store, run_id, ref)` reads v1 artifact. Durable calls use normal effect reconciliation and stable tool/store binding. - `Classifier.new/1` requires adapter struct and `labels: %{id => description}` (2–32 IDs, 1–64 ASCII letters/digits/dots/underscores/hyphens. Descriptions UTF-8 ≤1,024 bytes). Optional `instructions:` ≤4,096 bytes, `timeout: 30_000`, `max_input_bytes: 65_536`, `rate_limiter:` and `estimated_tokens:`. `Classifier.classify/2` takes text or JSON object/array, returns label, optional confidence and qualified usage or error. `Classifier.ReqLLM.new/2` uses stock single-choice evaluation. Model catalogue via `ReqLLM.evaluation_models/0`. `Classifier.NxServing.new(serving_or_name, opts)` requires optional `:nx`, decodes string label or `{label, confidence}` (0..1 or nil), validates labels, and leaves usage unknown. Named serving owns batch/distribution and can finish after caller deadline. Failure is `:result_unconfirmed`. - `Classifier.evaluator(classifier, name, input: projection, pass: labels, version: version)` retains available usage on grading failure. `Classifier.selector(routes, label_from_input \\ default)` maps a trusted preclassified input to a versioned Flow route. Preflight usage belongs to host. `Classifier.tool/2` permits `requires_approval: true` and charges scoped request/usage in live runs. C7 confirms label/usage through tool receipt and ambiguous provider results require reconciliation. Confirming label alone does not confirm charge. - `Result.citations/1` reads accepted citations and `Message.Response.citations/1` reads against the normalized response text. Typed sources URL, attachment ID or document ID/index. Ranges are half-open, answer offsets zero-based UTF-8 bytes and source coordinates retain provider basis. Max 32 citations, 16,384 JSON bytes together, 2,048 reference bytes, title 256, quotation 1,024 (UTF-8 prefix). Oversized IDs are dropped whole. Invalid citations are discarded without rejecting valid terminal/usage. Text-changing hooks clear answer ranges. Only unchanged accepted text output preserves answer ranges. History/C7 stores metadata, next request omits citations. `:model_response` and `:run_finished` carry source vs accepted citations respectively. Strip through `Event.strip_content/1` for export. - Citation wire limits. Responses stock normalizes URL/file annotations without part association, so no answer ranges, omit annotations when commentary phase is present. Gemini grounding can use ranges for exactly matching leading segments. Anthropic can project normalized source locations, but stock 1.31 drops native citation blocks and deltas in offline captures. Validate application citations separately against trusted document identity and half-open source byte range. - Evidence on stock 1.31.0 (2026-11-26) covers OpenAI Whisper, TTS-1 WAV length finalization, GPT-Image-2 PNG, Anthropic hosted PDF/text/PNG C7, and OpenAI/Google embeddings. Google embedding probe lacked public token/cost and left its hold open. Vertex Mistral OCR and Cohere rerank have loopback evidence, while Gemini Developer API has no stock OCR route. Gemini audio has an opt-in hosted WAV probe. Hosted PDF ref uses `EXAGENT_LIVE_GEMINI_PDF_REFERENCE=1` with Google selected and ready-file URI/size. Qualification should distinguish local evidence and actual deployment responses. [Models and limits guide](models-and-limits.md) · [Supported profiles](status.md) · [Known limits](known-limits.md) · [Migration](migration.md) #### Budgets, quotas, fallback, compaction and accounting ##### Usage limits and qualified accounting - `%UsageLimits{request_limit: nil, total_tokens_limit: nil, input_tokens_limit: nil, output_tokens_limit: nil, tool_calls_limit: nil, max_budget_cents: nil, accounting: :strict}`. Counters nonnegative integers and budget nonnegative cents. Agent, per-call (candidate), ancestor and saved C7 policies intersect at smallest non-nil limits and strictest accounting. Request and tool counts are exact host admissions. A Fallback logical request can include many HTTP attempts. Reject whole tool batch if its count will exceed the allowance. Mark all `:not_executed`. Recheck cost/tokens after permissions for individual tools and just before model dispatch. A blocked admitted request still counts and can have unknown usage/open acknowledged intent. In-flight work may exceed retrospective thresholds. Child scope cannot widen ancestors, root totals already include scoped children. - `UsageLimits.check_before_request(limits, usage, admitted, quote \\ nil)` checks a supplied snapshot. Limit error `{:usage_limit_exceeded, dimension, value}` with `:requests`/`:total_tokens`/`:input_tokens`/`:output_tokens`/`:tool_calls`/`:budget_cents`. Strict metric policy rejects declared normalized-only contracts with `{:accounting_unavailable, dimension, :normalized_only}` before IO. Unknown profile is checked against actual reports. Strict monetary cap requires a complete explicit `estimate_cost:` and otherwise can stop with `:cost_unknown`. Estimated metric/cost limits require a finite request cap in current or ancestor scope and use known subtotals. Independent runs inside tools have independent ledgers. Frame 10/11 check recorded subtotals before preparing successors, including input mapping. - `estimate_cost: fn model, usage -> cents | {:partial, cents} | :unknown end` takes precedence over qualified upstream estimate, including unknown/failure. `CostGuard.estimator/1` accepts only atom keys `:input_per_1k_cents` and `:output_per_1k_cents`, either may be absent. It prices available token counts with partial marker when coverage/rates are partial. A direction marked unavailable gives unknown even if a legacy number is retained. Fallback supplies the group, so per-rate maxima across eligible leaves bound a flat estimate. `Usage.with_estimated_cost/2` accepts nil or usage and complete/partial nonnegative cents. - `%Usage{input_tokens: integer_or_nil, output_tokens: integer_or_nil, details: %{}, accounting: nil, units: %{}}`. A custom adapter with plain counts can leave `accounting: nil` to qualify provided counts as reported. Unknown is nil, observed zero is evidence. Explicit accounting is a closed string-key v1 map. Fields `version: 1`, `source: "model" | "req_llm" | "aggregate" | "legacy_snapshot"`, `quality: "reported" | "normalized" | "mixed" | "unknown"`, `provider_presence: "unknown"`, `input_semantics: "inclusive" | "exclusive_cache" | "unknown"`, `reasoning_semantics: "included_in_output" | "separate" | "unknown"`, `availability` for `input`/`output`/`cache_read`/`cache_write`/`reasoning` and `cost`. Optional `service_tier` (1–32 ASCII letters/digits/underscore/hyphen). Coverage values `"available"`/`"partial"`/`"unavailable"`. Cost has `source`, `quality: "estimated"`, `availability`, `cents`, `subtotal_cents`. `Message.new_response/2` reports invalid field paths. - ReqLLM usage is normalized. Tool profiles include cached tokens in input except Anthropic exclusive cache. All include reasoning in output. Evidence comes from stock `usage_reported` where exposed, otherwise positive cache counts, and provider reasoning detail (Responses, or Chat detail apart from whole completion). Anthropic has no measured thinking count. A synthesized zero or zero input+output beside generated output does not establish token coverage. Stock USD→cents conversion occurs once. Missing billable dimensions yield partial if a subtotal is known, unavailable otherwise. Inclusive input without separate cache rate avoids double pricing. OpenRouter's reported charge can supply complete pricing. `cost_cents` is the full estimate only when complete. Known portion lives at `usage.accounting["cost"]["subtotal_cents"]`. - Cumulative stream updates replace observed directions (including zero) and keep prior values as partial when the latest report omits them. A missing terminal report retains observed partial evidence. An unsuccessful dispatched attempt with no usage makes later aggregate partial/unknown. A skipped preflight does not. Legacy reported numbers can remain in aggregates with partial coverage, so sum original qualified rows for measured-only subtotals. `usage_status: :complete | :partial | :unknown` follows available evidence, separate from `cost_status`. A model's incomplete terminal is diagnostic, preserving `partial.pending_response` and qualified usage. - `Usage.units` (candidate) keys `audio_input_milliseconds`, `audio_output_milliseconds`, `input_characters`, `output_images`, `output_pages` and `rerank_search_units`. Each has `"value"`, `"availability"` and `"quality"`. Qualities `measured/reported/normalized/mixed` for a known count, unavailable nil/unknown. An omitted unit makes no assertion. Stock transcription duration can be normalized from segment endpoints (numeric zero preserved). Speech uses input graphemes, image/OCR use returned item counts. Media `price_per_unit_cents` prices input milliseconds for transcription, graphemes for TTS, images for generation and pages for OCR. Absent unit can use a qualified stock price. Known units with missing tokens can yield partial run usage. - Tenant accounting uses root accepted `:run_finished` keyed by tenant/conversation/run ID once, cumulative across resumes. Pauses are interim. Failures/cancellations can carry `payload.partial` and Jobs by durable job ID. Authorization and logical-turn reservation/idempotency are host responsibilities. Reuse same key/estimator term/pricing on retry, inspect lost admissions and reconcile unknown charges. `Server.usage/2` reads conversation aggregate. Independently verified zero may close a hold. Missing cost remains null. ##### Shared spend budget - `UsageLimits.Budget.new(adapter: {module, handle}, reservation_cents: quote, timeout: 5000)` creates a scoped account handle. Attach with `spend_budget:` (candidate). Reserves each physical attempt (incl. retries, Fallback, classifier/Media) or separately priced tool before dispatch, once per fee. Descendants inherit account. C7 restores same authorized account. Replayed responses skip reservation. Amounts are accounted internally in bounded signed 64-bit microcents. Windows align with Unix epoch and a hold carries across windows. Complete charge (including confirmed zero) replaces reservation. Partial charge can raise hold. Missing/unconfirmed final price retains it. Closures remain idempotent. - `UsageLimits.Budget.ETS.start_link/1` requires `name:`, `limit_cents:`, `window_ms:`, defaults `max_receipts: 10_000` (refuses when full) and `thresholds: []` (candidate). Local owner loss loses state. ETS committed balance reads don't contend with admission. `UsageLimits.Budget.Postgres.new(repo, scope: scope, limit_cents: limit, window_ms: window, thresholds: [])` uses authorized shared scope and migration 1. Use same limits/window on replicas. Reservation and hold increases serialize per account. Final charges within holds lock receipt only. A dedicated supervised Repo pool isolates Budget connection occupancy from C7. - `Budget.balance(budget, opts)` (candidate) returns `window_start` UTC ms, `limit_cents`, `charged_cents`, `held_cents`, `partial?`. With gaps, charge is a subtotal or nil when no positive subtotal is known. `Budget.Postgres.pending/1,2` and `statement/2` (candidate statement) page `:items` and `:cursor` with `limit: 100`, `after: nil`, `timeout: 5000`. Statements carry receipt/request ID, reservation time/window, held/charged cents and candidate labels `model`, requested `tier`, host agent and `kind`. Omit invalid or >64-byte label values. Pending or open receipt has unknown final charge. `Budget.reconcile(budget, receipt_id, billed_cents)` is idempotent for equal amount, `{:error, :budget_settlement_conflict}` for differing closed amount. - `Budget.Postgres.update_limits(account, limit_cents: new_limit)` retains window/charges/holds. Compare previous policy and accept repeat of current limit. Stale handles can settle earlier holds but reservations give `:spend_budget_policy_mismatch`. Account refusal `{:usage_limit_exceeded, :budget_cents, {:retry_after_ms, wait}}`, with `:unknown` for unresolved holds or `:infinity` when quote exceeds limit. Lost ack `{:accounting_unavailable, "cost", :budget_unavailable}` can leave a committed hold. First refusal adds zero model requests/effects. Eligible durable Jobs with proof of effect-free preparation can reschedule a finite denial. - `thresholds:` (candidate) distinct integer percentages 1–100, claimed once per receipt's reservation window/account across replicas based on observed ceiling. `[:exagent, :usage_limits, :budget, :threshold]` is best effort. `[:exagent, :usage_limits, :budget, :settlement]` carries observed charge/subtotal/coverage. ##### Provider quota and model fallback - `RateLimiter.start_link/1` or child spec requires `name:` (local atom or via Registry) and `limits: %{key => [rpm: ..., tpm: ..., concurrency: ..., default_output_tokens: 4096]}`. Limits are positive, at least one RPM/TPM/concurrency per key. Key is `Model.system/1` string or `{provider, model_name}` with one granularity per provider. Unconfigured keys pass through. Use stable named limiter or local PID on agents. Delegates inherit. A per-tenant Registry + DynamicSupervisor can own independent accounts. - Local `max_queue: 1024` waiters/key, optional `clock: fn -> monotonic_ms end` for quota time. FIFO, rolling 60s from dispatch with expiry rounded up to second. TPM estimates projected input at ~4 encoded B/token (incl. tools, native schema and provider reasoning replay) plus output cap or default token estimate. Complete terminal counts replace estimate. Partial/missing leaves it charged. Monitor owners/deadline for unused holds. Restart clears history/cooldowns while already granted local permits can proceed. - Denial `{:rate_limited, key, wait_ms | :infinity | :queue_full | :unknown}`. Estimate bigger than TPM window or cooldown above 4,294,967,295 ms gives infinity. Known wait incompatible with deadline denies before enqueue, missing deadline ack gives `:deadline_exceeded`. Unavailable limiter `:rate_limiter_unavailable`. 429/503 hints cool the key, Google typed `google.rpc.RetryInfo.retryDelay` can raise Retry-After. `RateLimiter.reset_cooldown(name, key, timeout: 5000)` clears only matching key's cooldown. Lost acknowledgement `{:error, :result_unconfirmed}`. Reconciliation uses original operation evidence. Require authorization ack before first logical request/C7 intent and recheck deadline after C7 ack. Failed settlement retains observed usage in partial and complete diagnostic response in `pending_response`. Incomplete reason takes priority. - Shared `shared: [adapter: {RateLimiter.Postgres, handle}, lease_ms: 120_000, timeout: 5000]`. `RateLimiter.Postgres.new(repo, scope: scope)` with equal limits/scope and PostgreSQL quota schema 1. Local `clock`/`max_queue` are local-mode options. Shared refusals immediate and fresh permit per physical attempt. Lease/deadline bound backend and provider attempt. Lease expiry frees concurrency and leaves rolling charges for one more minute, acknowledged terminal frees slot and caps charge duration at 1 minute from settlement. Confirmed unused drops charges. First settlement wins. Background settlement retries same ID/outcome, 25 ms to 1s backoff while it fits, with final bounded report if deadline expired before ack. Shared `reset_cooldown/3` works from any replica. `{:rate_limiter_migration_required, 1}` covers missing/malformed tables, columns (incl. `settled` default/nullability) and indexes. `RateLimiter.Postgres.cleanup_expired(repo, limit)` reclaims expired attempts/cooldowns. - `Models.Fallback.new/1` requires nonempty ordered `models:` (resolved executable structs, can nest), defaults `max_retries: 2` (0–10), `backoff_ms: 500`, `max_backoff_ms: 8000`, `retry_statuses: [408, 429, 500, 502, 503, 504, 529]`, `retry_transport: false`, `fallback_on_quota_denial: false`. Leaf implements `request/4`, `model_name/1`, `system/1` and optional `request_stream/4`. Streaming-only leaf gives `{:error, {:unsupported, :buffered}}`. Buffered success needs a `Message.Response` and executable updated model. Invalid shape is `:invalid_model_result`. Preflight checks capabilities of full tree, intersects support for tools/native/files/audio/image results, and selects history-compatible candidates. - Retry only eligible no-output failures. Transport/total timeout may have billed and require transport opt-in. First model stream event (incl. cumulative `:usage`) commits attempt unless it is an eligible pre-output error. Backoff exponential+jitter and at least Retry-After when available. Delay above ceiling or exhausting deadline skips remaining same-leaf retries. Buffered Chat can hide Retry-After. Telemetry `[:exagent, :model, :retry]` has scheduled `delay_ms`. Recheck deadline after handler/wait and history validation, return last dispatched provider error if available, otherwise `{:timeout, :total}` pre-dispatch. Updated `RequestError.model` is revalidated before another attempt. Unusable replacement stops with prior usable state. Nested max attempts per leaf multiply outer and inner (retries+1). Terminal inner preflight stops outer routing. - Default quota denial stops. With `fallback_on_quota_denial: true`, compatible leaves request immediate permits with or without deadline, and confirmed denials skip leaf retries throughout subtree without disturbing queued waiters or spending requests/usage. Lost ack, unavailable limiter or deadline still stops. If all refuse pre-dispatch, shortest finite delay wins, otherwise `:queue_full` then `:unknown` then `:infinity`. After provider error keep last error if remaining leaves refused/mismatched. Durable Jobs can defer only safe initial refusals with schedulable waits. - `validate_resume/4` target/routing/mode mismatches skip candidate before IO/retry telemetry. If all mismatch, first mismatch unless prior dispatched error. Other preflight errors are terminal without dispatch. `foreign_history: :portable` on ReqLLM leaf can admit otherwise foreign history, excluding reasoning/proprietary metadata and retaining ExAgent tool codecs. All C7 leaves implement preflight, including backups, even with static matching binding. `Models.Fallback.codec(Models.ReqLLM.codec())` or resolver function needs `dump/1`/`load/2` for every leaf, including unused backups, or `{:model_state_not_persistable, module}`. Preserve ordered tree and stateful script positions. Use response `model_name` only when unique to identify answering route, otherwise join host attempt receipt with route label. Inclusive run cost cannot be attributed solely to the answering leaf. ##### Compaction, overflow and finish control - `Compaction.capability(compactor, opts)` projects request-only messages. Custom `compact(messages, opts, %{deadline: deadline, params: params, run_id: id, step: step})` and optional `validate/1`. Invalid/failed projection leaves input and emits `[:exagent, :compaction, :stop]` status `:error`. Success `:compacted`/`:no_change`. Default estimator includes request content/tools/native-schema. Custom `token_counter` supplies entire estimate. Keep compaction before synthetic user notes and Skills restore after it. Frame 10/11 reject modified requests before model IO with `{:unsupported, :composition_request_projection}`. - `Compaction.ClearToolResults` (candidate) defaults `threshold_tokens: 4000`, `keep_recent: 3` counted per successful/domain-error return, including parallel. `exclude_tools: []` and `keep_call_ids: []` pin matching returns. Replace only shorter payloads with marker keeping call, status/pair, offload ref and byte count. Pin the entire prefix through last provider-protected exchange. Canonical history, instructions, prompt and retries remain. `estimated_tokens_saved` is projection estimate, independent from billing. - `Compaction.Summary` (candidate) defaults `threshold_tokens: 4000`, `keep_recent: 6` messages, or `{:turns, n}` with n≥1. Keep tool exchanges paired. Keep current user and instruction/conversation groups, bounding eligible region around active request. User-level summary goes before active user. Required `summarize: fn old -> ... end` or arity two with effective monotonic deadline/nil, optional `token_counter:`, `memo:` and `preserve_signed_prefix:` (true on prefix-bound profiles, false otherwise). Return nonblank UTF-8, `{:no_change}` or `{:error, reason}`. Invalid text `:invalid_summary`. Summarizer IO owns its accounting/deadline and can run again. Fixtures propagate to its nested run. - `Compaction.Memo.start_link/1` (candidate) optional `name:` and `max_entries: 1024`. First-message key, stores positions/digest of earliest eligible exact messages. Reuse if still contiguous/eligible. Extend with prior summary + newly eligible when projection exceeds threshold. Changed/earlier eligible messages rebuild from original chronology. Use separate memo per policy. FIFO oldest conversation eviction, unavailable falls back to direct summarization. Wait at most remaining run deadline and 5s per memo operation. Already-running callbacks/writes may finish after expiry. - `context_overflow: {compactor, opts}` (candidate) permits one extra request per live run after explicit `%RequestError{reason: :context_overflow}` (recognized provider input-window codes). Fallback policies first, compaction before error hooks. Reprojection starts from effective request, preserving offered tools, active user, signed prefix, accepted steering and trailing plan/final reminders. Needs identifiable prompt and positive estimated savings. Retry same step with fresh request ID, admission/quota and prior usage, including qualified failed usage. Any text/thinking/tool-argument stream fragment commits original request and rules out retry. Second overflow terminates. `:context_compacted` emits step/reason/savings. Frame 3 rejects `{:unsupported, :context_overflow_recovery}`, Frame 10/11 `{:unsupported, :composition_request_projection}` before opening/claiming (even unselected steps. Late-loaded delegates on load). - `UsageLimits.WrapUp.new/1` (candidate) final capability to close on next admissible step. Defaults `remaining_requests: 1`, `remaining_tokens: 128`, `remaining_tool_calls: 0`, `remaining_budget_cents: 1`, `remaining_ms: 1000`, optional `instruction:` ≤1,024 bytes nonblank UTF-8. Nil disables one trigger. Request removes function offers but retains output tool. Hard limits and validation still apply. Reserve one closing slot per needing ancestor. `UsageLimits.WrapUp.reason/1` reads a retained closure, `[:exagent, :usage_limits, :wrap_up]` reports selection even if later failed. Frame 3 journals projection, Frame 10/11 reject. Last-slot uncertainty needs explicit `Continuation.reconcile_model/5`. Rerun requires another slot. - `max_steps: 50` (positive) and `on_max_steps: :error` default. `:final` on last step appends request-only final instruction with functions declared but not executable. Sends `tool_choice: none` or output tool where supported. Late function call is `:not_executed` and `{:max_steps_exceeded, max_steps}`. Scoped child has own steps and shared request budget. ##### Terminal and error triage | Boundary | Host reason or evidence | | --- | --- | | Definition/call config | `ArgumentError` names invalid key, including mutated struct recheck before IO. | | Model request | `{:model_request_failed, %RequestError{}}`. Bare adapter/bad result/missing stream errors use provider nil if none known, Test `:test`, Fallback own `:fallback`. Examples `:invalid_model_result`, `{:unsupported, :streaming}`, `:incomplete_stream`, `:invalid_stream_event`. C7 missing/invalid callback `:model_continuation_preflight_required`/`:invalid_model_continuation_preflight`, ordinary preflight errors wrapped like request failures. | | Provider model finish | `:stop` and `:tool_calls` admit based on actual parts. `:length`/`:content_filter`/`:cancelled`/`:error`/`:incomplete`/`:unknown`/nil give `{:incomplete_response, finish}`, unrecognized→`:unknown`. ReqLLM SSE needs terminal evidence in a decoded chunk. An incomplete finish skips post/recovery hooks, execution and executable history. Provider cancel is failed status. Host cancel reason/status `:cancelled`. | | Invalid model response | `:duplicate_tool_call_id`, `:invalid_tool_call_id`, `:invalid_model_usage`, `:invalid_model_response_transform`. | | Tool/output admission | `{:duplicate_tool_name, name}`, `:invalid_tool_definition`, `{:invalid_tool_schema, name, errors}`, `{:invalid_tool_callable, name}`, `{:invalid_tool_control, name, field}`, `{:tool_requires_deferral, name}`, `{:invalid_output_schema, errors}`, `:invalid_output_configuration`, `{:output_retries_exhausted, error}`, `{:tool_retries_exhausted, name, error}`. | | Retention/other | `{:retention_limit_exceeded, %{boundary: boundary, bytes: bytes, limit: limit}}` or stream chunk count/limit 4096, `:omitted_payload_history`, `{:execution_failed, exception}`. | - `RunError.reason` bounded to 4 KiB. `partial.pending_response` can preserve incomplete response and `payload_omitted` diagnostic. Other `RequestError.partial_response` copies can also omit payload at 4 KiB. `run!/3` raises the RunError or `RunPaused` with `result.continuation`. Absolute monotonic `deadline:` is scope-wide and distinct from receive inactivity, operation timeout, tool admission/execution and C7 lease/active-time. Cleanup can outlast deadline and external IO remains subject to receipt reconciliation. #### Diagnostics ##### `mix exagent.doctor` - From a compiled consumer. CLI loads paths and leaves the app stopped. Running `Mix.Tasks.Exagent.Doctor.run(args)` inside Mix sees live owners. Zero provider calls and credential presence only. Can temporarily start configured PostgreSQL Repo for `--check-store` or `--check-recovery`. `--json` returns `%{schema_version: 1, status: :ok | :missing, checks: [%{id: id, status: status, required: bool, action: text, details: map}]}`. Human mode prints rows and missing/unverified summary. Row `ok/missing/unverified/warning`. Prints before raising `Mix.Error` if required row missing. Invalid arguments/configure errors nonzero. Missing optional, warning and unverified permit successful CI. - Select catalogue with `--model P:ID` or `--model test` and `--profile PROFILE` (default auto). Candidate switches `--catalogue-max-age-days N` (default 30, nonnegative), `--files-api`, `--stored-responses`, `--base-url URL` and `--service-tier TIER` are optional advice inputs. Stable checks `--check-store`, `--check-run-headers`, `--check-catalog-lock`, `--check-jobs`, `--check-quota`; candidate checks `--check-recovery`, `--check-catalog`, `--check-mcp-lock`. CLI rejects repeats, unknowns and positional args. - Host `config :my_app, :exagent_doctor, [...]` keys `model`, `profile`, `files_api`, `stored_responses`, `base_url`, `service_tier`, `catalogue_max_age_days`, `store`, `catalog`, `catalog_scopes`, `conversations`, `mcp_finch`, `quota_repo`, `jobs_repo`. CLI wins. Optional packages report availability. `json.jason_decimal` is required and exercises decoder. Compile Decimal and run `mix deps.compile jason --force` if missing. | Row | Meaning and diagnostics | | --- | --- | | `model.profile`, `model.credentials`, `model.r1_2`, `model.catalogue` | Catalogue protocol and declared capabilities alongside admitted features, credential variable name/presence or key-free Ollama. An unlisted ID stays unverified without stock unverified-ID warning. Envelope row recommends qualify. Catalogue gives installed version/snapshot age. | | `model.lifecycle` (candidate) | Warning with canonical model, state `retired/retirement_scheduled/deprecated/invalid_retirement_date` and optional replacement/date. Invalid date sets `invalid_retirement_date: true` and null `retires_at`. | | `model.provider_redirect` (candidate) | Local advice for Google Developer API Gemini 2.5 Pro→3.8 Flash, Flash→3.5 Flash-Lite, date 2026-12-01. State scheduled/effective. | | `model.service_tier_retirement` (candidate) | For affected OpenAI EU models with Priority/fast tier, effective HTTPS host `eu.api.openai.com` (configured or resolved), effective date 2027-01-11 with scheduled/effective state and candidate model/tier metadata. | | `model.provider_files_retention`, `model.provider_responses_retention` (candidate) | Optional notices for provider-owned retention of Files API / stored responses, independent of local erasure. | | `req_llm.finch*`, `mcp.transport`, `mcp.finch`, `repo.configuration`, `repo.process`, `runtime.server`, `runtime.conversations`, `runtime.jobs` | Check stock Finch config/process, named host HTTP/1-only MCP pool, Repo descriptors/processes and local owners/registry. App stopped leaves process observation unverified. | | `store.ets`, `store.custom`, `store.configuration`, `store.postgres`, `store.migration`, `store.format`, `store.maintenance` | Config, snapshot/admission/native data-level schema and maintenance indexes. Segment mode verifies fragment columns/cascade. Format reader/write level and unified migration 1. `store_migration_required` details include internal SQL version (headers 4, admission 5, recovery 6, timers 7 even with no rows) and `unified_version: 1`. | | `store.run_headers`, `store.recovery`, `store.catalog` | Explicit header-vs-journal verification with `run_header_missing`/mismatch and namespace/logical ID. Recovery checks SQL 6/index/projection without reading bodies. Catalogue census by definition/policy/model incl. settled unadopted records. Missing headers unverified, custom scope with missing references unclassified. | | `catalog.lock`, `mcp.lock` | Verify local generated lock against compiled app config or per-endpoint pinned files. MCP check never contacts remote or invokes the callback. | | `jobs.durable`, `quota.postgres` | Read-only schema/connection on configured Repo/search path. Distinguish absent Jobs table and incomplete admission. Quota missing schema reports `rate_limiter_migration_required` version 1, incl. `settled` default/nullability checks. | ##### `mix exagent.qualify` (candidate) - Switches standalone `--help`/`-h` or required `--model P:ID`, optional `--base-url URL`, `--json`, `--yes`. Reject positional args/repeats/unknowns. With no yes, consent prompt gives model, destination, 10-request allowance, 2,048-token maximum and credential forwarding on override. Non-yes/EOF declines. HTTP only on localhost, 127/8 or ::1. Other destinations HTTPS. Reject userinfo, query, fragment. Vertex/Bedrock derive endpoint and reject overrides. Uses env-mode stock adapter, automatic profile, no output/tool retries and 45,000 ms per operation. Ordinary Chat/enabled reasoning 2,048 output tokens, other ordinary cases 256, truncation 32. - JSON v1 `%{version: 1, model: spec, profile: profile, output_mode: mode, status: pass_or_fail, requests: observed, request_limit: 10, cost: %{currency: "USD", upper_bound: number_or_nil, basis: :catalogue_limits | :unknown}, cases: rows}`. Row `id,status,required,diagnostic,requests,effects,usage`. `diagnostic` has `code` and bounded details. `usage` has qualified `input_tokens`, `output_tokens`, `quality` or nulls. Requests count matching `[:finch, :request, :start]` with synthetic marker including connect failures, not logical admissions or upper-bound estimates. Logs/confirmation to stderr in machine output. Print before nonzero on required failure. Unknown/custom/regional endpoint pricing yields null bound. For known default endpoint, sum applicable token/request rates across catalogue context/output ceilings and all allowances, apply multipliers, round USD upward to six decimals. Cancellation may incur provider charge. | Case | Required evidence and diagnosis | | --- | --- | | `tool_simple`, `tool_parallel`, `tool_stream` (2 requests each) | Expected batch 1/2/1, identical marker args for parallel with distinct IDs, matching successful receipts and exact effects, plus stream started/finished events. `tool_round_trip` on success. Negative codes `parallel_calls_collapsed`, `unexpected_tool_call_count`, `parallel_calls_split`, `unexpected_tool_arguments`, `invalid_tool_call_ids`, `tool_receipts_mismatch`, `stream_tool_events_missing`. | | `typed_output` (1) | Exact typed fixture value, `typed_result` or `unexpected_typed_result`. Prefer native by declared support, then tool, then prompted. | | `truncated_envelope` (1) | Zero effects and `invalid_tool_arguments` or length terminal with observed nonempty bad marker-tool argument fragments (`incomplete_tool_arguments`). Valid envelope, absence of evidence or thinking-only length do not pass. Negative `truncated_envelope_executed`, `length_without_tool_evidence`, `truncation_not_observed`. | | `cancellation` (1) | Halt on first provisional text/commentary/thinking/argument delta with zero effects, `stream_halted` or `cancellation_not_observed`. | | `reported_usage` (1, optional) | Both available input/output counts, `usage_available` or `usage_unavailable`. | - `not_applicable` cases have zero requests/effects and `streaming_unsupported` (text profile stream/cancel) or `tools_unsupported`. Other diagnostics `request_count_mismatch` with expected/observed, `terminal_missing`, `http_error` with status, `transport_error` with transport, `incomplete_response` with finish, `timeout`, `usage_limit_exceeded` with dimension, exposed atom reason or `run_failed`. Successful local tests and passing protocol rows certify only tested boundaries, separate from response quality and deployed backends. - Host triage. Match event namespace, agent ID and request ID. For `:checkpoint_pending` inspect `CheckpointError` and health persistence then retry the exact checkpoint, never the original prompt/effect. For `:unavailable` no command sent. `{:delivery_unconfirmed, id}`/`:result_unconfirmed` require original receipt evidence. Langfuse/Opik empty input/output are normal when content capture is off. Provide sanitized boundary reason, partial counters, package/source version, Elixir/OTP and model/profile in reproductions. Keep credentials, whole results and unredacted traces private. [Troubleshooting guide](troubleshooting.md) · [Testing guide](testing.md) · [Agent entry points](agents.md) --- ## Support and limits ### Supported features and limits This guide describes ExAgent 3.0.0. Its runtime targets are Elixir 1.18 / OTP 28 and Elixir 1.20 / OTP 29. The general model backend uses official ReqLLM 1.31. Applications can implement `ExAgent.Model` for a different adapter. #### API stability ExDoc groups modules under **Stable API** and **Candidate API**. Each public module has a stability label. A **candidate API** label beside a function or callback overrides its stable module's tier and applies to its default arities. The versioned inventory in `priv/api-stability.exs` is available in the source and package. | Tier | Compatibility | |---|---| | Stable | Strict SemVer. A breaking change requires a major release. This tier includes `ExAgent`, `ExAgent.Server`, `ExAgent.Store` and `ExAgent.MCP.Client`. | | Candidate (experimental) | Public APIs can break in a minor release with a documented migration. This tier includes `ExAgent.Coordination.Composition`, `ExAgent.Coordination.Flow`, `ExAgent.Sandbox` and `ExAgent.Eval.Online.Durable`. | | Internal | Implementation modules and hidden functions carry no compatibility guarantee. ExDoc omits them. | A candidate graduates after an application adoption trial and qualification of the same contract on its real backend. A candidate integration retains its tier when called through a stable module. The native OpenTelemetry adapter, versioned catalogue, chat view and reader, input-form helpers, guardrails, C7 deferred calls and recovery, shared budget adapters and subject erasure are stable. The stable `Jobs.Durable.recovery/2` callback was exercised during a rolling deploy and with Oban Lifeline on a live provider request. Provider coverage follows the named profiles and the capability limits below. [Upgrade guide](migration.md#check-the-api-stability-tier) The stable installation path includes `--chat`, `--model`, `--auth`, `--no-auth` and `--scope` on `mix exagent.install`, all three generators and `mix exagent.catalog.lock`. The ExAgent calls emitted by the 3.0 generators remain compatible throughout 3.x. A breaking change to generated code requires a deprecation cycle or a rewrite provided by `mix exagent.upgrade`. The goldens check the generated application, host tests and Eval suite against the stable manifest, including `Server.regenerate/2`, `Server.regeneration_target/1`, `Eval.Case.new/3` and `Eval.equals/0`. The offline testing path covers `ExAgent.Case`, `ExAgent.Testing`, `ExAgent.Fixture`, core Eval cases, evaluators, results, reports and suites, and `mix exagent.eval`. The case, cassette and report formats are versioned. `Tools.deftool/3` supports `effect:` with a default of `:write`. Use `Tool.new/1` to declare a write tool's read-only `reconcile:` callback. An uncertain tool return can preserve reported usage. The callable receives `RunContext.call_ref` and the idempotency key from its first dispatch. `:catalog` is stable for starting a Server, deciding an approval and defining a `Jobs.Durable` worker. An `ExAgent.Catalog` can be the first argument to `ExAgent.resume/3` or `resume_stream/3`. The catalogue must supply the saved agent definition and bindings for the pending revision. `Catalog.cast/1` recognizes a catalogue from a callback. `Store.namespace/1` returns the effective namespace of a scoped Store. `ExAgent.Migration.up/1`, `down/1`, `current_version/0` and `migrated_version/1` are stable. The unified PostgreSQL version sequence is append-only. Once a version is published, its DDL stays fixed in both directions. Put explicit versions in host migrations. The deprecated per-adapter helpers stay callable through 3.x and are scheduled for removal in 4.0. [PostgreSQL upgrade](migration.md#upgrade-postgresql-and-roll-out-a-store-format-level) | Stable surface | Candidate functions, options, fields and variants | |---|---| | Tools and context | `Tool.new/1` with `:reservation_cents` or `:max_heap_bytes` and `Continuation.ApprovalRequest.call_ref`. Classifier guard variants in `Capability` and CodeMode's `RunError.confirmed_program_steps`. | | Testing and Eval | `Eval.judge/1`, `Eval.calibration/3`, `Eval.Case.from_run/2`, `Eval.Suite.capture/1`, `Eval.Suite.labels/0`, scenarios, simulator output, workflow-specific evaluator options and the durable-child `:delegate` stub. | | Models, messages and usage | `ModelProfile.reasoning_binding` and `file_references`, `Message.Part.User.file_reference/4`, `Message.Response.citations` and the `citations/1` accessors on `Message.Response` and `Result`. `Message.Usage.units` and `with_estimated_cost/2`. | | Limits and spending | Per-call `:usage_limits`, the agent's `:spend_budget` integration and its run errors, including `{:usage_limit_exceeded, :budget_cents, {:retry_after_ms, wait}}`. The shared account's threshold options, attribution labels and Telemetry events are candidate. | | Permissions and steering | Argument predicates under `:rules`, `Permissions.decide/3` and `match_rule/3`, and `permission_rule` on approvals and events. `Server.steer_run/3` and `:on_steering`. | | Catalogue and reconciliation | Catalogue entries for candidate workflows and handoff policy bindings. `:catalog` for Judge, model reconciliation and effect retries. Read and model-preflight variants of `retry_effect/4`. `Jobs.Durable.definition/1` and `delivery_queue/2`. | | Continuation reads | The `:timeline` option on `Continuation.get/3`. | | Chat and recovery | Child and Job `:activities`, the scheduled follow-up row, and the input and timer variants of a deferred call and its Chat summary. `:call_ref` and `:wake_at` on deferred calls and summaries. Frame3 `:delegation_path` on inbox items, Chat deferrals and events, and in the authorization target. Recovery's `:follow_ups` startup option and sweep field, and the `:wake_timer` and `:deliver_follow_up` authorizer actions. `:cancel_follow_ups` in `Server.abort/2`. | | Erasure, Store, memory and diagnostics | Erasure's `:eval` option and `:follow_ups` receipt field. Inventory entries for fork families, scheduled follow-ups, input and timer deferrals. `Store.agent_key_in_namespace?/2`, `Store.retention_subject/3`, `Memory.erase_scope/2` and `Store.Postgres.check_recovery_schema/1`. Doctor's catalogue, model lifecycle and recovery checks. | | MCP and telemetry | `MCP.Client` with `:tasks`, `:pinned`, `:on_drift` or `:connect_on_start`, HTTP `:authorization_required`, `MCP.Server.Plug` with `:protected_resource`, and the `:mrtr_approval` server option. MCP form supply and `:mcp_input_required` are candidate variants of `Continuation.supply_result/4`. The `:observability` options on `ExAgent` and `Server`, native OTel `:metrics` and the provisional `:service_tier` attribute. The reasoning-prefix reset and embeddings events, catalogue diagnostic tags and GenAI attempt metadata are candidate. | #### Persistent execution by frame The table covers C7 admission. Each supported cell still depends on the applicable model profile, Store, host policy and journal evidence. | Capability | Agent and Server (Frame 3) | Agent delegate (Frame 3) | Composition (Frame 10) | Flow (Frame 11) | |---|---|---|---|---| | Static model-directed handoff | Yes | No | No | No | | Deferred tool result | Yes | Yes | No | No | | Pure input guardrail | Yes | No | No | No | | Pure stream guardrail | Yes | No | No | No | | Pure final output guardrail | Yes | No | No | No | | Pure tool-input and tool-output guardrails | Yes | No | Yes | Yes | | Tool guardrails alongside durable delegation | No | No | Yes | Yes | | Tool guardrails with custom tool rehydration | No | No | No | No | | Inline classifier guardrail | No | No | No | No | | Classifier as a journaled tool | Yes | Yes | Yes | Yes | | Tool program (code mode) | No | No | No | No | | Shared spend budget on an agent definition | Yes | Yes | Yes | Yes | | Provider context-overflow recovery | No | No | No | No | | Plan with its journal-backed projection | Yes | Yes | Yes | Yes | | Other rewrites of model request history | Yes | Yes | No | No | | Changes to bound tools or model settings between requests | Yes | Yes | No | No | | Prompted JSON map output | Yes | Yes | No | No | | Native JSON map or map output with free text | Yes | Yes | No | No | | Live steering | No | No | No | No | | Capability-supplied model answer before dispatch | No | No | No | No | | Capability-supplied answer after model failure | No | No | No | No | | Operator-supplied tool outcome via reconcile/5 | Yes | Yes | No | No | | Declared tool lookup via reconcile_tool/4 | Yes | Yes | Yes | Yes | | Retry of a pending read tool | Yes | Yes | Yes | Yes | | Manual retry of a write with accepted duplicate risk | Yes | Yes | No | No | | Retry of a lost model request | Yes | Yes | No | Yes | The host supplies the bound handoff catalog and authorizes administrative commands. A declared write lookup uses reconciliation. Retry requires an eligible uncertain effect and a new claim before dispatch. A structural workflow's read retry requires a pending dispatch in an active leaf batch. Workflow leaves inherit a declared spend budget through the execution scope. The [durability guide](durability-and-approvals.md) explains these conditions. #### Citation profiles | Profile | Offline citation evidence | Qualification | |---|---|---| | `:openai_responses_v1` | Buffered and streamed `url_citation` and `file_citation` retain the URL or attachment ID when the response has no identified commentary. Stock annotation flattening leaves answer ranges unset. | Offline, pending live qualification | | `:gemini_v1` | Buffered and streamed grounding web sources. Stock's retained grounding segment can supply a checked range in the leading part. | Offline, pending live qualification | | `:anthropic_messages_v1` | The normalized-source fixture retains document index, page, character or block coordinates, and excerpt. The native Messages fixtures demonstrate stock 1.31's loss of document citations in both modes. | Offline, pending live qualification and upstream citation retention | These fixtures cover response shapes and the local codec. Read the typed citations in [Read citations from a response](models-and-limits.md#read-citations-from-a-response). The source checkout has opt-in cases for all three profiles in the `--suite citations` runner. Live citation evidence is pending. #### Accounting and effects Host request/tool counters count admissions. Token values have declared normalized or reported quality; cost is an estimate in cents. Missing usage or price is unknown rather than zero. A limit checked after a response is not an invoice ceiling for work already in flight. Parent totals include their children. If a child owner dies during a request, the ledger keeps the observations received so far and reports partial coverage for that request. A timeout, cancellation, lost storage acknowledgement or process death cannot prove an external effect did not happen. Checkpoint retry saves the same state; it does not rerun a model or tool. For an uncertain write, reconcile the actual result before granting another execution attempt. A declared read can receive a separate recovery attempt. #### Resource boundaries Run deadlines and request/tool limits control owned admission. Host response and history retention limits apply after stock decoding; there is no upstream hard RAM bound before materialization. Compaction reduces the next request context, not the canonical persisted history. Arbitrary application callbacks and external systems have their own resource and cancellation contracts. Flow permits at most 32 branches/concurrent workers, separate 64 KiB branch/merge JSON bounds and an 8 MiB journal. Fail-fast cannot undo a sibling's completed effect. Collect continues eligible siblings after a confirmed pre-dispatch refusal for usage, step deadline, provider quota or maximum steps. See [Coordination](coordination.md) for construction and failure policy. #### Observability transport Langfuse and Opik receive native spans through the application's OTLP exporter. Default empty input/output previews indicate disabled content capture; inspect attributes for IDs, status and accounting. Exporter callback success and an HTTP 2xx do not prove every span was retained by the destination. Direct native OTLP HTTP can retain exporter-owned profiles, atoms and active sockets after timeout/shutdown. For bounded transport ownership, use the [disposable VM](otlp-isolated-transport.md) or [Collector](otlp-collector-transport.md) recipe. A finite processor restart budget limits recreation but does not repair cleanup. Size the queue for sampled physical attempts, including Fallback retries. See [Observability](observability.md) for authentication, privacy and lifecycle. #### Dependency diagnostics Some stock TOML, WebSockex and gproc dependencies emit compiler diagnostics. Functional operation and a warning-free dependency graph are different properties. ExAgent uses official dependency releases; applications should review their chosen graph and avoid treating suppression as a repair. --- ### Known limits These boundaries matter when deciding how to deploy ExAgent. Use [Supported features](status.md) for the capability map and the [C7 frame matrix](status.md#persistent-execution-by-frame) for durable admission. Each guide gives the configuration, results and failure handling. | Boundary | What to account for | |---|---| | Response citations | Stock ReqLLM 1.31 drops Anthropic Messages document citations. Responses retains references without answer ranges because stock flattens their provenance. Gemini grounding normalizes web sources and can merge text parts. The adapter retains a Gemini answer range only with matching text evidence. Provider citation behavior awaits live qualification. [Citation profiles](status.md#citation-profiles) | | Job notices | A notice identifies a terminal job. A later query can find that the result has expired or the volatile store has restarted. Historical tagged user text has no recoverable provenance marker. | | Durable background jobs | Workers use buffered Frame3 outside host transactions on a fixed PostgreSQL Repo and Oban prefix. Quota snoozes require a refusal certified before the first intent and replayable preparation. A lost first start, expired claim or ambiguous Server ACK requires host inspection. A lost attempt can spend its active-time reservation. Pruning retains one scoped ID per job for permanent exclusion even after clock rollback. The host owns version retention, authorization and cleanup. [Recovery](continuation-jobs.md#recover-a-job-after-node-loss) | | Image tool results | Inline PNG, JPEG and WebP only. ExAgent checks the file signature. A valid header alone cannot establish that the complete image is decodable. The 1 MiB typed-content ceiling includes base64 and metadata. A tighter run reservation can omit the complete payload. Soft truncation drops media without a ResultStore reference. Volatile background jobs handle JSON results. [Transport matrix](models-and-limits.md#image-results-from-tools) | | Chat history | The page cap measures external-term bytes. An oversized page item occupies one omitted position. History and replay detach binary slices. Guarded Server checkpoints retain up to `max_history_bytes` of accepted UTF-8 text. Eviction, history replacement or the C7 checkpoint budget can remove display rows. Older protected snapshots and snapshots with unknown policy hide assistant rows without acceptance evidence. Canonical history and raw events can contain candidates. Hosts can persist successful outputs for a permanent transcript. | | Chat streams | Answer and narration each have a 1 MiB provisional draft limit. SSE cursors identify a bounded replay buffer on one owner. AI SDK replay needs the retained events from the start of the root turn. If that prefix expires or the owner changes, reconnect through a fresh history window. The host supplies its transport and approval controls. | | Demand event delivery | Each reader has one outstanding notice until it acknowledges an applied cursor. Event replay lasts while the owner and its buffer retain those events. Transient tool data uses direct PubSub. An active unguarded root draft has a separate 1 MiB limit. [Demand reads](runtime-and-events.md#read-conversation-events-on-demand) | | Chat admission | A generated chat keeps the admission key in the URL until confirmed. If the receipt is unavailable or expired, reconcile with the host before submitting again. [Process receipts](runtime-and-events.md#start-a-conversation) | | Agent admission refusal | A claim with no model intent can already have run host callbacks. Reconcile before recovering the lease and resuming. [Agent continuations](durability-and-approvals.md) | | Continuation lease | A callback already in progress can outlive its writer. A renewal can commit even when its acknowledgement is lost. Read the stored horizon and recover after it elapses. [Effect recovery](durability-and-approvals.md#reconcile-an-effect) | | Tool effect recovery | The host authorizes each retry or lookup. A write may have run even if its result is unavailable. A stable key allows deduplication when the external service supports it. [Tool effects](durability-and-approvals.md#recover-a-declared-tool-effect) | | Local provider quota | A suspended limiter applies expirations and terminal reports when it runs again. A run deadline bounds the caller's wait. Restart clears the local rolling window and cooldowns. [Provider quotas](models-and-limits.md#share-a-provider-quota-across-runs) | | Live steering | Eight outstanding text corrections per live run, at most 16 KiB each. Waiters need a process independent of the run and stream consumer. Pending corrections expire at termination. C7 and its workflow leaves exclude live steering. | | Installation diagnostics | A fresh Mix VM sees configuration and the local catalogue. Runtime owners must be inspected in the running host. The endpoint's tool argument envelope and credential validity require separate qualification. | | Continuation run pages | Pages read scoped revision headers. Doctor's `--check-store` reads schema only. The read-only `--check-run-headers` scans journals and identifies the first missing header by namespace and logical ID. [Run header migration](migration.md#postgresql-continuation-run-headers) | | Provider capabilities | A catalogue model ID does not certify Chat tools, streaming or native JSON output. Declare the actual compatible profile and verify your endpoint. | | Anthropic Messages speed | Stock ReqLLM 1.31.0 lacks a request field for `speed`. ExAgent rejects it as an unknown option. | | Bedrock Converse | Offline fixtures show stock ReqLLM 1.31.0 collapses duplicate envelope keys and distinct calls with the same name and input. Both Converse formats discard the `server_tool_use` marker. Tools and their durable continuations are unavailable. The HTTP 200 stop reasons `model_context_window_exceeded` and `max_tokens` both arrive as `:length`. Live qualification is pending. [Profile](models-and-limits.md#amazon-bedrock-converse) | | Tool arguments | The mandatory `arguments` envelope gates the entire batch. Complete objects with the wrong shape can use the tool or output retry budget before any tool runs. Unparseable or truncated JSON, non-object values, observable duplicate keys and stock argument errors reject the model request immediately. Durable Composition and Flow leaves (Frame 10/11) reject any malformed envelope. Replay of `exagent.raw_arguments/1` to hosted strict Responses, Anthropic Messages and Gemini was verified in loopback and awaits live G3 qualification. The only live verification used `vllm:inkling-2-mini` on `llama.cpp`. [Argument envelope](models-and-limits.md#tool-argument-envelope) | | Permission comparators | Command prefixes admit literal argv. The callable validates allowed options. URL comparisons cover the origin and path. The callable validates queries, DNS and redirects. File path comparisons are lexical and case-sensitive. The callable owns containment across symlinks and filesystem aliases. [Argument rules](tools-and-output.md#match-permissions-against-tool-arguments) | | Retries and fallback | A retried request counts as one admitted request. Transport failures and timeouts are only retried on request, because the provider may have billed them. A portable history drops another model's reasoning and provider metadata. | | Chat Completions thinking | `:chat_tools_v1` preserves decoded plain thinking in responses and omits it from later requests. Provider `reasoning_details` and opaque or signed thinking reject. If `qualify` reaches the 32-token cap without evidence of invalid tool arguments, `truncated_envelope` fails with `:length_without_tool_evidence`. [Chat profiles](models-and-limits.md#profiles) | | Gemini | Gemini signs only the first of parallel function calls; stock sends a documented placeholder signature on the others and on portable foreign calls, and does not replay call ids. Stock removes `additionalProperties` from declared schemas, so extra argument keys are caught only by the local envelope check. Explicit context caching (`cachedContents`) is not exposed. A streamed response keeps no thought-part boundaries: consecutive thought fragments become one thought, closed by a signed fragment, and stock drops an empty streamed thought together with its signature. Gemini delivers `args` already parsed, so a duplicate envelope key cannot be detected; the protobuf `Struct` the server serializes cannot carry one. Whether Gemini 2.5 always signs the first call of a thinking turn is unverified (the live qualification used Gemini 3.5 Flash Lite). Implicit caching is best-effort: a live three-turn run over a 1.5k-word prefix reported no cache reads. | | Native output | OpenAI receives a non-strict schema. Anthropic receives a reduced, closed-object projection. Stock ReqLLM tool and native profiles require reference-free schemas. JSV validates the original schema locally. Stock responses may omit a refusal that accompanies valid JSON. | | JSON Schema map output | The root declares object type, and each encoded schema fits 65,536 bytes. Preview validation skips `required` and retains other constraints. Unions and output functions use tool mode. [Structured output](tools-and-output.md#return-a-json-object-without-ecto) | | Durable map outputs | Frame 3 supports all three modes. Frame 10/11 leaves require an output tool and exclude map unions with free text. Their journal certifies the tool resolution. | | Usage and cost | Tokens retain normalized/reported quality and cost is estimated. Unknown is not zero. A retrospective threshold cannot bound an invoice for work already in flight. | | Shared provider quota | The PostgreSQL adapter requires the same scope, keys and limits on all participants. Admission makes one database decision per attempt. An orphan retains concurrency until lease expiry and a conservative rolling charge. Repairing missing quota columns can extend waits when original values are lost. Quota covers participating calls and token estimates can differ from provider billing. The host owns physical cleanup. [Shared quota](models-and-limits.md#share-a-provider-quota-across-replicas) | | Memory | Host retention limits act after stock decoding. Upstream queues/materialization and caller-retained history have their own allocations. | | Prompt attachments | Base64 data and metadata count toward history. The host checks file type and decoded size before building the prompt. [Attachment boundaries](models-and-limits.md#send-images-and-documents) | | Provider file references | The host manages upload, permission, size, expiry and cleanup for every credential scope that uses the file. ExAgent bounds the retained metadata. Anthropic G3 exercised hosted PDF, plain text and PNG. Gemini PDF references have loopback evidence. [Gemini](models-and-limits.md#attach-a-provider-hosted-pdf-to-a-gemini-turn) · [Anthropic](models-and-limits.md#qualify-media-providers) | | Media operations | Stock calls are buffered. Byte and item limits bound retained output after decoding. Tool artifacts expire under the configured store's TTL. Unit coverage reflects observed quantities. Provider billing can use other meters. TTS-1 can return open-ended WAV sizes that strict file decoders require the host to finalize. Vertex Mistral OCR has loopback evidence. [Media qualification](models-and-limits.md#qualify-media-providers) | | Embeddings and rerank | Stock calls are buffered. Each call is one separately admitted batch of at most 1,000 inputs. Retention bounds apply after decoding. Usage and pricing depend on the public stock result. Tool artifacts use the configured store's scope, limits and TTL. [Embeddings and rerank](models-and-limits.md#embed-text-and-rerank-documents) | | Decision classifiers | Live guards require a run scope. C7 admits classifier calls through normal tools. A Flow selector consumes a label prepared by its host. ExAgent cassettes cover chat requests. OpenAI and Gemini decisions have loopback evidence. [Decision classifiers](models-and-limits.md#classify-with-a-decision-model) | | Automatic approval review | The host runs inference and commits the decision separately. Unconfirmed inference leaves the approval pending for explicit resolution. [Automatic review](durability-and-approvals.md#automate-a-persisted-approval) | | Closing request near a usage limit | The run must still have an admissible request. Durable Composition and Flow reject the closing projection. [Closing request](models-and-limits.md#close-before-a-run-limit) | | Audio attachments | Gemini uses one inline file part per clip and checks the declared MIME and 1 MiB decoded file limit. The host verifies format and duration, and applies retention when assembling history. Retained clips can be resent after restoring the conversation. The real Gemini API qualification used one WAV case. [Audio input](models-and-limits.md#attach-audio-to-a-gemini-turn) | | Long-term notes | A memory tool return can enter conversation history and continuation records. Explicit preloads supply system instructions and can enter durable model-request evidence. Scope these stores to the same audience as the notes. [Long-term memory](memory.md) | | Long runs | Settled receipts grow with admissions, including partial receipts after a child owner dies. Their usage slices own their backing bytes. Ordinary totals reuse per-ancestor aggregates. Order-sensitive prices, explicit exports and public chronological message lists can require full traversals. [Measured resource usage](observability.md#offline-load-measurements) | | Plan and workspace | Composition and Flow certify the built-in checklist reminder. Active ClearToolResults edits and arbitrary message projections are rejected. A tool-input guardrail or a `before_tool_call/3` hook restricts checklist review to approval or denial. Memory and ResultStore load their record before applying the file limit. The optional POSIX directory backend materializes one directory's names before checking its scan budget. It requires a host-controlled tree and cooperating writers. A path swap by an uncooperative process between `lstat` and access is a TOCTOU risk. An interrupted writer can leave a stale root lock or temporary file. Replacement quotas use the resolved file size. On case-insensitive filesystems (verified on a Linux casefold tmpfs) differently cased names alias one file. [Workspace limits](memory.md#mounted-text-files) | | Result references | The full callable return must fit its existing reservation. ETS releases content on eviction, expiry or restart. A durable preview can outlive the bytes. Child terminal outputs and externally supplied deferrals retain their own persistence guarantees. | | Context editing | Signed prefixes, pinned results and the active turn can exceed the model window. Opt-in overflow recovery admits one smaller request per live run, before any stream content fragment. Durable frames reject the policy. [Recovery contract](models-and-limits.md#recovering-from-a-provider-context-overflow) | | Prefix-bound reasoning | The fingerprint covers the request ExAgent hands to stock ReqLLM. Use the same provider account and stable attachment content for replay. Legacy signed blocks without a fingerprint require a reset. GPT-6.2 prefix removal has loopback evidence. [Replay contract](models-and-limits.md#preserve-prefix-bound-reasoning) | | PostgreSQL result retention | Each fetch loads one full result. FIFO quotas cover stored content bytes and rows per host scope. The number of scopes, PostgreSQL overhead, backups and access to private content are host responsibilities. Reads enforce TTL immediately. Physical reclamation of abandoned scopes needs a scheduled sweep and normal database vacuum. Admission requires READ COMMITTED. | | PostgreSQL checkpoint storage | Segmented writes reuse immutable bytes within a document. Reads and C7 validation still assemble the full JSON. PostgreSQL retains obsolete rows and TOAST versions for MVCC. Host vacuum settings govern space reuse. [Load measurements](observability.md#postgresql-load-measurements) | | PostgreSQL upgrades | Schema changes acquire PostgreSQL DDL locks. Rolling back application binaries requires a reader for every format already present. Finalizing a write level can retire that rollback path. [Upgrade guide](migration.md#upgrade-postgresql-and-roll-out-a-store-format-level) | | Streaming | Deltas are provisional. Every enumeration starts work. A suspended continuation remains caller-owned until resumed or halted. Child events are progress. The terminal closes the root. | | AG-UI | One root attempt per encoder. Replay requires the start of the attempt in the same emitter and a fresh client projection. The encoder's state document holds the current step. The staged text is provisional until the confirmed terminal result. [Phoenix integration](framework-integrations.md#serve-ag-ui-from-phoenix) | | Model finish evidence | ReqLLM's public decoded response or chunk metadata supplies the finish. Responses and Gemini also expose provider status. A buffered route that loses the raw finish in stock carries only its normalized reason. [Model terminals](models-and-limits.md#model-terminals) | | ReqLLM crash reports | ExAgent orders forced stream shutdown to avoid stock ReqLLM 1.31 reports caused by killing the producer. Independent backend crashes, explicit dependency logging and host diagnostics can still include request data. | | Scripted streams | Test scripts exercise normalized model events in process. A scripted timeout supplies a provider error immediately. Transport timing and wire decoding require adapter tests. [Testing guide](testing.md#script-a-streaming-failure) | | Stream cassettes | Each capture is capped at 4,096 provisional events and 1 MiB of event JSON. Independent roots with identical requests need distinct labels. Re-record legacy duplicate fingerprints. Use scripted streams for failure and timing tests. [Testing guide](testing.md#match-concurrent-cassette-requests) | | Structured previews | Up to 32 changes per request, using at most 64 KiB of JSON and 4,096 fragments. A smaller payload limit also caps previews. Adapters delivering only a terminal have no intermediate fields. | | Structured output projections | Terminal events and visible history check JSON bytes before publication. Custom Jason encoders and Ecto type dump callbacks run as trusted host code and can allocate work data before returning. | | Terminal observers | Abandoning a stream before its terminal skips the observer. Process loss can interrupt host observation or persistence. Durable recovery never replays an observer for a historical completed attempt. | | C7 attempt links | Linking needs a recording span during the pause and room for its identifiers in the checkpoint. The target of a link can be missing from the trace backend after export drops or retention expiry. [Traced attempts](observability.md#link-paused-and-resumed-attempts) | | Guardrails | Output checks govern final delivery. A stream guard reviews disjoint windows of provisional answer and narration. Whole-value rules belong at final delivery. Stream timing includes callback speed and backpressure. Frame3 tool-output guards with a raw receipt and result hooks withhold a result whose checked value could not be recovered. Composition and Flow certify both tool stages. [C7 guardrails](durability-and-approvals.md#bind-guardrails-to-a-continuation) | | Cancellation | Framework-owned tasks can close; arbitrary callbacks and external effects cannot be rolled back. | | Checkpoints | Confirmed data is durable only according to the Store. ETS is ephemeral, and failed saves block mutations until storage retry succeeds. | | Erasure by subject | Erasure covers one scoped Server ID and the stores and keys supplied by the host. C7 keeps uncertain evidence, including closed records with unconfirmed model effects. The host supplies remote owner PIDs, stops other writers and handles copies outside ExAgent, including backups. The tombstone lasts as long as the Store retains it. [Erasure guide](migration.md#erase-a-conversation-by-subject) | | Snapshot header pages | Pages cover standalone snapshots and bound row count. ID lengths determine header bytes. Concurrent mutations are visible between pages. Unmanaged ETS tables support only the full inventory. [Store guide](durability-and-approvals.md#browse-conversation-headers) | | Custom Store contract tests | Use backend tests for adapter-specific expiry and failure recovery. The bundled adapters have separate suites for atomic C7. [Store guide](durability-and-approvals.md#test-a-custom-store) | | Conversation evals | Scenarios script text prompts for an agent and decisions on its root tools. Model-driven users and workflow branch reviews require host code. The attempt timeout covers all turns and can interrupt an effect. Replay executes tools against the host's test dependencies. | | Eval baseline comparison | Hosts version custom scoring, opaque case setup and changes to reviewer services behind stable model names. Pairing needs a grade or target error on each side. [Testing guide](testing.md#compare-runs-when-the-suite-changes) | | Terminal regression cases | C7 summaries and content-free Online samples require a separately authorized prompt. The host reconstructs model requests in a test harness to record a cassette. Script model transport failures with TestModel. [Testing guide](testing.md#turn-a-production-failure-into-a-ci-case) | | Terminal regression cases | Automatic C7 capture needs a settled root turn with retained model replies and replayable tool returns. Script deferral resolutions, missing bodies and model transport failures with TestModel. C7 summaries and content-free Online samples need a separately authorized prompt. [Testing guide](testing.md#turn-a-production-failure-into-a-ci-case) | | Online evaluation | A full queue sheds samples. Local deduplication covers active work and the configured number of recent results. Restart can lose pending offers. The first durable job fixes the evaluation's deadline, and the receipt or tombstone continues to reserve its identity. Process loss after the export claim can interrupt dispatch. Collector receipt belongs to the host's exporter. [Online evaluation](testing.md#sample-confirmed-terminals) | | Strict tool fixtures | Substitution covers framework-dispatched tool callbacks. Host hooks, loaders and evaluators can perform IO. Supply test bindings and a scoped Store for durable runs and pass the strict fixture again on resume. | | External effects | Timeouts, owner loss or lost acknowledgement can leave outcomes uncertain. Recovery requires host reconciliation; approval is not universal exactly-once execution. A cancelled external deferral stays uncertain until its result is supplied. | | Supervised recovery and drain | The host resumes ready conversations. An opted-in Oban worker resumes eligible jobs on redelivery. A discarded delivery, held quota or missing C7 record requires operator recovery. A drain covers local conversation owners and waits for the current turn's boundary. [Jobs runbook](continuation-jobs.md#recover-a-job-after-node-loss) · [Drain](runtime-and-events.md#drain-a-conversation-manager) | | Isolated code | The adapter owns isolation. Docker shares the host kernel. Destruction, eviction, expiry or restart can remove a local receipt and allow the ID to be reserved again. Use fresh IDs. A missing receipt leaves C7 uncertainty open. [Sandbox threat model](tools-and-output.md#isolation-and-threat-model) | | Tool programs | Code mode runs a bounded sequence with JSON bindings. The program uses ordinary live tool admission. A stop can leave earlier effects completed. C7 admission requires a definition without code mode. [Program guide](tools-and-output.md#chain-tools-in-a-program) | | Tool task heap | The BEAM checks `max_heap_bytes` at garbage collection and includes shared binaries. The task can temporarily exceed the threshold. ETS, native allocations and processes launched by a tool have separate resource lifecycles. [Execution controls](tools-and-output.md#control-how-tool-calls-run) | | Guarded conversations | Failed live turns keep their evidence in the host's partial result. A snapshot from an earlier 3.0 development build may already contain a rejected turn. Restore known accepted history before continuing such a conversation. | | Concurrent snapshot writers | ETS and PostgreSQL detect stale saves after execution. A custom Store without snapshot CAS can overwrite a newer conversation. Keep a single owner for those Stores. | | Cold conversation activation | The manager bounds factory preparation and waiting callers. Store restore can hold a cold slot until the start settles or its supervising partition exits. A new key at capacity receives `{:error, {:start_failed, :activation_capacity}}`. [Runtime guide](runtime-and-events.md#start-a-conversation) | | Turn admission | A receipt confirms a reserved run or a settled queued cancellation. Owner loss or a stop with unconfirmed cancellations can leave a queued turn admitted and require host reconciliation. Snapshot-only owners forget keyed receipts on restart. A missing process-local receipt returns `:receipt_not_durable`. Expired keys are refused. A full window shared with Jobs notices refuses fresh keys. [Retry windows](runtime-and-events.md#recover-a-turn-admission-after-losing-the-reply) | | Receipts | A record keeps 1024 receipts per run and, across runs, only the last receipt of the 64 most recent earlier runs: a lost reply from an earlier run returns `:conflict`, and IDs older than that window are not checked for reuse. | | Model-directed handoff | Root C7 accepts static catalogs up to 16 destination levels. Composition, Flow, delegated continuations, persisted Session chat and custom tool rehydration remain unsupported. Unconfirmed batch controls can block a transfer. The bounded view carries text, authorized images and authorized current audio. Clips can be omitted by the view budget, and C7 retains admitted bytes. Document attachments and native provider state stay in host history. [Handoff guide](coordination.md#let-a-model-hand-off-the-turn) | | Coordination | Trusted definitions and versioned bindings constrain branches. Flow has bounded flat branch/concurrency and journal/result limits. Fail-fast cannot undo sibling effects. A durable step cannot use a capability that rewrites its requests (instructions, compaction, tool search). Certified admission refusals and pure output-tool vetoes can close branches. A lost model response requires explicit reconciliation or workflow closure. Unconfirmed tools and host callbacks prevent both closure and pruning. [Workflow recovery](coordination.md#recover-a-workflow-after-an-owner-crash) | | Flow manifests | A manifest holds up to 32 items and 64 KiB of JSON. The journal retains every item input. One template and one set of step options apply to all items. [Map Flow](coordination.md#run-a-flow-over-a-manifest) | | Durable tool batches | The checkpoint cap covers the journal and capacity to close every admitted call. The per-result slot uses the step's payload and history limits and is capped at 64 KiB. [Workflow tool batches](coordination.md#budget-durable-tool-batches) | | Tenant budgets | The shared account gates model attempts, Media, Embeddings and tools with a declared quote. Actual cost can exceed the quote. Pending holds count across windows and require reconciliation. Use a separate budget pool to bound contention with C7 checkpoints. The host owns accounting for other IO. Per-turn usage limits are retrospective. [Budget setup](models-and-limits.md#reserve-a-shared-spend-budget) | | MCP | The HTTP client uses an application-owned HTTP/1 Finch pool or a direct HTTP/1.1 connection per exchange with a header provider. Progress and elicitation use ephemeral POST streams subject to the client's SSE limits. The server publishes static text resources and argument-free prompts. The stock client leaves elicitation disabled. An unacknowledged tool can have executed. `call_tool/3` reports `:result_unconfirmed` or `{:result_unconfirmed, cause}`. Reconcile using independent evidence. | | Stateless MCP | The `2026-07-28` Plug serves synchronous JSON calls. Its execution concurrency limit applies per replica. The host handles token validation. Opt-in `:mrtr_approval` shares single-use receipts across replicas, with 256 live receipts per principal and 1,024 per endpoint. Server-side input is limited to approval forms. Task publication and subscriptions are outside the server profile. [Stateless HTTP](mcp.md#serve-stateless-http-across-replicas) · [Approval receipts](mcp.md#approve-a-stateless-mcp-tool) | | MCP Finch telemetry | Native `[:finch, step, phase]` events for request, queue, send and recv carry the request with its static headers. The recv stop event includes response headers and trailers. The request stop event carries an opaque accumulator reference. Use Mint via `:headers_provider` for credentials, including tokens sent in custom headers. [Transport and credentials](mcp.md#rotate-http-credentials) | | MCP OAuth | The host owns OAuth discovery, token acquisition and verification. Retry a confirmed authorization rejection at most once after updating the credential source. A challenge during a control POST or task poll leaves the original tool outcome uncertain. [Authorization challenges](mcp.md#handle-an-http-authorization-challenge) | | MCP Tasks | The opt-in HTTP client polls acknowledged tasks by server ID. Frame3 stores the ID in a deferral. Persisted workflow leaves use synchronous calls. A lost creation receipt or expired task leaves the original result uncertain and calls for independent evidence. Task input exchange and subscriptions are outside this profile. [Reconcile a missing task](mcp.md#reconcile-a-task-the-peer-no-longer-knows) | | MCP catalogue policy | Each replica evaluates the host's grants on each catalogue request. Replica agreement depends on the host's source of grants. Revocation applies to subsequent admissions. [Catalogue policy](mcp.md#authorize-the-catalogue-per-principal) | | MCP catalogue freshness | The client consumes change notifications over stdio and active HTTP response streams. Outside those streams, declarations can remain cached until the earliest page TTL, a credential change or a confirmed protocol rejection. [Catalogue caching](mcp.md#cache-tool-catalogues) | | Trace ingestion | HTTP success and exporter callbacks do not prove durable acceptance of every span. Sampling, saturation and partial rejection can lose data. | | Event export | Each key selected by `:metadata_keys` exports its entire value. Supply scalar labels or sanitize nested values in the host before export. | | LiveDashboard refresh | Runtime and Store reads share a one-second deadline. The Usage tab samples at most 500 live conversations. A refresh can show unknown values or a lower bound when some owners do not answer in time. [Runtime guide](runtime-and-events.md#inspect-running-processes) | | Durable job waits | A wait observes committed data from a separate checkout. A lock or pool queue can consume the budget before the first read, yielding `{:error, :timeout}`. | | Direct OTLP HTTP | Native exporter timeout/shutdown can retain profiles, atoms or sockets. Use an application-owned isolated VM/Collector when bounded cleanup is required. | | GenAI metrics | Native and ReqLLM bridge histograms require a host-owned experimental 0.6 metric SDK and reader. The histograms leave out unknown token totals. | | GenAI trace content | The Erlang span API accepts scalars and homogeneous arrays. Opt-in content uses bounded redacted JSON under `exagent.content.*`. | | Dependency warnings | Stock TOML/WebSockex/gproc can emit diagnostics. Review your graph; a functional integration does not imply warning-free dependencies. | For the corresponding application handling, see [Models](models-and-limits.md), [Runtime](runtime-and-events.md), [Durability](durability-and-approvals.md), [Coordination](coordination.md), [MCP](mcp.md) and [Observability](observability.md).