OpenProgram Docs

Agent resource governance

Who may create a Job, how many run, what they may spend, and how capacity comes back. Single user, local machine, one persistent worker.

preparing queue slot Job saved queued queue slot atomic claim live live slot cancel, budget stopping live slot exit confirmed released nothing Fails, or no Job after a restart: removed, not counted
  1. preparingqueue slot

    Fails, or no Job after a restart: removed, not counted

  2. Job saved
  3. queuedqueue slot
  4. atomic claim
  5. livelive slot
  6. cancel, budget
  7. stoppinglive slot
  8. exit confirmed
  9. releasednothing

Resource state is separate from Job status (pending, queued, running, completed, cancelled, errored). A Job can show cancelled while its slot is still stopping, so a 30-second escalation that only changes status cannot overallocate.

Out of scope: background-session UI, MCP server, purchases or top-ups, organization billing, multi-machine scheduling. These may later reuse the DTO, reason codes, budget scopes and reservation protocol.

Why these limits exist
LimitExistsReason
max_live_globalNoOPENPROGRAM_JOB_WORKERS (default 8) already sets the process-wide ThreadPoolExecutor. A second setting could conflict. The UI shows it read-only.
max_live_per_sessionYesOne session cannot take every worker. Counts only work running or not yet confirmed stopped.
max_queued_per_sessionYesBounds the persistent queue.
max_jobs_per_sessionYesBounds successful admissions over the session's life.
token, cost, runtime, idleYesEnforceable under different conditions, see Budgets.
Actual usageReusedusage_events is the only record. Admissions and open reservations are execution state, not a second ledger.

Limits

LimitCountsAt the limit
agent.max_spawn_depthGenerations in the execution context, default 1. Only agent(...) creating a branch adds one.Refuses the new branch (quota.spawn_depth). Existing branches still take work.
agent.max_messagesPer path: spawn and send_message set the target to sender plus one. Automatic follow-up reuses the completed Job's count. Parallel calls in one turn share no counter.Refuses new deliveries and hides agent. Cancels nothing.
agent.max_spawn_fanoutNew branches (creates_agent=true) per caller (session_id, turn_id).Refuses more branches this turn (quota.spawn_fanout). Child completion returns nothing.
max_jobs_per_sessionSuccessful admissions for the target session (parent_session_id), on new or existing branches. Caller provenance is recorded separately.quota.jobs_exhausted, not retryable.
max_queued_per_sessionTarget-session admissions in preparing or queued.quota.queue_full, retryable. No Job is created.
max_live_per_session, scheduler_capacitySession and global claims in live or stopping.Job stays queued. Waiting is not failure.
ValueMeaning
Collaboration limit 0Check off. Counts still propagate.
Resource limit nullUnset, inherit. Disabled if still unset after inheritance, except live, which defaults to scheduler_capacity.
Resource limit 0Invalid. Non-null values must be positive.
  • A Job's id is its canonical execution_id; read_conversation(execution_id) and close_agent take that identity.
  • send_message creates no branch but a new execution: message and hop limits plus target-session admission.
  • send_message to an idle target creates a creates_agent=false Job through run_agent_turn_async and consumes target-session admission.
  • The message limit binds new deliveries only. read_conversation, list_agents and close_agent on owned executions stay available.
  • The model sees agent, send_message, list_agents, read_conversation and close_agent; list_jobs and job_output stay registered for programs but hidden. close_agent cancels through JobRunner._cancel_cascade; the UI and API go through execution control.

Operation and message counts: Agent collaboration design §5.

Configuration

agent.resource_limits:
  max_live_per_session: integer | null
  max_queued_per_session: integer | null
  max_jobs_per_session: integer | null
  max_total_tokens: integer | null
  max_cost_usd: decimal-string | null
  max_runtime_seconds: integer | null
  idle_timeout_seconds: integer | null
AspectRule
OrderGlobal, session metadata, parent, Job. Each level can only tighten; a looser value is quota.invalid_limits.
Who setsOnly the owner sets global defaults and session overrides. A Job request may add stricter token, cost, runtime and idle budgets only.
ReportedEach field's configured, effective and source. Extends config get/set and session metadata; no second quota service.
LiveEffective value is the lesser of configuration and scheduler_capacity.
Token, cost scopeGoverned invocations carrying a job_id in the session. Ordinary foreground conversation is excluded.
Runtime, idle scopeEach Job and its ancestor scopes.
Changing a valueLive, queued, cumulative: existing work continues; next admission or claim uses it. Token, cost: next reservation. Runtime, idle: Jobs admitted later only, so deadlines are never retroactive.
Lowering below useDeletes nothing; later admissions are refused.

Admission

Every Job creation calls ResourceGovernor.admit_job: synchronous and asynchronous agent(), send_message busy-target precreation, run_agent_turn_async, WebSocket and API spawn, model tools, and any direct JobRunner.spawn_job. The model tool also keeps a process-local fan-out precheck.

  1. Create job_id, admission_id and request fingerprint. Validate arguments, target and permissions without changes.
  2. In a run-table transaction, check depth, fan-out, queue and cumulative count, then write the budget scope and a preparing admission. Every concurrent check sees it.
  3. Persist the canonical execution, then the Job in the session's jobs.json under the session lock and openprogram.host._platform.locking.flock. No broadcast yet.
  4. In a second transaction, move to queued. Only now create the branch and Job-bound inbox entry and broadcast acceptance.
  5. On failure, delete the preparing row and its scope and close the canonical row. No transaction spans Job-store I/O.
  • A refusal returns {accepted:false, job_id:null, reason_code, retryable, effective_limits, usage, capacity} and creates no Job, branch, Job-bound inbox entry or acceptance broadcast.
  • A retry with the same job_id and fingerprint is an idempotent read and adds no count. Different content is quota.admission_conflict.
  • Exhausted cumulative or parent budgets are not retryable until the owner raises limits or a new session starts.

An ordinary send_message to a busy target may persist a receipt first, under message authorization and inbox limits (50 pending). It is not a Job and claims no admission. If admission later fails, the receipt is marked failed and the sender gets the reason. It links to the admitted Job at delivery.

Queue and live capacity

  • The dispatcher picks the lowest admitted_seq whose session has live capacity. An ineligible session is skipped, so its head cannot block others.
  • queued to live releases the queue slot and takes the live slot in one transaction.
  • Only the process holding the worker lock may claim. Run tables live in that process, and function subprocesses and scheduled runs forward JobRunner calls to it. Several execution workers would need a separate scheduling design.

Parent and child budgets

  • A Job request may carry one limits object with token, cost, runtime and idle only. It cannot exceed session limits, parent limits or the parent scope's current remainder (quota.parent_budget_exhausted).
  • Without explicit limits, children join the shared parent scope. The budget is not divided up front and fan-out does not predict work.
  • Each reservation checks the Job's ceiling, every ancestor scope and the session scope; the first durable reservation gets the capacity.
  • Explicit child budgets are stricter local ceilings and deduct nothing up front. Actual reservations consume the parent.
  • The UI labels shared_remaining as a shared live balance, never an allotment.

Budgets

BudgetMeasured asBefore the callDuring and afterCannot enforce
TokenProvider input plus output. Cache reads and writes are separate diagnostics.Reserve input upper bound plus max_output_tokens; clamp the output cap to the remainder.Final usage settles and returns the difference. Open reservations count.No tokenizer or safe bound: quota.accounting_unavailable.
CostKnown provider, model, rate and actual tokens; keeps cost_source.Reserve a micro-USD bound only when all prices are known.Settles on actual tokens and rates; aggregates return cost_known and unknown_cost_events.With a budget, unknown price now or in the scope: quota.cost_unavailable. Without one, runs and shows unknown, never $0. Later catalog prices do not rewrite history.
RuntimeMonotonic time since live. Queue wait excluded.Operation timeout is the lesser of its limit and the time left.Expiry sets cancellation, cascading to children.error.nonpreemptible_operation.
IdleMonotonic time since meaningful activity.Records the call start; links child activity while waiting.Provider data, tool progress and child events count. Transport keepalives do not.A tool with no progress or bounded timeout is non-preemptible.
  • Governed provider calls reserve through BudgetedRequest before credentials or network access. Production uses reserve_provider_request, not the standalone reserve_tokens or reserve_cost.
  • Exhaustion is enforced at request and tool boundaries; while a Job runs, a budget loop sleeps until the earliest runtime or idle deadline and triggers cancellation then; a recorded stop or a helper usage write wakes it sooner; with none running it sleeps. An executing operation is not described as instantly ended.
  • The longest non-preemptible interval is the least of declared timeout, remaining runtime and cancel grace. In-process synchronous work that cannot meet that moves to a terminable subprocess or is refused under strict budgets. asyncio.wait_for returning does not mean the executor thread ended.
Accounting delay and crashes
  • Reservations go reserved, started, settled, or reserved, released before provider I/O.
  • Credential, configuration or generator-creation failure before start releases. After a successful start, cancellation, transport errors or missing usage keep conservative exposure for late settlement of the same reservation. No first stream event does not prove the provider never got the request.
  • Actual tokens and cost are never invented.
  • Budgeted Jobs fail closed if accounting is inaccessible before a call. A failed settlement errors the Job, stops further calls and keeps the reservation for reconciliation.
  • Non-budgeted legacy paths may keep best-effort recording.

What each outcome returns

EventQueue slotLive slotCumulativeJob
Admission refusedNot takenNot takenNo incrementNone created
preparing rolled backReleasedNot takenNo incrementNone, or restored consistency
Cancelled while queuedReleased at onceNot takenKeptcancelled
Cancelled or budget out while runningAlready releasedstopping, released on confirmed exitKeptcancelled
Error or completionAlready releasedReleased when the worker confirmsKepterrored, completed
Retry of the same job_idNo duplicateNo duplicateNo duplicateOriginal Job or conflict reason

Cumulative counts last the session's life. Archiving returns nothing and nothing resets them; start a new session or have the owner raise the override.

Restart and recovery

FoundAction
preparing, matching JobBecomes queued.
preparing, no JobRow and scope removed.
queuedBack to the dispatcher, no live capacity used. Job missing or already terminal: released.
live, stopping, owner aliveLeft alone.
live, stopping, owner goneFenced by raising lease_generation, Job marked errored under the orphan policy with error.worker_lost, then released. The diagnosis stays in Job output.
Pending job_finalizationsTerminal fields written and compared; a mismatch is a conflict, not a release.
  • A claim needs owner_instance_id and the worker lock, checked by probing the real advisory lock. Writes are fenced by lease_generation. The reconcile loop runs after another thread commits to the run tables and at durable-wait deadlines, passes at least 5 seconds apart, with a 60-second resync.
  • A lease proves worker ownership, not rollback of external side effects.
  • Run tables are in-memory tables in the process that owns the profile. Each transaction appends one line to the session's log, and tables are rebuilt from it. budget_scopes use one global log. Unique keys make admission and reservation idempotent.
  • jobs.json is one document per session, in its log, written under a per-session lock and flock.
  • No cluster consensus or remote scheduler. Multiple workers would need leader election, clock assumptions and external-runtime fencing.

What users see

Web, TUI, CLI and model tools read the same JobResourceView. Wording may differ; fields and reason codes do not.

SurfaceShowsInteractionCompatibility
WebJob and resource state, queue position, session live, queued and cumulative, four remaining budgets, known or unknown cost, reason.Existing Job cards and cancel. No background-session UI or standalone Tasks panel.job_status gains optional resource fields.
TUICompact session capacity, selected Job's remaining budgets, stop reason.Existing list, details, stop.Missing fields render as legacy, not zero.
CLITables and stable JSON: effective limits, usage, reservations, reason, retryable.Existing query and cancel commands.New fields are additive; the status enum is unchanged.
Model toolsread_conversation, close_agent and execution control return the same reason and simplified budgets.A refusal is a structured tool result, with no invented Job record.Text results stay; machine-readable fields are added.

Reason codes

CodeMeaning
quota.queue_fullSession queue full; retry when capacity returns.
quota.jobs_exhaustedCumulative count reached.
quota.spawn_depth, quota.spawn_fanoutDepth or per-turn fan-out reached.
quota.parent_budget_exhaustedParent remainder cannot take the child limit.
quota.parent_claim_unavailableParent's live claim to borrow is gone; retryable.
quota.token_exhausted, quota.cost_exhaustedNot enough capacity to reserve.
quota.cost_unavailableCost budget set, price unknown.
quota.invalid_limitsInvalid value, or looser than parent or session.
quota.accounting_unavailableAccounting unsafe.
quota.admission_conflictSame identity, different request.
cancel.user, cancel.parent, cancel.sessionExplicit cancellation source.
budget.token_exhausted, budget.cost_exhausted, budget.runtime_exhausted, budget.idle_exhaustedRunning Job hit a budget. Job becomes cancelled; cascades to descendants.
error.worker_lost, error.accounting_unavailable, error.nonpreemptible_operationA safeguard failed. Job becomes errored.
completedNormal completion.

Other cancel.* and error.* codes in openprogram/runtime describe execution-control and recovery paths.

Schema and JobResourceView
job_admissions(
  admission_id PRIMARY KEY, job_id UNIQUE, session_id,
  parent_job_id, caller_session_id, caller_turn_id,
  creates_agent, request_fingerprint, budget_scope_id,
  dispatch_ready, terminal_blocked, terminal_block_*,
  borrowed_parent_job_id, resume_parent_msg_id,
  state: preparing | queued | live | stopping | released,
  queue_state, resume_command_id, admitted_seq,
  owner_instance_id, lease_generation,
  created_at, started_at, last_activity_at, released_at,
  reason_code
)

budget_scopes(
  budget_scope_id PRIMARY KEY,
  scope_kind: session | job,
  session_id, job_id UNIQUE, parent_scope_id,
  max_total_tokens, max_cost_microusd,
  max_runtime_seconds, idle_timeout_seconds, created_at
)

usage_reservations(
  reservation_id PRIMARY KEY, job_id, session_id, budget_scope_id,
  kind: token | cost,
  state: reserved | started | settled | released,
  reserved_tokens, reserved_cost_microusd,
  request_started_at, settled_event_id, expires_at
)

job_finalizations(
  job_id PRIMARY KEY, session_id, owner_instance_id,
  lease_generation, fields_json, state, created_at, completed_at
)

usage_events, added columns: job_id, budget_scope_id, reservation_id
Job JSON, added fields: admission_id, budget_scope_id, effective_limits, reason_code
  • These tables hold occupied resources and unsettled exposure, never invented usage.
  • effective_limits is an audit snapshot at Job start. Job JSON does not copy cumulative usage.
  • Availability is computed live from the ledger and open reservations.
  • Money is configured as decimal strings and compared as integer micro-USD.
{
  "job_id": "...", "status": "running", "resource_state": "live",
  "reason_code": null, "reason_key": null, "retryable": false,
  "limits": {"scheduler_capacity": 4, "limits": {}},
  "capacity": {
    "scheduler_capacity": 4,
    "session_live": {"used": 2, "limit": 3},
    "session_queued": {"used": 1, "limit": 8},
    "session_jobs": {"used": 17, "limit": 100},
    "queue_position": null
  },
  "budget": {
    "scope": "job_with_shared_ancestors",
    "tokens": {"actual": 12000, "reserved": 4000, "limit": 50000},
    "cost_usd": {"actual": "0.38", "reserved": "0.12", "limit": "2.00",
                 "known": true, "unknown_events": 0},
    "runtime_seconds": {"used": 91, "limit": 600},
    "idle_seconds": {"used": 4, "limit": 120},
    "shared_remaining": {"tokens": 34000, "cost_usd": "1.50",
                         "cost_unknown_events": 0}
  }
}

Also carries execution_id, capabilities, checkpoint_head_id, event_cursor and a nested resource object.

Compatibility
  • Old Jobs without the new fields are legacy/unmetered. Missing is not zero, and history is not rewritten.
  • Status enum, Job ids, broadcasts and cascading cancel stay compatible. Resource state and reason are optional additions.
  • Depth, message and fan-out semantics are unchanged; they guard topology and cycles.
  • Admission rows in an older usage file move to the run tables once, keeping limits set and unfinished work; those tables are then removed.
  • Usage-event migration adds nullable columns only. Usage events stay append-only.
Other projects

Their values explain counting units; they set no defaults here. Evidence: Agent collaboration comparison, Agent collaboration design, Async Job lifecycle.

ProjectLimits, and where appliedIdentity and cancellationVisibility
Claude CodePublic documentation: depth 3 and concurrency 20 by default, no total spawn cap, 50 queued cross-session messages. At the depth limit a fork keeps the tool and gets an error at call.agentId; cascading cancel undocumented.ListAgents, /tasks, TaskStop
Codex CLIGlobal 6; V2 per session 4; V1 depth 1; V2 computes depth without enforcing. Checked by the execution controller before start.ThreadId; list, wait, interrupt. Full V2 cascade unconfirmed.Model can query and interrupt
OpenClawDepth 1, 5 live children per parent, pools 8 and 4, message-cycle limits. Spawn rechecks all.runId, session key; host-kept run; child cascade confirmed.list, host state
OpenCodePermissions imply depth 1; no numeric concurrency limit confirmed. Applied at child-session creation.Child session id, background metadata, host cascade.Background state visible; limited model queries
HermesDepth 1 (up to 3), child concurrency 3, 50 iterations per child, caller timeout 600 s, heartbeat. Applied at pool submission and caller wait.Synchronous wait, no stable model-facing id, host cascade.Dashboard, host; limited model control
CodeBuddyOfficial package docs: 16 concurrent workflow Agents, 1000 per run. Enforced by the orchestrator.Resumable in the session; teams are not restored by /resume.Workflow UI: phase counts, tokens, elapsed, abort
pi-monoExample extension: batch 8, concurrency 4, 50 KB per task, before spawning.No durable id or query; one-level cancel may leave descendants.Call results
Taken
Separate global and per-session live limits (Codex). Live, queued and cumulative counted apart. Recheck at submission and cascade (OpenClaw). Stable ids and queryable state. Tokens, elapsed and reason shown together (CodeBuddy). Runtime and idle signals (Hermes).
Not taken
Competitor values. Depth, fan-out or tool permissions as resource admission (OpenCode). Overlapping children and global settings (OpenClaw). Process-local semaphores alone (pi-mono). Caller timeout or a terminal marker as proof of termination (Hermes). Extending resume claims to teams (CodeBuddy).
Test matrix
AreaMinimum casesFailure means
ConfigurationGlobal defaults, session overrides, tightening only; null, positive integer, decimal validation; read-only worker display.Unpredictable effective values or overlapping global limits
Collaboration and resourcesDepth out still permits existing-target dispatch; messages out denies delivery but keeps observe and cancel; send_message Jobs count in target admission; topology 0 and resource null stay distinct.Limits bypassed, or existing work cannot be observed or stopped
Creation entriesSync and async Agents, target inbox, Web and API, runner internals; refusal leaves no Job, branch or Job-bound inbox entry; earlier receipt fails and notifies.Quota bypass
Atomic admission20+ concurrent callers; unique ids; limit boundaries; faults before and after preparing.Overallocation, double counts or leaks
Queue and liveQueue uses no live slot; atomic exchange; oldest eligible across sessions; full queue; stopping keeps live.Starvation, early release or unbounded executor queue
CumulativeNo return on any terminal state; rollback not counted; retries not duplicated; lowering limits.Terminal-dependent counts or retry bypass
Parent and childRefuse limits above the remainder; shared scope; concurrent siblings; multi-level ancestors.Children expand budgets or overspend
Token and costSafe bounds, output cap, no double cache tokens; known and unknown prices; late or missing usage; settlement failure.Budgets only observable afterwards, or unknown becomes zero
Runtime and idleQueue wait excluded; data, progress and child activity count; keepalive does not; deadline clamp; non-preemptible refused.Unenforceable, or active Jobs stopped wrongly
Cancel and recoveryUser, parent, session, budget cascades; thread outliving escalation; crash at each transaction; owner loss; idempotent reconcile.Early release, surviving descendants or permanent occupancy
VisibilityDTO contract on every surface; queue position, shared remaining, unknown cost, reason, retryable; legacy Job.Surfaces disagree, or unknown shows as zero
Feature-matrix filled-circle gate

For the row “concurrency and per-session cumulative spawn limits”. Token, cost, runtime and idle are not required; as separate rows each would need its own gate. UI, schema or a single-process semaphore alone is not enough. Current status needs item-by-item evidence.

  1. Stable configuration schema; global defaults, session overrides and effective values visible in Web, TUI and CLI.
  2. Every creation entry uses admission: no Web, synchronous, target-inbox or direct-runner bypass.
  3. Per-session live and cumulative admission are atomic under contention, without overallocation or double counts.
  4. Queue, live, cumulative and stopping follow this page.
  5. Completion, failure, cancellation, timeout, worker crash and mid-admission crash release capacity without leaks.
  6. Web, TUI and CLI show effective limits, usage, queue, live, cumulative and reason codes.
  7. Migration, concurrency and crash tests, documentation links and matrix scoring checks pass.

Implementation status

Everything above exists in source. “Primitive exists”, “entry returns state” and “full path accepted” are separate states; each row records only what still needs acceptance.

AreaCodeAwaiting acceptance
Job entity and storeopenprogram/runtime/jobs/types.py, store.pyCrash recovery, terminal idempotence
Runner, dispatcher, reconciler, budget loopopenprogram/runtime/jobs/runner/: admit_job_entity, spawn_job, _run_one, cancel_execution, await_job, bounded_operation_timeoutWhole-product gate, fairness, worker loss, per-operation stops
Admission, claims, releaseopenprogram/runtime/jobs/resource_governance/: admit_job, try_start, claim_next, request_stop, release_job, reconcile, resolve_resource_limits; runtime/execution/recovery/resource_saga.pyRefusal leaving no side effects on WebSocket, busy-target inbox, internal retries; failed-receipt notice; process-death timing
Run tablesopenprogram/runtime/execution/store/run_tables.py, _schema.pyRepeated recovery
Token and costopenprogram/models/providers/streaming/stream.py, budget.py; reserve_provider_request; openprogram/models/usage/ledger.pyProvider-by-provider coverage, late settlement, fault injection
Runtime and idleopenprogram/runtime/jobs/runner/progress.py; openprogram/models/providers/utils/http_transport/deadline.py; openprogram/programs/_host/runtime.pyStop confirmation per operation type
Spawn and message budgetsopenprogram/programs/tools/agents/agent/agent/agent.py; send_message/send_message/depth.py; openprogram/state/settings.pyExplicit child allocation, sibling contention
Surfacesbuild_job_resource_view; interfaces/server/ws_actions/job.py; apps/web/lib/execution/job-resource.ts; apps/cli/src/commands/jobResource.ts; interfaces/cli/commands/conversations/jobs.py; tools/agents/agent/list_jobs/, job_output/Field and reason parity, legacy records, unknown cost display, recovery states
Worker lock, usage recordingopenprogram/operations/worker/lock.py, paths.py; openprogram/models/usage/event.py, recorder.pyNone specific

Usage metering

Last updated · 2026-11-25