Harness adapters
Implement a harness runner over Brain's Go interface or stdio JSON protocol.
A harness adapter runs the model loop, manages conversation context and compaction, and writes native session state inside the session's native/ directory while Brain coordinates requests, tool dispatch, event logs, and checkpoints.
Go lifecycle (harness.Factory and harness.Runner)
Factory.Open(ctx, opts) receives a harness.Options struct containing the session ID, the native/ working directory (Dir), the immutable session Config, enabled Tools schemas, resolved Provider credentials (APIKey, BaseURL, API), and two callbacks: Event (for emitting assistant.delta and assistant.message) and Call (for executing bound tools).
The application package exports these contracts as brain.HarnessFactory, brain.Harness, and brain.HarnessOptions. Open returns a runner with five methods (see Go interfaces):
| Method | Purpose |
|---|---|
Prompt(ctx, text) | Runs one user turn to completion (including any model-initiated tool calls and follow-up generations) and returns when the turn settles. |
Steer(ctx, text) | Steers an active turn if Factory.SupportsSteering() is enabled. |
Interrupt(ctx) | Aborts the active turn cleanly when the caller sends user.interrupt or closes the session. |
Checkpoint(ctx) | Returns the list of core.NativeFile entries (path, size, append_only) relative to Dir required to restore the conversation. |
Close() | Terminates the runner and releases its resources. |
Core runner invariants
- Passive open: Opening an existing session directory must load saved native state without calling the model, re-running tools, or starting background cache-warming timers.
- Settled return:
Promptblocks until the turn finishes or is interrupted. - Clean checkpoints:
Checkpointis called only afterPromptsettles and must return regular, append-only relative file paths and exact byte sizes inDir, excluding any provider credentials.
Child process stdio protocol (harness.ProcessFactory)
You do not need to write Go code to add a harness runner. Every entry in the "harnesses" configuration block uses harness.ProcessFactory (internal/harness/process.go) to spawn a child process (such as node runners/pi/dist/main.js) and communicate over newline-delimited JSON frames (RunnerFrame) on stdin and stdout.
- Frame limit: Each line is capped at
4 MiB(MaxFrame = 4 << 20) with strict JSON decoding (DisallowUnknownFields). - Standard streams:
stdoutis reserved strictly forRunnerFrameJSON lines. Brain suppresses runner diagnostic payloads from logs. - Startup timeout: The initial
openrequest duringFactory.Openhas a 30-second timeout.
Brain → Runner requests (stdin)
Brain sends RPC requests with attachment, id, method, and params. An attachment identifies one native session within a shared host. prompt, steer, interrupt, events, and tool callbacks also carry the active turn identity; replies echo the request's attachment and turn. Open, checkpoint, and detach have no active turn.
{"attachment":"ATTACHMENT_ID","id":"REQUEST_ID","method":"open","params":{"session_id":"SESSION_ID","dir":"/path/to/native","config":{"model":"openai/gpt-4.1-mini","tools":["echo"]},"tools":[{"name":"echo","description":"Echo text","input_schema":{"type":"object"}}],"provider":{"api_key":"PROVIDER_TOKEN"}}}
{"attachment":"ATTACHMENT_ID","turn":"TURN_ID","id":"REQUEST_ID","method":"prompt","params":{"text":"Hello"}}
{"attachment":"ATTACHMENT_ID","id":"REQUEST_ID","method":"checkpoint","params":null}The runner replies on stdout with a matching id and either result or error (code: "provider_error" or "brain_error"):
{"attachment":"ATTACHMENT_ID","turn":"TURN_ID","id":"REQUEST_ID","result":{}}
{"attachment":"ATTACHMENT_ID","turn":"TURN_ID","id":"REQUEST_ID","error":{"code":"provider_error","message":"upstream rate limit exceeded"}}| Method | params | result |
|---|---|---|
open | harness.Options (session_id, dir, config, tools, provider) | {} (or diagnostic metadata such as {"tools": [...]}) |
prompt | {"text": "..."} (core.Text) | {} (or {"interrupted": true}) |
steer | {"text": "..."} (core.Text) | {} |
interrupt | null | {} |
checkpoint | null | [{"path": "session/file.jsonl", "size": 1024, "append_only": true}] ([]core.NativeFile) |
detach | null | {}; release this settled attachment without stopping peers. |
Runner → Brain events and tool calls (stdout)
While prompt is running, the runner can emit streaming events and reverse tool.call requests (up to 32 concurrent tool calls per runner):
{"attachment":"ATTACHMENT_ID","turn":"TURN_ID","event":"assistant.delta","data":{"text":"Hello"}}
{"attachment":"ATTACHMENT_ID","turn":"TURN_ID","id":"CALL_FRAME_ID","method":"tool.call","params":{"id":"TOOL_CALL_ID","name":"echo","arguments":{"value":"hi"}}}
{"attachment":"ATTACHMENT_ID","turn":"TURN_ID","event":"assistant.message","data":{"text":"Hello!","usage":{"input":12,"output":4},"stop_reason":"stop"}}For each tool.call, Brain validates that the tool is bound to the session, appends a tool.call event, dispatches the call to the external tool service, appends a tool.result event, and writes the correlated response frame back to the runner's stdin:
{"attachment":"ATTACHMENT_ID","turn":"TURN_ID","id":"CALL_FRAME_ID","result":{"content":[{"type":"text","text":"hi"}],"is_error":false}}Wire types for this protocol are generated in internal/harness and runners/pi/src/generated.ts via go run ./cmd/generate.
Acknowledge model observations
Send a reverse request with method: "model.request" and params containing a ModelRequest snapshot. Await its matching result before dispatching the model request and before returning a terminal result from Prompt. Model observations use this acknowledged method, not fire-and-forget event frames. A rejected observation stops the affected execution.
Go runners call Options.Event("model.request", data) synchronously and check its error before dispatch. Reuse a request/attempt identity for replacement snapshots, not for another inference call. Mark unobservable native paths and quantities explicitly; do not invent physical attempt identities.
Codex App Server adapter
Install the workspace dependencies with node scripts/setup.mjs. Start a three-harness server with go run ./cmd/brain -config examples/harnesses.json after setting BRAIN_API_KEY and OPENAI_API_KEY. Select pi, codex or opencode in the same session-creation request. Use the integration status to distinguish local and live-service evidence.
Configure harnesses.codex.command as ["node", "runners/codex/src/main.mjs"] and select a provider using the openai-responses transport. The installed package pins Codex 0.163.0. brain.Codex(command) installs its Go process-factory policy. Unsupported transports and reasoning selections fail admission.
One owned native App Server shares compatible threads. Hosts are partitioned by a private credential-context digest; the key is supplied in the child environment without mutating the Brain or runner process environment. Dynamic tools are the exact Brain catalog, environment access is disabled, and the pinned exclusion settings remove native local tools and question/approval capabilities.
The adapter selects the pinned server's complete JSONL history mode (historyMode: "legacy"). This is an upstream storage selection, not a Brain compatibility layer. Checkpoints append only the changed native rollout suffix and a small adapter-state record. Cold opens import the native checkpoint into the owned host and resume it without inference. Detachment archives the settled native thread and verifies notLoaded before releasing residency. Repeated interruption shares the same cancellation operation.
App Server exposes native-turn and cumulative token observations rather than a complete per-request pre-dispatch hook. Receipts identify boundary: "native_turn", mark generation/compaction/retry coverage as unmeasured, and retain observed positive token deltas as partial evidence. Unreported or ambiguous counters stay unknown. See the qualification matrix.
OpenCode embedded adapter
Configure harnesses.opencode.command as ["node", "runners/opencode/src/main.mjs"] with the openai-responses transport. brain.OpenCode(command) installs the process-factory policy. The runner pins the SDK, core and plugin packages to 2.0.30 and the Effect runtime family to 4.0.1. Unsupported transports, reasoning selections and the reserved execute tool name fail admission.
One owned embedded host uses separate native instance registries for each Brain session. The registry removes native tools and selects HTTP transport explicitly; permissions deny every action except selected Brain tools and always deny Code Mode. Model hooks inject each attachment's private credential into its own request. Optional title inference is suppressed. The embedding layer replaces SessionRestart with a passive startup service, so restoring native state does not continue work.
Native session exports supply metadata and messages, including compaction state. Each checkpoint scans that session's export and appends only changed message records and current metadata to session.jsonl. It never copies the shared SQLite database or peer sessions. Restoring folds those records and imports them through the native session API. This keeps checkpoint writes incremental; export reads still grow with that session's history.
Acknowledged native model hooks record logical primary, compaction and other enabled requests. HTTP hooks record physical attempts, failures and provider identifiers; raw Responses usage carries explicit cache/reasoning inclusion semantics. Streaming and non-streaming summary responses use the same evidence contract. WebSocket transport is excluded by the selected native provider settings and a rejecting handshake hook. See the qualification matrix.
Isolation and verification
A harness adapter must disable all built-in local tools (such as local shell execution or file editors), ambient plugins, and background cache warmers so the model can only invoke tools explicitly bound in config.tools. harness.ProcessFactory passes only minimal OS environment variables (PATH, SystemRoot, WINDIR, COMSPEC, PATHEXT, TMP, TEMP, TMPDIR, LANG, LC_ALL, and NO_COLOR=1) and supplies provider credentials exclusively through the open frame.
When testing a new harness adapter, verify:
- Passive open: Reopening a saved directory makes zero model or tool calls until the next
Prompt. - Checkpoint fidelity: Restoring a checkpoint into a fresh directory produces the exact same prompt context on the next turn.
- Failure separation: Tool errors (
is_error: true) return to the model as tool results, whereas broken stdio framing, unexpected exits, or disk failures abort the turn withbrain_error. - Clean interruption: Interrupting a turn while a tool call is waiting stops execution cleanly and leaves prior checkpoint files intact.