OpenProgram Docs

Background Job lifecycle

Every spawned sub-agent is a Job in openprogram/runtime/jobs/, with job_id equal to its execution_id. Control goes through the execution control plane; a Job adds admission, a worker pool and result delivery.

pending record saved queued waits for a worker running turn in progress completed cancelled errored pending and queued can also end cancelled or errored without running
  1. pendingrecord saved
  2. queuedwaits for a worker
  3. runningturn in progress
  4. completed · cancelled · erroredterminal; pending and queued can also end cancelled or errored

Terminal states absorb; illegal moves raise ValueError. Since canonical executions do not mirror their running transition, the projection may also go pending → running and queued → completed.

Entry points

agent(prompt, description, agent?, start_from="fresh", run_in_background=False, isolation?)Model tool. Foreground returns the result block; background returns the execution id. send_message delivers to an existing agent as a Job.
read_conversation(execution_id)Model tool. Returns the Job's status, and its reply once terminal, without waiting. job_output(job_id, block, timeout) stays registered for programs, hidden from the model.
list_agents()Model tool. Lists this session's running or queued Jobs, newest first, at most 20, beside its branches. list_jobs() is hidden from the model.
/task, /task --async, /spawnTyped in chat. Blocks, or writes a running placeholder and returns.
spawn_job, list_jobs, get_job (WS)Create and read. Replies: spawn_job_result, jobs_list, job. No session_id on list_jobs means all sessions.
execution.cancel (WS)Cancels; Job actions do not include a separate cancel

Clients follow the job_status broadcast. The branch view shows Job status; there is no separate Tasks panel.

Scenarios

CaseWhile runningResult reaches callerStop and failure
One foreground callCaller blocks; the attach card goes straight to its final stateReply as the tool resultStopping the session cancels the child and the parent turn; partial output returns
One background callCaller continues; a running card showsA notice turn in one result shape; read_conversation reads it earlierCancel from the UI or close_agent; a stop by the person is told to the caller
Several background callsPool runs up to its width; the rest stay queued, first in first outEach returns separately; finishing together during a turn produces one noticeEach has its own status and error; the parent decides on partial results
Long job, cancelledSlot held until the worker exitsPartial outputEscalates after 30 seconds

Worker pool

PoolThreadPoolExecutor, same thread model as a chat run. process_user_turn opens its own event loop, so there is no nested-loop conflict.
WidthOPENPROGRAM_JOB_WORKERS, default 8
AdmissionResource governance admits and limits a Job; see Resource allocation
Per-session limitNone

Persistence and recovery

StoreOne jobs.json document per session, {"jobs": {id: Job}, "version": 1}; each write is one line of the session log
LockingOne lock per session: read, mutate, write
Worker lostA non-terminal Job with no current attempt or accepted command becomes errored, worker died before completion. One with a canonical attempt follows restart recovery.
NoticesPending in <caller-session-dir>/notices.json, so a restart keeps them; a crash before queuing one is covered in Hand-offs across a crash

Hand-offs across a crash

A sub-agent request crosses three hand-offs between the parent and the run. Each writes what it is about to do before doing it, the step after it is idempotent, and the Worker's resource reconciliation (at start, on run-table changes and at least every 60 seconds) finishes whatever a dead process left half done. openprogram/runtime/jobs/handoff.py holds the shared pieces.

  1. AdmittedJob and its intent saved
  2. Handed overinbox entry or attach card, then published
  3. Rancanonical execution and its recovery
  4. Parent toldtool result or notice
WindowIntent written firstIdempotent stepNext Worker
send_message to a busy target: admitted, not yet queuedThe inbox entry rides on the Job as deferred_inbox, saved with admissioninbox.enqueue keeps one entry per job_idRecreates a missing entry; a surviving one stays as it is
Inbox drain: published, entry not yet removedThe admission row says the Job left the deferred stateDelivering an already published Job returns its idThe drain removes the leftover entry; the Job runs once
Spawn admitted held, attach card or publish not yet doneJob.submitter names the submitting process; attach_pointer_id names the cardThe card is written only when its node is missingOnce the submitter is gone, writes the card if missing and publishes the Job
Terminal written, notice not yet queuedThe terminal write sets notice_pending to the writing processnotices.queue keeps one entry per JobReplays a mark whose writer is gone, then clears it
Waited-on spawn whose waiter diedJob.submitter is the waiterAs aboveThe finished Job is told to the parent by notice, its reply inline, since its card stays out of context

The parent turn that was cut off in the middle of the agent call reads that call as interrupted with an unknown outcome (restart recovery); the attach card and the later notice tell it what became of the request. A held Job whose submitter still runs, in this process or another, is left to it.

Why this design

TopicWhy
Intent before actingExo's beginTurn durably accepts the input before the executor acts, and Maka commits the dispatch (T1) before a tool runs and the outcome (T2) before the result is published. Both make the record the authority and the action a consequence. Here the Job record is that record: whatever the next step needs travels on it, so recovery reads one row instead of guessing.
Idempotent by Job idMaka's graph claims preallocate the run identity and observe an existing run instead of starting it again; Codex publishes the spawn edge before the child exists. A replay keyed by the Job id can run at every reconciliation pass without a second inbox entry, card, run or notice, so recovery needs no extra state to know it already ran.
Liveness of the submitterThe held spawn and the waited result belong to whoever submitted them while that process lives; only its death hands them to recovery. Process identity is the pid plus its start token, as execution leases already record, so a reused pid is not mistaken for the old waiter.
A dead waiter's resultClaude Code and Codex lose a foreground sub-agent's result with the process; Maka re-delivers its supervisor wake until the root run completes. Telling the parent by the same notice a background agent uses costs nothing new and keeps the work from being lost or redone.
Run the request rather than cancel itThe request was admitted with its budget; dropping it would make the model guess, and its interrupted call already warns that the outcome is unknown. Running it once and reporting is the outcome the parent asked for.

Cancellation

  1. JobRunner.cancel_execution persists one execution.cancel command, and cascades to child Jobs.
  2. The owning worker consumes it and sets cancel_event, which process_user_turn bridges into the agent loop; the provider stream stops at its next chunk.
  3. Live subprocesses and exec runtimes are signalled by exact execution id. Agent methods check at their pre-invocation hook.
  4. After _CANCEL_ESCALATION_SECS (30 s) the owner's grace ends.

A tool's own atomic operation finishes first. A cancelled or errored Job cannot be resumed as the same work; retry is a new spawn.

Session and attach card

  • A Job runs in exactly one session, parent_session_id, and that never changes. A caller in another session is caller_session_id, with a linked mirror for visibility and ownership checks.
  • Output lands as a branch of that session, or a new root with context="clean".
  • An attach node (function="attach") is written after admission with status running and the job_id. The runner updates that same node at each terminal state. A cross-session card lives in the source session and names the target.
  • A synchronous caller settles the same card when its wait ends. Each writer merges only its own fields into the card as it stands inside the conversation's write lock (SessionStore.merge_node), never a copy read earlier.
  • That wait ends when this process's runner has finished the Job (status, card, notice), not when the status is first written, so the tool result and the card agree.
  • Context rendering skips a running card. A finished one becomes one sub-agent report with its task, final reply and transcript address.
Job fields
Identityid, parent_session_id, caller_session_id, parent_job_id, parent_msg_id, caller_msg_id, agent_id
Workprompt, subject, description, label, context_mode (inherit, clean), wait, source, model_override, tools_override, thinking_effort
Timingstatus, created_at, queued_at, started_at, completed_at, cancel_requested_at
Outcomehead_id, result_text, error, reason_code, attempt, attach_pointer_id, target_branch_head_id
Collaborationchain_messages, chain_generations, caller_chain_generations, archive_when_done, deferred_inbox, relation, worktree_id
Hand-offsubmitter, notice_pending
Authority and budgetspeaker_*, principal_id, authority_tier, admission_id, budget_scope_id, effective_limits, project_id

Runtime objects such as cancel events stay in the runner's maps, never on the record. JobRunner takes an injected governor and driver factory, so its state machine can run without a real model.

Invariants

  • Every Job ends in exactly one terminal state.
  • States only move forward.
  • The attach card changes with the record.
  • parent_session_id is immutable.
  • Runner maps are held under a lock.

Out of scope

AreaNot provided
SchedulingCross-process or multi-host workers; priorities and preemption; automatic retry (the agent decides)
Job relationsSeveral target sessions on one Job; Job dependency graphs; a parent agent subscribing to a child's output mid-flight

Implementation status

ImplementedRecord and state machine, persistent store, worker admission and execution, query and wait, cancellation at JobRunner, WS spawn, list, get and status, completion notices, hand-offs across a crash with a test that kills the process at each window
PartialAttach-card lifecycle across every recovery path; resource governance across token, cost, runtime and idle limits; the full spawn and concurrent-cancel test matrix
Not doneThe tool_call_id of a card that recovery writes is unknown, so that card is not paired with the interrupted tool call

Activity and control

Last updated · 2026-11-25