Runtime and operations contracts for coding agents

View Source

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 elementData
{: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

CallOptions, 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/3Same 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/2Reads {:ok, value} or {:error, :unavailable} and applicable Store/config errors. Default wait 5000 ms.
Server.reset/2, set_model/3, checkpoint/2timeout: 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 · Framework integration

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 · Persisted scheduling

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 · Migration and limits · Continuation jobs

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_<id> (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 · Workflow recipes

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 · External boundary support

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.

SuffixBoundary, measurements and selected metadata
:run, :start / :stop / :exceptionStart 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 / :exceptionOne 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 / :stopPhysical 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, :retryFallback scheduled attempt, delay_ms and model, status, fallback.
:model, :reasoning_prefix, :resetCandidate 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, :stopDuration, 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 / :stopAdmitted 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, :verdictCount 1, respectively name, stage, run_id, root_run_id, attempt_id / mode / kind, verdict.
:rate_limiter, :wait / :reject / :cooldown / :settlement_retryCount 1 and known wait_ms (settlement retry delay_ms, zero for single late report). Configured quota key.
:usage_limits, :budget, :settlementCount 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, :thresholdCount 1, charged/limit cents, window_start UTC ms, integer percent threshold, ETS account name/PG scope digest. Best effort, one claim per window.
:conversations, :activationCount 1, status :waiting / :queue_full / :capacity / :wait_timeout / :factory_timeout / :start_unconfirmed / :reconciled.
:job, :start / :stopVolatile, 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, :stopMemory 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_expiredCount 1, respectively operation/status, Repo/table/content-free error type, or generated resume job ID after checkpoint wait cancellation.
:mcp, :catalogue, :drift / :mcp, :validation_errorAdded/removed/changed counts and revision/drift rule. Validation count and rewritten, no values.
:eval, :online, :result / :delivery / :discardProjection 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 / :processorFixed 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 · Collector bridge
  • 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 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/<endpoint>.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 · Continuation binding recipe · Support and limits