OpenProgram Docs

Overview

Each call renders a selection of the session's execution DAG into a Context (system, messages, tools): the branch it continues, each tool result as its turn sent it, the oldest turns replaced by one summary once the window fills. This layer decides what to feed; the provider layer decides how to send it.

Prepare history from the DAG, token budget Compact at 80% of budget, inline summary Agent loop system, messages, tools Provider Context overflow: reactive compaction, one retry
  1. Preparehistory from the DAG, token budget
  2. Compactat 80% of budget, inline summary
  3. Agent loopsystem, messages, tools
  4. Provider

    Context overflow: reactive compaction, one retry

The DAG render is the only pipeline. A render failure fails the turn visibly. Auxiliary calls (summarization, memory sleep, branch summary, mixture-of-agents) bypass engine.prepare and build a minimal Context: a system prompt and one user message, no tools.

What engine.prepare does

process_user_turn (openprogram/runtime/conversation/turn_runtime/) calls openprogram/runtime/context/engine.py:

  1. Scan references: tool_use ids cited later.
  2. Resolve the head, then render_context, then render_dag_messages.
  3. Take the system prompt the caller assembled (identity, AGENTS.md chain, skills, tools).
  4. Compute the token budget: system, history, tools, output reserve.
  5. Reconcile usage: the last provider measurement plus a local estimate of what was added since.
  6. Return TurnPrep.

Storage: the DAG

A git-backed, append-only session store (openprogram/state/store/session/). No rule rewrites a node. Each turn is a commit and predecessor is what it responds to.

OperationEffect
New messageNode under HEAD; HEAD advances
RetrySibling with the same content; it replaces a turn whose reply is only an error
EditSibling with different content
Switch version < N/M >Checkout to a sibling; re-renders only
Copy conversationNew session holding the history up to HEAD

Edit, retry and checkout are refused while an agent runs, so the active tree never hangs on a stale node. The workdir does not roll back with checkout.

Call node fields
FieldMeaning
id, created_at, metadataIdentity, wall-clock time, extras
seqIncreases within a session; the sole ordering key
roleuser, llm or code
nameModel id, function name or user name; context/* names are pipeline nodes
inputPrompt blocks or arguments
outputReply, return value or user content. Permanent: compaction never touches it
callerCall edge; top-level turns use ROOT
predecessorConversation edge: the turn this one continues
readsNodes that went into this call's prompt

Pipeline nodes join the chain: context/system_prompt records the exact prompt whenever it changes; context/summary stands in for compacted turns.

Rendering and compaction

StageRule
Selectionrender_context walks the predecessor chain from the head and admits each turn's call subtree through the frame and expose rules. It writes nothing. render_dag_messages turns the chosen nodes into provider messages; a direct function call becomes a text pair.
Finished turnRendered as its requests sent it: the stored turn block (recalled memory, run note) on the user message, then each provider response as one assistant message under the reply's own provider, api and model, then those calls' results. The message holds the response's reasoning, its text under the provider's message id, and its calls.
ReasoningA finished turn's reasoning items go back whole (shown only when they have a summary) to the model that wrote the reply. Another model gets none: it cannot use the items and would read a summary as something the assistant said.
Response marksThe reply's ordered blocks mark where each response began (round_start); a turn resumed from a checkpoint takes them from its journal, one per decision. A reply without them (recorded earlier, or with spilled text) gives each call its own message and puts its text last.
Old tool resultsSent whole, as their turn sent them, however many turns follow. Nothing ages them; only compaction replaces old turns. A render_manifest recorded by an earlier version is ignored, so such a turn renders whole too.
CompactionAt context.auto_compact_percent (default 80), on /compact, or when the provider rejects a request as too long, engine.compact summarizes the oldest whole turns into one context/summary whose covers_ids lists them. Each branch reads the summary that lies wholly on its chain and reaches furthest, with its kept tail; a branch with none renders raw. The summary must be non-empty and strictly smaller; images are left out of what it summarizes. Compaction

Tool output

One rule throughout: a later request sends the bytes the turn sent. A result is cut once, where it is made, and history stores that form. Code: runtime/agent/loop/tool_dispatch.py (_as_stored), state/store/session/files/spill.py, models/providers/shared/tool_attachments.py.

SettingEffect
Result formThe turn sends a result as one text block, joined as its node stores it, with images where they were, so every later request sends the same bytes on every provider
Result sizeA weight (state/store/session/weight.py: a CJK or full-width character counts 1, anything else 0.25, so about a token). The cap is the model's tool_output_weight, default 10,000 (Codex's truncation_policy), at most 30% of its window, and at most the tool's own max_result_weight when it declares a smaller one (spill.result_cap). 10,000 Chinese characters or 40,000 English ones fit; an 8,000-token window gives 2,400
One cutA tool never cuts its own text: @function(max_result_weight=…) records the cap in details["cap"] and the loop applies it. The cut keeps the head (60%) and tail on line breaks, then names the whole text's path and the lines to read as a read("…", offset, limit) call. The note is measured before the tail is chosen, so the result never passes the cap and the range is exact
Full textKept once, by its content, at <conversation>/tool_results/<sha256>.txt, deleted and backed up with the conversation. Outside a conversation it goes to the profile's tool_results/, which the Worker collects once a day: a file older than 24 hours that no conversation's records name is removed, and if any record cannot be read nothing is (tool_output_gc.py)
Empty resultA result with neither text nor media reads (name completed with no output) or failed; media alone carries no empty text block
Guides and AGENTS.mdRecorded on the result as details["attachment"] ({text, paths, guides}), bounded on their own, and sent as one message after each group of results: a text block in the same user message on Anthropic and Bedrock, a user message elsewhere. The AGENTS.md files already attached are read from the request's own messages, so a branch, a compaction or a restarted Worker each see their own set
Read sizeread pages within the cap itself: a range too long for one result is a contiguous page ending on a whole line (a whole page for a PDF), with the offset to continue from. Attachments no longer share that room
MediaAn image, audio or video block a turn sent is kept by content at <conversation>/media/<sha256>.<ext>; the node records metadata.media = [{sha, mime, index, path}] and rendering puts each block back at its index. A person's pasted image is kept the same way
Image budgetThe last step of building a request (media_budget.bound_images): once the images pass 25 MiB the oldest become a short note until 15 MiB remain, so the cut moves once per 10 MiB, not every request. A person's image sent to a model without image input becomes a note
A person's messageNever cut: sent whole in its turn and every later one. Over 1,048,576 characters the send is refused with input_too_large and the text stays in the input box; --print exits 2
The cardShows the head of the tool's own output (details["preview"], 4,000 characters), not the note written for the model, with "N lines · full output saved"; opening it reads the saved file (details["output"])
Why this design
TopicReason
No agingTurning old results into stubs rewrote the cached prefix each time its boundary moved, and the batching that softened it still cost a full uncached read every few turns. Codex, Claude Code, Pi and OpenCode 1.19 keep results until compaction; old output is a compaction question, not a rendering one
One cut, by weightTwo caps (the tool's characters, then the loop's) cut some results twice and gave a Chinese result four times the tokens of an English one. Codex bounds once by tokens at the point a result is recorded; weight is that count without a tokenizer, so the same cap holds on every model
Attachment beside the resultJoining guides and AGENTS.md to the result made read predict their length and let a long AGENTS.md cut a page. Claude Code sends them as their own message after the results. They are stored on the result rather than as a new node, so they live in the branch's history with no new node type and every adapter places them the same way
Media in historyWithout it a later request dropped the screenshots the turn sent, which changed the bytes and lost what the model saw. Codex and Claude Code keep images in history; the budget follows OpenCode's boundImages hysteresis so the cache survives between cuts
Long messagesCutting a person's paste at render sent different text from the turn's and hid part of it. Codex, Claude Code, OpenCode and Pi send input whole; Codex refuses past 1 MiB characters, and so does this
Shared folder collectionA result's text names its file, and that name is sent on every later request, so a file is a record, not a cache. Hermes collects persisted results by reference and fails closed; a day's grace covers a run that wrote a file but not yet its node
The cardA person reads what the tool did, the model reads the bounded copy; mixing them showed people a line telling the model to read a file. Claude Code and Pi show the tool's own output and strip the note.
Empty resultSome providers refuse an empty tool result and some models read it as no reply; Claude Code, Pi and OpenCode fill in a line, and we use Claude Code's wording.

Pictures and long messages

Every way a picture enters a conversation writes the same record, so the next request carries the picture the turn carried, on every adapter. Code: state/store/session/files/media.py, runtime/conversation/turn_admission/branch_fork.py, models/providers/shared/google.py.

PathWhat is kept
Sent messageThe web, the desktop App and the TUI send pictures with chat; channels, ACP and --print go through the turn's preparation. Both record each image at the index the turn gave it: after the text, or from 0 when the message is pictures alone. A message of pictures alone renders with no text block
Retry and editA retry copies the message's media to the new branch and sends the same pictures again, read from the kept files. An edit sends and keeps only the attachments the edit carries
SteerA message sent while a turn runs is delivered as its text, then its pictures; the node records them at those indexes
AdaptersEvery built-in wire format carries a kept picture, a person's or a tool's: Anthropic, OpenAI chat and Responses, Codex, Azure, Bedrock, Gemini and the Gemini subscription. The Gemini API adapter builds its contents through the shared Gemini conversion, so it also gets the image budget, the instructions after tool results and a tool result's pictures
Earlier picturesOnly the latest message that carries pictures attaches them. An earlier one sends its text and a note naming each file's path, which image_analyze can open again (media.as_references). Follows Hermes, which keeps only the latest; each picture otherwise rides on every request
Older conversationsA message stored before pictures were kept has no media and is sent as its text, as it was. Its text names the saved upload's path, which the model can read again
Long pasteStored and sent whole on every request; only the 1,048,576-character limit refuses a send
Why this design
TopicReason
By content, beside the historyCodex (ImageReference::Inline), Pi's session file and OpenCode's file parts keep the base64 inline in history. Here a node is a history line that the search index also reads, so inline bytes would bloat both; the files are named by sha256 the way Claude Code's paste store names pasted text, so one screenshot sent on several branches or retried is one file
When pictures are droppedCompaction leaves them out of what it summarizes, as Claude Code does; past 25 MiB the oldest become a note (OpenCode's hysteresis); a model without image input gets a note (Codex). Nothing else removes them, so the prefix stays fixed between those points
A retry resends its picturesA retry's new branch is the same message again. Without its pictures the retried turn answered a different question, and its later requests would carry pictures its first request did not
No backfillThe upload saved for an older message is the original file, not the copy the model was sent, which may have been scaled down; sending it would send something the turn never did. Those conversations already re-sent text only, so leaving them changes no bytes

Attach and merge

One mechanism: an attach pointer, a node with function="attach" hanging off a user turn as a side child. It renders as text between [Attached from "label"] and [End of attached content].

UseBehaviour
AttachPassive: staged, read on the next model call
Sub-agent reportPointer holding the task, final reply and the read_conversation(session_id, head_id) address of the transcript. A synchronous spawn returns the reply in its agent tool result.
Mergeprocess_merge_turn() writes one pointer per peer after the target head, plus an instruction, and runs a normal turn. A base peer stays verbatim; others may be summarized. Merged heads are marked and a multi-parent context commit records the lineage.

Invariants

SubjectInvariant
DAGAppend-only; compaction never changes node content
RenderingWrites nothing; spill happens on write. Reads only the stored nodes: a tool result the loop bounded, a person's message and a reply render whole; another node is cut at the cap its spill stamp recorded (32,000 for one without), never at the running cap or an environment variable; a tool result renders with its stored failure mark and media
Finished turnOn the same model, the next turn's first request starts with the previous turn's last request, reasoning items and text ids included, except for the searches the provider ran, which the turn does not store. A tool result is sent again as stored, with its failure mark, attachment and media; only a node stamped by an earlier version keeps its stamped cut. A reply without response marks re-renders in a different order.
Historical callRe-renders byte for byte from its stored nodes; no policy that moves with time takes part
SummaryAt most one active per session; the next compaction absorbs it. Never moves HEAD or rewrites edges
BranchNever reads a sibling or a spawned sub-agent's internals; those arrive only through attach pointers
CheckoutDoes not re-run or roll back the workdir

UI

ViewShows
HistoryThe full DAG, one node shape per role: tool calls, retry branches, merges
Context timelineRecorded context commits, with siblings at one fork grouped; items, state badges, token counts. apps/web/components/right-sidebar/context-commit-timeline/, ws_actions/context_commits.py
Ringapps/web/components/chat/badges/context-badge.tsx: total_used / window
/context panelcontext-breakdown-panel.tsx: same fields; derives Free space

Occupancy: one record, two readers

{"window": int, "total_used": int, "basis": "measured" | "estimated",
 "estimated": int, "offset": int}   # offset: the last count less its estimate

openprogram/runtime/context/token_accounting/session_stats.py builds it; server.session_context_stats serves /context; server._broadcast_context_stats pushes the context_stats frame. Occupancy and compaction

BasisWhentotal_used
measuredA real request just completedWhat the provider billed for that prompt: input_tokens + cache_read + cache_write, by the rule of How large a request is. A count over the window, or over twice its request's estimate, is not a measurement. offset is the count less that estimate
estimatedThe graph moved sinceRecomputed from the current branch with the local tokenizer, plus the last offset on the same model. A ratio is never applied: a stored calibration is dropped when the conversation reopens, and the record worked out again
What re-estimates, and the window

server.refresh_context_stats re-estimates and broadcasts when the next request would change:

ChangeSite, under openprogram/interfaces/server/
Compaction mid-turnws_actions/chat/context_usage.py
Model switchroutes/execution/runtime.py, ws_actions/runtime.py
Branch checkout, deletews_actions/branch.py
Sibling checkoutroutes/chat_branches.py
  • A measurement belongs to its branch; another head is re-estimated.
  • Occupancy uses the last measured request, never the sum of a turn's requests. Empty terminal events keep the last measurement, as do a reply that ran provider-side tools (passes summed) and an implausible count. With none, the UI uses a local estimate. Usage in the older cumulative format is invalidated; cumulative billing totals are unchanged.
  • Window: the window of the Model the request ran on, resolved each time and never read back from a saved record; a model that does not resolve has none, and the UI then shows tokens without a limit (The window).
  • The WebSocket chat runner records each request's prompt size as it finishes, so ring and panel update between tool calls. At turn end it refreshes the branch head and persists the final measurement.
  • Session loading recovers a newer provider usage record from an older turn that never broadcast, unless a later session edit superseded it.
/context panel levels
PartDetail
System promptBase prompt, output style, agent's own prompt, environment, AGENTS.md, skills index, workflows and tool notes, plan mode, with their text
ToolsLoaded, on demand, MCP
MemoryMEMORY.md of each layer
ConversationBy kind (messages_detail.groups) and largest messages (messages_detail.top), each linking to its transcript row
  • Detail rows scale with their category, so they add up to it.
  • A chat with no session reads GET /api/context/draft?provider=&model= (session_stats.compute_draft_breakdown).
  • context/system_prompt metadata carries sections: [{name, chars}], so the text is cut back into components exactly. An older node is split by locating a fresh build's blocks; the rest shows as Other.

Where the three layers get their content

LayerContentSource
L0Base prompt, output style, agent instructions, tool listSystem-prompt assembly
L1Project blocks and historySystem-prompt assembly; DAG render, compaction
L2This call's input and sectionsThe turn

Implementation status

StatusItems
Authoritativeopenprogram/runtime/context/engine.py, nodes.py, render.py, compaction/view.py, state/store/session/files/spill.py, media.py
PartialContext commits are written at turn finalization and by merge turns; they are not on the render path, and the timeline does not show an ordinary turn's rendered view
Not yetSummarization and branch summary use a fixed prompt (compaction/prompts.py) that does not follow the agent's AGENTS.md, identity or skills. No manual pin or unpin of context items. No model in the catalog declares tool_output_weight yet, so every model uses the default. The input box shows no hint of its own for input_too_large (the refusal shows as "Not sent"), and the card's "full output saved" line waits on a look at its styling.

Composition: how each call is layered

Last updated · 2026-11-25