OpenProgram Docs

Runtime

For API usage, see Runtime API.

Package layout

openprogram/runtime/Is
agent/One model call: the Agent class and its use of a Context, agent() and llm(), the tool loop (loop/: loop.py, LoopDriver in driver.py, AgentSession, tool and event types, retry), and Runtime. The code of Agentic Programming.
conversation/Chats and turns on Agent: turn_runtime/ runs one turn, chat.py is ChatAgent, production_driver/ drives a turn as a canonical execution, run_control/ tracks the running turn; session settings, inbox, open work, rewind, always-on agents.
jobs/Background runs: job store, runner pool, resource_governance/ (admission and limits).
agent_registry/Saved Agent configurations: which exist, their model, tools and workspace.
permissions/What a tool call may do: policy (the one decision), identity (limits for non-owners), refusal (the one source of refusal text), approval, audit, authority (who is asking), attended mode (no questions when nobody is watching).
context/The Context class (model.py) and what the model sees: rendering, compaction, system prompt, session_db.py.
execution/Control plane for pause, cancel and recovery: execution store, revisions, waits, checkpoints.
events/The event bus.
scheduler/, proactive/, commands/Timed runs, proactive policies, slash commands.
Runtime packages by concept

Dependency direction

LayerRule
Featuresconversation, jobs, agent_registry, scheduler, proactive, commands build on agent
Call coreagent builds on the lower packages and never imports a feature
Lowerexecution, context, permissions, events do not import agent
Checked bytests/contracts/repository/test_runtime_layering.py; imports that break the directions are a frozen list that may only shrink. context and permissions keep them in full.
How lower packages reach higher ones
RegistrationSupplies
conversation/layer_registrations/context_registration.pyThe open_work system-prompt section and the Agent profile loader for context breakdowns
conversation/layer_registrations/permission_registration.pySession and turn facts read by permissions/session_facts.py
context/scope.pyTask-local call state Context reads (_call_id, workflow call site); the call core imports it from there
runtime/agent/engine_link.pyThe one port for what the call core needs from the engine: running a persistent turn or saved continuation (Agent.run_turn / resume_turn) and its Agent profile, a saved Agent's tools, binding a resumed tool call's pre-approved question wait, whether the worker is stopping, the running job's activity and operation timeout, the runtime contract a resumable tool loop checkpoints
conversation/layer_registrations/engine_registration.pyImplements that port when openprogram.runtime.conversation is imported; the worker and Server import it at start. The same import brings in conversation/run_control, which claims the core's cancellation check.
  • With nothing registered the core is a plain library: the worker is not stopping, no background job runs, Agent.run_turn raises EngineUnavailable.
  • Imported directly, with or without an engine: bound session and execution, nested-call admission and terminal marking (execution/run_control/), approval gating (permissions.approvals.approval.wrap_with_approval), the pre-approved wait id (permissions.session_facts).
  • TurnRequest and the request in force (agent/turn_request.py) are call-core types the engine builds and binds.
  • A module exports only the names it owns: execution binding from openprogram.runtime.execution.run_control, permission vocabulary from permissions/modes.py, tool contract (AgentTool, AgentToolResult) from openprogram.models.providers.types, call-scope ContextVars from context/scope.py. tests/contracts/repository/test_no_transitional_reexports.py keeps moved names from returning.
  • process_runner.py, which runs a turn's Agent method tools in a subprocess, is engine code in conversation/.

One runtime, one session

CallEffect
create_runtime()Open session
runtime.exec()Send one request in it
runtime.close()Close session

No reset() or new_session(); a new session is a new create_runtime(). Two independent conversations need two runtime objects, which is rare.

Why one Runtime does not reuse sessions
  • CLI providers keep session state in the subprocess; reuse would hang a mutable current session id on the Runtime and invite concurrency races.
  • API providers are stateless; multiple sessions would be an upper-layer dict, no new capability.
  • ContextVar injection relies on a runtime bound to the current function tree.

The runtime is injected through a ContextVar

An Agent method without runtime= reads the _current_runtime ContextVar. An entry function with neither calls create_runtime(), and closes it at exit. A child inherits its parent's runtime.

RejectedWhy
Explicit runtime: Runtime in every signaturePlumbing unrelated to the function's logic, repeated at every nested call
Module-level singletonShared across threads and coroutines, so concurrent agents step on each other. A ContextVar is isolated per thread and coroutine.

One abstraction for session and API providers

Authors see llm(...) / agent(...), both ending in runtime.exec. has_session picks the internal path.

Session provider (CLI)API provider
Conversation memoryKept by the subprocessNone; each exec is independent
Context injectionSkips DAG render; sends docstring and current contentHistory from the DAG via render_context + render_dag_messages
render_range.subcallsNo effectBounds the injected history

Two Runtime classes would need two implementations per function, breaking “functions describe the task, providers describe the channel”. One conditional is the cost.

Retry lives in the runtime

exec() / async_exec() have max_retries, default 3 (OPENPROGRAM_MAX_RETRIES), for every provider. Providers only send and receive; retry, throttling and caching are runtime concerns.

  • One policy for network timeouts, rate limits and 5xx.
  • One failure format: Attempt N: ErrorType: msg.
  • TypeError, NotImplementedError and ImportError are not retried: a provider bug or missing subsystem does not go away, and burning the backoff schedule only delays the failure.

DAG writes

MomentWrite
Enter Agent methodCode node, status=running; _call_id points at it
runtime.exec() in the bodyLLM node under _call_id, caller = _call_id
Exit (return or except)Backfill the same code node's output and status
expose="hidden"No code node; a phantom _call_id still gives inner LLM calls a frame

Two writes rather than one on completion: the visualizer shows a running call at once, and an exceptional exit still has a node for the error.

Embedding seams

The core runs inside hosts that are not OpenProgram (Embedding in your own stack). tests/component/runtime/test_standalone_embed.py executes the contract:

  • import openprogram and a full Runtime(call=...).exec() round trip do not pull in webui, FastAPI, Uvicorn or Textual.
  • With SessionStore(root_path=...) + session_scope(store, session_id) the run never consults openprogram.state.paths; with no store it persists nothing.
  • A standalone run starts with a principal drawn once per process and never stored, with the owner tier. It becomes the profile's owner when it is handed a profile runtime or sends a request to the profile's model. A run on a host-supplied call=, wherever the host creates it, reads no owner.json.
SeamCore defaultPlatform registration
set_cancellation_check (openprogram.host.cancellation)No-opopenprogram.runtime.conversation.run_control registers the exact execution check at import
set_cancellation_waker (openprogram.host.cancellation)None; a blocking host wait (a command's collect) notices a stop only at its own timeout or resyncrun_control wakes it when the tool call's, the turn's or the Worker's stop is fired
set_session_id_providerNone; runtime.can_ask() is Falserun_control provides the active session id
session_scope(store, id)Unset; no persistenceThe dispatcher binds the per-turn store

Hooks mirror add_pre_invocation_hook and keep the dependency one-way while run_control checks the exact execution token.

Implementation files
PathHolds
openprogram/runtime/agent/runtime/Runtime base class, exec / _call protocol, retry loop
openprogram/runtime/agent/call_state.pyDecorator, _inject_runtime, _current_runtime
openprogram/models/providers/catalog/registry.pydetect_provider, built-in PROVIDERS table
openprogram/runtime/agent/runtime/factory.pycreate_runtime, built from that detection
openprogram/runtime/agent/provider_runtimes/Runtime subclasses of subscription and CLI-credential providers (openai_codex.py, google_gemini_cli.py), PROVIDER_RUNTIMES. Others run on the base Runtime; openprogram/models/providers/adapters/<vendor>/ holds only model, auth and wire code.
openprogram/runtime/context/session_dag/nodes.pyrender_context: DAG to reads (the semantics of render_range)
openprogram/runtime/context/session_dag/render.pyrender_dag_messages: reads to provider messages
PageCovers
Execution recordAuthoritative data model: one graph, node roles user, llm, code, caller and predecessor edges, render_context
DAG renderingAuthoritative: layout, edges, legend, default visibility, 12 scenarios
Branch collaborationCommunication, dispatch, merge
Nested LLM node contentOrdered chat blocks
Call flowTurn and loop skeleton, orthogonal to the node model
Agent worktreeWorktrees
Async job lifecycleBackground jobs
Execution controlAuthoritative: pause, continue, step, steering, cancellation, checkpoint, revision, recovery
Dispatcher splitOne module per responsibility in conversation/turn_runtime/
Nested llm() streamingPer-node tokens: protocol, buffer, persistence, cancel and reconnect, in process and subprocess
File managementAuthoritative: attribution, Review, Undo, Restore, branch alignment, multi-agent ownership
Streaming resumeReconnecting to a running stream
User input requestsruntime.ask / confirm, question registry, WS/REST protocol, subprocess bridge
SessionData model, storage, naming, listing, lifecycle, broadcast
Agent collaborationAuthoritative: one cross-branch primitive, four domains, tool surface, three budgets; tool surface, eight references compared
Permission decisionThe one decision path, modes, refusal contract
Sandbox architectureAuthority tiers, permission modes and approval, enforcement, comparison, evidence
Last updated · 2026-11-25