Artifact 9ad62e870e4d1865d3312ff168b5dc23cf339e84c81638a3b59a0a360d4bd834:
- File
docs/harness-features.md
— part of check-in
[11f47eadde]
at
2026-11-18 11:58:22
on branch trunk
— Record S0/S1 qualification groundwork before product code
Contract maps and pinned Pi reference, local C qualification fixtures, MC/DC and Fil-C remote lifecycle tooling, and the context transaction substrate probe. No product harness code yet. (user: dmestas, size: 31304) [annotate] [blame] [check-ins using]
# Pi reference: harness feature/contract matrix (first pass) Scope: `packages/{agent,tui,mcp,codemode}` and `packages/coding-agent` (plus docs) at pinned commit `cead615b48b80d1c61eecab2f0b576d16eeaf4c5`. Provider/API implementation is out of scope. **Status: first pass, deliberately not exhaustive. No reference code or tests were run; every claim below is read from source/docs only.** Where a behavior was not traced to an implementation site it is marked *(inferred)*. Links are relative to this file. **Three different parity targets — do not conflate them:** - **Behavior and format parity:** loop/queue/event semantics, session JSONL tree, compaction rules, truncation limits, tool result shapes, JSON/RPC framing, MCP exposure rules, codemode observable contract, and trust decision order. Reproducing file formats is a separate choice from capability parity; documented limitations are not automatically requirements for the C implementation. - **TS plugin compatibility** (extensions written in TypeScript against `ExtensionAPI`/`ExtensionContext`, jiti loading, virtual modules, `ctx.ui.custom()` React-less components): *not* a portable target. A C implementation can expose an equivalent hook ABI, but existing `.ts` extensions cannot run unmodified. - **JS sandbox parity** (codemode: raw JS body, top-level `await`/`return`, `tools.*`, `text/image/console`, `store/load`, `ALL_TOOLS`, `searchTools`, `describeTool`, `models`, output formatting, limits): requires a JS engine. A C port would need an embeddable engine or must declare codemode unsupported. ## Feature/contract matrix | ID | Observable behavior / contract | Source (impl, docs, tests) | C implementation implication | |---|---|---|---| | H01 | **Agent loop.** One turn = one assistant response + its tool calls/results. Loop continues while tool calls remain or steering is pending; stops on `error`/`aborted`; outer loop resumes only for follow-ups or an explicit continuation decision. Last context message must be user or toolResult before continuing. | [agent-loop.ts:137](../reference/pi/packages/agent/src/agent-loop.ts#L137), [:184](../reference/pi/packages/agent/src/agent-loop.ts#L184), [:254](../reference/pi/packages/agent/src/agent-loop.ts#L254), [:310](../reference/pi/packages/agent/src/agent-loop.ts#L310); [how-pi-works.md](../reference/pi/packages/coding-agent/docs/how-pi-works.md#L9) | Explicit state machine (turn/outer-loop) with owned message vector; no recursion needed. | | H02 | **Tool ordering.** Default execution is `parallel` ([agent.ts:261](../reference/pi/packages/agent/src/agent.ts#L261)); any tool with `executionMode:"sequential"` forces the whole batch sequential ([agent-loop.ts:527](../reference/pi/packages/agent/src/agent-loop.ts#L527)). Parallel: prepare sequentially (preflight), execute concurrently, `tool_execution_end` in completion order, but **tool-result messages emitted in assistant source order** ([types.ts:38-47](../reference/pi/packages/agent/src/types.ts#L38)). | [agent-loop.ts:646](../reference/pi/packages/agent/src/agent-loop.ts#L646); test [8935-parallel-preflight-abort.test.ts:16](../reference/pi/packages/coding-agent/test/suite/regressions/8935-parallel-preflight-abort.test.ts#L16) | Needs a preflight phase distinct from execution; ordered result emission while completion is unordered. A C harness must not serialise result emission by completion time. | | H03 | **Tool errors never reject the batch.** Unknown tool, schema validation failure, thrown error, blocked call and aborted signal all become `isError:true` tool results ([agent-loop.ts:810](../reference/pi/packages/agent/src/agent-loop.ts#L810)); abort is checked before hooks. `terminate` ends the run only if **every** finalized result in the batch sets it. | [types.ts:424-463](../reference/pi/packages/agent/src/types.ts#L424); test [5998-blocked-tool-terminate.test.ts:16](../reference/pi/packages/coding-agent/test/suite/regressions/5998-blocked-tool-terminate.test.ts#L16) | Error-to-result conversion belongs in the loop, not per tool; aggregate terminate semantics must be explicit. | | H04 | **Truncation.** Two independent limits, first hit wins: 2000 lines, 50 KiB ([truncate.ts:11-12](../reference/pi/packages/coding-agent/src/core/tools/truncate.ts#L11)). `head` never returns partial lines (first-line-over-limit → zero lines, `truncatedBy:"bytes"`); `tail` may keep a partial first line. Never splits UTF-16 surrogate pairs. Tool budgets: grep 100 matches, find 1000 results. | [truncate.ts:78](../reference/pi/packages/coding-agent/src/core/tools/truncate.ts#L78), [:168](../reference/pi/packages/coding-agent/src/core/tools/truncate.ts#L168); [grep.ts:45](../reference/pi/packages/coding-agent/src/core/tools/grep.ts#L45), [find.ts:42](../reference/pi/packages/coding-agent/src/core/tools/find.ts#L42); tests [tools.test.ts:111](../reference/pi/packages/coding-agent/test/tools.test.ts#L111), [truncate-surrogates.test.ts:12](../reference/pi/packages/coding-agent/test/truncate-surrogates.test.ts#L12) | Byte limits are UTF-8 bytes; port must count bytes, not runes; truncation metadata is part of the result details. | | H05 | **Built-in tool set + prompt coupling.** `read, bash, powershell, edit, write, grep, find, ls` ([tools/index.ts:96](../reference/pi/packages/coding-agent/src/core/tools/index.ts#L96)); each contributes a `snippet` and `guidelines` that are injected into the system prompt, so the tool list and prompt rules are one contract. Edit is exact-unique multi-block replacement against the *original* file, BOM stripped. | [tools/index.ts:118](../reference/pi/packages/coding-agent/src/core/tools/index.ts#L118), [read.ts:18](../reference/pi/packages/coding-agent/src/core/tools/read.ts#L18), [edit.ts:18](../reference/pi/packages/coding-agent/src/core/tools/edit.ts#L18); [system-prompt.ts:127](../reference/pi/packages/coding-agent/src/core/system-prompt.ts#L127) | Tool registry must carry prompt text, not just schemas. | | H06 | **Steering vs follow-up.** Two queues with independent modes `all` / `one-at-a-time` (default one-at-a-time) ([agent.ts:255-256](../reference/pi/packages/agent/src/agent.ts#L255)). Steering drains after the current assistant turn/tools, before the next request; follow-up drains only when the agent would otherwise stop. One-at-a-time must not double-deliver after a long prepare step. | [agent-loop.ts:184](../reference/pi/packages/agent/src/agent-loop.ts#L184), [:210](../reference/pi/packages/agent/src/agent-loop.ts#L210), [agent.ts:404-412](../reference/pi/packages/agent/src/agent.ts#L404); tests [agent-session-queue.test.ts:129](../reference/pi/packages/coding-agent/test/suite/agent-session-queue.test.ts#L129), [:210](../reference/pi/packages/coding-agent/test/suite/agent-session-queue.test.ts#L210), [:258](../reference/pi/packages/coding-agent/test/suite/agent-session-queue.test.ts#L258) | Two FIFOs + drain points; the "poll after prepare only if empty" rule is a subtle parity trap. | | H07 | **Abort.** `abort()` aborts the active run's signal; in-flight tools get `"Operation aborted"` error results; assistant message gets `stopReason:"aborted"`; queued messages are restored to the editor in interactive mode, and `agent_settled{aborted:true}` is emitted. | [agent.ts:350](../reference/pi/packages/agent/src/agent.ts#L350), [agent-loop.ts:623](../reference/pi/packages/agent/src/agent-loop.ts#L623); [interactive-mode.ts:2097](../reference/pi/packages/coding-agent/src/modes/interactive/interactive-mode.ts#L2097); [json.md:31](../reference/pi/packages/coding-agent/docs/json.md#L31) | Abort must be cooperative and observable at defined checkpoints (before prepare, before execute, per update). | | H08 | **Event stream.** Canonical event set: `agent_start/end`, `turn_start/end`, `message_start/update/end`, `tool_execution_start/update/end`, plus session-level `agent_settled{aborted}`, `queue_update`, `entry_appended`, `session_info_changed`, `thinking_level_changed`, `compaction_start/end`, retry events ([types.ts:528](../reference/pi/packages/agent/src/types.ts#L528), [agent-session.ts:217](../reference/pi/packages/coding-agent/src/core/agent-session.ts#L217)). `agent_end` closes one low-level run; **only `agent_settled` means no automatic work remains**. | [json.md:31](../reference/pi/packages/coding-agent/docs/json.md#L31), [:101](../reference/pi/packages/coding-agent/docs/json.md#L101), [:117](../reference/pi/packages/coding-agent/docs/json.md#L117) | Two-level lifecycle is required; collapsing to one "done" event breaks clients. | | H09 | **Print/JSON modes + JSONL framing.** `--print` writes final text; `--mode json` writes a session header then the same session events and exits. Records are strict JSONL split **on LF only** (U+2028/U+2029 are legal inside strings; Node `readline` is unsuitable); CRLF tolerated. `message_update` is delta-only: cumulative `partial` is stripped, `toolcall_start` carries `id`/`toolName` ([json-event.ts:41](../reference/pi/packages/coding-agent/src/modes/json-event.ts#L41)). | [print-mode.ts:36](../reference/pi/packages/coding-agent/src/modes/print-mode.ts#L36); [json.md:13](../reference/pi/packages/coding-agent/docs/json.md#L13), [:70](../reference/pi/packages/coding-agent/docs/json.md#L70); test [rpc-jsonl.test.ts:5](../reference/pi/packages/coding-agent/test/rpc-jsonl.test.ts#L5) | A C writer must not use a generic getline that splits on Unicode separators if reading; must stream header first and preserve delta-only shape. | | H10 | **Session file.** JSONL, `~/.pi/agent/sessions/--<encoded-cwd>--/<ts>_<id>.jsonl`; header `{type:"session",version:3,id,timestamp,cwd,parentSession?}`; every entry has `id`/`parentId`/ISO timestamp. Entry types: message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, label, session_info, custom_message, context_edit. v1 linear and v2 tree are migrated on load. System messages persist prompt sections and tool loadout patches. | [session-manager.ts:43](../reference/pi/packages/coding-agent/src/core/session-manager.ts#L43), [:91](../reference/pi/packages/coding-agent/src/core/session-manager.ts#L91), [:183](../reference/pi/packages/coding-agent/src/core/session-manager.ts#L183), [:286](../reference/pi/packages/coding-agent/src/core/session-manager.ts#L286); [session-format.md:62](../reference/pi/packages/coding-agent/docs/session-format.md#L62) | Append-only writer with fsync/close discipline; parentId chaining is the only ordering. Timestamps are two different kinds (entry ISO, message ms). | | H11 | **Tree navigation / branching.** `branch(id)` moves the leaf without deleting; next append becomes a child of it. `branchWithSummary` adds a `branch_summary` entry carrying the abandoned path. `/tree` navigates in-file; leaving a branch can summarize it. | [session-manager.ts:1597](../reference/pi/packages/coding-agent/src/core/session-manager.ts#L1597), [:1618](../reference/pi/packages/coding-agent/src/core/session-manager.ts#L1618); [sessions.md:36](../reference/pi/packages/coding-agent/docs/sessions.md#L36); [compaction.md:169](../reference/pi/packages/coding-agent/docs/compaction.md#L169) | Tree is data, not control flow; branching must never rewrite existing entries. | | H12 | **Fork/clone vs filesystem state.** `/tree` stays in one file; `/fork` creates a new session from an earlier user message; `/clone` copies the active branch into a new file. `createBranchedSession` copies root→leaf only, re-parents labels/compaction `firstKeptEntryId`, writes `parentSession`. `SessionManager.forkFrom` rewrites header with new ID and target cwd. **A session records its cwd once and never changes it**; tools/@paths/config resolve from it, and a missing cwd prompts continue/fork/cancel. | [session-manager.ts:1650](../reference/pi/packages/coding-agent/src/core/session-manager.ts#L1650), [:1833](../reference/pi/packages/coding-agent/src/core/session-manager.ts#L1833); [sessions.md:5](../reference/pi/packages/coding-agent/docs/sessions.md#L5); tests [agent-session-branching.test.ts:90](../reference/pi/packages/coding-agent/test/agent-session-branching.test.ts#L90), [interactive-mode-clone-command.test.ts:23](../reference/pi/packages/coding-agent/test/interactive-mode-clone-command.test.ts#L23) | Conversation fork/clone does not snapshot or roll back workspace files or running processes. Preserve session configuration explicitly rather than re-deriving it on switch. | | H13 | **Compaction.** Triggers when `contextTokens > contextWindow - reserveTokens` (defaults 16384 / keep 20000) ([compaction.ts:126-129](../reference/pi/packages/coding-agent/src/core/compaction/compaction.ts#L126), [:268](../reference/pi/packages/coding-agent/src/core/compaction/compaction.ts#L268)). Cut walks back to `keepRecentTokens`; valid cut points are user/assistant/bash/custom messages, **never tool results**; split user-span cuts at an assistant message with a turn prefix. Appends `CompactionEntry{summary,firstKeptEntryId,tokensBefore}`; raw entries remain. Original `firstKeptEntryId` boundary carries into the next compaction. | [compaction.ts:431](../reference/pi/packages/coding-agent/src/core/compaction/compaction.ts#L431); [compaction.md:27](../reference/pi/packages/coding-agent/docs/compaction.md#L27), [:128](../reference/pi/packages/coding-agent/docs/compaction.md#L128), [:140](../reference/pi/packages/coding-agent/docs/compaction.md#L140); tests [compaction.test.ts:275](../reference/pi/packages/coding-agent/test/compaction.test.ts#L275), [:298](../reference/pi/packages/coding-agent/test/compaction.test.ts#L298), [:336](../reference/pi/packages/coding-agent/test/compaction.test.ts#L336) | Token estimation must be deterministic; compaction is an append, never a rewrite; tool-result/cut-point invariant is the main parity risk. | | H14 | **Overflow / length recovery.** Provider overflow or an early `stopReason:"length"` selects one compact-and-retry attempt. Ordering is fixed: persist response → extension `turn_end` → `agent_end` → append context-edit omissions → `session_before_compact`/compaction → fresh retry run. Length-with-tool-calls synthesizes failed tool results and follows normal scheduling. | [compaction.md:85](../reference/pi/packages/coding-agent/docs/compaction.md#L85); [agent-loop.ts:274](../reference/pi/packages/agent/src/agent-loop.ts#L274) | Recovery is a state transition, not an exception path; event order is part of the contract. | | H15 | **System prompt assembly.** Ordered, independently replaceable sections (`preamble`, tools, rules, docs, project_context, skills, cwd, custom) built from base text + tool snippets/guidelines + context files + skill descriptions ([system-prompt.ts:127](../reference/pi/packages/coding-agent/src/core/system-prompt.ts#L127)). Request transcript carries the prompt and tool declarations as system messages — never via `context.systemPrompt`/`context.tools`. | [types.ts:18-31](../reference/pi/packages/agent/src/types.ts#L18); [session-format.md:43](../reference/pi/packages/coding-agent/docs/session-format.md#L43) | Prompt is addressable state (sections), patchable across requests; needed for resume parity. | | H16 | **Instruction files.** Candidates per directory: `AGENTS.override.md`, `AGENTS.md`, `AGENTS.MD`, `CLAUDE.md`, `CLAUDE.MD`; `override` replaces siblings in the same directory only. Loaded from agent dir, cwd and ancestors (outermost first); deduped by canonical path; discovery does **not** require trust. | [resource-loader.ts:215](../reference/pi/packages/coding-agent/src/core/resource-loader.ts#L215), [:269](../reference/pi/packages/coding-agent/src/core/resource-loader.ts#L269); [configuration.md:41](../reference/pi/packages/coding-agent/docs/configuration.md#L41) | Ordered, path-keyed load; must not be gated on trust (differs from extensions). | | H17 | **Resource discovery + trust gating.** User dir `~/.pi/agent` (or `PI_CODING_AGENT_DIR`), project `.pi`. Trust required when any of `.pi/settings.json`, `.pi/mcp.json`, `.pi/{extensions,skills,prompts,themes}`, `.pi/SYSTEM.md`, `.pi/APPEND_SYSTEM.md`, or `.agents/skills` exists ([trust-manager.ts:193](../reference/pi/packages/coding-agent/src/core/trust-manager.ts#L193)). Order: CLI override → extension `project_trust` (first yes/no wins) → saved `trust.json` (nearest ancestor) → `defaultProjectTrust` (ask/always/never) → prompt; no UI ⇒ false. `sessionDir` is read **before** trust. | [project-trust.ts:47](../reference/pi/packages/coding-agent/src/core/project-trust.ts#L47), [runner.ts:308](../reference/pi/packages/coding-agent/src/core/extensions/runner.ts#L308); [security.md:27](../reference/pi/packages/coding-agent/docs/security.md#L27); test [project-trust-saved-decision.test.ts:115](../reference/pi/packages/coding-agent/test/project-trust-saved-decision.test.ts#L115) | Record decision order and the documented pre-trust sessionDir lookup. Whether to preserve or tighten that boundary is an explicit security/compatibility decision; do not reproduce a limitation merely for parity. | | H18 | **Skills.** Agent Skills spec: directory with `SKILL.md` + frontmatter (`name` ≤64 `[a-z0-9-]`, no leading/trailing/consecutive `-`; `description` required ≤1024; optional license/compatibility/metadata/allowed-tools/disable-model-invocation). At startup only name+description+path enter the prompt; body loads on demand. Missing description ⇒ skip; invalid fields ⇒ warn; collision ⇒ first wins. Locations include `~/.agents/skills` and ancestor `.agents/skills` (stop at repo root), plus configured/package paths. | [skills.ts:10-13](../reference/pi/packages/coding-agent/src/core/skills.ts#L10), [skills.ts:282](../reference/pi/packages/coding-agent/src/core/skills.ts#L282); [skills.md:41](../reference/pi/packages/coding-agent/docs/skills.md#L41), [:67](../reference/pi/packages/coding-agent/docs/skills.md#L67); tests [skills.test.ts:31](../reference/pi/packages/coding-agent/test/skills.test.ts#L31), [:77](../reference/pi/packages/coding-agent/test/skills.test.ts#L77), [:394](../reference/pi/packages/coding-agent/test/skills.test.ts#L394) | Validation is a spec surface; warnings vs skips differ and are observable. | | H19 | **Prompt templates.** Markdown file → `/name` command; `$1..$N`, `$@`/`$ARGUMENTS`, `${1:-def}`, `${@:-def}`, `${@:N}`, `${@:N:L}`; shell-like quoting with the stated partial-quote and backslash rules. Expansion happens before text enters the agent; extensions see raw input first via `input`. | [prompt-templates.ts](../reference/pi/packages/coding-agent/src/core/prompt-templates.ts#L1); [prompt-templates.md:27](../reference/pi/packages/coding-agent/docs/prompt-templates.md#L27) | Substitution grammar is a compatibility boundary; parse rules must match exactly. | | H20 | **Extension loading.** TypeScript/JS modules loaded via **jiti** with virtual modules for `@earendil-works/pi-*` and `typebox` in compiled builds, dist aliases in unbundled Node ([loader.ts:53](../reference/pi/packages/coding-agent/src/core/extensions/loader.ts#L53), [:596](../reference/pi/packages/coding-agent/src/core/extensions/loader.ts#L596)). Factories may be async; resources/dispose lifecycle; caches keyed by cwd and generation. | [extensions.md:123](../reference/pi/packages/coding-agent/docs/extensions.md#L123), [:186](../reference/pi/packages/coding-agent/docs/extensions.md#L186) | **Boundary:** arbitrary TS execution is not portable; a C port needs a native plugin ABI or subprocess extensions. Behavior parity ≠ plugin compatibility. | | H21 | **Extension events / hooks.** ~40 events incl. `project_trust`, `resources_discover`, `session_before_{switch,fork,compact,tree}`/`session_*`, `context`, `context_with_system`, `before_provider_request/headers`, `after_provider_response`, `before_agent_start`, `turn_*`, `message_*`, `tool_call`, `tool_result`, `input`, `user_bash`, `agent_before_settle`, `agent_settled`. Composition: notification / in-place mutation / chained transform / gate / last-override ([extensions.md:412](../reference/pi/packages/coding-agent/docs/extensions.md#L412)). `beforeToolCall` can block and hint terminate; `afterToolCall` field-wise overrides. | [extensions/types.ts:1426](../reference/pi/packages/coding-agent/src/core/extensions/types.ts#L1426), [:66-140](../reference/pi/packages/agent/src/types.ts#L66); [runner.ts:1057](../reference/pi/packages/coding-agent/src/core/extensions/runner.ts#L1057) | Hook ordering and merge semantics (replace, never deep-merge) are the real contract to reproduce. | | H22 | **Extension UI + renderers.** `ctx.ui.{select,confirm,input,editor,notify,setStatus,setWidget,custom,setHeader/setFooter/setEditor}`, autocomplete providers, message/entry renderers, tool renderers, `registerMarkdownTransformer`. RPC mode forwards these as `extension_ui_request`/`response` records. | [extensions/types.ts:164](../reference/pi/packages/coding-agent/src/core/extensions/types.ts#L164); [extensions.md:2815](../reference/pi/packages/coding-agent/docs/extensions.md#L2815); [rpc-extension-ui.md](../reference/pi/packages/coding-agent/docs/rpc-extension-ui.md#L1) | Component-system parity is effectively TS/TUI-framework parity; treat as out of scope for a minimal C core. | | H23 | **Terminal UI / images / editor.** Cells rendered as line arrays fitted to width; ANSI/wide-char width helpers; invalidate + coalesced render; focus/CURSOR_MARKER for IME; fullscreen vs regular mouse handling. Images support `kitty` and `iterm2` protocols only, detected from env; tmux disables images; explicit override. Editor: bracketed paste with `[paste #N …]` markers, kill ring, undo stack, grapheme-aware word motion. | [tui.md:20](../reference/pi/packages/coding-agent/docs/tui.md#L20), [:46](../reference/pi/packages/coding-agent/docs/tui.md#L46); [terminal-image.ts:8](../reference/pi/packages/tui/src/terminal-image.ts#L8), [:71](../reference/pi/packages/tui/src/terminal-image.ts#L71); [editor.ts:297](../reference/pi/packages/tui/src/components/editor.ts#L297) | Image protocol detection is a small portable surface; the editor/rendering stack is large and best scoped separately. | | H24 | **Config + auth discovery.** Layering: defaults → user settings → project settings (post-trust) → CLI. Agent dir files: settings, keybindings, mcp, models, auth, instructions, SYSTEM/APPEND_SYSTEM, extensions/skills/prompts/themes. Credential precedence: `--api-key` → `auth.json` → `models.json` apiKey → provider env/ambient. `auth.json` supports api_key and OAuth `{access,refresh,expires}`; `auth check|print-api-key|print-bearer-token` exit 0/1/2. | [settings-defaults.ts:4](../reference/pi/packages/coding-agent/src/core/settings-defaults.ts#L4); [auth-storage.ts:209](../reference/pi/packages/coding-agent/src/core/auth-storage.ts#L209); [configuration.md:7](../reference/pi/packages/coding-agent/docs/configuration.md#L7); [models.md:22](../reference/pi/packages/coding-agent/docs/models.md#L22) | Precedence lists are testable C logic; token refresh timing (min validity, default 5 min) is observable. | | H25 | **Model switching / thinking.** `setModel` records a `model_change` entry; `cycleModel` uses scoped models when set, else all available; thinking level is set/clamped per model and recorded; resuming restores both without touching defaults. | [agent-session.ts:2659](../reference/pi/packages/coding-agent/src/core/agent-session.ts#L2659), [:2701](../reference/pi/packages/coding-agent/src/core/agent-session.ts#L2701); [models.md:36](../reference/pi/packages/coding-agent/docs/models.md#L36) | Changes are transcript entries, not ephemeral config; clamping rules belong to the model catalog. | | H26 | **Print JSON / RPC / SDK.** RPC = long-lived JSONL: commands in, `response{id,command,success,data|error}` out, session events, extension-UI records; async handling ⇒ correlate by `id`; `prompt` success reports `disposition` and does **not** mean completion; shutdown on stdin EOF/SIGTERM, second signal forces exit. ~34 commands (prompt/steer/follow_up/abort/clear_queue/new_session/get_state/set_model/cycle_model/…/fork/clone/get_tree/export_html). SDK = in-process `createAgentSession` + `AgentSessionRuntime` replacement ops. | [rpc-types.ts:20](../reference/pi/packages/coding-agent/src/modes/rpc/rpc-types.ts#L20); [rpc.md:22](../reference/pi/packages/coding-agent/docs/rpc.md#L22), [:58](../reference/pi/packages/coding-agent/docs/rpc.md#L58), [:91](../reference/pi/packages/coding-agent/docs/rpc.md#L91); [rpc-commands.md](../reference/pi/packages/coding-agent/docs/rpc-commands.md#L1); [sdk.md:26](../reference/pi/packages/coding-agent/docs/sdk.md#L26) | RPC is the most C-friendly integration target: no JS needed, strict framing, ID correlation, defined shutdown. | | H27 | **MCP.** stdio + streamable HTTP (SSE rejected); config `~/.pi/agent/mcp.json` + `.pi/mcp.json` (project entry replaces same-name user entry; structural-less entry overrides only enabled/exposure). Tools named `mcp__<server>__<tool>` with sanitization/collision hash. Exposure: `codemode` (default), `deferred`, `direct`, `hidden`; `direct` tools are awaited 10 s at first prompt. OAuth: CIMD or DCR, loopback callback, tokens in `mcp-auth.json`, refresh; resources tools. All calls pass the tool pipeline (installed extension block hooks apply; there is no built-in permission engine). | [mcp.md:30](../reference/pi/packages/coding-agent/docs/mcp.md#L30), [:75](../reference/pi/packages/coding-agent/docs/mcp.md#L75), [:191](../reference/pi/packages/coding-agent/docs/mcp.md#L191), [:252](../reference/pi/packages/coding-agent/docs/mcp.md#L252); tests [agent-session-mcp.test.ts:230](../reference/pi/packages/coding-agent/test/suite/agent-session-mcp.test.ts#L230), [:288](../reference/pi/packages/coding-agent/test/suite/agent-session-mcp.test.ts#L288) | JSON-RPC 2.0 + two transports is portable; OAuth metadata discovery and naming/collision rules are the sharp edges. | | H28 | **Codemode / tool search.** `codemode` input is raw JS run as an async-function body in QuickJS (worker thread; per-run VM; no Node/fs/net/timers). Globals `tools.*`, `text/image/console/return/exit`, `store/load`, `ALL_TOOLS`, `searchTools` (BM25, limit 8), `describeTool`, `describeNamespace`, `models`. Limits: 10000 default output tokens, 16777216 output characters (including base64 image data)/100k output calls, store 256 KiB/value & 1 MiB total; store persists only on success via a session custom entry. `tool_search` BM25-loads `deferred` tools for the next call. | [codemode.md:5](../reference/pi/packages/coding-agent/docs/codemode.md#L5), [:20](../reference/pi/packages/coding-agent/docs/codemode.md#L20), [:224](../reference/pi/packages/coding-agent/docs/codemode.md#L224); [host.ts:78](../reference/pi/packages/codemode/src/runtime/host.ts#L78); [tool-search/tool.ts:222](../reference/pi/packages/coding-agent/src/extensions/tool-search/tool.ts#L222); tests [agent-session-codemode.test.ts:144](../reference/pi/packages/coding-agent/test/suite/agent-session-codemode.test.ts#L144), [tool-search.test.ts:70](../reference/pi/packages/coding-agent/test/tool-search.test.ts#L70) | **Explicit JS-sandbox boundary.** The BM25 tool search is portable; the script VM is not, absent an embedded engine. | | H29 | **Packages / update / export / share security.** `npm:`/`git:`/URL/local sources; pinned specs not auto-updated; `PI_OFFLINE` skips network; git cannot prompt; package deps in `dependencies`, host packages as `peerDependencies`. HTML export escapes/scheme-allowlists links, images, IDs and metadata (XSS tests). `/share` uploads JSONL/HTML to Radius or a private gist — exports can contain prompts, tool args, output, file contents. | [packages.md:7](../reference/pi/packages/coding-agent/docs/packages.md#L7), [:100](../reference/pi/packages/coding-agent/docs/packages.md#L100); [package-manager.ts:83](../reference/pi/packages/coding-agent/src/core/package-manager.ts#L83), [:1985](../reference/pi/packages/coding-agent/src/core/package-manager.ts#L1985); [session-export.ts:9](../reference/pi/packages/coding-agent/src/core/session-export.ts#L9); tests [export-html-xss.test.ts:7](../reference/pi/packages/coding-agent/test/export-html-xss.test.ts#L7) | Export sanitization is a real security contract; share destinations and redaction are absent by design (user must review). | | H30 | **No permission engine; trust ≠ sandbox. Core vs optional features.** There is no built-in approval gate: tools/extensions run with the process's OS permissions; the only gates are user-installed extensions (`tool_call` block) and unmodified `--tools` selection. Project trust only governs *loading* project resources, and even it has the pre-trust `sessionDir` read. Plan mode and subagents are **example extensions**, not core; subagents spawn separate `pi` processes with isolated context. | [security.md:9](../reference/pi/packages/coding-agent/docs/security.md#L9), [:35](../reference/pi/packages/coding-agent/docs/security.md#L35); [index.md:39](../reference/pi/packages/coding-agent/docs/index.md#L39); [plan-mode/README.md](../reference/pi/packages/coding-agent/examples/extensions/plan-mode/README.md#L1); [subagent/README.md](../reference/pi/packages/coding-agent/examples/extensions/subagent/README.md#L1) | Report Pi's baseline accurately. An added permission policy or sandbox is a deliberate enhancement, not a prohibited change; preserve a clear distinction between loading trust, tool authorization, and OS isolation. | ## Portability / compatibility boundary (summary) | Area | Portable to C as-is | Needs design decision | Do not claim parity | |---|---|---|---| | Loop, queues, abort, event order | Yes (H01–H08, H14) | — | — | | Session JSONL tree, fork/clone, compaction | Yes (H10–H13) | token estimator parity | — | | Truncation, tool result shapes | Yes (H03–H05) | UTF-8 byte counting | — | | Prompt/instruction/skill/template discovery | Mostly (H15–H19) | template quoting grammar | spec-warning parity | | Trust decision order | Yes (H17) | reproducing the sessionDir hole or fixing it | — | | Config/auth/model catalog | Yes (H24, H25) | OAuth providers | provider APIs (out of scope) | | RPC / JSON mode | Yes (H09, H26) | — | SDK in-process API | | MCP | Yes (H27) | OAuth CIMD/DCR | SSE (rejected by pi) | | Extension ABI | Event names/order/merge semantics (H21) | native plugin ABI | `.ts` extensions via jiti, `ctx.ui.custom()` | | Codemode | BM25 tool search only (H28) | embed a JS engine or declare unsupported | QuickJS global/limit semantics | | TUI | image protocol detection | rendering model | component framework, editor | | Packages/export/share | JSONL/HTML export sanitization (H29) | npm/git install | npm/git semantics | ## Known gaps in this pass - Compaction token estimation and retry/backoff details were not traced to line level. - Extension event list is enumerated from types/docs but per-event merge semantics were only sampled. - Terminal capability detection branches (Warp/Orca/herdr/JetBrains) were read but not fully enumerated. - Package manager internals (install layout, lockfiles, peer handling) were sampled, not audited. - No behavioral claims were verified by running the reference or its test suite.