pi-claude-tether 0.12.0 → 0.12.2
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 +17 -1
- package/README.md +2 -0
- package/docs/DETAILS.md +27 -13
- package/docs/REQUEST-LEDGER.md +2 -2
- package/index.ts +32 -1
- package/package.json +1 -1
- package/scripts/continuity-proof.py +26 -7
- package/src/account-command.ts +35 -2
- package/src/accounts.ts +124 -10
- package/src/cli-process.ts +2 -2
- package/src/control-handler.ts +1 -2
- package/src/handoff-broker.ts +2 -2
- package/src/process-manager.ts +6 -6
- package/src/provider.ts +22 -47
- package/src/removed-config.ts +6 -4
- package/src/startup-notices.ts +19 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.12.2 — 2026-11-20
|
|
4
|
+
|
|
5
|
+
- Removed the tether’s five-minute silence timeout and its override. A silent turn keeps running until Claude finishes, the CLI exits, or you press Stop.
|
|
6
|
+
- Long Pi tools no longer trigger Claude Code’s hidden follow-up at the default 30-minute stdio idle limit. The tether disables that idle watchdog by default for Pi MCP tools and keeps the handoff parked within the existing one-hour default budget.
|
|
7
|
+
- update-cli.sh from an installed package no longer demands Pi 1.4.0: the stub proof accepts stable Pi patches at or above the package's pinned Pi version in the same series.
|
|
8
|
+
|
|
9
|
+
## 0.12.1 — 2026-11-10
|
|
10
|
+
|
|
11
|
+
- Failover no longer needs a shell variable: `/claude-accounts failover on|off` stores it in the settings file and applies from the next turn. `PI_CLAUDE_TETHER_FAILOVER` remains an optional per-process override and now accepts Pi's boolean words (`1`/`true`/`yes`, `0`/`false`/`no`); any other value is ignored with a notice instead of silently turning failover off. `/claude-accounts` shows which setting decided.
|
|
12
|
+
- The account settings file moves to Pi's agent directory, `~/.pi/agent/pi-claude-tether.json` (following `PI_CODING_AGENT_DIR`), like other Pi extensions' settings. An existing 0.12.0 `~/.local/share/pi-claude-tether/accounts.json` is moved once with a notice; logins stay where they are.
|
|
13
|
+
- Configuration notices (retired `PI_CLAUDE_CLI_*` variables, an unrecognised value, the moved file) now appear as Pi notifications when a session starts, also when provider setup fails. Previously they went to the console, which Pi's interactive screen does not show.
|
|
14
|
+
- New "Where settings live" documentation, including why a shell or tmux session opened before editing shell files keeps old values.
|
|
15
|
+
- Tests no longer read or write the developer's real Pi agent or data directories.
|
|
16
|
+
|
|
17
|
+
Upgrading from 0.12.0: nothing is required. To drop the shell variables, run `/claude-accounts failover on` once (this also records env-declared accounts in the settings file), then remove the `PI_CLAUDE_TETHER_ACCOUNTS`/`PI_CLAUDE_TETHER_FAILOVER` exports and start Pi from a new shell.
|
|
18
|
+
|
|
3
19
|
## 0.12.0 — 2026-11-10
|
|
4
20
|
|
|
5
21
|
- New Claude models without waiting for a Pi release: models Claude Code's own catalog offers (for example Fable 5.2 on launch day) are added to `/model` next to Pi's built-in list, and a running Pi picks them up after the turn that refreshed the catalog.
|
|
@@ -25,7 +41,7 @@ export PI_CLAUDE_TETHER_ACCOUNTS="${PI_CLAUDE_TETHER_ACCOUNTS:-default,b}"
|
|
|
25
41
|
export PI_CLAUDE_TETHER_FAILOVER="${PI_CLAUDE_TETHER_FAILOVER:-1}"
|
|
26
42
|
```
|
|
27
43
|
|
|
28
|
-
Remove their old `PI_CLAUDE_CLI_ACCOUNTS` / `PI_CLAUDE_CLI_FAILOVER` definitions and
|
|
44
|
+
Remove their old `PI_CLAUDE_CLI_ACCOUNTS` / `PI_CLAUDE_CLI_FAILOVER` definitions and start Pi from a new shell: an already open shell, or a tmux session's saved environment, keeps the old values. (0.12.1 makes these exports optional; see above.) For any optional exports, replace the `PI_CLAUDE_CLI_` prefix with `PI_CLAUDE_TETHER_` for these supported suffixes: `ACCOUNT`, `ACCOUNTS`, `FAILOVER`, `ALLOW_USAGE_CREDITS`, `HANDOFF_PROXY`, `HANDOFF_WAIT_MS`, `KEEPALIVE_MS`, `SETTINGS`, `STATE_DIR`, `STRICT_VERSION`, `THINKING_DISPLAY`. No old variable is read as configuration. Remove the old `CONTEXT` switch instead of renaming it; there is no legacy mode to select. Remove the legacy-only `PI_CLAUDE_CLI_SYSTEM_PROMPT`, `PI_CLAUDE_CLI_AUTOCOMPACT`, `PI_CLAUDE_CLI_HERMETIC`, `PI_CLAUDE_CLI_STRICT_MCP`, `PI_CLAUDE_CLI_EPHEMERAL`, `PI_CLAUDE_CLI_TOOL_RESULTS`, `PI_CLAUDE_CLI_NO_AGENT_WAIT` and `PI_CLAUDE_CLI_AGENT_WAIT_MS` exports; their renamed spellings are not supported either. Pi always supplies isolation, owns compaction and executes tools.
|
|
29
45
|
|
|
30
46
|
A corrupt `session-map.json` in the state directory now fails closed instead of being ignored, and blocks every Claude turn, including in new sessions, until it is repaired or removed. The error names the state directory; starting a fresh Pi session alone does not clear it.
|
|
31
47
|
|
package/README.md
CHANGED
|
@@ -28,6 +28,8 @@ The tether reads that folder by default, so this login stays separate from any C
|
|
|
28
28
|
|
|
29
29
|
The tether runs the official Claude Code CLI and keeps one process alive per session and account, so follow-up turns and tool calls stay on the same process. Pi's system prompt replaces the Claude Code one, every tool runs in Pi, and Pi owns the history. Your login stays in the CLI, and the tether never reads it.
|
|
30
30
|
|
|
31
|
+
For several Claude accounts, use `/claude-accounts` inside Pi to add, switch and turn on failover. It saves everything in `~/.pi/agent/pi-claude-tether.json`, so no shell setup is needed. [Where settings live](docs/DETAILS.md#where-settings-live) explains the optional environment variables.
|
|
32
|
+
|
|
31
33
|
In short live tests on Sonnet 5.5, 98.3% of a warm turn's input came from the cache on one machine and 99.1% on another. I haven't published a comparison with the direct API yet.
|
|
32
34
|
|
|
33
35
|
## Why not something else
|
package/docs/DETAILS.md
CHANGED
|
@@ -47,19 +47,30 @@ See [the context contract](CONTEXT-POLICY.md).
|
|
|
47
47
|
|
|
48
48
|
## Configuration
|
|
49
49
|
|
|
50
|
-
The defaults above require no
|
|
50
|
+
The defaults above require no configuration at all.
|
|
51
|
+
|
|
52
|
+
### Where settings live
|
|
53
|
+
|
|
54
|
+
| What | Where | When it is read |
|
|
55
|
+
| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
|
|
56
|
+
| Accounts, default account, failover | `~/.pi/agent/pi-claude-tether.json` (Pi's agent directory; `$PI_CODING_AGENT_DIR` when set), written by `/claude-accounts` | On every turn and command, so changes apply without restarting Pi |
|
|
57
|
+
| Claude logins | One directory per account under `~/.local/share/pi-claude-tether/` (`$XDG_DATA_HOME` when set), owned by the official CLI | By the CLI, per account |
|
|
58
|
+
| Optional overrides | `PI_CLAUDE_TETHER_*` environment variables (table below) | Once, when Pi starts |
|
|
59
|
+
|
|
60
|
+
Use `/claude-accounts` for accounts and failover; you do not need to edit shell files. Environment variables are optional per-launch overrides for scripts, aliases and special setups. A program receives its environment from the shell that starts it, so after editing `~/.bashrc` or a similar file, start Pi from a **new** shell: a shell that was already open, or a tmux/screen session (tmux keeps its own saved copy of the environment for new windows), still carries the old values. `/claude-accounts` shows when a variable is overriding the settings file. Configuration notices (an unrecognised value, retired variables) appear as Pi notifications when a session starts.
|
|
51
61
|
|
|
52
62
|
| Variable | Default | Purpose |
|
|
53
63
|
| -------------------------------------- | ------------ | ----------------------------------------------------------------------------------------------------------------- |
|
|
54
64
|
| `PI_CLAUDE_TETHER_ACCOUNT` | `default` | This process's Claude profile; see Multiple Claude profiles |
|
|
55
|
-
| `PI_CLAUDE_TETHER_ACCOUNTS` | `default` |
|
|
65
|
+
| `PI_CLAUDE_TETHER_ACCOUNTS` | `default` | Extra declared profiles, e.g. `default,b`, listed before the settings file's accounts |
|
|
66
|
+
| `PI_CLAUDE_TETHER_FAILOVER` | unset | Overrides the settings file for this process: `1`/`true`/`yes` on, `0`/`false`/`no` off; other values are ignored |
|
|
56
67
|
| `PI_CLAUDE_TETHER_KEEPALIVE_MS` | cache TTL | Idle process lifetime; unset = until its prompt cache expires (1h on the subscription CLI); `0` for one-shot runs |
|
|
57
68
|
| `PI_CLAUDE_TETHER_SETTINGS` | unset | Explicit host Claude settings, including guard hooks |
|
|
58
|
-
| `PI_CLAUDE_TETHER_TIMEOUT_MS` | `300000` | Maximum stdout inactivity |
|
|
59
69
|
| `PI_CLAUDE_TETHER_HANDOFF_PROXY` | enabled | `0` disables proxy continuity; Pi still executes tools, with full-history reimports instead |
|
|
60
|
-
| `PI_CLAUDE_TETHER_HANDOFF_WAIT_MS` | `
|
|
70
|
+
| `PI_CLAUDE_TETHER_HANDOFF_WAIT_MS` | `3600000` | Time before retiring the CLI parked on a Pi tool; does not stop the Pi tool |
|
|
61
71
|
| `PI_CLAUDE_TETHER_THINKING_DISPLAY` | `summarized` | `omitted` returns no thinking summaries |
|
|
62
|
-
| `MCP_TOOL_TIMEOUT` | `3600000` |
|
|
72
|
+
| `MCP_TOOL_TIMEOUT` | `3600000` | Claude Code's overall MCP tool timeout; not a silence timer |
|
|
73
|
+
| `CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT` | `0` | Defaults to disabled in the tether's Claude subprocess with Pi MCP tools; explicit values still win |
|
|
63
74
|
| `PI_CLAUDE_TETHER_STRICT_VERSION` | unset | `1` refuses a CLI newer than the tested range instead of warning once and continuing |
|
|
64
75
|
| `PI_CLAUDE_TETHER_ALLOW_USAGE_CREDITS` | unset | `1` allows turns billed to overage usage credits instead of failing them |
|
|
65
76
|
|
|
@@ -67,7 +78,9 @@ Pi owns context and execution unconditionally in 0.12.0. There is no context-mod
|
|
|
67
78
|
|
|
68
79
|
### Multiple Claude profiles
|
|
69
80
|
|
|
70
|
-
One Pi process uses exactly one Claude subscription.
|
|
81
|
+
One Pi process uses exactly one Claude subscription at a time. Declare accounts with `/claude-accounts add <name>`, choose one with `/claude-accounts switch <name>` (add `--default` for future sessions), and let a limit move the turn to the next account with `/claude-accounts failover on`. All of this is stored in the settings file and needs no shell configuration.
|
|
82
|
+
|
|
83
|
+
Optionally, `PI_CLAUDE_TETHER_ACCOUNTS` (e.g. `default,b`) declares accounts from the environment, and `PI_CLAUDE_TETHER_ACCOUNT` chooses the profile a process starts on, so a shell alias starts Pi on a second account:
|
|
71
84
|
|
|
72
85
|
```bash
|
|
73
86
|
alias pi-b='PI_CLAUDE_TETHER_ACCOUNT=b pi'
|
|
@@ -83,16 +96,17 @@ Inside Pi, `/claude-accounts` (or `list`/`ls`) lists accounts. The official CLI
|
|
|
83
96
|
| `status [name]` | Auth status and requested/CLI-reported `configDirectory`, exhaustion, and last observed ledger utilization/reset with its age. These are observations, not live quota. |
|
|
84
97
|
| `switch <name> [--session]` | Select a verified account for subsequent turns and record a session custom entry (never sent to the model). |
|
|
85
98
|
| `switch <name> --default` | Also persist the default for future Pi sessions. |
|
|
99
|
+
| `failover [on\|off]` | Show, or persist in the settings file, whether a reached subscription limit moves the turn to the next ready account. Applies from the next turn. `PI_CLAUDE_TETHER_FAILOVER` overrides it for its process, and the output says so. |
|
|
86
100
|
| `remove <name> [--revoke] [--purge] [--force]` | Unregister, keeping the directory by default. `--revoke` invokes the CLI's `auth logout`; `--purge` deletes the directory only after confirmation. Active/last removal requires `--force`. Env-declared names must first be removed from the launch environment. |
|
|
87
101
|
| `doctor` | CLI executable/version versus tested range, account directory existence, credential-file **presence only**, auth-status parse health and exhaustion. |
|
|
88
102
|
|
|
89
|
-
|
|
103
|
+
The settings file `~/.pi/agent/pi-claude-tether.json` is the declaration/default/failover store: `{ "accounts": [{ "name": "work", "email": "…", "plan": "…", "addedAt": "…" }], "default": "work", "failover": true }`. Version 0.12.0 kept it at `~/.local/share/pi-claude-tether/accounts.json`; 0.12.1 moves that file once, with a notice, and never reads the old location again. The move never overwrites a newer file; on a filesystem without hard links it is left to you, and the notice says where. It contains no credentials; optional `console`/`sso` booleans retain the CLI login method for re-login. An added name is initially `pending: true`, visible for retry/removal but unavailable for switching, spawning or failover; only successful CLI completion followed by `auth status` verification clears pending and records identity metadata. A cancelled/failed add therefore remains safely removable. Login has no adapter deadline: the CLI completes, the user cancels the input, or the command signal aborts it.
|
|
90
104
|
|
|
91
|
-
Selection precedence is the latest session switch entry/runtime choice, then `PI_CLAUDE_TETHER_ACCOUNT` from launch, then `
|
|
105
|
+
Selection precedence is the latest session switch entry/runtime choice, then `PI_CLAUDE_TETHER_ACCOUNT` from launch, then the settings file's `default`, then `default`. This permits launching a `pi-b` alias and switching back to `default` inside Pi. A resumed session restores its choice; a no-longer-declared choice falls back to launch/default. Switching retires the warm CLI process. The original launch selection is captured once and never read back from the mutable environment. The effective selection is separately published to `PI_CLAUDE_TETHER_ACCOUNT` for child Pi processes, so subagents started after a switch inherit it; the parent's session custom entry remains its restoration owner.
|
|
92
106
|
|
|
93
|
-
Declarations and failover ordering are the env list first (its order preserved), then unique
|
|
107
|
+
Declarations and failover ordering are the env list first (its order preserved), then unique settings-file entries in file order; without a declaration file, the existing default-only behavior is unchanged. When env declarations are absent and the file exists, its entries alone declare the set, so unregistering the default (or forcing last removal) does not silently re-add it. The first UI declaration write preserves the currently declared set (including an implicit default), so adding or re-logging in an env-declared account does not silently unregister the other existing profiles. Pending accounts are skipped by failover. All names pass the same name gate.
|
|
94
108
|
|
|
95
|
-
`default` is the existing profile (`~/.local/share/pi-claude-tether/claude-config`, no re-login). Any other name `N` resolves to `~/.local/share/pi-claude-tether/accounts/N/claude-config` (under `$XDG_DATA_HOME` when set); authenticate it once with `CLAUDE_CONFIG_DIR=<that dir> claude auth login --claudeai`. Names must match `[A-Za-z0-9._-]` with no path separators, and a named account must be declared in `PI_CLAUDE_TETHER_ACCOUNTS` or
|
|
109
|
+
`default` is the existing profile (`~/.local/share/pi-claude-tether/claude-config`, no re-login). Any other name `N` resolves to `~/.local/share/pi-claude-tether/accounts/N/claude-config` (under `$XDG_DATA_HOME` when set); authenticate it once with `CLAUDE_CONFIG_DIR=<that dir> claude auth login --claudeai`. Names must match `[A-Za-z0-9._-]` with no path separators, and a named account must be declared in `PI_CLAUDE_TETHER_ACCOUNTS` or the settings file; anything else fails the turn with an explicit configuration error. Each account's spawns, version probes and auth probes run under its own directory, and the account is part of the launch signature, so a warm process is never reused across profiles. Unset, or exactly `default`, behaves exactly as before; a single named entry runs under its own directory (`accounts/<name>/claude-config`).
|
|
96
110
|
|
|
97
111
|
The prompt cache is per account: a profile change costs a full context reimport plus a cache write on the other account. Keeping a process warm avoids resending history on follow-ups and tool handoffs; it does not send periodic requests, guarantee a cache hit, reduce token usage, or change your subscription allowance. Users must check Anthropic's current consumer terms themselves before operating more than one subscription.
|
|
98
112
|
|
|
@@ -159,11 +173,11 @@ The cache figures in the README come from short live tests of the packed release
|
|
|
159
173
|
|
|
160
174
|
Each point below was verified in code and then passed once live: real installed `pi` in RPC mode with only this extension, the real Claude Code CLI (2.1.321), model `claude-haiku-5-5` (run under the provider id before the 0.12.0 rename), default account, scratch state dirs, and a Pi custom tool that sleeps a chosen duration and returns a marker. Times are UTC, 2026-11-10. The request ledger (`retire.log`) is metadata-only by design: it proves timing, episodes and causes, never bodies.
|
|
161
175
|
|
|
162
|
-
- **
|
|
176
|
+
- **Silent turns.** The tether does not time out a turn for lack of CLI output. A turn can finish normally, report an unexpected CLI exit, or be cancelled with Pi’s Stop.
|
|
163
177
|
|
|
164
|
-
- **
|
|
178
|
+
- **Handoff park expiry: retire and reimport.** The tether interrupts and retires a CLI process that stays parked waiting for Pi past `PI_CLAUDE_TETHER_HANDOFF_WAIT_MS`. Pi's tool keeps running. After it returns, the tether imports the transcript into a fresh CLI process. This is separate from the between-turn lifetime that follows prompt-cache expiry. The default park now uses the same one-hour budget as the default `MCP_TOOL_TIMEOUT`, rather than retiring at 30 minutes.
|
|
165
179
|
|
|
166
|
-
- **
|
|
180
|
+
- **MCP idle timeout: distinct from the wall-clock limit.** Claude Code's [stdio idle watchdog](https://code.claude.com/docs/en/env-vars#claude-code-mcp-tool-idle-timeout) defaults to 30 minutes without a response or progress notification. Pi's proxy waits silently for Pi to finish the tool. Extending just the park allowed Claude to end the MCP wait and make a detached model request while Pi's tool still ran. The tether defaults the CLI's idle watchdog to `0` when it configures Pi's MCP server, without changing the CLI's hard `MCP_TOOL_TIMEOUT`. Explicit overrides still apply; a CLI tool timeout shorter than the park can still end Claude's wait before Pi returns.
|
|
167
181
|
|
|
168
182
|
**Abort and steering during a long tool.**
|
|
169
183
|
|
package/docs/REQUEST-LEDGER.md
CHANGED
|
@@ -12,7 +12,7 @@ Every row includes `at` (UTC observation timestamp), `processId` (adapter-minted
|
|
|
12
12
|
- `request`: exactly one row for each top-level `message_start` through `message_stop`. Nested `parent_tool_use_id` streams are excluded. `physicalModel` comes from `message_start.message.model`. `requestId` is an adapter UUID, not an Anthropic HTTP request ID. `usage` includes `input`, `cacheRead`, `cacheWrite`, `output`, `cacheWrite1h`, `cacheWrite5m`. Start usage is replaced only by fields actually emitted in `message_delta`; counters are never added within a request. Missing tier breakdowns stay null.
|
|
13
13
|
- `result`: raw CLI envelope counters projected into `usage`; separately, `cumulativeModelUsage` contains each model's process-cumulative counters and cost. `totalCostUsd`, `numTurns`, and `reportedCliSessionId` are preserved. **Never add result usage, cumulative model usage, or results from successive turns to request rows.** To measure process-cumulative change, difference successive cumulative snapshots. Result model totals can include CLI auxiliary model calls not exposed as top-level requests.
|
|
14
14
|
- `rate_limit`: emitted utilization fraction, `windowType`, `resetsAt`, status and overage metadata. Missing utilization stays null. Older recorded streams omit it; persistence cannot create the missing signal. No allowance-percent estimate is fabricated. Concurrent account use confounds episode attribution; a window switch/reset breaks any utilization delta. Claude subscription percent is not additive with another subscription's percent or API dollars.
|
|
15
|
-
- `retire`: `reasons`, including launch-signature/history changes, thinking-control failure, keepalive disabled/expiry, cache expired/`cache_expiry` (the parked lifetime follows the observed cache TTL), handoff wait expiry, no Pi session, result/episode errors, unconfirmed steer consumption (`steer_unconfirmed`), failed steer write (`steer_write_error`), resume miss, abort,
|
|
15
|
+
- `retire`: `reasons`, including launch-signature/history changes, thinking-control failure, keepalive disabled/expiry, cache expired/`cache_expiry` (the parked lifetime follows the observed cache TTL), handoff wait expiry, no Pi session, result/episode errors, unconfirmed steer consumption (`steer_unconfirmed`), failed steer write (`steer_write_error`), resume miss, abort, agent-wait expiry, stdout closure, process exit, pool replacement and exact lifecycle event names (`model_select`, `session_compact`, `session_tree`, `session_shutdown`, `session_start`, `beforeExit`). Signature values are never logged. A replacement's `spawnCause` carries the previous retirement cause when known in the same host process; after a host restart it is `firstProcess`, not a guessed cross-process cause.
|
|
16
16
|
- `process_exit`: observed child-process exit code, separate from its retirement reason.
|
|
17
17
|
|
|
18
18
|
## Detached work and limits of coverage
|
|
@@ -25,6 +25,6 @@ No prompt text, tools' schemas/descriptions, tool arguments/results, result text
|
|
|
25
25
|
|
|
26
26
|
## Proof
|
|
27
27
|
|
|
28
|
-
`tests/request-ledger.test.ts` drives the shipped adapter using the hand-written synthetic `multi-cycle-episode.jsonl` stream. It proves all three request rows, 1h/5m splits, separate result/model totals, nested exclusion, handoff/turn reuse, emitted and absent utilization, buffered attribution, exact keepalive/lifecycle/
|
|
28
|
+
`tests/request-ledger.test.ts` drives the shipped adapter using the hand-written synthetic `multi-cycle-episode.jsonl` stream. It proves all three request rows, 1h/5m splits, separate result/model totals, nested exclusion, handoff/turn reuse, emitted and absent utilization, buffered attribution, exact keepalive/lifecycle/exit reasons, existing-file permissions, seeded body rejection and seeded double-count rejection. The handoff variant renames the synthetic ToolSearch call to a Pi-proxied tool; the cumulative-follow-up/rate-utilization cases explicitly enrich the synthetic frames. No fixture test spends subscription tokens.
|
|
29
29
|
|
|
30
30
|
For a live proof use Pi's documented extension path: `pi -ne -e /absolute/path/to/package/index.ts --model pi-claude-tether/claude-sonnet-5-5 -p ...`, in a disposable workspace with `XDG_STATE_HOME` set to a temporary directory. Limit the task itself to one Pi read tool call. Use the documented one-shot `PI_CLAUDE_TETHER_KEEPALIVE_MS=0`; this changes only the proof invocation, not production defaults. Inspect Pi's tool-call/result events and compare the **request-only** sum to the separately retained CLI result `usage` and main-model cumulative snapshot, reporting any auxiliary-model difference explicitly.
|
package/index.ts
CHANGED
|
@@ -24,7 +24,10 @@ import {
|
|
|
24
24
|
writeAccounts,
|
|
25
25
|
captureLaunchAccount,
|
|
26
26
|
isAccountPending,
|
|
27
|
+
migrateAccountsStore,
|
|
28
|
+
failoverSetting,
|
|
27
29
|
} from "./src/accounts.js";
|
|
30
|
+
import { addStartupNotice, takeStartupNotices } from "./src/startup-notices.js";
|
|
28
31
|
import {
|
|
29
32
|
ACCOUNT_ENTRY_TYPE,
|
|
30
33
|
accountsReport,
|
|
@@ -180,8 +183,33 @@ async function ensureHandoffSocket(): Promise<string | undefined> {
|
|
|
180
183
|
return handoffSocket;
|
|
181
184
|
}
|
|
182
185
|
|
|
186
|
+
/** Deliver load-time configuration notices where the user can see them. */
|
|
187
|
+
function flushStartupNotices(ctx: unknown): void {
|
|
188
|
+
const c = ctx as
|
|
189
|
+
| { hasUI?: boolean; ui?: { notify?: (m: string, l: string) => void } }
|
|
190
|
+
| undefined;
|
|
191
|
+
for (const message of takeStartupNotices()) {
|
|
192
|
+
if (c?.hasUI && c.ui?.notify)
|
|
193
|
+
c.ui.notify(`pi-claude-tether: ${message}`, "warning");
|
|
194
|
+
else console.warn(`[pi-claude-tether] ${message}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
183
198
|
export default function (pi: ExtensionAPI) {
|
|
184
199
|
warnRemovedEnvironment();
|
|
200
|
+
try {
|
|
201
|
+
migrateAccountsStore();
|
|
202
|
+
failoverSetting(); // validates the variable once, raising a notice if unrecognised
|
|
203
|
+
} catch (error) {
|
|
204
|
+
addStartupNotice(
|
|
205
|
+
`Claude account settings unavailable: ${error instanceof Error ? error.message : String(error)}`,
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
// Registered before provider setup so notices still arrive when it fails
|
|
209
|
+
// (for example, a missing CLI).
|
|
210
|
+
pi.on("session_start", (_event: unknown, ctx: unknown) =>
|
|
211
|
+
flushStartupNotices(ctx),
|
|
212
|
+
);
|
|
185
213
|
guardRemovedSessionProvider(pi);
|
|
186
214
|
try {
|
|
187
215
|
// Startup validation
|
|
@@ -325,7 +353,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
325
353
|
|
|
326
354
|
pi.registerCommand("claude-accounts", {
|
|
327
355
|
description:
|
|
328
|
-
"Manage official CLI accounts: list, add, login, status, switch, remove, doctor",
|
|
356
|
+
"Manage official CLI accounts: list, add, login, status, switch, remove, failover, doctor",
|
|
329
357
|
getArgumentCompletions: (prefix: string) => {
|
|
330
358
|
const options = [
|
|
331
359
|
"list",
|
|
@@ -333,6 +361,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
333
361
|
"login --all",
|
|
334
362
|
"status",
|
|
335
363
|
"doctor",
|
|
364
|
+
"failover on",
|
|
365
|
+
"failover off",
|
|
336
366
|
...parseAccountSet()
|
|
337
367
|
.filter((name) => !isAccountPending(name))
|
|
338
368
|
.map((name) => `switch ${name}`),
|
|
@@ -344,6 +374,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
344
374
|
},
|
|
345
375
|
handler: async (args, ctx) => {
|
|
346
376
|
const parsed = parseAccountArgs(args);
|
|
377
|
+
flushStartupNotices(ctx);
|
|
347
378
|
try {
|
|
348
379
|
if (parsed.action === "switch") {
|
|
349
380
|
const account = selectAccount(parsed.account);
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""Native
|
|
2
|
+
"""Native Pi RPC continuity proof; explicit source loading only.
|
|
3
3
|
|
|
4
4
|
Live (uses your Claude Haiku subscription; never runs on import/help):
|
|
5
5
|
python3 continuity-proof.py --source-extension-dir /checkout/integrations/pi-claude-tether \
|
|
@@ -31,6 +31,7 @@ import subprocess
|
|
|
31
31
|
from datetime import datetime
|
|
32
32
|
import os
|
|
33
33
|
from pathlib import Path
|
|
34
|
+
import re
|
|
34
35
|
import shutil
|
|
35
36
|
import signal
|
|
36
37
|
import sys
|
|
@@ -60,9 +61,8 @@ def package_data_dir(source: Path, home: Path) -> Path:
|
|
|
60
61
|
base = Path(os.environ.get("XDG_DATA_HOME") or (home / ".local/share"))
|
|
61
62
|
return base / "pi-claude-tether"
|
|
62
63
|
return home / ".local/share/pi-claude-cli"
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
SUPPORTED_INSTALLED_PI_VERSION = "1.4.0"
|
|
64
|
+
|
|
65
|
+
|
|
66
66
|
SYSTEM = ("This is a synthetic continuity proof. Call continuity_tool exactly once when asked, "
|
|
67
67
|
"using precisely the requested mode. Use no other tools. After its result, reply only "
|
|
68
68
|
"with the requested marker. Obey newer user steering over older instructions. "
|
|
@@ -432,6 +432,26 @@ def resolve_owned_pi(pi_bin_arg, source, *, allow_missing=False):
|
|
|
432
432
|
return Path(owned["cli"]), owned["version"]
|
|
433
433
|
|
|
434
434
|
|
|
435
|
+
def check_pi_version(source, version, exit_code, expected_version):
|
|
436
|
+
if expected_version is not None:
|
|
437
|
+
matches = version == expected_version
|
|
438
|
+
requirement = expected_version
|
|
439
|
+
else:
|
|
440
|
+
# Without an owned SDK, the updater accepts stable patches at or above
|
|
441
|
+
# the shipped devDependency pin, within the same major/minor series.
|
|
442
|
+
pin = json.loads((source / "package.json").read_text())["devDependencies"]["@earendil-works/pi-coding-agent"]
|
|
443
|
+
stable = r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
|
|
444
|
+
pinned = re.fullmatch(stable, pin) if isinstance(pin, str) else None
|
|
445
|
+
if not pinned:
|
|
446
|
+
raise RuntimeError("The Pi devDependency must pin a stable version")
|
|
447
|
+
observed = re.fullmatch(stable, version)
|
|
448
|
+
matches = bool(observed and observed.groups()[:2] == pinned.groups()[:2]
|
|
449
|
+
and int(observed[3]) >= int(pinned[3]))
|
|
450
|
+
requirement = f"{pin} or a newer patch in the same series"
|
|
451
|
+
if exit_code or not matches:
|
|
452
|
+
raise RuntimeError(f"Required Pi {requirement}; observed {version!r}")
|
|
453
|
+
|
|
454
|
+
|
|
435
455
|
def dump(path, data):
|
|
436
456
|
path.write_text(json.dumps(data, indent=2) + "\n")
|
|
437
457
|
|
|
@@ -1001,7 +1021,7 @@ async def run(args):
|
|
|
1001
1021
|
# Explicit updater-only exception; ordinary fixtures never infer this route.
|
|
1002
1022
|
pi = Path(args.installed_pi_bin).resolve(strict=True)
|
|
1003
1023
|
owned = resolve_owned_pi(None, source, allow_missing=True)
|
|
1004
|
-
expected_version = owned[1] if owned else
|
|
1024
|
+
expected_version = owned[1] if owned else None
|
|
1005
1025
|
else:
|
|
1006
1026
|
pi, expected_version = resolve_owned_pi(args.pi_bin, source)
|
|
1007
1027
|
if not pi.is_file() or not os.access(pi, os.X_OK):
|
|
@@ -1071,8 +1091,7 @@ async def run(args):
|
|
|
1071
1091
|
version_stdout, version_stderr = await version_process.communicate()
|
|
1072
1092
|
version = version_stdout.decode().strip()
|
|
1073
1093
|
dump(output / "pi-version.json", {"argv": [str(pi), "-ne", "--version"], "version": version, "exitCode": version_process.returncode, "stderrBytes": len(version_stderr)})
|
|
1074
|
-
|
|
1075
|
-
raise RuntimeError(f"Required Pi {expected_version}; observed {version!r}")
|
|
1094
|
+
check_pi_version(source, version, version_process.returncode, expected_version)
|
|
1076
1095
|
argv = [str(pi), "--mode", "rpc", "-ne", "-e", str(entry), "-e", str(fixture),
|
|
1077
1096
|
"--provider", PROVIDER, "--model", MODEL, "--thinking", "off",
|
|
1078
1097
|
"--session-dir", str(output / "sessions"), "--system-prompt", SYSTEM +
|
package/src/account-command.ts
CHANGED
|
@@ -12,6 +12,8 @@ import {
|
|
|
12
12
|
writeAccounts,
|
|
13
13
|
isAccountPending,
|
|
14
14
|
accountsForUpdate,
|
|
15
|
+
failoverSetting,
|
|
16
|
+
accountsPath,
|
|
15
17
|
} from "./accounts.js";
|
|
16
18
|
import {
|
|
17
19
|
cliAuthStatus,
|
|
@@ -28,7 +30,7 @@ import { accountAuth, type AccountUI } from "./account-login.js";
|
|
|
28
30
|
|
|
29
31
|
export const ACCOUNT_ENTRY_TYPE = "pi-claude-tether.account";
|
|
30
32
|
export const ACCOUNT_USAGE =
|
|
31
|
-
"Usage: /claude-accounts [list|ls] | add <name> [--email e] [--sso] [--console] | login <name>|--all | status [name] | switch <name> [--session|--default] | remove <name> [--revoke] [--purge] [--force] | doctor";
|
|
33
|
+
"Usage: /claude-accounts [list|ls] | add <name> [--email e] [--sso] [--console] | login <name>|--all | status [name] | switch <name> [--session|--default] | remove <name> [--revoke] [--purge] [--force] | failover [on|off] | doctor";
|
|
32
34
|
|
|
33
35
|
export function sessionAccount(
|
|
34
36
|
branch: ReadonlyArray<{ type?: string; customType?: string; data?: unknown }>,
|
|
@@ -105,7 +107,7 @@ export async function accountsReport(
|
|
|
105
107
|
const resets = new Map(
|
|
106
108
|
accountResetTimes(set).map((r) => [r.account, r.resetsAt]),
|
|
107
109
|
);
|
|
108
|
-
const lines = ["Claude accounts (* = this session):"];
|
|
110
|
+
const lines = ["Claude accounts (* = this session):", failoverLine()];
|
|
109
111
|
if (selectionError) lines.push(`Selection unavailable: ${selectionError}`);
|
|
110
112
|
if (!set.length)
|
|
111
113
|
lines.push("No accounts declared. Use /claude-accounts add <name>.");
|
|
@@ -161,8 +163,19 @@ export async function accountsReport(
|
|
|
161
163
|
return lines.join("\n");
|
|
162
164
|
}
|
|
163
165
|
|
|
166
|
+
/** Failover state and the setting that decided it. */
|
|
167
|
+
export function failoverLine(): string {
|
|
168
|
+
const { enabled, source } = failoverSetting();
|
|
169
|
+
const file = readAccounts().failover;
|
|
170
|
+
if (source === "environment")
|
|
171
|
+
return `Failover: ${enabled ? "on" : "off"} (set by PI_CLAUDE_TETHER_FAILOVER in this Pi's environment${file === undefined ? "" : `, overriding the settings file's ${file ? "on" : "off"}`}; unset it and start Pi from a new shell to use /claude-accounts failover)`;
|
|
172
|
+
if (source === "accounts") return `Failover: on (${accountsPath()})`;
|
|
173
|
+
return "Failover: off (enable with /claude-accounts failover on)";
|
|
174
|
+
}
|
|
175
|
+
|
|
164
176
|
type Parsed =
|
|
165
177
|
| { action: "list" | "doctor" | "usage" }
|
|
178
|
+
| { action: "failover"; enabled?: boolean }
|
|
166
179
|
| { action: "status"; account?: string }
|
|
167
180
|
| { action: "switch"; account: string; persistent?: true }
|
|
168
181
|
| {
|
|
@@ -186,6 +199,12 @@ export function parseAccountArgs(args: string): Parsed {
|
|
|
186
199
|
const action = words.shift() ?? "list";
|
|
187
200
|
if (["list", "ls", "doctor"].includes(action) && !words.length)
|
|
188
201
|
return { action: action === "doctor" ? "doctor" : "list" };
|
|
202
|
+
if (action === "failover" && words.length <= 1) {
|
|
203
|
+
if (!words.length) return { action };
|
|
204
|
+
if (words[0] === "on" || words[0] === "off")
|
|
205
|
+
return { action, enabled: words[0] === "on" };
|
|
206
|
+
return { action: "usage" };
|
|
207
|
+
}
|
|
189
208
|
if (action === "status" && words.length <= 1 && !words[0]?.startsWith("--"))
|
|
190
209
|
return { action, ...(words[0] ? { account: words[0] } : {}) };
|
|
191
210
|
const account = words.shift();
|
|
@@ -255,6 +274,20 @@ export async function manageAccount(
|
|
|
255
274
|
);
|
|
256
275
|
return;
|
|
257
276
|
}
|
|
277
|
+
if (parsed.action === "failover") {
|
|
278
|
+
if (parsed.enabled !== undefined) {
|
|
279
|
+
const store = accountsForUpdate();
|
|
280
|
+
// Record every currently declared account (including env-declared
|
|
281
|
+
// ones) so dropping the shell exports afterwards loses nothing.
|
|
282
|
+
for (const name of parseAccountSet())
|
|
283
|
+
if (!store.accounts.some((a) => a.name === name))
|
|
284
|
+
store.accounts.push({ name });
|
|
285
|
+
store.failover = parsed.enabled;
|
|
286
|
+
writeAccounts(store);
|
|
287
|
+
}
|
|
288
|
+
ui.notify(failoverLine(), "info");
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
258
291
|
if (parsed.action === "login" && "all" in parsed) {
|
|
259
292
|
for (const account of parseAccountSet()) {
|
|
260
293
|
const status = await cliAuthStatus(accountConfigDir(account), signal);
|
package/src/accounts.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Claude account profiles: manual selection plus opt-in failover exhaustion.
|
|
3
3
|
*
|
|
4
4
|
* One Pi process uses exactly one account. The ordered set is declared with
|
|
5
|
-
* PI_CLAUDE_TETHER_ACCOUNTS (e.g. "default,b") plus
|
|
5
|
+
* PI_CLAUDE_TETHER_ACCOUNTS (e.g. "default,b") plus settings-file entries.
|
|
6
6
|
* Selection follows runtime/session choice, captured launch account, stored
|
|
7
7
|
* default, then the existing profile. Launch example:
|
|
8
8
|
* `pi-b='PI_CLAUDE_TETHER_ACCOUNT=b pi'`.
|
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
* package data dir comes from src/data-dir.ts, which derives the directory
|
|
12
12
|
* from the installed package name.
|
|
13
13
|
*
|
|
14
|
-
* Automatic failover between accounts is OFF unless
|
|
14
|
+
* Automatic failover between accounts is OFF unless enabled in the settings
|
|
15
|
+
* file (`failover: true`, set with /claude-accounts failover on) or, per
|
|
16
|
+
* process, by PI_CLAUDE_TETHER_FAILOVER. A recognised variable overrides it.
|
|
15
17
|
* When on, a rejected subscription limit marks that account exhausted until
|
|
16
18
|
* the resetsAt the CLI itself reported, and the request is retried on the
|
|
17
19
|
* next non-exhausted account. The expiry comes only from CLI events; nothing
|
|
@@ -23,14 +25,21 @@
|
|
|
23
25
|
*/
|
|
24
26
|
|
|
25
27
|
import {
|
|
28
|
+
constants,
|
|
29
|
+
copyFileSync,
|
|
26
30
|
existsSync,
|
|
31
|
+
linkSync,
|
|
27
32
|
mkdirSync,
|
|
28
33
|
readFileSync,
|
|
29
34
|
renameSync,
|
|
35
|
+
rmSync,
|
|
36
|
+
unlinkSync,
|
|
30
37
|
writeFileSync,
|
|
31
38
|
} from "node:fs";
|
|
32
|
-
import { join } from "node:path";
|
|
33
|
-
import {
|
|
39
|
+
import { dirname, join } from "node:path";
|
|
40
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
41
|
+
import { packageDataDir, packageLeaf } from "./data-dir.js";
|
|
42
|
+
import { addStartupNotice } from "./startup-notices.js";
|
|
34
43
|
import { stateDir } from "./session-map.js";
|
|
35
44
|
|
|
36
45
|
export interface AccountDeclaration {
|
|
@@ -45,6 +54,7 @@ export interface AccountDeclaration {
|
|
|
45
54
|
export interface AccountsStore {
|
|
46
55
|
accounts: AccountDeclaration[];
|
|
47
56
|
default?: string;
|
|
57
|
+
failover?: boolean;
|
|
48
58
|
}
|
|
49
59
|
let sessionSelection: string | undefined;
|
|
50
60
|
let launchSelection: { account: string } | undefined;
|
|
@@ -55,10 +65,82 @@ export function captureLaunchAccount(): string {
|
|
|
55
65
|
return launchSelection.account;
|
|
56
66
|
}
|
|
57
67
|
|
|
68
|
+
/**
|
|
69
|
+
* The declaration/default/failover store, in Pi's agent directory like other
|
|
70
|
+
* extension settings (`<agent-dir>/pi-claude-tether.json`, honouring
|
|
71
|
+
* PI_CODING_AGENT_DIR). Claude login directories stay in the data directory.
|
|
72
|
+
*/
|
|
58
73
|
export function accountsPath(): string {
|
|
74
|
+
return join(getAgentDir(), `${packageLeaf()}.json`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 0.12.0 kept the store at <data-dir>/accounts.json. */
|
|
78
|
+
export function legacyAccountsPath(): string {
|
|
59
79
|
return join(packageDataDir(), "accounts.json");
|
|
60
80
|
}
|
|
61
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Move a 0.12.0 store to the agent directory once. The old path is never read
|
|
84
|
+
* as configuration; if both exist, the new one wins and the old one is named.
|
|
85
|
+
*/
|
|
86
|
+
export function migrateAccountsStore(): void {
|
|
87
|
+
const from = legacyAccountsPath();
|
|
88
|
+
const to = accountsPath();
|
|
89
|
+
if (!existsSync(from)) return;
|
|
90
|
+
mkdirSync(dirname(to), { recursive: true });
|
|
91
|
+
const published = publishNoClobber(from, to);
|
|
92
|
+
if (published === "unsupported") {
|
|
93
|
+
addStartupNotice(
|
|
94
|
+
`Could not move ${from} to ${to} automatically: this filesystem has no hard links, needed to move it without risking a newer file. Move it yourself; until then the old file is not read.`,
|
|
95
|
+
);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (!published) {
|
|
99
|
+
addStartupNotice(
|
|
100
|
+
`Ignoring old ${from}; account settings now live in ${to}. Delete the old file once you have checked it.`,
|
|
101
|
+
);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
unlinkSync(from);
|
|
105
|
+
addStartupNotice(`Moved Claude account settings from ${from} to ${to}.`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Publish `from` at `to` only if `to` does not exist, atomically: a hard link
|
|
110
|
+
* fails with EEXIST instead of replacing a file another Pi process wrote, and
|
|
111
|
+
* readers never see a partly written file. Across filesystems the copy is
|
|
112
|
+
* staged next to `to` and linked from there. Returns false when `to` already
|
|
113
|
+
* exists and "unsupported" when the filesystem has no hard links; the source
|
|
114
|
+
* is never removed here.
|
|
115
|
+
*/
|
|
116
|
+
export function publishNoClobber(
|
|
117
|
+
from: string,
|
|
118
|
+
to: string,
|
|
119
|
+
link: (source: string, target: string) => void = linkSync,
|
|
120
|
+
): boolean | "unsupported" {
|
|
121
|
+
const linkOnce = (source: string): boolean | "unsupported" => {
|
|
122
|
+
try {
|
|
123
|
+
link(source, to);
|
|
124
|
+
return true;
|
|
125
|
+
} catch (error) {
|
|
126
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
127
|
+
if (code === "EEXIST") return false;
|
|
128
|
+
if (code === "EXDEV" || code === "EPERM" || code === "ENOTSUP")
|
|
129
|
+
return "unsupported";
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
const direct = linkOnce(from);
|
|
134
|
+
if (direct !== "unsupported") return direct;
|
|
135
|
+
const staged = `${to}.${process.pid}.migrate`;
|
|
136
|
+
copyFileSync(from, staged, constants.COPYFILE_EXCL);
|
|
137
|
+
try {
|
|
138
|
+
return linkOnce(staged);
|
|
139
|
+
} finally {
|
|
140
|
+
rmSync(staged, { force: true });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
62
144
|
/** Only our declaration file, never the CLI's credential store. */
|
|
63
145
|
export function readAccounts(): AccountsStore {
|
|
64
146
|
let body: string;
|
|
@@ -94,6 +176,8 @@ export function readAccounts(): AccountsStore {
|
|
|
94
176
|
throw new Error("Invalid accounts.json default");
|
|
95
177
|
checkName(parsed.default, "accounts.json default", parsed.default);
|
|
96
178
|
}
|
|
179
|
+
if (parsed.failover !== undefined && typeof parsed.failover !== "boolean")
|
|
180
|
+
throw new Error("Invalid accounts.json failover: expected true or false");
|
|
97
181
|
return parsed;
|
|
98
182
|
}
|
|
99
183
|
|
|
@@ -107,7 +191,7 @@ export function accountsForUpdate(): AccountsStore {
|
|
|
107
191
|
|
|
108
192
|
/** Atomic declaration update; no credential or cached authentication state. */
|
|
109
193
|
export function writeAccounts(store: AccountsStore): void {
|
|
110
|
-
mkdirSync(
|
|
194
|
+
mkdirSync(dirname(accountsPath()), { recursive: true });
|
|
111
195
|
const tmp = `${accountsPath()}.${process.pid}.tmp`;
|
|
112
196
|
writeFileSync(tmp, JSON.stringify(store, null, 2) + "\n", { mode: 0o600 });
|
|
113
197
|
renameSync(tmp, accountsPath());
|
|
@@ -239,13 +323,40 @@ export function isSingleDefaultAccountSet(set: string[]): boolean {
|
|
|
239
323
|
return set.length === 1 && set[0] === DEFAULT_ACCOUNT;
|
|
240
324
|
}
|
|
241
325
|
|
|
326
|
+
// Pi's own boolean environment vocabulary (PI_TELEMETRY).
|
|
327
|
+
const ENV_ON = new Set(["1", "true", "yes"]);
|
|
328
|
+
const ENV_OFF = new Set(["0", "false", "no"]);
|
|
329
|
+
let warnedFailoverValue = false;
|
|
330
|
+
|
|
242
331
|
/**
|
|
243
|
-
* Whether a rejected subscription limit may replay on another account
|
|
332
|
+
* Whether a rejected subscription limit may replay on another account, and
|
|
333
|
+
* which setting decided it.
|
|
244
334
|
*
|
|
245
|
-
*
|
|
335
|
+
* PI_CLAUDE_TETHER_FAILOVER decides for this process when it is 1/true/yes or
|
|
336
|
+
* 0/false/no; any other non-empty value is ignored with a notice. Otherwise
|
|
337
|
+
* the settings file's `failover: true` enables. The file is read on each call, so a change made
|
|
338
|
+
* with /claude-accounts applies from the next turn without restarting Pi.
|
|
246
339
|
*/
|
|
340
|
+
export function failoverSetting(env: NodeJS.ProcessEnv = process.env): {
|
|
341
|
+
enabled: boolean;
|
|
342
|
+
source: "environment" | "accounts" | "default";
|
|
343
|
+
} {
|
|
344
|
+
const value = (env.PI_CLAUDE_TETHER_FAILOVER ?? "").trim().toLowerCase();
|
|
345
|
+
if (ENV_ON.has(value)) return { enabled: true, source: "environment" };
|
|
346
|
+
if (ENV_OFF.has(value)) return { enabled: false, source: "environment" };
|
|
347
|
+
if (value !== "" && !warnedFailoverValue) {
|
|
348
|
+
warnedFailoverValue = true;
|
|
349
|
+
addStartupNotice(
|
|
350
|
+
"Ignoring PI_CLAUDE_TETHER_FAILOVER: expected 1, true, yes, 0, false or no. Using /claude-accounts failover instead.",
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
if (readAccounts().failover === true)
|
|
354
|
+
return { enabled: true, source: "accounts" };
|
|
355
|
+
return { enabled: false, source: "default" };
|
|
356
|
+
}
|
|
357
|
+
|
|
247
358
|
export function failoverEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
248
|
-
return (env.
|
|
359
|
+
return failoverSetting(env).enabled;
|
|
249
360
|
}
|
|
250
361
|
|
|
251
362
|
/** The CLAUDE_CONFIG_DIR a spawn or probe for this account must use. */
|
|
@@ -350,9 +461,12 @@ export function selectFailoverAccount(
|
|
|
350
461
|
* call — then the first fresh account in set order, so a later spawn
|
|
351
462
|
* before resetsAt stays on the account that answered.
|
|
352
463
|
*/
|
|
353
|
-
export function pickInitialAccount(
|
|
464
|
+
export function pickInitialAccount(
|
|
465
|
+
set: string[],
|
|
466
|
+
failover: boolean = failoverEnabled(),
|
|
467
|
+
): string {
|
|
354
468
|
const pinned = selectedAccountName(set);
|
|
355
|
-
if (!
|
|
469
|
+
if (!failover) return pinned;
|
|
356
470
|
if (!isAccountExhausted(pinned)) return pinned;
|
|
357
471
|
return selectFailoverAccount(set, pinned) ?? pinned;
|
|
358
472
|
}
|
package/src/cli-process.ts
CHANGED
|
@@ -140,7 +140,7 @@ const ONE_HOUR_CACHE_TTL_MS = 60 * 60_000;
|
|
|
140
140
|
/** Grace after ending stdin before a still-running CLI is SIGKILLed. */
|
|
141
141
|
const EXIT_GRACE_MS = 500;
|
|
142
142
|
/** Grace after an interrupt for the CLI to persist the turn and emit result. */
|
|
143
|
-
const INTERRUPT_GRACE_MS = 2_000;
|
|
143
|
+
export const INTERRUPT_GRACE_MS = 2_000;
|
|
144
144
|
|
|
145
145
|
let controlSeq = 0;
|
|
146
146
|
|
|
@@ -701,7 +701,7 @@ export class CliProcess implements HandoffTarget {
|
|
|
701
701
|
// not answered yet. Anything else — an id from a sub-agent's nested block,
|
|
702
702
|
// a replayed id, a value invented by whoever reached the socket — is
|
|
703
703
|
// refused. It used to land in `pending`, where nothing would ever deliver
|
|
704
|
-
// a result for it and the caller blocked
|
|
704
|
+
// a result for it and the caller stayed blocked.
|
|
705
705
|
if (!this.awaiting.has(id) && !this.ready.has(id)) {
|
|
706
706
|
call.respond(errorResult(UNMATCHED_CALL_MESSAGE));
|
|
707
707
|
return;
|
package/src/control-handler.ts
CHANGED
|
@@ -25,8 +25,7 @@ export const MCP_PREFIX = "mcp__";
|
|
|
25
25
|
* `response`, and allow decisions carry `updatedInput` (the tool input,
|
|
26
26
|
* passed through unmodified). The 1.x shape (`request_id` at the top level)
|
|
27
27
|
* is silently ignored by 2.1.x — the CLI keeps waiting for an answer and
|
|
28
|
-
* the episode stalls
|
|
29
|
-
* as truncated multi-cycle turns. Verified against claude 2.1.237.
|
|
28
|
+
* the episode stalls. Verified against claude 2.1.237.
|
|
30
29
|
*/
|
|
31
30
|
interface ControlResponse {
|
|
32
31
|
type: "control_response";
|
package/src/handoff-broker.ts
CHANGED
|
@@ -178,8 +178,8 @@ export function defaultSocketPath(): string {
|
|
|
178
178
|
* No intake deadline or request-size cap by design: the socket lives in
|
|
179
179
|
* a 0700 runtime directory, so the only peer is our own MCP bridge, which
|
|
180
180
|
* sends one request line as soon as it connects. A bridge that dies closes
|
|
181
|
-
* the socket
|
|
182
|
-
*
|
|
181
|
+
* the socket. The provider can retire the parked process on handoff expiry
|
|
182
|
+
* or abort. Claude's MCP wall-clock timeout still applies.
|
|
183
183
|
*/
|
|
184
184
|
|
|
185
185
|
interface IncomingCall {
|
package/src/process-manager.ts
CHANGED
|
@@ -48,7 +48,7 @@ import { thinkingSpawnArgs, type CliThinking } from "./thinking-config.js";
|
|
|
48
48
|
* Where a spawn's system prompt is staged. Scoped to the CLI session so
|
|
49
49
|
* concurrent turns in one pi process cannot clobber each other.
|
|
50
50
|
*/
|
|
51
|
-
/**
|
|
51
|
+
/** Default Claude Code MCP tool wall-clock budget. */
|
|
52
52
|
export const DEFAULT_MCP_TOOL_TIMEOUT_MS = 3_600_000;
|
|
53
53
|
|
|
54
54
|
/**
|
|
@@ -390,11 +390,7 @@ export function spawnClaude(
|
|
|
390
390
|
args.push("--mcp-config", options.mcpConfigPath);
|
|
391
391
|
}
|
|
392
392
|
|
|
393
|
-
//
|
|
394
|
-
// the tool (src/handoff-broker.ts). Sub-agents and long shell tools take
|
|
395
|
-
// minutes, so unless the host set its own limit, give the MCP client an
|
|
396
|
-
// hour before it gives up on a call. Config, not context: it never touches
|
|
397
|
-
// the prompt cache.
|
|
393
|
+
// This is CLI configuration, not prompt context.
|
|
398
394
|
const env = cliEnvironment(options?.claudeConfigDir);
|
|
399
395
|
{
|
|
400
396
|
// Do not use --bare: it disables subscription OAuth/keychain reads.
|
|
@@ -411,6 +407,10 @@ export function spawnClaude(
|
|
|
411
407
|
}
|
|
412
408
|
if (!env.MCP_TOOL_TIMEOUT)
|
|
413
409
|
env.MCP_TOOL_TIMEOUT = String(DEFAULT_MCP_TOOL_TIMEOUT_MS);
|
|
410
|
+
// Pi runs proxied tools and may be silent for over Claude's 30-minute stdio
|
|
411
|
+
// idle window. Keep the wall-clock limit, but don't time out on silence.
|
|
412
|
+
// https://code.claude.com/docs/en/env-vars#claude-code-mcp-tool-idle-timeout
|
|
413
|
+
if (options?.mcpConfigPath) env.CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT ||= "0";
|
|
414
414
|
|
|
415
415
|
const proc = spawn("claude", args, {
|
|
416
416
|
stdio: ["pipe", "pipe", "pipe"],
|
package/src/provider.ts
CHANGED
|
@@ -27,9 +27,9 @@ import {
|
|
|
27
27
|
|
|
28
28
|
import {
|
|
29
29
|
spawnClaude,
|
|
30
|
+
DEFAULT_MCP_TOOL_TIMEOUT_MS,
|
|
30
31
|
verifyContextCli,
|
|
31
32
|
captureStderr,
|
|
32
|
-
forceKillProcess,
|
|
33
33
|
registerProcess,
|
|
34
34
|
cleanupSystemPromptFile,
|
|
35
35
|
sendInterrupt,
|
|
@@ -48,6 +48,7 @@ import {
|
|
|
48
48
|
addUsage,
|
|
49
49
|
subUsage,
|
|
50
50
|
maxUsage,
|
|
51
|
+
INTERRUPT_GRACE_MS,
|
|
51
52
|
ZERO_USAGE,
|
|
52
53
|
type Usage4,
|
|
53
54
|
type EpisodeSink,
|
|
@@ -120,16 +121,6 @@ import {
|
|
|
120
121
|
replayPiMessages,
|
|
121
122
|
} from "./pi-context.js";
|
|
122
123
|
|
|
123
|
-
/**
|
|
124
|
-
* Inactivity timeout. CLI-side tool executions (web search, user MCP
|
|
125
|
-
* servers, sub-agents) can be silent on stdout for minutes, so the default
|
|
126
|
-
* is generous and overridable via PI_CLAUDE_TETHER_TIMEOUT_MS.
|
|
127
|
-
*/
|
|
128
|
-
const INACTIVITY_TIMEOUT_MS =
|
|
129
|
-
Number(process.env.PI_CLAUDE_TETHER_TIMEOUT_MS) > 0
|
|
130
|
-
? Number(process.env.PI_CLAUDE_TETHER_TIMEOUT_MS)
|
|
131
|
-
: 300_000;
|
|
132
|
-
|
|
133
124
|
/** Empty CLI result boundaries cannot acknowledge a submitted Pi user turn. */
|
|
134
125
|
|
|
135
126
|
/**
|
|
@@ -154,15 +145,14 @@ function keepaliveMs(cli: CliProcess): number {
|
|
|
154
145
|
}
|
|
155
146
|
|
|
156
147
|
/**
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
* interrupted and retired when it fires.
|
|
148
|
+
* Bound a parked handoff by the same default budget as the CLI MCP call.
|
|
149
|
+
* An explicit shorter park still interrupts and retires the CLI without
|
|
150
|
+
* stopping Pi's tool.
|
|
161
151
|
*/
|
|
162
152
|
const HANDOFF_WAIT_MS =
|
|
163
153
|
Number(process.env.PI_CLAUDE_TETHER_HANDOFF_WAIT_MS) > 0
|
|
164
154
|
? Number(process.env.PI_CLAUDE_TETHER_HANDOFF_WAIT_MS)
|
|
165
|
-
:
|
|
155
|
+
: DEFAULT_MCP_TOOL_TIMEOUT_MS;
|
|
166
156
|
|
|
167
157
|
/** Kill switch for the proxied handoff (falls back to interrupt-and-reimport). */
|
|
168
158
|
function handoffProxyAllowed(): boolean {
|
|
@@ -413,9 +403,13 @@ export function streamViaCli(
|
|
|
413
403
|
// configuration error fails the turn loudly instead of guessing a profile.
|
|
414
404
|
let accountSet: string[];
|
|
415
405
|
let attemptAccount: string;
|
|
406
|
+
// Resolved once per turn inside this guard: a settings file edited or
|
|
407
|
+
// corrupted mid-turn cannot throw from the CLI's output callbacks.
|
|
408
|
+
let failover: boolean;
|
|
416
409
|
try {
|
|
417
410
|
accountSet = parseAccountSet();
|
|
418
|
-
|
|
411
|
+
failover = failoverEnabled();
|
|
412
|
+
attemptAccount = pickInitialAccount(accountSet, failover);
|
|
419
413
|
} catch (err: unknown) {
|
|
420
414
|
failPiRequest(err instanceof Error ? err.message : String(err));
|
|
421
415
|
return stream;
|
|
@@ -818,6 +812,7 @@ export function streamViaCli(
|
|
|
818
812
|
// Guard against double stream.end() and double error events.
|
|
819
813
|
let streamEnded = false;
|
|
820
814
|
let finished = false;
|
|
815
|
+
let abortDrainTimer: ReturnType<typeof setTimeout> | undefined;
|
|
821
816
|
let malformedRetirementError: string | undefined;
|
|
822
817
|
let resolveFinished!: () => void;
|
|
823
818
|
const finishedPromise = new Promise<void>((r) => (resolveFinished = r));
|
|
@@ -826,8 +821,8 @@ export function streamViaCli(
|
|
|
826
821
|
function finishEpisode() {
|
|
827
822
|
if (finished) return;
|
|
828
823
|
finished = true;
|
|
824
|
+
clearTimeout(abortDrainTimer);
|
|
829
825
|
live.ledger?.endEpisode();
|
|
830
|
-
clearTimeout(inactivityTimer);
|
|
831
826
|
live.detach();
|
|
832
827
|
resolveFinished();
|
|
833
828
|
}
|
|
@@ -966,22 +961,6 @@ export function streamViaCli(
|
|
|
966
961
|
]);
|
|
967
962
|
}
|
|
968
963
|
|
|
969
|
-
// Inactivity timeout: kill subprocess if no stdout for INACTIVITY_TIMEOUT_MS
|
|
970
|
-
let inactivityTimer: ReturnType<typeof setTimeout> | undefined;
|
|
971
|
-
|
|
972
|
-
function resetInactivityTimer() {
|
|
973
|
-
if (inactivityTimer !== undefined) clearTimeout(inactivityTimer);
|
|
974
|
-
inactivityTimer = setTimeout(() => {
|
|
975
|
-
if (finished || malformedHandoff) return;
|
|
976
|
-
live.expectedExitReason = ["inactivity"];
|
|
977
|
-
forceKillProcess(proc);
|
|
978
|
-
endStreamWithError(
|
|
979
|
-
`Claude CLI subprocess timed out: no output for ${INACTIVITY_TIMEOUT_MS / 1000} seconds`,
|
|
980
|
-
"inactivity",
|
|
981
|
-
);
|
|
982
|
-
}, INACTIVITY_TIMEOUT_MS);
|
|
983
|
-
}
|
|
984
|
-
|
|
985
964
|
// Drain an interrupt result before reusing the process. A Pi-owned
|
|
986
965
|
// process is not disposable just because its caller cancelled a turn.
|
|
987
966
|
if (options?.signal) {
|
|
@@ -993,7 +972,13 @@ export function streamViaCli(
|
|
|
993
972
|
return;
|
|
994
973
|
}
|
|
995
974
|
sendInterrupt(proc);
|
|
996
|
-
|
|
975
|
+
// A CLI ignoring Stop must not strand Pi. Only user cancellation
|
|
976
|
+
// starts this wait, using the process owner's existing interrupt grace.
|
|
977
|
+
abortDrainTimer = setTimeout(
|
|
978
|
+
() => endStreamWithError("Request aborted", "abort"),
|
|
979
|
+
INTERRUPT_GRACE_MS,
|
|
980
|
+
);
|
|
981
|
+
abortDrainTimer.unref?.();
|
|
997
982
|
};
|
|
998
983
|
|
|
999
984
|
if (options.signal.aborted) abortHandler();
|
|
@@ -1139,7 +1124,6 @@ export function streamViaCli(
|
|
|
1139
1124
|
msg.type !== "rate_limit_event" &&
|
|
1140
1125
|
msg.type !== "control_request"
|
|
1141
1126
|
) {
|
|
1142
|
-
resetInactivityTimer();
|
|
1143
1127
|
receiptQueue.push(msg);
|
|
1144
1128
|
// A terminal envelope cannot establish a missing receipt. Preserve
|
|
1145
1129
|
// the existing missing-receipt failure rather than waiting forever.
|
|
@@ -1151,9 +1135,6 @@ export function streamViaCli(
|
|
|
1151
1135
|
return;
|
|
1152
1136
|
}
|
|
1153
1137
|
if (awaitingTurnWrite) beforeTurnWrite.add(msg);
|
|
1154
|
-
// Reset inactivity timer on each line of output, even while a
|
|
1155
|
-
// response observer is asynchronously inspecting initialization.
|
|
1156
|
-
resetInactivityTimer();
|
|
1157
1138
|
// MCP calls can arrive while the response observer is pending. Keep
|
|
1158
1139
|
// transport bookkeeping current, but publish no body before it settles.
|
|
1159
1140
|
if (
|
|
@@ -1433,7 +1414,7 @@ export function streamViaCli(
|
|
|
1433
1414
|
? r.errors.join("; ")
|
|
1434
1415
|
: `Claude CLI returned ${r.subtype ?? "non-success result"}`);
|
|
1435
1416
|
if (
|
|
1436
|
-
|
|
1417
|
+
failover &&
|
|
1437
1418
|
multiAccount &&
|
|
1438
1419
|
rejectedResetsAt !== undefined &&
|
|
1439
1420
|
mode !== "handoff" &&
|
|
@@ -1538,7 +1519,6 @@ export function streamViaCli(
|
|
|
1538
1519
|
sawHandoffTool = false;
|
|
1539
1520
|
live.writeSteer(queuedUsers!);
|
|
1540
1521
|
queuedUsers = undefined;
|
|
1541
|
-
resetInactivityTimer();
|
|
1542
1522
|
return;
|
|
1543
1523
|
}
|
|
1544
1524
|
|
|
@@ -1546,7 +1526,6 @@ export function streamViaCli(
|
|
|
1546
1526
|
// Keep reading until the CLI produces content or reports spend.
|
|
1547
1527
|
if (!isError && !selfInterrupted && !aborted && episodeIsEmpty()) {
|
|
1548
1528
|
live.resumeTurn();
|
|
1549
|
-
resetInactivityTimer();
|
|
1550
1529
|
return;
|
|
1551
1530
|
}
|
|
1552
1531
|
|
|
@@ -1562,7 +1541,6 @@ export function streamViaCli(
|
|
|
1562
1541
|
steers === "pending"
|
|
1563
1542
|
) {
|
|
1564
1543
|
live.resumeTurn();
|
|
1565
|
-
resetInactivityTimer();
|
|
1566
1544
|
return;
|
|
1567
1545
|
}
|
|
1568
1546
|
if (steers === "unconfirmed") {
|
|
@@ -1584,10 +1562,7 @@ export function streamViaCli(
|
|
|
1584
1562
|
};
|
|
1585
1563
|
|
|
1586
1564
|
// Attach: buffered lines (a handoff gap) replay first, then live ones.
|
|
1587
|
-
if (!finished)
|
|
1588
|
-
live.attach(sink);
|
|
1589
|
-
resetInactivityTimer();
|
|
1590
|
-
}
|
|
1565
|
+
if (!finished) live.attach(sink);
|
|
1591
1566
|
|
|
1592
1567
|
// Continue the parked process
|
|
1593
1568
|
if (mode === "handoff") {
|
package/src/removed-config.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type {
|
|
|
2
2
|
ExtensionAPI,
|
|
3
3
|
ExtensionContext,
|
|
4
4
|
} from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { addStartupNotice } from "./startup-notices.js";
|
|
5
6
|
|
|
6
7
|
/** Diagnostics only: retired variables never configure the provider. */
|
|
7
8
|
const ACTIVE_SUFFIXES = new Set([
|
|
@@ -11,7 +12,6 @@ const ACTIVE_SUFFIXES = new Set([
|
|
|
11
12
|
"STATE_DIR",
|
|
12
13
|
"STRICT_VERSION",
|
|
13
14
|
"SETTINGS",
|
|
14
|
-
"TIMEOUT_MS",
|
|
15
15
|
"KEEPALIVE_MS",
|
|
16
16
|
"HANDOFF_PROXY",
|
|
17
17
|
"HANDOFF_WAIT_MS",
|
|
@@ -41,8 +41,8 @@ export function warnRemovedEnvironment(
|
|
|
41
41
|
.sort();
|
|
42
42
|
if (names.length === 0) return;
|
|
43
43
|
warned = true;
|
|
44
|
-
|
|
45
|
-
`
|
|
44
|
+
addStartupNotice(
|
|
45
|
+
`Ignored retired environment variables: ${names
|
|
46
46
|
.map((name) => {
|
|
47
47
|
const suffix = name.slice("PI_CLAUDE_CLI_".length);
|
|
48
48
|
if (REMOVED_SUFFIXES.has(suffix))
|
|
@@ -51,7 +51,9 @@ export function warnRemovedEnvironment(
|
|
|
51
51
|
? `${name}: use PI_CLAUDE_TETHER_${suffix} instead`
|
|
52
52
|
: `${name}: retired; consult the migration guide (no supported replacement known)`;
|
|
53
53
|
})
|
|
54
|
-
.join(
|
|
54
|
+
.join(
|
|
55
|
+
"; ",
|
|
56
|
+
)}. No old-name aliases are supported. A shell or tmux session started before you edited your shell files still carries old values: start a new one.`,
|
|
55
57
|
);
|
|
56
58
|
}
|
|
57
59
|
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration notices raised while loading (moved settings file, retired or
|
|
3
|
+
* unrecognised environment values). Pi's interactive screen does not show
|
|
4
|
+
* console output, so index.ts delivers them with ctx.ui.notify at
|
|
5
|
+
* session_start, and to stderr when there is no UI (print/JSON mode).
|
|
6
|
+
*/
|
|
7
|
+
const pending: string[] = [];
|
|
8
|
+
const seen = new Set<string>();
|
|
9
|
+
|
|
10
|
+
export function addStartupNotice(message: string): void {
|
|
11
|
+
if (seen.has(message)) return;
|
|
12
|
+
seen.add(message);
|
|
13
|
+
pending.push(message);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Take the notices not yet delivered. */
|
|
17
|
+
export function takeStartupNotices(): string[] {
|
|
18
|
+
return pending.splice(0, pending.length);
|
|
19
|
+
}
|