OpenProgram Docs

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.

LaneBehaviour
Asynchronous observationEventBus: nobody can stop what is happening
Synchronous consultationtool_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
  1. Sessionget or createprepare_turn
  2. Historybranch_fromget_branch
  3. User messagewritten before the runuser.prompt_submitted
  4. Bind turnContextVars_current_turn_id, _store
  5. Context and loopprepare, compact, agent_looprun_loop_blocking
  6. Assistant messagepersistpersist_assistant_message
  7. 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_fromHistoryMeaning
INHERIT_PARENTdb.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 ToolCalls; _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

StepWhat happens
StartPush AgentEventToolStart
Announcemake_event("tool.before", ...) and emit: one event for observers and the gate
Gatedecide_tool_gate. Any deny blocks, reasons merged; a raising gate allows
DeniedToolGateDenied sends the reason to the model as an error result
SubagentsCovered: the gate sits outside the permission_mode wrapper, so bypass cannot turn it off
Executetool.execute(...) with cwd snapshot and file checkpoint
EndPush AgentEventToolEnd, emit tool.after
Feed backA 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

EventEmitted byConsumed byNotes
user.prompt_submittedturn_runtime/prep.pyproactive state observerUser message committed
tool.beforeagent/loop/tool_dispatch.pytool_gate (sync), observersThe only interception point
tool.afteragent/loop/tool_dispatch.pyobserversCarries is_error
model.response_startedagent/loop/provider_lifecycle.pyobserversStream begins
model.response_completedagent/loop/provider_lifecycle.pyproactive wrap-up policiesWrap-up check
subagent.started / .endedjobs/runner/shared.pyobserversorigin system; session passed explicitly
branch.message_sentsend_message.pyobservers, ws.framefrom, to
question.askedagent/questions.pychannels _question_bridge.pyBus and ws frame
question.repliedpermissions/approvals/lifecycle.pyfront endws frame only
question.rejectedagent/questions.pyfront end, as withdrawnws frame only
context.compactedcontext/engine.pyUI, observersCompaction happened
file.changedfunctions watcher and othersobserversFile change
channel.message_inboundchannelsobserversInbound message
reminder.firedscheduler workerscheduler/reminders.pyShows it and wakes the agent
memory.ingest_started / .endedmemoryobserversMemory ingestion
skills.changed, plugins.update_available, sessions.listed, branches.listedvariousUI, observersLists and updates
ws.frameemit_ws_frameinterfaces/server/server.pyPassthrough; 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

LayerFiles
Storagestate/store/session/session_store/, memory_index.py, session_log.py
Event layerruntime/events/ (bus.py, tool_gate.py), runtime/agent/questions.py
Context engineruntime/context/: engine.py, render.py, compaction/; finalize in conversation/turn_runtime/finalize.py
Agent runruntime/agent/loop/, conversation/peer_agents/sub_agent_run.py, models/providers/utils/streams/event_stream.py, extensions/gating.py
Collaborationprograms/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

AreaBoundary
Plugin hooktool.before observes and denies; it cannot mutate or veto by plugin.
ApprovalGate.ask is not wired to the approval registry. The critical fail-closed tier awaits a rules layer.
TestsSeveral process_user_turn and agent_loop paths have no covering tests.
Context engineContextEngine.after_turn has a stub on the abstract base and the working version on the concrete engine.

Framework comparison

Last updated · 2026-11-25