Skip to content
pi-c Artifact [9ad62e870e]
Login

Artifact [9ad62e870e]

Artifact 9ad62e870e4d1865d3312ff168b5dc23cf339e84c81638a3b59a0a360d4bd834:


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:

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, :184, :254, :310; how-pi-works.md Explicit state machine (turn/outer-loop) with owned message vector; no recursion needed.
H02 Tool ordering. Default execution is parallel (agent.ts:261); any tool with executionMode:"sequential" forces the whole batch sequential (agent-loop.ts:527). 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). agent-loop.ts:646; test 8935-parallel-preflight-abort.test.ts:16 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); abort is checked before hooks. terminate ends the run only if every finalized result in the batch sets it. types.ts:424-463; test 5998-blocked-tool-terminate.test.ts:16 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). 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, :168; grep.ts:45, find.ts:42; tests tools.test.ts:111, truncate-surrogates.test.ts:12 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); 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, read.ts:18, edit.ts:18; system-prompt.ts:127 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). 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, :210, agent.ts:404-412; tests agent-session-queue.test.ts:129, :210, :258 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, agent-loop.ts:623; interactive-mode.ts:2097; json.md:31 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, agent-session.ts:217). agent_end closes one low-level run; only agent_settled means no automatic work remains. json.md:31, :101, :117 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). print-mode.ts:36; json.md:13, :70; test rpc-jsonl.test.ts:5 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, :91, :183, :286; session-format.md:62 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, :1618; sessions.md:36; compaction.md:169 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, :1833; sessions.md:5; tests agent-session-branching.test.ts:90, interactive-mode-clone-command.test.ts:23 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, :268). 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; compaction.md:27, :128, :140; tests compaction.test.ts:275, :298, :336 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; agent-loop.ts:274 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). Request transcript carries the prompt and tool declarations as system messages — never via context.systemPrompt/context.tools. types.ts:18-31; session-format.md:43 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, :269; configuration.md:41 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). 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, runner.ts:308; security.md:27; test project-trust-saved-decision.test.ts:115 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, skills.ts:282; skills.md:41, :67; tests skills.test.ts:31, :77, :394 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; prompt-templates.md:27 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, :596). Factories may be async; resources/dispose lifecycle; caches keyed by cwd and generation. extensions.md:123, :186 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). beforeToolCall can block and hint terminate; afterToolCall field-wise overrides. extensions/types.ts:1426, :66-140; runner.ts:1057 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; extensions.md:2815; rpc-extension-ui.md 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, :46; terminal-image.ts:8, :71; editor.ts:297 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; auth-storage.ts:209; configuration.md:7; models.md:22 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, :2701; models.md:36 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; rpc.md:22, :58, :91; rpc-commands.md; sdk.md:26 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, :75, :191, :252; tests agent-session-mcp.test.ts:230, :288 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, :20, :224; host.ts:78; tool-search/tool.ts:222; tests agent-session-codemode.test.ts:144, tool-search.test.ts:70 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, :100; package-manager.ts:83, :1985; session-export.ts:9; tests export-html-xss.test.ts:7 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, :35; index.md:39; plan-mode/README.md; subagent/README.md 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