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
Sessionget or createprepare_turn
Historybranch_fromget_branch
User messagewritten before the runuser.prompt_submitted
Bind turnContextVars_current_turn_id, _store
Context and loopprepare, compact, agent_looprun_loop_blocking
Assistant messagepersistpersist_assistant_message
Finalizeusage, Git commitsfinalize_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
run_loop_blocking calls ContextEngine.prepare(...): DAG history rendered into LLM messages (TurnPrep).
If should_auto_compact(prep): compact (LLM summarization into a durable node); then prepare again.
The prompt is added once per loop, so the prompt-cache prefix stays intact.
agent_loop([prompt], context, config, ...).
Core loop
Push AgentEventTurnStart.
_stream_assistant_response calls the model.
Extract ToolCalls; _execute_tool_calls runs them; results are appended to the context.
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
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.
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)
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.