ExAgent.Jobs (ExAgent v3.0.0)

View Source

Background jobs: tools and sub-agents that keep working while the agent goes on.

Stability — Stable.

A long tool call normally blocks the run until it returns, and is killed by the tool timeout. With ExAgent.Jobs, the tool returns a job ID as soon as the store acknowledges the start. The model can keep working, or talking to the user, and later read the result with job_status or wait_job. A finished job can submit a host ExAgent.Message.Part.JobNotice to start a new Server turn.

Supervise a distinct Jobs process for each application scope:

children = [{ExAgent.Jobs, name: MyApp.Jobs}]

Make any tool, or a whole agent, run in the background:

research = ExAgent.Jobs.agent_tool(
  jobs: MyApp.Jobs,
  name: "research",
  description: "Research a topic in depth. Takes minutes.",
  agent: research_agent,
  notify: fn job, ctx -> ExAgent.Jobs.notify_server(ctx.deps.server, job) end
)

crawl = ExAgent.Jobs.background(crawl_tool, jobs: MyApp.Jobs)

ExAgent.new(model: model, tools: [research, crawl | ExAgent.Jobs.tools(MyApp.Jobs)])

tools/2 binds job_status, wait_job and cancel_job to the supplied Jobs process. Use the notice's job ID to read the result or failure details from that process. Waiting reads the job without changing its configured delivery. Omit :notify or set it to nil for query-only delivery. Unexpected interruptions report the category and ask the reader to check for effects before repeating the work. A background agent's run failure contributes a diagnostic category and, for provider errors, its provider and HTTP status when available. Return {:tool_error, "message for the reader"} or {:error, "message for the reader"} to provide deliberate failure text. Other failure reasons are summarized: atoms, numbers and tuples of them are shown, while maps and lists inside a reason appear as :details_withheld. A job's function follows the tool result contract (ExAgent.Tool.result/0): any other shape, such as a returned %ExAgent.ModelRetry{}, fails the job as an unsupported result.

Boundaries

Jobs are volatile, like the Server's queue: they live in this process tree and are lost on restart; a lost job is reported as unknown, and the job tools report an unreachable store to the model instead of failing the run. Starting a job is the tool call's outcome, so permissions, approvals and persisted continuations see the start, not the job's later effects. A job runs outside the run that started it: run deadlines, usage limits and cancellation do not apply to it, and its token usage is not added to that run. The tool receives a copy of the run context; run-scoped handles in it (such as execution_scope for ExAgent.run_child/4) are closed once the starting run ends, so background tools must not depend on them.

Background submission tools return "running" on acknowledgement and "not_started" on a confirmed refusal or observed absence before sending. If the tool is still running when the store call times out (normally after five seconds) or exits after submission, it returns "unknown" with the job ID for use with job_status. A shorter agent :tool_timeout can end the tool before it returns the ID, even though the queued job may still start. Check the completion notification or the host's record for the business operation before resubmitting. A missing volatile record cannot establish whether work ran. Cross-node delivery and subsequent lookups can race. A store answers a request it does not know, such as one from another release, with {:error, :unsupported_request} instead of stopping its jobs; run the same release on a remote store and its clients.

Options for start_link/1:

  • :max_running — concurrent jobs (default 8). The same number limits notification slots separately. A job with :notify occupies a notification slot until its callback exits or Jobs finishes the job without invoking it.
  • :max_finished — finished jobs kept for status queries (default 256, oldest dropped first).
  • :max_result_bytes — result text kept per job (default 65_536, minimum 256); longer results keep their beginning and end, as ExAgent.Tool.OutputLimit does. Results are converted to text inside the job process. For structured results, Jobs checks the encoded JSON before shortening it. If the encoder raises, throws or exits, or the JSON is invalid or contains duplicate keys, Jobs keeps bounded Elixir inspect text. When the text is a slice of a larger binary, finished jobs retain only the slice. Failure messages, including tool retry messages, keep at most 2,048 bytes of UTF-8 text. Invalid byte sequences become ?.
  • :timeout — default job timeout in milliseconds (default 900_000). Store and per-job timeouts accept 1..4_294_967_295 milliseconds.

Telemetry: [:exagent, :job, :start] (%{system_time}) and [:exagent, :job, :stop] (%{duration}), with metadata %{job_id, name} and, on stop, status and qualified usage and cost metadata. The start timestamp is the VM's system time at admission. Duration is monotonic elapsed time in native units until the store processes completion, including task startup and synchronous start handlers.

Summary

Functions

A tool that runs agent in the background on the prompt the model gives it. The :name must be valid UTF-8 when building the tool.

Turn a tool into one that runs in the background.

Stop a running job. A finished job is returned unchanged.

Returns a specification to start this module under a supervisor.

Running and retained finished jobs, newest first, as {:ok, jobs}. Returns {:error, :unavailable} if the store does not reply within five seconds.

List running and retained finished jobs, newest by started_at first. Filter by one :status and use a non-negative :limit to cap the number of matching jobs. Both options are optional. Jobs with identical start times have no guaranteed relative order.

Format the host metadata of a finished volatile job for display, or a running snapshot as progress. notify_server/2 submits a typed ExAgent.Message.Part.JobNotice and the model uses the scope-bound job_status or wait_job tool to read any result or failure diagnostic.

The admission key for a finished volatile snapshot, or nil without a finish timestamp. Use ExAgent.Jobs.Durable.notification_key/2 for durable jobs.

Submit a finished volatile job as a new turn in a Server conversation. On admission, returns :ok. Subscribers can match the turn's request_id to job.id on the conversation topic. A supplied job with status :running returns {:error, :job_running} before contacting the Server. Use a fresh terminal snapshot from status/2, wait/3 or the completion callback. Its stable notification key expires one day after completion. Use notification_key/1 with ExAgent.Server.receipt/2 after a lost acknowledgement.

Run fun as a background job named name. Options: :timeout (ms) and :notify, a one-argument function called with the finished Job. Use notify: nil (the default) for query-only delivery. The store ignores the callback's return value and skips it after a successful cancellation. Returns {:error, :busy} when no job slot is free or when this job needs a notification slot and all of those slots are occupied.

Start a job store with the options listed in the module documentation. The optional :name registers the store. Unknown or duplicate keys raise ArgumentError before the store starts.

Current state of a job. Returns {:error, :unavailable} if the store does not reply within five seconds: a read has no effect to confirm.

Tools that let the model follow its jobs: job_status, wait_job and cancel_job. Option :max_wait_seconds caps one wait_job call, in seconds (default 60); that tool's timeout is set accordingly. wait_job observes the job with its configured completion delivery still in effect.

Wait for a job to finish and return its state. Supply a positive timeout in milliseconds. Use status/2 for a single read. For a local store, time spent waiting in its mailbox counts toward that timeout. The maximum is 4_294_962_295 ms, leaving five seconds for call overhead. Waiting on a finished job reads its retained result even if its notification has already been sent. Waiting never affects completion delivery. If the caller exits or its node disconnects, the store removes that wait when it observes the loss. The job continues running. Returns {:error, :unavailable} if the store does not reply within the wait and its call overhead.

Types

notify()

@type notify() :: (ExAgent.Jobs.Job.t() -> term()) | nil

server()

@type server() :: GenServer.server()

Functions

agent_tool(opts)

@spec agent_tool(keyword()) :: ExAgent.Tool.t()

A tool that runs agent in the background on the prompt the model gives it. The :name must be valid UTF-8 when building the tool.

Options: :jobs, :name, :description and :agent (required); :run_opts, a keyword list or fn ctx -> keyword end passed to ExAgent.run/3; :timeout; and :notify, as in background/2. The job result is the agent's output. If the agent pauses for approval, the job finishes with :failed. The host can review and resume the pending continuation using the store and ID in :run_opts. The sub-agent's usage is its own, not the parent run's. Static run options must be a keyword list with known, unique keys and valid message history. Invalid static options raise ArgumentError when building the tool. If the function returns invalid options, the tool reports "not_started" before submitting a job. The child checks its deadline and execution limits when it runs.

background(tool, opts)

@spec background(ExAgent.Tool.t(), keyword()) :: ExAgent.Tool.t()

Turn a tool into one that runs in the background.

The tool name must be valid UTF-8 when building the wrapper. Set takes_ctx on ExAgent.Tool.new/1. With true the callback takes context and arguments. With false it takes only the arguments. An invalid callback or flag raises ArgumentError. The returned tool keeps the name and argument schema; its description says that it returns a job id. Options: :jobs (required), :timeout (defaults to the tool's own timeout, then to the store's) and :notify, a fn job, ctx -> ... end called when the job finishes (or times out) with the run context of the call that started it, minus its message history. Use notify_server/2 there to continue a Server conversation, or leave :notify at nil for query-only delivery. Exclusive tools are rejected: jobs run concurrently, so their effects could not be serialized. Tools declared with requires_deferral: true are rejected too: a job runs outside any continuation, so it has no inbox to receive the deferred result.

The store receives a notification closure whose context already has an empty :messages field. A context-aware tool still receives its original context. A tool taking only arguments carries those arguments to the job. The job checks the original :result_schema before shortening its result for status queries. The submission tool returns the job receipt.

cancel(jobs, id, opts \\ [])

@spec cancel(server(), String.t(), keyword()) ::
  {:ok, ExAgent.Jobs.Job.t()}
  | {:error, :not_found | :unavailable | :result_unconfirmed}

Stop a running job. A finished job is returned unchanged.

The relative :timeout (5,000 ms by default) includes store lookup. Absence or expiry before dispatch returns {:error, :unavailable}. A dispatched request without its reply returns {:error, :result_unconfirmed}. Check status/2 with the same ID when the store is reachable.

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

list(jobs)

@spec list(server()) :: {:ok, [ExAgent.Jobs.Job.t()]} | {:error, :unavailable}

Running and retained finished jobs, newest first, as {:ok, jobs}. Returns {:error, :unavailable} if the store does not reply within five seconds.

list(jobs, opts)

@spec list(server(),
  status: ExAgent.Jobs.Job.volatile_status(),
  limit: non_neg_integer()
) ::
  {:ok, [ExAgent.Jobs.Job.t()]} | {:error, :unavailable}

List running and retained finished jobs, newest by started_at first. Filter by one :status and use a non-negative :limit to cap the number of matching jobs. Both options are optional. Jobs with identical start times have no guaranteed relative order.

The store filters before replying, locally and across nodes. The reply follows list/1.

notification(job)

@spec notification(ExAgent.Jobs.Job.t()) :: String.t()

Format the host metadata of a finished volatile job for display, or a running snapshot as progress. notify_server/2 submits a typed ExAgent.Message.Part.JobNotice and the model uses the scope-bound job_status or wait_job tool to read any result or failure diagnostic.

notification_key(job)

@spec notification_key(ExAgent.Jobs.Job.t()) :: ExAgent.Server.admission_key() | nil

The admission key for a finished volatile snapshot, or nil without a finish timestamp. Use ExAgent.Jobs.Durable.notification_key/2 for durable jobs.

notify_server(server, job)

@spec notify_server(GenServer.server(), ExAgent.Jobs.Job.t()) ::
  :ok | {:error, term()}

Submit a finished volatile job as a new turn in a Server conversation. On admission, returns :ok. Subscribers can match the turn's request_id to job.id on the conversation topic. A supplied job with status :running returns {:error, :job_running} before contacting the Server. Use a fresh terminal snapshot from status/2, wait/3 or the completion callback. Its stable notification key expires one day after completion. Use notification_key/1 with ExAgent.Server.receipt/2 after a lost acknowledgement.

Admission errors such as {:error, :queue_full} are returned directly, as are the replies of ExAgent.Server.send_message/3 without a confirmed receipt: {:error, :unavailable} when no Server process exists, and {:error, {:delivery_unconfirmed, job.id}} when admission cannot be confirmed. The Server may then still process the message. Check the receipt, conversation history or observed events before retrying. The finished job remains available under its retention policy.

A durable snapshot returns {:error, {:unsupported, :durable_notification}}. Use ExAgent.Jobs.Durable.wake/2 for delivery through the durable receipt.

start(jobs, name, fun, opts \\ [])

@spec start(server(), String.t(), (-> term()), keyword()) ::
  {:ok, ExAgent.Jobs.Job.t()}
  | {:error,
     :busy | :unavailable | :job_id_in_use | {:delivery_unconfirmed, String.t()}}

Run fun as a background job named name. Options: :timeout (ms) and :notify, a one-argument function called with the finished Job. Use notify: nil (the default) for query-only delivery. The store ignores the callback's return value and skips it after a successful cancellation. Returns {:error, :busy} when no job slot is free or when this job needs a notification slot and all of those slots are occupied.

A caller may supply an opaque :id of 1 to 128 visible ASCII bytes to correlate submission and execution. A retained ID returns {:error, :job_id_in_use} without starting work. An absent ID after eviction or restart is not evidence for resubmission.

The name must be valid UTF-8. An invalid byte sequence raises ArgumentError before submission. When the name is a slice of a larger binary, the admitted job retains only the bytes of its name. The job function can retain anything it captures.

Returns {:error, :unavailable} if the store is observed absent before sending, or {:error, {:delivery_unconfirmed, job_id}} if the submission exits without a reply. The job may still run. Use that ID with status/2 or wait/3 when the store is reachable before submitting the work again.

The timeout starts when the store reserves the slot and includes result encoding. The worker checks the deadline again after preparing its result and reports :timeout if the deadline has passed or been reached. A separate process can also stop the worker before it sends its result. A result sent on time is preserved even if the store is busy. The store publishes the terminal state and notification when it processes the result or exit. Effects already performed remain, and uninterruptible native code can delay task exit.

start_link(opts \\ [])

Start a job store with the options listed in the module documentation. The optional :name registers the store. Unknown or duplicate keys raise ArgumentError before the store starts.

status(jobs, id)

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

Current state of a job. Returns {:error, :unavailable} if the store does not reply within five seconds: a read has no effect to confirm.

tools(jobs, opts \\ [])

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

Tools that let the model follow its jobs: job_status, wait_job and cancel_job. Option :max_wait_seconds caps one wait_job call, in seconds (default 60); that tool's timeout is set accordingly. wait_job observes the job with its configured completion delivery still in effect.

Both backends project a confirmed query as a JSON object with "job_id", "name" and "status". It includes "result", "error" and "notification" when the snapshot has those fields. Without a confirmed snapshot the object has "job_id", "status": "unknown", a stable "code" (for example "not_found", "unavailable" or "timeout") and a bounded diagnostic "message".

wait(jobs, id, timeout)

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

Wait for a job to finish and return its state. Supply a positive timeout in milliseconds. Use status/2 for a single read. For a local store, time spent waiting in its mailbox counts toward that timeout. The maximum is 4_294_962_295 ms, leaving five seconds for call overhead. Waiting on a finished job reads its retained result even if its notification has already been sent. Waiting never affects completion delivery. If the caller exits or its node disconnects, the store removes that wait when it observes the loss. The job continues running. Returns {:error, :unavailable} if the store does not reply within the wait and its call overhead.