pi-claude-tether 0.12.0 → 0.12.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,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.1 — 2026-11-10
4
+
5
+ - 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.
6
+ - 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.
7
+ - 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.
8
+ - New "Where settings live" documentation, including why a shell or tmux session opened before editing shell files keeps old values.
9
+ - Tests no longer read or write the developer's real Pi agent or data directories.
10
+
11
+ 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.
12
+
3
13
  ## 0.12.0 — 2026-11-10
4
14
 
5
15
  - 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 +35,7 @@ export PI_CLAUDE_TETHER_ACCOUNTS="${PI_CLAUDE_TETHER_ACCOUNTS:-default,b}"
25
35
  export PI_CLAUDE_TETHER_FAILOVER="${PI_CLAUDE_TETHER_FAILOVER:-1}"
26
36
  ```
27
37
 
28
- Remove their old `PI_CLAUDE_CLI_ACCOUNTS` / `PI_CLAUDE_CLI_FAILOVER` definitions and unset old variables in existing shells (or start a new shell). 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`, `TIMEOUT_MS`. 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.
38
+ 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`, `TIMEOUT_MS`. 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
39
 
30
40
  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
41
 
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,12 +47,23 @@ See [the context contract](CONTEXT-POLICY.md).
47
47
 
48
48
  ## Configuration
49
49
 
50
- The defaults above require no environment variables.
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` | Ordered declared profile set, e.g. `default,b` |
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
69
  | `PI_CLAUDE_TETHER_TIMEOUT_MS` | `300000` | Maximum stdout inactivity |
@@ -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. The ordered set is declared with `PI_CLAUDE_TETHER_ACCOUNTS` (e.g. `default,b`); the profile for this process is chosen with `PI_CLAUDE_TETHER_ACCOUNT`, so a shell alias starts Pi on a second account:
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
- `accounts.json` in the package data directory is the UI's declaration/default store: `{ "accounts": [{ "name": "work", "email": "…", "plan": "…", "addedAt": "…" }], "default": "work" }`. 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.
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 `accounts.json.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.
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 `accounts.json` 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.
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 `accounts.json`; 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`).
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
 
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,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-claude-tether",
3
- "version": "0.12.0",
3
+ "version": "0.12.1",
4
4
  "description": "Use your Claude subscription in Pi through the official Claude Code CLI",
5
5
  "main": "index.ts",
6
6
  "keywords": [
@@ -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 accounts.json UI entries.
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 PI_CLAUDE_TETHER_FAILOVER=1.
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 { packageDataDir } from "./data-dir.js";
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(packageDataDir(), { recursive: true, mode: 0o700 });
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
- * Only the exact value "1" enables failover; other values leave it disabled.
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.PI_CLAUDE_TETHER_FAILOVER ?? "") === "1";
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(set: string[]): string {
464
+ export function pickInitialAccount(
465
+ set: string[],
466
+ failover: boolean = failoverEnabled(),
467
+ ): string {
354
468
  const pinned = selectedAccountName(set);
355
- if (!failoverEnabled()) return pinned;
469
+ if (!failover) return pinned;
356
470
  if (!isAccountExhausted(pinned)) return pinned;
357
471
  return selectFailoverAccount(set, pinned) ?? pinned;
358
472
  }
package/src/provider.ts CHANGED
@@ -413,9 +413,13 @@ export function streamViaCli(
413
413
  // configuration error fails the turn loudly instead of guessing a profile.
414
414
  let accountSet: string[];
415
415
  let attemptAccount: string;
416
+ // Resolved once per turn inside this guard: a settings file edited or
417
+ // corrupted mid-turn cannot throw from the CLI's output callbacks.
418
+ let failover: boolean;
416
419
  try {
417
420
  accountSet = parseAccountSet();
418
- attemptAccount = pickInitialAccount(accountSet);
421
+ failover = failoverEnabled();
422
+ attemptAccount = pickInitialAccount(accountSet, failover);
419
423
  } catch (err: unknown) {
420
424
  failPiRequest(err instanceof Error ? err.message : String(err));
421
425
  return stream;
@@ -1433,7 +1437,7 @@ export function streamViaCli(
1433
1437
  ? r.errors.join("; ")
1434
1438
  : `Claude CLI returned ${r.subtype ?? "non-success result"}`);
1435
1439
  if (
1436
- failoverEnabled() &&
1440
+ failover &&
1437
1441
  multiAccount &&
1438
1442
  rejectedResetsAt !== undefined &&
1439
1443
  mode !== "handoff" &&
@@ -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([
@@ -41,8 +42,8 @@ export function warnRemovedEnvironment(
41
42
  .sort();
42
43
  if (names.length === 0) return;
43
44
  warned = true;
44
- console.warn(
45
- `[pi-claude-tether] Ignored retired environment variables: ${names
45
+ addStartupNotice(
46
+ `Ignored retired environment variables: ${names
46
47
  .map((name) => {
47
48
  const suffix = name.slice("PI_CLAUDE_CLI_".length);
48
49
  if (REMOVED_SUFFIXES.has(suffix))
@@ -51,7 +52,9 @@ export function warnRemovedEnvironment(
51
52
  ? `${name}: use PI_CLAUDE_TETHER_${suffix} instead`
52
53
  : `${name}: retired; consult the migration guide (no supported replacement known)`;
53
54
  })
54
- .join("; ")}. No old-name aliases are supported.`,
55
+ .join(
56
+ "; ",
57
+ )}. 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
58
  );
56
59
  }
57
60
 
@@ -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
+ }