pi-claude-tether 0.11.0 → 0.12.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +41 -1
  2. package/README.md +14 -12
  3. package/SOURCE.md +2 -2
  4. package/docs/ACCOUNT-FAILOVER.md +4 -4
  5. package/docs/ARCHITECTURE.md +11 -748
  6. package/docs/CONTEXT-POLICY.md +4 -4
  7. package/docs/DETAILS.md +66 -27
  8. package/docs/REQUEST-LEDGER.md +1 -1
  9. package/index.ts +197 -107
  10. package/package.json +2 -1
  11. package/scripts/continuity-proof.py +44 -21
  12. package/scripts/package-dirs.sh +1 -1
  13. package/scripts/update-cli.sh +1 -1
  14. package/src/account-command.ts +384 -0
  15. package/src/account-login.ts +109 -0
  16. package/src/accounts.ts +167 -21
  17. package/src/cli-catalog.ts +135 -0
  18. package/src/cli-process.ts +161 -57
  19. package/src/cli-version.ts +1 -1
  20. package/src/context-policy.ts +5 -97
  21. package/src/control-handler.ts +4 -5
  22. package/src/data-dir.ts +5 -4
  23. package/src/env-flag.ts +0 -22
  24. package/src/event-bridge.ts +3 -235
  25. package/src/handoff-broker.ts +1 -11
  26. package/src/mcp-config.ts +2 -34
  27. package/src/overflow.ts +4 -1
  28. package/src/process-manager.ts +90 -110
  29. package/src/provider.ts +313 -512
  30. package/src/rate-limit.ts +3 -3
  31. package/src/receipt-error.ts +59 -0
  32. package/src/removed-config.ts +151 -0
  33. package/src/request-ledger.ts +4 -0
  34. package/src/runtime-dir.ts +26 -1
  35. package/src/session-map.ts +22 -168
  36. package/src/thinking-config.ts +2 -2
  37. package/src/types.ts +0 -119
  38. package/tests/e2e/continuity-extension.ts +6 -0
  39. package/src/autocompact.ts +0 -95
  40. package/src/prompt-builder.ts +0 -584
  41. package/src/system-prompt-mode.ts +0 -53
  42. package/src/task-tracker.ts +0 -240
  43. package/src/tool-markers.ts +0 -508
@@ -1,758 +1,21 @@
1
- # Legacy observer architecture
1
+ # Architecture
2
2
 
3
- This document describes the explicit `PI_CLAUDE_CLI_CONTEXT=legacy` compatibility
4
- path and the marker contracts needed to render old sessions. The default from
5
- 0.9.0 uses [pi-owned context and execution](CONTEXT-POLICY.md): all tools run in
6
- pi, CLI sessions are disposable and pi owns compaction. The lifecycle/bridge
7
- code is shared, but the native execution, saved pairing and CLI compaction
8
- sections below do not describe the default.
3
+ Pi owns the prompt, tools, conversation, compaction and retry policy. Claude Code owns subscription authentication and model transport. There is no CLI-owned context mode in 0.12.0.
9
4
 
10
- How the legacy path turns the Claude Code CLI into a pi model provider, what
11
- crosses the boundary in each direction, and why each non-obvious decision is
12
- the way it is.
5
+ ## Request path
13
6
 
14
- ## The inversion
7
+ `index.ts` registers provider and API identity `pi-claude-tether`. `src/provider.ts` projects Pi's current context, stages the active tool schemas, and sends user content through the official CLI's stream-json interface. The MCP server remains `custom-tools`: model tool names are `mcp__custom-tools__<name>`, independent of the provider identity. Tool receipts bind tool IDs and canonical content, not the old provider name.
15
8
 
16
- pi normally streams from a provider API. This extension implements pi's
17
- `streamSimple` contract using a **persistent `claude -p` process per session**
18
- and translating its stdout into pi stream events. Claude Code remains an
19
- agent: it owns native tools, its default prompt, and a separate transcript
20
- and compaction lifecycle. pi executes custom handoff tools and remains the
21
- front-end's system of record.
9
+ The CLI runs with native tools disabled and session persistence disabled. All tools execute in Pi through the authenticated handoff broker. The provider validates tool-result echoes before acknowledging consumption; unknown consumption retires the process rather than replaying tools.
22
10
 
23
- The [default context policy](CONTEXT-POLICY.md) replaces this execution model.
11
+ ## Disposable process cache
24
12
 
25
- Registration happens twice in `index.ts`, because pi 0.84 has two dispatch
26
- paths:
13
+ A warm process belongs to one Pi session, account, model and launch configuration. Its acknowledged history prefix must match Pi's current history. Changed prompts, tools, branch history, compaction or account selection retire it and import Pi's authoritative context again. Restarting Pi does not resume a hidden Claude transcript.
27
14
 
28
- - `pi.registerProvider()` — feeds pi's provider composer.
29
- - `registerApiProvider()` from `@earendil-works/pi-ai/compat` — feeds pi-ai's
30
- global api registry, which pi's default stream fn resolves through. Print
31
- mode and nested agent loops take that path; without this they throw
32
- `No API provider registered for api: pi-claude-cli`.
15
+ Thinking changes are applied through CLI control requests on the next user turn; a refused update retires the process. Cancellation drains the CLI turn and retains safe cache continuity. Settled transient errors return to Pi's retry policy without an adapter retry loop.
33
16
 
34
- The model list is pi's own Anthropic catalogue re-parented under the
35
- `pi-claude-cli` provider id. Each model keeps pi's own `thinkingLevelMap`,
36
- less `minimal` on adaptive models, where it would send exactly what `low`
37
- sends (`cliThinkingLevelMap`). So pi offers only levels the model has, and
38
- the result matches Claude Code's own per-model effort report on every model
39
- (see "Thinking: the same request pi would send").
17
+ ## State ownership
40
18
 
41
- ## One turn on the wire
19
+ Package data, Claude account profiles and ledger directories remain under `pi-claude-tether`; the provider rename does not move credentials or user data. Temporary prompt/MCP files are private and cleaned up on retirement/exit. Historical session maps and saved prompt sidecars do not enable a compatibility mode.
42
20
 
43
- ```
44
- pi agent loop
45
- └─ streamSimple(model, context, options)
46
- ├─ session-map → resume the pi session's CLI session, or import
47
- ├─ prompt-builder → delta (resume) or flattened history (import)
48
- ├─ cli-process → the session's live process if one is parked
49
- │ (0.7.0), else process-manager spawns claude -p …
50
- ├─ stream-parser → NDJSON lines (never throws)
51
- ├─ event-bridge → pi stream events; CLI-executed tools as markers,
52
- │ HANDOFF (custom pi) tools as toolCall blocks
53
- ├─ control-handler → answers can_use_tool permission requests
54
- ├─ handoff → pi's stream ends at message_stop; the CLI blocks on
55
- │ the proxied tools/call (handoff-broker) until the
56
- │ next pi call answers it on the same process
57
- └─ result → the process is parked for the next turn, not killed
58
- ```
59
-
60
- ### Prompt in
61
-
62
- `claude -p` accepts one user message, not a structured history, so
63
- `prompt-builder.ts` flattens pi's `Context.messages` into a labeled
64
- transcript (`USER:` / `ASSISTANT:` / `TOOL RESULT (historical <tool>):`).
65
- Images in the **final** user message are translated from pi-ai's
66
- `{data, mimeType}` shape to Anthropic's `{source:{type:"base64",…}}` blocks;
67
- images earlier in history degrade to placeholder text. pi's system prompt
68
- rides in through `--append-system-prompt-file` (a temp file path — the
69
- unsuffixed `--append-system-prompt` takes a literal string, and handing it a
70
- path silently makes the path itself the prompt; also avoids Windows
71
- `ENAMETOOLONG`). pi 0.86+ leaves `Context.systemPrompt` empty and sends the
72
- prompt as `system` messages; this path resolves it the same way the default
73
- does ([CONTEXT-POLICY.md](CONTEXT-POLICY.md#request-contract)) and leaves
74
- those messages out of the transcript.
75
-
76
- ### Spawn
77
-
78
- ```
79
- claude -p --input-format stream-json --output-format stream-json
80
- --verbose --include-partial-messages
81
- --model <id> --permission-prompt-tool stdio
82
- (--session-id <pi session id> | --resume <pi session id>)
83
- [--thinking disabled | --max-thinking-tokens <n> --effort <level>
84
- --thinking-display summarized] [--mcp-config <tmp>]
85
- [--strict-mcp-config --setting-sources ""] # hermetic mode
86
- ```
87
-
88
- stdin stays **open** after the user message: the CLI sends permission
89
- requests on stdout and expects answers on stdin mid-episode — and, since
90
- 0.7.0, the next turn's user message goes down the same stdin (see "One
91
- process per pi session" below).
92
-
93
- ### Stream out
94
-
95
- stdout is NDJSON. Five envelope types matter:
96
-
97
- | Envelope | Handling |
98
- | ----------------- | ---------------------------------------------------------------------------------------------- |
99
- | `stream_event` | Raw Anthropic SSE — bridged 1:1 into pi stream events |
100
- | `assistant` | Complete-block echo — used for CLI-side tool markers |
101
- | `user` | Tool results the CLI feeds itself between cycles (markers with `PI_CLAUDE_CLI_TOOL_RESULTS=1`) |
102
- | `control_request` | Permission prompt — answered on stdin |
103
- | `result` | Episode end: authoritative usage, final answer, errors |
104
-
105
- Two filters keep Claude Code's inner life out of pi's transcript: envelopes
106
- with `parent_tool_use_id` set (the CLI's own sub-agents) are dropped, and
107
- `tool_use` blocks for tools pi cannot execute are skipped by
108
- `isPiKnownClaudeTool`.
109
-
110
- ## Episodes, not messages
111
-
112
- **The single most important thing to understand.** One subprocess run is a
113
- full agentic _episode_: N API calls ("cycles") with CLI-side tool
114
- executions between them. SSE `content_block` indexes **reset every cycle**.
115
-
116
- `event-bridge.ts` therefore keys tracked blocks by `(cycle, index)`. A
117
- cycle counter increments on each top-level `message_start`; the previous
118
- cycle's usage is banked at that moment, so per-cycle numbers accumulate
119
- instead of overwriting. The final `result` envelope carries authoritative
120
- cumulative usage and replaces the running sum when present. The **last**
121
- cycle's `stop_reason` is the episode's stop reason.
122
-
123
- Before this was understood, later-cycle content folded into earlier blocks,
124
- usage reported roughly one cycle, and the final answer could be lost.
125
-
126
- ### Billed usage and context are different numbers (0.4.10)
127
-
128
- `usage.input/output/cacheRead/cacheWrite` are **cumulative across cycles** —
129
- that is what the account is charged for. `usage.totalTokens` is **not their
130
- sum**: it carries the _last_ cycle's prompt size
131
- (`input + cache_read + cache_creation`), because that is the only figure that
132
- describes the conversation the model is actually holding.
133
-
134
- The distinction is load-bearing, not cosmetic. pi's
135
- `calculateContextTokens()` short-circuits on `totalTokens` and feeds it to
136
- both the host's context gauge and `shouldCompact()`. Every cycle re-sends the
137
- same cached prefix, so the sum counts that prefix once per cycle:
138
-
139
- A repeated prefix is counted once in each cycle's billed usage, but only once
140
- in the last cycle's context. A compaction boundary resets the context latch to
141
- `postTokens`; `tests/multi-cycle.test.ts` and `tests/compaction.test.ts` cover
142
- these contracts with synthetic data.
143
-
144
- ### Billing reads `modelUsage`, not `usage` (0.4.10)
145
-
146
- `result.usage` describes the main agent, while `result.modelUsage` includes
147
- sub-agent and helper-model usage. The bridge folds the latter when available.
148
-
149
- Two caveats, both deliberate:
150
-
151
- - Folded tokens are priced at the **session's** model rates. Exact for
152
- sub-agents, which inherit the session model; slightly off for a cheaper
153
- helper model, which is worth far less than the tokens it stops hiding.
154
- - Older CLIs send no `modelUsage`. The bridge falls back to `result.usage`,
155
- and an empty object is treated as absent rather than as a zero bill.
156
-
157
- ### Thinking: the same request pi would send (0.10.0)
158
-
159
- A pi thinking level reaches the model as the same request fields pi's own
160
- Anthropic provider sends for it (pi-ai `streamSimple`). `thinking-config.ts`
161
- mirrors that mapping:
162
-
163
- | pi level | Spawn flags | On a live process |
164
- | ------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------- |
165
- | off | `--thinking disabled` | `set_max_thinking_tokens 0` |
166
- | minimal … max | `--max-thinking-tokens B --effort E --thinking-display summarized` | `set_max_thinking_tokens B` + display, then `apply_flag_settings` `E` |
167
-
168
- - **B** is pi's budget for the level (1,024 / 2,048 / 8,192 / 16,384; xhigh
169
- and max clamp to high), or the host's custom `thinkingBudgets`.
170
- - **E** is the model's `thinkingLevelMap` entry when it names an effort,
171
- otherwise low / medium / high, as pi-ai's `mapThinkingLevelToEffort`.
172
- - One flag set serves every model: budget models (Haiku 4.5, Opus 4.5,
173
- Sonnet 4.5) read the budget and ignore the effort; adaptive models read the
174
- effort and take any positive budget as "on". Verified on claude 2.1.283
175
- through a logging proxy; all four flags and both controls exist in 2.1.263,
176
- the pi-context floor.
177
- - A model whose map says `off: null` gets no flags for `off`, the way pi-ai
178
- sends no `thinking` field there. pi does not offer `off` for those models.
179
- - Levels offered: pi's map, less `minimal` on adaptive models. That equals
180
- what Claude Code's `initialize` reports per model (`supportedEffortLevels`,
181
- pinned in `tests/thinking-config.test.ts`). The report is not read at
182
- runtime: it adds nothing to pi's map, ignores `maxEffortLevel` limits, and
183
- its model list is Claude Code's picker rather than access (Opus 4.5 and
184
- Sonnet 4.5 are missing from it and run fine), so it cannot be used to hide
185
- models.
186
- - `PI_CLAUDE_CLI_THINKING_DISPLAY=omitted` asks for no summaries. The default
187
- is `summarized`, as pi-ai's: billing counts the full thinking either way.
188
-
189
- Before 0.10.0 only `--effort` was passed. Budget models ignored it and
190
- thought with the CLI's 31,999-token default at every level, pi's `off` (which
191
- pi passes as no level) reached the CLI as no flag, so Sonnet 5 ran adaptive
192
- at effort `high`, and adaptive models streamed no thinking text because the
193
- CLI's default display is `omitted`.
194
-
195
- **Changing the level mid-session keeps the process.** Thinking is not part
196
- of the reuse signature. Before writing a new user turn to a parked process,
197
- `CliProcess.applyThinking` sends the control requests above, each with its
198
- own `request_id`, and waits for every `control_response` (intercepted in
199
- `handleLine`, never forwarded to an episode). If one is refused or not
200
- answered within `THINKING_CONTROL_TIMEOUT_MS` (5 s), the process is retired
201
- and a fresh one spawns with the new flags, so the turn is right either way.
202
- `max_thinking_tokens` is always a number: on 2.1.263 an omitted value resets
203
- the budget, on 2.1.283 it leaves it.
204
-
205
- Claude Code reads thinking once per user turn. A change made while a tool
206
- runs (a handoff) is not applied to the rest of that turn; it lands on the
207
- next user turn, still on the same process. Verified live: a change sent
208
- during a `sleep` tool call returned success, the continuation kept the old
209
- budget, the next turn had the new one.
210
-
211
- Cache cost is the API's: on adaptive models the effort and on/off state are
212
- part of the prompt-cache key, so the first switch to a setting the session
213
- has not used re-writes the prompt, and switching back reads it from cache.
214
- Native pi pays the same, except on Opus 5, Opus 5.5 and Fable 5.1, where it
215
- sends effort as mid-conversation messages behind a beta Claude Code does
216
- not use.
217
-
218
- `tests/live-thinking.test.ts` (`PI_OWNED_LIVE=1`) drives one pi session per
219
- model through level changes and asserts, from the request bodies, that every
220
- turn ran at the level set before it on exactly one CLI process.
221
-
222
- ### Effort maps 1:1, and never upward (0.4.12)
223
-
224
- `--effort` used to be shifted up a rung for opus: `medium` became `high` and
225
- `high` became `max`. That compensated for a cap the CLI no longer has, and it
226
- made `high` unrequestable on opus at all.
227
-
228
- The CLI accepts `--effort high`, `--effort xhigh` and `--effort max` as
229
- distinct values.
230
-
231
- Passing through the requested level also avoids unintentionally increasing effort.
232
-
233
- Every level now passes through unchanged. `minimal` still floors at `low`
234
- because the CLI has no effort rung below it (budget models get their own
235
- 1,024-token budget for it); that is a floor, and the invariant is
236
- one-directional: **no level ever maps above what the host asked for**.
237
-
238
- ### Thinking blocks are materialized lazily (0.4.4)
239
-
240
- Adaptive Claude models (fable-5, opus-5, sonnet-5) stream **encrypted**
241
- thinking when the display is `omitted`, which is the CLI's default: a
242
- multi-kilobyte `signature_delta` plus `thinking_delta` events whose text is
243
- the empty string, and no plaintext ever. Haiku 4.5 sends plaintext either
244
- way. Since 0.10.0 the provider asks for `summarized`, so every model streams
245
- a summary, but `PI_CLAUDE_CLI_THINKING_DISPLAY=omitted` and thinking the
246
- model chose to skip still produce signature-only blocks.
247
-
248
- Materializing on `content_block_start` therefore produced thinking blocks
249
- with a 3k signature and zero characters of text, which front-ends faithfully
250
- render as a "thought" that expands to nothing. So a thinking block is now
251
- created on the **first `thinking_delta` that actually carries text** — an
252
- empty-string delta must not bring one into existence — and dropped at
253
- `content_block_stop` if none ever arrived. A signature that precedes the
254
- plaintext is buffered and applied on materialization, so genuine thinking
255
- keeps its signature.
256
-
257
- This is why `TrackedContentBlock` carries an explicit `contentIndex` instead
258
- of a parallel-array invariant with `output.content`: a dropped block must not
259
- shift the indexes of the blocks after it.
260
-
261
- Sessions recorded before 0.4.4 still hold empty thinking blocks on disk
262
- forever, so front-ends need their own guard regardless — a host skips them on
263
- settled items.
264
-
265
- ## Tools: the three-way split
266
-
267
- **Built-in name translation** (`tool-mapping.ts` is the single source of
268
- truth): `Read→read` (`file_path→path`), `Write→write`, `Edit→edit`
269
- (`old_string→oldText`, `new_string→newText`), `Bash→bash`, `Grep→grep`
270
- (`head_limit→limit`), `Glob→find`. Claude proposes them under its names; pi
271
- records their activity as markers; the CLI executes them natively.
272
-
273
- **Custom pi tools** (anything a pi extension registered — a front-end's
274
- artifact tools, MCP-adapter tools) cannot be renamed into Claude's
275
- vocabulary, so they are advertised over MCP: `mcp-config.ts` writes every
276
- non-built-in tool's schema to a temp file and points `--mcp-config` at
277
- `mcp-schema-server.cjs`. Claude emits `mcp__custom-tools__<name>`; the bridge
278
- strips the prefix and emits a pi `toolCall`; pi executes the real tool. The
279
- server itself executes nothing: its `tools/call` handler forwards the request
280
- over a local socket to `handoff-broker.ts` in pi's process and blocks until
281
- pi has run the tool (0.7.0). Before that it could only refuse, and the
282
- provider had to interrupt the CLI and resume a new process with the result
283
- pasted in as user text — see "One process per pi session".
284
-
285
- ### The runtime directory and who may reach the broker
286
-
287
- Anything that can reach the broker socket can ask pi to execute a tool, so the
288
- socket is not a public surface. Every runtime artifact — the socket, the tool
289
- schemas, each session's `--mcp-config`, each spawn's system prompt, the broker
290
- secret — lives in one private per-process directory created by
291
- `src/runtime-dir.ts`:
292
-
293
- - `mkdtempSync(join(tmpdir(), "pi-claude-"))` — random name, mode `0700`, so
294
- the path cannot be derived from the pid and no other local user can traverse
295
- into it. Files inside are written `0600`, and the socket is `chmod`ded `0600`
296
- after bind (a bind honours the umask, so a stock `umask 022` box would
297
- otherwise leave it `0755`).
298
- - Every request must carry the process's 32-byte `secret`, compared with
299
- `timingSafeEqual` **before** the session id reaches any routing table. The
300
- schema server receives the secret as a **file path**, never as a command-line
301
- argument: argv is world-readable through `ps` and `/proc`, which would hand
302
- the secret to exactly the user the directory mode keeps out.
303
- - The directory is removed on exit. A `SIGKILL`ed process leaks it, but leaks a
304
- `0700` directory nobody else can open.
305
-
306
- Until 0.8.2 these were pid-named files written straight into `os.tmpdir()` with
307
- whatever the umask allowed — on Linux a `0755` socket and `0644` configs in a
308
- world-readable `/tmp`, and the config names the socket and the CLI session id
309
- (reported as agustinsacco/pi-claude-cli#35). macOS was unaffected in practice:
310
- `TMPDIR` there is already a per-user `0700` directory.
311
-
312
- Windows has no mode bits for a named pipe and Node exposes no ACL for one, so
313
- there the random pipe name and the secret are the whole of the defence. That
314
- asymmetry is why the secret check exists at all rather than relying on file
315
- permissions alone.
316
-
317
- **Everything else** — WebSearch, WebFetch, ToolSearch, `Task` sub-agents,
318
- the user's own MCP servers — is executed **by the CLI itself**, mid-episode.
319
- These are surfaced as one-line marker text blocks so transcripts show what
320
- happened:
321
-
322
- ```
323
- [Claude Code · WebSearch {"query":"news headline today 2026"}]
324
- ```
325
-
326
- ### The marker is a wire contract
327
-
328
- Front-ends parse the marker string, so its shape is API:
329
-
330
- ```
331
- [Claude Code · <ToolName>] # no arguments
332
- [Claude Code · <ToolName> <argsJson>] # complete, parseable JSON
333
- ```
334
-
335
- a host renders matches as activity rows and anything else as markdown prose,
336
- so a format change that looks cosmetic here degrades rendering there.
337
-
338
- `argsJson` is **complete JSON** as of 0.8.0, and `src/tool-markers.ts`
339
- decides what goes in it. Before that it was `JSON.stringify(input)` cut at
340
- 120 characters: usually invalid JSON (so a consumer needed a fragment
341
- scanner with its own escape decoder), cut at the END of values — so an
342
- absolute path lost the filename, the one part a row shows — and easily
343
- consumed whole by a single bulk argument (`Write`'s file contents, `Edit`'s
344
- replacement, `Task`'s prompt). Now each tool contributes its identifying
345
- arguments in priority order, values are clipped individually (paths from the
346
- front, keeping the tail), bulk arguments are replaced by measurements
347
- (`lines`, `bytes`, `edits`, and for `TodoWrite` the live item), and the
348
- 700-character budget is enforced by dropping trailing fields rather than by
349
- cutting the document.
350
-
351
- ### Not yet surfaced (extension seams)
352
-
353
- One thing the CLI reports is forwarded only on opt-in, and one is still
354
- dropped:
355
-
356
- - **Results of CLI-side tools — forwarded when `PI_CLAUDE_CLI_TOOL_RESULTS=1`.**
357
- The `user` envelopes between cycles carry `tool_result` blocks for tools the
358
- CLI executed itself. With the flag set, the call marker gains a
359
- `#<toolUseId>` tag and each result becomes a
360
- `[Claude Code · result #<toolUseId> {payload}]` marker
361
- (`handleUserEnvelope`), letting a front-end pair them and render CLI-side
362
- tools as expandable rows. The payload is complete JSON: `status`, the
363
- `tool` it answers, a printable `summary`, typed metrics, a capped `preview`
364
- and the full `length`. The metrics come from the CLI's own
365
- `tool_use_result` object — a read's `numLines`/`totalLines`, an edit's
366
- `structuredPatch`, a command's `stdout`/`stderr`/`interrupted`, a glob's
367
- `numFiles`, a failed command's exit code — so a row can say "419 lines" or
368
- "exit 1 · No such file" instead of just "ok". Only ids that produced a call
369
- marker are forwarded, so a handoff tool's replayed result (pi already has
370
- the real one) never renders twice. Without the flag the wire is unchanged:
371
- the id-tagged shapes are a contract change a consumer must know how to
372
- parse.
373
- - **Sub-agent transcripts.** What a sub-agent actually did — its own tool
374
- calls and text — arrives with `parent_tool_use_id` set and is still
375
- filtered out in both `provider.ts` and `handleAssistantEnvelope`. Those
376
- events carry a full nested episode; a front-end that wanted a live
377
- sub-agent _tree_ would consume them there. Lifecycle and progress are
378
- surfaced (see below), so a consumer knows which agents ran, how long they
379
- took and what they cost — but not what they read or wrote.
380
-
381
- ### Sub-agent lifecycle rides its own channel (0.4.13)
382
-
383
- Nested agent transcripts are filtered, so the provider uses the separate
384
- lifecycle feed to make sub-agent activity visible without replaying its content.
385
- The CLI publishes `system` envelopes with a `task_*` subtype. They arrive at **top level**
386
- — `parent_tool_use_id` is null — even for agents nested several deep,
387
- verified on claude 2.1.231 at spawn depth 2. `src/task-tracker.ts` folds
388
- them, and the split is by durability:
389
-
390
- | Envelope | Where it goes | Why |
391
- | ------------------- | ------------------------------------------------ | ------------------------------------------------------- |
392
- | `task_started` | marker in the turn | durable: this agent ran |
393
- | `task_notification` | marker in the turn | durable: it finished, with tool count, tokens, duration |
394
- | `task_progress` | `onTaskProgress` → `claude-subagents` status key | ephemeral: fires once per sub-agent tool call |
395
- | `task_updated` | `onTaskProgress` | ephemeral status patch |
396
-
397
- Each tracked sub-agent contributes a start and a terminal marker. The
398
- progress channel follows `claude-rate-limit`: state ABOUT the turn, never
399
- folded into content, and never persisted.
400
-
401
- `task_notification` carries the sub-agent's full report in `summary`. The
402
- marker deliberately omits it — the model already receives it as the `Task`
403
- tool's own result, and repeating it would duplicate kilobytes into every
404
- later replay. The snapshot exposes `outputFile` instead, for a host that
405
- wants the whole thing.
406
-
407
- One honest limit remains. There is **no tree**: no task envelope names its
408
- parent task, so a nested agent is indistinguishable from a top-level one and
409
- the list is flat.
410
-
411
- Two envelopes on this channel are **not** sub-agents, and both used to be
412
- reported as ones:
413
-
414
- - `task_started` carries `task_type`. The CLI auto-backgrounds a slow `Bash`
415
- into a `local_bash` task wearing the tool's own description. Only
416
- `local_agent` and `remote_agent` count. A
417
- missing `task_type` still counts, so an older CLI does not go silent.
418
- - `task_notification` carries only `task_id` — no description, no
419
- `task_type`. A task started in an earlier episode notifies into a later
420
- one, and inventing a placeholder from the id emitted
421
- `{"status":"stopped","description":"example-task-001"}`. An id this
422
- episode never saw start is dropped.
423
-
424
- Markers carry `task_id`, so a host can join `started` to `completed` rather
425
- than matching on description. The description is clipped to 120 characters
426
- before the whole-payload cap, because one long description used to eat the
427
- preview and take `subagent_type` with it.
428
-
429
- ### The turn ends when the sub-agents do (0.4.14)
430
-
431
- `Agent` backgrounds by default. The CLI answers such a call in milliseconds
432
- with "Async agent launched successfully… you will be notified when it
433
- completes", so the model ends its turn to wait — correctly, per its own tool
434
- contract. The CLI then emits `result` for that turn **while the agents are
435
- still running**, and this provider killed the subprocess on it.
436
-
437
- The CLI can later emit a `task_notification`, resume the model, and produce
438
- another `result` without another user prompt. Closing the process at the first
439
- result would discard that pending work.
440
-
441
- So while `pendingAgents()` is non-zero, a `result` is a cycle boundary, not
442
- the end of the episode. `applyResult` per cycle stays correct because
443
- `modelUsage` is cumulative for the CLI session, so the last snapshot wins
444
- rather than summing cumulative snapshots.
445
-
446
- Two timers bound the wait:
447
-
448
- | Bound | Default | Reset by |
449
- | ---------- | ---------------------- | --------------------------------- |
450
- | inactivity | 300s of no stdout | any output, incl. `task_progress` |
451
- | wall clock | 15 min from first wait | never |
452
-
453
- Both expiries end the turn on what it already has. An error there would
454
- throw away the launch markers and the model's own words, which are real.
455
- `PI_CLAUDE_CLI_NO_AGENT_WAIT=1` restores the old teardown;
456
- `PI_CLAUDE_CLI_AGENT_WAIT_MS` moves the wall clock.
457
-
458
- ### Enforcement is belt-and-suspenders
459
-
460
- The belt is `control-handler.ts`: custom-tools requests get
461
- `{behavior:"deny"}` (so pi runs them), everything else `allow`. The
462
- suspenders are the **handoff interrupt** in `provider.ts`: at the first
463
- top-level `message_stop` after a HANDOFF `tool_use`
464
- (`mcp__custom-tools__*` only), the provider sends the CLI's own `interrupt`
465
- control request and freezes the stream until the result envelope arrives.
466
- Built-in tools never trigger either mechanism — the CLI executes them
467
- natively and pi renders the markers.
468
-
469
- **Never SIGKILL a healthy turn.** A kill truncates the CLI's session file
470
- before the assistant turn is written; every later `--resume` then splices a
471
- synthetic `No response requested.` assistant turn into the replayed
472
- transcript, which can affect subsequent model behavior. SIGKILL remains only as the abort
473
- backstop (2s after an interrupt) and the post-result reaper.
474
-
475
- ### Empty arguments are `{}`, malformed arguments are the raw text
476
-
477
- A handoff tool's arguments arrive as `input_json_delta` events and accumulate
478
- into `partialJson`. A call with **no** arguments — `mcp({})`,
479
- `artifact_list()` — produces no deltas at all, so the accumulator is still the
480
- empty string when `content_block_stop` lands.
481
-
482
- `event-bridge.ts` therefore treats empty and malformed as two different
483
- things:
484
-
485
- | accumulated payload | forwarded to pi |
486
- | ------------------------------------------ | ------------------------------------- |
487
- | `""` or whitespace | `{}` |
488
- | valid JSON object | the parsed object, after arg renaming |
489
- | valid JSON non-object (`null`, `[]`, `12`) | the raw string |
490
- | unparseable (truncated stream) | the raw string |
491
-
492
- The empty case must not fall into the parse-failure branch. `JSON.parse("")`
493
- throws, and forwarding the raw `""` makes pi reject the call against the
494
- tool's schema with `root: must be object` — which silently killed every
495
- zero-argument handoff tool, including `mcp({})`, the documented first step for
496
- checking MCP status.
497
-
498
- The reverse is equally deliberate: a **non-empty** payload that cannot be used
499
- is passed through as its raw string rather than coerced to `{}`. That text is
500
- the only evidence of what actually arrived, and blanking it would turn a
501
- visible failure into a tool that silently ran with no arguments.
502
-
503
- ## One process per pi session (0.7.0)
504
-
505
- A persistent process avoids restarting the CLI between a proxied tool call
506
- and its result, and allows later turns to reuse its warm prompt cache.
507
- `src/cli-process.ts` therefore keeps the process:
508
-
509
- - **Through a handoff.** The permission for `mcp__custom-tools__*` is now
510
- ALLOWED. The CLI calls `tools/call`; the schema server forwards it over the
511
- broker socket with the CLI session id, `_meta["claudecode/toolUseId"]` and
512
- the broker secret;
513
- pi's stream ends at `message_stop` with `stopReason: toolUse` exactly as
514
- before, pi runs the tool, and the next `streamSimple` call — whose delta is
515
- all unique toolResults for the awaited ids, optionally followed by user
516
- steers — attaches to the same process and answers the call. Trailing users
517
- go to the same stdin in one ordered, image-preserving UUID-tagged message.
518
- The CLI's default stream-json priority reads them once its running tools
519
- finish. A nonempty result must echo their UUID before turn-end reuse;
520
- missing confirmation retires the source. An earlier result or empty queued
521
- notification is not proof that the steer was consumed.
522
- Either order works: the call may arrive
523
- before pi's result (held as pending) or after (held as ready). The CLI
524
- transcript records a real `tool_result`; the rejected-tool /
525
- `[Request interrupted]` / `No response requested.` filler is gone.
526
-
527
- The `toolUseId` must name a `tool_use` block this process actually streamed
528
- and has not answered yet, and must ask for the tool that block named.
529
- Anything else is refused immediately. Before 0.8.2 an unmatched id was
530
- parked in `pending`, where nothing would ever deliver a result for it and
531
- the caller blocked until the MCP tool timeout — an hour by default. A
532
- sub-agent's nested custom-tool call lands here: pi never sees non-top-level
533
- `tool_use` ids, so it could never answer one. It now gets an error rather
534
- than a stall.
535
-
536
- A connection that sends no complete request within a minute is dropped
537
- (`HANDOFF_REQUEST_TIMEOUT_MS`). That bounds the request, not the call: once
538
- the request line arrives, the call stays open for as long as pi runs the
539
- tool, bounded only by the CLI's `MCP_TOOL_TIMEOUT` (an hour by default) and
540
- `PI_CLAUDE_CLI_HANDOFF_WAIT_MS`. Before 0.9.1 the timer kept running after
541
- the request, and under pi context every tool comes through here, `bash`
542
- included. So any tool slower than a minute (a build, a test suite) returned
543
- "pi closed the connection without a result" to the model while pi recorded
544
- the real output, and the next call usually had to respawn the process.
545
-
546
- - **Across turns.** After `result` the process is parked
547
- until its prompt cache expires (last request + the longest TTL written:
548
- 1h on the subscription CLI, else 5 min; `PI_CLAUDE_CLI_KEEPALIVE_MS`
549
- overrides). The next call whose delta
550
- is a user message writes it to the same stdin. The live persistent-process
551
- tests compare warm reuse with restarting the CLI.
552
-
553
- Exactly one episode (pi call) is attached at a time; lines that arrive while
554
- none is — a built-in tool's result during a handoff, a sub-agent event — are
555
- buffered and replayed to the next episode. Permission requests are answered
556
- attached or not. The process is retired (interrupt if a turn is live, then
557
- stdin EOF, then SIGKILL after a grace) whenever the next call cannot use it:
558
- different model/prompt mode/cwd, a thinking change the process refused
559
- (see "Thinking"), a rewritten tool schema (`version`
560
- bump — the CLI advertised the old surface at connect), a stale pi history, a
561
- delta that is not the complete awaited tool results followed only by users,
562
- unconfirmed steer consumption, or the idle timers
563
- (`PI_CLAUDE_CLI_HANDOFF_WAIT_MS` for a handoff pi never answers). Retiring
564
- falls back to the `--resume` path below, so nothing is lost — only the
565
- cache-warm restart is.
566
-
567
- **Billing across a long-lived process.** `result.usage` is per CLI turn, but
568
- `result.modelUsage` — the figure the provider trusts, because it includes
569
- sub-agents — is cumulative for the **process**. Each result is therefore
570
- billed as the delta against the previous
571
- result's totals, and a turn split across two episodes by a handoff is billed
572
- once: the finishing episode reports the turn's delta net of what the first
573
- episode already reported, floored at its own streamed cycles.
574
-
575
- `PI_CLAUDE_CLI_HANDOFF_PROXY=0` restores the interrupt-and-resume handoff
576
- (the schema server then answers `tools/call` with an error result). Without a
577
- pi session id (print mode, tests) nothing is parked or proxied.
578
-
579
- ## Session model: one CLI session per pi session
580
-
581
- pi's session JSONL is the **only** authoritative record; the CLI session is
582
- the model's working memory. The sidecar map
583
- `<package-state-dir>/session-map.json` (exact path in README;
584
- `PI_CLAUDE_CLI_STATE_DIR` overrides; `src/session-map.ts`) links pi session
585
- id → CLI session id, and
586
- `sysprompt/<cliId>.txt` beside it holds the system prompt that session was
587
- created with.
588
-
589
- `PI_CLAUDE_CLI_EPHEMERAL=1` opts a one-shot out of all of it: the CLI runs with
590
- `--no-session-persistence` and neither the pairing nor the prompt is recorded,
591
- so every respawn in that pi session is a create/import and none is a resume.
592
- Reuse of a parked process is unaffected — it needs no pairing.
593
-
594
- When a matching CLI session cannot be resumed, the provider imports the
595
- available pi history into a new CLI session.
596
-
597
- Forks, model switches, copied machines and lost sidecars all collapse into
598
- one recovery path: a single full-history import. Never a lost turn.
599
-
600
- ### The delta anchor is load-bearing (0.4.6)
601
-
602
- `buildResumePrompt` anchors on the **last assistant message** and sends only
603
- what follows it. It must not anchor on the last _user_ message: pi's tool
604
- loop appends `[user, assistant(toolUse), toolResult, assistant(toolUse),
605
- toolResult, …]`, so the single `user` entry stays at index 0 for the life of
606
- the loop, and anchoring there replays the whole transcript on **every
607
- iteration** — content the CLI already holds.
608
-
609
- The delta begins after the last assistant entry, including any later tool
610
- results or user messages that the CLI has not yet received.
611
-
612
- The invariant to preserve: **delta size stays flat as the tool loop
613
- deepens.** If a change makes the resume prompt grow with conversation
614
- length, it has regressed.
615
-
616
- ## Errors and recovery
617
-
618
- - Any `result` with a non-success subtype, `is_error`, or an error field
619
- ends pi's stream as an error (never a silent empty message).
620
- - **Context overflow** is rewritten by a provider-scoped `message_end`
621
- handler (`overflow.ts`) to the `context_length_exceeded:` prefix pi's
622
- auto-compaction recognizes — so pi compacts and retries instead of
623
- failing. The matcher is deliberately narrow (Anthropic's two overflow
624
- phrasings) and never touches rate limits, which must stay on pi's
625
- retry/backoff path.
626
- - An inactivity timer (default 300s, `PI_CLAUDE_CLI_TIMEOUT_MS`) kills hung
627
- subprocesses. It is generous because CLI-side tools are legitimately
628
- silent on stdout for minutes.
629
- - pi's abort signal SIGKILLs mid-stream; a process registry cleans up
630
- orphans at exit.
631
-
632
- ## Usage and cost
633
-
634
- Usage comes from `message_start` / `message_delta` per cycle and the
635
- `result` envelope for the episode total, then runs through pi's own
636
- `calculateCost`. **Token counts are real; the dollar figure is notional** —
637
- it is computed at API list prices while the user is actually spending plan
638
- quota.
639
-
640
- ## Account state: rate limits (0.4.5)
641
-
642
- The CLI emits a `rate_limit_event` envelope describing the **account's**
643
- plan window. This is not turn content and must never become any: it says
644
- nothing about the answer being streamed, and folding it into the message
645
- would put account state into the user's transcript and into pi's session
646
- file. It travels a separate path end to end:
647
-
648
- ```
649
- provider.ts rate_limit_event → options.onRateLimit(info) (never touches pi's stream)
650
- index.ts publishRateLimit → ctx.ui.setStatus("claude-rate-limit", json)
651
- front-end reads the status key, renders it however it likes
652
- ```
653
-
654
- The key is **`claude-rate-limit`** — deliberately neutral rather than
655
- namespaced to any one front-end, since it is account state any pi front-end
656
- can use. The payload is JSON:
657
-
658
- ```jsonc
659
- {
660
- "status": "allowed", // "rejected" once the window is capped
661
- "resetsAt": 1700003600, // example unix seconds
662
- "rateLimitType": "five_hour",
663
- "overageStatus": "rejected",
664
- "isUsingOverage": false,
665
- "observedAt": 1700000000,
666
- } // when we saw it, not from the CLI
667
- ```
668
-
669
- Two behaviors worth knowing before you build on it. The CLI repeats the
670
- event **every turn**, so `publishRateLimit` pushes only when the payload
671
- changes (comparing with `observedAt` stripped) — a status that rewrites
672
- itself constantly is noise for whatever renders it. And `session_start`
673
- stashes its `ctx` in module scope, because the stream runs deep inside
674
- `streamSimple`, which has no `ExtensionContext` of its own.
675
-
676
- **What this does not carry: utilization percentages.** The "12% of your 5-hour
677
- limit" figures in Claude Code's own TUI come from
678
- `anthropic-ratelimit-unified-*` **response headers**, which the CLI consumes
679
- in-process and never forwards to stdout. So a consumer can honestly say
680
- _when capacity returns_ and whether the account is capped or on overage —
681
- never _how much is left_. Getting the percentages would mean making
682
- authenticated Anthropic requests outside the CLI, which is exactly the line
683
- this extension exists not to cross.
684
-
685
- ## Environment bleed
686
-
687
- Unless hermetic mode is on, the subprocess runs in the user's full Claude
688
- Code environment: personal/project MCP servers load and execute CLI-side,
689
- hooks fire, project CLAUDE.md and memory are injected by the CLI, and skills
690
- can load twice (natively via claude, and again via pi's own
691
- `~/.claude/skills` support). `PI_CLAUDE_CLI_HERMETIC=1` adds
692
- `--strict-mcp-config` and an empty `--setting-sources` to shut all of that
693
- off; the schema-only custom-tools server and the subscription login are
694
- unaffected.
695
-
696
- ## Compatibility notes
697
-
698
- The CLI's control protocol changed between major lines. Claude Code **2.x**
699
- expects `request_id` **inside** `response`, and allow decisions carry
700
- `updatedInput`:
701
-
702
- ```jsonc
703
- { "type": "control_response",
704
- "response": { "subtype": "success", "request_id": "…",
705
- "response": { "behavior": "allow", "updatedInput": { … } } } }
706
- ```
707
-
708
- The 1.x shape (`request_id` at the top level) is **silently ignored** by
709
- 2.1.x: the CLI keeps waiting, the episode stalls until the inactivity timer
710
- fires, and the turn looks truncated. This was the root cause behind every
711
- "web search / MCP turn returns only the preamble" report.
712
-
713
- ## Version history of behavioral fixes
714
-
715
- | Version | Change |
716
- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
717
- | 0.4.0 | Port to `@earendil-works` pi 0.84; api-registry registration; scoped release |
718
- | 0.4.1 | 2.x control protocol; cycle-aware bridge (ordering, cumulative usage, final-answer safety net); CLI-side tool markers; 300s timeout |
719
- | 0.4.2 | Resume-miss → one full-replay retry (fixes forked sessions) |
720
- | 0.4.3 | Overflow → `context_length_exceeded` rewrite (pi auto-compaction); hermetic mode |
721
- | 0.4.4 | Lazy thinking materialization (no empty blocks for encrypted thinking); explicit `contentIndex` per tracked block |
722
- | 0.4.5 | `rate_limit_event` → `claude-rate-limit` status key for front-ends |
723
- | 0.4.6 | Resume delta anchors on the last **assistant** message — stops full-transcript replay on every tool iteration |
724
- | 0.4.9 | `utilization` on `claude-rate-limit` (percentage of the binding window) |
725
- | 0.4.10 | `usage.totalTokens` = last cycle's prompt, not the summed cycles (fixes inflated context gauges and premature auto-compaction); billing reads `modelUsage`, so sub-agent spend is no longer invisible |
726
- | 0.4.12 | `--effort` maps 1:1 for every model; the opus up-shift (`high`→`max`) is gone, so a host asking for `high` gets `high` |
727
- | 0.4.13 | Sub-agent lifecycle surfaced: `task_started`/`task_notification` as markers, `task_progress` on the `claude-subagents` status key |
728
- | 0.4.14 | Background sub-agents run to completion and report back (a `result` with agents pending is a cycle, not the end); non-agent tasks and orphan notifications no longer reported as agents; `AskUserQuestion` disallowed |
729
- | 0.4.15 | System prompt re-sent on `--resume` (the CLI drops it), replayed verbatim from the sidecar so the cached prefix survives |
730
- | 0.4.16 | System prompt passed via the `-file` flag variants — the unsuffixed flags take a literal string, so pi's instructions had never reached the model |
731
- | 0.5.0 | `--autocompact 200000` by default (`PI_CLAUDE_CLI_AUTOCOMPACT`) |
732
- | 0.5.1 | `PI_CLAUDE_CLI_STRICT_MCP`; the tool schema follows pi's registry instead of freezing at turn 1 |
733
- | 0.5.2 | A tool call with no arguments reaches pi as `{}` |
734
- | 0.6.0 | CLI-side tool results forwarded as paired `result` markers (`PI_CLAUDE_CLI_TOOL_RESULTS=1`) |
735
- | 0.6.1 | A `result` with no content and no tokens (the CLI answering its own queued task notification) is a cycle boundary, not the turn's end |
736
- | 0.7.0 | One CLI process per pi session: custom-tool calls proxied through the MCP server instead of interrupt-and-resume, process parked between turns — no more full-context re-bill after a commit or branch rename |
737
-
738
- ## Testing
739
-
740
- - `npm test` — unit suites with mocked `cross-spawn`; includes
741
- `tests/fixtures/multi-cycle-episode.jsonl`, a **synthetic 3-cycle
742
- episode** (claude 2.1.237) used to assert ordering, markers, and both
743
- usage modes; `tests/persistent-cli.test.ts` drives two pi calls through one
744
- mocked process (proxied handoff, turn continuation, delta billing, every
745
- retire condition); `tests/schema-server-proxy.test.ts` runs the real
746
- `mcp-schema-server.cjs` against a fake broker socket.
747
- - `npm run test:e2e` — full pipeline through a real `pi` binary against a
748
- deterministic CLI stub (`tests/e2e/claude-stub.cjs`); no credentials.
749
- - This tree does not include CI workflows; run these checks locally on each target OS.
750
- - `scripts/e2e-live.sh` (= `PI_CLAUDE_CLI_LIVE=1 vitest run
751
- tests/live-observer.test.ts`) — live observer-mode suite against the real
752
- CLI; spends plan quota, so it is opt-in. `PI_CLAUDE_CLI_LIVE=1 npx
753
- vitest run tests/live-persistent.test.ts` proves the 0.7.0 cache properties
754
- (one process through a handoff and a commit; the legacy path re-billing
755
- after the same commit) using usage reported by the live CLI. Covers: a native multi-tool
756
- turn, a cheap resume of the same CLI session (asserts cacheRead > 5k and
757
- cacheWrite < 2k), the custom-tool handoff round-trip, a PreToolUse guard
758
- hook blocking an out-of-workspace read, and abort/steer + resume.
21
+ See [Context policy](CONTEXT-POLICY.md), [technical details](DETAILS.md), [account failover](ACCOUNT-FAILOVER.md) and [request ledger](REQUEST-LEDGER.md) for the full contracts.