Runtime and operations contracts for coding agents
View SourceExAgent 3.0.0. Names are relative to ExAgent unless qualified. C7 denotes persisted approval and continuation. Candidate marks APIs that can change across releases. Namespaces, subjects, stores, dependency context and authorization come from the host.
Streaming, Server, conversations and events
Lazy streams
ExAgent.run_stream(agent, prompt, opts \\ []) returns an Enumerable. ExAgent.resume_stream(agent_or_catalog, ready_ref, opts) starts a fresh enumeration for a saved continuation. Construction checks options/definition, each enumeration starts work anew, and all deltas remain provisional. Consume one terminal {:result, %Result{}} (including status: :paused) or {:error, %RunError{}}. Accept deliverable output only on :succeeded. Unknown event types are additive.
| Stream element | Data |
|---|---|
{:run_started, data} | run_id, root_run_id, parent_run_id, attempt_id |
{:run_step_started, data} | step |
{:steering_applied, data}, {:run_handoff, data} | step, correction_id or step, from, to, call_ref |
{:text_delta, data}, {:commentary_delta, data}, {:thinking_delta, data} | step, text, distinct channels. Reviewed text/commentary adds stream_checked?: true. |
{:tool_call_delta, data} | step, index, tool, fragment, opt-in tool_call_deltas: true |
{:output_partial, data}, {:model_response, data} | step, output (provisional map/Ecto struct) or step, response (admitted normalized response) |
{:tool_call_started, data} | step, tool, call_ref, call, args_source where call is admitted %Message.Part.ToolCall{}, source :model/:reviewer |
{:tool_call_finished, data} | step, tool, call_ref, return, duration_ms, duration_measured, return is %Message.Part.ToolReturn{} |
{:tool_data, data} | step, call_ref, tool, part_id, name, data, transient |
{:guardrail_tripped, data} | step, name, stage |
{:context_compacted, data} | step, reason: :context_overflow, estimated_tokens_saved |
{:approval_requested, data} | continuation, pending with identifiers, optional permission rule and candidate deferral/delegation fields |
{:run_step_finished, data} | step, outcome, one of :continued/:retry/:succeeded/:paused/:failed |
{:child, %{run_id: id, parent_run_id: parent, root_run_id: root}, element} | Child progress once at any depth with child_events: :all. Root terminal closes stream. |
- Each started step closes once before terminal (abrupt kill can emit terminal alone). Calls waiting for approval finish on the executing attempt. Nested CodeMode calls add candidate
program_call_ref, one-basedprogram_stepandeffect.RunContext.emit(ctx, name, data, opts)usesid:to upsert one part,transient: trueto 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:usagereplaces 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.exsstarts Mix in a new session, translates SIGINT to SIGUSR2 forSystem.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/1starts a Server via a DynamicSupervisor.AgentSupervisor.stop_agent/1terminates it.Server.child_spec/1ID{: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 stableagent_id:. Registered local or{:via, Registry, {...}}names fence simultaneous local startups (second gets{:error, {:already_started, pid}}). Tests can supply child ID throughstart_supervised!/2.Server.start_link/1requiresagent:. Keysagent_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. Defaultsmax_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_foundcan create a fresh owner.missing: :errorrefuses. Invalid configuration raisesArgumentError, 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: 16distinct cold keys andmax_activation_waiters: 128per key incl. first, both 1–1,024. Errors{:start_failed, :activation_capacity}/{:start_failed, :activation_queue_full}. Same key shares activation.create: falsepermits restore only.factory_timeout: 5000ms 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: 5000covers lookup and replacement waits.ensure/3expiry returns:result_unconfirmedand releases waiter.call/4maps 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_000andhibernate_after: 15_000ms, 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_stoppedwith:idleand exits{:shutdown, :idle}. Viewers cap 1,024 PIDs, death detaches. Runtime exposes elapsed idle and attachment count. registry: :globalgives cluster lookup on connected nodes. Requires atomic durable Store and C7durability: :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 viaCheckpointError. 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}implementsConversations.Registry.Conversations.stop(name, key, reason: {:shutdown, :stopped}, timeout: 5000)interrupts owned work, sends unconfirmed active synchronous reply, emits per-turn cancellation then stopped.:okconfirms exit and keyed cancellation receipts. Otherwise it exits with unconfirmed event and{:error, :result_unconfirmed}. Unread discarded mailbox commands explicitly return unavailable. Ordinary postdispatch death is uncertain.Conversations.drain(name, timeout: 5000)fences local admissions including with shared registry, lets current turn reach normal persistence boundary, cancels queue, confirms exits. Continues after caller timeout. Repeat to await same drain. Restart manager to reopen.
Server admissions, control and reads
| Call | Options, return and decision |
|---|---|
Server.chat(server, prompt, opts \\ []) | Synchronous outcome {:ok, %Result{}} or error, timeout: :infinity, request_id: and message_history: plus run options. Current active turn yields :busy. Reply loss :result_unconfirmed, work can continue. |
Server.send_message(server, prompt, opts \\ []) | timeout: 5000, queue: true, chat run options plus idempotency_key:. Queue back. queue: false uses synchronous admission rules without waiting for outcome. Receipt {:ok, %{status: :admitted, run_id: run, request_id: req}}. Lost ack {:error, {:delivery_unconfirmed, request_id}}. |
Server.steer/3 | Same asynchronous controls minus :queue, priority/front separate turn. |
Server.steer_run(server, run_id, text) | Candidate, volatile runs only ({:unsupported, :continuation_steering} on C7). Corrects the active live root at the next step boundary. {:ok, %{step: step, correction_id: id}} after history apply. Terminal first gives :run_not_active, handle lookup loss unavailable. |
Server.resume(server, ready_ref, opts \\ []) | timeout: :infinity and applicable run options. Uses stored request ID/history and checks lifetime/run/revision. Rejects message_history, request_id and idempotency_key. C7 uses Server.decide/4 rather than synchronous approver. |
Server.abort(server, opts \\ []), abort_run(server, run_id, opts \\ []) | Current work vs exact run ID (incl. queue). timeout: 5000. Candidate abort/2 option cancel_follow_ups: false. :run_not_active if exact target no longer cancellable. Observed run/lifetime/revision conflict :continuation_abort_conflict. |
Server.receipt(server, key, opts \\ []), turns(server, opts \\ []) | timeout: 5000. Receipt gives original admission or :cancelled_before_start incl. revision. Turns gives root and queue order, up to max_pending + 1, run_id, request_id, admission_key, status incl. :cancellation_unconfirmed. |
Server.health/2, history/2, history_page/2, usage/2, pending/2, continuation/2 | Reads {:ok, value} or {:error, :unavailable} and applicable Store/config errors. Default wait 5000 ms. |
Server.reset/2, set_model/3, checkpoint/2 | timeout: 5000 (checkpoint infinity). Retry checkpoint saves exact outstanding transition. Confirmation may reveal previously hidden accepted rows and expire cursors. |
- Forwarded options
deps, model_settings, stream_text, tool_call_deltas, child_events, estimate_cost, deadline, max_concurrent_requests, max_concurrent_tools, permissions, approve, observability, trace_context, usage_limits. Candidate options include observability and per-turn limits. Startup/submission rejects invalid unknown/repeated keys.timeoutcontrols caller wait (0–4,294,967,295 ms or infinity for control/turn calls) anddeadlinecontrols 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_unconfirmedis 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,:runningowns one worker (sync chat/model/reset busy),:pausedinbox,:blockedclaim/uncertainty,:reset_requiredterminal unanswered tool batch. In last three, sync chat/model refuse:continuation_pendingand reset allowed only for reset-required.:checkpoint_pendingfences 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/1roundtrip 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_foundcan 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.persistenceand 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:uncertainfor 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_suppliedand 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. Repeatabort/2can 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. Directon_steering: fn handle -> ... end(candidate) andSteering.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/2acceptsbefore:,since:,limit: 40(1–1,024),max_bytes: 65_536(64–67,108,864),projection: :messages | :visible_text | :chat,include_draft: falseandtimeout: 5000. Chronologicalitems,startzero-based,total,revision,before/head. Cursor valid across append, expired by reset/replacement/projection rewrite/owner restart.:omittedpreserves one item position on overflow. An incremental start beyond prior count requires replacing the displayed window.:messagescanonical terms.:visible_textdisplay string, nil hidden or omission.:chatadds{:job_notice, %Message.Part.JobNotice{}}, latest owner failure and candidate activities. Page includes same-instantevent_cursor,checkpoint_pending?and active root ID with chat/draft.include_draft: trueincludesdraft/commentary,stream_checked?anddraft_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. Rejectmessage_history/queuein run options. Admit callback checks branch key/prompt after creation.Server.regeneration_target/2reads latest confirmedturn_refand originalprompt. 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_frommetadata. 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}onEvent.agent_topic/2orsession_topic/2(nil preserves legacy topic). Match scope, conversation, request and emitter before applying.Event.payload/2projects stream data. Terminals:run_finished/:run_pausedcarrynew_messagesand accepted result fields outside whole history/steps.:run_failed/:server_request_cancelledcarry error/partial. Selectedoutput_nameand optionalhandoff_target/citations. Output projectionoutput/output_textmay return%{serialization_error: true}and nil text. Failed history/usage conversion becomes nil. Tool finish containsstatus, content, content_withheld, usage, duration_ms. Declaredtoolor"unknown_tool"/nil preview. Opaquecall_refmatches one invocation, stable across resume, separate from provider IDs. Durable Frame 3 child start and candidate:child_run_stoppedare live observed only. Child drafts/steps stay private. Candidate:job_startedacks known background submission.:server_request_queuedcarriesposition: :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_changedand:shared_state_updated. Participant ID refers to changed/receiving participant, nil for lifecycle. Persisted state and following turn change can share revision.:session_doneleaves owner running.Event.strip_content/1,2nulls 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 withEvent.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.limit1–65,536,max_bytes64–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/3withnotice: refdefaults 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/3also idempotent, old notice may remain in mailbox. Default first/ack/detach timeout 5s with nondelivery vs unconfirmed distinction.Runtime.list/1filterskind:(:server,:session,:jobsor list, defaults all),namespace:,node: node(),limit: 500(1–10,000),timeout: 1_000. Version 1 rowskind, 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:redactedargs. Trustedcontent: {:redact, {m, f, args}}runs on owner node by field, callback failure:redaction_failed. Approval uses authoritativeServer.pending/2orContinuation.pending/2.exagent_dashboardprojects 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/1can 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/3latest/older/reload,notice/3reads and reduces the batch into{:ok, chat, rows_or_nil, events_or_replay}(leaving the notice pending until the caller callsServer.ack_events/4withchat.cursor),approvals/2reads controls,admission/5andcancellation/5combine 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, returnsid/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) requiresauthorize: fn conn -> {:ok, owner_pid} | {:error, :unauthorized | :forbidden | :not_found | :unavailable} end. Optionalrun_options: fn conn -> opts end, defaultsheartbeat_ms: 15_000,stream_timeout: 300_000,max_body_bytes: 1_048_576. GET SSE withLast-Event-ID, snapshot at initial/gap/control/transcript refresh, replay retained suffix andcursorevents. POST object string"prompt"+ encodedIdempotency-Key, GET with same key receipt, DELETErun_idasks 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 transientdata-exagent-commentarywith cursor ID, status asdata-exagent-status, stable tool refs including review stubs/withheld output. Accepted output replaces draft.resume_after: pause_cursorrequires entire retained prefix to rebuild and stops at next pause/terminal.regenerate/3maps 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, optionalthread_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.approvalrequested items/decided action,exagent.inputinterruptinput_required,exagent.timerinterrupttimer_waitwith UTCwakeAt. Delegated path/activity message ID inmetadata.exagent. Resume uses same Server run ID with fresh wire attempt and preceding decision events.Chat.AGUI.Input.decode/2handles answered client interrupts. Timers and effect reconciliation are host/Recovery actions. Candidate reasoning for both encoders opts into bounded provider summaries throughfn :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/2is one read.wait/3waits within1..4_294_962_295ms.cancel/3returns the confirmed job snapshot, with defaulttimeout: 5_000.list/2filters by:statusand:limit, neweststarted_atfirst. 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 andrequires_deferral: falsequalify.Jobs.agent_tool/1requires:jobs,:name,:descriptionand:agent.:run_optscan be a list or unary resolver.:timeoutand:notifyare optional. A paused child is a failed job with separately recoverable child state.Jobs.tools/2returnsjob_status,wait_job,cancel_job(job_idrequired for each,secondsrequired for wait). Durable query tools expose status and wait.max_wait_seconds: 60in1..4_294_962and an extra 5,000 ms on the wait tool timeout. Tool JSON carriesjob_id,name,status, optionalresult,errorandnotification. Lookup failures carrystatus: "unknown",codeandmessage. A notification slot is reserved with start. Callback return is ignored.Jobs.notify_server/2admits aJobNoticewithjob_id,status,tool_nameand candidatefollow_up, using the job ID asrequest_id.Jobs.notification_key/1for 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: falseselects new journal writes. Both configurations read supported inline and segmented journals.new(worker, namespace, oban: Oban)builds the scoped handle.store/1exposes its Store.new_id(ttl_ms \\ 86_400_000)embeds immutable expiry, range1..4_294_967_295ms.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 integers1..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/2enqueues 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 candidatedefinition(namespace) → catalog | {catalog, run_opts}. Candidatedelivery_queue(namespace, ref)selects an existing Oban queue.server(namespace, id)gives a stable destination address without activating the owner ornilto 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 withactor:,authorize:(arity 3),model: :cancel | :leave | :retry(:canceldefault). 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/2retires only a start without C7 proof.status/2 → {:ok, %Jobs.Job{}} | {:error, reason},wait/3polls 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_atis UTCDateTimewhen a ready safe wait or pending timer has a known horizon. Status can return:missing_exagent_jobs_table,:jobs_migration_required,:missing_exagent_snapshots_tableor: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_foundand the original ID stays expired for admission.
Scheduled follow-ups
- Candidate
Tool.FollowUp.tools(store, opts \\ [])exposesschedule_follow_up,list_follow_upsandcancel_follow_up.max_pending: 8(1..100),min_delay_ms: 1_000,max_delay_ms: 2_592_000_000(ceiling4_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/2andcancel_all/2expose scoped controls.Server.abort(cancel_follow_ups: true)also clears pending follow-ups. Recovery authorizes:deliver_follow_upwith namespace, subject ID, follow-up ID andretry_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 theon_readypath. 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 (defaultStore.ETSin app supervisor). Reads use ETS and writes serialize through the owner. Snapshots survive Server restart while the table owner lives.Store.Postgresaccepts 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/2andSession.checkpoint/2retry the exact save after failure without effect replay.CheckpointErrorrecords operation and underlying cause.checkpoint/2can return:busywhile 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}}withagent_id,revision,updated_at(UTCDateTime), physical-ID sort order, defaultlimit: 50(1–100) and opaque scope-boundafter: cursor, nil cursor at end. Invalid cursor returns:invalid_scan, missing header callback:unsupported_store_capability. C7 state is queried viaContinuation.list_runs/2. Custom Store snapshot callbacks receive a namespace-encoded key and validated serialized snapshot data.Store.agent_key_in_namespace?/2checks ownership. Optional paginated header callbacklist_agent_headers/4. UseStore.ContractCasefor the public snapshot contract.ExAgent.Migration.current_version/0 == 1. In an Ecto migration callup(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 (4run headers,5admissions,6recovery,7timers), 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/1validate 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.Maintenancerequiresrepo:.table: "exagent_snapshots",interval_ms: 5_000andmax_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(:ephemeralor:durablematching 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), candidateretain_failed_turn: false. Extra/malformed keys return:invalid_continuation_configuration. Store mismatch returns:unsupported_store_capability. Server takes binding without:storeand:id(supplies its Store and agent ID) and raisesArgumentErrorfor invalid/owned keys. References are%{version: 1, id: ..., record_id: ..., revision: ..., run_id: ...}with optionalattempt_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_unconfirmedcarryhint: :recover_continuation_lease.lease_untilis 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,:pendingfor approval/deferral,:readyafter confirmed decisions/results,:uncertainwhen an effect remains open, terminal:completed,:failed,:cancelled,:expiredand old:deniedrecords. Publicget/2/list_runs/2adds:executingfor claimed intent/callback and:approvedfor 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_responsebefore tools). Dump/load failures surface:model_state_not_persistable/:model_state_not_restorable. - Candidate
retain_failed_turn: truepreserves 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_unconfirmedrequires 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} | :erroraccepts the struct.resolve/2exact reference or identity.fingerprint/1canonical SHA binding overid:,agent:,policy:,model_ref:,model_codec:and optionalpermissions:,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_lockMFA 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)takesrecover/3options plus targetdefinition:. 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: trueadds internal:record(admin writes also:receipt). Raw diagnostic layout is private.list_runs/2acceptslimit: 50(1–100),status:(including:executingfor unresolved claimed intent),after:. Empty filtered page can have a cursor.{:store_migration_required, 4}for missing SQL 4 column/index,:run_header_missingfor 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 includingApprovalRequestandDeferredCall. Delegated entries keep the root reference anddelegation_pathentries%{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 includeid, namespace, record_id, revision, expires_at, operation_id, run_id, call_id, call_ref, tool_name, args, definition, delegation_path. Approval addsapproval_id, payload_hash, permission_rule, decisions. Deferral addsdeferral_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:andauthorize: fun/3required, authorizer returns{:ok, actor_id}for permission.tool:orcatalog:binds edit validation, plus optionaldiagnostics: true.decide(store, id, :cancel | :expire, opts)uses the record/revision operation binding. Approval changes state only. Denial supplies status:deniedand 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
:editwithoriginal_argsandargs. The original model call remains in history. Errors:tool_mismatch,{:invalid_args, errors},{:permission_rule_changed, %{permission_rule: rule_or_nil}}or:unsupported_decisionleave 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,:expiredand:invalid_transitionprotect current state. Server decision loss may return:result_unconfirmed, so retry the exact operation or inspectget/2andpending/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/4uses cutoff, actor and per-record revision checks. Retry changed records from a fresh scan.Candidate
Judge.Approval.review/3,commit/3,evidence/2andusage/1. Host authorizes:reviewbefore 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 includingid, record_id, revision, operation_id, run_id, call_id, tool_name, definition, policy, leaf, permission_rule, original_args, args, message, result(nil as inapplicable), pluspayloadon recovery and optional delegated path. Only bounded actor ID is persisted. Effectleaf.pathstarts 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, declarationrequires_deferral: trueand SQL 7 verified before effect. Deferral and approval each expose exact record/revision binding. Live candidateon_input: fun/1can answer MCP requests before answer dispatch (including repeated rounds). With a scoped continuation the MCP call pauses forsupply_result/4instead. supply_result(store, deferred_call, outcome, tool: bound_tool, actor: actor, authorize: auth)(optionaldiagnostics:) 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_executedwith"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)takesrecover/3options plus requiredtool:matching exact persisted leaf (resolve it from trusted catalogue if needed). Recover expired claim first. Authorize:reconcile_toolbefore callingreconcile.(original_key)(arity 2 with saved external deferral metadata). The Store rechecks its hash. Accepted outcomes{:confirmed, %{"status" => ..., "data" => ...}},:not_executedand:unknown. Lookup timeout is tool timeout or 5,000 ms default.:execution_uncertainon unknown/timeout/crash,:invalid_reconciliationon invalid return,:no_reconcilerwithout 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: ...}fromget/2. Requiredoperation_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 requiresaccept_duplicate_risk: true. Use originalidempotency_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 trustedagent:/continuation:orcatalog:. 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:accountingcontains qualified Usage maps for exact ancestor IDs. Workflows derive usage from response. Supplyrecover/3options and either leafagent:/continuation:or candidatecatalog:. 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/1optionsstore:,actor:,authorize:required, optionalname:,policy:,namespaces: nil(trusted list or arity-zero resolver for unscoped Store),on_ready: nil,follow_ups: nil,interval_ms: 5_000andpage_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}inissueswhile visiting other candidates.Continuation.Recovery.Policy.default/1v1 defaults to cancellation of model-only uncertainty, preserving original intent and usage. Alternativemodel: :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 useCatalog.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:resumethen pass exact ready reference, including a committed initial Frame 3 request before its first claim. Callback:okconfirms delivery,:leaveleaves operator work, error can be retried. Same ready revision may be delivered again. Deduplicate by reference and recheck atServer.resume/3. Timer handling authorizes:wake_timerbefore committing local result, then resumes by exact ready reference. Follow-ups use separate:deliver_follow_upauthority.Recovery.sweep/2reports:appliedand:replayedindependently of:woken,:leftand: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: :infinityor 1–4,294,967,295 ms after deletion confirmation. Ordered receipt keyssnapshot,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:evaluse 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_upsreturns 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 suppliedprovider_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 anExAgentorfn ctx, args -> agent end. Optionsname: "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: :allfor 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:unknowncan mark delegation outcome unknown. Retention omission does not prove safety to repeat.- In a persisted scope,
run_child/4without a durable descriptor returns:continuation_child_descriptor_requiredbefore dispatch, even with a context copy lacking:continuation. Durabledelegation_tool/2binds:definition,:policy,:model_ref,:model_codecand 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_uncertainrequires 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: nilor exact string reference. Default false for each ofshare_images:,share_audio:,share_file_references:. Generatestransfer_to_<id>(Handoff.tool/1) with optionalnote≤1,000 characters. Normal permissions, guardrails and approvals (including supported edit) apply.:multiple_handoffsbefore 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_targetis last destination.:run_handoffcarries 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/2for ambiguous checkpoint. Edits can supplytool: Handoff.tool(destination).:continuation_handoff_catalog_changedor:continuation_guardrail_policy_changedbefore claim under a changed binding. - Volatile
Session.chat/4verifies source and destination roster IDs and exact agent refs, checks policy'shandoff/3at the batch boundary. Current participant changes before successor runs. Event:session_turn_changedwithvia: :model_handoff. Finish advancement withSession.end_turn/3.
Session and shared state
Session.start_link/1accepts: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 raiseArgumentError. Invalid join returns:invalid_participantsbefore mutation.Session.child_spec/1uses{:exagent_session, session_id},restart: :transientand 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/3can 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. RetrySession.checkpoint/2. Restart before save uses last confirmed revision. Keep computations pure.- Read
current/2,participants/2,status/2,read_state/2andhealth/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/4keeps turn,end_turn/3advances.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_participantversus:not_your_turn.:checkpoint_pendingprevents further mutation. TurnPolicycallbacksinit/1,next_participant/2(returns{:ok, id, state} | {:done, state}),can_act?/3, optionalparticipant_joined/2,participant_left/2,handoff/3and custom persistencesnapshot/1/restore_snapshot/3. Roster order from initial options, later context roster unordered. Eligibility check can repeat within one turn. Advance cursor innext_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. ExplicitSession.handoff/3applies policy, preserves schedule cursor and emitsvia: :handoff.- Local subscription before
Session.start/2sees first event. Empty roster:no_participantskeeps:createdwith no checkpoint. Policy returns no turn:{:ok, :done}, publish:session_startedthen:session_done,payload.persistencereports save evidence. Done process remains available until close. Volatilechat/4takes run options plustimeout: 5_000for reply, explicitmessage_historyif needed, separate executiondeadline. Other mutations during chat:turn_in_progress. Requires no Store nor bound continuations. - Up to 64 configured continuation bindings.
Session.continuation/3reads bound participant evidence.complete_turn/5requires exact terminal ref, pure state update and same lifetime/run, rechecks after callback and commits once.reconcile_turn/4acknowledges exact local diagnostic without callback/advancement. Block:continuation_pendinguntil settled.health.continuation_blockedhas participant and:completion_required,:unavailable,:identity_changed,:result_not_finalor:changed_during_callback. Native participant execution and bound turn transitions are separate calls. - Mutations except chat accept only trailing
:timeout. Default 5,000 ms,:infinityfor checkpoint/complete/reconcile.:unavailableindicates no destination at send.:result_unconfirmedafter 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/1requires:id,:version(nonempty UTF-8 up to 512 bytes) and 1–255 steps, distinct IDs. Onlykind: :sequenceandfailure_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 pairinput: fun/2andinput_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/1requiresid:,version:,kind: :router | :parallel | :map. Router/parallel take 1–32 steps without mappers. Routerselect: fun/1andselect_version:choose declared ID. Maptemplate: stepandmax_items: 32(1–32). All take optionalmerge: fun/1and matchingmerge_version:.max_concurrency: 4(1–32).max_result_bytes: 65_536andmax_branch_result_bytes: 65_536, each 1–65,536 JSON bytes. Failure policy defaults:fail_fastfor router/parallel,:collectfor 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_optionskeyed 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 raisesArgumentError.binding/1emits versioned portable identity/fingerprint ≤64 KiB, no code or credentials.validate_binding/2errors: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_conflictfor 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_optionsby 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 delegateload/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 validatedUsageLimits. 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: :finalnotice) 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_toolslimits leaf dispatch,max_concurrencycontrols overlapping branch reservations. External cancel winning CAS returnsRunError.reason: :cancelledwith confirmed partial, completed steps retained and queued steps:not_started. Coordination.Resultstatus:succeeded | :failed | :paused | :cancelled. Fieldsoutput,output_omitted,steps,run_id/root_run_id/attempt_id, qualifiedusage/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. Stepid,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 inusage.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 withhint: :flow_output_veto_requires_pure_validators. Callback phases:mapping | :select | :mergereturn{: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. Useeffect.leaffor 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:andallow_evidence_deletion: trueto 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.Casepasses options to ExUnit and imports helpers.test_model/1needs a nonempty proper script list.assert_output/2requires succeeded accepted output with===,assert_tool_called/3supportstimes:,status:,args:,assert_usage/2supportsinput:/output:as{:complete | :partial, n} | {:unknown, nil}andquality:,assert_cost/2accepts{: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 aModelProfile, 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_requiredand hint forvalidate_resume/4.- Initially empty script uses label or generic text. Nonempty script consumes a text string,
Message.Response,{:tool_calls, calls},Test.stream/2orfn messages, params -> item endper 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 withtool_call_deltas: true.Fixture.open(path, opts \\ [])(cassette v1).mode: :replaydefault,:recordreplaces on successful close,:record_missinguses existing entries and records unmatched, prunes unused.case: Path.basename(path)valid UTF-8 and matches file.store_requests: falsefingerprints only, true stores canonical redacted request and allows first changed JSON Pointer diagnostic.redact_request: fun/1filters canonical hash in all modes.redact_response: fun/1changes 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: :verbatimsaves exact normalized chunk sequence, including commentary, thinking, tool fragments and cumulative usage. Unary policy returns matching event type or:dropand recording run receives the same result. With response redactor, stream policy requires callback, including omission of all fragments carrying sensitive text. Existing:record_missinghits 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/2on independent roots or siblings (inside tools useRunContext.fixture/1). Views share cursor/lifetime. Same-path overlap/indistinguishable admissions:fixture_ambiguous, no matching request:fixture_miss. Use fresh:recordafter changing paths.Fixture.close/1confirms completed write. Offloaded result refs normalized by first occurrence order in tool-return headers, preview/bytes/reader args kept. Built-inread_result/grep_resultresolve live reference by index. Other refs/prose literal. tool_stubs: %{offered_name => fun}orTesting.with_tool_stubs(fixture, stubs)returns strict view of same cursor. Per-call validated args orfun.(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" => :delegateplus 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_optionsfor workflows). Strict inventory and trusted policy jointly bind reservedexagent.strict_toolsreference. 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:integrationexclude/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(alsoExAgent.Case) portable case v1 omits execution options. Schema rejects invalid/unsupported version. CandidateEval.Case.from_run(source, opts)accepts settled run/stream terminal, trusted C7 read or authorized Online sample. Requiredname:andredact: fun/2with field/value (:input | :expected | :output) and{:ok, replacement} | :drop. Optionsinput:,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 authorizedContinuation.get(..., diagnostics: true)for settled root. Requiredname:,suite:,redact:. Optionaldir: "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.:completedor settled:failed | :denied | :cancelled | :expiredif replayable (failed bodies need candidateretain_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 pairedcase.json(≤8 MiB) andfixture.jsonwithout replacing an existing pair. Candidatemix exagent.eval.capture --suite NAME --run ID [--fixtures DIR]usesEval.Suite.capture/1for 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 scopedrun_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/1requiresmodel:and nonblank UTF-8persona:,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/1drives 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.stopand 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. Declaredmodel: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{}. TargetExAgentorfun.(input, merged_run_opts), success with%{output: value}andnew_messages:for evidence.evaluators: [],concurrency: 4,timeout: 120_000,evaluator_timeout: 120_000,repeat: 1,fixtures:(requiresdir: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/1exact expected (trim true, case-sensitive true, optional Unicode case-folding),contains/1fraction of nonempty string/number terms (trim true and case-sensitive false),matches/2regex. Nil expected skips equals/contains.tool_called(name, opts)counts emitted calls, malformed included if no args filter. Options:name,:timesexact nonnegative or nil for presence,:statusfirst 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 fortimes: 0. Nested delegate evidence belongs to child.tool_arguments(name: ..., threshold: 1.0, step: ...)pairs by tool name/occurrence withcase.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/1requiresmodel:,criteria:. Optionsmodel_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 lineVERDICT: PASS/FAILwith 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. Totalcost_centsonly if all priced,known_cost_centssubtotal. Repeated paused attempts need distinct C7 IDs and same-run resume after reporting leaves the original score fixed. - Reliability at shared
kacross repeats draws without replacement:pass_at_k = 1 - choose(n-c,k)/choose(n,k),pass_all_k = choose(c,k)/choose(n,k)forcsuccesses, with per-case and suite means.Eval.Report.compare/2matches same case name and verified digest of input/expected/metadata/opts/timeouts/evaluators/scenario, compares different target definitions and repeats. Version opaque callbacks/options. Reportsadded,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/2point listsregressed/improvedplus"beta_paired_v1": independentBeta(1+c,1+n-c)per case and report, 95% interval for mean paired change,:regressedbelow 0,:improvedabove 0,:inconclusiveotherwise.:no_common_cases/:no_comparable_casesgive nil interval.significant_regressionsentries 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.Suiteuses namedtarget/1,cases/0,evaluators/0, optionaloptions/0, candidatelabels/0andcapture/1.mix exagent.evaldiscoversevals/**/*_eval.exs. Switches--suite NAME,--only CASE,--repeat N,--fixtures DIR(defaultevals/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 inCI=truerequires 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-regressiondisables baseline gate. Matching diagnostics include case/attempt in stderr (and portable text/JUnit). Target JSONerroror graderdiagnostic. 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/2returns{: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/1requiresscope:andevaluator:, optionalversion:(criterion version),name:,sample_rate: 0.01,capacity: 64including active,seen_capacity: 4_096,timeout_ms: 5_000,judge_max_tokens: 512,content: false,max_content_bytes: 16_384combined,store: nil,grading_backend: :memory,otel: nil.handle/1local 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_startreceipt deduped with event by run ID. Active cancel needs confirmed:server_request_cancelled(persistence andpayload.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.:otelcallback receives OTLP/HTTP JSON loggen_ai.evaluation.resultwith optional trace/span from evaluated context, score/error, safe tool evidence, qualified grading, evaluator/version and independent integerexagent.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:okon acknowledged dispatch.[:exagent, :eval, :online, :result | :delivery | :discard]correlates evaluation ID. Delivery status:dispatchedor: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 viaEval.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 andexagent.evaluation.idstable. Existing export mark fences old duplicate reservations, otherwise follow earliest reserved deadline. Ambiguous/failed emission leaves claim, no automatic replay,:delivery_unconfirmedor:job_faileddiscard as appropriate. Bounded local dedupe supplements durable fence. Subject erasure usesRetention.erase/3with 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.
| Suffix | Boundary, measurements and selected metadata |
|---|---|
:run, :start / :stop / :exception | Start system time. Terminal duration, agent and lineage. Stop status, usage, steps. Exception bounded reason: %{type: ..., provider: ..., status: ...} when known. Both carry usage/cost evidence. Stop includes confirmed pause (:paused) and success (:succeeded). Failed pause save is exception. Counts/usage cumulative across attempts. |
:model, :request, :start / :stop / :exception | One admitted logical request, including retry or replay. agent, run_id, root_run_id, model_request_id, step, model, provider, stream, fixture. Terminal usage_status, usage_quality, cost_status, estimated cost_cents or cost_subtotal_cents. Stop finish_reason, exception bounded reason. Incomplete provider finish is a stop while run fails {:incomplete_response, finish}. Known input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens appear only as evidenced. |
:model, :attempt, :start / :stop | Physical callback entry and return/cleanup per direct dispatch or Fallback leaf/retry. Join telemetry_span_context to span exagent.attempt.id and logical model_request_id. conversation_compacted candidate true with proof, else nil, operation: "chat", model/provider labels ≤256 bytes or "other", source: :test or :adapter, fixture: :record or nil. Stop includes duration, usage/cost coverage and available token counts, outcome :succeeded / :failed / :incomplete / :cancelled, finish and HTTP status. Kill may orphan start. Quota/preflight skips and replay produce zero attempts. A callback can fail before network IO. |
:model, :retry | Fallback scheduled attempt, delay_ms and model, status, fallback. |
:model, :reasoning_prefix, :reset | Candidate dropped_blocks, model/provider/reasons plus logical IDs when available. Reasons :system_changed, :tools_changed, :output_format_changed, :history_changed, :reasoning_chain_changed, :unverified_history, :unreplayable_reasoning, :projection_removed, :foreign_history, :provider_prefix_mismatch. Capability plus leaf can each report. Preflight/replay emit no adapter reset. |
:tool, :stop | Duration, agent/run, declared name or "unknown_tool", return status/success, opaque call_ref, duration_measured true for worker time and false for elapsed batch when no worker report. Candidate CodeMode adds program_call_ref, program_step (1-based), effect. |
:embeddings, :request, :start / :stop and :media, :request, :start / :stop | Admitted embedding/rerank or media operation with provider/model, run/call ref, telemetry_span_context (span exagent.request_id). Embeddings includes input_items and available rerank_search_units. Stop duration, outcome, qualified usage/cost, known token/media counts and HTTP status. No text/vectors/documents/scores/media bytes/URLs. |
:guardrail, :tripped / :output, :partial / :judge, :verdict | Count 1, respectively name, stage, run_id, root_run_id, attempt_id / mode / kind, verdict. |
:rate_limiter, :wait / :reject / :cooldown / :settlement_retry | Count 1 and known wait_ms (settlement retry delay_ms, zero for single late report). Configured quota key. |
:usage_limits, :budget, :settlement | Count 1, available reservation, full charge or subtotal. reservation_id, labels, source (:runtime / :reconciliation), coverage (:available / :partial / :unavailable), outcome (:priced / :unused / :held). Duplicate reconciliation may repeat ID. Append :unconfirmed for failed settlement retry, %{count: 1} and empty metadata. |
:usage_limits, :budget, :threshold | Count 1, charged/limit cents, window_start UTC ms, integer percent threshold, ETS account name/PG scope digest. Best effort, one claim per window. |
:conversations, :activation | Count 1, status :waiting / :queue_full / :capacity / :wait_timeout / :factory_timeout / :start_unconfirmed / :reconciled. |
:job, :start / :stop | Volatile, job ID/name, start system time, stop duration and status. Duration admission to Jobs owner processing completion includes start handlers and mailbox. Durable delivery timing from [:oban, :job, :stop] / :exception and true job/notice state via Jobs.Durable.status/2. |
:memory, :command / :compaction, :stop | Memory count 1, command/status (including :preload). Compaction duration, input/output message counts, known estimated tokens saved, agent/run/step/compactor/status/error. :compacted / :no_change / :error. Error keeps incoming projection. |
:continuation, :recovery / :store, :postgres, :maintenance_failed / :chat, :checkpoint_wait_expired | Count 1, respectively operation/status, Repo/table/content-free error type, or generated resume job ID after checkpoint wait cancellation. |
:mcp, :catalogue, :drift / :mcp, :validation_error | Added/removed/changed counts and revision/drift rule. Validation count and rewritten, no values. |
:eval, :online, :result / :delivery / :discard | Projection v1, scope/run/source/criterion/version and correlated ID for result/delivery. Result count, duration, system_time plus run status, event name, trace, optional response ID, safe tools/completeness and label/score/error/qualified grading. Delivery/discard count 1 with status/reason. |
:observability, :failure / :content_dropped / :processor | Fixed stage/count or bounded exporter processor diagnostics, no raw exporter errors. |
ExAgent.Telemetry.metrics/0available when compiled with optionaltelemetry_metrics ~> 1.1. Phoenixlive_dashboard ..., metrics: ExAgent.Telemetryor 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.0are the documented native setup. API without SDK is no-op.ExAgent.Observability.OpenTelemetry.new/1optionscontent: 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), candidatemetrics: false,link_continuations: false, candidateservice_tier: false. Passobservability: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.v3andexagent.gen_ai.revision d0e74ba6c48bcc4ded473b1828a8212f06b23753(GenAI v0.1.0). Spansinvoke_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 spansexagent.*.embeddings {model},exagent.rerank {model},exagent.media.{operation} {model}include bounded metadata with qualified dimensions. CodeMode child span attrsexagent.tool.program_call_ref,exagent.tool.program_step,exagent.tool.effect. Invocationexagent.call_refmatches Event and pending records. - Direct client span ends before after-request hook/tool IO. Fallback has parent
exagent.model_requestand leaf client spans. Replay uses internal model request span.exagent.attempt.dispatched=trueonly on callback entry, false if redactor exhausts deadline before dispatch.gen_ai.conversation.compacted=trueonly 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 subtotalsexagent.cost.*reuse ledger. OpenRouter reported charge can be complete. Native service-tier opt-in exports known response tier. capture_context/0andwith_context/2propagate span context/config only and restore previous OTel/Logger span keys after callback. Explicittrace_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: trueon 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 underexagent.content.*issystem_instructions(parts),input_messages/output_messages(messages),tool_arguments/tool_result(JSON effective args/visible success). Messages%{"role" => role, "parts" => parts}, parts typetextwithcontent,tool_callwithid/name/arguments,tool_call_responsewithid/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, withcontent_dropped. Max three attribute fields per span, redacted JSON string (Erlang scalar/array attrs). Withheld result retains effect status andexagent.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_bridgeand observed model call{:observability_conflict, :req_llm_bridge}before IO. Enrich active native model/leaf with boundedexagent.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 usesexagent.req_llm.content.*namespace.detach/0andprune_stale_spans/1only 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 useLogger.put_module_level(..., :error | :none)and keepconfig :req_llm, debug: true/REQ_LLM_DEBUG=1off for content-free logs. Finch request/send/recv/queue telemetry can include static MCP/other request headers and response headers/trailers.:headers_provideruses 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.0with host readers. Native meter:exagentmeasuresgen_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.MetricsviaReqLLM.attach(metrics: [models: labels])accepts 1–32 unique models, false default.:exagent_req_llmmeter uses inference/embedding duration and positive normalized token counters, suppressed when native attempt metrics already account for request. Streamgen_ai.client.inference.time_to_first_chunkandexagent.req_llm.stream.estimated_seconds_per_output_tokensupplement 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/0default instanceticks, passes, pruned_entries, last_pruned_entries, status(:waiting / :active / :detached) or:unavailableat 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
BoundedProcessorSDK extension config map requiresexporter: {Module, opts}. Defaultsname: __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: :infinityor 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/1scalar counters/state/gauges,acceptedenqueue,exportedcallback success,retainedqueue/in-flight and drop/loss/restart counters.force_flush/1asynchronous request.shutdown(config, timeout \\ 5_000)monotonic caller wait:infinityor 0–4,294,967,295 ms. Discards queued/in-flight and returns final snapshot after bounded stop. Invalid wait raises before send.:unavailableno instance,:result_unconfirmedafter 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, baseotlp_endpointappends/v1/traces. Headers via exporter env/app configuration,OTEL_EXPORTER_OTLP_TRACES_HEADERScomma-separated andOTEL_SERVICE_NAMEresource. 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 OTLPpartial_successevidence. Verification distinguishes enqueue, callback, peer status and durable backend ingestion. Example trace endpoints are Langfuse EUhttps://cloud.langfuse.com/api/public/otel/v1/traces(Basic +x-langfuse-ingestion-version=4) and Opikhttps://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.pywith HTTPvm_http_worker.exsor gRPCvm_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 publicotel_otlp_traces:to_proto/2and generatedexport/3, optional trustedrequest_profile.project/1for 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.pyplus 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, inspectdropped_spanswarn logs (and metrics) beyondsent_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.exsandtest/support/postgres_load_probe.exswith 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/1common opts:name,:transport,timeout: 5_000(1–4,294,967,295 ms),max_pending: 128,max_frame_bytes: 8_388_608excluding 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 raisesArgumentErrornaming key. Runtime spawn/handshake failure returns{:stdio_spawn_failed, reason}or protocol/transport reason.- Stdio opts
command: pathrequired,args: [],env: [],cd:,environment_policy: :isolated. Direct spawn. If needed resolve executable withSystem.find_executable/1. Default retains small OS runtime allowlist plus explicit pairs (binary/charlist names/values, false removes, later wins).:inheritkeeps 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-18and unbound accepts it,2025-03-26or2024-11-05. Bound stdio revision pin incontinuation_binding.protocol_version(no top-level key), exact reply required or:mcp_protocol_binding_mismatch.initializeresult needs objectcapabilitiesandserverInfostringname/versionelse:invalid_initialize. Other revision:unsupported_protocol_version. Stdio and legacy SSE answerpingand respond-32601for 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_httprequiresurl:(HTTP(S) ≤8,192 bytes with host, no userinfo/fragment) and exactly one offinch: poolorheaders_provider: fun/1. Finch requires host-owned HTTP/1-only pool,headers: []static, defaultnodelay: true. Body callback separates header/body upload. HTTP/2 yields:http_transport_errorfor 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:finchand: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/discoverat2026-07-28, falls back toinitializeat supported legacy2025-11-25,2025-06-18or2025-03-26only on compatible legacy negotiation. Transport/auth errors propagate. Bad discovery:invalid_discovery, no supported rev:unsupported_protocol_version. Explicitprotocol_version:restricts to it. Reconnect keeps negotiated version. July carriesparams._meta io.modelcontextprotocol/protocolVersion,clientInfoandclientCapabilities(same namespace), plusMcp-Method, applicableMcp-Name/Mcp-Param-*andMCP-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 orderedtools/listpagesnextCursorup 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_invalidatedbefore next page. Restart from first page or reconnect if unready. July invalid remotex-mcp-headerdeclaration omits that tool. Literalannotations.readOnlyHint: truemapseffect: :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.Searchfor large collections.- Discovered object
outputSchemabecomesTool.result_schemawith validator and saved result binding.structuredContentvalidated 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 validcontent(can be empty). Malformed content → unconfirmed.Client.call_tool/3projects by name without result schema, even after discovery. ValidisError: 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 usesstructuredContentJSON. Earlier protocols require object. July also supports array/scalar/null.image_toolssuccessful text/image returns{:content, parts}and imports multimodal Tool. Incompatible mixed blocks/invalid image data unconfirmed. Server multimodal output mapsImageContentwithtype,mimeType, Base64data, omits object result schema. Unbound discovery and July routing can cache only full traversal with all pages positive integer
ttlMsand samecacheScope: "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 ornotifications/tools/list_changedinvalidates. JSON-RPC v2 notification has string method, absentid, object params default%{}. One pre-upload routing refresh on staleness, second:session_invalidatedwithout upload. Generated tools use declarations captured during discovery. No automatic repeat after upload. Bound unpinned discovery reads live tools for fingerprints.- Candidate
Client.snapshot/1fetches live declarations bypassing TTL or returns existing pinned bytes.MCP.Snapshot.decode/1requires canonical JSON ≤8 MiB, unique keys and matching lowercase SHA-256 overschema_version: 1,revision,tasks, orderedtoolswithname, description, inputSchema, outputSchema, annotationswhen supported/present. Name unique UTF-8 1–128 bytes. Object keys sorted and schema/tool array order preserved.:invalid_mcp_snapshoton mismatch/malformed.mix exagent.mcp.lock ENDPOINTcompiles with:exagent_mcp_lockmap entry (opts or MFA), opens transport/lists/closes, writespriv/exagent/mcp/<endpoint>.lock.json. Can start temporary HTTP/1 Finch. Host stays stopped. Doctor--check-mcp-lockoffline verifies configured locks. Use distinct lock per principal view. - Candidate
pinned: bytesprovides declarations offline, revision/Tasks opt-in fixed by lock (explicit pinned options must match). Tool-only client can omit transport config,reconnect/1then:not_available. Otherwise calls wait for verification. Defaultconnect_on_start: falserequires connection/verification on demand viareconnect/1, true verifies before startup reply. Exact comparison:ok.{:mcp_catalogue_drift, %{added: ..., removed: ..., changed: ..., revision: ...}}sorted names. Defaulton_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_requiredbefore 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/3and 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/1performs fresh handshake/pin verification without replay.Client.close/1releases 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_timeoutbefore 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 completeWWW-Authenticatefield: 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_unconfirmedfor 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/1returns 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-listcode_challenge_methods_supportedcontaining"S256"(else:pkce_unsupported).pkce_verifier/1encodes random 32–96 bytes base64url unpadded,pkce_challenge/1requires 43–128 RFC 7636 chars and S256.validate_issuer/2checksisson success/error before use, including:issuer_mismatch/:missing_issuer. Host owns trust, redirects, OAuth state, code exchange, credential custody and refresh. - Client
trace: truecaptures caller span before worker and injects W3Ctraceparentand optionaltracestateintoparams._metaon both transports. Server Plugtrace: falsedefault,:local,:trustedor 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 typetool_result_schema_mismatch,mcp.tool.result_schema.reasonone ofmissing_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"withinputRequestsobject and optional opaque stringrequestState→%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_inputfor 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,:cancelcloses run via decision. Fabricated success/failure:mcp_input_requiredleaves pending. Candidate liveon_input: fun/1gets%{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: falseonly advertised with2026-07-28and peerio.modelcontextprotocol/taskssupport. Peer chooses immediate vs task.MCP.Client.Tasks.start_tool(client,name,args)returns ordinary projected reply or{:task, map}with private servertaskId(UTF-8 1–512 bytes) and optionalpollIntervalMs(at least 10 ms honored, default 500).get_task/2reads"working","input_required","completed"with result,"failed"with error code,"cancelled".cancel_task/2 :okacknowledges 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_idandpoll_interval_msin root/leaf inbox. Structural workflow leaves use synchronous calls. Rebuild same bound tool on replacement ready client, authorizeContinuation.reconcile_tool/4for 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_uncertainkeeps 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/3keeps open task evidence ({:retained, :open_external_deferral}). Task IDs are in trusted inbox andMcp-Nameheader 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. Finchconn_max_idle_timereduces 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-32004or July10001yields effect unconfirmed on any transport. ConfirmedisError: trueproduces{: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/1per static catalogue. Requirestools:function tools, optsname:,capabilities: [],permissions: %Permissions{},on_validation_error: nilor 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 stringprompt, authenticated actor indeps. 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 validatedstructuredContentand 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_callthen 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-32004or July10001. 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}andclose(server, sid, actor, opts \\ [])require authenticated actor.timeout: 5_000for 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.Plugrequiresserver:andauthorize: fun/1→ verified actor or error, optsorigins: []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 (-32700on parse error). Separate mounts for revisions. POST responsesCache-Control: no-store.- Legacy initialize returns
Mcp-Session-Idand negotiated revision for subsequent POSTs. Client sendsnotifications/initializedbefore list/call, Accept JSON + SSE, one JSON-RPC message. Progress token (string/integer) or live approval uses chunked SSEmessageevent 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/cancelledwith originalrequestIdstops matching call and final stream without result, POST 202. Disconnect doesn't cancel. Legacy sessions node-local and sticky. - Progress
params._meta.progressTokenechoed with count innotifications/progress, advances on tool entry, model step andRunContext.emit/4. Samples every 250 ms and final, milestones can coalesce. Legacyelicitation: truedelegates approval trust to authenticated peer with form capability.:ask/required approval after arg/guard checks, deny always wins.elicitation/createfresh ID and required booleanapprovewith original tool args, same principal/session answers through separate POST. Onlyacceptwith 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 (-32020mismatch,-32022unsupported revision). Tool"x-mcp-header" => "suffix"on string/integer/boolean leaf through nestedpropertiesmaps toMcp-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 hintsttlMs: 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 bindinputRequests/signedrequestState, 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, emptyresources/templates/listif available,prompts/list/prompts/get. Exact registered URI and text/MIME defaulttext/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-32000on 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-32002or 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. Metadataresource,authorization_servers,bearer_methods_supported: ["header"], optional scopes.authorizevalidates Bearer issuer/audience/expiry/scopes and returns stable actor.{:error, :unauthenticated}and:invalid_tokenwith optional required scope list → 401 Bearer challenge (invalid token parameter accordingly),:insufficient_scopeoptionally with list → 403 and required scopes. Authorization before dispatch and exact Origin allowlist.
MCP guide · Continuation binding recipe · Support and limits