ExAgent. Server
(ExAgent v3.0.0)
View Source
Supervised owner of conversational history, model state and accumulated usage.
Stability — Stable.
Runs execute in owned supervised tasks. Stopping or killing the Server kills
its active worker; external effects and detached user processes cannot be undone.
After admission, chat/3 waits for the run outcome. send_message/3 and
steer/3 return an admission receipt with the reserved run and request IDs.
Both accept an optional :idempotency_key for retry and receipt/2 lookup
after a lost reply. A receipt acknowledges admission. Execution and
completion have their own outcomes.
Each request function accepts only its own options, as a keyword list with
known, unique keys. Invalid options raise ArgumentError before submission.
A malformed prompt fails admission with {:error, :invalid_prompt} or
{:error, {:invalid_prompt_part, index}} before it can occupy a queue slot.
States
health/1 reports one of these statuses:
:idle: no run is active; queued turns start in order.:running: one owned worker executes a run.chat/3,set_model/3andreset/2return{:error, :busy}.send_message/3andsteer/3queue by default. Passqueue: falsetosend_message/3to require an idle Server.:paused: a durable continuation waits fordecide/4orsupply_result/4, thenresume/3with the decision's reference. Useabort_run/3to cancel it.:blocked: the durable continuation needs recovery because its record is claimed or uncertain, its last save is unconfirmed, or a continuation run failed. Confirm the pending checkpoint, reconcile an outstanding effect or resume a ready record. For an interrupted claim, useabort/2after the stored lease expires.:reset_required: the restored history ends in an unanswered tool batch.reset/2clears the history and leaves this state.
In :paused, :blocked and :reset_required, chat/3 and set_model/3
return {:error, :continuation_pending} and queued turns wait. A blocked
owner also returns that error for fresh asynchronous turns.
reset/2 returns the same error in :paused and :blocked.
Persistence
With an opt-in Store, terminal success follows a confirmed checkpoint. A failed
save returns ExAgent.CheckpointError, preserving the execution outcome and
new state in memory. Until checkpoint/2 confirms it, mutations return
{:error, :checkpoint_pending} and queued turns wait. A queued turn may still
be removed by its receipt with abort_run/3. checkpoint/2 retries only saving.
Adapter IO is synchronous and must be bounded by the adapter.
Recovery restores conversation data, never replays tools or queued work.
health/1 and terminal event payloads carry the same :persistence map:
%{mode: :disabled | :snapshot | :atomic, status: :confirmed | :unconfirmed, revision: non_neg_integer() | nil, error: map() | nil}.
Health reports the owner's revision. A terminal event reports the revision
it acknowledges. While status is :unconfirmed, the Store may hold an
earlier revision and error describes the failed save.
A C7 SQL 4 error appears as {:store_migration_required, 4} in
ExAgent.CheckpointError and as a bounded "store_migration_required"
diagnostic with version: 4 in health and terminal events. Apply the
migration, rebuild existing run headers, then retry checkpoint/2.
Calls without a reply
{:error, :unavailable} means dispatch could not reach an owner or the
stopping owner explicitly acknowledged that it discarded the request unread.
{:error, {:delivery_unconfirmed, request_id}} means admission could not
be confirmed. The ID was assigned before sending.
{:error, :result_unconfirmed} means a request was sent and its effect may
have happened. Reads return {:ok, value} or {:error, :unavailable} on
loss of the owner or timeout (default 5000 ms). Cursor and Store errors retain their reasons.
Events
Events (ExAgent.Event, envelope version 2) use the agent topic and a seq
local to emitter_id. A run's elements are the same as ExAgent.run_stream/3
(Event.payload/2); pass stream_text: true for :text_delta and
tool_call_deltas: true for :tool_call_delta, and child_events: :all for
the elements of children started with ExAgent.run_child/4. Frame3
delegation emits its live start and stop with the child's lineage. The
candidate :child_run_stopped event carries the observed status. UI readers
use attach/3 with delivery: :demand and
read a bounded batch with events_since/3. After applying it, acknowledge
its notice and cursor with ack_events/4. Each attached reader has at most
one pending notice. Read history_page/2 and check
receipt/2 for any unconfirmed submission when a cursor expires.
Each event is published synchronously to the optional :pubsub and kept
in the bounded event buffer. PubSub sends full events without a per-reader
bound and is intended for hosts that control how they consume them. It also
carries transient tool data, which is excluded from replay and demand reads.
With event_buffer: false and no :pubsub, events are discarded.
Summary
Demand event delivery
Acknowledge the calling reader's outstanding notice up to an applied cursor.
Keep this Server active while the attached process lives (up to 1024 distinct pids).
Remove a process attachment and its demand subscription. Repeated detachments
are harmless. A notice already sent can still be in the reader's mailbox.
The :timeout option and acknowledgement rules are the same as for attach/3.
Replay the buffered events published after cursor (ExAgent.Event.cursor/1).
Types
Immutable UTC expiry in milliseconds (0..9223372036854775807) and a UTF-8 client ID of 1..512 bytes.
Admission of a turn or its confirmed cancellation before start.
Confirmed cancellation of a keyed queued turn within its receipt window.
Content-free metadata for a turn observed by the live conversation owner.
Functions
Cancel the Server's current work, including a pending durable continuation.
:timeout (5000 ms) bounds the caller's wait, including Store IO.
A call that exits without a reply returns {:error, :result_unconfirmed}.
Repeating this call can cancel the next queued run once it starts.
An observed C7 pause uses the same cancellation as abort_run/3.
On a blocked continuation, :ok can confirm a fence while an outstanding
effect keeps the Server blocked. Inspect it with continuation/2.
After a lease failure, wait for the stored horizon before aborting.
Use abort_run/3 to target a specific turn.
Cancel a queued, active, paused or interrupted turn by run_id. Use
the ID from its admission receipt, run event or continuation details.
Execute a run and wait for its outcome. Options are :deps, :model_settings, :stream_text,
:tool_call_deltas, :child_events, :estimate_cost, :deadline, :max_concurrent_requests,
:max_concurrent_tools, :permissions,
:approve, :observability, :trace_context, :message_history, :timeout,
and :request_id. A %ExAgent.UsageLimits{} in the candidate :usage_limits option
tightens the agent's limits for this turn. The smaller threshold wins for
each field, and strict accounting wins when both policies are supplied.
Explicit :message_history overrides accumulated context. The Server owns
the run ID, event and progress callbacks, and instruction management.
Retry an unconfirmed save only, without repeating execution, in both
persistence modes. Returns :ok once nothing is pending,
{:error, %ExAgent.CheckpointError{}} if the save fails again and
{:error, :busy} while a run is active. :timeout defaults to :infinity.
A call that exits without a reply returns {:error, :result_unconfirmed}.
Child specification with id {:exagent_server, key}, where key is
:agent_id, :name or a unique reference, in that order. A missing
:agent_id is generated once for the specification. An abnormal exit
restarts the Server with the same conversation ID.
Query the persisted continuation independently of PubSub delivery.
For a :ready or :approved run, :continuation is the exact revision's
resume reference. In other states it is nil. The claim's :lease_until
is a UTC timestamp in milliseconds, or nil without a claim.
Pass diagnostics: true to include the stored body as in
ExAgent.Continuation.get/3. The :timeout option bounds the read.
Returns {:error, :unavailable} if the Server does not reply.
Persist a host-authorized decision without resuming the run.
Decode a key created by encode_admission_key/1. This checks the encoding;
the Server checks expiry, scope and admission state when the key is used.
Encode a turn's admission key as a URL-safe string for HTTP clients. Keep the encoded key unchanged across retries. It is scoped by the Server on receipt, has the original expiry and grants no authorization.
Report the server's agent ID, namespace, emitter, queue and persistence status.
Read history from the Server with an optional caller timeout.
Read the newest window, or the window ending just before a returned :before
cursor. Supply the last page’s :head as :since to fetch just the newest
changes within the window. If its start exceeds the old count, reload the
window. Items are chronological. :start is the first zero-based offset,
:total the current count and :revision stays valid across appends. Reset,
replacement, a change to the public projection of existing rows or owner
restart expires previous cursors with {:error, :cursor_expired}.
Mint a key before sending a logical turn. Call new_admission_key() for the
default 15-minute window or pass an integer TTL in 1..4_294_967_295
milliseconds directly, for example new_admission_key(60_000).
A new receipt requires an expiry
at most 4_381_367_295 milliseconds ahead of the admission clock (the Store
clock for C7). A later expiry returns {:error, :idempotency_expiry_out_of_range}.
Read the review inbox of the Server's continuation: the
%ExAgent.Continuation.ApprovalRequest{} and %ExAgent.Continuation.DeferredCall{}
items of ExAgent.Continuation.pending/2, read from one revision.
Returns {:error, :unavailable} if the Server does not reply.
Read the admission receipt within this conversation. Status :admitted
confirms the reserved run ID. That run may still be queued or require
reconciliation. Status :cancelled_before_start confirms the queued turn's
outcome and carries its receipt revision.
Before returning {:error, :idempotency_expired}, admission records the clock
watermark and prunes expired receipts. Reconcile the original turn before
submitting it with a new key.
Fork before a settled user turn and submit its original prompt to the branch.
Read the latest confirmed user turn from the owner's scoped Store.
On success, :turn_ref is its root run ID and :prompt is the original
user content. Pass the ID as :at when staging an edit in a trusted host.
The fork checks the selected history again.
Clear the conversation history and usage.
:timeout (5000 ms) bounds the caller's wait, including Store IO.
A call that exits without a reply returns {:error, :result_unconfirmed}.
Check the history and revision before repeating the reset.
Resume the exact ready revision identified by reference in a new owned worker.
Submit a turn and acknowledge admission before waiting for completion.
Replace the model in the running Server. Supply the desired model again after restart.
:timeout (5000 ms) bounds the caller's wait, including model resolution.
A call that exits without a reply returns {:error, :result_unconfirmed}.
Start with :agent and optional :agent_id, :name, :store, :pubsub,
:namespace (trusted application string, nil for legacy), :metadata,
:max_pending (8), :observability, :continuation and :event_buffer.
Submit a turn at the front of the queue. Accepts the same options as
send_message/3 except :queue and returns the same admission receipt.
Correct the volatile root run identified by its :run_started event.
Waits until a fresh model request takes the correction or the run ends.
Returns the same receipt or refusal as ExAgent.Steering.correct/2.
A different or finished run returns {:error, :run_not_active}.
Continuation Servers return {:error, {:unsupported, :continuation_steering}}.
Record the result of a %ExAgent.Continuation.DeferredCall{} from pending/1
without resuming the run, as ExAgent.Continuation.supply_result/4 does.
Invalid options raise ArgumentError in the caller; an item of another agent
or namespace returns {:error, :stale_request} before any IO. Unless
replayed, broadcasts :deferred_result_supplied. If that write settles an
uncertain cancellation, it then broadcasts :server_request_cancelled
with status: :cancelled and the reconciliation revision. A call that
exits without a reply returns {:error, :result_unconfirmed}.
Read the live turn and queue from the conversation owner in one call.
Read usage from the Server with an optional caller timeout.
Demand event delivery
@spec ack_events(GenServer.server(), reference(), ExAgent.Event.cursor(), keyword()) :: :ok | {:error, {:cursor_expired, ExAgent.Event.cursor()} | :stale_notice | :unavailable | :result_unconfirmed}
Acknowledge the calling reader's outstanding notice up to an applied cursor.
Use the cursor returned by an applied batch or a rebuilt history page. The Server sends a fresh notice if events remain beyond that cursor. If the acknowledgement reply is lost, retry the same notice and cursor without applying the batch again. The reader's most recent acknowledgement can be repeated without rearming delivery twice.
An obsolete or foreign notice returns {:error, :stale_notice}. A cursor
from another emitter, ahead of the head or behind the last acknowledged
cursor returns {:error, {:cursor_expired, head}}. The caller's wait is
bounded by the relative :timeout (5,000 ms by default), including owner lookup.
@spec attach(GenServer.server(), pid(), keyword()) :: :ok | {:error, :event_buffer_disabled | :too_many_attachments | :unavailable | :result_unconfirmed}
Keep this Server active while the attached process lives (up to 1024 distinct pids).
With delivery: :demand, the process receives
{:exagent_events_ready, server_pid, notice} when there is activity to read.
Pass the reference as notice: to events_since/3 to read a bounded batch.
After applying the batch, call ack_events/4 with the notice and applied
cursor. Only that acknowledgement rearms the reader. Demand requires an
enabled event buffer.
Attach before reading the initial history page so later events can wake the
reader. Repeated attachments are idempotent. Use detach/2 to stop receiving
notices before the reader exits.
The relative :timeout (5,000 ms by default) includes owner lookup. Expiry
before dispatch returns {:error, :unavailable}. Losing the acknowledgement
after dispatch returns {:error, :result_unconfirmed}.
@spec detach(GenServer.server(), pid(), keyword()) :: :ok | {:error, :unavailable | :result_unconfirmed}
Remove a process attachment and its demand subscription. Repeated detachments
are harmless. A notice already sent can still be in the reader's mailbox.
The :timeout option and acknowledgement rules are the same as for attach/3.
@spec events_since(GenServer.server(), ExAgent.Event.cursor() | nil, keyword()) :: {:ok, %{items: [ExAgent.Event.t()], cursor: ExAgent.Event.cursor()}} | {:error, {:cursor_expired, ExAgent.Event.cursor()} | {:event_too_large, pos_integer()} | :stale_notice | :unavailable}
Replay the buffered events published after cursor (ExAgent.Event.cursor/1).
Returns {:ok, %{items: events, cursor: cursor}} with events in seq order.
An empty page advances to the emitter's head. A nil cursor starts at the
oldest retained event. The default read returns all remaining buffered events.
Pass limit: (1..65536 events) and max_bytes: (64..67108870 bytes) to
bound a batch. The byte limit covers the uncompressed ETF items list. When
the first event cannot fit, the read returns {:error, {:event_too_large, bytes}}
with the minimum required size. Retry with a larger limit or rebuild from history.
For a demand attachment, use notice: notice after receiving the ready
message. The default batch then holds up to 64 events and 262144 bytes.
An obsolete notice or a notice for another reader returns
{:error, :stale_notice}. A read leaves the notice pending regardless of its
result. Retry from the last applied cursor after a timeout. When a batch
applies, use ack_events/4 with its notice and cursor.
A cursor of another emitter (the Server restarted), one ahead of the Server
or one older than the buffer returns {:error, {:cursor_expired, current}}
with the current cursor. Rebuild with history_page/2 and resume from the
page's :event_cursor. Returns {:error, :unavailable} if the Server does not
reply within :timeout (5000 ms by default). A malformed cursor raises
ArgumentError in the caller.
Types
@type admission_key() :: {non_neg_integer(), String.t()}
Immutable UTC expiry in milliseconds (0..9223372036854775807) and a UTF-8 client ID of 1..512 bytes.
@type admission_receipt() :: %{run_id: String.t(), request_id: String.t(), status: :admitted} | cancelled_admission_receipt()
Admission of a turn or its confirmed cancellation before start.
@type cancelled_admission_receipt() :: %{ run_id: String.t(), request_id: String.t(), namespace: String.t() | nil, status: :cancelled_before_start, reason: :cancelled | :stopped | :superseded, persistence: %{ mode: :disabled | :atomic, status: :confirmed, revision: pos_integer(), error: nil } }
Confirmed cancellation of a keyed queued turn within its receipt window.
@type turn() :: %{ run_id: String.t(), request_id: String.t() | nil, admission_key: admission_key() | nil, status: :running | :paused | :blocked | :queued | :cancellation_unconfirmed }
Content-free metadata for a turn observed by the live conversation owner.
Functions
Cancel the Server's current work, including a pending durable continuation.
:timeout (5000 ms) bounds the caller's wait, including Store IO.
A call that exits without a reply returns {:error, :result_unconfirmed}.
Repeating this call can cancel the next queued run once it starts.
An observed C7 pause uses the same cancellation as abort_run/3.
On a blocked continuation, :ok can confirm a fence while an outstanding
effect keeps the Server blocked. Inspect it with continuation/2.
After a lease failure, wait for the stored horizon before aborting.
Use abort_run/3 to target a specific turn.
Pass candidate :cancel_follow_ups as true when ending a conversation
with scheduled follow-ups. The call also clears its pending jobs in the
conversation's ETS or PostgreSQL Store. A Store error leaves that cleanup
unconfirmed even if the turn cancellation committed.
@spec abort_run(GenServer.server(), String.t(), keyword()) :: :ok | {:error, term()}
Cancel a queued, active, paused or interrupted turn by run_id. Use
the ID from its admission receipt, run event or continuation details.
Removing a queued turn releases its bytes and emits
:server_request_cancelled with status :cancelled_before_start.
For a live admission key, the Server first confirms the outcome in the
receipt. In C7 the event acknowledges that receipt's atomic revision.
An ambiguous Store acknowledgement can return :result_unconfirmed. The
owner keeps the turn fenced from dispatch and checks the receipt. Retry
this call with the same run ID, or read the receipt with the original key.
After the key expires, the live owner can still cancel the queued turn
with process-local evidence.
An active or paused cancellation also uses payload.status, with
:cancelled for a settled cancellation. payload.partial includes the
accounting observed by a live worker or confirmed by the C7 journal.
A restored owner uses the same journal evidence as the original owner.
A paused C7 turn uses the Server's observed record lifetime and revision.
A resumed C7 turn keeps its run ID and uses the observed revision or the
resumed worker's claim. The journal orders an active abort against finish.
A blocked C7 owner can cancel its observed claim by ID, including when a
replacement owner has just restored it.
A committed finish keeps its usual terminal and the abort returns
{:error, :run_not_active}.
A competing transition returns {:error, :continuation_abort_conflict}.
After the Store confirms the cancellation, the Server emits
:server_request_cancelled with the original run and request IDs.
A lost model response leaves its intent in the journal and its cost unknown.
payload.status is :uncertain when a tool or callback still needs reconciliation.
Both confirmed cancellation states return :ok. If the save is
unconfirmed, retry it with checkpoint/2.
That retry emits the event once it confirms the original transition.
The snapshot keeps the preceding history and drops the unfinished turn.
Existing effects remain in the journal. The next queued turn can start
once the cancellation and any required reconciliation are confirmed.
Returns {:error, :run_not_active} when the ID has no cancellable turn.
Accepts :timeout and the same delivery receipts as abort/2.
@spec chat(GenServer.server(), term(), keyword()) :: {:ok, ExAgent.Result.t()} | {:error, term()}
Execute a run and wait for its outcome. Options are :deps, :model_settings, :stream_text,
:tool_call_deltas, :child_events, :estimate_cost, :deadline, :max_concurrent_requests,
:max_concurrent_tools, :permissions,
:approve, :observability, :trace_context, :message_history, :timeout,
and :request_id. A %ExAgent.UsageLimits{} in the candidate :usage_limits option
tightens the agent's limits for this turn. The smaller threshold wins for
each field, and strict accounting wins when both policies are supplied.
Explicit :message_history overrides accumulated context. The Server owns
the run ID, event and progress callbacks, and instruction management.
Jobs start a host turn with an explicit ExAgent.Message.Part.JobNotice.
Ordinary text and multimodal prompts are user input. The Server never infers
host activity from the contents of a prompt.
Invalid option values raise ArgumentError in the caller, as in ExAgent.run/3.
A Server started with :continuation persists :ask decisions for decide/4,
so it also rejects an :approve callback that way.
:timeout bounds the caller's wait. Pass :infinity (the default) or an
integer in 0..4_294_967_295 milliseconds. An invalid wait raises
ArgumentError before sending the chat request.
If the call exits without a reply, returns {:error, :result_unconfirmed}.
The Server may still complete the turn. A supplied :request_id lets the
caller correlate its events after a timeout.
Use send_message/3 with queue: false for a recoverable admission that
also requires an idle Server. See receipt/2 for the retention boundary.
Retry an unconfirmed save only, without repeating execution, in both
persistence modes. Returns :ok once nothing is pending,
{:error, %ExAgent.CheckpointError{}} if the save fails again and
{:error, :busy} while a run is active. :timeout defaults to :infinity.
A call that exits without a reply returns {:error, :result_unconfirmed}.
Child specification with id {:exagent_server, key}, where key is
:agent_id, :name or a unique reference, in that order. A missing
:agent_id is generated once for the specification. An abnormal exit
restarts the Server with the same conversation ID.
To stop or replace the child by ID in a supervisor or in ExUnit, use the specification's ID or pass an explicit override when starting it.
@spec continuation(GenServer.server(), keyword()) :: {:ok, ExAgent.Continuation.run_details()} | {:error, term()}
Query the persisted continuation independently of PubSub delivery.
For a :ready or :approved run, :continuation is the exact revision's
resume reference. In other states it is nil. The claim's :lease_until
is a UTC timestamp in milliseconds, or nil without a claim.
Pass diagnostics: true to include the stored body as in
ExAgent.Continuation.get/3. The :timeout option bounds the read.
Returns {:error, :unavailable} if the Server does not reply.
Persist a host-authorized decision without resuming the run.
target is an item from pending/1 with the decisions and options of
ExAgent.Continuation.decide/4, or :run for :cancel and :expire with
the binding options of its logical-ID form. The Server's configured
:catalog takes precedence when validating a fresh approval and supplies
the tool for an edit.
Invalid options raise
ArgumentError in the caller. An item of another agent or namespace returns
{:error, :stale_request} before any IO. Returns the
ExAgent.Continuation.admin_reply/0 and, unless replayed, broadcasts
:approval_decided. A call that exits without a reply returns
{:error, :result_unconfirmed}: repeat the same item and decision to resolve
the outcome.
@spec decode_admission_key(term()) :: {:ok, admission_key()} | {:error, :invalid_admission_key}
Decode a key created by encode_admission_key/1. This checks the encoding;
the Server checks expiry, scope and admission state when the key is used.
@spec encode_admission_key(admission_key()) :: String.t()
Encode a turn's admission key as a URL-safe string for HTTP clients. Keep the encoded key unchanged across retries. It is scoped by the Server on receipt, has the original expiry and grants no authorization.
@spec health(GenServer.server(), keyword()) :: {:ok, map()} | {:error, :unavailable}
Report the server's agent ID, namespace, emitter, queue and persistence status.
@spec history(GenServer.server(), keyword()) :: {:ok, [ExAgent.Message.t()]} | {:error, :unavailable}
Read history from the Server with an optional caller timeout.
@spec history_page(GenServer.server(), keyword()) :: {:ok, map()} | {:error, :unavailable | :cursor_expired}
Read the newest window, or the window ending just before a returned :before
cursor. Supply the last page’s :head as :since to fetch just the newest
changes within the window. If its start exceeds the old count, reload the
window. Items are chronological. :start is the first zero-based offset,
:total the current count and :revision stays valid across appends. Reset,
replacement, a change to the public projection of existing rows or owner
restart expires previous cursors with {:error, :cursor_expired}.
:limit defaults to 40 (1..1024) and :max_bytes to 65536 (64..67108864).
The byte limit covers the uncompressed ETF items list. An item too large
for an empty page becomes :omitted at its original position.
:projection defaults to :messages. With :visible_text each item is
display text, nil (hidden) or :omitted. Structured output, a stream or
final-output guardrail, an output validator or a handoff catalog sets the page's
:output_guarded? flag. Display successful final output and provisional
deltas marked :stream_checked? for these agents. The owner retains
these values up to :max_history_bytes in UTF-8 bytes, evicting oldest first,
and includes them in the same checkpoint as the conversation when a Store is set.
The continuation writer can omit these values to fit its checkpoint limits.
Structured values use the terminal event's JSON projection and run payload
byte limit. The owner hides values that fail this projection.
After restart, protected history and history from snapshots with no recorded
policy hide assistant text without acceptance evidence, even with a plain
agent definition. Confirming a failed snapshot save can reveal an existing
row and expire old cursors.
The :chat projection returns {:job_notice, %ExAgent.Message.Part.JobNotice{}}
for host activity and a :failure field with the owner's last turn
diagnostic. The candidate chat projection also carries bounded :activities
observed by this owner for its latest root attempt. The page reports this
state and the event cursor at the same instant.
The page includes :active_run_id for projection: :chat or
include_draft: true. Its value is the active root run's ID while running
and nil otherwise. With include_draft: true the page also returns
:draft, :commentary, :stream_checked? and :draft_limit.
The drafts contain the active root run's answer and narration respectively,
including deltas evicted from the event buffer. For guarded output the draft
includes only deltas passed by a stream guard. The flag identifies a
reviewed draft. Both channels are nil outside an active run or with
replay disabled. Each channel has a 1 MiB
byte limit and becomes :omitted on overflow. The page also reports
:checkpoint_pending? when a mutation must wait for a confirmed save.
@spec new_admission_key(pos_integer()) :: admission_key()
Mint a key before sending a logical turn. Call new_admission_key() for the
default 15-minute window or pass an integer TTL in 1..4_294_967_295
milliseconds directly, for example new_admission_key(60_000).
A new receipt requires an expiry
at most 4_381_367_295 milliseconds ahead of the admission clock (the Store
clock for C7). A later expiry returns {:error, :idempotency_expiry_out_of_range}.
@spec pending(GenServer.server(), keyword()) :: {:ok, list()} | {:error, term()}
Read the review inbox of the Server's continuation: the
%ExAgent.Continuation.ApprovalRequest{} and %ExAgent.Continuation.DeferredCall{}
items of ExAgent.Continuation.pending/2, read from one revision.
Returns {:error, :unavailable} if the Server does not reply.
@spec receipt(GenServer.server(), admission_key(), keyword()) :: {:ok, admission_receipt()} | {:error, term()}
Read the admission receipt within this conversation. Status :admitted
confirms the reserved run ID. That run may still be queued or require
reconciliation. Status :cancelled_before_start confirms the queued turn's
outcome and carries its receipt revision.
Before returning {:error, :idempotency_expired}, admission records the clock
watermark and prunes expired receipts. Reconcile the original turn before
submitting it with a new key.
C7 Servers retain receipts in the scoped atomic Store. A lookup with no
matching live receipt there returns {:error, :not_found}. Recovery across
owner replacement requires that the same Store and its data survive.
PostgreSQL receipt operations require Store migration 5.
Without C7, receipts last for the lifetime of the Server process, including
when snapshot persistence is enabled. A missing receipt in this mode returns
{:error, :receipt_not_durable}. Reconcile an unconfirmed turn after owner
replacement before resubmitting, even with the same key.
:timeout bounds the lookup (5,000 ms by default). An absent owner or a
lookup that could not obtain a reply returns {:error, :unavailable}.
@spec regenerate(GenServer.server(), keyword()) :: {:ok, map()} | {:error, term()}
Fork before a settled user turn and submit its original prompt to the branch.
Set destination: {manager, new_id} for a Conversations manager that restores
the same scoped Store. By default this selects the latest user turn. Pass its
root run ID as :at to select explicitly and :prompt to submit an edit.
Pass new-turn options in :run_options using the options of send_message/3.
Regeneration supplies the forked history and disables queueing. It rejects
:message_history and :queue in :run_options.
An optional :admit function receives the branch key and validated prompt
after branch creation and before the send.
Return :ok to proceed or {:error, reason} to refuse admission. Use
:timeout (5,000 ms by default) for fork acknowledgement and destination
activation. Invalid option keys, destinations, turn IDs and callbacks raise
ArgumentError. An invalid replacement prompt returns an error before the fork.
The source requires a scoped Store backed by supervised ETS or PostgreSQL.
Other sources return :unsupported_store_capability. An unconfirmed
checkpoint returns :checkpoint_pending. During a run, selecting the
latest user turn or the active run's ID returns :busy. A missing target
returns :turn_not_found. A stored turn without a settled terminal returns
:turn_not_closed. An unresolved effect in the selected history returns
:open_effects, including a pending approval in the target turn. Select an
earlier settled turn by ID while a later turn waits for approval.
On success the result includes :branch and the normal admission receipt.
A missing destination manager uses no family slot. A refused admission
releases and seals the branch ID if it is still eligible for
ExAgent.Conversations.discard_fork/2. A family capped at 64 branches
returns {:error, :fork_limit}. Release unused slots with
ExAgent.Conversations.discard_fork/2.
An error with a retained branch is {:error, {:branch_created, branch, reason}}.
Use the same destination ID and an admission key to look up delivery if
the result was unconfirmed.
The host authorizes the source and owns the destination's application row.
@spec regeneration_target(GenServer.server(), keyword()) :: {:ok, map()} | {:error, term()}
Read the latest confirmed user turn from the owner's scoped Store.
On success, :turn_ref is its root run ID and :prompt is the original
user content. Pass the ID as :at when staging an edit in a trusted host.
The fork checks the selected history again.
With the default selection :last_user, the source checks match
regenerate/2. Expect :checkpoint_pending while persistence is
unconfirmed, :busy while a run is active, and :open_effects for a
pending approval in the selected turn. An absent user turn returns
:turn_not_found and a stored turn without a settled terminal returns
:turn_not_closed. An unsupported Store returns :unsupported_store_capability.
An unavailable owner returns {:error, :unavailable}. Set :timeout
to bound the wait (5,000 ms by default).
Clear the conversation history and usage.
:timeout (5000 ms) bounds the caller's wait, including Store IO.
A call that exits without a reply returns {:error, :result_unconfirmed}.
Check the history and revision before repeating the reset.
@spec resume( GenServer.server(), ExAgent.Continuation.continuation_reference(), keyword() ) :: {:ok, ExAgent.Result.t()} | {:error, term()}
Resume the exact ready revision identified by reference in a new owned worker.
Pass the :continuation from decide/4 or supply_result/4. For an
explicit recovery, use the reference from the revision verified by the host
with continuation/2. Delayed callers must keep the original reference.
An invalid reference or a different record, run or revision returns
{:error, :continuation_conflict}. A matching record that cannot resume
returns {:error, {:continuation_not_ready, status}}. A matching reference
can return {:error, :busy} while a worker is active. If the owner loses its
write fence before the claim commits, the call can return :superseded.
With a pending Writer checkpoint, an exact ready revision of the same run
can resume when the journal proves its initial save or covers the pending
claim. A later ready revision can also resume once the Store has fenced a
Writer attempt. Other pending checkpoints return {:error, :checkpoint_pending}.
Options are :deps, :model_settings, :stream_text, :tool_call_deltas,
:child_events, :estimate_cost, :deadline, :max_concurrent_requests,
:max_concurrent_tools, :permissions, :observability, :trace_context,
:usage_limits and :timeout (:infinity by default). The run keeps its
persisted history and request ID. The limits from the agent, saved run
and this call all apply. The per-call :usage_limits option is candidate.
If the call exits without a reply, returns {:error, :result_unconfirmed}.
Check the outcome of the referenced revision before retrying it.
@spec send_message(GenServer.server(), term(), keyword()) :: {:ok, admission_receipt()} | {:error, term()}
Submit a turn and acknowledge admission before waiting for completion.
Accepts the options of chat/3, plus :idempotency_key and
:queue (default true). The receipt always includes the reserved run ID
and request ID. A continuation Server claims a keyed receipt in the scoped
Store before dispatch. A retry with the same key, admission mode and input
returns the retained receipt. Without a continuation, the key only
deduplicates within the same Server process. With queue: false, a fresh
submission follows the idle-only admission rules of chat/3.
A blocked owner refuses fresh submissions with
{:error, :continuation_pending}, or :checkpoint_pending while it has
an unconfirmed checkpoint. Existing admission receipts remain readable.
With an infinite :idle_timeout, a paused or reset-required
continuation Server reads its fence before admitting a queued turn.
It stops and returns {:error, :superseded} if another writer advanced it.
:timeout bounds the admission wait (5,000 ms by default). It accepts
:infinity or an integer in 0..4_294_967_295 milliseconds. It is
independent of the run's :deadline and is excluded from keyed admission.
A missing :request_id is generated before sending, so a call that
exits without a reply returns {:error, {:delivery_unconfirmed, request_id}}.
An unconfirmed Store admission uses the same reply. Check receipt/2 with
the original key or correlate events for that request. {:error, :unavailable}
means there was no reachable owner or the owner rejected the request
before admitting it. An invalid :request_id returns
{:error, :invalid_request_id} without sending.
Replace the model in the running Server. Supply the desired model again after restart.
:timeout (5000 ms) bounds the caller's wait, including model resolution.
A call that exits without a reply returns {:error, :result_unconfirmed}.
Start with :agent and optional :agent_id, :name, :store, :pubsub,
:namespace (trusted application string, nil for legacy), :metadata,
:max_pending (8), :observability, :continuation and :event_buffer.
:event_buffer bounds the events kept for events_since/2:
[max_events: 1024, max_bytes: 524_288] by default (max_events in
1..65536, max_bytes in 1..67108864, measured as Erlang external term size
of each event), or false to keep none. The oldest events leave first, and
an event larger than max_bytes is never kept.
Option values are validated before starting the process. A malformed list,
an unknown or duplicate key or an invalid value raises ArgumentError naming
the key, never its value. With a Store, :metadata must encode as a JSON
object. :continuation follows the agent configuration in the durability
guide; the Server supplies its :store and :id.
A continuation definition with CodeMode returns
{:error, {:unsupported, {:code_mode, :continuation}}} at startup.
Only Store :not_found starts a new conversation. A Store load failure or an
invalid or incompatible snapshot returns {:error, {:restore_failed, reason}}.
The :catalog option supplies historical agent
definitions for a Server with continuations. New turns use the configured
agent and binding. An open record from another version restores and resumes
using its exact catalogue entry. To start new turns after reading a settled
record from another version, adopt the current binding with
ExAgent.Continuation.adopt/4 and reopen the owner.
Set missing: :error to return {:error, :not_found} for an absent conversation.
A finite :idle_timeout requires a Store. After the last activity, eviction
waits for confirmed persistence, empty work, an empty mailbox and no attached
processes. GenServer.stop/2 reports the dropped work as ExAgent.Conversations.stop/3 does.
:hibernate_after controls OTP hibernation. Both timeouts default to infinity.
Payload admission options are :max_input_bytes (1MiB), :max_pending_bytes
and :max_history_bytes (8MiB each), all integers from 1 byte to 64MiB.
Sizes use uncompressed Erlang external term format (ETF), including option,
dependency and callback terms where measured. Queued work rechecks input
and history when dequeued. Pending count or bytes can return :queue_full.
Health exposes charged pending bytes.
:max_admission_receipts (256 by default, in 1..256) bounds live keyed
receipts per conversation. Submissions and Jobs notices share this window.
A new key at capacity returns {:error, :receipt_limit}. Live receipts keep
their original expiries and remain readable and retryable at capacity.
The owner checks existing or supplied history at admission and restore.
The run uses the smaller of the Server and agent history limits. A
RunError with {:retention_limit_exceeded, details} reports boundary: :input
when the initial run history, including the new prompt, exceeds the cap.
It reports boundary: :history when retaining new messages would exceed it.
Canonical history is never silently truncated. These checks apply to
already materialized terms. Caller timeout does not cancel work.
@spec steer(GenServer.server(), term(), keyword()) :: {:ok, admission_receipt()} | {:error, term()}
Submit a turn at the front of the queue. Accepts the same options as
send_message/3 except :queue and returns the same admission receipt.
@spec steer_run(GenServer.server(), String.t(), String.t()) :: {:ok, ExAgent.Steering.receipt()} | {:error, term()}
Correct the volatile root run identified by its :run_started event.
Waits until a fresh model request takes the correction or the run ends.
Returns the same receipt or refusal as ExAgent.Steering.correct/2.
A different or finished run returns {:error, :run_not_active}.
Continuation Servers return {:error, {:unsupported, :continuation_steering}}.
Record the result of a %ExAgent.Continuation.DeferredCall{} from pending/1
without resuming the run, as ExAgent.Continuation.supply_result/4 does.
Invalid options raise ArgumentError in the caller; an item of another agent
or namespace returns {:error, :stale_request} before any IO. Unless
replayed, broadcasts :deferred_result_supplied. If that write settles an
uncertain cancellation, it then broadcasts :server_request_cancelled
with status: :cancelled and the reconciliation revision. A call that
exits without a reply returns {:error, :result_unconfirmed}.
@spec turns(GenServer.server(), keyword()) :: {:ok, [turn()]} | {:error, :unavailable}
Read the live turn and queue from the conversation owner in one call.
Returns the running, paused or blocked turn first, followed by queued turns in
dispatch order. The list is bounded by :max_pending plus one. Each item
contains only IDs, the original admission key when known, and its status.
A restored, paused or resumed turn has no live admission key. A queued turn with
:cancellation_unconfirmed is held from dispatch while its cancellation
is unresolved.
The queue is process-local. Use the :run_id with abort_run/3 and keep
the key for receipt/3 after reconnecting. A receipt can confirm a
queued cancellation after the owner changes. Authorize access to the
conversation before exposing turn metadata.
Accepts :timeout (5,000 ms by default). The read uses no Store IO.
@spec usage(GenServer.server(), keyword()) :: {:ok, ExAgent.Message.Usage.t()} | {:error, :unavailable}
Read usage from the Server with an optional caller timeout.