@agentproto/adapter-pi 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/MCP-BRIDGE.md ADDED
@@ -0,0 +1,132 @@
1
+ # MCP → pi-tools bridge
2
+
3
+ Pi ships **no MCP client**. This adapter still lets the host inject
4
+ `mcpServers` into a pi session — including the daemon's `agent_start`
5
+ orchestration gateway — by bridging every MCP tool into a native **pi tool**
6
+ through pi's own TypeScript **extension** system. Pi never speaks MCP; the
7
+ bridge extension does, on pi's behalf.
8
+
9
+ ## How it works
10
+
11
+ ```
12
+ host connect({ mcpServers })
13
+
14
+
15
+ adapter (client.ts) ┌─ pi child process ────────────┐
16
+ 1. enumerate each server: tools/list │ pi --mode rpc │
17
+ 2. write config JSON ───────────────────▶│ -e mcp-bridge-extension.mjs │
18
+ (PI_MCP_BRIDGE_CONFIG) │ PI_MCP_BRIDGE_CONFIG=… │
19
+ 3. spawn pi with -e + env │ │
20
+ │ extension registers one pi │
21
+ │ tool per MCP tool; execute → │
22
+ │ @modelcontextprotocol/sdk → │
23
+ │ callTool() on the MCP server │
24
+ └───────────────────────────────┘
25
+ ```
26
+
27
+ 1. **Enumerate (adapter, `src/mcp-bridge/enumerate.ts`).** On `connect()`, for
28
+ each injected `AcpMcpServer` the adapter opens a short-lived MCP client,
29
+ `tools/list`, and closes it. Enumerating host-side surfaces connect/list
30
+ errors early and keeps the extension's registration synchronous.
31
+ 2. **Config JSON (`config.ts` / `parse-config.ts`).** The enumerated tools +
32
+ server specs are written to a per-session temp file
33
+ (`{ servers:[…], tools:[{ toolName, server, remoteName, description,
34
+ inputSchema }] }`). Path is passed via `PI_MCP_BRIDGE_CONFIG`.
35
+ 3. **Spawn.** The adapter adds `-e <dist>/mcp-bridge-extension.mjs` to the
36
+ `pi --mode rpc` argv (additive — pi's own extension discovery is untouched)
37
+ and sets `PI_MCP_BRIDGE_CONFIG` in the child env. The extension path is
38
+ resolved from the adapter's own module URL (`import.meta.url`), not cwd.
39
+ 4. **Register (extension, `src/mcp-bridge/extension.ts`).** At load, pi calls
40
+ the extension's default export; it reads the config and calls
41
+ `pi.registerTool(...)` once per tool — **synchronously**. Each tool's
42
+ `execute` lazily connects (memoized per server) and proxies via
43
+ `@modelcontextprotocol/sdk` `callTool`, mapping the result back to pi's
44
+ tool-result shape.
45
+
46
+ ## Tool namespacing
47
+
48
+ Bridged tools are named `mcp__<server>__<tool>`, sanitized to `[a-zA-Z0-9_-]`
49
+ and capped at 64 chars (provider tool-name limits). Collisions after
50
+ sanitizing/truncation get a `_2`, `_3`, … suffix. Namespacing avoids clashing
51
+ with pi's built-in tools (`read`, `bash`, …).
52
+
53
+ ## Result mapping (`map-result.ts`)
54
+
55
+ MCP `callTool` returns `{ content: ContentBlock[], isError? }`. The bridge maps
56
+ **text blocks directly**; every **non-text block** (image / audio / resource /
57
+ resource_link) is **stringified** into a labeled text block
58
+ (`[non-text MCP content] …`). An `isError: true` result is surfaced as text the
59
+ model can read and recover from (MCP's tool-error convention), prefixed
60
+ `MCP tool error (<server>/<tool>): …`, with `details.isError` set for logs. A
61
+ thrown/rejected SDK call is caught and returned as an error tool result (pi
62
+ never sees an uncaught throw).
63
+
64
+ ## The two make-or-break details (verified against pi 0.80.3, in source AND live)
65
+
66
+ - **Synchronous registration at extension load works.** pi's loader awaits the
67
+ extension factory (`core/extensions/loader.ts` — `await factory(api)`) and
68
+ `registerTool()` is valid during load (loader comment: "registerTool() is
69
+ valid during extension load"). The bridge registers synchronously in the
70
+ factory (like pi's own `hello.ts` example), so it does not depend on any
71
+ async-load timing. Proven live: pi called `mcp__echo__echo` in a `--mode rpc`
72
+ session.
73
+ - **Import resolution "just works" — because the extension imports NO pi
74
+ package.** pi loads extensions with **jiti**; in a Node install (the global
75
+ `pi` bin is a `#!/usr/bin/env node` script, not the Bun binary) jiti aliases
76
+ `@earendil-works/*` + `typebox` to pi's own install
77
+ (`loader.ts` `getAliases()`), so an extension living outside pi's tree still
78
+ resolves them. The bridge sidesteps the question entirely: it uses pi's
79
+ **structural** runtime contract (a `registerTool` method; a plain JSON Schema
80
+ as `parameters`) and imports nothing from `@earendil-works/*`
81
+ (`grep -c "@earendil-works" dist/mcp-bridge-extension.mjs` → `0`). The MCP SDK
82
+ is **inlined** into the extension bundle (pi's process can't resolve it
83
+ otherwise); only node builtins stay external.
84
+
85
+ ### Why a raw JSON Schema is a valid pi `parameters`
86
+
87
+ pi expects a TypeBox `TSchema`, but validates tool arguments with
88
+ `Compile(tool.parameters)` (`pi-ai/utils/validation.ts`). A raw MCP JSON Schema
89
+ compiles + validates unchanged (verified: `Compile({type:"object",…}).Check`
90
+ respects `required`/types), and pi additionally runs JSON-Schema-aware coercion
91
+ when the schema carries no TypeBox `Kind` symbol. So the bridge passes the MCP
92
+ `inputSchema` through verbatim — no `Type.Unsafe`, no `@earendil-works/pi-ai`
93
+ import, no cast.
94
+
95
+ ### ESM/CJS interop
96
+
97
+ The inlined MCP SDK pulls in CJS deps (e.g. `cross-spawn`) that `require()` node
98
+ builtins. The bundle banner injects a real `require`
99
+ (`createRequire(import.meta.url)`) so esbuild's `__require` helper uses it
100
+ instead of throwing "Dynamic require … is not supported".
101
+
102
+ ## Limitations / known gaps
103
+
104
+ - **Image & binary content** returned by an MCP tool is stringified to text, not
105
+ passed to pi as an image block (pi supports image tool results, but mapping
106
+ binary payloads through faithfully is deferred). Text tools (the common case)
107
+ are lossless.
108
+ - **No MCP sampling / elicitation / roots.** The bridge is one-directional
109
+ (pi → MCP tool call → result). MCP servers that request LLM sampling back from
110
+ the client are not supported.
111
+ - **Cancellation** — pi passes an `AbortSignal` into `execute`; the bridge
112
+ forwards it to the SDK `callTool({ signal })`. Whether the remote server
113
+ honors it depends on the server.
114
+ - **Brokered credentials.** Only static `headers` on an `AcpMcpServer` are
115
+ honored for http/sse servers. A `credentialRef` must be resolved into headers
116
+ by the host **before** injection (the bridge does not call the credential
117
+ broker).
118
+ - **Double connect for stdio.** The adapter probes each stdio server once to
119
+ enumerate, then the extension re-spawns it for live calls (two spawns total).
120
+
121
+ ## Live e2e
122
+
123
+ `e2e/echo-mcp-server.mjs` is a ~30-line stdio MCP server exposing one `echo`
124
+ tool; `e2e/run-e2e.mjs` injects it via `piRuntime().start({ mcpServers })`,
125
+ prompts pi to call it, and asserts the stream shows a `tool-call` for
126
+ `mcp__echo__echo`, a `tool-result` carrying the echoed text, and a completed
127
+ `turn-end`. Run (needs `ANTHROPIC_API_KEY` + a global `pi`), after a build:
128
+
129
+ ```bash
130
+ pnpm --filter @agentproto/adapter-pi build
131
+ node adapters/pi/e2e/run-e2e.mjs
132
+ ```
package/PI-RPC.md ADDED
@@ -0,0 +1,158 @@
1
+ # Pi RPC wire profile
2
+
3
+ Reverse-engineered from pi source at **0.80.3**
4
+ (`github.com/earendil-works/pi`, package `@earendil-works/pi-coding-agent`):
5
+
6
+ - `packages/coding-agent/src/modes/rpc/rpc-types.ts` — command + response unions
7
+ - `packages/coding-agent/src/modes/rpc/rpc-mode.ts` — the event loop (the
8
+ decisive file: `session.subscribe((event) => output(event))`)
9
+ - `packages/coding-agent/src/modes/rpc/jsonl.ts` — framing
10
+ - `packages/coding-agent/src/core/agent-session.ts` — `AgentSessionEvent`
11
+ - `packages/agent/src/types.ts` — base `AgentEvent`, `AssistantMessageEvent`
12
+ - `packages/ai/src/types.ts` — `StopReason`, `Usage`, `ToolCall`, message shapes
13
+
14
+ ## Transport & framing
15
+
16
+ `pi --mode rpc` is a persistent duplex:
17
+
18
+ - **stdin** — one command per line: `JSON.stringify(command) + "\n"`.
19
+ - **stdout** — one record per line, **LF-only framing** (`\n`). Payloads may
20
+ contain U+2028/U+2029, so records MUST be split on `\n` only (pi deliberately
21
+ avoids Node `readline`). The client mirrors this with a `StringDecoder` +
22
+ manual `\n` scan.
23
+
24
+ The process stays alive until stdin ends (pi then shuts down) or it receives
25
+ `SIGTERM`/`SIGHUP`. `close()` calls `stdin.end()` then `SIGTERM`.
26
+
27
+ ## stdout carries three kinds of record
28
+
29
+ 1. **Responses** — `{ type: "response", command, success, id?, data?, error? }`.
30
+ `id` echoes the command's `id` for correlation. `success:false` carries
31
+ `error: string`.
32
+ 2. **Session events** — pi's `AgentSessionEvent` union, emitted verbatim by
33
+ `session.subscribe`. These are the stream this adapter maps.
34
+ 3. **Extension-UI requests** — `{ type: "extension_ui_request", ... }` (and
35
+ `extension_error`). This adapter ignores them (classified as `other`); pi's
36
+ RPC mode does not require a response for the fire-and-forget ones.
37
+
38
+ Note: `--mode rpc` does **not** emit the `{ type: "session", version, id, ... }`
39
+ header that `--mode json` emits. The client obtains the session id via a
40
+ `get_state` command instead.
41
+
42
+ ## Commands this adapter sends
43
+
44
+ | Command | Shape | When |
45
+ | ------- | ----- | ---- |
46
+ | `get_state` | `{ id, type: "get_state" }` | right after spawn — readiness probe + captures `data.sessionId` |
47
+ | `set_thinking_level` | `{ id, type: "set_thinking_level", level }` | after connect, when an `effort` is set (`level ∈ off\|minimal\|low\|medium\|high\|xhigh`) |
48
+ | `prompt` | `{ id, type: "prompt", message }` | each turn (fire-and-forget; events follow) |
49
+ | `abort` | `{ id, type: "abort" }` | `cancel()` |
50
+
51
+ Model + resume are passed as **spawn argv**, not RPC commands:
52
+ `pi --mode rpc [--model <provider/id>] [--session <resumeSessionId>]`
53
+ (flags verified in `packages/coding-agent/src/cli/args.ts`;
54
+ `--model` accepts `provider/id` and an optional `:<thinking>` suffix).
55
+
56
+ ### `prompt` is fire-and-forget
57
+
58
+ Pi acks `prompt` as soon as preflight succeeds
59
+ (`{ command:"prompt", success:true }`) — the real work streams as events. A
60
+ `{ command:"prompt", success:false, error }` means **no events will follow**, so
61
+ the client synthesizes an `error` + `turn-end{error}` on the active turn so
62
+ `events()` terminates instead of hanging.
63
+
64
+ ## Session events (`AgentSessionEvent`) and their fields
65
+
66
+ Base `AgentEvent` (`packages/agent/src/types.ts`):
67
+
68
+ ```
69
+ { type: "agent_start" }
70
+ { type: "agent_end"; messages; willRetry } // session-extended
71
+ { type: "turn_start" }
72
+ { type: "turn_end"; message: AgentMessage; toolResults }
73
+ { type: "message_start"; message }
74
+ { type: "message_update"; message; assistantMessageEvent } // streaming
75
+ { type: "message_end"; message }
76
+ { type: "tool_execution_start"; toolCallId; toolName; args }
77
+ { type: "tool_execution_update"; toolCallId; toolName; args; partialResult }
78
+ { type: "tool_execution_end"; toolCallId; toolName; result; isError }
79
+ ```
80
+
81
+ Session-only additions: `agent_settled`, `queue_update`, `compaction_*`,
82
+ `auto_retry_*`, `entry_appended`, `session_info_changed`,
83
+ `thinking_level_changed`.
84
+
85
+ `AssistantMessageEvent` (carried on `message_update.assistantMessageEvent`):
86
+
87
+ ```
88
+ { type: "text_delta"; delta; contentIndex; partial }
89
+ { type: "thinking_delta"; delta; contentIndex; partial }
90
+ { type: "done"; reason: "stop"|"length"|"toolUse"; message }
91
+ { type: "error"; reason: "error"|"aborted"; error }
92
+ ... plus start/text_start/text_end/thinking_start/thinking_end/toolcall_* (ignored)
93
+ ```
94
+
95
+ `StopReason = "stop" | "length" | "toolUse" | "error" | "aborted"`.
96
+ `Usage = { input, output, totalTokens, cost: { total, ... }, ... }` (on the
97
+ assistant message).
98
+
99
+ ## Event → StreamEvent mapping table
100
+
101
+ | pi event | condition | StreamEvent |
102
+ | -------- | --------- | ----------- |
103
+ | `message_update` / `text_delta` | — | `text-delta { text: delta }` |
104
+ | `message_update` / `thinking_delta` | — | `thought { text: delta }` |
105
+ | `message_update` / `done` | — | *(no event)* — records `stopReason` for turn-end |
106
+ | `message_update` / `error` | `reason === "error"` | `error { message: errorMessage }` + records `stopReason` |
107
+ | `message_update` / `error` | `reason === "aborted"` | *(no event)* — records `stopReason` |
108
+ | `tool_execution_start` | — | `tool-call { toolCallId, toolName, arguments: args }` |
109
+ | `tool_execution_end` | — | `tool-result { toolCallId, result, isError }` |
110
+ | `turn_end` | assistant `message.stopReason` present | records `stopReason` |
111
+ | `turn_end` | assistant `message.usage` present | `usage_update` (see note) |
112
+ | `agent_end` | `willRetry !== true` | **`turn-end { reason: mapStopReason(lastStopReason) }`** — the turn terminator |
113
+ | `agent_end` | `willRetry === true` | *(no event)* — an auto-retry cycle; the turn continues |
114
+ | `agent_start` / `turn_start` / `agent_settled` | — | *(no event)* |
115
+ | anything else (queue_update, compaction, extension_ui, …) | — | ignored |
116
+
117
+ ### `stopReason` → `turn-end.reason`
118
+
119
+ | pi StopReason | turn-end reason |
120
+ | ------------- | --------------- |
121
+ | `stop` | `completed` |
122
+ | `aborted` | `cancelled` |
123
+ | `error` | `error` |
124
+ | `length` | `max_turns` *(closest "hit a budget limit"; see gap below)* |
125
+ | `toolUse` | `completed` *(never the settled reason; defensive)* |
126
+ | *(absent)* | `completed` |
127
+
128
+ **Terminator choice.** A prompt turn's RPC stdout sequence ends at `agent_end`
129
+ (verified empirically against pi 0.80.3):
130
+ `response/prompt → agent_start → turn_start → message_* → turn_end → agent_end`.
131
+ Pi's `agent_settled` event is emitted to in-process **extension** listeners
132
+ (`_emitAgentSettled`) but is **not** written to the RPC stdout stream, so it
133
+ cannot be the terminator. This adapter therefore terminates on `agent_end`,
134
+ honoring `willRetry`: an `agent_end{willRetry:true}` (auto-retry) is ignored and
135
+ only the final `agent_end{willRetry:false}` emits `turn-end`.
136
+
137
+ ## Known gaps / assumptions
138
+
139
+ - **`usage_update.size` / `.used`** — pi's per-message `Usage` reports token
140
+ totals + cost, but **no context-window size**. The mapper surfaces
141
+ `usage.totalTokens` as both `size` and `used`. `tokensIn`/`tokensOut` =
142
+ `input`/`output`; `cost = { amount: usage.cost.total, currency: "USD" }`.
143
+ A future improvement could issue `get_session_stats` (which carries
144
+ `contextUsage`) for a true window size, at the cost of an extra round-trip.
145
+ - **`length` → `max_turns`** — pi's `length` stop reason is a token/context
146
+ cap, not a turn-count cap. `max_turns` is the closest canonical "budget hit"
147
+ reason; there is no exact equivalent in the `StreamEvent` taxonomy.
148
+ - **Multimodal** — pi's `prompt` command accepts `images: ImageContent[]`.
149
+ `capabilities.multimodal` is `true` (pi supports it), but the current client
150
+ extracts **text only** from the host message; image passthrough is not yet
151
+ wired.
152
+ - **`plan`** — pi emits no plan/todo event on the RPC stream, so this adapter
153
+ never produces `StreamEvent{kind:"plan"}`.
154
+ - **`steer` / `follow_up`** — pi's RPC mode supports these mid-turn duplex
155
+ commands (hence `bidirectional: true`), but the AgentCliClient contract only
156
+ exposes `send` / `cancel`; this adapter maps `send` → `prompt` and `cancel` →
157
+ `abort`. Steering is available on the wire but not surfaced by the current
158
+ contract.
package/PI.md ADDED
@@ -0,0 +1,103 @@
1
+ ---
2
+ name: pi
3
+ id: pi
4
+ description: earendil-works/pi — MIT headless TypeScript coding agent. Driven over pi's persistent JSON-over-stdio RPC mode (`pi --mode rpc`) as a spawned child. Multi-provider (Anthropic/OpenAI/Google), streaming, live-duplex (steer/follow-up/abort mid-turn). No native ACP/MCP, but injected MCP servers are bridged into pi tools via a generated pi extension (see MCP-BRIDGE.md).
5
+ version: 0.1.0
6
+ bin: pi
7
+ install:
8
+ - method: npm
9
+ package: "@earendil-works/pi-coding-agent"
10
+ global: true
11
+ - method: curl
12
+ url: https://pi.dev/install.sh
13
+ version_check:
14
+ cmd: npm view @earendil-works/pi-coding-agent version
15
+ parse: "(\\d+\\.\\d+\\.\\d+)"
16
+ range: ">=0.80.0"
17
+ timeout_ms: 15000
18
+ auth:
19
+ ref: ./SECRETS.md
20
+ state:
21
+ env: [ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY]
22
+ sandbox: ./SANDBOX.md
23
+ protocol: proprietary
24
+ adapter: "@agentproto/adapter-pi"
25
+ session:
26
+ mode: persistent
27
+ idle_timeout_ms: 1800000
28
+ turn_idle_timeout_ms: 300000
29
+ context_carryover: true
30
+ capabilities:
31
+ streaming: true
32
+ tool_calls: true
33
+ sub_agents: true
34
+ file_io: true
35
+ multimodal: true
36
+ resumable: true
37
+ bidirectional: true
38
+ continuation:
39
+ default: native-resume
40
+ supported: [native-resume, pinned-session, transcript, none]
41
+ tags: [pi, earendil, proprietary, rpc, agent-runtime, coding, mcp-bridge]
42
+ ---
43
+
44
+ # Pi — AIP-45 manifest overview
45
+
46
+ `@agentproto/adapter-pi` drives **earendil-works/pi**
47
+ (`@earendil-works/pi-coding-agent`) as a `protocol: "proprietary"` AGENT-CLI
48
+ operator. The canonical, executable manifest lives in `src/index.ts`
49
+ (`defineAgentCli({...})`); this file is the human-readable overview.
50
+
51
+ ## Why `protocol: "proprietary"`
52
+
53
+ Pi ships neither ACP nor MCP, so neither the `acp` nor the `print` arm applies.
54
+ Pi *does* ship a persistent JSON-over-stdio RPC mode (`pi --mode rpc`), so the
55
+ adapter implements the proprietary-arm `AgentCliClient` contract directly:
56
+ `createAgentCliRuntime` skips its own subprocess plumbing and dynamic-imports
57
+ this package's `createAgentCliClient` factory, which spawns `pi --mode rpc`
58
+ and translates the stream. See [`PI-RPC.md`](./PI-RPC.md) for the wire profile.
59
+
60
+ ## Protocol arm
61
+
62
+ - **`bin`**: `pi` — a real binary. The proprietary arm never spawns it for you;
63
+ `client.ts` does, invoking `pi --mode rpc`. `AGENTPROTO_PI_BIN` overrides the
64
+ path.
65
+ - **`adapter`**: `@agentproto/adapter-pi` (self-reference the proprietary arm
66
+ dynamic-imports at session start).
67
+
68
+ ## Models
69
+
70
+ Default `anthropic/claude-sonnet-4-5`. `allowed` is a curated cross-provider
71
+ menu (`anthropic/claude-sonnet-4-5`, `openai/gpt-5.1`,
72
+ `google/gemini-2.5-flash`); the free-form `model` option accepts any pattern
73
+ pi's `--model` understands (`provider/id`, verified against pi's
74
+ `core/model-resolver.ts`). `env` maps provider → key env var.
75
+
76
+ ## Options
77
+
78
+ | id | type | values | maps to |
79
+ | -------- | ------ | ------ | ------- |
80
+ | `model` | string | free-form `provider/id` | pi `--model <pattern>` spawn flag |
81
+ | `effort` | enum | `off, minimal, low, medium, high, xhigh` | pi `set_thinking_level` RPC command |
82
+
83
+ ## Modes
84
+
85
+ A single `default` mode. Pi's RPC surface exposes no plan/build/read-only mode
86
+ switch, so none is invented — the manifest stays honest.
87
+
88
+ ## Continuation
89
+
90
+ `native-resume` by default. `client.ts` captures pi's session id from the
91
+ `get_state` response after connect; the host persists it and, on a cold start,
92
+ `connect({ resumeSessionId })` re-spawns pi with `--session <id>`.
93
+
94
+ ## Capabilities & MCP bridging
95
+
96
+ Pi has no native MCP client, but `connect({ mcpServers })` is **bridged**: the
97
+ adapter enumerates the servers' tools and spawns pi with a generated extension
98
+ (`-e <mcp-bridge-extension.mjs>` + `PI_MCP_BRIDGE_CONFIG`) that registers one pi
99
+ tool per MCP tool (`mcp__<server>__<tool>`), proxying calls over
100
+ `@modelcontextprotocol/sdk`. So injected toolsets — including the daemon's
101
+ `agent_start` gateway — are callable from pi, enabling sub-agent orchestration
102
+ when the daemon injects its gateway (`--orchestrator` flag). Mechanism +
103
+ limitations: [`MCP-BRIDGE.md`](./MCP-BRIDGE.md); sandbox: [`SANDBOX.md`](./SANDBOX.md).