ExAgent.Jobs.Durable behaviour (ExAgent v3.0.0)

View Source

PostgreSQL-backed background agents delivered by a host Oban worker.

Stability — Stable.

For scheduled turns in an existing conversation, see ExAgent.Jobs.Durable.FollowUps.

Implement resolve/2, or use the :catalog option with a catalogue or a trusted catalogue builder for its namespace. The resolver returns the exact versioned agent, its C7 policy/model references and codec, and fresh run options. Each job owns its execution scope, expiry and active-time budget. Tools run through the agent's normal durable tool path. Delivery supports synchronous Frame3 execution. Queue arguments contain only a namespace and an opaque job ID.

Use a dedicated PostgreSQL Repo configuration shared by Oban and C7. Apply the unified ExAgent.Migration and the Oban migrations in the host. Jobs use exagent_snapshots for C7 records in the Repo's default schema. Set segments: true in use ExAgent.Jobs.Durable to write fragments. Submit or wake inside a host transaction and run the worker after commit. Delivery inside a transaction on the worker's Repo returns {:error, {:unsupported, :transactional_delivery}} before effects. Enable Oban Lifeline and implement the optional recovery/2 callback for automatic continuation recovery after a lost delivery. See the continuation jobs guide for deployment and the operator inbox.

Summary

Callbacks

Return the trusted catalogue for this namespace, optionally with fresh run options.

Choose a configured Oban queue for a saved definition reference.

Opt a trusted namespace and versioned definition into automatic recovery. The default is manual recovery. Return :manual or options with a required :actor and the regular arity-three continuation :authorize callback. :model is :cancel by default, :leave, or :retry to accept possible duplicate provider spend for one linked attempt.

Look up a stable Server address without activating an owner. Return nil to disable notification. If the owner is absent, keep returning its address and let the host restore it before waking the same job.

Functions

Define the host Oban worker. Set catalog: &catalog/1 for a namespace-specific catalogue, or pass a catalogue expression directly. The worker evaluates it at delivery. Options besides :catalog and :segments are passed to Oban.

Check the Jobs admission table on the fixed Repo's search path without reading job rows. Use ExAgent.Migration to install the table and its current export marker, delivery diagnostic and index. An incomplete or incompatible shape returns {:error, :jobs_migration_required}.

migration_sql() deprecated

Idempotent SQL for the standalone Jobs schema. Unified migration 1 installs the same schema. The SQL installs the export marker, the durable delivery diagnostic and the index used to find reservations by evaluation identity.

Bind a worker and an authenticated namespace to a running Oban instance.

Mint a job/continuation ID before submitting. Retain this ID across retries.

Return the scoped Server admission key for checking a durable job notification.

Erase one expired admission after the execution has settled. The compact tombstone protects against clock rollback and stale submissions. The installed PostgreSQL maintenance can fold tombstones of ordinary IDs into a durable expiry watermark. C7 history follows its own pruning policy. An outstanding notice or uncertain effect preserves the receipt.

Record the host's verified notice outcome after the old sender has stopped. :admitted records receipt. :abandon retires the notice without sending. Authorize the operator and verify Server history first.

Retire a lost initial admission with no C7 record after its lease. Authorize the operator, stop the original worker and verify external effects first. The original job can never start again. Wake it to deliver its terminal notice.

Commit admission and its first wake-up in one transaction. The ID embeds its immutable expiry. Repeating identical input returns the same ID. A changed definition, prompt or budget returns {:error, :conflict}. Options are :request_limit (default 50), :active_time_limit_ms (default nil) and :lease_ms (default 60000). The live worker renews its execution claim until completion, approval or the job's deadline or expiry. The job can only tighten the agent's limits. A committed receipt remains readable during an Oban restart. A new delivery requires the handle's configured Repo and prefix or returns {:error, :unavailable}. A missing Jobs table returns {:error, :missing_exagent_jobs_table}. An incompatible Jobs schema returns {:error, :jobs_migration_required} using the same check as check_schema/1. Apply the unified ExAgent migration on the configured Repo.

Read one Jobs.Job snapshot with the confirmed state, bounded result text and persisted Server notice receipt in :notification. A confirmed refusal or delivery diagnostic is reported in :diagnostic and :error. A ready job with a certified quota wait or a pending job with a timer also reports :retry_at as a UTC DateTime. Terminal jobs expose qualified usage and the available estimated cost from their committed checkpoint. Returns {:error, :unavailable} if the Repo could not serve the query. Returns {:error, :missing_exagent_snapshots_table} when the configured Repo cannot find the C7 table. Apply the unified ExAgent migration on that Repo. Both worker configurations read supported inline and fragmented formats.

Scoped C7 Store on exagent_snapshots for authorized decisions and reconciliation.

Resolve a standalone function tool as a Frame3 agent. The job input is a JSON object encoded as text. Two local model steps dispatch once and report the confirmed tool status and content as JSON. Permissions, schemas, approvals and uncertain effects use the normal durable tool path. Pass trusted run options (e.g. :permissions) as the last argument.

Build tenant-scoped job_status and wait_job tools. :max_wait_seconds caps one model wait (default 60). Both tools observe the committed state. They use the JSON projection of ExAgent.Jobs.tools/2.

Poll committed state until completion, an operator boundary or the wait deadline in milliseconds. Returns the same job snapshot as status/2. Waiting never affects notice delivery. The budget covers the connection pool, receipt and continuation reads. At the deadline, return the last confirmed state, or {:error, :timeout} if no read completed in time. Supply a positive budget in 1..4_294_962_295 milliseconds. Use status/2 to perform one read.

Enqueue a fresh read of an admitted job, e.g. after approval or recovery.

Types

definition_ref()

@type definition_ref() :: %{required(String.t()) => String.t()}

t()

@type t() :: %ExAgent.Jobs.Durable{
  namespace: term(),
  oban: term(),
  prefix: term(),
  repo: term(),
  scope: term(),
  segments: term(),
  worker: term()
}

Callbacks

definition(t)

(candidate API) (optional)
@callback definition(String.t()) :: ExAgent.Catalog.t() | {ExAgent.Catalog.t(), keyword()}

Return the trusted catalogue for this namespace, optionally with fresh run options.

delivery_queue(t, definition_ref)

(candidate API) (optional)
@callback delivery_queue(String.t(), definition_ref()) :: atom() | String.t()

Choose a configured Oban queue for a saved definition reference.

recovery(t, definition_ref)

(optional)
@callback recovery(String.t(), definition_ref()) ::
  :manual
  | [
      actor: term(),
      authorize: (term(), atom(), map() -> term()),
      model: :cancel | :leave | :retry
    ]

Opt a trusted namespace and versioned definition into automatic recovery. The default is manual recovery. Return :manual or options with a required :actor and the regular arity-three continuation :authorize callback. :model is :cancel by default, :leave, or :retry to accept possible duplicate provider spend for one linked attempt.

A delivery consults this side-effect-free callback when a C7 claim has expired or its outcome is uncertain. The built-in policy uses the matched agent for its declared tool lookup and model preflight. Automatic recovery applies to a static Frame3 definition with the original references. It allows side-effect-free guardrails and pure output validators. Jobs with custom capability hooks, dynamic instructions, a progress or approval callback, cost estimator, handoffs, delegation, or rehydrated tools use operator recovery.

resolve(t, definition_ref)

(optional)
@callback resolve(String.t(), definition_ref()) ::
  {:ok, ExAgent.t(), map(), keyword()} | {:error, term()}

server(t, t)

(optional)
@callback server(String.t(), String.t()) :: GenServer.server() | nil

Look up a stable Server address without activating an owner. Return nil to disable notification. If the owner is absent, keep returning its address and let the host restore it before waking the same job.

Functions

__using__(opts)

(macro)

Define the host Oban worker. Set catalog: &catalog/1 for a namespace-specific catalogue, or pass a catalogue expression directly. The worker evaluates it at delivery. Options besides :catalog and :segments are passed to Oban.

check_schema(repo)

@spec check_schema(module()) ::
  :ok
  | {:error,
     :missing_exagent_jobs_table | :jobs_migration_required | :unavailable}

Check the Jobs admission table on the fixed Repo's search path without reading job rows. Use ExAgent.Migration to install the table and its current export marker, delivery diagnostic and index. An incomplete or incompatible shape returns {:error, :jobs_migration_required}.

migration_sql()

This function is deprecated. Use ExAgent.Migration for new migrations. Removal in 4.0..
@spec migration_sql() :: String.t()

Idempotent SQL for the standalone Jobs schema. Unified migration 1 installs the same schema. The SQL installs the export marker, the durable delivery diagnostic and the index used to find reservations by evaluation identity.

new(worker, namespace, opts \\ [])

@spec new(module(), String.t(), keyword()) :: t()

Bind a worker and an authenticated namespace to a running Oban instance.

new_id(ttl_ms \\ 86_400_000)

@spec new_id(pos_integer()) :: String.t()

Mint a job/continuation ID before submitting. Retain this ID across retries.

notification_key(h, id)

@spec notification_key(t(), String.t()) ::
  {:ok, ExAgent.Server.admission_key()} | {:error, term()}

Return the scoped Server admission key for checking a durable job notification.

prune(h, id)

@spec prune(t(), String.t()) :: {:ok, non_neg_integer()} | {:error, term()}

Erase one expired admission after the execution has settled. The compact tombstone protects against clock rollback and stale submissions. The installed PostgreSQL maintenance can fold tombstones of ordinary IDs into a durable expiry watermark. C7 history follows its own pruning policy. An outstanding notice or uncertain effect preserves the receipt.

reconcile_notice(h, id, outcome)

@spec reconcile_notice(t(), String.t(), :admitted | :abandon) ::
  :ok | {:error, term()}

Record the host's verified notice outcome after the old sender has stopped. :admitted records receipt. :abandon retires the notice without sending. Authorize the operator and verify Server history first.

retire_start(h, id)

@spec retire_start(t(), String.t()) :: :ok | {:error, term()}

Retire a lost initial admission with no C7 record after its lease. Authorize the operator, stop the original worker and verify external effects first. The original job can never start again. Wake it to deliver its terminal notice.

start(h, id, ref, prompt, opts \\ [])

@spec start(t(), String.t(), definition_ref(), String.t(), keyword()) ::
  {:ok, String.t()} | {:error, term()}

Commit admission and its first wake-up in one transaction. The ID embeds its immutable expiry. Repeating identical input returns the same ID. A changed definition, prompt or budget returns {:error, :conflict}. Options are :request_limit (default 50), :active_time_limit_ms (default nil) and :lease_ms (default 60000). The live worker renews its execution claim until completion, approval or the job's deadline or expiry. The job can only tighten the agent's limits. A committed receipt remains readable during an Oban restart. A new delivery requires the handle's configured Repo and prefix or returns {:error, :unavailable}. A missing Jobs table returns {:error, :missing_exagent_jobs_table}. An incompatible Jobs schema returns {:error, :jobs_migration_required} using the same check as check_schema/1. Apply the unified ExAgent migration on the configured Repo.

status(h, id)

@spec status(t(), String.t()) :: {:ok, ExAgent.Jobs.Job.t()} | {:error, term()}

Read one Jobs.Job snapshot with the confirmed state, bounded result text and persisted Server notice receipt in :notification. A confirmed refusal or delivery diagnostic is reported in :diagnostic and :error. A ready job with a certified quota wait or a pending job with a timer also reports :retry_at as a UTC DateTime. Terminal jobs expose qualified usage and the available estimated cost from their committed checkpoint. Returns {:error, :unavailable} if the Repo could not serve the query. Returns {:error, :missing_exagent_snapshots_table} when the configured Repo cannot find the C7 table. Apply the unified ExAgent migration on that Repo. Both worker configurations read supported inline and fragmented formats.

store(h)

@spec store(t()) :: ExAgent.Store.scoped()

Scoped C7 Store on exagent_snapshots for authorized decisions and reconciliation.

tool(ref, tool, policy, opts \\ [])

@spec tool(definition_ref(), ExAgent.Tool.t(), definition_ref(), keyword()) ::
  {:ok, ExAgent.t(), map(), keyword()}

Resolve a standalone function tool as a Frame3 agent. The job input is a JSON object encoded as text. Two local model steps dispatch once and report the confirmed tool status and content as JSON. Permissions, schemas, approvals and uncertain effects use the normal durable tool path. Pass trusted run options (e.g. :permissions) as the last argument.

tools(h, opts \\ [])

@spec tools(t(), keyword()) :: [ExAgent.Tool.t()]

Build tenant-scoped job_status and wait_job tools. :max_wait_seconds caps one model wait (default 60). Both tools observe the committed state. They use the JSON projection of ExAgent.Jobs.tools/2.

wait(h, id, ms)

@spec wait(t(), String.t(), pos_integer()) ::
  {:ok, ExAgent.Jobs.Job.t()} | {:error, term()}

Poll committed state until completion, an operator boundary or the wait deadline in milliseconds. Returns the same job snapshot as status/2. Waiting never affects notice delivery. The budget covers the connection pool, receipt and continuation reads. At the deadline, return the last confirmed state, or {:error, :timeout} if no read completed in time. Supply a positive budget in 1..4_294_962_295 milliseconds. Use status/2 to perform one read.

wake(h, id)

@spec wake(t(), String.t()) :: {:ok, String.t()} | {:error, term()}

Enqueue a fresh read of an admitted job, e.g. after approval or recovery.