Migration guide
View SourceUpgrade one major version at a time. Each section lists the changes an application makes; the task guides describe the resulting behavior.
Upgrade from 2.x to 3.0
Update the dependency to {:exagent, "~> 3.0.0"}. Before switching writers,
stop admission and drain active runs and workers. Back up the Store and retain the old executable,
endpoint, tool inventory, definition versions and codecs for unfinished runs.
Test restoration on a copy. Complete records lacking endpoint evidence with
their original release. For an unconfirmed effect, reconcile against the
external system before allowing another attempt. Restoring a backup alone
cannot undo an external write. For rolling deploys between releases that
share a Store format level, use the procedure below.
Apply PostgreSQL retention and resume recovery
Rerun the installer with the same Repo and Store options to add PostgreSQL
retention maintenance to the host supervisor. For a generated background
agent, rerun mix exagent.gen.agent Name --durable. In a hand-wired
supervisor, add the maintenance child after the Repo.
{ExAgent.Store.Postgres.Maintenance, repo: MyApp.Repo, table: "exagent_snapshots"}Use your configured table if you chose a custom name. The child also checks
the default snapshots table used by Jobs. Unified schema version 1 installs
the retention indexes. Doctor --check-store reports missing snapshot
indexes under store.maintenance for an enrolled schema. --check-jobs
also checks the retired Jobs index. If an earlier 3.0 development schema
lacks the indexes, recreate that development schema before starting the child.
Assign a finite TTL only when your host can bound late deliveries.
Update the host-owned Agents.ResumeWorker to snooze in steps of at most
five seconds on :checkpoint_pending for up to 15 minutes from job
insertion. At the deadline the worker emits
[:exagent, :chat, :checkpoint_wait_expired] and cancels the job with
:checkpoint_pending. Confirm the owner's pending checkpoint or reconcile
it, then re-enqueue using the exact current ready reference. The live
owner can adopt a ready revision when the interrupted Writer attempt is
fenced. For an unconfirmed reset or abort, use the exact
Server.checkpoint/2 retry.
Sync coding-agent guidance
Enable skills: [package_skills: [:exagent]] in the consuming app's
UsageRules 1.3.1 configuration and run mix usage_rules.sync.
Select :exagent under usage_rules: to sync the package's
usage-rules.md as well. Use .agents/skills for Codex and Cursor or
.claude/skills for Claude Code.
The synced rules and skills now resolve guide paths from the installed
dependency root. Run mix usage_rules.sync again after upgrading a
path: dependency to refresh both.
UsageRules package skills
Capture failed agent turns
Set retain_failed_turn: true in the source C7 continuation configuration
to retain bounded failed-turn evidence for authorized diagnostics. The
option affects future closures. Earlier failed records can only use the
evidence they still have. For an output-guardrail rejection, give the test
target a guardrail that returns the same verdict on the redacted model reply.
Callers matching :capture_history_unavailable or
{:unsupported, :projected_tool_result} should handle
{:capture_body_unavailable, body, cause} for a missing body and
:capture_journal_mismatch for evidence that cannot be bound to the run.
:missing_input still covers an explicitly absent or dropped prompt.
When the journal provides no prompt, the new error identifies its absence.
Existing case and fixture files load with the same formats. The Store
requires no database migration. Upgrade owners that can reset persisted
conversation history before enabling retention. A history reset clears
the opt-in body and leaves intent payloads in the execution journal
until the next confirmed turn or subject erasure.
Reset behavior
Capture recipe
Offer Ash actions with durable approval
Install the candidate exagent_ash 0.1.0 in an Ash 3.38.1+ app.
In an AshPostgres host, mix igniter.install exagent_ash generates
the ExAgent Store migration. Apply it with mix ecto.migrate
and configure ExAgent.Store.Postgres for C7.
When replacing individual from_action/3 calls with tools/2, review
the offered list and approval flags. tools/2 requires approval for writes
by default. Carry over custom names and pass deliberate overrides in
the action's option list. Retain the original definition for existing
continuations and assign a new reference if its tools change. A policy
denial before dispatch or an Ash input detected as invalid before
execution now returns :tool_error to the model. Reconcile errors from
dispatched writes through C7. Resolve the approved continuation's tenant
from its authorized host scope and supply an authorized Ash actor on
resume. Ash authorizes against the supplied dependencies, so changing
the tenant can redirect the write.
Framework integrations
Upgrade PostgreSQL and roll out a Store format level
mix exagent.install generates one pinned Ecto migration for a new PostgreSQL
host. On a 2.2.x or 2.3.0 host, keep the applied migrations and use the same
Repo and snapshot table with mix exagent.upgrade. The task requires the
same optional Igniter dependency as the installer and is safe to repeat.
mix exagent.upgrade --yes
Use --repo MyApp.Repo in a host with several Repos, --table my_snapshots
for a custom Store table and --memory-table my_memory for a custom Memory
table. The task reads the selected Repo's migration files and pins rollback
to the highest literal unified version in their up/0 functions. It uses 0
when the existing files use 2.x adapter migrations. For custom migration
paths or dynamically computed pins, set down/0 to the unified version that
the earlier migrations establish.
Unified versions from 3.0 development have been consolidated. Replace
unpublished migration pins and recreate development schemas that used them.
Regenerate development reports with the current suite and record development
cassettes again with mix exagent.eval --record.
Use the same explicit pins in a hand-written migration.
defmodule MyApp.Repo.Migrations.MigrateExAgentToV1 do
use Ecto.Migration
def up, do: ExAgent.Migration.up(version: 1)
def down, do: ExAgent.Migration.down(version: 0)
endApply the migration with mix ecto.migrate. Every published version keeps
its DDL in both directions. Future releases add new versions.
Unified schema version 1 includes Store SQL 1–7 on every enrolled Store,
including the pending timer index, and adds the retention indexes. It installs
Jobs, Budget with attribution and threshold claims, RateLimiter, Memory, tool results and scheduled
follow-ups on the Repo's first search-path schema. exagent_follow_ups is
a reserved table name. If a 2.x host used it for Store or Memory, rename
the host table and its Memory version sequence, where applicable, in Ecto.
Use the new table name in the host descriptor and when enrolling. Oban
and host application tables use their own migrations.
After mix ecto.migrate, run the
header backfill on each enrolled
Store table with 2.x C7 journals, including the default table if it holds
durable Jobs journals. Verify the headers before starting writers and Recovery
or relying on run pages and the catalogue census.
Update the host's approval code to read pending requests with
Continuation.pending/2 and approve or deny through their
ApprovalRequest. Missing-option errors from Continuation.decide/4
list the absent keys and link to the administration steps.
Approvals and continuation administration
Run Doctor with --check-store against the configured Repo. store.migration
reports the applied and pending schema versions, and store.format reports the
current write level and the binary's reader level. The schema version and
the Store format level advance independently. store.postgres checks the
recovery and timer indexes (Store SQL 6 and 7) even on an empty table. If
unified version 1 is already recorded, restore a missing index in a new host
migration.
Store.Postgres.migrate/1, Store.Postgres.migrate/2 and
Memory.Postgres.migrate/2 are for replaying 2.x host migrations.
The legacy Store helper installs Store SQL 1, 2 and 4–6. Apply the unified
migration after those files when upgrading, and use it directly for a fresh
installation. The standalone SQL helpers for Store, Jobs, quota and tool
results are also deprecated. Before moving to 4.0, preserve the original SQL
in host-owned code for historical migrations that call those helpers and
verify a replay from an empty database.
Each table stores one write level for all its namespaces. New or enrolled
PostgreSQL tables and ETS start at level 1. It includes
the full 3.0.0 format, including C7 permissions, MCP forms, principal-grouped
MRTR receipts, generation-bound erasure and service-tier accounting. 3.0
writes approval v2 and run header v1. Approval readers also accept the
published v1.
PostgreSQL writers can opt into fragments with segments: true.
Both descriptors read inline and fragmented rows.
The level 1 Store reader also handles snapshots and continuations from
before the internal split of Server, the continuation writer and MCP.Client.
Use the following procedure when a future 3.x release adds a Store format level.
- Apply the additive schema migration and record the table's active write level. Keep the original definition, policy and codec available for every open run.
- Roll out the binary that reads both the active level and the next one.
With the level still at N, all writers stay within level N. A feature
that requires a higher level returns
{:format_level_required, feature, required_level, active_level}when no compatible encoding is available. Roll back to a release that supports N and all formats already present while the active level is N. - After every worker and replica can read the next level, the authorized operator finalizes it for the table. A release supporting level 2 can advance level 1 using the following call.
{:ok, receipt} = ExAgent.Store.finalize_format(store, from: 1, to: 2, actor: "deploy-372")The Store commits the new level and its audit receipt together. The receipt
contains the old and new levels, the host's actor ID and the Store timestamp.
A concurrent finalization returns the level that won. Finalization is
monotonic. Use a reader that supports the new level from that point onward.
A reader encountering a newer format returns
{:unsupported_store_format, feature, required_level, reader_level}.
Rolling back the application during step 2 leaves the additive DDL in place.
An Ecto rollback to schema version 0 preserves adopted tables and their
additive repairs apart from the pending timer and retention indexes. It
refuses to drop nonempty newly installed tables or undo a format finalization.
The rollout governs ExAgent's bundled Store boundaries. Cassette files and external queue consumers follow their own versions.
Check the API stability tier
Check the module tier and any candidate API label beside the function or
callback in ExDoc. Check the support table for candidate options, fields and
variants on otherwise stable entry points. Examples include Tool.new/1 with
:reconcile, ExAgent.resume/3 with a catalogue, and per-call :usage_limits.
Jobs.Durable.recovery/2 follows stable SemVer for its qualified Lifeline
path. The catalogue's worker definition and queue callbacks are candidate.
Stable APIs follow strict SemVer from 3.0. Candidate APIs can break in a minor
release with migration instructions. Keep a patch-only constraint such as
~> 3.0.0 while you adopt a candidate API and rehearse the upgrade to each
new minor. Keep compatible readers for saved records. Replace calls to
internal modules or hidden functions with a documented public API.
Support policy
Use the stable operational APIs
Keep existing catalogue references, budget accounts and C7 bindings when adopting the stable catalogue, recovery, spend and erasure APIs. Look up candidate fields in erasure and sweep replies by key. The native OpenTelemetry adapter and the generated chat's view, reader and flat-form helpers also follow stable SemVer. Candidate options and fields
Use the original request ID with Chat.Reader.admission/4 or /5.
A receipt with a different ID yields {:error, :idempotency_conflict}.
Reload forms for the authorized deferred call with Chat.InputForm.present/2
before accepting a submission. Handle {:error, :invalid_mcp_input} from
responses/3 for invalid submissions and malformed form projections.
Update the final 3.0 candidate contracts
Update code adopted from earlier 3.0 candidates.
| Surface | Earlier candidate | Closing candidate |
|---|---|---|
Server startup and generated Agents.server_options/1 | continuation_catalog: catalog | catalog: catalog |
| Startup of an adopted conversation missing its catalogue | {:error, {:restore_failed, {:adopted_definition_requires, :continuation_catalog}}} | {:error, {:restore_failed, {:adopted_definition_requires, :catalog}}} |
Continuation.retry_effect/4, reconcile_model/5 and custom Recovery actions using a catalogue | agent: catalog | catalog: catalog |
use ExAgent.Jobs.Durable with a catalogue builder | definition: &catalog/1 | catalog: &catalog/1 |
Generated Agents.input_agent/2 when the saved definition is missing | {:error, :definition_unavailable} without a catalogue | {:error, {:definition_unavailable, ref}} for either lookup |
Models.ReqLLM.new/1 | Reserved speed: nil | Remove the key. A supplied :speed raises the standard unknown-option error. |
Budget.Postgres.statement/2 | {:ok, %{entries: receipts, next: next}} | {:ok, %{items: receipts, cursor: cursor}}. Pass the cursor as :after. |
| Budget Telemetry subscriptions | Prefix [:exagent, :spend_budget] | Prefix [:exagent, :usage_limits, :budget] with suffixes [:settlement], [:settlement, :unconfirmed] and [:threshold]. |
Pass the catalogue as :catalog for C7 decisions and Judge approval.
An edited Server approval can rely on the Server's configured catalogue
to supply the saved tool. An effect operation with an explicit agent
uses :agent and :continuation together. Pass a catalogue as the first
argument to ExAgent.resume/3 or resume_stream/3. Workers can supply the
trusted catalogue through the Jobs.Durable.definition/1 callback.
Existing Store records are readable at format level 1.
Deploy with open continuations
Apply the wave 31 QA fixes
- Pass the whole authorized inbox to
Chat.AGUI.Input.decode/2. Send client answers for approvals, inputs and declared frontend tools. The host or Recovery settles timers and other external deferrals. - Handle
{:error, :fork_limit}when 64 branches are retained. A refused regeneration can now return the original refusal after discarding and sealing an unused destination. Use a fresh ID to retry a confirmed refusal and keep the same ID to look up unconfirmed delivery. Branch retention - Declare timer tools with
requires_deferral: trueand migrate PostgreSQL before enabling deferral-capable roots. For a v3 rollback, settle open timers before removing their index. For a v2 rollback, switch Budget processes to a v1-compatible binary before removing the ledger schema. Timer setup and rollback · Budget rollback - Use argv for tools with a
:commandcomparator. Non-ASCII whitespace and zero-width separators are rejected in rules and arguments. Permission predicates
Update adoption checks and fixtures
mix exagent.catalog.lock distinguishes missing configuration, invalid
callback output and callback failures. Its diagnostic gives the exception
type and can show a bounded ArgumentError or RuntimeError message
with nested argument strings redacted.
First deployment and lock refresh
A supervised pinned MCP.Client can use candidate connect_on_start: true
to verify its catalogue during startup. An explicit false works without
:pinned. Use the same reviewed lock and binding in the offline task and
the live chat.
Generated chat recipe
Recovery.sweep/2 now counts a committed timer as :applied even when
the same sweep calls :on_ready. Keep separate counters for fresh
mutations and delivery outcomes (:woken, :left and :rejected).
The telemetry event for the timer is wake_timer with status :applied.
A receipt replay increments only :replayed.
Use the candidate deftool/3 options :effect and :requires_deferral
to set these fields in a typed declaration. For an optional output schema,
use output: schema || :text with the default output mode.
Attach a complete estimated cost to TestModel's generated or scripted
replies when exercising a spend budget.
TestModel settlement example
Consume the candidate chat streams
For the conversation SSE endpoint, configure the optional :run_options
callback to set dependencies and permissions from trusted request assigns.
Apply the deferrals and activities arrays on snapshot and upsert live
activity by kind and ID. Use approval_requested.pending for the
public review identifiers. Fetch review details and submit C7 decisions
in the authorized host.
For AI SDK 7, render dynamic tool parts and read the outcome in
message.metadata.exagent. Continue handling data-exagent-status for
host-owned waits and cancellation. Save the cursor before admission and
replay the run from its first attempt. For a resumed attempt, pass the
preceding confirmed pause cursor as :resume_after to Chat.AISDK.new/3.
Refresh the authorized chat snapshot when the run prefix is unavailable.
The native tool approval view uses the Server IDs.
The host continues to own review and effect admission.
HTTP and AI SDK recipes
Adopt the AG-UI encoder
Use candidate ExAgent.Chat.AGUI to project an ordered root Server
attempt to AG-UI 1.0. Use the authorized threadId and a fresh wire
runId for each request, including after a C7 pause. If you omit :run_id,
Chat.AGUI.new/3 generates one for the encoder. Initialize the
encoder from the host's chat page and read events from the cursor before
dispatch. For C7, read from before the decision so the new stream can
carry its confirmation. Existing chat and Store integrations can adopt
this encoder without a data migration.
Phoenix recipe
Render AG-UI activity and summaries
Render exagent.child_run and exagent.job activity by messageId. Apply each
ACTIVITY_DELTA.patch to its snapshot. A job notice can replace the same job
activity in a later attempt. chat.activities exposes these status records
from replay of the latest attempt. Children still open at the root terminal
show unknown.
For C7 child activity, supply a durable delegation descriptor and its
catalogue entry. Enable child_events: :all on the turn or resume. The
resumed child sends a replacing snapshot under the same activity ID.
If you retained candidate child activities keyed by
<wireRunId>:child:<childRunId>, rekey them to exagent:child: followed by
the unpadded Base64url encoding of content.runId. Keep the latest
activity for each child. Each stream uses a distinct wire runId.
Durable delegation
Reasoning defaults off. The candidate :reasoning redactor receives
:reasoning_summary and provider summary text on unguarded turns. Stream
and final-output guardrails suppress the summaries. Return
{:ok, reviewed_text} or :drop. For stock OpenAI Responses, request summaries
with reasoning_mode: :enabled, provider_options: [reasoning_summary: :auto].
An authorized C7 resume can carry a reasoning message at the end of its wire history.
Phoenix recipe
The visible history of a stream-guarded conversation requires accepted rows. Older stream-only snapshots may have assistant rows without that evidence. History pages
Expose paused input at the chat boundary
Use chat.deferrals to distinguish :input, :external and :timer. Pending
entries in :approval_requested still identify a deferral with
kind: :deferred. Read the new deferral_kind to choose the UI. Existing
events without that field use the generic deferral status. AG-UI clients
can handle the input_required interrupt and exagent.input event.
Fetch form details from an authorized Server.pending/1 read.
Use Chat.AGUI.headers/0 and sse/1 for SSE and
Chat.AGUI.Input.decode/2 after authenticating a request. Bind the request
to the host's attempt and full C7 inbox. Send one answer per item the
client can resolve. Timers and host-owned external deferrals can remain
pending while the Server commits those answers. Apply the commands
through the Server with the host authorizer. Frontend tools require
explicit host declarations. Phoenix recipe
Update the generated form controls in existing Phoenix apps to present
the result of Chat.InputForm.present/2 and validate submissions with
Chat.InputForm.responses/3. Commit the supply and any Oban resume job in
one transaction. Runs without a Store can opt in to
:on_input.
Resolve pauses in delegated Frame3 runs
Keep using Server.pending/1, Server.decide/4 and
Server.supply_result/4 on the root Server. For a delegated item, resolve
:definition to the requesting agent to validate edited arguments, present
an MCP input form or supply a result with its tool. The candidate
:delegation_path lists the parent call and child identity for each hop.
Use the authorization target's path to apply your policy to the stored
destination. Recovery's :wake_timer target also uses the child's
:definition and :policy. Resume using the root reference returned by
the last decision. Resuming a bound delegation checks the current
permissions, approval and child call binding before the child advances.
Revoking the delegation closes the attempt with :execution_uncertain
when the child is unfinished.
Chat deferral summaries carry the path for delegated calls. AG-UI native
interrupts add metadata.exagent.delegationPath and
metadata.exagent.messageId. The same activity ID is used when that child
resumes in a new AG-UI attempt. Pass child_events: :all on the turn and
on resume to receive live child activity.
This rollout applies between unpublished 3.0-dev builds. The Store still accepts level-1 records on both builds. An older owner can claim a new record and present a child's deferral with the root definition and policy, without its delegation path. Upgrade all owners, Recovery processes and resume workers sharing the Store before serving traffic on the updated build. Settle delegated deferrals before rolling back.
MCP tools that negotiate Tasks on an input-capable connection automatically use deferred mode inside a durable Frame3 delegate. The root run can pause as soon as the upgraded runtime calls one of these tools.
Schedule durable timer deferrals
Return {:defer, meta, kind: :timer, wake_at: utc_ms} from a Frame3 tool
declared with requires_deferral: true. The timestamp is absolute
UTC in milliseconds. Either keyword order is accepted. For PostgreSQL,
apply unified migration 1
before running a deferral-capable tool. A missing or invalid
index returns {:store_migration_required, 7} before the callable can run.
Timers use Store write level 1.
The parent of a durable delegate receives the child's exact bounded rejection
cause when the journal confirms that the child tool was refused before
dispatch and the subtree has settled its effects and deferrals. Handle
{:store_migration_required, 7} in RunError.reason by applying the unified
migration or restoring the timer index. For :execution_uncertain, inspect
the journal for effects to reconcile and deferrals that still need a result.
Stop timer writers and settle open waits before rolling back to version 0.
The downgrade refuses while any enrolled table has pending timers. Let
Recovery settle due waits or cancel runs whose waits can be abandoned.
If the index is removed outside the unified migration while timers remain,
the sweep reports SQL 7 in its :issues and Doctor marks store.recovery
missing with --check-recovery. Restore the SQL 7 index for the affected
table to process the waits.
Recovery and reconciliation also require the index before they can
publish a timer from an interrupted tool batch.
Use Continuation.pending/2 and supply_result/4 for an early signal. The
Store accepts a new result only before :wake_at and can replay a receipt
after the timestamp. Once due, an open timer returns {:error, :timer_due}
to a new supplier. Timer calls reject {:input, responses} with
{:error, {:invalid_result, :input_not_supported}}.
Configure Recovery
for the namespace and authorize :wake_timer for its actor. The timer's
CAS supplies a local :not_executed result. Authorize :resume separately
to pass the ready revision to :on_ready. Later sweeps can deliver that same
revision while it remains ready. Deduplicate by continuation reference.
Durable Jobs retain the same Oban delivery, expose the next time as Job.retry_at and
settle the timer on redelivery.
Use deferral_kind: :timer and :wake_at for a passive Chat status. AG-UI
projects timer_wait and exagent.timer with wakeAt for display. Leave
timer IDs out of client resume entries. Early signals go through the
authorized host. Retention.inventory/2 includes open deferrals. Erasure
removes local waits with the journal.
Enable scheduled follow-ups
Apply unified migration 1 on the conversation Repo. Then add
Tool.FollowUp.tools/2 to the durable conversation definition and enable
follow_ups: on Recovery. Give the system actor permission to deliver to the
target conversation. Integration steps
The generated chat can use Tool.FollowUp.tools(Agents.store(namespace), opts)
in agent/1, including its auxiliary agent(nil) call. The same catalogue
references work across scope. A live execution needs the scoped Store.
Generated chat
At Store write level 1, job_notice_v1 carries an optional follow-up topic.
Before rolling back to version 0, stop scheduling and delivery and settle or cancel pending
follow-ups. The migration checks that the table is empty before dropping it.
Job notice turns require allow_chaining: true to schedule additional
follow-ups. A consumed follow-up that fails before dispatch settles as a
failed turn. Follow the host recovery path
if the failed turn has an unconfirmed effect.
Configure provider pricing options
Set :service_tier on ExAgent.Models.ReqLLM.new/1 for OpenAI. For models
supporting the cache policy, use prompt_cache: [ttl: "30m"] in Chat
Completions or Responses. Responses also supports [ttl: "12h"]. A
cache key can accompany the TTL. These options are outside the
continuation binding.
Use ExAgent.Message.Usage.service_tier/1 to read the returned tier.
History records the tier in accounting["service_tier"] when available.
The accessor returns nil when the recorded usage lacks that information.
When a tariff is unresolved,
accounting["cost"]["availability"] is "partial" and both monetary
amounts may be nil. The spend hold then remains available for reconciliation.
To export the draft gen_ai.response.service_tier on model spans, pass
service_tier: true to ExAgent.Observability.OpenTelemetry.new/1.
Remove any explicit Anthropic version other than "2023-06-01".
Anthropic's 2026-10-21 revision returns HTTP 400 for sampling parameters.
For embedding token pricing, set :price_per_token_cents on an embedding
call or tool config. It prices the reported input tokens. A missing token
count leaves the tariff unapplied.
Anthropic API migration
Maintainers can run the Responses Background contract with
bin/check-req-llm-main.
ReqLLM compatibility canary
Check Flex eligibility and EU service tiers
LLMDB 2026.11.6 supplies the model and API eligibility for OpenAI Flex.
Remove service_tier: :flex (or "flex") from adapters without a matching
catalogue entry, or select a Flex-capable model. An ineligible selection raises
ArgumentError at construction. A request that reaches preflight with that
selection returns %ExAgent.RequestError{reason: {:invalid_option, :service_tier}}
before dispatch. Changing only the tier preserves the C7 binding.
Flex with fallback to Standard
Doctor shows model.lifecycle for retired or scheduled models represented in
the installed catalogue. To see the candidate model.service_tier_retirement
row for affected OpenAI models in the EU, pass
--service-tier priority --base-url https://eu.api.openai.com/v1 or add
service_tier: and base_url: to the host's :exagent_doctor configuration.
Doctor also recognizes the effective ReqLLM endpoint when base_url: is
omitted. For GPT-5.2, GPT-5.4 and GPT-5.4 mini in the EU, use
service_tier: :default before January 11, 2027, or qualify GPT-6.2.
OpenAI API deprecations
Declare closed tools explicitly
With ReqLLM, the default Tool.new/1 parameter schema (%{}) accepts any
JSON object inside the required arguments envelope. To reject additional
keys on a zero-argument tool, use
%{type: "object", properties: %{}, additionalProperties: false} as its
:parameters_json_schema.
Adopt argument-based permission rules
Existing {tool_glob, action} rules and Permissions.decide/2 still work.
Add args: %{key => glob} to match validated text fields. Use
Permissions.decide/3 when checking a call with arguments.
C7 persists the argument-based permission floor and the approval's winning
rule reference when there is one. Match permission_rule as an optional
field in review and event consumers.
Argument rules
Use structured permission comparators
In Permissions.new!/1, replace a shell, endpoint or directory glob with
{:command, argv_prefix}, {:url, http_prefix} or {:path, directory}.
Use default: :deny for an allowlist. Match commands with a literal word
prefix and send absolute paths to file tools. URL and path lists require all
members for allow or approval and match a denial on any member. A supplied
malformed comparator value denies the call.
When the BEAM cannot load IDNA, constructing a URL rule with a DNS or IPv4
host raises ArgumentError with the dependency to add, {:idna, "~> 8.0"}.
C7 policy version 2 carries both argument globs and canonical comparators. Name-only rules use the published policy layout. Approval records bind the winning rule's reference. Catalog fingerprints include the canonical predicates. Keep any old definitions available while their open records still require them. Argument rules
Validate ReqLLM maintenance at startup
Invalid ExAgent.Observability.ReqLLM.Maintenance.start_link/1 options raise
ArgumentError. Remove any branches handling
{:error, :invalid_maintenance_configuration}. Supply :ttl_ms and
:interval_ms. To register a worker under a different local atom, pass
:name. stats/0 reads the default registration.
Tracking maintenance
Fork and regenerate conversations
Replace manual history slicing for retries and edits with
Conversations.fork/3 and Server.regenerate/2. The application supplies a
fresh ID in the same namespace and authorizes both identities. Keep
send_message/3's existing :message_history option for explicit context
replacement within one conversation. That option uses the conversation's
current identity, usage and journal.
The built-in Store uses the existing PostgreSQL schema and format level 1. Update every runtime that accesses the Store before enabling forks. On a generated LiveView app, copy the regeneration handler and controls into the host-owned templates. Check the app's prompt policy and row registration hooks. Runtime guide · AI SDK transport
For hosts adopting the 3.0 development API, update pattern matches on
Server.regeneration_target/1,2. Wait for persistence on
:checkpoint_pending or for the run to finish on :busy. An approval
pause returns :open_effects when it affects the selected turn. Use the
normal approval and continuation flow to settle that turn. Reserve
:turn_not_closed for a stored turn without a settled terminal.
An explicit :at pointing to the active run also returns :busy.
Match :turn_not_found from either call for a missing turn, including
regenerate/2 on an empty source where it previously returned :not_found.
The target read now requires a scoped Store backed by supervised ETS or
PostgreSQL. Use
Server.history/1 to read the messages of an in-memory owner.
For inventory or erasure, authorize access to the linked conversations
and their dependent stores. Retention.inventory/2 can return
{:conversation, id} for each retained member. Retention.erase/3 applies
to that group when called with any member ID.
Erase a conversation by subject
Expose ExAgent.Retention.erase/3 to an authorized operator
using the subject's scoped Store.
The generation and optional expiry are written in the existing PostgreSQL
data column. Readers still accept the earlier phase-only tombstones.
{:ok, receipt} =
ExAgent.Retention.erase(store, conversation_id,
owners: remote_owner_pids,
memory: [{memory_descriptor, memory_scope}],
result_store: [{result_store_descriptor, run_id}],
jobs: [{{ExAgent.Jobs.Durable, job_handle}, job_id}],
eval: [{{ExAgent.Eval.Online.Durable, {eval_job_handle, "judge", "v1"}}, run_id}]
)
receipt[:journal]
receipt[:follow_ups]
receipt[:provider_copies]Replace receipt map matches with keyword access or a pattern on
Keyword.take(receipt, keys). The order is :snapshot, :journal,
:admission_receipts, :event_buffer, :jobs, :follow_ups, :memory,
:result_store, :eval, :provider_copies and :tombstone.
Targets within each associated store follow input order.
The candidate :follow_ups entry lists the pending IDs deleted by the
confirmed fence in this call. The :jobs outcomes correspond to the host's
:jobs option.
Custom Stores implementing candidate Store.retention_subject/3 now receive
{namespace, kind, id}. Update that callback along with application callers.
Use kind: :session for a scoped Session snapshot, kind: :composition
or kind: :flow for a durable workflow, and the default :agent for an
agent. With a workflow pass its continuation ID. A Session binding can
reference a separately owned agent continuation. Authorize that agent's
erasure independently. The framework finds local Servers and Sessions.
Pass known remote owners. A fenced subject rejects new work with
:subject_erased, which can appear inside
{:continuation_checkpoint_failed, :subject_erased}.
Read retained IDs before erasing with
ExAgent.Retention.inventory(store, id: conversation_id, limit: 50).
Pass :kind and the preceding page's :after cursor on subsequent
calls. Restart from the first page if the inventory changed.
Use the retained {:run, id}, {:job, id} and {:result, ref} rows
to build exact mappings to authorized handles. Compacted history and pruned
journal entries can remove references. The host supplies any missing IDs and
exact memory scopes. Quiesce other writers, including online evaluation
collectors, before deleting their data. Copies already sent to an evaluator's
exporter follow that exporter's retention policy.
Each provider row has the form
{{:retained, :provider_copy}, %{provider: "anthropic", kind: :file, id: file_id}}.
The inventory discovers hosted file references and saved response IDs with
explicit storage evidence. Supply known external references in
:provider_copies with kind: :file or :response. Save the retained
IDs from the page or receipt and use the provider's deletion endpoint
after the relevant work settles. A lost erase acknowledgement can
leave the provider inventory unconfirmed. Configure files_api: true
or stored_responses: true under :exagent_doctor to see the relevant
default-retention warning. Anthropic Files lifecycle ·
OpenAI data controls
Reconcile retained effects and retry with the same mappings. The default
tombstone is permanent. An optional :tombstone_ttl of 1 to 4,294,967,295
milliseconds starts at confirmed local cleanup. Pending work or a retained
target keeps the fence. A retry cannot shorten a seal. Use a finite TTL
only when all earlier deliveries have a bounded lifetime, and allocate a
fresh ID if deliveries can outlast it.
Recovery.sweep/2 includes :issues when it encounters a PostgreSQL lease
whose root is missing or outside a claim. These rows count as rejected and
the worker continues through the page. A sweep and Doctor
--check-recovery report the physical key. Check the owning record and its
evidence before repairing the projection. The host can partition its
authorized namespace lists across recovery workers to reduce duplicate
authorization checks.
Read Doctor's catalogue and redirect checks
The optional model.catalogue and model.provider_redirect rows appear in
text and JSON schema version 1. Set :catalogue_max_age_days in
:exagent_doctor or pass --catalogue-max-age-days. The default is 30 days.
Use the provider's replacement model ID explicitly after qualifying it.
ReqLLM compatibility canary
Apply the wave 28 QA fixes
- Handle
{:retained, :open_external_deferral}in subject erasure receipts. The journal, snapshot, turn receipts and supported dependent stores stay available. The receipt reports this reason while the subject stays sealed. Supply the result or cancel and reconcile the task under the sealed tombstone. Repeat erasure with the same mappings. Confirmed fatal tool errors can now return a journal at:failedwith its lease released. Keep recovery for unconfirmed effects. - Budget five SQL statements per warm PostgreSQL renewal of a scoped agent, excluding transaction boundaries. The statement that locks the retention marker shares the renewal transaction. Renewal measurements
- Handle
{:error, {:permission_rule_changed, %{permission_rule: rule}}}when applying a reviewer edit. A rejected edit leaves the original request pending. Approve or deny that call, or obtain a new submission under the effective rule. Reviewers can read the trusted:permission_ruleon the authorizer target for valid decisions. Existing receipts still replay. - Pass the current
catalog:to bothJudge.Approval.review/3andcommit/3. A Server uses its configured catalogue for decisions. Keep:catalogon Servers reopening adopted conversations. A missing catalogue gives{:restore_failed, {:adopted_definition_requires, :catalog}}. - Embedding, rerank and Media tools use normalized or unavailable token
evidence. Under strict token limits their admission fails before provider
IO with
{:accounting_unavailable, dimension, :normalized_only}as the tool error cause. Use a finite request limit withaccounting: :estimatedfor runs that accept qualified subtotals. - Move MCP credentials to
:headers_providerto use Mint directly. Finch subscribers can still see static headers in native request events. The request stop event now contains an opaque accumulator reference in the returned tuple. HTTP transport and credentials
Apply the wave 26 adoption fixes
- Refresh generated chat integrations. Forward the chat module's optional
run_options/2andadmit_prompt/3hooks throughAgents. The defaults are[]and:ok. Pass the host options toServer.send_message/3andServer.resume/3as the new templates do. Resolve dependencies from trusted host state on both paths. - A durable Server whose worker reports failure can now close the turn as
:failedwhen its active effects are settled. The failed turn stays out of reusable history and the owner can admit again. These terminal records are part of the Store format level 1 baseline. - Remove CodeMode from durable Server definitions before startup. Live
programs can bind nested arguments. Tool error notices name the step,
and a failed batch can carry
RunError.confirmed_program_steps. Doctor now fails the requiredjson.jason_decimalcheck if Jason lacks Decimal support. Recompile Jason in the affected environment. - Use an authorized Ash lookup in
reconcile:and persist the C7 idempotency key from the action context with the outcome. Handle:no_reconcilerwhen a write has no declared lookup. - Match
:spend_budget_policy_mismatchfor accounts accessed with an old ceiling or different window. UseBudget.Postgres.update_limits/2to change an existing ceiling. Reads and settlements of earlier holds remain available with the old handle. The existing SQL schema applies. - Pass an explicit
:inputprojector for:tool_inputand:tool_outputclassifier guards. Construction rejects these guards without it. Use the:streamclassifier guard with a projector in live agents. For a durable chat, run the classifier in the host's admission hook or as a declared tool. C7 still rejects inline classifier guards. - Accept redacted observed output in cases captured from trusted C7
diagnostics. The accepted display text is used for guarded output.
Use
ExAgent.Case.to_map/1andfrom_map/1for portable case JSON and provide host run options separately. - Pass
--yesfor non-interactive installation. The chat guide describes a rolling drain and stream reconnect with stable admission keys. Phoenix chat integration
Apply the wave 25 QA fixes
- When resuming a guarded root continuation, handle
:streamand:outputfailures from a reconciled answer as terminal guardrail failures. Treat the reconciliation receipt as evidence of the provider response. In Store renewal consumers, handle:stale_ownerfor a superseded epoch and:lease_expiredfor the current expired epoch. - Render
chat.failurefor the last failed turn on the current owner. Chat status can be:failedwhen that owner is idle. For an immediate prompt row, render the locally submitted text under the admission run ID. Deduplicate transient AI SDK commentary by itsidwhen accumulatingonDataacross a full replay. Use the headers returned byChat.AISDK.headers/0. - Match
{:usage_limit_exceeded, :requests, count}for the live request threshold. The struct field and durable admission error'slimitvalue still userequest_limit. Useaccounting: :estimatedin an additional limits struct when the applicable policies should stay estimated. For a stream fragment overflow readchunks. Byte limits still reportbytes. - Read non-token measurements from
usage.units. A units-only report now projects as:partial. A zero duration exposed by stock ReqLLM produces a normalized zero in milliseconds. Readcost_statusindependently. Buffered speech finalizes open WAV lengths before delivering the bytes. - Include classifier guard and tool inference when sizing a shared
spend_budget. A denial can stop the classifier before dispatch. For Eval CI, give--baseline,--saveand--outputdistinct files. Symlinks and hard links to the baseline count as the same file.
Apply the wave 26 QA fixes
- For unsupported delegate guardrails, handle
{:unsupported, {:guardrail, stage, :agent_continuation_delegate}}at C7 admission. A builder that returns such a delegate leaves a confirmed:not_executedtool result. When a heap-capped write is killed with its intent still open, handle:uncertainas soon as the run returns. - A C7 model retry needs another request slot at each ancestor. Handle
{:usage_limit_exceeded, :requests, count}fromretry_effect/4. A WrapUp request can consume the final slot. Usereconcile_model/5with confirmed provider evidence, and size child headroom for parent requests. Closing requests - Prefix-bound ReqLLM models send JSON tool results in lexical key order.
Saved histories still load. An older reasoning fingerprint may reset once
if it committed a different order. Reconcile outstanding model requests
with structured tool results before upgrading across this change. Earlier
captures lack wire-order evidence and reject an idempotent retry with
:retry_model_request_changed. - Code calling
Compaction.Summary.compact/3directly should handle{:no_change, :protected_prefix}. The matching telemetry keepsstatus: :no_changeand addsskip_reason: :protected_prefix. - Allow a request slot for each admitted live
Classifier.tool/2inference. Its usage is in the execution scope's total. In C7, an unreported classifier charge stays unknown after reconciling the label. A tool can now return{:unknown, reason, usage}to retain usage evidence for an unconfirmed outcome. Check coverage when displaying measured subtotals. Classifiers - Treat
:missing_exagent_jobs_tableand:jobs_migration_requiredas configuration failures in Broadway consumers. Apply the migration before redriving deliveries. Accept the new optional warning states in Doctor's JSON v1. Doctor warnings
Adopt decision classifiers
Use Classifier.new/1 with a stock Decisions or Nx Serving adapter when
the application needs one label from a fixed list. Optional entry points
cover live guardrails, Eval grading and routing a Flow from an already
confirmed label. Add Classifier.tool/2 to a versioned definition for
calls that need C7 accounting and effect receipts. Keep the classifier
policy and adapter identity bound to that definition while runs are open.
Declare Nx in the application's dependencies before constructing
Classifier.NxServing. The adapter accepts ~> 0.5 or ~> 1.0 and raises
ArgumentError when Nx is missing. Other classifier adapters compile and run
without Nx.
Decision classifiers
Review answers and persisted approvals with a classifier
Existing Judge constructors still accept :model and their text policy.
To switch to a decision model, put the policy in the classifier's instructions
and its "allow", "deny" and optional "ask" label descriptions. Pass
classifier: classifier as the review source. The output validator uses
the live scope's request budget and usage ledger.
For a C7 approval, have a trusted host worker read the pending request, then
call Judge.Approval.review/3 and commit/3. Authorize the new :review
operation for the reviewer actor and keep the review for an acknowledgement
retry. The Store uses the existing decision schema. Give the reviewer policy
a new version when its configuration changes.
Automatic review
Close before a run limit
Add UsageLimits.WrapUp.new/1 at the end of the capability list. Keep the
hard UsageLimits and deadline. Choose headroom for the smallest complete
answer the application can use. Read UsageLimits.WrapUp.reason/1 on a
closing result or subscribe to its telemetry event.
Closing request
Set tool heap thresholds and adopt code mode
Set max_heap_bytes on tools whose task heap needs its own threshold.
It defaults to the VM policy. Resumed tool calls take the threshold from
their current definition. An unconfirmed task exit after dispatch still
requires the same effect recovery as any other interrupted tool.
Use ExAgent.Tool.CodeMode on live definitions to let the model chain
directly offered JSON tools in one call. Use ordinary calls for steps
that require a persisted approval or deferral. A program that exceeds
the binding buffer fails with boundary: :tool_program. Return smaller
values or references from intermediate tools that feed later bindings.
The nested step events expose the optional program_call_ref,
program_step and effect fields for grouping. Tool program controls ·
Persisted chain
Rehearse before cutover
Use scripted models and fixture tools. Work through the same boundaries the application will use after the switch.
- Update explicit model finishes. Run the host tests with the new admission receipt, Event v2 and telemetry patterns.
- Check Job waits, notices and listings. Exercise structured MCP results and Eval report consumers in CI.
- Restore a copy of the Store. Compare
Server.history_page(server, projection: :chat)with the authorizedServer.history/1before the switch. The chat page can hide assistant rows from older snapshots even when private history restores. Preserve accepted finals the application must display. - Apply PostgreSQL headers and segments if used. Run Doctor against the descriptors each replica will use.
- Simulate a lost reply and restart the Server. Check receipt recovery against the actual Store.
- Drain an Oban job queued by 2.3 against a restored approval. Redeliver it and verify the effect count stays the same.
For PostgreSQL continuations and keyed admission, apply the unified migration to the Repo and rebuild headers for existing runs. Repeat the rehearsal with the active write level before finalizing a higher one. Store rollout
Consume assistant narration separately
For OpenAI Responses, read answer text with Message.Response.text/1.
Hosts that concatenate Part.Text directly can filter on phase, keeping
nil and :final_answer. Consume :commentary_delta separately for progress.
The generated LiveView draft and history page use answer text. Stock
annotations in an answer with narration are omitted because ReqLLM 1.31
flattens their source parts.
A completed narration-only response spends one model step and follows the existing deadline, usage and step limits. It spends no output retry. C7 restores the saved phase at a pending response and advances from confirmed history. The optional JSON field uses the existing Store schema. Histories and cassette entries without that field retain their original interpretation, including old provider metadata. Re-record a cassette to capture phase-aware terminals and deltas. Phase and streaming details
Register per-tenant limiters
Applications can use {:via, Registry, {registry, tenant_id}} in the
limiter child specification and in the agent's :rate_limiter option.
Existing registered atoms continue to work. A local PID targets one owner.
For an unfinished persisted handoff, retain its configured limiter reference.
Use a stable registered name when the handoff must reopen after process
replacement. Per-tenant quotas
Share provider quotas in PostgreSQL
Apply the unified migration
on the Repo and search path shared by all participants.
Admission and Doctor validate the quota tables, columns, indexes and
settled definition.
If unified version 1 is already recorded and the quota schema needs repair
after {:rate_limiter_migration_required, 1}, use the deprecated
ExAgent.RateLimiter.Postgres.migration_sql(:up, version: 1) statements in
a locked host migration. They rebuild missing schema objects and restore
settled NOT NULL DEFAULT false. Existing null values become unsettled.
Check the same Repo using Doctor's :quota_repo setting and --check-quota.
An unconfirmed reset still requires reconciliation.
Upgrade participating limiters before applying a repair. When charged_until
is lost, it is restored to the surviving retention deadline. Missing estimates
without a surviving token count and lost settlement counts hold TPM while the
charges are live. A surviving unknown usage marker keeps the estimate when
available. A lost bucket has no recoverable attribution.
The repair retains its rows under surrogate keys and holds admission across
the quota tables until that evidence expires. A lost cooldown deadline
defaults to infinity. Use trusted backup data or reconcile that cooldown
before clearing it.
Other versions, a missing version and unsupported directions raise
ArgumentError in migration_sql/2.
For each account, drain local traffic and let its rolling charges and
cooldowns expire before switching admission to shared mode. Start every
participating limiter with the same database scope, keys and limits.
Keep existing atom or Registry references on agent definitions and durable
handoffs. Existing local limiter configurations continue to use FIFO queues.
The quota tables leave continuation records in their existing format.
Drain shared traffic before schema rollback. The historical quota down
migration deletes the quota evidence and cooldowns.
To observe background settlement retries, subscribe to
[:exagent, :rate_limiter, :settlement_retry]. Custom adapters must make
settle/5 idempotent for repeated reports with the same attempt ID.
Configuration
Route Fallback around quota refusals
Set fallback_on_quota_denial: true when building a Fallback group to
continue after a confirmed local or shared refusal. Opted-in leaves check
immediate local capacity even without a run deadline. Keep the default
policy for FIFO waiting and a stop at the first refusal. An initial refusal
from every compatible leaf reports the shortest certified delay in
{:rate_limited, key, wait}. The key can identify a backup. Handle
:unknown when immediate local admission lacks a delay estimate.
Eligible durable Jobs defer using a schedulable wait. A held claim with
an unknown wait records wait_ms: "unknown" and a null retry_at in the
existing diagnostic in the Store format level 1 baseline.
Fallback quota configuration
Emit explicit model finishes
Supply finish_reason: :stop or :tool_calls when returning a complete
Message.Response from ExAgent.Model.request/4 or request_stream/4.
Supply the same evidence to Continuation.reconcile_model/5. Both values
admit the response. The parts determine whether to dispatch tools or return
text, including tool calls with :stop and text with :tool_calls.
A capability returning {:skip, response} or {:recover, response} supplies
:stop.
A model's nil or :cancelled finish now returns a failed run with
{:incomplete_response, finish}. Read bounded diagnostics from
partial.pending_response and qualified usage from partial.usage.
Models.Test supplies complete finishes for strings and
{:tool_calls, calls}. Change explicit tool-call responses in scripts.
| 2.x script | 3.0 script |
|---|---|
Message.new_response([call]) | Message.new_response([call], finish_reason: :tool_calls) |
Buffered and streaming example
Re-record cassettes that lack finish evidence. A replay supplies a new reply.
Old snapshots and confirmed C7 history still load with nil finishes.
Model terminal contract
Replay exact stream sequences
Cassette entries recorded without exact events synthesize deltas from the terminal.
To test exact chunks or argument previews, use :record with a streamed
target and stream_events: :verbatim or a unary event redactor. Use an event
redactor when the recording also uses :redact_response. Eval accepts the
same option under :fixtures.
:record_missing retains the recorded payload of existing hits. Use
:record to capture those streams or apply a new redaction policy to all
the entries. C7 continues to confirm the validated terminal through the
existing Store format. Testing guide
Use stable cassette paths
Cassette v1 records a path and a 1-based ordinal for each request fingerprint on the path. Flow and Composition derive the path from the workflow ID, version and step ID. Keep those declarations stable to reuse the recordings. Keep the same open fixture through a pause and resume.
Use Fixture.with_label(fixture, "left") and other distinct labels for
independent roots with identical requests. Pass the same labels when
recording and replaying. For workflows pass the view under :root_options.
In a tool, get the inherited fixture with RunContext.fixture/1 and use
labeled views to add segments to child paths. Re-record cases where you
introduce child labels with :record or mix exagent.eval --record.
Testing guide
Correlate tool invocations
Use the full opaque call_ref to correlate tool events, reviews, deferrals,
handoffs, telemetry, OTel spans, Eval tool evidence and dashboard rows. Each
model request of a run has its own references, even when a provider reuses
a call ID. The same invocation keeps its reference across C7 resume and
reviewer edits.
Current references start with call_v2_. Refresh cached review items after
upgrading from a candidate with call_ references. C7 derives the current
reference from the stored request or its journal binding. If the journal
lacks this evidence, it projects the old call_ reference, which can be
shared by calls in separate requests. Previously exported references retain
their original values. Provider IDs, effect IDs and decision receipts keep
their formats and roles.
Declare tool effects and recover by key
Use effect: :read for a tool that only queries data. Existing declarations
default to :write. A context-aware write can provide reconcile: fn key -> … end
to look up the external receipt. In agent runs, the tool receives
ctx.call_ref and ctx.idempotency_key on its first dispatch. Applications
that used a nil key to detect a first dispatch should remove that check.
Use the stable key for both dispatch and lookup.
After recovering an expired claim, use Continuation.retry_effect/4 with the
read binding from get/2, or Continuation.reconcile_tool/4 with the
write's ID and bound tool. Both require host authorization. A manual write
retry still requires accept_duplicate_risk: true. Omit the key to reuse the
recorded key. Supply one when a historical attempt lacks it. If you pass a key
explicitly, it must match the recorded key.
Earlier descriptors and intents restore as writes. Keep historical definitions available to complete existing approvals. The Store format level 1 baseline includes the effect descriptors and intents. For tools imported from MCP, review the server's read classification before granting a retry. Recovery guide
Read typed citations
Use ExAgent.Message.Response.citations/1 instead of provider citation keys
in text-part metadata for the supported citation profiles. Use
ExAgent.Result.citations/1 or the optional payload.citations of
:run_finished when highlighting accepted output. Source references can be
present with a nil answer range, including stock Responses annotations.
Successful runs record the effective output_mode. Highlight only the ranges
returned by Result.citations/1, which checks for an unchanged text completion.
A cassette response redactor receives citation references with excerpts and
ranges cleared. Return safe replacements explicitly. Re-record pre-release
cassettes with inherited excerpts or stock Responses answer ranges.
Histories without the optional citations
array restore with an empty list. Preserve the optional field in custom history
consumers and use ExAgent.Event.strip_content/1 for exports. Citation contract
Recover a turn admission
Use Server.chat/3 to await the result. For a recoverable idle-only admission,
replace candidate uses of Server.chat/3 with idempotency_key: by
Server.send_message/3 with idempotency_key: and queue: false. This mode
preserves the earlier chat fingerprint. A supplied :timeout now bounds
only the admission wait in this mode.
Mint one key per logical turn. Call Server.new_admission_key() for 15 minutes
or Server.new_admission_key(60_000) for one minute. The argument of /1 is
an integer TTL in milliseconds in 1..4_294_967_295. Save the original
{expiry, nonce} pair, input and run options before dispatch. If the host
supplies a :request_id, save and reuse it too. When the option is omitted,
the Server derives the request ID from the key.
alias ExAgent.Server
key = Server.new_admission_key()
# Save the key with the input before submitting.
Server.send_message(server, prompt, idempotency_key: key, queue: false)For every send_message/3 and steer/3 success, match
{:ok, %{request_id: request_id, run_id: run_id, status: :admitted}}.
On {:error, {:delivery_unconfirmed, request_id}}, use Server.receipt/2
with the original key. Follow both IDs from a found receipt. The receipt
confirms admission, and the run may still need reconciliation. A resend uses
the original key, input, mode and options and is subject to :max_input_bytes.
- Snapshot-only or no Store. Receipts live in the current Server. A
snapshot can restore history even when
Server.receipt/2now returns{:error, :receipt_not_durable}. After owner loss, the same key can produce the same request ID with a new run ID and execute the turn again. Keep admission blocked until host or external evidence resolves the first attempt. Apply the same rule to an earlier candidate's:not_foundreply. - Persisted continuations (C7). Configure
:continuationand keep the same scoped atomic Store across owner replacement. Back up and restore itsadmission:rows in PostgreSQL. An ETS Store must keep its table owner. Only a retained Store can return an authoritative:not_foundfor a live key. A prior submission can still be in flight. When you retry against that Store, its atomic claim resolves the race. A custom atomic Store without turn admission returns{:error, {:unsupported, :turn_admission}}. Enabling C7 selects the continuation record as the restore source. Plan the history transition separately for existing standalone snapshots.
Count live Jobs notice keys alongside user keys within the default
256-receipt capacity. Jobs keys retain their original expiries. Query the
destination receipt before reconciling an uncertain notice. Hand-built Jobs
snapshots with no finish timestamp retain unkeyed delivery. New receipts
reject manual expiries over 4,381,367,295 milliseconds ahead of the admission
clock with {:error, :idempotency_expiry_out_of_range}. C7 uses the Store
clock. A custom Store must commit the watermark and pruning before confirming
expiry. Existing journals restore with their recorded expiries.
Follow run_id on the queued and cancellation events of all async turns, using
the run ID from the admission receipt.
Runtime contract and example
Set OTP control timeouts
Pass timeout: in milliseconds to Server.send_message/3, Server.steer/3,
Server.receipt/3 or RateLimiter.reset_cooldown/3. The default is 5,000 ms.
The caller can change it when retrying a keyed admission. The original
:deadline remains a run option and is part of the admission fingerprint.
For cooldown reset, handle {:error, :result_unconfirmed} when a dispatched
request loses its acknowledgement. {:error, :rate_limiter_unavailable}
indicates there was no reachable limiter before dispatch. Use
timeout: :infinity if the host needs the former indefinite reset wait.
Quota controls
Job queries, retry measurements and Mix arguments
| 2.x behavior or pattern | 3.0 adoption |
|---|---|
A live Jobs.wait/3 suppressed the configured notice. | The waiter receives the result and the notice still fires. Omit :notify or pass notify: nil for query-only delivery. For durable jobs, omit server/2 or return nil for that job. |
jobs = Jobs.list(jobs_server) | Match {:ok, jobs} and handle {:error, :unavailable}. |
A configured notice can start a chat turn even after another consumer has
read the result with wait/3 or wait_job.
- In
Jobs.tools/2replacemax_wait: 30withmax_wait_seconds: 30. For applications using an earlier 3.0 candidate, apply the same change toJobs.Durable.tools/2and switch fromDurable.job_status/2andDurable.wait_job/3toDurable.status/2andDurable.wait/3. Keep the millisecond timeout in direct Elixir calls and thesecondsargument to the model'swait_jobtool. - Replace
wait(jobs, id, 0)withstatus(jobs, id)in both backends. A wait requires a positive integer budget. Forjob_statusandwait_jobfailures, readcodefor the stable identifier,messagefor the diagnostic, andjob_idfor correlation. A confirmed job failure can carry its ownerrordiagnostic. Optional snapshot fields are omitted when unavailable. - Both backends return
{:ok, %ExAgent.Jobs.Job{}}fromstatus/2andwait/3. Existing map patterns and dot access still work. Replacejob[:status]withjob.status. Matchbackend: :durablefor the persisted:notificationreceipt orbackend: :volatilefor the timestamps. Convert the struct withMap.from_struct/1before passing it to a map-only encoder. UseJobs.Durable.wake/2for durable notice delivery andJobs.Durable.notification_key/2to look up its admission. - Durable Jobs use the Oban Repo's
exagent_snapshotstable for C7. Migrate it even when conversations use a custom table. Handle{:error, :missing_exagent_snapshots_table}from job reads and delivery. Once the table is available again, wake the same ID. Oban recipe - Read
measurements.delay_msin handlers for[:exagent, :model, :retry]. The numeric value is already milliseconds. Error counters classify public run failures such astool_requires_deferralunder their own reason. Include those series when comparing historical counts grouped underother. - Pass each ExAgent switch once to
mix exagent.eval,mix exagent.installandmix exagent.gen.live Chat. For example, replace--repeat 2 --repeat 4with--repeat 4if four attempts were intended. Eval exits with code 2 when a switch repeats, including opposite forms of the same boolean flag.
Operate tenant jobs and HTTP turns
- Stop relying on implicit
1/1tokens fromModels.Test. For tests that assert usage or cost, supplyusage: %ExAgent.Message.Usage{input_tokens: 1, output_tokens: 1}on the model. Script explicit responses when different requests need different usage. Existing response fixtures keep their recorded usage. - Read
usage,usage_status,cost_centsandcost_statusfromJobs.Job. A query tool returns the two statuses as strings and a null full price when unknown. Match individual report fields if you previously compared the entire tool response. - Configure
:jobs_repofor Doctor's--check-jobsand handle:missing_exagent_jobs_tableor:jobs_migration_requiredat submission. Submission checks the same table shape as Doctor before admitting the job. Apply unified ExAgent migration 1 on the same Repo. To recover after a node exits, use the Jobs runbook. - Reserve a tenant balance in the host and supply tighter
:usage_limitsto Server turn calls. Match the additional:namespacemetadata in run and model-request telemetry as needed. Exports before this change may have no key. Ledger and budget recipe - Use
Fallback.codec/1for new durable Fallback bindings. Use the same codec that wrote a retained continuation when restoring it. Keep its versioned binding until those records expire or are migrated. Fallback encoding errors can now report{:model_state_not_persistable, module}. - Match
{:output_retries_exhausted, errors}onRunError.reasonas before. For display, read the message, hint and bounded:output_failuredetails. JSV reports actionable validation errors without intermediary errors. - In Eval CI, use
--format junit --output eval-junit.xmlfor the artifact. Keep the report path distinct from--baselineand--save. Machine formats send startup and evaluation diagnostics to stderr. - Keep the established Elixir key tuple for stored receipts. Use
Server.encode_admission_key/1andServer.decode_admission_key/1for HTTP clients. HTTP and SSE recipe
Read qualified usage and tighten run limits
- Handle
usage_status: :unknownwhen a request has no credited counts, including TestModel's default and buffered OpenAI Chat replies withoutusage. For those OpenAI replies,usage.accounting["quality"]is"unknown"and both token counts are nil. Use:partialfor a measured subtotal and preserve explicit zeros. Telemetry uses nil for unknownusage_quality. Keep reading historical statuses as recorded. - Read
cost_centsindependently of usage coverage. When it is nil, keep any knownusage.accounting["cost"]["subtotal_cents"]. Request and attempt Telemetry carries such subtotals incost_subtotal_cents. - Read
payload.partialon a confirmed C7:server_request_cancelledfrom either owner. It includes the turn's confirmed request and tool counters. A missing model response keeps the full cost unknown. Older events can omit the partial. C7 and Eval report readers accept the existing formats. - Pass
usage_limits: %ExAgent.UsageLimits{...}to a direct run, stream, resume or Server turn. The lowest threshold applies across the invocation, agent and saved C7 policies. Strict accounting takes precedence. UseServer.resume(server, reference, opts)with the ready reference from the decision.
Enable a shared spend budget
- Apply the unified migration on the Repo for the PostgreSQL adapter. Select an authorized tenant account when building the agent. Use that account in the trusted definitions for C7 restore, including the durable Job resolver.
- Pass
ExAgent.UsageLimits.Budgetwith the candidate:spend_budgetoption on the definition. Replacereservation_microcentswithreservation_centsandlimit_microcentswithlimit_cents. Divide existing values by 1,000,000. Apply the same conversion to the amount passed toBudget.reconcile/3. Readheld_centsfromBudget.Postgres.pending/2. UseDecimalfor high-precision amounts that a float cannot represent. SQL rows andBudget.Adapterrequests and settlements keep their integer microcents. Keep the same tenant key and window to reuse the existing account. - Match
{:usage_limit_exceeded, :budget_cents, {:retry_after_ms, wait}}in place of{:spend_budget_exceeded, wait}. The per-run cap still reports the accumulated cents in the third position. Match{:accounting_unavailable, "cost", :budget_unavailable}in place of:spend_budget_unavailable, including errors from custom adapters. Job diagnostics expose"usage_limit_exceeded"withlimit: "budget_cents"andwait_ms, or"accounting_unavailable"withdimension: "cost"andcause: "budget_unavailable". The reader projects existing Job receipts into this vocabulary. - Pass the budget to direct Media calls with
:spend_budget. Media tools inherit the account. Set:price_per_unit_centsto price observed media usage. For a separately billed tool, set:reservation_centsand return pricedMessage.Usage. Keep per-run caps for retrospective limits. Budget setup
Read the spend ledger
Apply unified schema version 1 before deploying the PostgreSQL Budget
writer. Use mix exagent.upgrade and the host's Ecto migration command.
Reservations without labels appear with empty labels. Rollback to 0 requires
empty Budget tables when the unified migration created them.
Custom adapters can accept an optional :labels key on reserve requests.
Implement the optional Budget.Adapter.balance/2 callback to support
Budget.balance/2. Use partial? for pending holds and charged_cents: nil
when a partial balance has no positive subtotal.
Usage
Validate public values and export events
Use the same settings values in a keyword list, map or %ExAgent.ModelSettings{}.
Replace zero :max_tokens and zero timeouts before constructing or running an
agent. Integer sampling and penalty values remain valid.
Use Message.new_request/2 for user, system, retry and tool-return parts.
Use Message.new_response/2 for text, thinking and tool calls. Invalid parts
or portable fields now raise ArgumentError at construction. A typed image
tool return must be successful and pass the size and format checks even when
supplying an existing struct in :message_history. Update history readers
to handle the two public failure reasons:
case ExAgent.Message.from_json(bytes) do
{:ok, messages} -> {:ok, messages}
{:error, :invalid_json} -> {:error, "Unreadable JSON"}
{:error, :invalid_history} -> {:error, "Invalid conversation history"}
endGive Server.Snapshot.new/1 a UTF-8 string ID, a nonnegative revision, valid
history and usage, and JSON objects for metadata and optional provider state.
Read the returned metadata and provider state with string keys. Existing
published snapshots keep their version-specific readers.
Build events with a nonnegative sequence, valid v2 envelope fields and maps
for payload and metadata. Use a replay cursor only when Event.cursor/1
returns a string. Event.strip_content/2 exports the fields defined for
the type, including after JSON decoding. Keep application-specific payload
extensions on the private event. Use the exported qualified usage counters
for metrics. Free-form model tags in usage.details are omitted from
operator summaries and exported events.
Write a report with {:ok, map} = ExAgent.Eval.Report.to_map(report) and
Jason.encode!(map). Read the bytes with Jason.decode/1 and pass the
decoded map to ExAgent.Eval.Report.from_map/1. Replace the candidate's
Report.to_json/2 and Report.from_json/1 aliases with these map functions.
If your programmatic export needs previews or reasons, pass
include_content: true to to_map/2. The CLI uses --include-content.
Use UTF-8 binaries for text and thinking parts and a confirmed tool-return
status in manual histories. Each object key must have one JSON spelling.
Replace maps containing both :size and "size" before admission. The
history reader also checks repeated keys in persisted JSON.
Run-stop telemetry exposes qualified accounting and known numeric usage
details. Keep custom usage labels in the application's result. Export a
numeric or UTF-8 participant ID to correlate Session events externally.
Composite IDs export as nil. Checkpoint operations export as agent or
session. Report writers return {:error, :invalid_report} when the
selected schema rejects the projected fields.
Match malformed replies by reason atom: :invalid_store_return,
:invalid_memory_backend_result, :invalid_update_result,
:invalid_target_result, :invalid_model_result or :invalid_stream_event.
The last two appear inside RequestError. For generated Phoenix projects,
pass a discovered Ecto Repo to --repo and exactly one positional Chat
to mix exagent.gen.live.
Declare Ecto when using schemas
3.0 makes Ecto optional. If you use Ecto schemas for agent output or rely on
ExAgent to provide Ecto to your application, declare
{:ecto, "~> 3.14 and >= 3.14.3"} in your application's mix.exs and
recompile ExAgent. This includes agents exported through MCP and schemas
referenced by pending continuations. Text agents and JSON tools can omit Ecto.
PostgreSQL snapshot headers
Unified PostgreSQL migration 1 installs the projection used by
Store.list_agent_headers/2. Keep any existing migration for the
historical SQL 2 step available to replay.
SQL 2 builds a stored generated revision column and a partial B-tree over physical keys. Allow time and disk space for a locked table rewrite and index build. Existing snapshot bytes, revision values and database timestamps stay intact. The projection uses revision zero for an old snapshot with no revision field, excludes record envelopes and reports an unreadable header as a read error. Applying SQL 2 again is safe. Its historical rollback removes the derived objects and disables snapshot header reads. Standalone snapshot writes can use SQL 1. Unified migration
Probe the same scoped read before and after the DDL. Use the host's authorized
workspace and pass its Repo as repo_config (or {Repo, table: "my_snapshots"}
for a custom table).
store = ExAgent.Store.scoped({ExAgent.Store.Postgres, repo_config}, workspace)
ExAgent.Store.list_agent_headers(store, limit: 10)- Schema v1 returns
{:error, %Postgrex.Error{postgres: %{code: :undefined_column}}}for the missingsnapshot_revisioncolumn. Snapshot and continuation restores can already work at this point. - Schema v2 returns
{:ok, %{items: items, cursor: cursor}}on success. Each item has:agent_id,:revisionand:updated_at. For the next page passlimit: 10, after: cursorto the same scoped Store. A nil cursor ends the scan.
Use keyword options. An option map from an earlier 3.0 candidate raises
ArgumentError before querying the Repo. An invalid cursor returns
{:error, :invalid_scan}.
Set :exagent_doctor in the host application config. Pass the Store
descriptor used by the host, including its Repo and table.
config :my_app, :exagent_doctor,
store: {ExAgent.Store.Postgres, {MyApp.Repo, table: "my_snapshots"}}Run this from the host project with the Repo started by the application.
Use --model test for the offline schema probe.
mix run -e 'Mix.Tasks.Exagent.Doctor.run(["--json", "--check-store", "--model", "test"])'
Check for store.postgres with status ok. Doctor checks column read access,
including the version 2 projection, and the version 4 column and index.
Use the host conversation inventory for continuation-backed chats.
Optional PostgreSQL segments
The unified migration includes the SQL 3 segment columns and indexes. Both Store descriptors read inline records from 2.x and earlier 3.0 candidates as well as segmented rows.
Set store: {ExAgent.Store.Postgres, {MyApp.Repo, table: @table, segments: true}}
where the writer should use fragments. For durable Jobs, pass segments: true
to use ExAgent.Jobs.Durable. Put the segmented descriptor in the host's
:exagent_doctor configuration and repeat the
Doctor probe.
Doctor checks segment_parent text, segment_refs bigint[],
segment_digest bytea and the validated cascading foreign key to the
parent for the supplied segmented descriptor. Server, Session and durable
Jobs reject invalid descriptor options before starting with them.
The version 3 migration rejects preexisting segment columns with
other types. Correct an incompatible layout in a host migration before
enabling fragmented writes.
Use a disposable scope and have a segmented
writer call Store.save_agent_snapshot/2 with a probe of at least 8 KiB of
payload. Check that its root has nonempty segment_refs. Read the probe through each replica using
Store.load_agent_snapshot/2 and compare its contents. For a C7 table, use
a test continuation and read it with ExAgent.Continuation.get/3. Pass
diagnostics: true to compare the stored journal.
A successful write can convert a row to the writer's layout under the same root lock. A writer switching to inline removes its old references in the same transaction. Include the complete table in backup and restore. Before using the historical SQL 3 down migration, retire fragmented rows through their usual retention policy or rewrite them inline. The migration checks for remaining fragments under a table lock.
Use independent continuation deadlines
:lease_ms is now a renewable claim window for agent, Flow, Composition
and durable Jobs. Set :deadline or :deadline_at if you used the lease
to limit the wall-clock duration of an attempt. Use :active_time_limit_ms
to limit active time across attempts. The Store computes the lease horizon
and applies the earlier of :deadline_at and :expires_at on its own clock.
The writer counts down the granted time from send on its monotonic clock.
Lock waits and delayed acknowledgements consume that time.
Match :continuation_lease_expired and :continuation_lease_unconfirmed
in RunError.reason and use :recover_continuation_lease from RunError.hint.
Read the current claim and recover it once the Store's clock reaches its
persisted horizon. Keep explicit reconciliation of unconfirmed effects.
The bundled PostgreSQL Store uses a small lease row keyed to the journal.
This projection is part of the Store format level 1 baseline. Earlier
records and data-only claim tokens with an absolute lease_until keep
their original horizons and replay rules.
A custom Store that implements the internal C7 interface applies
Continuation.Transition.apply_encoded/5 under its clock and write
boundary. New claims carry a relative "lease_ms". Fresh relative
claims and renewals confirm %{lease_until: timestamp, lease_remaining_ms: ms}
from the same Store clock sample. Renewals keep the semantic revision and
receipts. A replayed claim confirms its original receipt.
For renewal, return {:error, :unavailable} only when the Store can confirm
that no renewal committed. The writer retries that rejection before the
last confirmed horizon. Preserve a distinct error for an ambiguous commit.
Use Server.abort/2 after the Store's clock reaches the persisted horizon
to close an interrupted Server turn and reconcile any tool effects.
Durability and approvals
PostgreSQL continuation run headers
The unified migration installs the SQL 4 projection used for C7 writes
and Continuation.list_runs/2, including on exagent_snapshots for durable
Jobs. With 2.x journals, the new header column starts at NULL. Once the
DDL commits, run both calls on each enrolled table with those journals.
Pass the same Repo or {Repo, options} used in the Store descriptor.
Rebuilding writes headers at the active level and seeds missing leases.
:ok = ExAgent.Store.Postgres.rebuild_run_headers(repo_config)
:ok = ExAgent.Store.Postgres.verify_run_headers(repo_config)The backfill locks one journal root at a time and verifies the existing record before writing the derived header. You can rerun it after an interruption. Journal bytes, revisions, fragments and timestamps stay intact. A malformed journal stops the backfill. Use the host's normal journal recovery procedure for that record. Stage enough time for one full read of the eligible C7 journals for each pass.
To verify the schema with Doctor, configure the running host with the same
descriptor and pass --check-store. A missing or unusable SQL 4 schema now
fails this check. Pass --check-run-headers to also compare headers with
their validated journals across the table. Run this before resuming the
writers for a complete migration check.
- A missing column or missing or invalid index returns
{:error, {:store_migration_required, 4}}from C7 writes, run pages and header maintenance. Doctor reportsdetails.reason: "store_migration_required"withdetails.version: 4anddetails.unified_version: 1. Apply the unified migration to the configured table. Repair an existing invalid index before rerunning the check. If Server has a pending checkpoint, rebuild existing headers and retryServer.checkpoint/2. - A journal without its header returns
{:error, :run_header_missing}from run pages andContinuation.census/2.ExAgent.Store.Postgres.verify_run_headers/1returns{:error, {:run_header_missing, %{namespace: namespace, id: id}}}for the first such journal. Doctor reportsdetails.reason: "run_header_missing"with the same namespace and logical ID. Each ID is bounded by the 512-byte C7 limit. Run the backfill to rebuild the header.
Rolling back a historical SQL 4 migration drops the derived column and index. Restore the migration and rebuild before resuming writes that maintain the projection.
ETS commits the header in the owned table. Run pages read it directly.
They skip keys deleted during the read. If you import older ETS rows,
run ExAgent.Store.ETS.rebuild_run_headers(table) on the owner and use
verify_run_headers/1 or Doctor to check them. The ETS verifier uses the same
identity-bearing error for a journal without its header.
PostgreSQL turn admission receipts
Unified migration 1 includes SQL 5 for a PostgreSQL C7 Server that accepts keyed turns or Jobs notices.
Run Doctor with --check-store against the running Repo. It checks the receipt
columns, expiry index and cascading reference without reading receipts.
Receipt operations return {:error, {:store_migration_required, 5}} if the
columns are missing.
Indexed admission receipts are part of the Store format level 1 baseline. The Store commits individual receipt rows and the conversation's watermark in the same transaction. Include the whole table in backups. The version 5 down migration rejects tables that hold indexed receipts or their watermarks.
Use the public Store APIs
Custom adapters implement the snapshot callbacks of ExAgent.Store. Round-trip
the supplied snapshots through ExAgent.Server.Snapshot.serialize/1 and
ExAgent.Server.Snapshot.deserialize/1, or the equivalent
ExAgent.Session.Snapshot.serialize/1 and ExAgent.Session.Snapshot.deserialize/1.
Use the runtime to create and restore Session snapshots. For C7 operations, use
ExAgent.Continuation with a bundled Store. Replace calls to the internal
Store record loader with ExAgent.Continuation.get/3 and diagnostics: true,
or use ExAgent.Server.continuation/2 with that option for a live Server.
Custom Store guide
Use ExAgent.Store.ContractCase to exercise your existing descriptor from
ExUnit. The case takes a fresh test Store in setup and uses the public
snapshot API. Repair an invalid continuation: :atomic declaration before
running the suite. It checks divergent Session revisions when
snapshot_cas: true. Custom header callbacks can match physical keys with
Store.agent_key_in_namespace?/2.
Contract suite setup
Handle durable workflow tool batches and cancellation
Match {:workflow_tool_batch_checkpoint_limit, required_bytes, limit_bytes}
for a batch that cannot reserve journal space. Raise
:max_checkpoint_bytes in the continuation up to 8 MiB or set a smaller
:max_payload_bytes for the step. For a Flow with overlapping batches,
reduce :max_concurrency. The journal keeps its existing format.
Workflow tool batches
An agent, Composition or Flow whose live writer loses to a confirmed
Continuation.decide(:cancel) returns a RunError with reason :cancelled.
Read its confirmed continuation reference and partial. Continue to
reconcile uncertain effects using the journal.
Runtime reads
Change callers of Store.list_agent_snapshots/1 to enumerate the snapshots
inside {:ok, snapshots}. Present an empty inventory only for {:ok, []}.
Handle {:error, reason} separately, including invalid snapshot data and
backend failures. Update custom Store list callbacks to return the same tagged
result and verify each stored snapshot against its physical key.
When starting Store.ETS, replace table: MyApp.Snapshots with
name: MyApp.Snapshots. Pass the same atom in {Store.ETS, MyApp.Snapshots}
when configuring the Store. For supervisor operations such as
Supervisor.terminate_child/2, change the Store child ID from Store.ETS to
{Store.ETS, MyApp.Snapshots} (or {Store.ETS, Store.ETS} for the default).
Memory.ETS already used :name and the tuple child ID. Both adapters now
reject unknown or duplicate startup options. Existing snapshot bytes can be
read directly.
Unwrap {:ok, value} from Server history, usage and health, and Session current,
participants, status, read_state and health (including SharedState.read/1).
Replace {:ok, events, cursor} with {:ok, %{items: events, cursor: cursor}}
for Server.events_since/2. All queries accept timeout: and return
{:error, :unavailable} if the owner disappears or times out. Handle cursor
and continuation domain errors separately. Persisted records require no rewrite.
Phoenix chat and job integrations
The installer and chat generator locate the installed Agents module by
name. Generation locates the router by module too and places new chat files
alongside those modules. Generated tests mirror the host's directories.
Existing generated modules can stay where they are. Both Mix tasks exit
nonzero when Igniter reports issues or the user declines its changes. In a
shell without a TTY, use --dry-run for a preview. Check the exit code before
continuing to migrations or other setup steps.
For a previously generated chat that uses TestModel, port the default codec
selection in Agents.Chat from fresh output generated with --model test.
The codec saves the script index. Keep the same TestModel template when
restoring an active run. A host-supplied :chat_codec still takes precedence.
Framework integrations
Match ExAgent.Message.Part.JobNotice in custom model adapters and history
consumers. Read its job_id, status and tool_name. Supply Jobs.tools/2
or Jobs.Durable.tools/2 for the originating scope in the agent's tools so
the model can call job_status with the notice's job_id to retrieve the
retained result. Jobs.notification/1 formats metadata only. Older tagged user
messages restore as user text because their origin cannot be inferred from
their contents. job_notice_v1 is part of the Store format level 1 baseline.
Hosts that copied the earlier LiveView or Oban macros can migrate their authorization and presentation logic to the generated chat and resume worker. Keep pending decisions on their original scoped Store and bindings. For standalone jobs, port the copied dispatcher. Framework integrations
The host owns the files the generator writes. If you generated the chat with a
3.0 pre-release, compare ChatLive.Show and its tests with fresh output from
the same auth variant in a disposable host. Port the blocked status from the
history page, the send guard and the Check recovery control.
Change the connected mount from
PubSub.subscribe/2 and Server.attach/2 to
Server.attach(pid, self(), delivery: :demand). Replace the per-event handler
with a handler for {:exagent_events_ready, pid, notice}. Replace the earlier
ack: notice read option with notice: notice. Apply the batch, then call
Server.ack_events(pid, notice, applied_cursor). Retry a timed-out read with
the same notice and previous cursor. Retry a timed-out ACK with the same
notice and applied cursor.
Use paged :chat reads for mount, earlier messages and root terminals,
including :server_request_cancelled. Render
{:job_notice, %ExAgent.Message.Part.JobNotice{}} as activity. Use
output_guarded? for progress-only rendering in replay and live delivery,
including all structured output. On event cursor expiry or an oversized
event, rebuild with Server.history_page(pid, projection: :chat, include_draft: true)
and acknowledge the notice after applying the page's event cursor. The
snapshot covers the active draft
and the history available to the view. Demand reads
For per-turn cancellation, port the controls and browser hook from a fresh
generation. Use Server.turns/2 to recover live IDs on mount and
Server.abort_run/3 to target a specific row. The original key recovers
a queued cancellation receipt. An admitted receipt alone leaves the
cancellation unconfirmed.
Phoenix integration
Round-trip the optional output_guarded and accepted_rows fields in
custom Stores. New checkpoints restore retained accepted finals after an
owner restart. A guarded root C7 run started by ExAgent.run/3 also writes
its accepted final in the same checkpoint as its completion. Older
snapshots and continuations load without a rewrite.
When acceptance evidence is absent, a protected or unknown policy hides
assistant rows. A recorded unguarded policy keeps the text view with a
plain agent. Check both projection: :chat and canonical history in your
upgrade test.
Assert that private instructions and reasoning are absent from the DOM after a
turn and after remount. Port the colocated admission hook and its handlers to
ChatLive.Show. Keep the Phoenix 1.8 colocated hooks import in the host.
Mint the key when the form is submitted. Save the pair in the tab's
sessionStorage before dispatch. Keep the original nonce and expiry in the
URL for a reported {:delivery_unconfirmed, request_id}.
On remount, check the stored pair before enabling Send. Confirm it with the
scoped receipt or a retained root terminal. Match the terminal to the owner
emitter, conversation and request ID. Keep the form blocked while the outcome
is unconfirmed. For a Jobs notice use its notification key to recover the same
receipt. Port the lost-reply, expired-receipt and duplicate-job tests.
Adopt the shared chat view
New mix exagent.gen.live Chat output uses ExAgent.Chat and
ExAgent.Chat.Reader. To regenerate an existing chat, move the
ChatLive.Show source to a backup outside the application's compiled source
directories. Run mix exagent.gen.live Chat with the same auth and scope
options originally used. Preview with --dry-run if needed. The generator
recreates the missing module and preserves the existing generated modules
and routes. Reapply any application-specific changes to the new LiveView.
Reuse the existing database schema and stored records.
For a custom view, apply Server.history_page/2 with
projection: :chat, include_draft: true. Chat.apply_page/2 emits the row
update. Use Chat.reduce/2 for live or retained batches and resume at
chat.cursor. Chat.draft/1 reads provisional answer text and
Chat.draft(chat, :commentary) reads provisional narration.
Use approved history pages for final display. Both channels stay hidden
while the owner protects output. The draft page now includes
:active_run_id, :commentary and :checkpoint_pending?. Server text and
narration deltas include the boolean payload.output_guarded?.
LiveView and HTTP integrations
Bind queued chat resumes to their approval
Call Server.resume(server, reference, opts) with the version 1
:continuation from decide/4 or supply_result/4. Options are optional.
The reference identifies the logical conversation, record lifetime, run and
revision. The old call that resumed the current ready record is gone.
When a recovery operator selects a ready run, verify the run and revision with
Server.continuation/2 or Continuation.get/2 and pass that exact reference.
Generated files belong to the host. Port Agents.Chat.decide/4 and
Agents.ResumeWorker from fresh output for your auth variant. Keep the
decision and the Oban insert in one Repo transaction. The job now carries
"conversation" and a "continuation" object with "version", "id",
"record_id", "run_id" and "revision". A stale reference cancels the
job with :continuation_conflict. A job with only the conversation ID
cancels with :missing_continuation_reference.
For a rolling deployment, pause the legacy chat workers on every node before any upgraded producer can enqueue jobs. Let active deliveries finish and check the journal for ambiguous outcomes. Replace producers and workers before resuming consumers. The older worker accepts a job with extra fields and would use the current conversation state. This upgrade needs no Store schema change.
Inventory queued jobs without references. Requeue a versioned job only if host evidence links the original job to its committed decision and the authorized Store still has that exact ready revision. Use the original record ID, run ID and revision. When the evidence is absent or the state has changed, cancel the old job and handle the run through explicit, authorized recovery. The current approval by itself cannot establish which approval produced a legacy job. Reconcile uncertain effects before any new resume. Continuation recovery
Migrate continuation recovery calls
Pass the full version 1 :continuation from decide/4, supply_result/4
or the recovery that makes the run ready. The decision replaces the pause
reference. Keep :version, :id, :record_id, :run_id and :revision
when serializing it for a worker. :attempt_id is optional metadata.
ExAgent.resume/3 and ExAgent.resume_stream/3 also require this shape.
For a stored reference with only the ID, lifetime and revision, fetch the
full reference from the authorized Store. Verify that it identifies the
original decision and revision before resuming. If you cannot verify that
binding, handle the run through explicit recovery. An invalid or stale
reference returns :continuation_conflict. A matching record whose state
blocks resume returns {:continuation_not_ready, status}. Workflows still
support reading a confirmed terminal through resume/3.
When authorizing a new model retry with Continuation.retry_effect/4,
pass the trusted :agent and its :continuation binding with the leaf's
:definition, :policy, :model_ref and :model_codec. Resolve the leaf
through the effect details and use the configuration that will resume it.
ExAgent checks the captured request with the proposed key after authorization.
A failed check leaves the original intent eligible for reconciliation.
Existing authorized plans and receipts remain usable.
Return both dump/1 and load/2 from every Models.Fallback.codec/1 leaf
selector. If a journal already exists, supply a load/2 that can read the
state it wrote. Read the current claim's UTC horizon in milliseconds from
:lease_until in Continuation.get/2 or Server.continuation/2.
The Store uses its own clock to decide whether the claim expired.
Durability and approvals
Adopt supervised continuation recovery
Add Continuation.Recovery to the supervisor with one scoped Store or an
unscoped Store and a trusted :namespaces list or provider function.
Configure the existing authorizer to recognize the system actor and grant
its specific recovery operations. Give a custom policy a version and return
:leave for effects that need an operator.
To wake conversations that become ready, add :on_ready and authorize
:resume for the same scoped revision. Copy the generated :system
authorization clause and ResumeWorker.wake_recovered/1 into existing
chat scaffolds. Existing queued approval jobs keep their argument shape.
Before stopping a conversation supervisor, use Conversations.drain/2
to finish running turns and confirm queued cancellations.
Recovery setup ·
Generated chat configuration ·
Drain setup
Update a generated Phoenix chat
New Phoenix hosts can start with mix igniter.install exagent --chat.
Use the existing install and generation tasks on an already configured host,
or add the combined install to supervise Recovery and create a missing lock.
To reverse a fresh install, roll back its generated migrations with Ecto
before reverting the source changes. Rolling those migrations back removes
the state in their new tables.
For an existing LiveView, copy the updated approval refresh logic to keep
open review forms valid across refreshes of the same request.
Setup
Add :wake_timer to the system authorizer's owner-scoped operation guard.
Copy the updated LiveView controls to display timer deadlines and disable
sending while a continuation is paused. Show pending approval or input
in the paused turn's label before the timer wait. If replacing the base
Agents scaffold, route LiveView input to Agents.Chat.supply_input/4.
Keep existing migrations and deployed catalog entries. Configure Doctor
with the same Repo and Store table used by the host.
Catalog upgrades ·
Doctor configuration
New hosts receive a short chat_live_test.exs for sending and streaming a
message, restoring a pending approval after the conversation owner restarts,
and checking Doctor. Keep any application tests you added to an earlier
scaffold. Update their candidate API calls using the
published stability tiers.
For the retired durable_oban.exs sketch, use the
persisted continuation jobs recipe.
If you used zai_anthropic.exs for historical routing, see the
provider routing migration.
Index PostgreSQL recovery candidates
The unified migration builds the SQL 6 index scanned by
Continuation.Recovery. It verifies lease projection coverage under a
table write lock. Allow time for the lock and index build. If a table
already has SQL 4 headers and enrollment reports missing lease projections,
run Store.Postgres.rebuild_run_headers/1 and retry the migration.
Existing renewed horizons take precedence.
On an enrolled 2.x Store, backfill before enabling Recovery. The index uses derived headers and leases. A sweep can report success while omitting imported work with neither projection, even when the schema check passes.
Run Doctor with --check-run-headers --check-recovery on the running Repo
before enabling the sweeper. A missing recovery index returns
{:error, {:store_migration_required, 6}} from Recovery.sweep/2.
If store.recovery reports version 6 after migration, rerun the header
backfill and inspect the index. A historical SQL 6 rollback drops the index
and its scope function. Existing lease projections
remain readable and are cleaned up when their claims end. ETS maintains its
index in the Store owner. For an imported ETS table, rebuild its run headers.
Run header migration
Enable automatic recovery for Oban jobs
Workers can implement Jobs.Durable.recovery/2 and enable Oban Lifeline.
Pass an actor and the existing continuation authorizer. Deploy the same
worker module, versioned bindings, policy and Oban prefix on all replicas.
Admitted jobs use their existing IDs, queue arguments and C7 records.
Apply unified migration 1 for the Store SQL 6 recovery index when using a
separate PostgreSQL namespace sweeper.
Choose model: :leave to keep lost model responses for review, or
model: :retry to accept possible duplicate spend. The default closes
model-only uncertainty as cancelled. Add effect: :read only for
repeatable reads. For writes, supply reconcile: to query the saved key
and return evidence. Jobs outside the policy use the operator procedure.
To configure a custom Continuation.Recovery policy, pass the result of
Recovery.Policy.new/2 as :policy.
Catalogue and recovery migration
An initial spend refusal with :unknown delay now writes a scheduled
:ready receipt when the writer can certify effect-free preparation.
The scheduled receipt is part of the Store format level 1 baseline.
Previous held receipts with a null retry_at remain readable. Inspect
their preparation and use the existing operator recovery procedure
before waking them.
Jobs recovery and shutdown
Deploy versioned definitions and recovery policies
Move a custom Recovery decision function into its policy. Keep the same reference so that existing operation IDs still identify the same decisions.
alias ExAgent.Continuation.Recovery.Policy
policy = Policy.new(%{"id" => "review", "version" => "1"}, &MyApp.Recovery.decide/1)
# Pass policy: policy in the Recovery child options.Omit the top-level :decide option. The built-in policy remains
Policy.default/1 and accepts a catalogue or resolver functions.
Existing explicit agent and codec bindings can keep using the same API.
The unified migration adds the Jobs delivery diagnostic column. Keep the column during application rollbacks. For imported journals, run the header backfill before taking the census. Oban arguments and continuation reference formats remain valid.
- Expand the catalogue on every relevant replica to include the current and next definitions, and preserve their agents, tools, policies and codecs. Keep admission on the current version. In a copied Phoenix chat, add the catalogue to the Server. For a host upgrading from 2.3, keep the explicit definition, policy and model references from its saved continuations.
- Start the queues for the retained versions and verify each replica's catalogue with Doctor. Switch admission to the new definition. Route wake-ups to queues serving the saved version. Roll back by switching admission to the earlier definition and keeping both versions and their queues live.
- Drain the old version. Check
Continuation.census(scopes, include_closed: true)across the chat, workflow and Jobs scopes. Settle open records and explicitly adopt retained chat history that should start new turns on the current version. Check jobs queued before their first C7 write. Remove the old entry only when these checks account for all remaining references. Keep any definition still needed to read retained history. Deploy with open continuations
Adopt a generated background agent
Run mix exagent.gen.agent Name to add a background agent to an existing
host. Apply the generated migrations with Ecto. The example receipt table
belongs to the host. Keep its migration and adapt the write and read-only
lookup together when replacing the example effect.
The generator registers each worker's lock callback under
:exagent_background_catalogs. Keep the existing :exagent_catalog_lock
callback for chat or a custom primary catalogue. Both contribute to the same
priv/exagent/catalog.lock. Keep the previous worker definitions and bindings
available when updating a deployed reference. Run mix exagent.catalog.lock --check
against the compiled host before deploying.
Background agent setup
Enable a separate reviewer for generated chat
Run mix exagent.gen.approvals after installing the current authenticated
chat. Grant the reviewers access to specific requester namespaces in the
host configuration. The inbox uses the existing PostgreSQL tables and
retained continuations. Existing pending runs can be reviewed there
without changing their definition or migrating their records.
With the igniter_new archive from chat setup, the command can load temporary
Igniter for hosts that do not declare the dependency.
For older generated hosts, merge the current approval_notifier/0,
pubsub/0 and authorize/3 hooks into Agents and the waiting state into
ChatLive.Show before running the task. The generator stops and names
these hooks if it cannot find the starter's chat decision guard or notifier
wiring. Keep custom chat policy in the guard's fallback branch.
The inbox uses the existing workers for delivery. For a named Oban
instance, grant {Worker, requester_namespace, oban_name} using the name
passed to Jobs.Durable.new/3 when starting its jobs. Two-element grants
continue to use the default Oban instance. In an inbox already generated,
merge the current Agents.Approvals source to use the job's Repo and
instance and skip pages without pending requests. To send notices from an
older background worker, merge the current worker's perform/1 wrapper.
Apply the same host review policy to custom endpoints that submit decisions.
Inbox setup
Handle deferred result retention errors
Handle {:error, {:invalid_result, {:retention_limit_exceeded, details}}}
and {:error, {:invalid_result, :record_limit}} when supplying a deferred
result through the continuation or Server API. Retry the same pending call
with a smaller result or a reference the tool can consume. C7 preserves the
revision and records no receipt for the rejected value.
New Frame3 pauses record a configured :max_checkpoint_bytes for the
checkpoint estimate. For a saved pause without that field, the estimate
uses the Store limit. A custom budget missing from the record is checked
by the writer on resume. Committed receipts still replay. No database
migration is required.
Lock durable agent definitions before deployment
Use Catalog.fingerprint/1 for a new or changed durable agent. Pass the
agent, a definition ID, the binding's policy and model references and its
codec. Include the :permissions from turn admission and
:rehydrate_tools when used. Equivalent JSON data produces the same
reference. Version behavior changes inside the same function or captured
values through the explicit policy or model reference.
When upgrading from 2.3, add each deployed definition needed by saved runs to the catalogue with its original agent, tool behavior, model and codec. Use the exact saved definition, policy and model references for those entries. Derive a reference for the new active definition and use a new revision for changed behavior.
Run mix exagent.catalog.lock on a checkout that serves the deployed
definition before making changes. Commit priv/exagent/catalog.lock with
the catalogue. The lock stores the primary active reference and the
fingerprints of all protected agents and bindings. When the host has only
generated worker callbacks, the first key by name supplies the primary.
Each active reference includes turn permissions. A restored run uses the
permission floor saved in C7 and the host's current permissions.
If the lock contains only draft definitions from before your first
deployment, and no durable runs or queued jobs you intend to keep use
them, delete priv/exagent/catalog.lock and rerun
mix exagent.catalog.lock to record the new draft.
When the active reference changes, keep the original definition under its
old reference and rerun mix exagent.catalog.lock. Run the generated test
or mix exagent.doctor --check-catalog-lock with the compiled deployment
configuration. A missing definition or changed code under a protected
reference blocks updating the lock and passing the checks. After the
retirement checks
account for all earlier records, queued jobs and rollback targets, remove
the retired reference from the catalogue and the lock's entries together.
Update the generated ResumeWorker to limit missing-definition snoozes.
:chat_definition_wait_seconds sets the maximum age of a Job at a
missing-definition attempt. It defaults to 900 seconds. Zero parks the
delivery on its first missing-definition attempt. Oban preserves the
attempt budget during snoozes. At the deadline it cancels the delivery
with the missing reference in the Job's errors. Subscribe to
[:exagent, :catalog, :definition_wait_expired] for the Job ID and
definition. Restore the exact version and retry the cancelled Oban Job
to deliver the original approved revision.
Resume jobs queued by 2.3
Keep the copied Oban worker's module name and argument shape. A job stored
with %{"reference" => id} still calls that worker with the same ID.
Resolve the trusted agent, scoped Store, continuation config and run options
from the ID through the existing host authorization.
The 2.3 dispatcher read record["record_id"] and record["revision"].
In 3.0, take the :continuation reference from Continuation.get/2
in your copy of job_dispatch.ex. The read returns the same reference as
the current administrative acknowledgement for a ready or approved run.
Server.continuation/2 provides it when reading through a live Server.
alias ExAgent.Continuation
case Continuation.get(config.store, config.id) do
{:ok, %{continuation: %{} = reference}} ->
ExAgent.resume(agent, reference, Keyword.put(run_opts, :continuation, config))
other ->
dispatch_other.(other)
enddispatch_other handles the remaining statuses and read errors. For copied
pending and terminal branches, also read top-level :record_id and
:revision when returning that metadata. Leave pending approvals waiting.
Acknowledge redelivery after a terminal state. Keep the worker's attempt
and reconciliation logic for claimed, executing or uncertain records.
Use the original definition and policy bindings on resume. Rehearse with a copy of the original Oban row and continuation record. Verify the job completes with the same record and run IDs. Redeliver it and check that the effect count stays the same.
Handle process and MCP acknowledgements
Replace exit handlers for Server.attach/2, Server.detach/2, MCP.Client.tools/1,
MCP.Client.reconnect/1, MCP.Client.close/1, MCP.Server.handle/4 and
MCP.Server.close/3 with error tuple matching. Match
{:error, :unavailable} for an absent PID or name, including the old
:client_not_running from call_tool/3 and :not_found from
Conversations.stop/3. A dispatched command without a reply returns
{:error, :result_unconfirmed}. An activation timeout from ensure/3 also
returns this receipt. A start already requested may finish later. Conversations.call/4
returns :unavailable if activation never reached its callback. Retry a
dispatched command only on an explicit unread receipt or a pre-execution
writer fence. An exit reason cannot establish non-delivery.
Pass timeout: to Conversations.stop/3, Server.attach/3, Server.detach/3,
Jobs.cancel/3 or MCP.Server.close/4 to set the same caller budget as
Server.ack_events/4. The default is 5,000 ms, including owner lookup.
Lookup expiry before dispatch returns :unavailable. Expiry while
waiting for a dispatched command returns :result_unconfirmed.
Change Conversations.stop(manager, key, reason) to
Conversations.stop(manager, key, reason: reason) for a custom exit reason.
Set timeout: :infinity for a caller that intentionally waits indefinitely.
For a direct tool call, move matches on causes such as {:error, :timeout}
or {:error, :invalid_tool_result} to {:error, {:result_unconfirmed, cause}}.
The generated callback returns {:unknown, cause}. Valid JSON-RPC rejections
keep their existing tuple. Replace matches on {:error, {:jsonrpc_error, -32004}}
from a direct tool call with {:error, :result_unconfirmed}. It also covers
July's wire code 10001. The discovered callback returns
{:unknown, :result_unconfirmed} in both cases. Forwarding the direct
receipt from a host tool also leaves the continuation uncertain. Stdio
peers must include "jsonrpc": "2.0" and typed
content blocks. Treat unknown HTTP 5xx responses after upload as uncertain
and reconcile before another call. Use MCP.Client.start_link(transport: :streamable_http, url: url, finch: pool) for HTTP. The transport worker's functions are internal.
Validate constructor options
Supply a local registered atom as :name and a unary function or MFA as
:server to Conversations.start_link/1. Missing or invalid options
raise ArgumentError in the caller. Use the same options in a supervisor
child specification.
Pass a UTF-8 string as :case to Fixture.open/2, or omit it to use the
file's basename. Cassettes use that string to match the case.
If a custom cassette used a non-string JSON case, update its
"case" field and the opener to use the same string.
Consume MCP structured results
Discover MCP tools with MCP.Client.tools/1. An advertised object
outputSchema is imported as Tool.result_schema. A successful callback
returns {:ok, map}. Update callers that decoded the accompanying text
as JSON or parsed a text label.
| 2.x result pattern | 3.0 result pattern for a tool with an object schema |
|---|---|
{:ok, stock_text}, with text like "stock: 17". | {:ok, %{"stock" => available}} |
MCP.Client.call_tool/3 always uses the text or opted-in image projection.
If a direct caller currently uses a result schema learned from the catalogue,
switch it to the callback of the validated tool. Stateless HTTP still
resolves routing metadata before a named call. To enforce agent approval and
permission checks, supply the discovered tool to the agent.
Handle {:tool_error, notice} for a complete, correlated success with
missing or invalid structured data. The notice confirms execution and
omits the rejected data. Route it as a tool error.
Missing acknowledgements still require reconciliation. New C7 bindings
include the imported schema. Older MCP approvals use their original text
or image projection when the endpoint identity and tool definition match.
Keep the original schema for a pending approval that already bound one.
Persisted handoffs also verify the saved catalogue and its callback build.
Complete pending handoffs with their original build if this check fails after upgrading.
MCP client guide
Migrate MCP HTTP negotiation and input
An HTTP client with no protocol pin sends server/discover first at
2026-07-28. For an older peer it uses initialize and accepts a supported
Streamable HTTP response. If a proxy or provider requires the old first
request, set protocol_version: "2025-06-18" on the client. Pass the stored
HTTP revision when rebuilding tools for a C7 record. Keep the original
endpoint and principal references. Stdio uses its own revision selection.
For peer forms, accept DeferredCall.kind == :input and pass the responses
as {:input, responses} to Continuation.supply_result/4. Resume with the
returned reference after the inbox is settled. The journal records the
form, optional opaque requestState, retry_version: 2 and a supply_input
receipt. The same SQL 6 layout stores these records.
To serve approval on a July Plug, configure the server's :mrtr_approval
with the same MAC key and atomic Store on every replica. Start OAuth
integration with ExAgent.MCP.OAuth.metadata_urls/1 and
validate_metadata/2, then use PKCE and validate the callback issuer.
MCP form round trip ·
Server configuration
Apply the wave 29 QA fixes
- MRTR approvals. Decode HTTP 400 with JSON-RPC
-32040as a rejected answer.error.data.scopeidentifies the active quota. The limit is 256 live receipts per principal and 1,024 per endpoint. Earlier receipts still reject replay and count toward the endpoint ceiling until their signed states expire. Stateless approvals - OAuth.
MCP.OAuth.validate_metadata/2can return{:error, :pkce_unsupported}. Proceed with authorization only after validation succeeds. Configure the authorization server to publish"S256"in its advertised PKCE methods. MCP Authorization Code Protection - C7 input rounds. Replace ordinary
:succeededor:failedresults for an open MCP form with{:input, responses}and resume to get the peer's result. Use{:denied, content}or{:not_executed, content}to settle the tool locally, orContinuation.decide/4with:cancelto end the run. MCP form round trip - Catalog lock. The v2 definition fingerprint includes root settings
and uses the existing C7 reference fields. Keep deployed definitions
and their exact saved references in the catalogue beside the active
reference. Use JSON-portable
ModelSettings.extravalues and a stable limiter name when deriving a new reference across replicas. Deploy with a lock - AG-UI. Use the Server run ID to read ExAgent events. Store the wire
runIdfromRUN_STARTED, or supply your own authorized wire ID through:run_id. A new encoder generates a fresh wire run ID by default, even when the Server resumes the same run. AG-UI encoder
Pin MCP declarations before locking a definition
Capture each endpoint with mix exagent.mcp.lock ENDPOINT and track the
reviewed lock with the deployment. Use the peer revision and declarations
that the open approval originally recorded. Supply the same transport,
endpoint and principal binding, and build the tools with pinned: bytes.
This lets mix exagent.catalog.lock --check compute a durable reference
offline. The catalog task warns about unpinned remote tools.
Run mix exagent.doctor --check-mcp-lock in CI to validate integrity and
presence. Call MCP.Client.reconnect/1 at runtime before dispatching pinned
tools. It keeps the selected protocol revision. Match drift errors or opt
into :serve_pinned to use the locked description after a description-only
edit. On a schema, annotation or tool removal, keep the reviewed definition
and an endpoint serving that contract for any open work. Capture and review
a new lock before publishing the new definition version.
MCP guide
Opt in to stateless MCP
Keep the existing HTTP path available for clients and pending approvals bound
to 2025-06-18. Mount the July profile on its own path with
protocol_version: "2026-07-28". New HTTP clients probe that revision first.
Use stable host principal references and rediscover tools before building
agents. The selected revision participates in the C7 tool fingerprint. Resume
pending approvals with their original endpoint, revision and principal.
Correct invalid x-mcp-header declarations before restarting the server.
A malformed declaration now raises at startup with the tool name and cause.
Published :result_schema values still require an explicit object root.
Stateless HTTP
Opt in to MCP Tasks
Set tasks: true on a 2026-07-28 HTTP client for new runs. Rediscover
the tools before building the agent. When the peer offers Tasks, imported
tools become context-aware writes with a read-only reconciler. Restore
existing runs with the discovery profile used to write their tool fingerprint.
For a new root C7 run, use Continuation.pending/2 and
Continuation.reconcile_tool/4 to resolve a stored task before resuming.
Move direct calls to start_tool/3, get_task/2 and cancel_task/2 from
MCP.Client to MCP.Client.Tasks. Pass the same client, arguments and task
IDs. The client option and automatic polling through MCP.Client.call_tool/3
keep their existing behaviour. A -32602 response to a Task lookup or
cancellation now returns {:error, :mcp_task_unknown}. Reconcile its original
effect with independent evidence.
MCP Tasks
· Operator recovery
Handle MCP authorization challenges
Add a match for {:error, {:authorization_required, challenge}} to HTTP
callers that handled only :unauthorized and :forbidden. Those atoms still
cover responses without a valid Bearer challenge. The host gets a token
using the challenge and updates the source read by :headers_provider.
Retry the rejected operation once and return its receipt. Reconcile an
unconfirmed effect before issuing another tool call.
To publish RFC 9728 metadata on the server, add :protected_resource to
the Plug options and mount its well-known route for public GETs. Update
the host's :authorize to verify Bearer tokens for that resource and
return the missing, invalid or insufficient-scope result.
Client recovery
· Protected resources
Handle malformed MCP stdio requests
Custom stdio transports consuming MCP.Protocol.decode/1 can receive
{:invalid_request, id}. Send JSON-RPC -32600 for this kind of server
request. Use the decoder's ID or JSON null when the ID is unusable.
Stdio protocol
Use MCP tool catalogue caching
Existing clients automatically use positive ttlMs and matching
cacheScope hints on every tools/list page. Concurrent cold lookups for
the same identity share the completed catalogue when it is cacheable.
Use ttlMs: 0 on the server
to request a fresh listing each time. For C7, rediscover with the
continuation-bound client before rebuilding the agent for resume. A schema
change can require a new approval. The server still authorizes every
tools/call, including calls routed from cached declarations.
MCP catalogue caching
When using MCP.Protocol.decode/1 in a custom transport, send notifications
as JSON-RPC 2.0 messages with a string method and an optional object params.
Omitted params decode as %{}. Reserve id for requests and responses.
A valid server ping yields {:ping, id}. Other well-formed server requests
yield {:unsupported_request, id}. In stdio and MCP 2025-06-18 HTTP SSE,
answer those requests with JSON-RPC -32601 and the original ID. In
2026-07-28, requests originate with the client. The ExAgent HTTP client
reports :unexpected_server_request for an incoming RPC on a July SSE stream.
JSON-RPC responses · July transports
Scope MCP catalogues to authenticated principals
Set :catalog_policy on ExAgent.MCP.Server to filter tools, resources and
prompts using your application's grants. Keep the Plug authenticator's
actor ID stable across credential rotation. Provide the same grants and
catalogue order on each replica. With the default policy setting, every
authenticated principal sees all configured entries.
Forward nextCursor as an opaque string. Restart from the first page after
upgrading from numeric cursors or receiving -32602 for a stale cursor.
If startup reports that a descriptor exceeds a tight page budget, allow
room for the new cursor. July returns -32602 for missing or hidden tools
even if the request carries tool-specific routing headers.
Existing C7 records restore with their saved endpoint, principal, revision and tool schema. A tool hidden at resume returns a confirmed rejection and consumes the approval. Recover lost replies through C7 reconciliation. MCP catalogue policy
Rotate MCP credentials and propagate trace context
For HTTP credential rotation, replace :finch and static :headers with a
:headers_provider callback. It returns a host principal reference and headers
within the request deadline. The existing client can use new credentials for
the same principal. Preserve the endpoint, principal, protocol revision and
tool schema when resuming an existing approval. A different principal requires a
different binding and a new approval. Reconcile uncertain calls using the
original execution before resuming.
An expiry before upload returns :http_pre_dispatch_timeout. A
{:mcp_headers, cause} failure after C7 claimed the approved run consumes
that approval even if the tool POST never started. Restore the expected
credentials, or build a new binding for a different principal. Start a new
run with a fresh continuation ID and approval-required permissions. Review
and approve the new request before resuming it.
The optional OTel SDK remains application-owned. Set client trace: true to
propagate trace context. Select :local, :trusted or a predicate of
authenticated actors on the Plug. No persisted record migration is required.
MCP credentials and tracing
Configure MCP subprocesses
Pass the absolute executable path as :command, or resolve a name on the
host's PATH before starting the client. For example, launch an installed
Python MCP server with its entry point in server_script.
command = System.find_executable("python3") || raise "python3 is missing from PATH"
ExAgent.MCP.Client.start_link(command: command, args: [server_script])Stdio spawns that path directly. If startup returns
{:error, {:stdio_spawn_failed, :enoent}}, check the executable at :command
and the working directory if you set :cd.
Stdio now inherits a small OS environment. Pass required variables through
:env; select environment_policy: :inherit only for trusted servers
requiring their former environment. Version the endpoint reference if launch
semantics change. See MCP.
Move Finch pools to their owners
3.0 removes the registered ExAgent.Finch pool and its :exagent, :finch_pools
setting. Applications using the default provider transport or an existing
host-owned MCP pool need no change.
If your application sent requests through ExAgent.Finch, add a Finch child
to its supervision tree before the clients. Move the former pool options into
that child's :pools and update callers to use its registered name. For MCP
Streamable HTTP, use HTTP/1-only pools and pass the name as :finch.
{Finch, name: MyApp.MCPFinch, pools: %{default: [protocols: [:http1], size: 32]}}ExAgent.MCP.Client.start_link(transport: :streamable_http, url: url, finch: MyApp.MCPFinch)To tune the provider transport, configure the pool that ReqLLM supervises in the application's configuration.
config :req_llm, :finch, pools: %{default: [protocols: [:http1], size: 32]}Tools and runtime inspection
Replace kind: :unapproved with kind: :function, requires_approval: true.
Supply the run's :approve callback or use a durable :continuation to review
marked tools. Existing permission denies still win. After composing names,
update permission globs and capability selectors. Keep the original inventory
for pending runs: changing a name, review flag or MCP mapping invalidates its
fingerprint. Old descriptors remain readable.
Use Tool.new/1 for public fields. Remove :prepared_validator,
:prepared_result_validator, :execution_binding and :delegation from
constructor options. Build remote, sandbox and delegation tools with
MCP.Client.tools/1, Sandbox.tools/2 and Coordination.delegation_tool/2.
The runtime prepares schemas. Use Tool.validate_args/2 or
Tool.validate_result/2 for host-side checks.
Opt in to isolated code execution
When adopting sandboxing, replace a code-evaluation callback with
Sandbox.tools/2 on a host-provided adapter. Bind the trusted scope and
versioned executor identity at agent construction. Select read-only mounts
and quotas, and supervise one Jobs process per scope to expose background
submission. Review sandbox_execute and sandbox_start through the
ordinary approval flow.
Retain the original effect ID for reconciliation. Use Sandbox.new_id/0
for each new host execution. In candidate configurations and custom
Sandbox.Backend implementations, rename :cpu_millis to
:cpu_millicores. The CPU unit and C7 policy fingerprint are unchanged.
Match {:error, {:operation_exists, id}} for an existing reservation,
{:error, {:unavailable, id}} for an unavailable read, and
{:error, {:result_unconfirmed, id}} for an uncertain outcome. Custom
mutation tools can forward an existing reservation or lost acknowledgement
as {:unknown, reason}. Custom query tools can return a fixed
{:tool_error, message} for an unavailable or unconfirmed observation,
like sandbox_read and sandbox_capture. The generated queries cut off a
slow backend at 5,000 ms or half the remaining tool budget, whichever is
shorter. Keep custom backend reads within that budget.
Use the original ID when reconciling. Destruction, eviction, expiry or restart can remove the local receipt and allow an ID to be reserved again. Earlier C7 approvals and uncertain query entries restore with their original bindings. Reconcile open entries using host evidence. Sandbox guide
Enforce tool result schemas
Check callbacks and result hooks for each existing result_schema. Return
the declared JSON shape before ExAgent projects a preview or reference. A
mismatch now yields a confirmed :tool_error. MCP clients should look for
isError: true in the call result. For Jobs.background/2, the schema
applies to the underlying job result and the submission still returns its receipt.
New continuation bindings include the result schema, including nil. Keep
the offered definition available while approvals or deferrals remain open.
Earlier bindings restore under the old fingerprint. New results use the live
schema, and replays use the recorded final return. Use
result_mode: :multimodal with a nil schema for typed image output.
Recovery of a raw confirmation applies the configured output limits and
offload. Budget for the same bounded preview the model sees on a live run.
Recovery skips after_tool_call/4 and on_truncate host callbacks.
On a failed workflow, read the journal for the effect receipt when progress
withholds a result that still awaited schema validation.
New Continuation.reconcile/5 receipts bind the normalized proposal and the
projected result. Reuse the original revision, operation ID and outcome for an
exact retry. A receipt already written by an earlier version still loads.
If replay returns :operation_conflict, inspect the existing receipt and
effect with Continuation.get/2. Authorizers that read target.payload
now receive result and proposal_hash instead of a computed snapshot
and progress.
Tool admission and inspection
A tool call's timeout now counts from its dispatch, and its admission
(preparation hooks, validation, permissions, a synchronous :approve) has a
separate budget of the same length. An approval or hook that outlived the
timeout used to leave the call :unknown with {:tool_execution_failed, name, {:exit, :timeout}}; it is now :not_executed with {:tool_admission_timeout, name}, which also tells the host that nothing ran. Match the new reason where
you handle tool timeouts, and allow up to twice the timeout per call.
Move scrapers of raw Server, Session and Jobs OTP status to
ExAgent.Runtime.info/2. OTP status now contains redacted summaries.
Use the authorized application's history or pending APIs when actual messages
or actionable approval requests are needed.
Jobs replies
ExAgent.Jobs.list/1,2 returns {:ok, jobs} or {:error, :unavailable};
update every caller that took the bare list. status/2, wait/3, cancel/2
and start/4 can also return {:error, :unavailable}. cancel/2 can return
{:error, :result_unconfirmed} and start/4 {:error, {:delivery_unconfirmed, id}}: the request may have taken effect, so read status/2 with that id before
acting again.
Defer durable Jobs on provider quota
use ExAgent.Jobs.Durable now schedules a quota refusal certified before
the first model intent. A deferred job reads as :ready and retains its
cause in Job.diagnostic along with its scheduled UTC Job.retry_at. Read
Job.error for display text. A certified deadline closes the job as
:expired. Let the generated perform/1 return its Oban snooze, and
display the job state from Durable.status/2.
Held claims report the refusal and need authorized C7 recovery. Apply unified
migration 1 for quota SQL 1 if Job.diagnostic.type is "rate_limiter_migration_required".
Inspect the record and host callbacks, recover the expired claim, then wake
the same ID if repeating preparation is safe. These diagnostic writes are
part of the Store format level 1 baseline. Readers accept the earlier
job_refusal shape and the existing Job admission arguments.
Quota handling in the Oban worker
Declare a TestModel profile
Set %ExAgent.Models.Test{profile: %ExAgent.ModelProfile{...}} to exercise
capability-dependent paths. Omitting the field preserves the current defaults.
Supply the profile through the trusted model template when restoring a
script. A run with :model_continuation_preflight_required now names
validate_resume/4 in its hint. The error reason and existing model codecs
keep their contracts.
Testing profiles
Set system: and model_name: on TestModel to exercise distinct quota
keys with Fallback. The defaults stay "test". Include the desired identity
on the trusted template if your test restores a model from its script index.
Quota example
Snapshot writers
When replacing a snapshot in ETS or PostgreSQL, increment its stored revision
by one. Retry an unconfirmed save with the original snapshot, including its
timestamp. Custom adapters can advertise snapshot_cas: true in
capabilities/1 once they atomically accept creation, the immediate
successor, and identical bytes, rejecting other writes with :superseded.
PostgreSQL compares inline and fragmented snapshots with the same portable JSON reader under the row lock. Snapshots carrying escaped NUL data can be advanced without rewriting the existing rows ahead of time.
A tool returning nil now stores JSON null in the history. 2.x stored the
text "nil" for both a missing value and that literal string; the loader keeps
those strings because their original value cannot be inferred. When upgrading
workers gradually, keep a run with a new null result on updated workers for each
subsequent checkpoint and resume.
Results and output unions
Agent run terminals and agent error partials are %ExAgent.Result{}. Field patterns
and bracket reads still work. For map enumeration use Map.from_struct/1.
Export history with ExAgent.Message.to_json/1 because the live model can hold credentials.
Rename application and skill tools whose names start with final_result, the
prefix reserved for output tools. Persisted runs with a single output schema keep
their fingerprints. After adopting an output union,
resume each run with the same ordered branches, names and schemas.
Declare Jason encoders for structs and embeds whose public fields differ from
the Ecto dump. Render the accepted projection from terminal events or visible
history. Both check encoded JSON against the run's max_payload_bytes. Handle
%{serialization_error: true} in payload.output and hidden history rows
for values that exceed the budget.
Durable workflows
Composition and Flow are stable SemVer APIs from 3.0. Assign the struct returned
by new/1 and the map returned by binding/1 directly. Rename Flow's
branches: option to steps:. Validate dynamic worker options before dispatch:
invalid definitions and workflow options raise ArgumentError before Store IO.
An invalid continuation configuration still returns a RunError.
Return {:ok, value} or {:error, reason} from input mappers, selectors and
merges. For an in-flight 2.x record, adapt the return shape of select and
merge without increasing select_version or merge_version. Increasing
either version changes the fingerprint. An old bare return on resume becomes
a confirmed terminal host failure. The live reason is {:callback_failed, phase, reason}.
Match %ExAgent.Coordination.Result{} for workflows. Read the ordered steps
for per-agent messages, portable errors and status. Remove workflow-root reads
of model, messages, new_messages, parent_run_id and branches.
Flow's default output remains the stored list of JSON outcomes.
Reading a failed sequence or Flow returns {:workflow_failed, portable_error}. Pass a
direct step ID as :step to Eval's judge and tool_called evaluators.
Map a Flow over a list
Set kind: :map and supply one versioned :template step descriptor.
Pass the ordered list of %{id: id, input: json} items to Flow.run/3.
The template's ID keys :step_options. The item IDs key results, retry
paths and cassette routes. Map flows default to :collect.
Map flows use a version 2 binding and a manifest in Frame 11, both part of the Store format level 1 baseline. Existing Frame 11 bindings and records restore in place. Manifest example
Recover or close a lost workflow model request
Use Continuation.reconcile_model/5 after recovering a Flow or Composition
claim if the host has the complete response and portable model state. Pass
the affected leaf's agent and continuation binding. Resolve them from
get/2 effects using :leaf. The authorizer can use the same projection
from its target. When the reply is ready, use its :continuation to resume.
If only model requests remain uncertain, decide/4 can return :cancelled
or :expired. Take the terminal :continuation from get/2 and pass it
to Flow.resume/3 or Composition.resume/3. A terminal read of a closure
returns RunError.partial
with the confirmed steps and marks unfinished started steps :cancelled.
Archive any needed evidence before explicitly pruning the terminal.
Existing Frame 10 and Frame 11 records keep their schemas and restore in place. The Store format level 1 baseline includes workflow terminals that retain uncertain model intents. Recovery example
Retry a lost Flow branch request
After recovering a Flow claim, read :retryable_effects from get/2.
Pass the model effect's binding to retry_effect/4 with
accept_duplicate_risk: true. Resume with the returned ready reference.
Confirmed work and its accounting stay in the same workflow.
Callers that previously treated all workflow retries as
:unsupported_operation can use this path for model intents in Flow.
The Frame 11 schema adds optional retry evidence as part of the Store
format level 1 baseline and reads earlier records.
Retry example
Certify Flow output vetoes
Declare each validator on a direct Flow branch as {:pure, fn output -> ... end}
to make its returned {:error, reason} a confirmed output-tool veto. The chain
must be deterministic and free of side effects. Keep the same validator
behavior and :output_ref for records you intend to resume. Bump
:output_ref for changed behavior and use that definition for new runs.
Context-aware validators keep their existing behavior.
When a missing pure declaration blocks certification, Flow returns
{:output_validation_failed, reason} with a hint on the RunError.
Read error.hint for :flow_output_veto_requires_pure_validators or
render Exception.message(error) for the instruction.
The Store format level 1 baseline includes the veto resolution variant.
Existing Frame 11 records restore in place. For a prior failure
with no veto resolution, inspect the journal and recover its expired claim
with the original binding. If the old chain was pure, it can use the pure
declaration with the same behavior and :output_ref. Flow can evaluate it
against the retained model response. For an already certified veto, recovery
closes the branch from the journal before loading the validator or replaying
any confirmed effect. Inspect the resulting portable error in the
Flow outcomes.
Evaluation baselines
Update report consumers to read JSON v1 and remove the development
:version option from Report.to_map/2 calls. The reader recomputes
passes and grading coverage from the scores. Report.from_map/1 rejects
duplicate attempts with {:error, {:duplicate_attempt, {case, attempt}}}.
Read summary.grading_coverage for total attempts without a target error
and how many received at least one emitted grade. The synthetic zero
marked with "error": true adds no coverage. JUnit reports grading
errors as failures and attempts with only abstentions or no evaluators as skipped.
Use version: "rubric-1" on each custom Eval.evaluator/3 used by a baseline
gate. Advance it whenever scoring behavior changes. Use the same option on
Eval.tool_called/2 for argument filters, Eval.judge/1 for opaque reviewer
configuration, and Eval.Case.new/3 for opaque case setup. Eval.Online
can use the evaluator's version when the queue's :version is omitted.
Run your baseline target with the versioned suite and save the report.
The paired comparison excludes changed and unverified cases. It uses
emitted grades and keeps target failures. A grading error excludes the
whole attempt, even if another evaluator issued a grade. An enabled
mix exagent.eval --baseline gate exits 2 if no comparable pairs are
available. Use --no-fail-on-regression to run the absolute pass-rate gate
on its own. It also exits 2 if the suite contains no emitted grades or target errors.
Programmatic callers should handle :no_comparable_cases and
ungraded_cases.
Testing guide
Read reliability and simulated turns in Eval reports
Read report JSON v1 with Eval.Report.from_map/1. The report stores
suite and case reliability, simulated-user usage and stop reasons.
Use summary.reliability[k].pass_all_k for pass^k and
summary.case_reliability[name][k] for case-level metrics. The in-memory
suite summary retains pass_hat_k as an alias. Use --min-pass-all to
gate on pass^k in replay CI. Supply --min-pass-rate explicitly when a
job also requires a minimum overall pass rate.
Testing guide
Turn a production incident into a regression
For a C7 turn with retained evidence, implement the suite's optional
capture/1 callback and run mix exagent.eval.capture --run ID --suite NAME.
The paired case and cassette use the current Eval formats. Keep both files
in the suite's fixture directory.
Capture recipe
Use Eval.Case.from_run/2 when building cases from settled run terminals.
Supply an explicit redactor and pass the intended answer as expected:.
For a C7 summary, pass the authorized prompt as input:. Record a cassette
For a C7 summary, pass the authorized prompt as input:. Record the cassette
against a deterministic test harness with tool substitutes. Testing guide
Replay misses in evaluation reports
An unmatched or ambiguous cassette request exits 2. Read error.type
with value "fixture_miss" or "fixture_ambiguous" in the attempt row for
a target request. Read the optional scores[].diagnostic with the
corresponding type for a grading request. JUnit puts the type in <failure>. The text
report and stderr identify the case and attempt. They suggest
mix exagent.eval --record-missing for a miss and mix exagent.eval --record
for ambiguity.
Replay in CI
Evaluation reviewers
By default, text and map reports retain case labels and omit evaluator reasons. Update CI readers that depended on that detail. Opt in only for an output that can contain review content.
| Previous CI use | 3.0 adoption |
|---|---|
Read evaluator reasons from Eval.Report.format(report). | Use Eval.Report.format(report, include_content: true) for detailed text. |
| Export evaluator reasons with CI results. | Match {:ok, map} from Eval.Report.to_map(report, include_content: true). Use Eval.Report.from_map(Jason.decode!(json)) when reading the exported JSON. |
Update scripted Eval reviewers to put their reasoning first and finish with
VERDICT: PASS or VERDICT: FAIL on its own line. Existing label-first
reviewers can use Eval.judge(reasoning: false, ...). The output validator
and approval judge continue to consume label-first replies.
Online sampling is opt-in. To add it, offer the target's acknowledged
terminal to ExAgent.Eval.Online with a trusted scope and evaluator version.
Move evaluation off the terminal path if a callback currently grades inline.
For text grading, explicitly authorize each text field you pass. Existing
offline evaluation suites can continue to use the same evaluators.
Offer the native Session.chat/4 reply as {:session, reply}. Use the
runtime namespace as the scope for Server terminal Events. C7 uses the
authorized source Store's namespace.
Include "cancelled_before_start" in result telemetry consumers that
enumerate terminal statuses.
Online evaluation
Durable evaluation exports
Update each Eval.Online exporter to acknowledge dispatch with :ok.
Map successful HTTP statuses to :ok and failures to {:error, reason}.
A raw {:ok, response} leaves delivery unconfirmed. Listen to
[:exagent, :eval, :online, :delivery] for :dispatched and
:delivery_unconfirmed, correlated to the grade by :id. Use
:discard to count admitted samples that yield no published grade.
The event uses reason: :delivery_unconfirmed when an export claim fails or
times out. The queue keeps that identity in its bounded duplicate window.
Consume :projection_version in telemetry and
exagent.evaluation.projection_version in the LogRecord as the ExAgent
projection version, independently of the evaluator version.
OTLP callback
For an existing exagent_jobs table, apply the
unified migration.
The migration adds the reservation index and preserves existing job rows
and export marks. Upgrade all collectors for the same grading worker
together. Rename the queue option :delivery to :grading_backend.
Use the same effective evaluator version in the queue and in
Online.Durable.resolve/5. When the old queue used an explicit
:version, supply it at resolution too. This keeps the identities of
existing job reservations. Use the tenant as the queue's :scope and
the grading worker's namespace. Configure store: Jobs.Durable.store(source)
for a source Jobs worker on the same tenant.
Use a refreshed expiry for new evaluation identities. A repeat offer uses the first reservation and its original deadline. A result from a candidate that already exported its grade can have an empty marker. When reoffering such a result during upgrade, deduplicate at the receiver by evaluation ID. Durable evaluation
Configuration errors raise before IO
ExAgent 3.0 checks configuration in one place. Constructors and the run
boundary accept options only as a keyword list with known, unique keys and
every required key. They also check each value that can be known without
running. A failure raises ArgumentError before any model, tool, store or
process IO, and the message names keys, never their values. Run the
application's tests: every error below appears on the first call that builds
or runs the configuration.
| 2.x | 3.0 |
|---|---|
ExAgent.new(output_type: Schema) | ExAgent.new(output: Schema); :output_type is an unknown key. |
agent.output_type, agent.settings, %{agent | output_type: x} | agent.output, agent.model_settings, %{agent | output: x}: the struct fields have the option names; the old fields raise KeyError. |
run(agent, prompt, usage_limits: limits) returned {:unsupported, {:run_option, :usage_limits}} | Pass a valid %UsageLimits{} to tighten the limits for this call. The option also works with direct streaming and resume. |
Invalid permissions, deadline, max_concurrent_requests or estimate_cost returned :invalid_execution_scope_options | ArgumentError from run/3, resume/3 and their streams. |
Invalid usage_limits, retention bytes, output mode or capability in ExAgent.new/1 failed when the run started | ArgumentError from ExAgent.new/1. |
:approve with :continuation ignored the callback | ArgumentError; decide persisted requests with ExAgent.Continuation.decide/4. |
resume/3 without :continuation returned :invalid_continuation_configuration | ArgumentError naming the missing key. |
Some constructors raised KeyError for a missing or unknown option (Tool.new/1, Judge, Advisor, Memory.tool/2, Models.Fallback) | ArgumentError naming the keys. |
| Message, participant, event, run context, Server snapshot and skill constructors could ignore a misspelling or choose one repeated key | Supply known keyword options once. For example, use Message.new_response(parts, finish_reason: :stop). Skill directory loaders take :tools and derive the path from the directory argument. |
Tool.OutputLimit, Tool.RepeatGuard, Models.Fallback and ModelSettings accepted maps, streams or unknown fields | Keyword lists with known keys; ModelSettings.new/1 still accepts a map or a settings struct. |
Eval.run/3 warned about repeated evaluator names and pooled their scores | ArgumentError; give each evaluator a distinct :name. |
Models.ReqLLM.new/1 accepted any value until the first request | Types and enumerations are checked in new/1, offline. |
prompt_cache on a provider without caching (Google, Groq…) returned {:unsupported, :prompt_cache} from the first request | ArgumentError from Models.ReqLLM.new/1, also for an option the provider cannot honour. |
%Compaction.Capability{compactor: Compaction.Summary, opts: opts} | Compaction.capability(Compaction.Summary, opts); the struct is private. |
Memory.preload/3 concatenated into :instructions stayed fixed at the first Server turn | Use Memory.capability(memory, scope: scope, preload: true) to refresh notes as user data each attempt. Remove the memory tool from :tools when installing the capability. |
MCP.Client.start_link/1 returned {:invalid_option, key} for a missing :command or a repeated key; stdio accepted :protocol_version | ArgumentError, also for another transport's key. There is no :protocol_version option. |
Stdio requested MCP 2024-11-05 and accepted any initialize result | It requests 2025-06-18 and accepts 2025-06-18, 2025-03-26 or 2024-11-05. A result without a capabilities object or a serverInfo with string name and version gives :invalid_initialize; another revision gives :unsupported_protocol_version. |
A 2.x record with bound MCP stdio tools restored with continuation_binding: %{endpoint: e, principal: p} | Start the client with continuation_binding: %{endpoint: e, principal: p, protocol_version: "2024-11-05"}, using the original endpoint and principal references. Rediscover the tools with this client and rebuild the agent before resuming. The 2025-06-18 default changes the tool fingerprint. |
Messages changed to one format, for example
unknown or duplicate Models.Fallback options: [:models] instead of
duplicate Models.Fallback option: :models. Match the exception type, not its
message. RunError now reports only facts known while running; the
catalogue lists
its reasons. A host that turned the replaced RunError reasons into a user
message should validate its configuration at startup instead.
For Store.Postgres and Memory.Postgres, pass Repo or {Repo, []} for
the default table. A custom table takes exactly one option, as in
{Repo, table: "archive"}. If the table name comes from the environment,
check that it is set before constructing this tuple.
Preload memory at user authority
Memory.capability/2 keeps preload: false as its default. A view takes a
tool call and a follow-up model request. Explicit preload: true or a list
without :mode now supplies notes as a user part. The byte budget covers
the complete block. Review small budgets if they previously held a whole file.
Move deliberate system guidance to a separate operator-managed scope and set
read_only: true, preload: [mode: :system].
Keep the original definition and policy references and tool options for
pending C7 records. For earlier previews that implicitly preloaded notes, set
preload: true explicitly to continue reading them on fresh requests at
user authority. Keep preload: false for tool-only definitions. Pending
records with a writable memory tool still require that tool when resuming.
An explicitly authorized model retry uses its captured request, including
the original role on an older intent. Reconcile that intent if you need to
avoid resending its captured content.
Agent C7 frames with memory_preload bind the preload policy even when Memory
is absent. The policy binds presence, mode, byte limit, priority order and each
handoff phase. Keep the matching configuration to resume. Use a new host
definition version for future turns that change the policy or the scope's
writers. The field is part of the Store format level 1 baseline.
A legacy C7 frame without memory_preload can resume after adding Memory if its
existing definition, tool and policy checks pass. New model requests use the
current preload configuration. An authorized retry still uses its captured
request. Published 2.x definitions can keep their existing tools and manually
composed instructions.
Memory.preload/3 counts the entire rendered block against :max_bytes.
Increase a budget sized for file text alone if you need the same content.
A budget too small for the framing returns an empty string.
Use preload: false for durable Composition and Flow. Re-record fixtures
that captured the previous projection. Fixture matching includes role and
rendered notes.
Capability v2: phase hooks and a package
Memory.Postgres disables Ecto query logging and query telemetry for reads
and writes. Move command counters to [:exagent, :memory, :command].
Capabilities keep the :capabilities option but have a new shape. Every
callback is optional, hooks receive an ExAgent.ModelRequest or the part
they act on instead of the run state, and they return {:ok, value} or
{:error, reason}. use ExAgent.Capability raises CompileError for a
module that still defines a 2.x hook, and ExAgent.new/1 raises
ArgumentError for one that exports it, so no 2.x hook stays silently inert.
| 2.x | 3.0 |
|---|---|
before_model_request(cap, state) returning the state | before_model_request(cap, req, ctx) returning {:ok, req}; write req.messages, req.tools, req.settings or req.model. |
state.request_messages || state.messages | req.messages (the projection); the canonical history is req.history. |
state.params.function_tools, state.agent.tools | req.tools (offered) and req.inventory (every tool of the agent). |
state.run_step, state.params.final_step, state.deps, state.execution_scope | req.step, req.final_step, ctx.deps, ctx.execution_scope. Counters and budgets are no longer visible. |
after_model_request(cap, state) editing the last message | after_model_request(cap, response, req, ctx) returning {:ok, response}; only parts may change. |
before_tool_execute(cap, ctx, call) returning the call | before_tool_call(cap, call, ctx) returning {:ok, call}; only args may change. |
after_tool_execute(cap, ctx, call, {:ok, part} | {:error, e}) | after_tool_call(cap, part, call, ctx) returning {:ok, part}; only content may change, and the hook sees only confirmed returns. |
| After-hooks ran in list order | They run in reverse order. List Tool.OutputLimit before capabilities whose after_tool_call/4 needs the full result. |
A hook added a tool to params.function_tools | Return it from the capability's tools/1; a hook may offer only inventory tools, otherwise {:capability_failed, mod, :before_model_request, {:unknown_tool, name}}. |
tools: Search.tools(search) plus capabilities: [search] | capabilities: [search] only; the search tools join agent.tools. |
Skills.tools(skills, opts) plus Skills.capabilities(skills) | Skills.capabilities(skills, opts); the gate carries the skill tools. |
{:tool_hook_failed, name, reason}, :tool_call_identity_changed | {:capability_failed, module, hook, reason}; changing a read-only field gives the reason {:read_only, field}. |
| A hook changed usage, finish reason, call identity or a return's status, and the runtime silently kept the original | {:capability_failed, module, hook, {:read_only, field}}. |
on_model_request_error/4 ran inside the failed request's span and its result was the telemetry reason | It runs after the request's span and [:exagent, :model, :request, :exception] close, whose reason is always the request's own failure. It may now return {:recover, response}. |
compact(messages, opts) and Summary.compact/2 | compact(messages, opts, ctx) with ctx = %{deadline, params, run_id, step}; optional validate(opts). |
Compaction.Summary.capability(opts), %Compaction.Capability{} | Compaction.capability(Compaction.Summary, opts); unknown options raise ArgumentError. |
Two tools with the same name but different definitions across :tools and
the capabilities' tools/1 raise ArgumentError in ExAgent.new/1; an
identical tool is kept once. A capability that provided instructions through a
hook can return them from instructions/2, evaluated once per run attempt and
placed in the request projection, never in the history. Computed instructions
that need no capability can be functions in the agent's :instructions, which
run the same way before capability instructions. A failing compactor is
reported by [:exagent, :compaction, :stop] with status: :error.
Persisted records do not change: tool fingerprints use the same
definition/1, so a 2.x record whose tools came from Search.tools/1 restores
unchanged, and the persisted tool evidence code stays "tool_hook_failed".
Typed streams and Event v2
ExAgent.run_stream/3 now yields {type, data} elements with explicit keys
and still ends with one terminal, {:result, result} or
{:error, %RunError{}}. Steps, model responses, tool calls and approvals are
elements too, so match the ones you need and keep a catch-all clause:
ExAgent.run_stream(agent, prompt)
|> Enum.each(fn
{:text_delta, %{text: text}} -> IO.write(text)
{:tool_call_finished, %{return: return}} -> IO.inspect(return.status)
{:result, result} -> IO.inspect(result.status)
{:error, error} -> IO.puts(Exception.message(error))
_element -> :ok
end)| 2.x | 3.0 |
|---|---|
{:ok, request_id} = Server.send_message(server, prompt) | Match {:ok, %{request_id: request_id, run_id: run_id}}. Match both IDs on the root Event v2 terminal in the same namespace and conversation. |
{:delta, text} | {:text_delta, %{step: step, text: text}}; thinking is {:thinking_delta, _}. |
| The terminal followed the deltas | Lifecycle elements come before it: :run_started, :run_step_started, :model_response, :tool_call_started, :tool_call_finished, :approval_requested and :run_step_finished (outcome). Find the terminal by its type. |
Server.stream(server, prompt, opts) | Server.send_message(server, prompt, [stream_text: true] ++ opts) and the :text_delta events. It queues behind an active run or a pending continuation instead of returning :busy or :continuation_pending. |
deps: %{on_text_delta: fun, on_tool_call_delta: fun} | Consume run_stream/3 or Server events. Tool-argument previews need tool_call_deltas: true; the callbacks are no longer called. |
:on_event in a delegation or composition leaf | Removed; observe the root run's stream or Server events. |
Event version: 1 | version: 2 with run_id, root_run_id and parent_run_id in the envelope. |
:tool_call_finished payload.success | payload.status == :succeeded. |
Preview name and Event tool_name | tool shows a declared name or "unknown_tool". A preview fragment without a name has tool: nil. |
Tool Event tool_call_id or approval call_id | Correlate events and Runtime.pending/2 with the invocation's call_ref. Fetch the original request with Server.pending/2 or Continuation.pending/2 for decisions. |
:approval_requested payload.attempt_id | payload.continuation.attempt_id. |
:run_finished payload.messages and payload.steps | payload.new_messages and payload.run_step; read the conversation with Server.history/1. |
| Event consumers that select an output schema | Accept the optional payload.output_name on Event v2 :run_finished. It is the declared branch and survives Event.strip_content/1. |
:run_step_finished only on success | Once per step, with outcome :continued, :retry, :succeeded, :paused or :failed. |
| Queue and run events had no replay | Server.events_since(server, cursor) from a bounded event_buffer; {:error, {:cursor_expired, current}} means reload state. |
Events keep carrying content for your UI. Call ExAgent.Event.strip_content/1
before sending one to logs or an external bus. It clears envelope metadata by
default. If the destination needs a host field, pass its exact atom or string
key, for example ExAgent.Event.strip_content(event, metadata_keys: ["release"]).
When exporting recorded events that predate the projected tool and
call_ref fields, their legacy names and IDs disappear from the export.
Trusted message parts, history and continuation records retain the original
provider IDs.
For the dashboard companion package, put redactors and inventory callbacks in
a named entry under config :exagent_dashboard, :pages on the server.
Reference it with {ExAgent.Dashboard, config: :operations} in the router.
Enable the run inspector
Set inspector: true in the named dashboard page configuration and enable
:conversations or :continuations with the host's namespace callback.
The candidate inspector opens from the inventory row or live conversation
detail. History remains off with content: false. To show redacted history,
set content: {:redact, {module, function, args}} and return bounded text or
nil for the inspector's :history, :args and :content values.
Applications that need the C7 timeline directly can pass timeline: true
to Continuation.get/3 with the authorized Store scope.
Frame3 child rows include a :delegation_path with opaque call references.
Consumers matching on row kinds should handle :deferred entries for child
external waits, timers and input, including MCP form rounds. These rows
show the retained pause state and keep form bodies private. The optional
child binding on new resolution receipts uses Store format level 1. Upgrade
the readers and writers of a shared journal together. Existing records
remain readable and can show a resolution against a child when its binding
is retained.
Dashboard setup
To add actions to saved timelines, configure the candidate
:inspector_actions option with the host's :authorize callback. Enable
:fork to save a branch through a selected settled turn. Configure
:export with the Eval target and a mandatory redactor to save a supported
root-only C7 agent run as a case and cassette on the dashboard node.
Both actions are off by default and work with content: false.
An unconfirmed effect blocks a cut through its run, including effects in
delegated children.
Dashboard action setup
Telemetry and traces without content
| 2.x | 3.0 |
|---|---|
[:exagent, :run, :start] metadata prompt | Removed; take the prompt from your application or from :run_started events. |
| Run events without lineage | run_id, root_run_id, parent_run_id and attempt_id on start, stop and exception. |
Atom keys such as :cached_tokens in run-stop metadata.usage.details | Match string keys such as "cached_tokens". The enclosing metadata and usage fields still use atoms. |
[:exagent, :tool, :stop] without run or call IDs | Adds run_id and call_ref. An undeclared tool has tool_name: "unknown_tool". |
[:exagent, :compaction, :stop] without the agent | Adds agent. |
| No per-request event | [:exagent, :model, :request, :start | :stop | :exception]; token measurements appear only when reported. |
OTel profile exagent.gen_ai.v1 (revision b5d8440) | exagent.gen_ai.v3 at the v0.1.0 tag. Dashboard migration |
Spans exagent.run, exagent.model, exagent.tool | invoke_agent {agent}, chat {model}, execute_tool {tool}. |
| Raw provider tool call IDs in span attributes | Join with tool events by the opaque exagent.call_ref. |
exagent.usage.reasoning_tokens on requests | gen_ai.usage.reasoning.output_tokens. |
Redactor fields :input and :output, returning a binary | :system_instructions, :input_messages, :output_messages, :tool_arguments, :tool_result, returning data in the semconv message schema. |
Attributes exagent.content.input and exagent.content.output | Select the new JSON keys in Content capture. |
Update dashboard filters on reason to include the typed Store, quota and
handoff failures that now have their own series. For application events,
use :telemetry.execute/3 with the application's prefix. ExAgent's emitter
is internal. Metric definitions
This handler sends one sample for each reported cache count. The duration is in native time units. A missing key means unknown, so skip the sample. A reported zero still produces a sample. Attach once with your handler ID and metrics receiver, then detach with the same ID when the receiver stops.
defmodule MyApp.RunMetrics do
def handle(
[:exagent, :run, :stop],
%{duration: duration},
%{root_run_id: run_id, usage: %{details: %{"cached_tokens" => count}}},
receiver
) do
send(receiver, {:run_cache_tokens, run_id, duration, count})
end
def handle([:exagent, :run, :stop], _measurements, _metadata, _receiver), do: :ok
end
:ok =
:telemetry.attach(
handler_id,
[:exagent, :run, :stop],
&MyApp.RunMetrics.handle/4,
metrics_receiver
)Rewrite dashboards and trace queries on the span and attribute names. A
redactor now matches a field and returns the same kind of data, for example
fn :tool_result, _value -> {:ok, "[withheld]"}; _field, data -> {:ok, data} end
or :drop; see Observability.
Query Fallback traces by request or attempt
For logical request counts and totals, query exagent.model_request and its
exagent.usage.* and exagent.cost.* attributes. Group the child
chat {model} spans by parent or exagent.model_request_id for provider
attempts. Include leaves with boolean exagent.attempt.dispatched=true
in attempt counts. A false value records a leaf that stopped before the
model callback. Expect multiple client spans after a retry and zero for
a fixture replay. A direct live call has one chat {model} span. Direct
fixture replay uses the internal exagent.model_request span.
Fallback span hierarchy
Measure model attempts
Keep the exagent.model.request.* series for admitted logical requests. Use
exagent.model.attempt.* for adapter dispatches and outcomes, including each
Fallback retry and leaf. A replay contributes only to the logical request
series. Filter source: :adapter to exclude the scripted TestModel from
attempt dashboards.
For logical requests, read model as a bounded string of up to 256 bytes.
An invalid model name maps to "other" as in the attempt series.
Correlate starts and stops by their attempt telemetry_span_context. Group
them by model_request_id for the logical request. Token sums may include
known subtotals under usage_status: :partial. Use the ReqLLM bridge's
gen_ai.client.* series for ReqLLM-specific measurements such as chunk timing.
Report each scope as its own total to avoid counting overlapping samples twice.
Attempt event and metric scopes
Move dashboards to GenAI v0.1.0
Filter ExAgent spans by exagent.profile=exagent.gen_ai.v3. The revision
attribute contains d0e74ba6c48bcc4ded473b1828a8212f06b23753.
Update selectors and units before queries cross the deployment boundary.
GenAI v0.1.0
| Previous selector | Query on 3.0 |
|---|---|
Workflow roots grouped under invoke_agent | Filter gen_ai.operation.name=invoke_workflow and group by gen_ai.agent.name, the Flow or Composition definition ID. Leaves use invoke_agent. |
| Chat spans as a proxy for request count | Count exagent.model.request.* for logical requests, or exagent.attempt.dispatched=true for adapter attempts. Join the span's exagent.attempt.id to attempt Telemetry's telemetry_span_context. |
| Compaction span counts | Filter inference spans by gen_ai.conversation.compacted=true to count calls that used a proven compacted projection. The exagent.compaction diagnostic still measures compactor work. |
gen_ai.tool.call.id for ExAgent tool joins | Use exagent.call_ref. A withheld result still carries exagent.tool.content_withheld=true. |
gen_ai.client.operation.duration | Use gen_ai.client.inference.duration for inference and gen_ai.client.embeddings.duration for ReqLLM embeddings. Enable native workflow and tool histograms with OpenTelemetry.new(metrics: [...]). |
gen_ai.client.token.usage by gen_ai.token.type | Query gen_ai.client.inference.operation.input_tokens and gen_ai.client.inference.operation.output_tokens separately. The bridge uses gen_ai.client.embeddings.operation.input_tokens for embeddings. All use {token}. |
gen_ai.client.operation.time_to_first_chunk and gen_ai.client.operation.time_per_output_chunk | Use gen_ai.client.inference.time_to_first_chunk and exagent.req_llm.stream.estimated_seconds_per_output_token from the bridge. The estimate is per token. |
JSON in the gen_ai.* content attributes | Point opt-in mappings at exagent.content.system_instructions, exagent.content.input_messages, exagent.content.output_messages, exagent.content.tool_arguments and exagent.content.tool_result. |
For throughput use the inference duration histogram's count. The token histograms omit unavailable totals, including stock ReqLLM zeros without evidence. Native metrics can record an evidenced zero. Compare only the appropriate metric scope. When native metrics own a traced attempt, the bridge adds streaming timing for it. Metric setup
Update exporter content filters for the new JSON keys. The Erlang span API
currently accepts scalar values and homogeneous arrays. The tagged GenAI
message attributes require nested values. ExAgent's opt-in capture continues
using its bounded, redacted JSON. The integrated bridge uses
exagent.req_llm.content.* for its separate standalone ReqLLM opt-in.
Privacy before export
Link paused and resumed traces
The Store format level 1 baseline supports the optional execution.pause_trace
pair written by OpenTelemetry.new(link_continuations: true). Earlier records
restore without the pair. Custom atomic Stores must round-trip it with the rest
of the journal. The same SQL schema supports it in inline and segmented layouts.
The claim, cancel and expiry transitions remove the pair. Enable the option on
both attempts to export a link.
Traced attempts
Error reasons and outcome statuses
Each error below now has one reason across models, transports and entry points,
and workflow outcomes use the run statuses. Update case clauses and rescue blocks:
| 2.x | 3.0 |
|---|---|
{:max_tokens_exceeded, m}, {:content_filter, m}, {:incomplete_model_response, f} and ReqLLM's {:model_request_failed, %RequestError{reason: {:incomplete_response, f}}} | {:incomplete_response, f} for every model, with the response in partial.pending_response, never in partial.messages. |
{:model_request_failed, reason} with a bare atom, tuple or exception | {:model_request_failed, %RequestError{reason: reason}}; provider: nil when ExAgent wrapped it, :test for Models.Test, :fallback for Fallback's own failures. |
:continuation_target_mismatch, :continuation_routing_mismatch, :continuation_mode_mismatch | {:continuation_mismatch, :target | :routing | :mode}; Fallback skips all three. |
A persisted run that failed validate_resume/4 ended with the callback's reason (a RequestError or a bare term) | {:model_request_failed, %RequestError{}}, as for a request; :model_continuation_preflight_required and :invalid_model_continuation_preflight are unchanged. |
Composition and Flow status: :completed, steps :completed, branches "completed" | :succeeded and "succeeded". Eval no longer accepts :completed. |
Server.abort/2 reason :aborted | :cancelled, as for a stopped stream. |
rescue ExAgent.UnexpectedModelBehavior around run!/3, with error.error | rescue error in ExAgent.RunError (error.reason, error.partial), and ExAgent.RunPaused (error.result.continuation) for a pause. |
{:unexpected_model_behavior, {:output_retries_exhausted, e}}, {..., {:tool_retries_exhausted, name, e}} | {:output_retries_exhausted, e}, {:tool_retries_exhausted, name, e}. |
run/3 accepted :on_event, :run_id, :prepend_instructions, :parent_context, :observability_operation | ArgumentError. Use run_child/4 for nested runs and Server or run_stream/3 for events. |
run_child/4 returned {:error, :continuation_child_descriptor_required} and dropped :run_id or :execution_scope | {:error, %RunError{reason: :continuation_child_descriptor_required}}; those options raise. |
Composition and Flow :step_options, and the options of a :delegate_definitions loader, accepted :on_event, :prepend_instructions, :permission_floor and :permission_floors | Only run/3 options, with its value rules: invalid workflow options raise ArgumentError and invalid loader results give :invalid_delegation_definition. Observe steps with :on_progress. |
MCP.Client.start_link/1 returned {:invalid_option, k}, :invalid_http_configuration or :invalid_mcp_continuation_binding | ArgumentError naming the key. |
Stdio JSON-RPC error map; HTTP :invalid_jsonrpc_response, :unsupported_tool_content; {:invalid_response, e} | {:jsonrpc_error, code}, :invalid_jsonrpc, :invalid_tool_result; a mapping failure is :invalid_tools, :invalid_tool_result or :invalid_jsonrpc. |
Two status vocabularies remain, for different things. ExAgent.Result,
ExAgent.Coordination.Result and workflow steps report a run's outcome:
:succeeded, :paused, :failed or :cancelled. A continuation record's
status (:pending, :ready, :completed, :failed, :denied, :expired,
:cancelled and others) describes the stored record's lifecycle, as listed by
ExAgent.Continuation.get/2 and list_runs/2.
Records persisted by 2.0–2.3 keep restoring: none of these reasons is stored,
and records keep their own "completed" states. A Flow result saved by 2.x
keeps the "completed" branch statuses it stored.
Handle provider quota deadlines
Match %RunError{reason: :deadline_exceeded} when an outstanding quota
reservation, authorization or settlement reaches the run deadline. This
includes the case previously reported as {:rate_limited, key, :unknown}
when a queued reservation expired. Keep matching {:rate_limited, key, wait}
for immediate quota refusals. Use the run's :deadline option to bound
execution through a host runtime. The caller-wait option :timeout on
Server.chat/3 or Session.chat/4 controls reply delivery.
A deadline can follow dispatch. Read the reported usage and any diagnostic
reply from error.partial. Reconcile an open C7 intent before resuming.
Provider quotas
Read withheld tool returns
Tool-output guards withhold the return until the verdict. A veto or a failure
to confirm the verdict leaves a fixed notice in the receipt. The receipt keeps
its effect status and available usage. Update partial-result and stream
consumers to check return.content_withheld before showing a result. A tool
may report :succeeded even though the guardrail stopped delivery and the
run failed. Use the invocation reference to correlate the effect.
Event v2 publishes content_withheld and usage in :tool_call_finished.
Keep the flag when consuming content-free events. A tool span records the
flag as exagent.tool.content_withheld and omits the result attribute.
Frame3 keeps the raw outcome and verdict evidence needed for reconciliation.
Older guarded records retain their saved status and fixed notice. The change
requires no database migration.
Limit parallel tool calls
Set max_concurrent_tools: to a positive integer on ExAgent.new/1.
The same option on a run, stream, Server turn or workflow step overrides the
agent default. A continuation retains the run override. Pass a new value on
resume to update it. The default still uses the online BEAM scheduler count.
Version guardrail policies for C7
Root agent continuations now support Guardrail.tool_input/2,
Guardrail.tool_output/2 and Guardrail.output/2. Mark a code or configuration
change with a new continuation :policy version. Keep the old policy and
guardrail inventory available for outstanding runs. Resume detects a changed
binding with :continuation_guardrail_policy_changed. Existing 2.x and
candidate records restore under their original definitions. Enable the new
stages on a fresh run.
Persisted approval edits are checked against tool-input policy on resume,
before dispatch. A settled tool or output veto ends at :failed. The
effect journal retains confirmed outcomes. Chat pages carry forward only
accepted turns, including after restart.
C7 handoff destinations support their own guardrails. Set
Handoff.new(policy: %{"id" => id, "version" => version}, ...) to version
a destination independently. Otherwise, version its rules with the root
continuation's :policy reference at every depth. Destination guards are
part of the Store format level 1 baseline. Earlier Frame 3 records with active runs
resume under their original catalog. A Server can restore a settled
legacy handoff and use the new policy on a fresh turn.
Continuation.get/2 now returns the saved :definition, :policy and
:handoff_policies. Use these references to load the matching catalog
entry when resuming. The destination map is empty on older journals.
Tool guards with durable delegation or custom tool rehydration still return their typed admission errors. Durability guide
Enable reviewed stream drafts
Add Guardrail.stream/3 to the agent's existing capabilities. Keep final
delivery policy in Guardrail.output/2. To display drafts under that policy,
use ExAgent.Chat or check payload.stream_checked? === true on root
:text_delta and :commentary_delta events from the conversation owner.
On remount, use its history page with include_draft: true. Regenerate the
chat view to show reviewed drafts while the final guard runs.
Stream guards are part of the Store format level 1 baseline. Their policy inventories include the window limits and can persist a stream veto in Frame 3. Resume active records with their original policy and window settings. Enable the stage on the next fresh turn and version changes to its check. Older inventories and records retain their existing representation. Stream window guide
Approvals and continuation administration
Persisted approvals have one review inbox, one reply and per-call decisions. Update administrative code:
| 2.x | 3.0 |
|---|---|
Continuation.decide(store, id, :approve | :deny, record_id:, revision:, approval_id:, payload_hash:, operation_id:, …) | {:ok, items} = Continuation.pending(store, id), then Continuation.decide(store, request, decision, actor:, authorize:). The ID form takes only :cancel and :expire. |
A denial ended the run as denied | On resume the tool return has status :denied and the model sees the reviewer's message, including for pending 2.x records. Pass :cancel to decide/4 with the approval request if the run should stop. |
{:ok, %{record: record, receipt: receipt, replayed: r}}, then record["execution"]["state"] | {:ok, %{status: s, continuation: ref, pending: n, revision: rev, replayed: r}}; pass diagnostics: true for :record and :receipt. |
get/2 was :approved after recover or reconcile | :ready; :approved means the last write was a decision or a supplied result. |
:record in Continuation.get/2 or Server.continuation/1 | Read operator metadata by default. Use Continuation.get(store, id, diagnostics: true) or Server.continuation(server, diagnostics: true) for the body. |
Server.decide(server, decision, opts) by ID | Server.pending(server), then Server.decide(server, request, decision, opts), or Server.decide(server, :run, :cancel | :expire, opts). |
Reading record["execution"]["effects"] | Read get/2 :effects for journal metadata, including each effect's owning :leaf when known. |
| An unknown, duplicate or missing option returned an error tuple | ArgumentError before any read or authorization. |
| A lost reply from an earlier run replayed its receipt | :conflict once the next start compacted that run's receipts; read get/2. |
list_runs/2 entries with :pending_approvals | :pending (open approvals plus deferred calls). |
list_runs(store, %{status: s, limit: n, after: c}) and prune_page(store, before, actor, %{limit: n, after: c}); a bad query returned {:error, :invalid_scan} | Keyword options: list_runs(store, status: s, limit: n, after: c), prune_page(store, before, actor, limit: n, after: c); an unknown key or invalid value raises ArgumentError. |
:runs from list_runs/2 and :results from prune_page/4 | Both return %{items: items, cursor: cursor}. Pruning items contain :id and :outcome (:deleted or {:error, reason}). |
Store.scan_records/2 with a physical map and cursor | Use Continuation.list_runs/2 for operator pages. Start from the first page after upgrading. Keep subsequent cursors with the Store, namespace and filter or retention query that issued them. |
After a cancel or expire left an external effect uncertain, reconciling it made the run :ready again, also past its deadline | The run ends :cancelled or :expired (:expired past its deadline) with no continuation, and retry_effect/4 returns :invalid_transition after a cancel or expire. |
In durable compositions, deny, cancel and expire returned :unsupported_structural_operation or :invalid_frame10_transition | Deny is per call and cancel and expire are per run. reconcile_model/5 accepts model evidence after recovery. reconcile/5 and retry_effect/4 return :unsupported_operation. |
A durable Server conversation ended in :receipt_limit after 1024 lifetime receipts | Receipts are bounded per run; the next turn of a 2.3 record at the limit starts. |
Decisions also accept {:approve, args: map} (an edit, with the offered tool as
tool:) and {:deny, message: text}; the authorizer sees :edit apart from
:approve. The same values work as the result of the one-shot :approve
callback. A tool can return {:defer, meta} to pause a durable run until
Continuation.supply_result/4 records its result; see
Defer a tool call.
Records persisted by 2.0–2.3 keep restoring, pending approvals included. A record that 3.0 writes with an edit, a denial message or a deferral is rejected by 2.x readers.
Update the persisted approval authorizer
In authorize.(actor, operation, target), the third argument for
Continuation.decide/4 is a map of fields from the stored run and call.
3.0 removes :payload from this target. Update the policy reads.
| 2.x policy read | 3.0 source |
|---|---|
target.payload["decision"] | Match the second callback argument, for example :approve or :deny. A decision with changed arguments arrives as :edit. |
target.payload["approval_id"] and target.payload["payload_hash"] | request.approval_id and request.payload_hash on the ApprovalRequest from Continuation.pending/2. Pass the request back unchanged. Use target.run_id and target.call_id to identify the call in a policy. |
Tool or arguments read from target.record | Check target.tool_name and target.args for an approval or edit. An edit carries the original arguments in target.original_args and the validated replacement in target.args. For a denial, use target.original_args and target.message. |
| Namespace read from the record | Bind the authorizer to the host's scoped Store and check the actor's grant for that workspace. target.id, target.definition and target.policy can further restrict a grant. |
target.record is diagnostic data. Recovery operations that document a
:payload still receive their proposal there.
For a run with one pending approval, this policy checks the granted workspace,
the review's continuation ID and the order ID. The host authenticates the actor,
loads their permitted order IDs and authorizes access to workspace before
reading the inbox.
alias ExAgent.{Continuation, Store}
alias ExAgent.Continuation.ApprovalRequest
store = Store.scoped(base_store, workspace)
{:ok, [%ApprovalRequest{} = request]} = Continuation.pending(store, review_id)
authorize = fn
%{id: actor_id, workspace: ^workspace, reviewable_order_ids: order_ids},
:approve,
%{id: ^review_id, tool_name: "mark_reviewed", args: %{"order_id" => order_id} = args}
when map_size(args) == 1 ->
if order_id in order_ids, do: {:ok, actor_id}, else: :deny
_, _, _ ->
:deny
end
Continuation.decide(store, request, :approve, actor: actor, authorize: authorize)A grant returns {:ok, actor_id} with a UTF-8 string of 1–512 bytes. Any other
return denies the decision with {:error, :unauthorized}.
Read model retirement warnings
Doctor's JSON v1 may add a model.lifecycle row with status: "warning"
and required: false. If you validate individual rows in CI, allow
warning for this row. Its details identify the model and report
state as retired, retirement_scheduled, deprecated, or
invalid_retirement_date. An invalid date sets invalid_retirement_date
to true and leaves retires_at null. replacement is null when unavailable.
Doctor
Models: one-line form, profiles and reasoning
ExAgent.new(model: "anthropic:claude-sonnet-5-5", tools: tools) now runs tools
and streaming, and OpenAI Responses and Anthropic Messages join the Chat
profiles. One profile: key replaces the two profile keys, and a profile is
selected from the catalogue instead of requested:
| 2.x | 3.0 |
|---|---|
tool_profile: :chat_tools_v1 or :openrouter_chat_tools_v1 | Remove it (profile: :auto selects it from the provider and the declared wire) or pass profile:. A profile that contradicts the catalogue raises. |
output_profile: :chat_json_schema_v1 | Remove it. output_mode: :native works on the OpenAI provider's Chat and Responses profiles and on :anthropic_messages_v1 with catalogue json.schema. Unsupported models raise in ExAgent.new/1. |
reasoning_mode: :none, or nil | :disabled. When omitted, the mode is resolved from the catalogue (:enabled for a model that cannot turn reasoning off) and stored. |
reasoning_effort: :medium | reasoning_effort: "medium", a string from the catalogue's effort.values. |
Buffered total_timeout nil inherited config :req_llm (unbounded by default); stream nil was 60 s | 120,000 ms for both; raise it up to 300,000 or stream. |
| Anthropic rejected tools, thinking and any history with a response | Tools, streaming and signed thinking replay; output_mode: :native uses output_config.format when the catalogue declares json.schema. |
%ModelProfile{} had supports_json_object_output, supports_thinking and default_output_mode; output_mode admitted :prompted and :auto | Those fields and modes are gone; remove them from custom models. The agent option output_mode: :prompted is new in 3.0 and reaches models as :text. |
| A text-only or tool-call history without continuation was native on some profiles | Only a text-only response without continuation is accepted everywhere. Tool calls without one (for example from Models.Test) need foreign_history: :portable. |
Each new response stores continuation version 5 and each persisted run binding
version 2 (Fallback's too), which add profile and typed provider reasoning.
Versions 1–4 and binding version 1 written by 2.x are still read: a run paused
in 2.x resumes in 3.0 when its configuration is unchanged. 2.x cannot read what
3.0 writes, so there is no downgrade.
Preserve prefix-bound reasoning
For signed Claude thinking or GPT-6.2+ Responses reasoning, keep the same
instructions, tool declarations and earlier messages on each request. Append
new turns. Check ExAgent.Model.profile(model).reasoning_binding for
:prefix. A Fallback exposes the constraint when any leaf declares it.
Keep the complete response continuation when saving history. The adapter
records its request fingerprint in v5 message metadata. Existing snapshots
and C7 records still load. A signed block written without this fingerprint
is retired on replay. No data migration is required.
If an in-flight model effect needs an idempotent retry and its signed history
lacks the fingerprint, preflight reports :retry_model_request_changed.
Reconcile the effect before proceeding with that conversation.
Compaction.Summary now defaults to preserving protected exchanges on
these models. Set preserve_signed_prefix: false if you intend to compact
that history. Loading tools in the default mode of Tool.Search or
activating them with Skills.Gate also changes the prefix. Subscribe to
the reset event to track reasoning loss.
Model behavior
For a new conversation or versioned definition, candidate Tool.Search.new(mode: :bridge, deferred: tools)
keeps discovery from replacing the offered definitions. Start with the
chosen mode on the first request. Existing C7 attempts resume with their
original definition. Per-request capability filters can remove deferred
definitions from req.tools in either mode.
Bridge mode
OpenAI IDs that stock ReqLLM routes to Responses (o-series, gpt-4o, gpt-4.1,
gpt-5) now select :openai_responses_v1. Such a model built from the
catalogue in 2.x had no tool profile; with tools it now sends Responses
requests, always with store: false. To keep OpenAI Chat, pass an explicit
model map with extra: %{wire: %{protocol: "openai_chat"}}. A text conversation
saved by 2.x on such a model reports {:continuation_mismatch, :target} under
the new profile: continue it with profile: :text_v1, or send it as portable
history with foreign_history: :portable.
Google models now select :gemini_v1 (Gemini API with tools and streaming)
instead of :text_v1. A Google text conversation saved by 2.x or a 3.0
candidate reports {:continuation_mismatch, :target} under the new profile;
continue it the same way, with profile: :text_v1 or foreign_history: :portable. Remove presence_penalty and frequency_penalty from Gemini
settings: stock never sent them, and they now reject.
To attach audio, use :gemini_v1 with catalogue :audio input and pass a
Base64 file part such as media_type: "audio/wav". Use an exact supported
MIME and keep each clip within 1 MiB decoded. Use
Model.profile(model).supports_audio_input to enable the upload control.
Custom adapters opt in with %ModelProfile{supports_audio_input: true}
when they accept audio. Message and continuation codecs retain the file
part and optional filename. Audio input
Finish pending Chat tool runs that lack endpoint evidence using the original
release and endpoint before upgrading. This includes OpenAI :chat_tools_v1
records with reasoning_mode: nil and no binding, and OpenAI :none or
OpenRouter bindings with "endpoint" => nil. It also applies to paused
approvals and these profiles inside a Fallback. For uncertain effects, use
independent evidence to resolve the original effect before starting a new run
with a new ID. The provider's current URL cannot establish where an earlier
request went.
ExAgent 3.0 uses ReqLLM 1.31. Check estimated budgets against provider charges: a reported USD charge, including zero, takes precedence over the catalogue estimate.
Use tools on more Chat Completions providers
Ollama, LM Studio, vLLM, Groq, DeepSeek, Mistral and xAI Chat Completions
select :chat_tools_v1 under profile: :auto in 3.0. Use output_mode: :tool
or :prompted for structured output. DeepSeek Chat disables thinking for
catalogue reasoning models. A Chat Completions model that requires reasoning
without a qualified off control can continue in text with profile: :text_v1.
Text history saved with the old profile can report
{:continuation_mismatch, :target}. For existing histories and in-flight
continuations, keep profile: :text_v1 on the original model definition.
To start a new run under the new profile with old text history, use
foreign_history: :portable. New tool approvals bind the provider, model,
profile and effective endpoint. Local models and qualification
Account for tool envelope retries
With the ReqLLM tool profiles, a complete JSON object with the wrong
envelope shape can spend one of the run's existing retries. Function
batches use max_retries on each named tool. Batches containing an output
tool use output_retries. A budget of zero rejects the model request on the
first malformed envelope. Fatal JSON and stock argument errors also reject
the request immediately. Live capabilities can recover from a request error.
mix exagent.qualify uses zero retries.
When inspecting or exporting messages, a call marked
metadata["arguments_codec"] == "exagent.raw_arguments/1" carries the
rejected object exactly as received at the adapter boundary. Preserve the
marker and retry message when forwarding history. Upgrade readers and
continuation workers before writing histories that contain the new codec.
Existing histories remain readable with the new reader. Frame 3 restores
these histories with the retry budget already spent. Frame 10/11 rejects the
model request on the first malformed envelope.
Argument envelope
Enable Azure OpenAI and Vertex AI tools
In 3.0, :auto selects the Chat Completions or Responses profile for
Azure OpenAI and the Gemini or Anthropic Messages profile for Vertex AI.
Pin profile: :text_v1 on the original definition when keeping an existing
text history. To start a new run using that history with the new profile,
set foreign_history: :portable.
New Azure approvals bind the resource, deployment and API model. New
Vertex approvals bind the API model, project and region. Resume with
the same destination and supply current credentials through the host
adapter or provider configuration. Use auth_token: or stock ADC for
Vertex tools. Azure, Vertex and Bedrock
Enable tools on Bedrock Claude
:auto selects InvokeModel with :anthropic_messages_v1 for Bedrock Claude
models that declare tool capability. When constructing a Bedrock instance
with api_key:, pass provider_options: [region: region] for InvokeModel
or Converse. Use the original region for an existing InvokeModel
continuation. The one-line form reads AWS_REGION or defaults to
"us-east-1". New approvals bind the regional runtime and API model ID. Pin
profile: :text_v1 to keep using an existing Bedrock text history. To start
a run on InvokeModel with that history, set foreign_history: :portable.
Bedrock setup
Recover a queued cancellation by its admission key
Keep the original key when you need to recover a queued turn after losing its
event cursor. The same key can return either :admitted or
:cancelled_before_start from Server.receipt/3 and from a same-input retry.
Both shapes carry the reserved run and request IDs. A cancelled receipt also
carries the namespace, reason and confirmed receipt revision.
For C7, the Server commits the cancellation against the live admission row
before releasing the queue slot. With ETS or PostgreSQL, the receipt survives
Server replacement until its original expiry. The next owner can read it
even if the run has no continuation record. An ambiguous response to
Server.abort_run/3 can return {:error, :result_unconfirmed}. Read the
receipt or retry the abort with the same run ID. The owner holds that turn
from dispatch while it resolves the cancellation.
The Store format level 1 baseline retains the terminal in the admitted
receipt. A custom Store using turn_admission/4 must
handle the cancellation with the same atomicity as a claim. The bundled
admission reducer handles both actions under the journal lock.
The generated LiveView shows the terminal when it recovers a saved key.
For online grading, pass {:server, reply} with the reply from
Server.receipt/3 to Eval.Online.offer/3. The queue's scope must match
the receipt namespace.
Read cancellation and orderly stop acknowledgements
Use payload.status on :server_request_cancelled for queued, active and
paused turns. Read :cancelled_before_start for a discarded queued turn,
:cancelled for a cancellation and :uncertain when confirmed C7 state
still requires effect reconciliation. An active turn keeps the partial
accounting in payload.partial. Regenerate or update the LiveView reducer
and check payload.persistence before displaying a confirmed cancellation.
Offer the confirmed Server event to Eval Online for active cancellations. For queued work, you can also offer the confirmed keyed receipt after reopening the conversation.
Conversations.stop/3 returns {:error, :result_unconfirmed} if the owner
exits with any live queue cancellation still unconfirmed. Query the original
key using Server.receipt/3 after reopening. The receipt can still show
:admitted. Retrying with that key returns its receipt without replaying
the discarded turn.
Cancel turns by receipt and bound cold activation
Keep the run_id returned by Server.send_message/3 and Server.steer/3.
Pass it to Server.abort_run/3 to cancel that turn by identity. The command
now covers queued and paused C7 turns as well as active turns. Handle
:server_request_cancelled with status :cancelled_before_start for a queued
discard. The admission key identifies the retained receipt. Issue another
turn with a fresh key. After :continuation_abort_conflict, inspect the
current C7 revision. Recover the terminal by key
Handle :server_request_cancelled for paused and resumed C7 turns. Match the
original run and request IDs and read payload.status. Use :cancelled
for a closed turn and :uncertain for a turn that still needs effect
reconciliation. Offer only the settled event to Eval Online. For an
unconfirmed checkpoint, retry Server.checkpoint/2 with the live owner.
The event follows confirmation and carries the original atomic revision.
The CAS keeps the earlier accepted history and removes the unfinished turn
from the snapshot. The effects remain in the journal. The next turn can
start as soon as cancellation and any required reconciliation are confirmed.
When Server.supply_result/4 settles a cancelled turn, a second event with
:cancelled carries the reconciliation revision. Remove automatic
reset/2 calls after cancelling a paused or resumed turn to preserve earlier
history. The C7 continuation record keeps its existing schema.
Cancel an agent turn with a lost model response
Use Server.abort_run/3 with the original run ID. If only model requests
are unconfirmed, the confirmed event now carries payload.status: :cancelled.
Keep accepted messages, remove the provisional turn and allow the queue to
advance. Keep the cost unknown. Reserve the reconciliation state for an
unconfirmed tool or callback.
For an already recovered model-only turn, pass the current record ID and
revision to Continuation.decide/4 with :cancel. A running Server can
also close it with abort_run/3. The Store format level 1 baseline includes
cancelled agent records that retain unconfirmed model intents. Earlier
records restore with the same schema.
Cancellation
Treat {:error, :run_not_active} from Server.abort_run/3 as a signal to
read the turn's outcome. A C7 finish that committed ahead of cancellation
still publishes its usual terminal. Confirmed cancellation partials now
include the model admissions already recorded in the journal. A live Server
can publish an authorized external cancellation or a later reconciliation
that closes it. Match the run ID and the revision in each event.
A restored blocked claim appears in Server.turns/2 with status: :blocked.
Use its original run ID with Server.abort_run/3. A fresh asynchronous send
to a blocked owner now returns {:error, :continuation_pending} before
admission. A repeat with the original key still returns its existing receipt.
Handle conversation activation limits and deadlines
Conversations defaults to 16 distinct cold keys per manager and node
(max_activations:) and 128 waiting callers per key
(max_activation_waiters:, including the first). Match
{:error, {:start_failed, :activation_capacity}} for a new key at capacity
and {:error, {:start_failed, :activation_queue_full}} for a full key.
Both receipts report backpressure before a callback runs. An absent manager
still reports {:error, :unavailable}. The factory_timeout: supervisor child option
defaults to 5,000 ms for option preparation. A caller still waiting then
receives {:start_failed, :factory_timeout}. Tune each limit in the manager's
child options. Use Conversations.whereis/2 to check an unconfirmed startup.
Choose timeout: for the full lookup and activation wait. A retry in
Conversations.call/4 spends the time left on that deadline. Set a separate
timeout on the Server operation inside the callback. With a finite
activation timeout, a host registry adapter's whereis/2 may run in a
separate process.
Runtime guide
Conversation lifecycle
Applications can adopt the local manager per conversation using their existing
Store, namespace and agent ID. Event consumers with exhaustive matching must
handle :server_stopped with reason :idle, :superseded or :stopped. When abort
returns a superseded CheckpointError, reconcile its retained outcome. Runtime
inspection clients now receive integer elapsed milliseconds and attachment counts.
Coordination.handoff(session, to) is removed: call ExAgent.Session.handoff/3,
which also accepts :timeout. ExAgent.Conversations.via/2 raises
ArgumentError for a manager that is not running; resolve the address after
starting it, or use whereis/2, which returns nil.
To opt into model-directed transfer, add an ExAgent.Handoff catalog on the
source. Authorize each generated transfer_to_<id> tool with your existing
permissions. Stream and Server consumers can handle :run_handoff and read
handoff_target from the terminal. Catalog-enabled agents send a bounded
text view of previous turns on new requests. The original messages remain
available to the host.
Root C7 agent runs, Server and durable Jobs can now persist these transfers.
Give their continuation codec support for every destination model. Keep
the saved catalog available until its runs finish. If a pending run used
no catalog, resume it with its original definition before enabling one
for a new run. A mismatch returns :continuation_handoff_catalog_changed.
Update the host definition version for changes to opaque settings and
callbacks. Pass Handoff.tool(destination) when editing an approval.
Frame 3 handoff metadata is part of the Store format level 1 baseline.
Existing records still restore.
Persisted handoffs
Grant audio on a handoff
Add share_audio: true only to destinations authorized to receive clips.
Use the effective model's supports_audio_input to check compatibility.
Account for encoded audio within the destination's view budget. The
portable view now redacts audio filenames. The host history retains them.
C7 catalogs without audio grants retain their fingerprints. Existing records use the saved grant for each transfer, with an absent grant denying audio. A committed transfer retains its saved transcript text, including any audio filename rendered by an earlier reader. Finish pending runs with their original catalog. Apply grant changes on a fresh turn. The Store format level 1 baseline includes the grant-bearing Frame 3 records. Audio handoff setup
Preserve non-token media usage
Readers of usage JSON can accept the optional units object. Each
measurement has value, availability and quality. Audio duration
uses integer milliseconds. Store implementations and cassette readers
should round-trip the object through the existing usage codec. Older
records restore with an empty map. The existing accounting version,
Store migrations and cassette version cover both forms.
Each media result carries usage, including partial evidence when available.
Unconfirmed Media, embedding and rerank tool calls carry their unknown usage
into the run. Read :usage_status and :cost_status for coverage.
Apply token and cost limits to their respective accounting fields. When a
tool supplies an estimated cost, ledger totals retain it with its original
coverage. Pin the media tool configuration and the result store to the
application's continuation definition. After the store's TTL expires
Media.fetch/3 reports an expired reference even when its history remains.
For Anthropic Messages use the same v1 file constructor with :anthropic
and the Files API ID. The selected profile and catalogue must accept the
MIME. Keep the file available to the credentials for the original run
and its resumes.
Media and file references
Update media calls from earlier 3.0 candidates
Match image items as %{data: bytes, media_type: mime, url: nil} or
%{data: nil, media_type: mime, url: url} within Media.Images. The item
type is Media.Images.image(). Stored version 1 media references keep
their JSON keys and Base64 encoding.
Media tools use the run's configured rate limiter when present. Check the
shared bucket if the operation is newly subject to RPM or TPM. Media and
Embeddings report HTTP 429 as a provider rejection and apply the cooldown
to later reservations. For Media, handle HTTP 5xx and ambiguous transport
failures as :result_unconfirmed and reconcile the effect before issuing
another request. Media runtime
Adopt accounted embeddings and rerank
Replace direct calls that need the tenant's shared quota or budget with
Embeddings.embed/3 and Embeddings.rerank/4. Put provider options under
:req_llm and pass the limiter and spend account as call options. Embed
returns a list of vectors for either input form. Use rerank's zero-based
result indices to look up the original documents. Split a larger input
into separately admitted calls in the host.
Add rerank_search_units to readers that validate a closed list of
Usage.units keys. The existing usage v1 format and Store schema cover
both old and new records. Read cost independently from counts and
retain pending holds when the provider evidence is incomplete.
Add the two tools through Embeddings.tools/1 and fetch their results using
the originating run ID. Use [:exagent, :embeddings, :request, :start | :stop]
for per-request accounting in dashboards. Its span context corresponds
to exagent.request_id on the client span.
Embeddings and rerank
Use Gemini provider file references
For a hosted PDF use Message.Part.User.file_reference/4 with :google,
the provider-issued URI, "application/pdf" and its declared byte size.
Choose :gemini_v1 with catalogue PDF input. A different owning provider
in any Fallback leaf fails before dispatch with
RequestError.reason == :file_reference_provider_mismatch. Apply the host's
file permission and expiry checks for active credentials on every run and
resume.
Custom adapters that handle references declare file_references on
ModelProfile. Use pairs of strings such as {"google", "application/pdf"}
with the adapter's own system and MIME type. TestModel uses "test" and
its existing :profile option. ExAgent lowercases MIME in new reference
parts and in the pairs returned by Model.profile/1. Match core admission
errors on RequestError.reason. These errors carry provider: nil.
with the adapter's own system and the lowercase MIME. TestModel uses its
system: value, which defaults to "test", and its :profile option.
ExAgent lowercases MIME from new reference parts. An invalid constructor
argument raises ArgumentError naming its field. Match core admission
errors on RequestError.reason. For a mismatch or an unsupported
reference, read details.provider and details.leaf_index for the provider
and zero-based leaf in traversal order. The top-level provider stays
nil on these admission errors.
Use share_file_references: true to allow forwarding to an authorized
destination. Hosted-file parts and grant-bearing transfers are part of the
Store format level 1 baseline. Records without the new grant keep their
catalog identity. Resume an open C7 run
with its original catalog. Reference setup
Older upgrades
These steps take a 1.x application to 2.0 and describe the 2.0 contracts. Then apply the 2.x to 3.0 section above, which changes several of them. The code examples use the 3.0 API.
ExAgent 2 changes model configuration, operational failures, streaming, events, accounting and persistence contracts. Upgrade the application's dependency and review each boundary it uses before resuming existing conversations or jobs.
Update the dependency and environment
{:exagent, "~> 2.0"}Use Elixir 1.18/OTP 28 or Elixir 1.20/OTP 29. Update the application lock for the ReqLLM range and decoder/HTTP dependencies declared by your ExAgent version. When the application supplies credentials itself, set this before startup:
config :req_llm, load_dotenv: falseReqLLM otherwise loads .env from the working directory. Credentials belong in
trusted application configuration, outside prompts, snapshots and trace payloads.
1. Run failures retain progress
Operational failures carry the original cause and last known progress.
Pass your application's options in run_opts.
case ExAgent.run(agent, prompt, run_opts) do
{:ok, %{status: :succeeded, output: output}} ->
deliver_validated_output(output)
{:ok, %{status: :paused, continuation: reference}} ->
{:paused, reference}
{:error, %ExAgent.RunError{reason: reason, partial: partial}} ->
record_failure(reason, partial)
endThe two functions are application callbacks. Update nested error patterns to
match the original cause in RunError.reason; the
result contract describes the
pause, the partial result and safe logging.
An incomplete response stays outside executable history in
partial.pending_response. Its duplicate error copy may replace large parts with
an explicit omission marker; read the original diagnostic partial from RunError.
Neither copy authorizes a tool or proves completion.
2. Streaming runs the full loop
run_stream/3 executes tools, output validation, hooks and limits. It emits
provisional {:delta, text} events followed by {:result, result} or
{:error, %RunError{}}. A failure is not another successful result containing an
error field. Use the validated terminal result instead of concatenating deltas
and assuming they are final output.
Creating a stream does not start a request. Each enumeration starts a new run and can repeat effects; enumerate once. Halting closes owned resources. If your application suspends enumeration, it owns resuming or halting that continuation. Custom streaming Models emit a complete terminal response or an error.
3. Configure the ReqLLM backend explicitly
Replace legacy provider-specific wrappers with ExAgent.Models.ReqLLM.new/1 or
ExAgent.Model.resolve/2. Supply instance api_key: and, for a gateway,
base_url:. Anthropic may use explicit auth_token: instead. Resolution alone
does not supply credentials or enable a tool/stream/native-output profile.
Tools require :chat_tools_v1 or OpenRouter's :openrouter_chat_tools_v1, with
truthful Chat protocol and capability metadata. Models with reasoning enabled
require the separately supported reasoning_mode: :none capabilities or, on
OpenRouter's profile, reasoning_mode: :enabled, which replays reasoning blocks
unchanged; merely declaring those flags cannot establish provider compatibility.
The provider sees each function's mandatory outer arguments object. Callers,
hooks and local tools continue to work with logical argument objects. Invalid
or truncated arguments reject before execution; no unwrapping, JSON repair or
guessing old history is performed.
OpenRouter's provider route and reasoning mode participate in static bindings and response continuation version 4. Reusing routed history with a changed mode or route rejects. OpenAI's supported continuation versions remain separate. Pre-envelope or unbound routed history cannot be silently upgraded: reconcile the old conversation and start a fresh one with the current configuration.
zai: resolves the stock ZAI provider. OpenCode Go/Zen require explicit gateway
specifications and endpoints; do not treat those aliases as interchangeable.
Custom implementations of ExAgent.Model remain supported.
Timeouts and retention
Receive inactivity timeout precedence is request ModelSettings.timeout, model
http_options[:receive_timeout], then 60,000 ms. Stock pool checkout also uses that
receive value; there is no separate exposed pool timeout.
total_timeout: bounds one buffered operation and may inherit the ReqLLM default
when nil. Streaming nil means 60,000 ms; explicit stream values are 1–300,000 ms.
Run deadline: is a separate absolute monotonic-millisecond admission boundary.
None of these can roll back an external effect or stop arbitrary callback descendants.
Stream limits apply after decoding: at most 4,096 public chunks, 65,536 bytes per
chunk and 1,048,576 serialized bytes across chunks. Stock decoding and upstream
queues can allocate before those checks. No hard predecode RAM guarantee or
end-to-end backpressure is provided. Streaming max_tokens defaults to 4,096 and
explicit values must be 1–4,096.
4. Validate tools and typed output locally
Tool parameters use JSON Schema and are validated before invocation. Tools can
return a value, {:ok, value} or {:error, reason}; successful values must be
JSON-portable. Use ExAgent.ModelRetry only for a correctable rejection. A timeout
or arbitrary execution failure cannot establish that the effect never happened.
An Ecto output schema uses tool mode by default. Native output requires agent
output_mode: :native and model output_profile: :chat_json_schema_v1.
The non-strict remote schema is a request hint; local JSON/schema validation and
the actual changeset decide success. Corrective retries spend the same request
budget. Native output does not silently fall back to tool output.
Review required/optional fields, defaults, bounds and supported schema constructs. Unsupported adapter schemas reject rather than strengthening optional fields. Stock Chat may discard a wire refusal beside otherwise valid JSON; the exposed response, rather than the original wire representation, is validated.
5. Use scoped events and conversation ownership
Server async calls acknowledge volatile admission with a request ID. Completion
arrives through versioned ExAgent.Event envelopes. Derive the namespace from
authenticated application state and match the namespace, conversation and request ID.
Events are notifications; query Server history/health on reconnect.
Minimal runtime integration recipe
The application supplies agent. Local PubSub and ETS need no Phoenix or database;
ETS does not survive loss of its table owner or VM.
alias ExAgent.{Event, PubSub, Server}
namespace = "workspace-a" # obtained from authenticated application context
conversation_id = "conversation-1"
pubsub = PubSub.normalize(:local)
:ok = PubSub.subscribe(pubsub, Event.agent_topic(conversation_id, namespace))
{:ok, server} = Server.start_link(
agent: agent,
agent_id: conversation_id,
namespace: namespace,
pubsub: pubsub,
store: :ets,
max_pending: 2
)
{:ok, %{request_id: request_id}} = Server.send_message(server, "Hello")
%{server: server, namespace: namespace, request_id: request_id,
cancel: fn run_id -> Server.abort_run(server, run_id) end}For Phoenix use {ExAgent.PubSub.Phoenix, MyApp.PubSub} after starting the host's
PubSub. For the matching conversation and request in that namespace, bind the cancel button to the
run_id from :run_started. A late click returns {:error, :run_not_active}
once a different run is active. Closing the UI can leave admitted work running.
6. Migrate snapshots and persisted approvals deliberately
Snapshots hold portable data; restore obtains live models, tools, policy and codecs from trusted application templates. Restore validates structure, version, namespace, identity and bindings. Missing data can start a new conversation; corrupt, future or mismatched data fails. Preserve and reconcile old snapshots instead of silently replacing rejected data with an empty conversation.
With a Store, positive completion acknowledgement follows a confirmed save.
CheckpointError retains the new state and blocks further mutations while dirty.
Retry Server.checkpoint/1 or Session.checkpoint/1 to save that same transition;
do not run the prompt, tool or state-change callback again.
Applications provide their Repo and database lifecycle for Store.Postgres
and apply the unified migration. A typed Session supplies shared_state_codec: on
every start; stored bytes cannot choose its module. Keep encoding/decoding pure.
Persisted approval uses a stable execution ID, scoped Store, trusted versioned references, codecs and current authorization. Persisting a decision performs no effect. Resume revalidates the current definitions and executes the approved cursor. Completed steps are data, not replay instructions. After owner loss, explicit recovery and effect reconciliation determine what may execute next. See Durability and approvals and Continuation jobs.
7. Keep accounting quality and observability ownership
Request/tool counts are exact host admissions. Tokens retain declared normalized or reported quality, costs are estimated cents and missing values remain unknown. Parent totals include descendants; do not add inclusive parent and child totals. Strict token/cost limits reject normalized accounting. Opt into estimated thresholds with a finite request limit if that contract fits your application.
Native OpenTelemetry is optional. The application owns its SDK, processors and
exporter. Use ExAgent.Observability.ReqLLM.attach/1 once when also tracing ReqLLM
calls: ExAgent produces its run/model spans and the bridge enriches them.
Replace a separate stock ReqLLM bridge rather than attaching both.
Content remains off unless an explicit redactor is configured.
For metrics, tracking maintenance, transport ownership and callback/ingestion counters, follow Observability. Traces are not a billing ledger.