# Headless `--print` runs

1. **`openprogram --print`** on the running Worker, or in this process without one
2. **`build_turn_request`** the request every typed-input surface builds
3. **Execution tree** what the usage file and transcript count

Code: `interfaces/cli/chat.py` `_run_oneshot`; `interfaces/cli/print_mode/worker_turn.py`; `interfaces/cli/print_mode/print_turn.py`; `interfaces/cli/print_mode/print_stop.py`; `interfaces/cli/print_mode/print_events.py`; `interfaces/cli/print_mode/print_input.py`; `interfaces/cli/print_mode/print_session.py`; `runtime/conversation/turn_admission/local_commands.py`; `interfaces/server/handshake.py`; `runtime/conversation/turn_admission/turn_input.py`; `runtime/execution/projections/execution_tree.py`.

## Two transports, one request

With a Worker up for the profile, the turn goes to it as the Web UI's `chat` command and the CLI relays frames; without one it is admitted and activated in this process. `--standalone` (or `OPENPROGRAM_PRINT_IN_PROCESS=1`) forces the second.

| Part | Rule |
| --- | --- |
| Request | `turn_input.build_turn_request` builds the request for every surface that takes typed text: the Worker's chat command, a retry or edit, `--print`, ACP, chat channels and owner turns. It applies the authority, the conversation's permission, the run settings the surface takes, and the surface's own fields last. Jobs, scheduled runs, sub-agents and merges build theirs from a task definition. |
| Run note | A run no one watches carries `runtime/conversation/turn_admission/run_note.py` `RUN_NOTE`: the in-process `--print`, and a Worker chat command whose authority says `interaction="non-interactive"`. The surface asks for it (`build_turn_request(unattended=True)`); the authority alone does not, because a chat channel admits a paired sender as non-interactive while a person reads every reply. The note tells the model nobody can answer and that its first reply without a tool call ends the run. |
| Per-turn settings | The chat command's overrides are one table (`TURN_OVERRIDES` in `ws_actions/chat/turn_request.py`): effort, web search, permission mode, sandbox and speed tier stick to the branch for later turns; the desktop surface is this turn's only, and so are `turn_model`, `turn_effort` and `turn_permission_mode`, which `--print` sends for `--model`, `--effort` and `--permission-mode` and which win over the branch's and an Agent trial's saved values. A model the provider lists but no one enabled is used for that turn in that process only (`enabled_models.use_model_in_process`). |
| Values left out | A frame that leaves one out, or sends `null`, keeps the conversation's value. A typed `/task` or `/merge` is marked in `slash_action`, so `interaction` keeps the authority's value; a request stored before the field is read with `slash_action_of`. |
| Who is on each side | The Worker says who it is on connect (`worker_capabilities`, under `server`) and in every `chat_ack`: name, version, the highest history protocol it serves and its capabilities (`handshake.server_identity`). The chat command says who sent it (`client`). The CLI keeps a fallback for each capability a Worker does not name: a structured reply read from the text, a stop resent at the version a refusal names. The run's record names the transport and the Worker's version. |
| Stopping | Both transports stop by `print_stop`: the first Ctrl-C, SIGTERM, SIGHUP or SIGBREAK is raised and named; later ones are noted. The turn has 30 s to end from the stop, or 2 s from the cancel once a further signal came (`StopClock`); a stale refusal is resent at most three times. A stop exits 128 plus the signal's number (`STOP_EXIT_CODES`): 130 for SIGINT, 143 for SIGTERM and SIGBREAK, 129 for SIGHUP. |
| Frames before the ack | Until the ack names the execution, the relay takes only frames that echo its `client_request_id` (a refusal, a slash command's answer). Another branch of the same conversation can end or be stopped meanwhile without ending this run. |
| Worker restart | The relay reconnects and reads the execution's state. An interrupted turn is followed on when its latest restart intent asks for a new turn, whatever reason the interruption carries (`owner_lost` when the Worker died, `restart_new_turn` when the restart paused it first). An unsettled intent is read again within the reattach window. Settled as `new_turn_admitted`, the new turn's id derives from the intent (`execution_tree.continuation_key`); the relay follows it to its reply and records `restarted`. Any other outcome is a failure. |

## The headless interface

A script calls `openprogram -p` the way it calls the other agent CLIs, so each option follows the harness most scripts already use. Exit 0 is a finished run, 1 a failed one, 2 a usage error, 3 and 4 a structured-output request that is unsupported or failed, 128 + N a stop by signal N.

| Topic | Rule | Why |
| --- | --- | --- |
| Approvals | No one answers a `--print` run, so a call that would ask is refused at once (`policy._ask_or_nobody`, sandbox escalation in `approval.py`) with code `NON_INTERACTIVE` and a fixed note the model reads: the call did not run, continue without it. The refused calls are listed in the record (`permission_denials`), as `permission_denied` events, and as one `permission denied: TOOL (WHAT)` line each on stderr; the run still exits 0. | OpenCode's headless run does the same; a refusal the model can read lets it finish the task another way, where waiting would hang the script and failing would waste the rest of the run. Wider permission is chosen up front with `--permission-mode` (ask, acceptEdits, plan, auto, bypass) for this turn. |
| Slash commands | Typed text is taken as the Worker takes it (`local_commands`): a registered builtin answers without a model turn, `/compact [N]` compacts the conversation (the Worker's `compact` action, or `trigger_compaction` here), `/task` and `/merge` mark the turn, `/goal <objective>` runs a turn with the objective as its message (marked `starts_goal`) and prints that turn's reply, and anything else, an unknown `/name` included, goes to the model as written. The record names the command in `local_command`. | Claude Code and Pi run their local commands in print mode; one resolver on both surfaces means a command behaves the same in a script and in the App. |
| Transport | `--standalone` runs in this process even with a Worker up. | OpenCode separates attaching to a server from running alone; a benchmark or CI job wants a run that shares no state with an App the person is using. |
| Output | `--output-format text` (default) prints the reply; `json` prints one record (the outcome below, `reply`, `structured_output`); `stream-json` prints run events one per line, `init` first (transport, Worker version, model, effort, permission mode, conversation, execution, tools) and `result` last, `seq` continuous across all of them. `--include-partial-messages` adds `text_delta` and `reasoning_delta` as they arrive. | these are Claude Code's names and shapes, which harnesses already parse. |
| Conversation | `--resume ID` continues a conversation and fails (exit 1) when there is none; `--continue` takes this folder's latest, among the conversations its project's registry entry lists (`session_ids`; the session list's rows carry no project), and in the home folder those no project lists; `--session-id ID` starts one with that id and fails when it is taken. | Claude Code and Pi use these flags; a typo in an id silently starting a fresh conversation is the failure they avoid. |
| Branch point | `--at REF` names a branch, a branch's tip, or a message inside a branch (`print_session`). A turn on another recorded branch moves only that branch and leaves the selection alone. After a message inside a branch, the turn starts a new branch as an edit does, and that branch becomes the selected one; the branch it left keeps its messages. A branch already running a turn is refused with `error_kind` `branch_busy`. | Recorded branches run beside the selected one. A new branch is recorded only when the head moves onto it (`compare_and_set_head` writes `branch_refs`); a fork that left the head alone would be an unnamed tip no later `--at` or Branches panel finds. So it follows the owner's rule for edits and retries. |
| Model | `--model` and `--effort` apply to this turn only: nothing is pinned on the conversation, nothing enabled in the config. An effort the model lacks is sent as the nearest one it has, the next stronger first (`thinking_spec.normalize_reasoning_level`): `minimal` on a model that starts at `low` sends `low`. | Claude Code and Kimi treat the flag as the run's; a script must not change what the App later uses. |
| Instruction | `-p` is `--print`. `-p -`, or `-p` alone with a pipe, reads the instruction from stdin; `-p TEXT` with a pipe appends what is in it within 0.2 s as a `<stdin>` block, so an open but unused stdin never hangs the run (`print_input`). An empty instruction exits 2, `-p ""` included: only an absent `-p` opens the chat (`application._runs_print`). | `-p` is Claude Code's, Pi's and Kimi's spelling; piping a file under an instruction is how Codex and OpenCode are used. |
| Folder and keys | `--no-project-binding` writes nothing in the folder; the conversation stays in the profile. A provider's standard variable (`OPENAI_API_KEY` and so on) serves when the credential store has no key, in that process only and never written (`read_env_keys_in_this_process`). | Codex runs in a checkout it must not dirty and takes its key from the environment; a container has no stored credentials. |
| Web | `--no-web` turns web tools off for this turn: no tool whose name says web, deferred ones included, and no provider-side search; on the Worker it is the turn-only `turn_no_web`, declared as the `no_web` capability. | Harbor turns Codex's and Claude Code's web tools off with one switch; a benchmark can then ask both sides the same. |
| Turn limit | There is no `--max-turns`. | most of the harnesses compared have none; a run ends when the model answers without a tool call, and the caller's timeout and a stop bound the rest. |
| Exit codes | 0 done, 1 failed, 2 usage, 3 and 4 structured output; a stop exits 130 for SIGINT, 143 for SIGTERM and SIGBREAK, 129 for SIGHUP, and a further signal keeps the first one's code. | Follows Kimi Code, which also tells the three signals apart and keeps 130 for Ctrl-C; Codex exits 1 for every stop, so a script cannot tell a kill from a failure. |
| Failure reason | `error_reason` takes only the closed set of reasons; a narrower category goes in `error_kind`. | Follows Codex's closed error enum: a value outside the set falls into a caller's default branch. |

## Usage and transcript by execution tree

Every model request is recorded in the usage ledger with the execution bound to the context it is made in (`models/usage/context.py` `call_context`). A call on a thread of its own, like the title the Worker writes beside a finished turn, names no execution.

| Member | How it is found |
| --- | --- |
| The run | The execution admitted for it. A run that never started has none, and counts nothing. |
| Sub-agents | Children by `parent_execution_id` and the Jobs the run called, at any depth, as the conversation's own execution scope places them. |
| Restart continuation | The execution admitted under `restart:{execution}:{sequence}` for each restart intent on a member, and its own descendants. |

`--usage-file` sums the ledger rows of these executions. `--transcript-file` is the run's events (below): their requests, the instruction and reply messages their admissions name, and the tool results as the model read them. Another branch running in the same conversation at the same time is not part of either.

## Run events

```
{"schema_version": 1, "seq": 7, "execution_id": "…", "parent_execution_id": "…",
 "type": "tool_result", "data": {"tool_call_id": "…", "content": "…", "complete": true, …}}
```

`print_events.run_events` maps the stores to one versioned schema: `seq` counts from 1 with no holes, and each event names its execution and that execution's parent (`null` for the run's own). A sub-agent's reply takes only its own requests. The transcript file writes each event as `{"type": …, **data}`.

| Type | What it says |
| --- | --- |
| `run` | The conversation, model, run note and how the run ended. |
| `user`, `reply` | An instruction an execution of the run admitted, and the end of its reply. |
| `request` | A ledger request with its tokens, placed before what it returned. |
| `reasoning`, `assistant_text`, `tool_call`, `tool_result` | What a request returned. A result is stored as the model read it, so it is `complete`. |
| `credential_switch` | Another of the provider's keys took over before a reply started, before that reply's blocks: `to`, `from` and `cause` (`rate_limit`, `quota`, `auth`, `model`), stored with the reply (`credential_notices`). A text or `json` run says it on stderr as it happens: `[notice] Switched to Work: Personal hit a rate limit`. |
| `permission_denied` | A refused call, after its `tool_result`: the call id, tool, code, layer, rule and arguments. |
| `init`, `text_delta`, `reasoning_delta`, `result` | Only on the `stream-json` stream: what the run starts with, partial text when asked for, and the record it ends with. Their permission mode is the one the turn was admitted with: the request's in this process, the `chat_ack`'s on the Worker (`--permission-mode`, else the branch's own). The stream leaves out `run`, which `init` and `result` carry. |
| `gap` | What the stores do not hold, said in place: `tool_result` for a call with no stored result, `requests` when the ledger could not be read, `messages` when the run's messages could not be found. |

## How a run ended

```
{"ended": "failed", "error": "…", "phase": "in_turn",
 "error_reason": "transport", "error_retryable": true, "error_kind": null,
 "restarted": false, "stopped_by": null, "transport": "worker",
 "worker_version": "…", …}
```

| Field | Meaning |
| --- | --- |
| `phase` | `in_turn` once an execution was admitted, `not_started` before: a model that could not be enabled, a Worker refusal before the ack. |
| `error_reason`, `error_retryable` | The runtime's classification of a failed turn, from the turn result in-process or the error frame on the Worker. |
| `error_kind` | A stable category of what failed, beside the broader reason: a stalled stream and a reset connection are both `transport`, only the first is `stream_idle`. The runtime names it with `errors.error_kind` (`stream_idle`, `stream_total`, `memory_unavailable`, `auth`), found on the exception or anything it wraps, and puts it in the turn result and the error frame (`kind`); the CLI passes it on and sets `model_unavailable` and `branch_busy` itself. Required memory that failed is reason `unknown`, not retryable, kind `memory_unavailable`. |
| Refused input | Input that admission refuses (`AgentDriverError`: `input_too_large`, `image_too_large`, `invalid_input`) ends the send with an error frame whose `code` and `kind` are that code, never a bare `handler_error`. The person's message is measured against the one-message limit (1,048,576 characters, `agent_input_budget.AGENT_USER_TEXT_MAX_CHARS`), apart from the 256 KiB envelope budget, so a prompt `print_input` accepts is admitted. |
| `stopped_by` | The signal that first asked the command to stop: `SIGINT`, `SIGTERM`, `SIGHUP` or `SIGBREAK`. |
| `permission_denials`, `local_command` | The calls refused because no one could approve them (tool, call id, code, rule), and the local command that answered instead of a model turn. |
| `transport`, `worker_version` | `worker` or `in_process`, and the version the Worker gave (`null` in-process or from a Worker that gives none). |
| `effort_requested`, `effort`, `tools_count` | What `--effort` asked for (this turn only, never saved; without it the Agent's own applies), and what the turn's first request sent: its effort and number of tools. An in-process run reads them where the provider adapter builds the body (`capture.observing`); on the Worker the chat command watches its execution's requests (`wire_facts.watch`) and the result frame carries them back (`wire_facts`), so both transports fill them. The Worker takes `minimal` to `max`; `off` runs in-process only. |

The run record at the head of the transcript carries the same fields, the version, the permission mode, hashes of the run note and system text, and the first request's model, `include`, `store` and tools by name.

It also names `no_web`, the tool-output weight, and the commit and build time a launcher build carries in `openprogram/_build_info.py` (`null` in a source checkout; `--version` shows the commit too).

Each `request` record this process saw sent adds its effort, `include`, `store` and tool-list hash.

`openprogram transcript [--state DIR] [--session ID] [--output FILE]` writes a killed run's transcript from the state it left (the only conversation there, or the one named), less the request bodies only the process saw.

*Why:* Codex's and Claude Code's Harbor adapters derive the trajectory from the session their CLI wrote record by record; one code path gives a killed run the transcript a finished one writes.

## Implementation status

| Item | State |
| --- | --- |
| The Harbor adapter dropping its error-text patterns; it types a failure by `error_kind`, then `error_reason`, and reads the text only when neither settles it, until one Harbor trial shows both readings agree | Waits for a trial |
| The `stream-json` stream relaying history protocol 3 live (transcript updates and their gap recovery); it writes `init` and partial deltas live and the stored events at the end | Not built |
| Dropping the CLI's fallbacks (the reply-text parse, the stale-version resend) once both instances announce the capabilities | Waits for a release that carries them |
| A Worker turn recorded with `source` `cli`; it stays a foreground source until the Web UI shows and stops such turns the same way | Not built |
| `--at` to a message inside a branch on the Worker; it runs in this process with a note | Not built |
| `branch_busy` for an in-process run that meets a turn another process runs on the branch | Not built |
| `error_kind` `auth` for a provider with no credential; it reports `model_unavailable` | Not built |
