pi-claude-tether 0.11.0 → 0.11.1

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/CHANGELOG.md CHANGED
@@ -1,8 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.11.1 — 2026-11-05
4
+
5
+ - A pre-model OAuth refresh collision ("another Claude Code process is refreshing it") now retires the process and returns a transient error, so Pi's own retry decides, instead of killing the turn.
6
+ - Long error tool results that the official client clips (head 5000, marker, tail 5000) are accepted as that exact projection and recorded as declared-lossy, instead of forcing a full cache rewrite. Any other change still fails.
7
+ - An empty `PI_CLAUDE_CLI_CONTEXT` selects Pi-owned mode rather than the old CLI-owned mode. Stored prompt files are written with restricted permissions.
8
+ - Runtime allocation errors name the boundary that failed.
9
+
3
10
  ## 0.11.0 — 2026-10-28
4
11
 
5
- Prepared first public release as `pi-claude-tether` (not yet published).
12
+ First public release as `pi-claude-tether`.
6
13
 
7
14
  - Explicit public export and npm allowlists; policy-backed public-tree scan.
8
15
  - Public data, state and ledger roots remain unchanged. Unknown package names now use a generic legacy data directory; no automatic credential migration.
package/README.md CHANGED
@@ -1,6 +1,5 @@
1
1
  # pi-claude-tether
2
2
 
3
-
4
3
  Use your Claude subscription in [Pi](https://github.com/earendil-works/pi), through the official Claude Code CLI.
5
4
 
6
5
  Hi, I do most of my work in Pi and I have a Claude subscription. While Anthropic has not been magnanimous enough to let us use our subscription directly in third-party harnesses, it still allows its usage through [`claude -p`](https://support.claude.com/en/articles/15036540-use-the-claude-agent-sdk-with-your-claude-plan), in its installed coding agent CLI. Pi is my main harness and I don't want to be swapping coding agents, and most importantly I don't want to juggle identities and system prompts. The goal of this tether is to unlock the high limits a subscription allows while using your own Pi custom prompt as much as possible, staying lighter on the system prompt than the less-than-optimal vendor harnesses, and not having to go through the API. I wrote it with a coding agent.
@@ -33,12 +32,12 @@ In short live tests on Sonnet 5.5, 98.3% of a warm turn's input came from the ca
33
32
 
34
33
  ## Why not something else
35
34
 
36
- | Option | Why I didn't use it |
37
- |---|---|
38
- | Pi with the direct API | It works well, but you pay per token instead of using your plan. |
39
- | Packages that reuse your Claude login and imitate Claude Code | I don't want my account depending on imitating a client. Those packages also have to keep up each time the client changes. |
40
- | [pi-claude-bridge](https://github.com/elidickinson/pi-claude-bridge), on the Agent SDK | It's a good official route and Pi runs the tools there too. I went with the CLI because this project started as a fork of pi-claude-cli. |
41
- | [pi-claude-cli](https://github.com/rchern/pi-claude-cli) | This is where the project started. I forked it to add cache continuity across cancelled tools, retries and steering, several accounts, and a safe way to update the CLI. |
35
+ | Option | Why I didn't use it |
36
+ | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
37
+ | Pi with the direct API | It works well, but you pay per token instead of using your plan. |
38
+ | Packages that reuse your Claude login and imitate Claude Code | I don't want my account depending on imitating a client. Those packages also have to keep up each time the client changes. |
39
+ | [pi-claude-bridge](https://github.com/elidickinson/pi-claude-bridge), on the Agent SDK | It's a good official route and Pi runs the tools there too. I went with the CLI because this project started as a fork of pi-claude-cli. |
40
+ | [pi-claude-cli](https://github.com/rchern/pi-claude-cli) | This is where the project started. I forked it to add cache continuity across cancelled tools, retries and steering, several accounts, and a safe way to update the CLI. |
42
41
 
43
42
  ## When not to use it
44
43
 
@@ -46,6 +45,9 @@ In short live tests on Sonnet 5.5, 98.3% of a warm turn's input came from the ca
46
45
  - You're short on memory. Each parked session keeps a Claude process in memory.
47
46
  - You expect to run into usage credits. A turn billed to credits fails, unless you set `PI_CLAUDE_CLI_ALLOW_USAGE_CREDITS=1`.
48
47
  - You want several accounts without reading the rules. The tether supports them, but check Anthropic's terms first.
48
+ - Your tools run for a very long time. The tether waits 30 minutes for a tool by default, then stops that Claude process, and the next turn imports the history again. I haven't tested a real tool against that limit.
49
+ - You need Pi's `onProviderStreamEvent` hook. The Claude CLI doesn't expose the raw stream, so the tether can't call it. The other provider hooks work.
50
+ - You run it in a restricted sandbox and don't want to open anything up. It needs a short writable folder for its sockets, plus the Claude profile and state folders. If one is missing, the error tells you which.
49
51
 
50
52
  ## More
51
53
 
package/docs/DETAILS.md CHANGED
@@ -138,3 +138,11 @@ MIT license, copyright (c) 2026 Rebecca Chernoff — see [LICENSE](../LICENSE).
138
138
  ## How I measured
139
139
 
140
140
  The cache figures in the README come from short live tests of the packed release candidate on two machines, using Sonnet 5.5 in a real Pi session with a warm follow-up turn on one CLI process. The percentage is the input read from cache divided by all input on that turn. These tests show the cache works across a follow-up. They don't compare the tether with the direct API.
141
+
142
+ ## Long tools and current limits
143
+
144
+ A Pi tool handoff can wait 30 minutes by default; if no continuation arrives, the tether interrupts and retires that blocked CLI process. A later continuation must reimport. This is **not** the ordinary parked-process lifetime: between completed turns the default follows the observed prompt-cache expiry. The official CLI also receives a default `MCP_TOOL_TIMEOUT` of one hour, unless already set. During an active CLI episode, five minutes without stdout triggers the tether's default inactivity timeout. These are code paths, not proof that a real tool survived each boundary. Abort and steering during tools beyond these boundaries remain unqualified.
145
+
146
+ Pi's `onProviderStreamEvent` hook is currently **not called** by this tether. Claude CLI emits its own stream-json events rather than exposing the underlying HTTP stream; consumers cannot assume direct-API event visibility. The other provider hooks are separate.
147
+
148
+ For restricted children, the launcher must grant a short, writable runtime directory for sockets as well as the required Claude profile and state paths. A failed runtime allocation reports the underlying error and points to `TMPDIR`, `XDG_RUNTIME_DIR` and sandbox grants; a blocked optional session sidecar instead loses resume mapping and causes reimport. The tether does not repair sandbox grants or authenticate a profile.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-claude-tether",
3
- "version": "0.11.0",
3
+ "version": "0.11.1",
4
4
  "description": "Use your Claude subscription in Pi through the official Claude Code CLI",
5
5
  "main": "index.ts",
6
6
  "keywords": [
@@ -58,6 +58,7 @@
58
58
  "format:check": "prettier --check .",
59
59
  "test:e2e": "bash scripts/e2e-stub.sh",
60
60
  "test:e2e:continuity": "out=$(mktemp -d); python3 scripts/continuity-proof.py --pi-bin \"$(node scripts/resolve-pi-cli.mjs)\" --source-extension-dir . --output-dir \"$out/proof\" --stub --transient-retry",
61
+ "test:e2e:refresh": "out=$(mktemp -d); python3 scripts/continuity-proof.py --pi-bin \"$(node scripts/resolve-pi-cli.mjs)\" --source-extension-dir . --output-dir \"$out/proof\" --stub --scenario transient --refresh-retry",
61
62
  "test:e2e:failover": "out=$(mktemp -d); python3 scripts/continuity-proof.py --pi-bin \"$(node scripts/resolve-pi-cli.mjs)\" --source-extension-dir . --output-dir \"$out/proof\" --stub --failover"
62
63
  },
63
64
  "engines": {
@@ -181,7 +181,8 @@ if (!process.env.CONTINUITY_OBSERVER_OWNER_PID) {
181
181
  if (seeded) {
182
182
  const receipt = receipts[0];
183
183
  const expectedSha256 = sha(JSON.stringify(receipt.content));
184
- receipt.content = [{type:'text',text:'SEEDED-RECEIPT-BODY-LOSS'}];
184
+ receipt.content = process.env.CONTINUITY_RECEIPT_SHAPE === 'long-error' && typeof receipt.content === 'string'
185
+ ? '!' + receipt.content.slice(1) : [{type:'text',text:'SEEDED-RECEIPT-BODY-LOSS'}];
185
186
  raw = JSON.stringify(m);
186
187
  emit({type:'seeded_receipt_mismatch',pid:child.pid,toolUseId:receipt.tool_use_id,
187
188
  expectedSha256,observedSha256:sha(JSON.stringify(receipt.content))});
@@ -325,8 +326,12 @@ function user(msg) {
325
326
  turn.delivered = true;
326
327
  lastToolResult = textOf(response.content);
327
328
  // Verified CLI 2.1.283 representation: only single-text errors trim.
328
- const echo = response.isError && response.content?.length === 1 && response.content[0].type === 'text'
329
+ let echo = response.isError && response.content?.length === 1 && response.content[0].type === 'text'
329
330
  ? response.content[0].text.trim() : response.content;
331
+ // Official error codec (2.1.284/2.1.311): 10k retained, 1024 allowance.
332
+ // This stub qualifies the receipt boundary, never live cache economics.
333
+ if (response.isError && typeof echo === 'string' && echo.length > 11024)
334
+ echo = echo.slice(0,5000) + `\n\n... [${echo.length-10000} characters truncated] ...\n\n` + echo.slice(-5000);
330
335
  emit({type:'user',message:{role:'user',content:[{type:'tool_result',tool_use_id:id,
331
336
  content:echo,is_error:!!response.isError}]},session_id:session,parent_tool_use_id:null});
332
337
  if (mode === 'plain') {
@@ -339,9 +344,19 @@ function user(msg) {
339
344
  return;
340
345
  }
341
346
  if (text.includes('CONTINUITY-RETRY')) {
342
- if (retrySeen) throw new Error('Transient retry resent the original failed user/prefix');
343
- retrySeen = true;
344
- result('Request timed out'); return;
347
+ if (process.env.CONTINUITY_REFRESH_RETRY !== '1') {
348
+ if (retrySeen) throw new Error('Transient retry resent the original failed user/prefix');
349
+ retrySeen = true;
350
+ result('Request timed out'); return;
351
+ }
352
+ const markerFile = process.env.CONTINUITY_STUB_LOG + '.refresh-seen';
353
+ if (!fs.existsSync(markerFile)) {
354
+ fs.writeFileSync(markerFile, 'failed before model');
355
+ trace({type:'refresh_failure_before_model'});
356
+ result('Failed to refresh OAuth token: another Claude Code process is refreshing it or exited mid-refresh. This is usually transient; retry in a minute, and if it persists close other Claude Code processes or sign in again'); return;
357
+ }
358
+ trace({type:'refresh_retry_received_user'});
359
+ cycle('RETRY-OK'); result(); return;
345
360
  }
346
361
  if (failover && !failoverB && text.includes('FAILOVER')) { limitRejected(); return; }
347
362
  let marker;
@@ -1033,6 +1048,8 @@ async def run(args):
1033
1048
  env["PI_CLAUDE_CLI_ALLOW_USAGE_CREDITS"] = "1"
1034
1049
  if args.seed_receipt_mismatch:
1035
1050
  env["CONTINUITY_RECEIPT_SEED"] = str(output / "receipt-mismatch.seed")
1051
+ if args.refresh_retry:
1052
+ env["CONTINUITY_REFRESH_RETRY"] = "1"
1036
1053
  if args.context:
1037
1054
  env["PI_CLAUDE_CLI_CONTEXT"] = args.context
1038
1055
  if args.stub_cli or args.stub:
@@ -1155,7 +1172,7 @@ async def run(args):
1155
1172
  if message.get("responseModel") and message["responseModel"] != MODEL:
1156
1173
  raise RuntimeError("Native assistant physical response model differs")
1157
1174
  if message.get("stopReason") in ("error", "aborted"):
1158
- if not (native_retry and message is not messages[-1] and message.get("stopReason") == "error" and "timed out" in message.get("errorMessage", "").lower()):
1175
+ if not (native_retry and message is not messages[-1] and message.get("stopReason") == "error" and ("timed out" in message.get("errorMessage", "").lower() or "failed to refresh oauth token" in message.get("errorMessage", "").lower())):
1159
1176
  raise RuntimeError(f"Unexpected native assistant stop: {message.get('stopReason')}")
1160
1177
  text = "".join(b.get("text", "") for b in messages[-1].get("content", []) if b.get("type") == "text").strip()
1161
1178
  if text != marker:
@@ -1340,7 +1357,7 @@ async def run(args):
1340
1357
  qualification_failures.append("Native Pi did not exit cleanly")
1341
1358
  if measurements["physicalCoverageGaps"] or not measurements["physicalRequests"]:
1342
1359
  qualification_failures.append("Physical request accounting has explicit coverage gaps")
1343
- expected_starts = 3 if args.failover else (2 if args.seed_receipt_mismatch else 1)
1360
+ expected_starts = 3 if args.failover else (2 if args.seed_receipt_mismatch or args.refresh_retry else 1)
1344
1361
  if measurements["totalCliStarts"] != expected_starts:
1345
1362
  qualification_failures.append("Unexpected main CLI process count for the requested seeded/non-seeded workload")
1346
1363
  cli_rows = [json.loads(line) for line in (output / "cli-metadata.jsonl").read_text().splitlines()]
@@ -1359,6 +1376,12 @@ async def run(args):
1359
1376
  old_exit = [row for row in cli_rows if row.get("pid") == starts[0]["pid"] and row.get("type") in ("cli_exit", "cli_close")]
1360
1377
  if not old_exit or min(int(row["seq"]) for row in old_exit) >= int(starts[1]["seq"]):
1361
1378
  qualification_failures.append("Replacement spawned before old-process termination was observed")
1379
+ if args.refresh_retry:
1380
+ stub_rows = [json.loads(line) for line in (output / "stub-events.jsonl").read_text().splitlines()]
1381
+ failures = [row for row in stub_rows if row.get("type") == "refresh_failure_before_model"]
1382
+ retries = [row for row in stub_rows if row.get("type") == "refresh_retry_received_user"]
1383
+ if len(failures) != 1 or len(retries) != 1 or failures[0]["pid"] == retries[0]["pid"]:
1384
+ qualification_failures.append("Refresh retry did not reimport the user through a new CLI after the seeded pre-model failure")
1362
1385
  if args.failover:
1363
1386
  qualification_failures.extend(failover_qualification(output, measurements, manifest))
1364
1387
  if args.overage:
@@ -1392,15 +1415,18 @@ def main():
1392
1415
  route.add_argument("--stub-cli", type=Path, help="Executable continuity-compatible Claude fixture; disposable HOME, no live credential route")
1393
1416
  parser.add_argument("--failover", action="store_true", help="Stub-only multi-account failover: stub rejects under the default profile and answers under account b")
1394
1417
  parser.add_argument("--overage", choices=("deny", "allow"), help="Stub-only usage-credit guard: stub bills the turn to overage; deny expects the guard failure, allow expects success with PI_CLAUDE_CLI_ALLOW_USAGE_CREDITS=1")
1395
- parser.add_argument("--receipt-shape", choices=("synthetic-error", "error-outer-whitespace", "synthetic-read", "image-derivative", "multi-text-error"), help="Synthetic failed-bash error, large read, image derivative, or multi-text error shape (generated fixture; src/tests unchanged)")
1418
+ parser.add_argument("--receipt-shape", choices=("synthetic-error", "error-outer-whitespace", "synthetic-read", "image-derivative", "multi-text-error", "long-error"), help="Synthetic failed-bash error, large read, image derivative, or multi-text error shape (generated fixture; src/tests unchanged)")
1396
1419
  parser.add_argument("--expected-cli-version", help="Exact physical CLI version required by this qualification")
1397
1420
  parser.add_argument("--parallel-handoff", action="store_true", help="Request two results in the same native handoff")
1398
1421
  parser.add_argument("--seed-receipt-mismatch", action="store_true", help="Rewrite one synthetic stdout receipt to prove transparent retirement/replay")
1399
1422
  parser.add_argument("--scenario", choices=("all", "abort", "steer", "transient", "receipt"), default="all", help="Independent continuity scenario; baseline-tool and warm-followup are always included")
1400
1423
  parser.add_argument("--transient-retry", action="store_true", help="Stub-only: synthesize one timeout then require native Pi parked retry")
1424
+ parser.add_argument("--refresh-retry", action="store_true", help="Stub-only: synthesize pre-model refresh contention and require native Pi retry")
1401
1425
  args = parser.parse_args()
1402
1426
  if args.installed_pi_bin and not (args.stub or args.stub_cli):
1403
1427
  parser.error("--installed-pi-bin is restricted to stub qualification")
1428
+ if args.refresh_retry:
1429
+ args.transient_retry = True
1404
1430
  if args.live and (args.transient_retry or args.scenario == "transient"):
1405
1431
  parser.error("Transient injection is a deterministic fixture workload, never a fabricated live timeout")
1406
1432
  if args.failover and not args.stub:
@@ -27,6 +27,7 @@ import { createHash, randomUUID } from "node:crypto";
27
27
  import { createInterface } from "node:readline";
28
28
  import { parseLine } from "./stream-parser.js";
29
29
  import { matchesDerivativeImages, receiptImageHeader } from "./receipt-image.js";
30
+ import { errorTruncation } from "./receipt-error.js";
30
31
  import { removeSessionMcpConfig } from "./mcp-config.js";
31
32
  import { handleControlRequest } from "./control-handler.js";
32
33
  import {
@@ -434,9 +435,11 @@ export class CliProcess implements HandoffTarget {
434
435
  const expectedContent = canonicalHandoffContent(receipt.result.content);
435
436
  const observedContent = canonicalHandoffContent(block.content);
436
437
  const sameContent = JSON.stringify(observedContent) === JSON.stringify(expectedContent);
438
+ const truncation = sameError && !sameContent ? errorTruncation(receipt.result, block.content) : undefined;
437
439
  if (!sameError || (!sameContent &&
438
440
  !matchesTrimmedErrorEcho(receipt.result, block.content) &&
439
441
  !matchesFlattenedErrorEcho(receipt.result, block.content) &&
442
+ !truncation &&
440
443
  !matchesDerivativeImages(expectedContent, observedContent))) {
441
444
  // A same-ID generic denial is not the Pi result, even for isError=true.
442
445
  const expected = receiptMetadata(receipt.result.content, !!receipt.result.isError);
@@ -450,6 +453,7 @@ export class CliProcess implements HandoffTarget {
450
453
  void this.retire(["handoff_receipt_mismatch"], { toolUseId: block.tool_use_id, kinds, expected, observed });
451
454
  return;
452
455
  }
456
+ if (truncation) this.ledger?.toolResultLoss(block.tool_use_id, truncation);
453
457
  this.deliveryWaiters.delete(block.tool_use_id);
454
458
  receipt.settle(true);
455
459
  }
@@ -1,5 +1,4 @@
1
1
  /** Configurable context has one loader; execution remains Claude-native. */
2
- import { TOOL_MAPPINGS } from "./tool-mapping.js";
3
2
 
4
3
  export const PI_CONTEXT_MARKER = '<pi_context_policy version="1">';
5
4
  export class ContextPolicyError extends Error {}
@@ -63,82 +62,13 @@ export function assertContextCliVersion(output: string): void {
63
62
 
64
63
  export function usesPiContext(env: NodeJS.ProcessEnv = process.env): boolean {
65
64
  const value = (env.PI_CLAUDE_CLI_CONTEXT ?? "pi").trim().toLowerCase();
66
- if (value === "pi") return true;
67
- if (!value || value === "legacy") return false;
65
+ if (!value || value === "pi") return true;
66
+ if (value === "legacy") return false;
68
67
  throw new ContextPolicyError(
69
68
  "PI_CLAUDE_CLI_CONTEXT must be 'pi' or 'legacy'.",
70
69
  );
71
70
  }
72
71
 
73
- /**
74
- * Only edit pi's generated preamble, never user directives, project files or
75
- * skill contents. Keep custom-tool guidance (especially artifacts) intact.
76
- * The boundary is intentionally narrow: unknown/custom prompts pass through
77
- * with an explicit vocabulary binding rather than being rewritten blindly.
78
- */
79
- export function alignPiContext(prompt: string): string {
80
- const boundary = prompt.indexOf("\n\nPi documentation (");
81
- if (
82
- prompt.startsWith(
83
- "You are an expert coding assistant operating inside pi,",
84
- ) &&
85
- boundary !== -1
86
- ) {
87
- const names = new Map(TOOL_MAPPINGS.map((m) => [m.pi, m.claude]));
88
- const descriptions: Record<string, string> = {
89
- read: "Read file contents using the native Read schema (file_path).",
90
- write:
91
- "Create or overwrite a file using the native Write schema (file_path, content).",
92
- edit: "Replace exact text using native Edit (file_path, old_string, new_string); use separate calls for disjoint replacements.",
93
- bash: "Execute commands using the native Bash schema.",
94
- };
95
- let preamble = prompt.slice(0, boundary);
96
- preamble = preamble.replace(
97
- /(^Available tools:\n)([\s\S]*?)(?=\n\n)/m,
98
- (_, heading, tools: string) =>
99
- heading +
100
- // Grep/Glob are not present in every CLI/model inventory. Do not
101
- // advertise them based solely on pi's registry; binding below covers search.
102
- tools
103
- .replace(/^- (?:grep|find):.*(?:\n|$)/gm, "")
104
- .replace(/^(- )(\w+)(:.*)$/gm, (_, lead, name, rest) =>
105
- names.has(name)
106
- ? `${lead}${names.get(name)}: ${descriptions[name]}`
107
- : `${lead}mcp__custom-tools__${name}${rest}`,
108
- ),
109
- );
110
- // These are pi Edit's semantics, not Claude Code Edit's. Other tool and
111
- // artifact guidelines survive, as does the complete suffix below.
112
- preamble = preamble
113
- .split("\n")
114
- // `edits[]` is pi's edit signature; native Edit takes one old_string per
115
- // call. So ANY line naming that array is wrong here, whatever its
116
- // wording — that is the rule, rather than a list of the phrasings pi
117
- // happens to ship. Enumerating them missed "Keep edits[].oldText as
118
- // small as possible…" in pi 0.85.1, and it reached live sessions.
119
- .filter((line) => !line.includes("edits[]"))
120
- .map((line) =>
121
- line.replace(
122
- /\b(Use|use|Prefer|prefer) (read|write|edit|bash|grep|find)\b/g,
123
- (_, verb, tool) =>
124
- `${verb} ${tool === "grep" || tool === "find" ? "available native search tools (or Bash)" : names.get(tool)}`,
125
- ),
126
- )
127
- .join("\n");
128
- prompt = preamble + prompt.slice(boundary);
129
- }
130
- return [
131
- PI_CONTEXT_MARKER,
132
- "pi supplies the project instructions, skill index and custom integrations below. Do not independently discover Claude skills or memory.",
133
- "Claude Code retains its default system prompt and native coding tools. In pi-authored instructions, read/write/edit/bash refer to native Read/Write/Edit/Bash. For grep/find, use native search tools only if actually advertised; otherwise use Bash. Use actual tool schemas, not pi argument names.",
134
- "Native Edit uses file_path, old_string and new_string, not pi's multi-edit array. Native Read/Write use file_path. Other pi tools use their advertised mcp__custom-tools__ names and unchanged schemas; this includes artifacts and the pi MCP gateway.",
135
- "Load a listed pi skill with native Read at its exact path. Preserve .pi paths; they are not aliases for .claude. Only the supplied skill index defines the available pi skills.",
136
- "</pi_context_policy>",
137
- "",
138
- prompt,
139
- ].join("\n");
140
- }
141
-
142
72
  /** A policy change cannot safely reuse the CLI's hidden history/pinned prompt. */
143
73
  export function assertContextPolicy(
144
74
  storedPrompt: string | undefined,
package/src/provider.ts CHANGED
@@ -1642,6 +1642,18 @@ export function streamViaCli(
1642
1642
  finishEpisode();
1643
1643
  return;
1644
1644
  }
1645
+ if (piOwned && !sawHandoffTool && !live.hasUnconfirmedHandoffResults &&
1646
+ bridge.getOutput().content.length === 0 &&
1647
+ [r.usage?.input_tokens, r.usage?.output_tokens, r.usage?.cache_read_input_tokens, r.usage?.cache_creation_input_tokens].every(value => value === 0) &&
1648
+ /^Failed to refresh OAuth token: another Claude Code process is refreshing it or exited mid-refresh\./i.test(String(errMsg))) {
1649
+ // The CLI could not obtain credentials for this request. Retire
1650
+ // its session; Pi alone decides whether to retry the user turn.
1651
+ if (piSessionId) clearCliSession(piSessionId);
1652
+ clearSystemPrompt(live.cliSessionId);
1653
+ void discardProcess();
1654
+ endStreamWithError(`server error: ${errMsg}`);
1655
+ return;
1656
+ }
1645
1657
  if (piOwned && isTransientApiError(String(errMsg))) {
1646
1658
  applyResultUsage(r);
1647
1659
  live.turnReported = ZERO_USAGE;
@@ -0,0 +1,59 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { HandoffResult } from "./handoff-broker.js";
3
+
4
+ /** Official Claude Code 2.1.284/2.1.311 error codec: 10,000 UTF-16 units,
5
+ * with a 1,024-unit no-truncation allowance. These are vendor constants,
6
+ * not adapter limits. The middle is replaced by the exact counted marker.
7
+ * Qualified against native receipt hashes and real Pi; never applies to
8
+ * successes, images, unknown parts, or arbitrary same-ID replacement text.
9
+ */
10
+ const ERROR_KEEP = 10_000;
11
+ const ERROR_ALLOWANCE = 1_024;
12
+ const marker = /\n\n\.\.\. \[(\d+) characters truncated\] \.\.\.\n\n/g;
13
+ export type ErrorTruncation = {
14
+ rule: "claude-error-middle-v1";
15
+ evidence: "declared-lossy";
16
+ modelVisibility: "middle-omitted";
17
+ originalChars: number;
18
+ omittedChars: number;
19
+ omittedSha256: string;
20
+ };
21
+
22
+ function projection(text: string): { echo: string; evidence: ErrorTruncation } | undefined {
23
+ if (text.length <= ERROR_KEEP + ERROR_ALLOWANCE) return;
24
+ let head = text.slice(0, ERROR_KEEP / 2);
25
+ let tail = text.slice(-ERROR_KEEP / 2);
26
+ // The official client does not bisect surrogate pairs at either edge.
27
+ if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
28
+ if (/^[\uDC00-\uDFFF]/.test(tail)) tail = tail.slice(1);
29
+ const omitted = text.slice(head.length, text.length - tail.length);
30
+ let count = omitted.length;
31
+ // The native codec carries forward counts from already-truncated text.
32
+ const middle = text.slice(ERROR_KEEP / 2, text.length - ERROR_KEEP / 2);
33
+ for (const match of middle.matchAll(marker)) {
34
+ // The native codec only carries decimal counts of at most 15 digits.
35
+ const n = match[1].length <= 15 ? Number(match[1]) : NaN;
36
+ if (Number.isSafeInteger(n) && n >= match[0].length) count += n - match[0].length;
37
+ }
38
+ return {
39
+ echo: `${head}\n\n... [${count} characters truncated] ...\n\n${tail}`,
40
+ evidence: { rule: "claude-error-middle-v1", evidence: "declared-lossy",
41
+ modelVisibility: "middle-omitted", originalChars: text.length,
42
+ omittedChars: omitted.length,
43
+ omittedSha256: createHash("sha256").update(omitted).digest("hex") },
44
+ };
45
+ }
46
+
47
+ /** Positional verification, not global marker replacement. Surviving bytes,
48
+ * status, part kinds and the native omission count must all agree. The model
49
+ * sees the explicit native marker; the ledger separately discloses the loss.
50
+ */
51
+ export function errorTruncation(result: HandoffResult, echo: unknown): ErrorTruncation | undefined {
52
+ if (!result.isError || typeof echo !== "string" || !result.content.length ||
53
+ !result.content.every(part => part.type === "text" && typeof part.text === "string")) return;
54
+ const text = result.content.map(part => (part as { text: string }).text).join("\n");
55
+ for (const candidate of [text, text.trim()]) {
56
+ const projected = projection(candidate);
57
+ if (projected?.echo === echo) return projected.evidence;
58
+ }
59
+ }
@@ -5,6 +5,7 @@ import { join } from "node:path";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { packageLedgerDir } from "./data-dir.js";
7
7
  import type { ReceiptImageHeader } from "./receipt-image.js";
8
+ import type { ErrorTruncation } from "./receipt-error.js";
8
9
 
9
10
  // One ordered, best-effort writer. No request awaits it; no rotation or limits.
10
11
  // Disk/write failure, host process.exit() or SIGKILL can lose pending rows;
@@ -181,6 +182,9 @@ export class RequestLedger {
181
182
  this.flushDetached();
182
183
  this.record("retire", { reasons, ...(handoffReceiptMismatch ? { handoffReceiptMismatch } : {}) });
183
184
  }
185
+ toolResultLoss(toolUseId: string, loss: ErrorTruncation): void {
186
+ this.record("tool_result_vendor_truncation", { toolUseId, ...loss });
187
+ }
184
188
  exit(code: number | null): void {
185
189
  this.flushDetached();
186
190
  this.record("process_exit", { exitCode: code });
@@ -1,3 +1,28 @@
1
1
  import { createRuntimeDirectory } from "pi-tether-core/runtime";
2
2
  export { RUNTIME_FILE_MODE, HANDOFF_SOCKET_NAME } from "pi-tether-core/runtime";
3
- export const { runtimeDir, existingRuntimeDir, runtimeFile, cleanupRuntimeDir, resetRuntimeDirForTests } = createRuntimeDirectory("pi-claude-");
3
+
4
+ const runtime = createRuntimeDirectory("pi-claude-");
5
+ export const {
6
+ existingRuntimeDir,
7
+ cleanupRuntimeDir,
8
+ resetRuntimeDirForTests,
9
+ } = runtime;
10
+
11
+ /** Name the failing boundary without claiming an unrelated login is broken. */
12
+ export function runtimeDir(): string {
13
+ try {
14
+ return runtime.runtimeDir();
15
+ } catch (error) {
16
+ const detail = error instanceof Error ? error.message : String(error);
17
+ throw new Error(
18
+ `Claude tether runtime directory unavailable: ${detail}. Check TMPDIR and XDG_RUNTIME_DIR and the sandbox write grants.`,
19
+ { cause: error },
20
+ );
21
+ }
22
+ }
23
+
24
+ export function runtimeFile(name: string): string {
25
+ // Ensure allocation failures get the same diagnostic on every entry path.
26
+ runtimeDir();
27
+ return runtime.runtimeFile(name);
28
+ }
@@ -17,7 +17,13 @@
17
17
  * given pi session at a time.
18
18
  */
19
19
 
20
- import { readFileSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
20
+ import {
21
+ readFileSync,
22
+ writeFileSync,
23
+ mkdirSync,
24
+ rmSync,
25
+ chmodSync,
26
+ } from "node:fs";
21
27
  import { join } from "node:path";
22
28
  import { packageStateDir } from "./data-dir.js";
23
29
  import { isEphemeral } from "./env-flag.js";
@@ -166,7 +172,9 @@ export function setSystemPrompt(cliSessionId: string, prompt: string): void {
166
172
  if (isEphemeral()) return;
167
173
  try {
168
174
  mkdirSync(join(stateDir(), "sysprompt"), { recursive: true });
169
- writeFileSync(systemPromptPath(cliSessionId), prompt, "utf-8");
175
+ const path = systemPromptPath(cliSessionId);
176
+ writeFileSync(path, prompt, { encoding: "utf-8", mode: 0o600 });
177
+ chmodSync(path, 0o600);
170
178
  } catch {
171
179
  // Best effort: an unwritable sidecar degrades to rebuilding the prompt.
172
180
  }
@@ -68,6 +68,12 @@ export default function (pi: ExtensionAPI) {
68
68
  // A fresh result nonce cannot be guessed from prior markers or mode names.
69
69
  // Synthetic failure payload exercises Unicode and whitespace preservation.
70
70
  const shape = process.env.CONTINUITY_RECEIPT_SHAPE;
71
+ if (shape === "long-error" && mode === "plain") {
72
+ // 15,344 chars is the measured production error, not a transport cap.
73
+ const text = ("ERROR_HEAD\\n" + "synthetic-error-data ".repeat(15344)).slice(0, 15334) + "ERROR_TAIL";
74
+ record(ctx, { type: "tool_return", mode, toolCallId, resultText: text });
75
+ throw new Error(text);
76
+ }
71
77
  const syntheticError = (shape === "synthetic-error" || shape === "error-outer-whitespace") && mode === "plain";
72
78
  const syntheticRead = shape === "synthetic-read" && mode === "plain";
73
79
  const syntheticBody = "─".repeat(112) + "é".repeat(7) + "x".repeat(483);