# Framework overview

Subsystems are decoupled by one process-wide event bus: the dispatcher, agent loop, tool execution, storage and collaboration never call each other's UI or broadcast logic. They `emit`; whoever cares subscribes.

| Lane | Behaviour |
| --- | --- |
| Asynchronous observation | `EventBus`: nobody can stop what is happening |
| Synchronous consultation | `tool_gate`: the one place that can stop a tool |

## One turn

1. **Session** get or create prepare_turn
2. **History** branch_from get_branch
3. **User message** written before the run user.prompt_submitted
4. **Bind turn** ContextVars _current_turn_id, _store
5. **Context and loop** prepare, compact, agent_loop run_loop_blocking
6. **Assistant message** persist persist_assistant_message
7. **Finalize** usage, Git commits finalize_turn

- **Entry**: `ChatAgent().run_turn` (production), which reaches `_process_turn_once` in `runtime/conversation/turn_runtime/__init__.py`. `process_user_turn` is a compatibility entry. Synchronous so channel worker threads can call it; starts its own asyncio loop and returns `TurnResult`
- **User message**: A DAG Call node with `caller=ROOT`, written before the run so a crash leaves a record. Emits `chat_ack` and `user_message` for the UI
- **Turn binding**: `TurnBindings` sets `_current_turn_id`, read by every coroutine in the turn (tools, Agent methods, `send_message`) and routing file backups and sub-branch anchors; and `_store`, a `SessionNodeWriter` for the same DAG. Assistant id is `user_msg_id + "_reply"`. Reset on success, exception and early return
- **Finish**: Emits `chat_response`, returns `TurnResult`

### History and branches

| `branch_from` | History | Meaning |
| --- | --- | --- |
| `INHERIT_PARENT` | `db.get_branch(sid)` | Multi-turn: the whole current branch |
| `None` | `[]` | Root fork: starts empty |
| `"<node_id>"` | `db.get_branch(sid, node_id)` | Sibling fork: up to the fork point |

Single-turn and multi-turn differ only in chain length. Writing a fork means pointing a user node's caller away from the active tail (`set_head` moves the UI pointer), or a new root through the `agent` tool.

### Before the model call

1. `run_loop_blocking` calls `ContextEngine.prepare(...)`: DAG history rendered into LLM messages (`TurnPrep`).
2. If `should_auto_compact(prep)`: `compact` (LLM summarization into a durable node); then prepare again.
3. The prompt is added once per loop, so the prompt-cache prefix stays intact.
4. `agent_loop([prompt], context, config, ...)`.

### Core loop

1. Push `AgentEventTurnStart`.
2. `_stream_assistant_response` calls the model.
3. Extract `ToolCall`s; `_execute_tool_calls` runs them; results are appended to the context.
4. Push `AgentEventTurnEnd`. Stop when there are no tools, steering or follow-up.

Chat turns have no iteration cap. `runtime.exec` passes `max_iterations=20`.

### Each tool call

| Step | What happens |
| --- | --- |
| Start | Push `AgentEventToolStart` |
| Announce | `make_event("tool.before", ...)` and `emit`: one event for observers and the gate |
| Gate | `decide_tool_gate`. Any deny blocks, reasons merged; a raising gate allows |
| Denied | `ToolGateDenied` sends the reason to the model as an error result |
| Subagents | Covered: the gate sits outside the `permission_mode` wrapper, so `bypass` cannot turn it off |
| Execute | `tool.execute(...)` with cwd snapshot and file checkpoint |
| End | Push `AgentEventToolEnd`, emit `tool.after` |
| Feed back | A `ToolResultMessage`. Steering is checked after each tool; a hit skips the remaining tools |

### Finish

- **Failure**: The error folds into the placeholder row or a standalone error node; `head_id` moves to the failed turn
- **Success**: `persist_assistant_message`, then `finalize_turn`: head and token update; ContextCommit output backfill; `after_turn` feeds provider usage back; shadow Git turn commit and project auto-commit (`commit_turn_changes`); auto-title, usage, snapshot eviction; session status
- **DAG**: User node, assistant placeholder, tool results and Agent method nodes all reach one `SessionNodeWriter`. `commit_turn` makes session fields durable: append-only, no mutable mirror file, so concurrent agents never collide

## Events

| Event | Emitted by | Consumed by | Notes |
| --- | --- | --- | --- |
| `user.prompt_submitted` | `turn_runtime/prep.py` | proactive state observer | User message committed |
| `tool.before` | `agent/loop/tool_dispatch.py` | tool_gate (sync), observers | The only interception point |
| `tool.after` | `agent/loop/tool_dispatch.py` | observers | Carries is_error |
| `model.response_started` | `agent/loop/provider_lifecycle.py` | observers | Stream begins |
| `model.response_completed` | `agent/loop/provider_lifecycle.py` | proactive wrap-up policies | Wrap-up check |
| `subagent.started / .ended` | `jobs/runner/shared.py` | observers | origin system; session passed explicitly |
| `branch.message_sent` | `send_message.py` | observers, ws.frame | from, to |
| `question.asked` | `agent/questions.py` | channels _question_bridge.py | Bus and ws frame |
| `question.replied` | `permissions/approvals/lifecycle.py` | front end | ws frame only |
| `question.rejected` | `agent/questions.py` | front end, as withdrawn | ws frame only |
| `context.compacted` | `context/engine.py` | UI, observers | Compaction happened |
| `file.changed` | functions watcher and others | observers | File change |
| `channel.message_inbound` | channels | observers | Inbound message |
| `reminder.fired` | scheduler worker | scheduler/reminders.py | Shows it and wakes the agent |
| `memory.ingest_started / .ended` | memory | observers | Memory ingestion |
| `skills.changed, plugins.update_available, sessions.listed, branches.listed` | various | UI, observers | Lists and updates |
| `ws.frame` | `emit_ws_frame` | interfaces/server/server.py | Passthrough; sources never touch _broadcast |

Paths under `openprogram/runtime/` unless otherwise clear. Subscribers: proactive engine takes all events and filters by `on`; the Web server only `ws.frame`; the channels bridge only `question.asked`. `emit` is fire-and-forget: a raising handler prints to stderr and never reaches the emitter; an async handler with no loop is skipped; `emit_safe` swallows everything.

## Layers

| Layer | Files |
| --- | --- |
| Storage | `state/store/session/session_store/`, `memory_index.py`, `session_log.py` |
| Event layer | `runtime/events/` (`bus.py`, `tool_gate.py`), `runtime/agent/questions.py` |
| Context engine | `runtime/context/`: `engine.py`, `render.py`, `compaction/`; finalize in `conversation/turn_runtime/finalize.py` |
| Agent run | `runtime/agent/loop/`, `conversation/peer_agents/sub_agent_run.py`, `models/providers/utils/streams/event_stream.py`, `extensions/gating.py` |
| Collaboration | `programs/tools/agents/send_message/`, `programs/tools/agents/agent/` |

### Storage

- **Log**: One append-only log per session; `_open(sid)` returns `(SessionLog, SessionMemoryIndex)`, LRU cached, index rebuildable from the log
- **Branch**: Stable branch identity plus its current head. `get_branch(sid[, head])` walks the predecessor chain; separate branch references may share a head after Rewind. Each reference keeps independent configuration; project files remain shared
- **Commit**: `commit_turn(sid, msg)` at turn boundary. Events: `sessions.listed`, `branches.listed`

### Event layer

- **Bus**: `EventBus.subscribe(handler, types=...)`, legacy `on`, process singleton `get_event_bus()`
- **Gate**: `register_tool_gate`, `decide_tool_gate`: strictest wins, fails open, must be fast (no LLM or slow IO)
- **Questions**: `QuestionRegistry`: process-wide pending table, claim-once, thread-safe

### Context engine

- **Tool output**: A tool result is bounded once by weight when it is made and sent whole as stored on every later request; only compaction replaces old turns
- **Context commits**: `state/store/session/context_commit/`: stored per-turn records, written when branches merge and shown in the context timeline (`context/commit/views.py`). Finalize backfills the final assistant output
- **Event**: `context.compacted`

### Agent run

- **`EventStream`**: Async-iterable plus a terminal value; provider dict events become typed
- **`LoopDriver`**: `prompt`, `follow_up` (append at wrap-up)
- **Static admission**: `gate(name, disabled, allowed, categories)`: fnmatch, in that order. `agent.json` declares who may use what; separate from `tool_gate`
- **Subagents**: `run_agent_turn(sid, prompt, agent_id, ...)` durably admits one turn with `source="agent_spawn"`, inherits the parent's permission mode and rules, and waits for its Job. Returns `AgentTurnResult` (`head_id` is the new tip); `label` names the branch

### Collaboration

- **`to`**: `SID:HEAD` (one more turn from that head) or a branch name. Creating branches is the `agent` tool's job; `to="new"` is rejected with a redirect
- **Parent anchor**: `_resolve_parent` reads session and turn ContextVars and falls back to the session head when the turn id is missing: worker-thread ContextVars are unreliable, which is also why `subagent.started` and `.ended` pass the session explicitly
- **Delivery**: Always asynchronous through the Job runner (`run_agent_turn_async`). On completion it writes an attach pointer and dispatches a follow-up to the initiator. The caller's model reads it as a user-role report (`_attach_report`): name, task, final reply and `read_conversation(session_id, head_id)`. A synchronous spawn adds nothing: the `agent` result already has reply and `SID:HEAD`
- **Guards**: `agent.max_messages` (0, off by default; children inherit count + 1; A↔B round trips count); a turn cannot message itself; target session must exist; `tool.before` applies
- **In chat**: Sender shows the tool's own row ("Sent to …"); the receiving branch draws one row named after the sender, from `[message from SID:HEAD (sender)]`

## Known boundaries

| Area | Boundary |
| --- | --- |
| Plugin hook | `tool.before` observes and denies; it cannot mutate or veto by plugin. |
| Approval | `Gate.ask` is not wired to the approval registry. The critical fail-closed tier awaits a rules layer. |
| Tests | Several `process_user_turn` and `agent_loop` paths have no covering tests. |
| Context engine | `ContextEngine.after_turn` has a stub on the abstract base and the working version on the concrete engine. |

[Framework comparison](https://fzkuji.github.io/OpenProgram/docs/reference/design/framework-comparison/overview.html)
