Durability and approvals

View Source

Real business agents don't just answer questions — they issue refunds, send emails, update tickets and run long workflows that must pause for human sign-off or survive a deploy. Hand-rolling pause/resume over a database is notoriously tricky: a single crash right after calling a payment API can easily cause duplicate charges if the system blindly retries.

What ExAgent simplifies:

  • Crash-safe checkpoints (store:): Persist ExAgent.Server history and atomic continuation journals in ETS (dev/tests) or PostgreSQL (production).
  • Pause for approvals and external deferrals (ExAgent.Continuation): Approvals (requires_approval: true or :ask in ExAgent.Permissions) pause cleanly before the tool runs and write an atomic compare-and-swap (CAS) checkpoint. Deferred tools (requires_deferral: true) hand work off to an external queue and return {:defer, meta}, pausing until the external result is supplied (volatile runs reject them before any effect intent).
  • Zero blind replays: If a process dies while an external effect is in-flight, ExAgent marks the outcome :uncertain and waits for explicit host reconciliation rather than guessing or repeating an unconfirmed mutation.
  • Safe rolling deploys (ExAgent.Catalog & Recovery): Versioned definitions let old in-flight approvals finish cleanly while new conversations use your latest code, with supervised lease recovery and timers.

Need exact CAS states, journal formats or storage benchmarks?

For full continuation state diagrams, PostgreSQL schema details and segmentation timings, see Runtime & ops contracts.

Add a conversation checkpoint

Start with simple conversation snapshots by passing store: (:ets for in-node dev/testing, or {ExAgent.Store.Postgres, MyApp.Repo} after applying unified ExAgent migration 1):

{:ok, server} = ExAgent.AgentSupervisor.start_agent(
  agent: ExAgent.new(model: "test"),
  agent_id: "docs-checkpoint",
  namespace: "docs-workspace",
  store: :ets
)

{:ok, result} = ExAgent.Server.chat(server, "Hello!")
:ok = ExAgent.Server.checkpoint(server)
result.output

For write-heavy PostgreSQL workloads with long conversations, pass segments: true on the Store to deduplicate unchanged history and attachment fragments across revisions (Migration · Segmented store notes).

Browse conversation headers

List standalone conversation headers within an authenticated namespace without loading full message bodies until the user opens a thread:

alias ExAgent.Store

store = Store.scoped(:ets, "docs-workspace")
{:ok, %{items: headers, cursor: cursor}} = Store.list_agent_headers(store, limit: 20)
if cursor, do: Store.list_agent_headers(store, limit: 20, after: cursor)
for %{agent_id: id} <- Enum.take(headers, 1), do: Store.load_agent_snapshot(store, id)

Use persisted approval

When a tool declares requires_approval: true (or matches an :ask rule in Permissions), passing a :continuation map pauses the run atomically before the tool runs. The example below uses ETS (durability: :ephemeral) so you can run it locally across process restarts inside one VM; for deploys and node restarts, swap in {ExAgent.Store.Postgres, MyApp.Repo} with durability: :durable after applying unified migration 1:

alias ExAgent.{Continuation, Store}

binding = %{
  durability: :ephemeral,
  expires_at: nil,
  lease_ms: 30_000,
  definition: %{"id" => "support", "version" => "1"},
  policy: %{"id" => "support", "version" => "1"},
  model_ref: %{"id" => "support-model", "version" => "1"},
  model_codec: codec
}

config =
  Map.merge(binding, %{
    store: Store.scoped({Store.ETS, :approvals}, "workspace-a"),
    id: "order-42"
  })

# Pauses *before* the tool executes and records a confirmed checkpoint.
{:ok, %{status: :paused}} = ExAgent.run(agent, "Refund order 42", continuation: config)
{:ok, [request]} = Continuation.pending(config.store, "order-42")

# Return {:ok, actor_id} to authorize; any other value or raise returns :unauthorized.
authorize = fn actor, _operation, _target -> {:ok, actor} end

{:ok, %{status: :approved, continuation: ready_ref}} =
  Continuation.decide(config.store, request, :approve,
    actor: "reviewer-1",
    authorize: authorize
  )

{:ok, %{status: :succeeded, output: output}} =
  ExAgent.resume(agent, ready_ref, continuation: config)

Reviewers can supply :approve, {:approve, args: map} (when editing is permitted, passing tool: or catalog: so arguments re-validate against the schema and permissions), :deny, {:deny, message: text}, or :cancel. ready_ref is nil while other approvals on the same run remain open — always resume with the new non-nil reference returned once the run becomes ready, never the replaced pause reference. The run resumes using your live agent, tools and credentials — secrets are never stored in the database.

Configure an agent continuation

In production, set durability: :durable with a PostgreSQL Store, a realistic lease_ms: (e.g., 30_000–120_000), and explicit versioned definition:, policy: and model_ref: maps so resume verifies the saved run still matches your deployed code.

When wiring continuations into ExAgent.Server, pass store:, namespace: and agent_id: as top-level Server options (Server reserves :store and :id and rejects them inside :continuation), passing only the shared binding map under continuation::

{ExAgent.Server,
 agent: agent,
 store: {ExAgent.Store.Postgres, MyApp.Repo},
 namespace: "workspace-a",
 agent_id: "order-42",
 continuation: Map.put(binding, :durability, :durable)}

See Framework integrations for a full Phoenix + Oban + PostgreSQL setup.

Automate a persisted approval

Want a trusted policy classifier or LLM reviewer to pre-screen low-risk approvals while escalating uncertain ones to humans? ExAgent.Judge.Approval splits review from commit under the same host authorize/3 boundary:

alias ExAgent.Judge.Approval

authority = [actor: reviewer, authorize: &MyApp.Approvals.authorize/3, catalog: catalog]

with {:ok, review} <-
       Approval.review(store, request, authority ++ [classifier: classifier, version: "2"]),
     {:ok, reply} <- Approval.commit(store, review, authority) do
  reply.continuation
end

Defer a tool call

When a tool hands work off to an external asynchronous system (declaring requires_deferral: true and returning {:defer, meta} after submission), the continuation pauses until your webhook or Oban worker supplies the confirmed result:

ExAgent.Continuation.supply_result(store, call, {:succeeded, %{"url" => url}},
  actor: actor,
  authorize: authorize,
  tool: tool
)

Then call ExAgent.resume/3 (or ExAgent.Server.resume/3) with the returned continuation reference to finish the agent loop.

Schedule a reminder without pausing the chat

Need an agent to follow up later ("Check back on this shipment in 2 hours") while the user keeps chatting right now? Add ExAgent.Tool.FollowUp.tools/2 and enable follow_ups: on ExAgent.Continuation.Recovery:

tools = ExAgent.Tool.FollowUp.tools(store, max_pending: 8)

{ExAgent.Continuation.Recovery,
 store: store,
 actor: :system,
 authorize: &MyApp.Agents.authorize/3,
 follow_ups: [conversations: MyApp.Conversations]}

When the timer fires, Recovery dispatches a %ExAgent.Message.Part.JobNotice{follow_up: topic} turn to the conversation automatically.

Bind guardrails to a continuation

When using guardrails (ExAgent.Guardrail) on a durable agent, version them via :policy in your continuation config (and on each ExAgent.Handoff destination). If you change a guardrail rule, bump the policy version so in-flight pauses are reviewed under the exact policy they were created with.

Find work across runs

Build an operator dashboard or approvals inbox across a tenant namespace using ExAgent.Continuation.list_runs/2 (filter by status such as :pending, :approved, :uncertain or :executing) and ExAgent.Continuation.get/2 for one run's summary (or Continuation.get/3 with diagnostics: true for authorized operator inspection).

Recover uncertainty explicitly

If a worker crashes mid-flight, its lease expires without guessing whether the external HTTP call succeeded:

  • Lease expired before an effect started: ExAgent.Continuation.recover/3 transitions the run back to :ready so it can resume cleanly.
  • Process crashed during an unconfirmed external effect: the run enters :uncertain. Inspect your external system (Stripe, database, MCP peer) and reconcile explicitly before resuming.

Reconcile an effect

Tell ExAgent what actually happened in the external system with ExAgent.Continuation.reconcile/5 (or reconcile_tool/4 / reconcile_model/5 when recording a tool or model outcome directly):

  • Confirmed success → supply the external return value so ExAgent records it without calling the tool a second time.
  • Confirmed never executed → mark it safe to retry (or call ExAgent.Continuation.retry_effect/4 with an idempotency key when explicit retry is authorized).
  • Confirmed failed → record the failure cleanly and let the model or operator decide next steps.

Recover a declared tool effect

Tools tagged effect: :read can be recovered automatically without human intervention when a lease expires (and context-aware :write tools can attach a read-only :reconcile callback to inspect their original idempotency key), while ordinary :write tools always stay protected from automatic replay.

Recover a persisted handoff

If an agent paused or lost its lease after transferring control to a Handoff destination, the root continuation journal preserves the transfer and destination policy so recovery resumes the active specialist directly without re-running the triage agent.

Supervise recovery for a namespace

Add ExAgent.Continuation.Recovery to your supervision tree to sweep expired leases, fire due follow-up timers and notify your app when runs become ready to resume:

{ExAgent.Continuation.Recovery,
 store: store,
 actor: :system,
 authorize: authorize,
 policy:
   ExAgent.Continuation.Recovery.Policy.default(
     resolve_tool: &MyApp.Tools.resolve_recovery_tool/1
   )}

Deploy with open continuations

Never break in-flight approvals on deploy. Register both old and new versions of your durable agents in an ExAgent.Catalog (verified in CI by mix exagent.doctor --check-catalog-lock):

catalog = ExAgent.Catalog.new([
  {old_binding.definition, old_agent, old_binding},
  {current_binding.definition, current_agent, current_binding}
])

runtime = %{store: store, id: ref.id, durability: :durable, lease_ms: 30_000, expires_at: nil}
ExAgent.resume(catalog, ref, continuation: runtime)

ExAgent.resume/3 resolves the exact saved definition from catalog, or an authorized operator can migrate an open record onto a newer compatible version explicitly with ExAgent.Continuation.adopt/4.

Erase a conversation and its branches

Need GDPR / right-to-be-forgotten deletion? ExAgent.Retention discovers every record belonging to a conversation family (standalone snapshots, forks, continuation journals, admission receipts, offloaded results, durable jobs and pending follow-ups) and erases them cleanly:

alias ExAgent.Retention

{:ok, page} = Retention.inventory(store, id: conversation_id, limit: 50)
family_ids = for {:conversation, id} <- page.items, do: id

{:ok, receipt} = Retention.erase(store, conversation_id, owners: remote_owner_pids)

Reset history after a failed turn

To clear a Server's active conversation history and stored failure evidence while keeping the conversation ID reusable, call ExAgent.Server.reset/1 (see Cancel and checkpoint):

:ok = ExAgent.Server.reset(server)
{:ok, %{record: record}} = ExAgent.Server.continuation(server, diagnostics: true)
Map.has_key?(record["execution"]["progress"], "failure_evidence")
# => false

Implement a custom snapshot Store

Need to store snapshots in a database other than PostgreSQL or ETS? Implement the snapshot callbacks of ExAgent.Store (save_agent_snapshot/2, load_agent_snapshot/2, etc.) and serialize/deserialize snapshots using ExAgent.Server.Snapshot.serialize/1 & deserialize/1 (and ExAgent.Session.Snapshot for sessions). Keep atomic continuations on the bundled ETS or PostgreSQL adapters.

Test a custom Store

Drop use ExAgent.Store.ContractCase into your ExUnit test suite to verify your custom adapter against ExAgent's full snapshot and namespace isolation contract automatically:

defmodule MyApp.SnapshotContractTest do
  use ExUnit.Case, async: true
  use ExAgent.Store.ContractCase

  setup do
    name = __MODULE__.Snapshots
    start_supervised!({ExAgent.Store.ETS, name: name})
    {:ok, store: {ExAgent.Store.ETS, name}}
  end
end

API: ExAgent.Store, ExAgent.Store.Postgres, ExAgent.Continuation, ExAgent.Continuation.Recovery, ExAgent.Catalog, ExAgent.Retention, ExAgent.Judge.Approval.