Jobs with persisted approvals

View Source

Generate a background agent

In a Phoenix or Mix app with ExAgent and a PostgreSQL Ecto Repo, run the candidate generator. Use the igniter_new archive from the chat setup or an Igniter dev dependency already present in your app.

mix exagent.gen.agent Billing.Refunds --yes
mix ecto.create
mix ecto.migrate
mix test
mix exagent.eval

Run the Ecto commands in the same Mix environment as the app or test database you are preparing. Phoenix's generated test alias already runs its test migrations. The generator configures Oban when needed. It creates YourApp.Agents.Billing.Refunds, its tools, an Oban worker, and tests that demand review and recover a committed write after losing the worker. The starter uses Models.Test and a strict cassette substitute for the example write in Eval. --no-durable emits the definition, tools, unit tests and Eval without database infrastructure. Rerunning generation preserves host edits. When the host manages Oban plugins, enable Lifeline in that configuration.

From trusted host code, use Durable.new(YourApp.Agents.Billing.Refunds.Worker, tenant_id) to bind the worker to an authorized tenant. Persist an ID from Durable.new_id/0 with the host operation, then call Worker.start(jobs, id, reference). Read the pending review and persist your authorized decision together with Durable.wake/2. The generated recovery policy can read a stored receipt to reconcile a write. An uncertain outcome without evidence stays open.

The starter caps requests and tool calls per run. Attach shared spend by selecting a tenant Budget in the host's worker definition. When replacing the scripted model, update the versioned model binding and codec in the worker. Tenant Budget

After customizing the generated definition, refresh priv/exagent/catalog.lock. Follow the draft lock replacement steps if only draft definitions are locked and no durable runs or queued jobs you intend to keep use them. Retain the version of any deployed definition that still has durable work. Refresh the catalogue lock

Durable background agents and tools with Oban

Add {:oban, "~> 2.24"}, :ecto_sql and :postgrex to your host. Jobs.Durable is compiled when Oban is available. If ExAgent was already built, fetch and compile the new dependencies, then run mix deps.compile exagent --force in the same Mix environment before compiling workers or applying migrations.

Start Oban on your Repo with the worker's queue enabled. Apply the Oban migrations and the unified ExAgent migration. Backfill headers on an existing table. For the optional segmented layout, pass segments: true to use ExAgent.Jobs.Durable. Both worker configurations support operator reads and decisions. Run header migration Both tables use the Repo's default schema. If chats use saas_snapshots, pass it as the custom table. The unified migration also installs exagent_snapshots and the keyed-turn receipt columns. Unified migration Use a fixed PostgreSQL Repo on every node, with Oban's normal persisted engine in production and testing: :manual in tests. Keep the Repo and Oban prefix stable. A cached handle returns {:error, :unavailable} when a new delivery would use a replacement instance on another Repo or prefix. Use Doctor's --check-jobs with :jobs_repo to verify the admission schema. Check the unified migration if start/5 reports :missing_exagent_jobs_table or :jobs_migration_required.

defmodule MyApp.MeasureWorker do
  use ExAgent.Jobs.Durable, queue: :exagent, max_attempts: 20
  alias ExAgent.{Jobs.Durable, Tool}

  @impl ExAgent.Jobs.Durable
  def resolve(_tenant, %{"id" => "measure", "version" => "1"} = ref) do
    tool = Tool.new(
      name: "length",
      effect: :read,
      takes_ctx: false,
      parameters_json_schema: %{
        "type" => "object", "required" => ["text"],
        "properties" => %{"text" => %{"type" => "string"}}
      },
      call: fn %{"text" => text} -> String.length(text) end
    )

    Durable.tool(ref, tool, %{"id" => "measure-policy", "version" => "1"})
  end

  def resolve(_, _), do: {:error, :not_found}
end

alias ExAgent.Jobs.{Durable, Job}
jobs = Durable.new(MyApp.MeasureWorker, "tenant-42")
id = Durable.new_id(3_600_000)
ref = %{"id" => "measure", "version" => "1"}
{:ok, ^id} = Durable.start(jobs, id, ref, Jason.encode!(%{text: "hello"}), request_limit: 2)
{:ok, %Job{} = state} = Durable.wait(jobs, id, 10_000)
# Once succeeded, Jason.decode!(state.result) is %{"status" => "succeeded", "content" => 5}.

For an ordinary agent, the resolver returns {:ok, agent, %{definition: ref, policy: policy_ref, model_ref: model_ref, model_codec: codec}, run_opts}. These are the same trusted policy/model references and codec used by Frame3. Use catalog: &catalog/1 in the worker's use ExAgent.Jobs.Durable options to resolve the saved reference through an ExAgent.Catalog. The function receives the trusted namespace and returns the catalogue or {catalog, run_opts} for fresh run dependencies. The optional binding keys are :rehydrate_tools and :max_checkpoint_bytes. Run options are durable leaf options, including dependencies and permissions. Use C7 decisions for approval. A resolver that supplies an :approve callback leaves the job :blocked with its start reservation available for a corrected wake. The queue runs buffered agents. Live streams, workflow definitions, anonymous background functions and caller-owned execution scopes are outside this API. Keep the resolver and optional server(namespace, job_id) lookup pure. Deliveries can call them more than once. Keep the old version available until its last job settles. Workers derive a dedicated C7 namespace from the worker module name and authenticated host namespace. Keep both stable across deploys.

Persist the ID with the triggering host operation. The same ID and inputs deduplicate concurrent submissions and retries, including after an ambiguous database reply. A changed prompt, version or budget conflicts. start/5 also participates in an enclosing Repo transaction. It persists prompt text in the admission table; the Oban payload contains only the namespace and ID. Repeating a committed admission reads the existing receipt during an Oban restart. A new ID needs a running queue instance. Internal inserts disable Oban uniqueness for both starts and wakes. The receipt and C7 guard execution. Run workers and manual queue drains outside host transactions. Delivery inside a Repo transaction returns {:error, {:unsupported, :transactional_delivery}} before resolving the worker or sending a notice. Rollback of an enclosing transaction still removes its new admissions and wakes. The SQL adapters suppress Ecto query events and logging for receipt and snapshot payloads, including query results. Other host SQL and database logging use the host's own configuration. Apply the same access, logging and backup policies as for C7 history.

Each job owns its request budget (50 by default), tightened by the agent's limits, and a fixed UTC expiry embedded in its ID. Standalone tools use two local model steps. :active_time_limit_ms optionally adds a C7 active-time budget. An unconfirmed attempt can consume its whole reservation. Its budget stays spent after recovery. The default lease is a 60-second recovery window. An active writer renews the claim through model and tool calls, up to the job's deadline or expiry. An elapsed execution lease gives state :recovery_required and, when there is no prior refusal diagnostic, "continuation_lease_expired". If the lease reached the run's deadline or expiry first, the diagnostic is "deadline_exceeded". Recovery

  • Durable.status/2 reads a %ExAgent.Jobs.Job{} with the notice receipt in :notification. Durable.wait/3 polls the same state for up to the supplied milliseconds, including connection checkout and both SQL reads. Neither query changes notice delivery. At expiry it returns the last state read within budget or {:error, :timeout} if no read completed. Use a positive wait budget or call status/2 for a single read. Waits use a separate connection to read committed admissions. Durable.tools(jobs, max_wait_seconds: 60) exposes job_status and wait_job to a model scoped to the same host namespace. The wait_job argument "seconds" is an integer from 1 to that cap. Query failures include job_id, status: "unknown", code and message, using the same shape as volatile Jobs. Successful jobs retain at most 64 KiB of result text in the C7 finish checkpoint. For standalone tools, inspect the tool status inside the result. A missing C7 table gives {:error, :missing_exagent_snapshots_table}. Apply the Store migration on the Oban Repo, then wake the same admitted ID.
  • For :pending, use Continuation.pending(Durable.store(jobs), id) and the usual authorized decision or deferred-result API. Enqueue Durable.wake(jobs, id) in the same host transaction as the decision. Each wake reads C7 before work. A pending wake otherwise snoozes for at most a day, shortened to the earlier of the C7 deadline and ID expiry (rounded up to whole seconds). At that boundary status becomes :expiry_due until a delivery records expiry.
  • For :blocked, inspect the deployed resolver, run configuration and budget, correct the cause, then wake the same ID. A fresh wake clears the hold and C7 rechecks its limits. For a Job left at :recovery_required, inspect C7. Recover an expired claim and reconcile unconfirmed model/tool outcomes against external evidence using the administrative API. Then wake the same ID. A lost first-start reservation with no C7 record also requires inspection. Stop the original worker and verify the outcome, then use retire_start/2 after its lease. This closes the original admission.
  • Implement server/2 to return a stable Server address for the host conversation. Omit the callback or return nil to select query-only delivery and record a "disabled" notice. Server admits a configured notice as a turn with the job ID as request ID. Its Part.JobNotice contains that ID, the terminal status and the durable definition ID as tool_name. Bind Durable.tools(jobs) from the same namespace to the receiving agent so it can read the result. A confirmed refusal restores "pending". Correct the cause and wake the same ID if queue retries have stopped. A lost ACK or interrupted sender leaves notification "unconfirmed" or "sending". Inspect Server history and stop the sender before reconcile_notice/3 with :admitted or :abandon. Neither operation dispatches another turn.
  • Use prune/2 after the ID expires and the terminal notice settles, then apply normal C7 terminal pruning. Keep both receipts while recovery is open. Pruning clears admission content and retains a compact fence. The installed PostgreSQL maintenance can fold the expired fence of a new ordinary ID into a durable watermark. Retain the watermark and the individual tombstones of older IDs and durable Eval to prevent re-admission. Status then returns :not_found, and a new submission of the ID returns :expired. Schedule cleanup for your retained IDs and wake jobs after operational failures such as exhausting Oban attempts.

To script a model that waits for the length job above, use "seconds" => 3 in the tool arguments. The equivalent direct wait is Durable.wait(jobs, id, 3_000). Read the job status inside the tool return. A successful query can observe a job that is still queued or has failed.

alias ExAgent.Jobs.Durable
alias ExAgent.Message.Part.{ToolCall, ToolReturn}
alias ExAgent.Models.Test

call = %ToolCall{
  tool_name: "wait_job", tool_call_id: "wait-1",
  args: %{"job_id" => id, "seconds" => 3}
}

model = %Test{script: [
  {:tool_calls, [call]},
  fn messages, _params ->
    case List.last(messages).parts do
      [%ToolReturn{status: :succeeded, content: %{"status" => "succeeded", "result" => json}}] ->
        %{"status" => "succeeded", "content" => value} = Jason.decode!(json)
        "Tool result: #{value}"

      [%ToolReturn{content: %{"status" => status}}] ->
        "Job status: #{status}"

      [%ToolReturn{content: %{"error" => reason}}] ->
        "Job lookup failed: #{reason}"
    end
  end
]}

agent = ExAgent.new(model: model, tools: Durable.tools(jobs, max_wait_seconds: 60))
ExAgent.run(agent, "Read the job result.")

The inner JSON shown here is a standalone tool's result. A job for a background agent carries its rendered output as text.

For conversations managed by Conversations, return the address even when the owner has been evicted. This worker sends report jobs for an authorized namespace to its existing reports conversation.

@impl ExAgent.Jobs.Durable
def server(namespace, _id) do
  ExAgent.Conversations.via(MyApp.Chats, {namespace, "reports"})
end

While the owner is absent, delivery returns {:error, :unavailable}. The job can already be :succeeded with notification "pending". To deliver a pending notice for that job before the next visit, restore the conversation from trusted state and wake the same ID.

with {:ok, %{status: :succeeded, notification: "pending"}} <- Durable.status(jobs, id),
     {:ok, _pid} <- ExAgent.Conversations.ensure(MyApp.Chats, {namespace, "reports"}, create: false) do
  Durable.wake(jobs, id)
end

The next successful admission records notification "admitted" without rerunning completed work.

Recover a job after node loss

Enable Oban Lifeline on the instance that delivers the jobs. Implement recovery/2 on the worker to opt in for a trusted namespace and versioned definition. Pass the same authorization service you use for C7.

config :my_app, Oban, lifeline: [rescue_after: {30, :minutes}]
@impl ExAgent.Jobs.Durable
def recovery(namespace, definition) do
  [
    actor: {:job_recovery, namespace, definition},
    authorize: &MyApp.JobPolicy.authorize_recovery/3
  ]
end

The authorizer checks the namespace, definition and requested operation against the stored target. Return :manual from recovery/2 for jobs you want operators to handle. Keep the resolver and recovery configuration consistent across replicas.

Choose a window longer than a legitimate delivery. Lifeline uses execution age, so a shorter window can rescue a slow worker that is still alive. Older Oban versions configure the same option under plugins: [{Oban.Plugins.Lifeline, rescue_after: ...}]. Lifeline makes orphaned deliveries available again, or discards them if they exhausted their Oban attempts. The C7 Store checks the lease against its SQL clock again under the recovery CAS. A fresh lease keeps the owner in control.

The built-in policy cancels model-only uncertainty with its evidence intact. Use model: :leave for operator review or model: :retry if the host accepts possible duplicate provider spend for one linked attempt. A declared read can receive one linked retry with the same key. A write can use its bound reconcile: callback to read the service's outcome by that key. An unknown or denied outcome stays at :recovery_required. Recovery consults only the static Frame3 definition returned by resolve/2 with the saved references. It supports pure guardrails and pure validators. Custom capability hooks, dynamic instructions, progress and approval callbacks, cost estimators, delegation, handoffs and rehydrated tools require operator review. So do held quota refusals and a lost first start without a C7 record.

Each confirmed recovery decision snoozes the same Oban delivery. The next visit reads the journal and can resume a ready or approved record or deliver a terminal notice. If the node dies before Oban acknowledges the snooze, Lifeline can rescue the delivery again. Monitor [:exagent, :continuation, :recovery] for decisions left in the inbox (:left) or rejected (:rejected). The event reports operation and status.

During a rolling deployment

Configure the worker with use ExAgent.Jobs.Durable, catalog: &catalog/1 to resolve the job's saved definition in the trusted namespace catalogue. Define delivery_queue(namespace, definition) to send starts and wakes to an Oban queue enabled on replicas serving that version. Keep a queue for each retained version enabled while its deliveries drain.

If a replica lacks a version, it snoozes the same delivery and records "definition_unavailable" in Job.error and Job.diagnostic.type. The snooze preserves the Oban attempt allowance. A definition with an incompatible binding is held for recovery with "definition_incompatible" and the mismatched field. Deploy the matching binding and wake the original ID after addressing the diagnosis. Deployment sequence

Jobs with a durable timer report Job.retry_at while the timer is open. Oban schedules a redelivery for the earlier of the next timer or the job expiry. An elapsed timer is settled using the SQL clock and a C7 CAS. The following delivery resumes the same ready revision. Timer setup

Keep the Repo, conversation manager and Oban in that supervisor order. In the application's prep_stop/1 callback, stop admitting new traffic on this replica and pause its local queue with Oban.pause_queue(MyApp.Oban, queue: :exagent, local_only: true). Give active deliveries their configured :shutdown_grace_period with the Repo available. If the host waits for deliveries before draining conversation owners, use Oban.check_queue/2 and a deadline within its shutdown budget. Call ExAgent.Conversations.drain(MyApp.Chats, timeout: 30_000) with the remaining shutdown budget while the Store is still available. The drain lets the active turn checkpoint and confirms queued cancellations. An unconfirmed drain or interrupted job is inspected on the surviving node. Drain contract

Operator recovery

Use this procedure for work left in the inbox, a deployment without recovery/2, or a delivery discarded by Lifeline.

  1. Read Durable.status(jobs, id). For :running, check the worker and the stored lease. The live owner can renew it. If it expires, the Job reports :recovery_required and can include continuation_lease_expired.
  2. Read Continuation.get(Durable.store(jobs), id). The Store decides expiry using its clock and the returned :lease_until in UTC milliseconds. Recover an expired claim with the returned :record_id and :revision, an operator identity, an authorizer and a stable operation ID. Reuse that operation ID with the same binding after an unconfirmed reply.
  3. If recovery returns :uncertain, find the provider or tool outcome using external evidence. Use Continuation.reconcile_model/5 or Continuation.reconcile/5 with the evidence. When a provider response is lost and the operator accepts possible duplicate spend, obtain a fresh :retryable_effects binding from Continuation.get/2. Agent jobs also support Continuation.retry_effect/4 with that binding, the trusted :agent and :continuation (including the leaf codec), and accept_duplicate_risk: true, a stable idempotency key and an authorized operation ID. If the captured request fails preflight, the Job still needs recovery and the original intent can be reconciled. A provider may charge both attempts, even when the new attempt carries the key.
  4. After confirming a ready record, call Durable.wake(jobs, id). Use the same ID even when Lifeline discarded the old delivery. For pending approval or input, wait for the authorized decision and use the usual wake path. Terminal jobs can be woken for any remaining notice.

If the job has a first-start reservation but C7 returns :not_found, stop the original worker and verify its external effects. Once the reservation expires, use Durable.retire_start/2 to close the admission. Investigate the outcome before creating fresh work. C7 recovery

Handle provider quota refusals

use ExAgent.Jobs.Durable supplies the Oban worker's perform/1. A first request refused by the local or shared limiter as {:rate_limited, key, wait} can release its C7 claim once the Store confirms the refusal. The claim must still own the initial frame with no effects. Jobs with dynamic instructions, capability instruction or request hooks, or a progress callback keep their claim for host recovery. Those callbacks can have effects before the quota gate. Once its lease expires, the held job reports :recovery_required. Job.diagnostic reports %{type: "rate_limited", wait_ms: wait}. Job.error provides display text for the same cause. An unknown provider-quota delay is :unknown in the diagnostic and keeps the claim for recovery. Inspect the journal and verify the preparation effects before acting. If it is safe to repeat preparation, use authorized Continuation.recover/3 with the expired claim's record ID and revision, then call Durable.wake/2 for the same ID once it is ready. If the preparation must not be repeated, authorize a cancellation instead. Use the current journal revision and reconcile any unconfirmed intents. C7 recovery

If the quota Repo is missing SQL 1, the claim stays held with %{type: "rate_limiter_migration_required", version: 1} in Job.diagnostic. The first request is refused before a model intent or dispatch. Held refusals have retry_at: nil and the delivery completes without snoozing. Apply the quota migration, recover the expired claim and wake the same ID. Quota migration

After release the job is :ready. The worker returns {:snooze, seconds} to Oban, which keeps the delivery scheduled without spending an attempt. Read Job.retry_at for its scheduled UTC DateTime. An integer wait in the diagnostic is in milliseconds. The worker bounds it by the earlier of the job's ID expiry and the stored C7 deadline. The wake time uses the Store clock and survives a worker restart or an early duplicate delivery. The worker rounds the delay up to whole seconds, at most one day per snooze. A full local queue (:queue_full) uses one second. A confirmed initial spend refusal ({:usage_limit_exceeded, :budget_cents, {:retry_after_ms, :unknown}}) with replay-safe preparation schedules another spend check after five seconds. Its diagnostic keeps :unknown, with the new time in Job.retry_at. Once the shared budget permits it, the same delivery can dispatch the first model request. An unschedulable wait (:infinity) waits for expiry. The wait also stops scheduling attempts if the C7 journal has only enough receipts left to close. A snooze preserves the job's request allowance and remaining active-time budget. An immediate local refusal with an unknown delay keeps the claim for host recovery and records the refusal with no quota retry time.

A certified :deadline_exceeded or exhaustion of the job's active-time budget closes the first attempt as :expired. If the job's wall deadline arrives while it waits, the next delivery records expiry and delivers any configured terminal notice. Read Job.error for display text, including "rate_limited (… ms)" while scheduled and "deadline_exceeded" on expiry. An expiry after a quota refusal also includes the refusal. An admitted model or tool intent requires the usual C7 recovery if its outcome is uncertain. Losing the quota backend's acknowledgement keeps the usual recovery path.

Queue-independent example

continuation_job.exs is a runnable, deterministic recipe using public continuation APIs. A queue attempt loads the record first. A pending approval waits. A ready or approved record resumes with the :continuation reference from Continuation.get/2. A terminal record returns data without starting another run. A live claim is busy. An expired claim or uncertain record returns :host_recovery_required. The demo uses ephemeral ETS and synthetic effects; PostgreSQL durability and an actual Oban worker require application configuration.

Run the example

From the root of your Mix application with ExAgent installed, run the packaged script.

EXAGENT_OFFLINE=1 MIX_ENV=test mix run deps/exagent/examples/continuation_job.exs

From an ExAgent source checkout, run the repository copy.

EXAGENT_OFFLINE=1 MIX_ENV=test mix run examples/continuation_job.exs

A passing run prints PASS continuation job: approval authority, cursor and duplicate dispatch. It checks that the run pauses before the effect, an authorized decision enables resumption, and redelivery keeps the effect count at one.

The trusted app supplies the template, scoped Store, stable run ID, versioned definition/policy/model references, codecs and credentials. Job arguments carry only the application's identifier. Tenant/actor authorization is resolved from authenticated app state; a prompt, job payload or notification cannot approve a tool. Pass the server-held request from ExAgent.Continuation.pending/2 to ExAgent.Continuation.decide/4 with an authenticated actor and authorizer. The request carries the exact record lifetime, approval ID and payload hash. If the reply has a continuation, enqueue a wake-up. See Queue delivery for the shared-Repo transaction and recovery with separate backends. A duplicate wake-up inspects the same record while it is retained. After Continuation.prune_page/4 deletes it, the recipe's :not_found branch starts a fresh run. Retain the record while the queue or an operator can redeliver the reference. To prune earlier, have job_target/1 reject the retired reference durably and wait for already admitted deliveries to finish.

For Oban, the app's perform/1 calls the recipe's dispatch/4. A terminal result or :await_approval completes that queue attempt. The app can schedule a later wake-up for :attempt_in_progress; :host_recovery_required enters its recovery flow. A checkpoint error retries only its captured data transition through Continuation.retry_checkpoint/2; its receipt cannot authorize another effect. After a RunError, inspect the stored outcomes. Recovering an expired claim can leave it ready to resume and make a new model request using the confirmed tool result. To end a claimed run with a confirmed failure, use an authorized Continuation.decide/4 with :cancel and the freshly read record revision. Do not convert every RunError into a fresh ExAgent.run/3. Oban uniqueness is useful queue admission and does not replace the continuation's CAS boundary.

The example leaves queue admission, authentication and the database lifecycle to the application. Replace the demo ETS store with the app-owned PostgreSQL Repo and durability: :durable after configuring and verifying durable storage. A changed template must change its version/reference, and resumes still validate current tool, authority, Model and output bindings. The recipe does not provide transactional external effects or exactly-once delivery.