OpenProgram Docs

Session DAG design

ROOT user 1 reply 1 user 2 reply 2 predecessor user 2′ retry: same predecessor, a fork tool model call caller caller
  1. ROOT
  2. predecessor
  3. user 1 → reply 1 → user 2 → reply 2A retry of user 2 shares predecessor reply 1: a fork.
  4. caller
  5. tool → model callNesting under reply 2

Arrows point at the edge's target. One node per user message, model call, function or tool call. Transcript and call tree are two views of this per-session, append-only record; any past call re-renders as the model saw it.

ItemDetail
Graph ownerEach Agent execution (ownership)
Ordinary helpersNo durable nodes; semantic operations are still recorded completely
Permission, cancellation, file checkpointsOriginating execution, whoever owns the graph
Inherited ContextDoes not turn computation into history

Model selection

ModelUseful forBoundary
Flat logsAppend-only, simple collectionNesting, ancestry and reads need extra relationships
Span treeIdentity, parent-child calls, timing, status, attributesParentage describes calls, not the conversation predecessor; cannot name alternative continuations
Timed nested intervalsPerformance views (Chrome Trace, Perfetto)Timing cannot say which branch a reply follows
Session DAG (selected)Calls, branches and reads in one recordNeeds edge validation, indexes, explicit rendering rules

One record must hold nested calls, branches and the exact nodes each LLM call read.

Adopted and rejected choices
ItemDetail
Uniform operation recordAdopted: all nodes share Call; role and metadata differ
Parent-child call relationshipAdopted as caller
Time order instead of the conversation edgeRejected: seq cannot identify branch ancestry
Context reads only as tracing eventsRejected: reads lists node IDs; telemetry export is a separate mapping
caused_byNot part of the schema
OTel SDK for persistenceRejected: storage and context reconstruction stay in OpenProgram
GenAI attribute conventionsReference for model and usage metadata (conventions); no exporter is implied
Span structureOpenTelemetry trace model
Studied, storage not copiedDatadog, New Relic, Honeycomb, Lightstep, Pixie, Cilium, Langfuse, Arize Phoenix/OpenInference, LangSmith, OpenLLMetry, W&B Weave, Braintrust
Optional diagnosticsKept separate
ValidationCall tree and conversation chain independently
Token, cost, evaluation metadataNeed explicit definitions; never inferred from timing

Data model

ItemDetail
idUnique identifier
seqMonotonic; the only sort key
created_atWall clock, for humans
roleuser, llm or code; decides rendering, not essence
nameModel id, function name or user name
inputPrompt, function args or None
outputReply, return value or user text
callerSub-call parent
predecessorConversation parent
readsNodes this LLM call read; not structure
metadataToken usage, model, source, expose, tool_call_id…; LLM leaf fields align with gen_ai.*
metadata.statusrunning, completed, error, cancelled on every path. Error nodes carry structured type and trace; a user cancel writes cancelled
Scenariorolecallerpredecessor
ROOT (display=root)useremptyempty
User messageuserROOTprevious reply; "ROOT" on the session's first node
LLM replyllmthis turn's user, or the enclosing code nodethis turn's user
LLM calls a toolcodethat llm node—
User calls a functioncodeemptybranch head, or "ROOT"
Agent requests a model or direct toolllm / codeowning operation in this graph—

Loops are not nodes: their model and tool operations are.

Edges and invariants

ItemDetail
Both edgesDirected, acyclic, orthogonal
callerConnects top-level nodes to ROOT
predecessorChat order and forks, which caller plus seq cannot give. Only this top-level field; no metadata mirror or legacy read
Write (session_store/shared.py)A mislinked branch is unrepairable, so a ROOT-level user or llm node with no real caller needs a predecessor, else PredecessorMissingError
Legal exceptionsFirst node and explicit root forks (sentinel "ROOT") · ROOT itself · spawn roots (predecessor=None, caller = spawner) · ask_user answers (user node with non-None input) · summary nodes covering from the session start (§8)
Readget_branch and list_branches walk edges only. A missing predecessor must be a spawn root, ROOT, the first node, a code node opening a run branch or such a summary, else BrokenPredecessorChainError with the node id

Branches and spawn

ForkReplacedNewShared edge
Resend a messageuser2 (P=llm1)user2′ (P=llm1)predecessor
LLM retryllm1 (P=user1)llm1′ (P=user1)predecessor
Tool retrycode (C=llm1)code′ (C=llm1)caller

Failure

ItemDetail
ErrorTerminal: status=error, turn committed, head stops
CancelLikewise, cancelled
RetryAn ordinary fork. The failed line stays reachable, off the active branch, so out of the retry's context; nothing filters by status
Finalization on errorRuns
Git, project and shadow-git commits, snapshot evictionYes: no timeline hole, a retry has a committed predecessor
Context-commit backfill, usage feedback, auto-titlingNo: they presuppose a reply

Spawn

user spawn turn notice₁ answer₁ notice₂ answer₂ predecessor spawn root caller clean: predecessor=None, context stops here both ways first user inherited: an exact fork from the requested node
  1. spawn turn → notice₁ → answer₁ → notice₂ → answer₂Completions chain on HEAD.
  2. caller
  3. spawn rootClean: predecessor=None. Context stops here both ways.
  4. InheritedFirst user node's predecessor is the requested node: an exact fork.
ItemDetail
SessionStore.spawn_branch(session_id, caller_node_id, *, source, name=…, register_head=True)The only way to open a clean spawn root. Called by TurnWriter for branch_from=None with spawn_caller, which Job runner, collaboration messages and background agents set
Root nodeUser node with caller, metadata.source, metadata.spawn_branch_root=True
HeadRegistered, unless register_head=False (same-session sub-agents)
Contextget_branch stops at the root; rendering from the parent does not descend through caller (Context rendering)
Cross-session exact fork
ItemDetail
Source session SKeeps the attach card beside initiating node A. A is spawn_out; the card points at attach.session_id=T and the target head
Target TNew user node: predecessor=M, caller=A, metadata.spawned_from_session=S. The graph cannot draw into another session, so T's projection places the caller at ROOT and marks the node spawn_remote
HEADsNeither moves. The result is registered as a branch tip; a later reply-back advances the source HEAD as an ordinary turn

Completion notification

Written backAnchored atBecause
Attach pointerThe caller turnA record of a call
Notification turn (source="job_followup")Current HEAD, advancing itA new turn: N sub-agents form one chain, not N answers to one message

The runner leaves TurnRequest.branch_from at INHERIT_PARENT and never rewinds head. JobRunner._followup_lock, one per delivery session, serialises simultaneous finishes.

Head and branches

ItemDetail
head_idActive branch tip. Conversation writes advance it to a real node, never a placeholder or summary; a dangling head renders empty. Caller-tagged nodes leave it
get_branch(session_id, head_id)Predecessor chain from head to terminus
list_branches(session_id)Visible conversation tips plus retained branch references. Rewind hides withdrawn suffixes while preserving sibling references, including references at a shared ancestor or ROOT. Branch identity distinguishes references at the same head. Internal execution rows do not create conversation tips, and neither does a turn's message written under a recorded branch's head in the moment before the head and the record move onto it
Branch namesSession metadata: branch-reference labels own each branch name; branches keeps the selected-head compatibility projection

Context rendering

A node renders if and only if its nearest ROOT-level ancestor (up caller) lies on the predecessor chain of head_id, and the frame and expose rules admit it.

ItemDetail
seqOnly orders
EngineResolves head, calls render_context, hands the result to render_dag_messages; filters nothing itself
Read pathWrites nothing
ROOTNever expanded: its caller-subtree would re-admit every sibling branch
Spawn root (metadata.spawn_branch_root)Not entered via caller: a Goal working agent cannot read its judge. Seen through the spine from inside the branch
Top-level chat (frame −1)Every spine turn is fully visible
Inside a function (frame = its seq)Pre-frame history, own progress; others' internals per expose (default io)
Code node with metadata.tool_call_idA real ToolCall/ToolResult pair inside its llm node's assistant message
Code node without oneText pair
Chat streamTop-level user and llm by seq, nesting folded
Call treeExpanded along caller, loop siblings folded ×N

Context assembly

ItemDetail
One assemblerbuild_system_prompt(agent, *, channel, tools, additional_working_dirs, plan_mode), for every model call: identity, project memory, unified tool list, skills
BudgetCounts the string that ships
VariationConstant by default, for KV-cache hits and one background across chat and functions. A slim prompt is an explicit call-site choice that accepts the miss
Wrong tool use in a functionUser-turn guidance plus a depth cap, never another tool list (self-recursion)
RecordingOn a hash change (start, toolset change, plan-mode toggle): a role=code node name="context/system_prompt", caller=ROOT, output = full text. Rendering pins the latest on the spine
context/* namesReserved and hidden from chat, except context/summary, which is real conversation content
Memory prefetchPrefix block in the user node's wire message, stored as the memory_prefetch entry of its turn_context metadata (Composition). System and tools stay byte-stable
Images and filesBy reference; bodies in the attachments directory, loaded by render

Compaction

P a b c d e · HEAD covers_ids = exact chain nodes S role=llm, name="context/summary" no edge rewritten, HEAD stays A chain holding all of a–c renders [S, d, e]. Any other renders raw.
  1. P → a → b → c → d → ee is HEAD and stays.
  2. Spredecessor = P, covers_ids = a, b, c. No edge rewritten.
  3. RenderedA chain holding all of a–c: [S, d, e]. Any other: raw.
ItemDetail
metadata.covers_idsIds, because sibling branches interleave seqs. The WebUI payload adds covered turns' caller subtrees (rendering §9)
Next summaryAbsorbs the one in effect, which nodes.active_summary_for_chain picks for the chain; the graph builder folds each branch with the same pick
Full specCompaction
Old tool resultsNever aged: each renders as its turn sent it until compaction covers its turn, so the cache prefix only grows between compactions
ReplayRendering reads only stored nodes, so a graph renders the same bytes on any day; a render_manifest written by an earlier version is ignored
SpillWhen recorded, once and deterministically, never when rendered
One pipelineThe DAG render is the only context path; if it raises, the turn fails visibly

Storage

ItemDetail
SessionLogOne append-only log per session under <state>/projects/<project_id>/chats/<id>/
SessionMemoryIndexPer session, lazy; node-by-id and children-by-predecessor
head_id, branch namesSession fields
Store scopeRaw nodes and meta; context commits belong to the commit subsystem
Agent method bodyRuns in a spawned subprocess (a fork would crash on the first BLAS call once PyTorch/libomp is loaded), so stop can SIGKILL the process group
Its code subtreeWritten by the subprocess's own SessionStore; the parent then invalidates its cache. The one truth for a function call: WebSocket frame and refresh load give the same card

Implementation status

Data model through Compaction and graph ownership are in code with regression coverage.

Ablation switches
VariableMovesRead
OPENPROGRAM_NODE_RENDER_CAPSpill size for a new node that is neither a tool result nor a message (a summary, a program's return value); an existing node keeps the limit it was recorded underAt import
OPENPROGRAM_NODE_SPILLLarge-node spillAt import
OPENPROGRAM_EXPOSE_DEFAULTWhat an unspecified expose= means; an explicit one winsAt call
Code map
FileHolds
openprogram/state/store/session/nodes.pyCall, Graph, role constants
openprogram/state/store/session/session_store/Append invariant, get_branch, spawn_branch, list_branches
openprogram/state/store/session/files/spill.pyWrite-path spill
openprogram/runtime/context/session_dag/nodes.pyrender_context, segment substitution
openprogram/runtime/context/session_dag/render.pyrender_dag_messages
openprogram/runtime/context/prompt_assembly/components.pyThe system-prompt assembler
openprogram/runtime/context/prompt_assembly/system_prompt_node.pycontext/system_prompt recording, context/* hiding
openprogram/runtime/context/compaction/persistence.pySummary nodes
openprogram/runtime/conversation/turn_runtime/__init__.pyChat entry
openprogram/runtime/agent/runtime/Function-body model calls

Rendering specification · Layout scenes

Last updated · 2026-11-25