Framework integrations
View SourceGenerate a Phoenix chat
In a Phoenix 1.8 application with PostgreSQL, install Igniter in development
and add the ExAgent dependency. Configure Oban on the same Repo. Generate
authentication with mix phx.gen.auth Accounts User users --live if the app needs it. Then run
mix exagent.install, mix exagent.gen.live Chat, mix exagent.catalog.lock
and mix ecto.migrate.
The authenticated routes live under /chat. Run the generated tests with
mix test and configure the selected provider before starting a real chat.
Pass --yes to apply changes in a shell without a TTY. Pass --dry-run
to preview the changes. Run mix help exagent.install for the list of
switches. New chat modules follow the directories
of the installed Agents module and the Phoenix router. The generated tests
mirror those directories under test/. Rerunning the generator keeps existing
modules in their current paths.
The installer generates the unified PostgreSQL migration. Existing
applications can generate a pending migration with mix exagent.upgrade.
Store rollout
The installer accepts --repo, --pubsub, --table and --result-store. Without --pubsub,
the generated Agents.pubsub/0 reads the Endpoint's :pubsub_server from the
application environment at runtime. The installer starts ExAgent.Conversations
right after the Repo, so it is running before Oban executes resume jobs and
stops only after Oban drains. It refuses an existing Agents module that lacks
server_options/1. A project without a Repo receives an ephemeral ETS store. Generating the chat requires a Repo
and Oban configured for that same database. Select the chat model with
--model and the authenticated scope module with --scope.
Use --model test for an offline chat with a durable TestModel binding.
The generated codec saves the TestModel script index and loads it into the
host's current model template. ReqLLM uses its stateless codec. Set
:chat_codec when supplying a custom model with its own persisted state.
For a single-user local app, --no-auth generates a fixed actor. Enabling
this variant in production requires the host setting
config :my_app, :allow_unauthenticated_chat, true.
The generated code belongs to the application. The chat derives its definition
reference from the tool contracts, model binding and definition revision.
The fresh catalogue contains the active definition.
Keep the previous factory and binding in catalog/2 when deploying a change.
Bump the revision for changes to callable, instruction, policy or codec
behavior. Preserve the old model and codec when changing provider settings.
For a host on 2.3, enroll its Store with mix exagent.upgrade and retain
the exact definition, policy, model and codec bindings of its saved runs.
Create the catalog lock before deploying the active 3.0 definition.
Lock durable definitions
While replacing the demo tool, run mix test --exclude exagent_demo_tool.
Adapt or remove the tagged tests and update the catalog lock for the new definition.
A lost admission reply carries the request ID. Keep the original admission key and suppress further submissions until its receipt is confirmed.
Implement MyApp.Agents.Chat.run_options(namespace, phase) for tools that
need host dependencies. The LiveView passes the options from :turn.
ResumeWorker loads the conversation from the host database and passes
the options from :resume. Return [deps: %{actor: actor, tenant: tenant}]
for Ash. Resolve both values from trusted host data under the current policy.
Implement MyApp.Agents.Chat.admit_prompt(scope, key, prompt) to classify a
fresh message before durable admission. Return :ok to admit it. The
generated LiveView reports a decline for every other reply. Use
Classifier.classify/2 with a classifier and labels approved for this scope.
Account for the pre-admission inference separately from the turn.
For the chat list, MyApp.Chat.list(scope) reads the host's conversation rows
for the authenticated owner. These include chats with continuations and
newly created chats. MyApp.Chat.get!(scope, id) checks ownership again on open.
Snapshot headers
cover chats persisted in snapshot mode.
Use a pinned MCP client in the generated chat
Use the endpoint options and binding from Pin an MCP tool catalogue.
For example, point :exagent_mcp_lock at {MyApp.KB, :connection_options, []}
under "kb" and run mix exagent.mcp.lock kb. Add these functions alongside
connection_options/0 in MyApp.KB.
alias ExAgent.MCP.Client
def pinned_options do
path = Application.app_dir(:my_app, "priv/exagent/mcp/kb.lock.json")
Keyword.put(connection_options(), :pinned, File.read!(path))
end
def tools("catalog-lock") do
{:ok, client} = Client.start_link(pinned_options())
try do
tools!(client)
after
Client.close(client)
end
end
def tools(_namespace), do: tools!(__MODULE__)
defp tools!(client) do
{:ok, tools} = Client.tools(client)
tools
endStart the client before Conversations and Oban. The candidate
:connect_on_start option verifies the peer against the lock before the
child's startup succeeds. The default drift policy rejects changes.
{ExAgent.MCP.Client,
[name: MyApp.KB, connect_on_start: true] ++ MyApp.KB.pinned_options()}In MyApp.Agents.Chat.agent(namespace), append MyApp.KB.tools(namespace) to
the existing :tools list. LiveView and the recovery and resume path then
build the same definition from the supervised client. The generated
catalog_lock/0 uses the reserved "catalog-lock" namespace. Its temporary
client reads the same lock and binding with the host stopped and closes
after discovery. Run mix exagent.catalog.lock to record the definition.
For a transport invalidation in a running client, use Client.reconnect/1
to verify it again. If the client process is replaced, stop affected owners
with Conversations.stop/3 and reopen them to rebuild their callbacks.
Deploy with open continuations
Deploy three replicas
Point all three replicas at the same PostgreSQL database and ExAgent tables.
Use the same conversation namespace, Oban configuration and durable bindings.
Connect the BEAM nodes with your release's node discovery and a shared
distribution cookie. Use the same Phoenix session and LiveView signing
settings on all replicas. In the application supervisor on each node,
add registry: :global to the installed child:
{ExAgent.Conversations,
name: MyApp.Agents.Conversations,
server: {MyApp.Agents, :server_options, []},
registry: :global}Rehearse with TestModel against disposable data:
Check that
Node.list()on each node contains the other two. Open a chat on replica B and complete a turn. Open the same authorized chat on replica A. Check that the first turn is visible and thatConversations.whereis/2for the conversation key on A returns a PID on B.Send a second turn through B while A's view is still mounted. Verify that A receives the turn live. Reload the page on A and check that both confirmed turns appear once.
While B owns an active turn, queue a second turn and keep its admission key. Remove B from ingress and drain it while its Repo and Conversations supervisor still run. Add the drain to the
prep_stop/1callback in your release application module. Allow enough shutdown grace for both the drain and supervisor shutdown.require Logger @impl Application def prep_stop(state) do case ExAgent.Conversations.drain(MyApp.Agents.Conversations, timeout: 20_000) do :ok -> :ok {:error, reason} -> Logger.warning("Conversation drain #{inspect(reason)}") end state endAfter draining,
Conversations.call/4andensure/3through that manager return{:error, :unavailable}until it restarts. This includes reads.Reopen the chat on C. Verify the confirmed active turn from PostgreSQL. Read the queued turn's receipt using its original key. A successful drain cancels the local queue with reason
:stoppedand a:cancelled_before_startreceipt. To submit that message again, start a fresh turn with a fresh key.Rehearse losing B during a C7 claim. The surviving nodes' authorized Recovery workers wait for the Store's lease horizon. When Recovery leaves a record
:ready, read its current continuation reference. An authorized host dispatcher can enqueue the generatedResumeWorkerwith that reference. The worker locates or activates the current owner and the revision protects against stale delivery.with {:ok, %{status: :ready, continuation: reference}} when is_map(reference) <- ExAgent.Continuation.get(MyApp.Agents.store(namespace), id) do args = %{"conversation" => id, "continuation" => reference} Oban.insert(MyApp.Agents.ResumeWorker.new(args)) end
The registry locates the owner across connected nodes. C7 uses the Store to arbitrate turn admission during a partition. Cluster behavior · Application.prep_stop/1
Before stopping a replica, close its local admissions and drain its conversation manager while the Repo is available. Follow the Jobs runbook for the local Oban queue, shutdown grace and recovery on the remaining replica. Rolling deployment
Resume recovered conversations
After applying the unified PostgreSQL migration, add one Recovery worker per
replica below the Repo and Oban. The generated chat authorizer grants
:system the recovery operations for stored conversations in the
corresponding owner namespace. Its operation guard includes :wake_timer
to settle due timers after the owner stops, and :resume to dispatch the
ready revision. Add :wake_timer to the same authorized scope in older
generated modules. Supply namespaces from the host's trusted tenant inventory
and opt in only for definitions that can resume from the checkpoint.
{ExAgent.Continuation.Recovery,
store: MyApp.Agents.store(nil),
namespaces: &MyApp.ChatNamespaces.active/0,
actor: :system,
authorize: &MyApp.Agents.authorize/3,
on_ready: &MyApp.Agents.ResumeWorker.wake_recovered/1}wake_recovered/1 enqueues the exact ready revision, with Oban uniqueness
by reference while its delivery is retained. If the insert fails, a later
sweep can deliver the same ready revision again. The queue worker checks
ownership again and restores the conversation with create: false. A
stale reference cannot claim a newer run. An existing host can copy these
functions into its generated modules. Migration
Schedule follow-ups in the generated chat
Apply unified migration 1. In the generated MyApp.Agents.Chat module,
add the follow-up tools to the same constructor used by
continuation/0, catalogue locking and live turns.
def agent(namespace) do
follow_ups = ExAgent.Tool.FollowUp.tools(Agents.store(namespace), max_pending: 8)
ExAgent.new(
model: Application.get_env(:my_app, :chat_model, @default_model),
tools: [review_note() | follow_ups]
)
end
# Place this clause before the generated system fallback.
def authorize(:system, :deliver_follow_up, %{namespace: namespace, id: id}) do
with {:ok, id} <- Ecto.UUID.cast(id),
%Conversation{} <- Repo.get_by(Conversation, id: id, owner_id: namespace) do
{:ok, "exagent-recovery"}
else
_ -> {:error, :unauthorized}
end
end
def follow_up_options(%{namespace: namespace}), do: Agents.run_options(namespace, :turn)Agents.store(nil) builds the same catalogue descriptors for
continuation/0. Live turns use the authenticated namespace, which the
tools check against the running conversation. Regenerate the deployment
lock with mix exagent.catalog.lock after adding the tools.
Add :follow_ups to the Recovery child from the previous recipe.
The :run_options callback retains the dependencies and permissions
that the host supplies for ordinary turns.
{ExAgent.Continuation.Recovery,
store: MyApp.Agents.store(nil),
namespaces: &MyApp.ChatNamespaces.active/0,
actor: :system,
authorize: &MyApp.Agents.authorize/3,
on_ready: &MyApp.Agents.ResumeWorker.wake_recovered/1,
follow_ups: [
conversations: MyApp.Agents.Conversations,
run_options: &MyApp.Agents.Chat.follow_up_options/1
]}LiveView events and reconnect
ChatLive.Show calls Chat.get!(scope, id) to check ownership before
activating the conversation. On connected mount it attaches to the Server,
using delivery: :demand, and loads the newest 40 positions with a 64 KiB
items budget. An attached reader gets one pending :exagent_events_ready
notice. The view reads a bounded batch with Server.events_since/3 and then
acknowledges the applied cursor with Server.ack_events/4. It retries a
timed-out read or acknowledgement without waiting for new activity. The page
carries an event cursor and history revision from the same owner. On a
root terminal, including :server_request_cancelled, the view refreshes from
history and shows the current draft and progress. The Load earlier
messages button prepends older rows. A replacement reloads the latest window
even if the message count stays the same. A Server restart remounts the view.
ExAgent.Chat supplies the view and row updates. Chat.Reader handles
history reads, replay and receipt correlation for LiveView and custom UIs.
The chat reads Server.turns/2 on connected mount and refreshes it when a
root turn queues, starts, pauses or ends. Each row shows its status and a
Cancel turn button. The button passes that row's reserved run_id to
Server.abort_run/3. The view uses the confirmed root event's status, so
an uncertain cancellation is shown as needing reconciliation.
Every connected view shows a blocked conversation, including after remount and when another tab started the turn. The chat disables sending and marks existing queued turns as waiting for recovery. After an interrupted claim, the blocked row keeps its Cancel turn control. An operator can also recover the claim once its stored lease expires. Use Check recovery to refresh the state after an operator action.
The browser saves an encrypted reference for its latest cancellation in the current tab before dispatch. On reconnect the view checks retained events, the original receipt for a keyed queued turn, or a matching C7 run. The browser reference lasts up to 15 minutes. A queued receipt can confirm cancellation after the owner changes, until the key expires. The live queue belongs to the current owner. Use Check cancellation to read again when the outcome is still unconfirmed. Cancellation
On a local 2,002-message idle conversation, eight concurrent readers made
160 reads per path. The content replies per remount fell from 1,897,222 to
20,511 uncompressed ETF bytes. Median and p95 read times fell from 1,618/3,302 µs
to 55/79 µs. These are process reads on one host, excluding browser rendering
and transport. Reproduce with mix run test/support/history_remount_probe.exs.
When page.output_guarded? is false, the chat displays provisional answer
and narration from the root run in separate regions. It matches scope, emitter
and root lineage. include_draft: true provides both channels at the history
page's cursor, including deltas evicted from the event buffer. Each channel has
its own 1 MiB limit during live delivery and recovery.
Structured output, an output guardrail or any output validator sets the flag
for the whole root run. Use Guardrail.stream/3 to show reviewed answer and
narration while the final guard still controls delivery. Both readers see
progress until a reviewed draft appears or the accepted value arrives.
A remount restores
retained accepted rows from the conversation snapshot. Protected assistant
rows without acceptance evidence stay hidden.
Add a root output guard in the generated Agents.Chat module:
def agent(_namespace) do
guard = ExAgent.Guardrail.output("public-reply", fn reply ->
if MyApp.PublicReplies.allowed?(reply), do: :ok, else: {:tripwire, "unapproved_reply"}
end)
ExAgent.new(model: model(), tools: [tool()], capabilities: [guard])
end
defp policy_ref, do: %{"id" => "public-reply", "version" => "1"}Use policy_ref() in the binding constructed by continuation/1 and implement
MyApp.PublicReplies.allowed?/1 as a pure check of the final value.
Bump the policy version when the check or its settings change. Keep the
original policy and definition available to resume runs that started with
them. After a veto, remounting still shows earlier accepted replies.
Versioned guardrails
The LiveView reads only from the PID of the authorized conversation.
The browser hook saves the nonce and expiry in tab storage before dispatch.
A reported {:error, {:delivery_unconfirmed, id}} also exposes the ID
and puts the pair in the URL. On remount, the view checks the stored pair
before enabling Send. It checks the receipt or a matching root terminal
on a related event or when recovering an expired event cursor. A recovered
:cancelled_before_start receipt settles the admission and shows the
cancellation. A missing acknowledgement leaves Send disabled.
On completion, a replay gap or remount, read Server.history_page/2 with
projection: :chat and refresh pending approvals.
Render {:job_notice, notice} as host activity with the job ID, status and name.
Tool results, reasoning, provider metadata, narration and raw messages
stay out of the transcript. The authorized review card separately shows
the proposed tool arguments.
With a stopped local reader, 4,096 synthetic deltas and an eight-event buffer,
the topic bus left 4,101 messages in its mailbox and demand delivery left one.
The offline server_demand_test.exs regression checks the complete root draft
before completion and the retained terminal and transcript afterwards.
Serve a conversation over HTTP and SSE
Chat.SSE is the candidate ExAgent conversation protocol for an application
that owns its UI and wants a separate admission endpoint and a long-lived
feed. Use AG-UI for an AG-UI client that expects a standard run stream with
native tool parts and interrupts. Use the AI SDK encoder for useChat clients.
AG-UI recipe ·
AI SDK recipe
Add {:plug, "~> 1.18"} to a Plug application and forward from an authenticated
route. On every request the host resolves the authorized conversation to a
concrete owner PID. Derive its namespace from the authenticated identity.
Keep the host's CSRF protection on cookie-authenticated mutations.
forward "/api/chat",
to: ExAgent.Chat.SSE,
init_opts: [
authorize: &MyApp.ChatEndpoint.authorized_owner/1,
run_options: &MyApp.ChatEndpoint.turn_options/1
]The optional turn_options/1 callback takes the authorized connection and
returns a keyword list with :deps, :permissions and optionally
child_events: :all. Resolve the dependencies and permission policy from
trusted request assigns. The JSON body supplies the prompt. A keyed retry
uses the original turn options as part of its admission identity.
Mint an admission key on the host before the first submission and return its encoded string to the client.
key = ExAgent.Server.new_admission_key()
client_key = ExAgent.Server.encode_admission_key(key)| Request | Behavior |
|---|---|
| GET | Opens SSE. Pass the last applied cursor as Last-Event-ID when reconnecting. |
POST with Idempotency-Key | Admits {"prompt":"…"}. Retain the header and reuse the same prompt on retry. |
GET with Idempotency-Key | Reads the receipt, including a confirmed cancellation before start. |
DELETE with run_id in the query string | Requests cancellation of that turn. Watch for the matching :server_request_cancelled event or receipt. |
The host authorizes each request independently of the key. C7 retains receipts across an owner
change until the key expires. A delivery_unconfirmed response carries the
request ID. A cancellation response of acknowledged confirms receipt of the
control call. A matching event can still report an uncertain effect.
Decode each data field as JSON and keep the last applied SSE id. Apply a
snapshot as a replacement for the bounded transcript, eligible answer and
commentary drafts, turns, approval summaries, deferrals, observed activities
and the last turn's failure. C7 restores pending controls after owner
replacement. The current owner keeps up to 256 activity summaries for its
latest observed attempt, including through a replay gap.
When an idle owner has a failed last turn, its chat status is failed.
The diagnostic is also in run_failed.error. Keep any immediately shown
prompt in local state keyed by the admitted run ID until history refreshes.
Root deltas and status events include run_id and request_id.
approval_requested.pending gives item IDs, call references, tool names,
deferral kinds and any timer's UTC millisecond wake_at. The decision
and deferred-result events carry the matching identifiers and disposition.
The host reads full reviews from the authorized runtime and applies decisions
and results through its application endpoints.
For activity, upsert the nested activity by kind and id within the
current attempt. Reset the list at run_started, which may carry an initial
job activity. A new snapshot reconciles the entire list. A cursor event
advances the position by itself. The Plug acknowledges a batch after writing
it. A retained Last-Event-ID behind the head replays subsequent events
before a fresh snapshot. A cursor at the head, expired or from a previous
owner starts with a snapshot. Reconnect through the same authorized route.
A disconnected stream leaves the turn running.
Encode a Vercel AI SDK stream
ExAgent.Chat.AISDK implements AI SDK 7's UI Message Stream Protocol v1.
For a single-turn UI response, take the authorized chat page before sending
the turn. Save its cursor with the turn and use the returned run_id. Set
the response headers with Chat.AISDK.headers/0 and write the iodata from each
Chat.AISDK.push/2 in cursor order. End after Chat.AISDK.finished?/1.
A confirmed success replaces provisional text with the accepted answer,
including a structured value as JSON text, while preserving completed
tool parts and reasoning summaries. Set reasoning: redactor in
Chat.AISDK.new/3 to show reviewed provider summaries on unguarded turns.
Raw thinking remains private. Narration uses transient
data-exagent-commentary parts. Deduplicate accumulated narration by the
part ID on a full resumeStream() replay.
Tool parts use the Server call reference for toolCallId. The encoder
sends validated inputs atomically as tool-input-available. Provider
input fragments lack the admitted call identity and stay private.
The tool output uses the public event projection. It includes JSON
null and toolMetadata.exagent.contentWithheld when a successful
result's content is withheld. Execution stays on the Server. Use
message.metadata.exagent for the Server run and request IDs, terminal
status and qualified accounting. For a confirmed server cancellation,
read the status there or in data-exagent-status. The SDK's
onFinish.isAbort reports a local request abort.
Native approval requests use the C7 approval ID and a tool part with
null input until admission. Read review details through the authorized
host. Apply decisions with Server.decide/4 and resume with the resulting
reference. Start a fresh encoder for the next attempt with the same root run
ID and resume_after: Event.cursor(previous_pause), where previous_pause
is the preceding confirmed :run_paused event. Feed the retained run events
from the first attempt, including decisions and deferral receipts. The SDK
rebuilds the assistant message on resumeStream(), so every resumed stream
includes the earlier tool results. An approved or denied decision
reconstructs its native approval before emitting the response.
An immediate permission denial uses a tool error with ExAgent status
denied. The SDK's native denied output requires a review decision.
An approved edit carries the validated edited input when execution starts
and reports the edit in data-exagent-status. Cancellation, expiry, timer,
input and other deferrals also use status data. Only C7 commits the
decisions and effects.
AI SDK 7 stream protocol
Admit and resume with useChat
Use the SDK's user message ID as the stable client ID for a turn. Send the newest user message to the controller and keep its ID across network retries.
import { useChat } from '@ai-sdk/react'
import { DefaultChatTransport } from 'ai'
const { sendMessage, regenerate, resumeStream } = useChat({
id: conversationId,
transport: new DefaultChatTransport({
prepareSendMessagesRequest: ({ id, messages, trigger, messageId }) => ({
api: `/api/chats/${encodeURIComponent(id)}/turns`,
body: trigger === 'regenerate-message'
? { trigger, messageId }
: { message: messages.at(-1) },
}),
prepareReconnectToStreamRequest: ({ id }) => ({
api: `/api/chats/${encodeURIComponent(id)}/stream`,
}),
}),
})For POST /api/chats/:id/turns, authorize access and validate the message
ID, role and supported parts. Atomically get or insert a row keyed by
{namespace, conversation_id, message_id} in shared PostgreSQL. On insert,
mint and encode a Server.new_admission_key/0. Store that encoded key and
a digest of the validated prompt. A unique constraint arbitrates
simultaneous inserts. Read the winning row and reject a changed prompt
for the same message ID. Decode the saved key and pass it to
Server.send_message/3 as :idempotency_key, along with stream_text: true
and host :deps.
Use Server.receipt/3 with the same key to resolve an uncertain POST.
Preserve the key's expiry across retries. Reconcile an expired submission
before offering a new logical turn. Use the confirmed receipt's run ID
to open the SDK stream.
When the user calls regenerate(), authorize the source, reserve a fresh
branch ID and its admission key, and pass the request to
Chat.AISDK.regenerate/3. The encoder uses the root run ID as the assistant
message ID. The host can map its own message IDs to :at. The selected
prompt comes from the stored source. Initialize the stream from the
returned branch owner and use its new run ID. Return the branch ID to the
client with a transport header or app event and use it for later turns and
reconnects. For an edited user message, validate the replacement and pass
it as :prompt to Server.regenerate/2.
AI SDK transport contract
For GET /api/chats/:id/stream, authorize again and resolve the current
owner. Use Server.turns/2 for the live turn, or the host's saved run ID
when replaying an attempt that just settled. Return 204 No Content when
there is no response to replay. Load an authorized chat page and attach
to demand delivery. Read Server.events_since/3 from the saved pre-admission
cursor and check that the first :run_started for the run is retained
before sending SSE headers. For a resumed attempt, select the confirmed
pause immediately before that attempt for :resume_after. A confirmed
pause in the selected attempt ends its stream. Feed the encoder from the
start of the run, then follow ordered events and acknowledge each written
batch until the stream finishes or the client disconnects.
If the prefix expired or the cursor belongs to a replaced owner, tell the
client to refresh its chat snapshot. Before sending SSE headers, return
409 Conflict with an application code such as replay_expired. If headers
have been sent, end the stream and refresh the client on an interrupted
response. Reload confirmed rows and any eligible draft via
Server.history_page/2 with projection: :chat, include_draft: true.
Replace the client's provisional message with that snapshot.
AI SDK resumable streams
Serve AG-UI from Phoenix
Route POST /api/agent/run to your Phoenix controller. Authenticate the
request and resolve its thread to an authorized Server PID. Reserve the
wire run ID for this attempt in the host and pass the trusted IDs to
Chat.AGUI.Input.decode(body, %{thread_id: thread_id, run_id: run_id}).
Enforce a request body limit in the transport. The decoder projects the
final user message and keeps the Server's accepted transcript. It drops
state, forwardedProps and context unless the host lists fields under
:allow. Use selected fields as application data. Read identity and runtime
settings from the host.
With the authorized namespace, conversation id and decoded input,
attach before dispatch and keep the history page's event cursor. The
receipt's Server run ID identifies the attempt to stream.
alias ExAgent.{Chat, Server}
:ok = Server.attach(server, self(), delivery: :demand)
{:ok, page} = Server.history_page(server, projection: :chat, include_draft: true)
{chat, _} = Chat.apply_page(Chat.new(namespace, id), page)
cursor = page.event_cursor
{:ok, receipt} =
Server.send_message(server, input.message.text,
stream_text: true,
child_events: :all,
idempotency_key: admission_key
)
stream_agui(conn, server, chat, cursor, receipt.run_id, input)The controller can use this loop after admission. input is the validated
decoder result, and cursor is the page cursor from before dispatch.
alias ExAgent.{Chat.AGUI, Server}
import Plug.Conn, only: [put_resp_header: 3, send_chunked: 2, chunk: 2]
defp stream_agui(conn, server, chat, cursor, server_run_id, input) do
encoder =
AGUI.new(chat, server_run_id, thread_id: input.thread_id, run_id: input.run_id)
conn =
AGUI.headers()
|> Enum.reduce(conn, fn {key, value}, conn -> put_resp_header(conn, key, value) end)
|> send_chunked(200)
stream_events(conn, server, cursor, encoder)
end
defp stream_events(conn, server, cursor, encoder) do
receive do
{:exagent_events_ready, ^server, notice} ->
with {:ok, page} <- Server.events_since(server, cursor, notice: notice),
{events, encoder} <- Enum.flat_map_reduce(page.items, encoder, &agui_event/2),
{:ok, conn} <- chunk(conn, AGUI.sse(events)),
:ok <- Server.ack_events(server, notice, page.cursor) do
if AGUI.finished?(encoder), do: conn, else: stream_events(conn, server, page.cursor, encoder)
else
{:error, _reason} -> conn
end
after
30_000 -> conn
end
end
defp agui_event(event, encoder) do
{encoder, events} = AGUI.push(encoder, event)
{events, encoder}
endDetach in the action's after block. A timeout, disconnect or expired
cursor truncates the stream. Refresh through the authorized chat history
route and give a subsequent AG-UI request a fresh run ID. The exported
state document holds the current step.
Use the terminal result for the accepted answer. Text deltas can show
reviewed or unguarded drafts before that answer is available.
Pass child_events: :all on both the initial admission and any observed
resume for delegated run activity. For generated C7 chat, use a trusted
helper with its durable binding.
Include the tool in Agents.Chat.agent/1 and the helper entry in
Agents.Chat.catalog/2 with the active root entry.
Durable delegation recipe
delegate = ExAgent.Coordination.delegation_tool(helper, name: "summarize", continuation: binding)
# In catalog/2, using the generated binding for the active root agent.
ExAgent.Catalog.new([
{active_binding.definition, active, active_binding},
{binding.definition, helper, binding}
])A C7 child started without the descriptor is refused with
:continuation_child_descriptor_required. With the descriptor, Frame3
provides live start and stop activity for each executed child attempt.
A resumed child updates its existing activity message. Activity messages
also carry identifiers and status for acknowledged background submissions
and terminal job notices.
Use reasoning: &MyApp.Reasoning.review/2
in AGUI.new/3 to opt in to reviewed provider summaries on unguarded turns.
Activity and summary fields
For a resume, use the authenticated thread's current paused attempt and
a fresh wire run ID. In the decoder binding add :resume with the
authorized conversation :id and :namespace, the :record_id and
:revision from Server.continuation/1, and :pending from
Server.pending/1 for that revision. If the revision changed, refresh
the pending view. resume contains one entry per approval, input request
and declared frontend tool deferral. Send
%{"approved" => true} or %{"approved" => false} for approval.
An input_required interrupt and exagent.input carry identifiers for
form review. Retrieve the form through an authorized pending read and
use the MCP response map as the interrupt's payload.
Show timer_wait and exagent.timer with the supplied wakeAt as status.
Omit timer and host-owned external IDs from resume. The host or Recovery
settles those items. A request with only passive waits stays paused.
Apply {:decide, request, decision} with Server.decide/4 and
{:input, call, supplied} with Server.supply_result/4. Supply trusted
tools and the host authorizer. Begin reading before committing commands
and resume with the exact ready reference after every item has settled.
ExAgent keeps the original Server run ID. For frontend tools, expose
host-built Chat.AGUI.Input.frontend_tool/1 definitions in the decoder
binding and offer the returned tools with the run's C7 definition.
Arrange browser execution after the confirmed external deferral and use
an authorized result receipt as the interrupt payload.
Persisted decisions
AG-UI adapter security release
Queue delivery
The browser submits an operation ID. The server finds the corresponding held
request from Server.pending/1. The generated Agents.Chat.decide/4 checks
scope, owner, request identity and Repo. In one Repo transaction it calls
Continuation.decide/4 with the host authorizer and enqueues its exact
continuation reference when the reply contains one. Approve, deny with a message,
or submit edited arguments if the request offers editing. A denial with an
empty reason records the default denial message.
The generated chat also reads input deferrals from the authorized Server. It presents guarded flat forms and validates typed answers against the saved request. In one transaction it commits the answer and enqueues the ready reference with Oban. External deferrals show a waiting status.
For tenant-owned chats, resolve namespace(scope) from the authenticated
server-side scope. The generated owner_id then stores the tenant namespace.
Keep the namespace and request checks in decide/4. In authorize/3, check
the caller's current membership and role in that tenant and load the target
chat through the scoped query. Return the reviewer's individual ID. C7 stores
that string as the actor for the decision.
def authorize(%MyApp.Accounts.Scope{user: %{id: user_id}} = scope, operation, %{id: id})
when operation in [:approve, :deny] do
tenant_id = namespace(scope)
with {:ok, %{role: :reviewer}} <- MyApp.Accounts.fetch_membership(tenant_id, user_id),
%{owner_id: ^tenant_id} <- Chat.get!(scope, id) do
{:ok, "user/#{user_id}"}
else
_ -> {:error, :unauthorized}
end
end
def authorize(_, _, _), do: {:error, :unauthorized}fetch_membership/2 is a host query for an active membership by tenant and
user. The example permits approval and denial. Check edit authority separately
before adding :edit. If user IDs are unique only within each tenant, include
the tenant in the actor ID.
Agents.ResumeWorker resolves the owner and ID from the conversation row
and calls Server.resume(server, reference, opts) with the job's versioned reference through
Conversations.call/4 with create: false. The owner and C7 claim check the
original record, run and revision. A stale reference cancels the job, including
a duplicate after the revision has advanced. Jobs from older generated chats
require evidence or explicit recovery.
Queue upgrade
A busy Server snoozes for five seconds if the reference still matches.
The worker uses the saved definition to choose a queue from the
:chat_resume_queues application setting. Keys are definition references and
values are configured Oban queues. A replica without that definition snoozes
without spending the retry allowance. A binding mismatch cancels the
delivery with {:definition_incompatible, field} and leaves the C7 record
available for diagnosis. Transient registry errors retry with backoff.
An uncertain external effect requires reconciliation before another attempt.
The generated Chat.binding/2 derives a version from the model, policy,
tool schemas and static instructions. When changing a callable or codec,
advance its definition revision and retain the old factory and binding in
Chat.catalog/2. Deploy both definitions before activating new admissions.
Retire a definition
For standalone runs without a Server, the source checkout includes
examples/continuation_integrations/job_dispatch.ex. Follow the
continuation job recipe for dispatch and recovery.
The Jobs.Durable worker uses certified quota refusals
to schedule the same job or record expiry before its first effect.
If you copied the dispatcher in 2.3, port its
resume branch before draining the queue.
Livebook and Ash
KinoExAgent renders results, responses and events in Livebook. Its widget displays a conversation from an already authorized Server PID using the shared chat reducer. Every collaborator in that notebook shares the Server's scope. For a cluster, connect the notebook runtime and match the release's ExAgent build before passing it the authorized PID. Cluster setup in KinoExAgent
The candidate ExAgentAsh package builds tools from an Ash domain or a list of
public actions with ExAgentAsh.tools/2. Writes require approval by default.
Supply the authenticated actor and tenant in deps: when starting or
resuming a run. Ash enforces its policies when the tool executes.
mix igniter.install exagent_ash prepares the Store migration in an
AshPostgres app.
Ash package
Ingest durable jobs with Broadway
Use Broadway to limit demand from a broker and Oban to run the agents that
were durably admitted. Add {:broadway, "~> 1.3"} to the host and install
the Repo, Oban queue and schemas.
Broadway ·
Durable Jobs
This example sizes ingestion for 40 of the provider's 60 RPM. A job
can make five logical requests, so the producer forwards up to eight messages
per minute. Four processors each ask for one in-flight message. Start the
Oban :enrichment queue with concurrency four and supervise the quota
limiter before starting the workers and the pipeline.
defmodule MyApp.EnrichmentQuota do
def child_spec(_opts) do
ExAgent.RateLimiter.child_spec(
name: __MODULE__,
limits: %{"openai" => [rpm: 60, tpm: 100_000, concurrency: 4]}
)
end
def requests_per_job, do: 5
def messages_per_minute, do: div(40, requests_per_job())
end
defmodule MyApp.EnrichmentWorker do
use ExAgent.Jobs.Durable, queue: :enrichment
@impl ExAgent.Jobs.Durable
def resolve(_namespace, %{"id" => "enrich", "version" => "1"} = definition) do
model = "openai:gpt-6-luna"
agent = ExAgent.new(model: model, rate_limiter: MyApp.EnrichmentQuota)
{:ok, agent,
%{
definition: definition,
policy: %{"id" => "enrichment-policy", "version" => "1"},
model_ref: %{"id" => model, "version" => "1"}
}, []}
end
def resolve(_, _), do: {:error, :not_found}
end
defmodule MyApp.Ingest do
use Broadway
alias Broadway.Message
alias ExAgent.Jobs.Durable
alias MyApp.{EnrichmentQuota, EnrichmentWorker}
@definition %{"id" => "enrich", "version" => "1"}
def start_link(producer) do
Broadway.start_link(__MODULE__,
name: __MODULE__,
producer: [
module: producer,
concurrency: 1,
rate_limiting: [allowed_messages: EnrichmentQuota.messages_per_minute(), interval: 60_000]
],
processors: [default: [concurrency: 4, min_demand: 0, max_demand: 1]]
)
end
@impl Broadway
def handle_message(
_,
%Message{data: %{namespace: namespace, job_id: id, prompt: prompt}} = message,
_
) do
jobs = Durable.new(EnrichmentWorker, namespace)
case Durable.start(jobs, id, @definition, prompt,
request_limit: EnrichmentQuota.requests_per_job()
) do
{:ok, ^id} ->
message
{:error, reason}
when reason in [
:conflict,
:expired,
:invalid_record_key,
:missing_exagent_jobs_table,
:jobs_migration_required
] ->
Message.failed(message, reason)
{:error, {:delivery_unconfirmed, ^id}} ->
Message.failed(message, :admission_unconfirmed)
{:error, _} ->
Message.failed(message, :admission_failed)
end
end
def handle_message(_, message, _), do: Message.failed(message, :invalid_envelope)
endPass the broker's producer as {module, options}. Its transformer should
produce a trusted envelope with an authorized namespace and a bounded prompt.
Mint Durable.new_id/1 once at the source and persist it with the envelope.
On broker redelivery or a lost reply, submit the same ID, prompt, definition
and limits. Acknowledge success after Durable.start/5 confirms the
transaction. Configure the connector to retry temporary failures with the
same envelope. Dead-letter conflicts, expired IDs, invalid input and job
schema errors. Apply the required migration before redriving schema failures.
Broadway's producer rate is local sizing. Retries, fallback attempts and other traffic still compete for the same provider quota. ExAgent's limiter enforces RPM, estimated TPM, concurrency and cooldown at each dispatch. Across replicas, use a shared quota adapter and size aggregate producer demand for the shared budget. If arrivals can outpace completions, bound the outstanding durable backlog at the source. Broadway demand limits messages in flight through the pipeline. See shared provider quotas and durable quota refusals.