# Runtime

For API usage, see [Runtime API](https://fzkuji.github.io/OpenProgram/docs/reference/api/runtime.html).

## 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](agent-code-structure.svg)

### Dependency direction

| Layer | Rule |
| --- | --- |
| Features | `conversation`, `jobs`, `agent_registry`, `scheduler`, `proactive`, `commands` build on `agent` |
| Call core | `agent` builds on the lower packages and never imports a feature |
| Lower | `execution`, `context`, `permissions`, `events` do not import `agent` |
| Checked by | `tests/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**

| Registration | Supplies |
| --- | --- |
| `conversation/layer_registrations/context_registration.py` | The `open_work` system-prompt section and the Agent profile loader for context breakdowns |
| `conversation/layer_registrations/permission_registration.py` | Session and turn facts read by `permissions/session_facts.py` |
| `context/scope.py` | Task-local call state `Context` reads (`_call_id`, workflow call site); the call core imports it from there |
| `runtime/agent/engine_link.py` | The 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.py` | Implements 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

| Call | Effect |
| --- | --- |
| `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.

| Rejected | Why |
| --- | --- |
| Explicit `runtime: Runtime` in every signature | Plumbing unrelated to the function's logic, repeated at every nested call |
| Module-level singleton | Shared 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 memory | Kept by the subprocess | None; each exec is independent |
| Context injection | Skips DAG render; sends docstring and current content | History from the DAG via `render_context` + `render_dag_messages` |
| `render_range.subcalls` | No effect | Bounds 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

| Moment | Write |
| --- | --- |
| Enter Agent method | Code node, `status=running`; `_call_id` points at it |
| `runtime.exec()` in the body | LLM 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](https://fzkuji.github.io/OpenProgram/docs/capabilities/agentic-programming/embedding-in-your-own-stack.html)). `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`.

| Seam | Core default | Platform registration |
| --- | --- | --- |
| `set_cancellation_check` (`openprogram.host.cancellation`) | No-op | `openprogram.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 resync | `run_control` wakes it when the tool call's, the turn's or the Worker's stop is fired |
| `set_session_id_provider` | `None`; `runtime.can_ask()` is `False` | `run_control` provides the active session id |
| `session_scope(store, id)` | Unset; no persistence | The 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**

| Path | Holds |
| --- | --- |
| `openprogram/runtime/agent/runtime/` | Runtime base class, `exec` / `_call` protocol, retry loop |
| `openprogram/runtime/agent/call_state.py` | Decorator, `_inject_runtime`, `_current_runtime` |
| `openprogram/models/providers/catalog/registry.py` | `detect_provider`, built-in `PROVIDERS` table |
| `openprogram/runtime/agent/runtime/factory.py` | `create_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.py` | `render_context`: DAG to reads (the semantics of `render_range`) |
| `openprogram/runtime/context/session_dag/render.py` | `render_dag_messages`: reads to provider messages |

## Related designs

| Page | Covers |
| --- | --- |
| [Execution record](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/overview.html) | Authoritative data model: one graph, node roles user, llm, code, caller and predecessor edges, `render_context` |
| [DAG rendering](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/rendering.html) | Authoritative: layout, edges, legend, default visibility, 12 scenarios |
| [Branch collaboration](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/branch-collaboration.html) | Communication, dispatch, merge |
| [Nested LLM node content](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/nested-llm-node-content.html) | Ordered chat blocks |
| [Call flow](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/agent/agent-call-flow.html) | Turn and loop skeleton, orthogonal to the node model |
| [Agent worktree](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/agent-worktree.html) | Worktrees |
| [Async job lifecycle](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/async-job-lifecycle.html) | Background jobs |
| [Execution control](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.html) | Authoritative: pause, continue, step, steering, cancellation, checkpoint, revision, recovery |
| [Dispatcher split](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/dispatcher-split.html) | One module per responsibility in `conversation/turn_runtime/` |
| [Nested `llm()` streaming](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/agent/agentic-llm-streaming.html) | Per-node tokens: protocol, buffer, persistence, cancel and reconnect, in process and subprocess |
| [File management](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/operations/file-management.html) | Authoritative: attribution, Review, Undo, Restore, branch alignment, multi-agent ownership |
| [Streaming resume](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/operations/streaming-resume.html) | Reconnecting to a running stream |
| [User input requests](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/operations/user-input-requests.html) | `runtime.ask` / `confirm`, question registry, WS/REST protocol, subprocess bridge |
| [Session](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/README.html) | Data model, storage, naming, listing, lifecycle, broadcast |
| [Agent collaboration](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/collaboration/agent-collaboration.html) | Authoritative: one cross-branch primitive, four domains, tool surface, three budgets; [tool surface](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/collaboration/agent-collab-architecture.html), [eight references compared](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/collaboration/agent-collab-comparison.html) |
| [Permission decision](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/security/permission-decision.html) | The one decision path, modes, refusal contract |
| [Sandbox architecture](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/security/sandbox-architecture.html) | Authority tiers, permission modes and approval, enforcement, comparison, evidence |
