@zgltyq/pi-provider-claude 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -71,12 +71,58 @@ PI_CLAUDE_PROVIDER_DEBUG_LOG=/tmp/claude-provider.log pi
71
71
  In `/tmp/claude-provider.log`, the `"after"` payload's `tools[]` should show your
72
72
  extension tools as `mcp__pi__<name>` and **nothing dropped**.
73
73
 
74
+ ## Multi-account failover (opt-in)
75
+
76
+ If you have **two subscription accounts** (e.g. personal + work), the extension can
77
+ fail over between them: when the active account hits its rate / usage cap (429/529),
78
+ it's put on cooldown and the next turn transparently continues on the other account.
79
+ Subscription billing is preserved (Pi detects the OAuth path from the token shape).
80
+
81
+ It is **inert** unless `<agentDir>/claude-pool.json` exists with ≥2 accounts and
82
+ `"enabled" !== false`.
83
+
84
+ ### Enroll accounts with the native `/login` (recommended)
85
+
86
+ `/login anthropic` only keeps ONE credential (a second login overwrites the first),
87
+ so the extension adds a command to snapshot each login into the pool:
88
+
89
+ ```
90
+ /login anthropic → sign in with account A
91
+ /claude-pool-add personal → stash account A in the pool
92
+ /login anthropic → sign in with account B (overwrites auth.json — fine)
93
+ /claude-pool-add work → stash account B in the pool
94
+ /claude-pool-status → verify both are present
95
+ ```
96
+
97
+ Restart, and failover activates. `/claude-pool-add <label>` only writes
98
+ `claude-pool.json` (it never touches the request path).
99
+
100
+ ### Alternative: harvest via separate profiles
101
+
102
+ ```bash
103
+ PI_CODING_AGENT_DIR=~/.pi-personal pi # /login anthropic (personal)
104
+ PI_CODING_AGENT_DIR=~/.pi-work pi # /login anthropic (work)
105
+ ./harvest-claude-pool.sh # writes ~/.pi/agent/claude-pool.json
106
+ ```
107
+
108
+ `claude-pool.json` shape:
109
+
110
+ ```json
111
+ { "enabled": true, "accounts": [
112
+ { "label": "personal", "refresh": "...", "access": "...", "expires": 0 },
113
+ { "label": "work", "refresh": "...", "access": "...", "expires": 0 }
114
+ ] }
115
+ ```
116
+
117
+ Kill switch: `PI_CLAUDE_PROVIDER_POOL_DISABLE=1` (or `"enabled": false`).
118
+
74
119
  ## Environment variables
75
120
 
76
121
  | Variable | Effect |
77
122
  |---|---|
78
- | `PI_CLAUDE_PROVIDER_DEBUG_LOG=/path` | Append `before`/`after` payloads for debugging. |
123
+ | `PI_CLAUDE_PROVIDER_DEBUG_LOG=/path` | Append `before`/`after`/`pool` events for debugging. |
79
124
  | `PI_CLAUDE_PROVIDER_DISABLE=1` | Pass all tools through with flat names (no renaming). Debug escape hatch. |
125
+ | `PI_CLAUDE_PROVIDER_POOL_DISABLE=1` | Disable multi-account failover even if `claude-pool.json` exists. |
80
126
 
81
127
  ## How it differs from `@benvargas/pi-claude-code-use`
82
128
 
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env bash
2
+ # Harvest both accounts' Anthropic OAuth creds (from two PI_CODING_AGENT_DIR
3
+ # profiles) into ~/.pi/agent/claude-pool.json for pi-provider-claude failover.
4
+ #
5
+ # Prereq — log into each profile ONCE (interactive), in separate terminals:
6
+ # PI_CODING_AGENT_DIR=~/.pi-personal pi # then: /login anthropic (personal)
7
+ # PI_CODING_AGENT_DIR=~/.pi-work pi # then: /login anthropic (work)
8
+ set -euo pipefail
9
+ P_PERSONAL="${1:-$HOME/.pi-personal/auth.json}"
10
+ P_WORK="${2:-$HOME/.pi-work/auth.json}"
11
+ OUT="$HOME/.pi/agent/claude-pool.json"
12
+ python3 - "$P_PERSONAL" "$P_WORK" "$OUT" <<'PY'
13
+ import json,sys,os
14
+ def block(path,label):
15
+ if not os.path.exists(path): sys.exit(f"missing {path} — run /login anthropic in that profile first")
16
+ a=json.load(open(path)).get("anthropic")
17
+ if not a or "access" not in a or "refresh" not in a:
18
+ sys.exit(f"{path}: no anthropic OAuth creds (did you /login anthropic with a subscription account?)")
19
+ return {"label":label,"refresh":a["refresh"],"access":a["access"],"expires":a.get("expires",0)}
20
+ personal, work, out = sys.argv[1], sys.argv[2], sys.argv[3]
21
+ pool={"enabled":True,"accounts":[block(personal,"personal"),block(work,"work")]}
22
+ os.makedirs(os.path.dirname(out),exist_ok=True)
23
+ with open(out,"w") as f: json.dump(pool,f,indent=2)
24
+ os.chmod(out,0o600)
25
+ print(f"wrote {out} with {len(pool['accounts'])} accounts:",", ".join(x['label'] for x in pool['accounts']))
26
+ PY
package/index.ts CHANGED
@@ -36,7 +36,14 @@
36
36
  * PI_CLAUDE_PROVIDER_DISABLE=1 → pass everything through flat (debug)
37
37
  */
38
38
 
39
- import { appendFileSync } from "node:fs";
39
+ import {
40
+ appendFileSync,
41
+ existsSync,
42
+ readFileSync,
43
+ writeFileSync,
44
+ } from "node:fs";
45
+ import { homedir } from "node:os";
46
+ import { join } from "node:path";
40
47
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
41
48
 
42
49
  // Prefix used to disguise flat tools as MCP tools. Kept short so
@@ -252,6 +259,308 @@ function writeDebugLog(payload: unknown): void {
252
259
  }
253
260
  }
254
261
 
262
+ // ════════════════════════════════════════════════════════════════════════════
263
+ // Multi-account failover (OPT-IN)
264
+ //
265
+ // Inert unless <agentDir>/claude-pool.json exists with >=2 accounts and
266
+ // "enabled" !== false. Kill switch: PI_CLAUDE_PROVIDER_POOL_DISABLE=1.
267
+ //
268
+ // Mechanism: override the anthropic provider's OAuth credential supply so the
269
+ // per-request token is the *currently active* pooled account. On a 429/529
270
+ // (rate / usage cap) the active account is put on cooldown and the pointer
271
+ // flips to the other account, so the next turn uses it. Tokens are refreshed in
272
+ // an async before_agent_start hook because getApiKey() is synchronous.
273
+ //
274
+ // Subscription billing is preserved: Pi's transport detects the OAuth path from
275
+ // the token's SHAPE (isOAuthToken), so any genuine pooled OAuth token still gets
276
+ // the Claude Code identity headers automatically.
277
+ // ════════════════════════════════════════════════════════════════════════════
278
+
279
+ interface PoolAccount {
280
+ label: string;
281
+ refresh: string;
282
+ access: string;
283
+ expires: number;
284
+ }
285
+ interface PoolConfig {
286
+ enabled?: boolean;
287
+ accounts: PoolAccount[];
288
+ }
289
+
290
+ const POOL_PATH = join(
291
+ process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"),
292
+ "claude-pool.json",
293
+ );
294
+ const POOL_REFRESH_BUFFER_MS = 60_000;
295
+ const POOL_DEFAULT_COOLDOWN_MS = 5 * 60_000;
296
+
297
+ let poolAccounts: PoolAccount[] = [];
298
+ let poolActive = 0;
299
+ let poolCooldownUntil: number[] = [];
300
+
301
+ function poolLog(msg: string): void {
302
+ writeDebugLog({ stage: "pool", time: new Date().toISOString(), msg });
303
+ }
304
+
305
+ function loadPool(): boolean {
306
+ try {
307
+ if (!existsSync(POOL_PATH)) return false;
308
+ const cfg = JSON.parse(readFileSync(POOL_PATH, "utf-8")) as PoolConfig;
309
+ if (cfg.enabled === false) return false;
310
+ const accts = (cfg.accounts || []).filter(
311
+ (a) => a && a.refresh && a.access,
312
+ );
313
+ if (accts.length < 2) return false;
314
+ poolAccounts = accts;
315
+ poolCooldownUntil = accts.map(() => 0);
316
+ poolActive = 0;
317
+ return true;
318
+ } catch {
319
+ return false;
320
+ }
321
+ }
322
+
323
+ function persistPool(): void {
324
+ try {
325
+ writeFileSync(
326
+ POOL_PATH,
327
+ JSON.stringify({ enabled: true, accounts: poolAccounts }, null, 2),
328
+ {
329
+ mode: 0o600,
330
+ },
331
+ );
332
+ } catch {
333
+ /* persistence is best-effort */
334
+ }
335
+ }
336
+
337
+ function poolSelectActive(): void {
338
+ const now = Date.now();
339
+ if (poolCooldownUntil[poolActive] <= now) return; // active still usable
340
+ let pick = -1;
341
+ for (let i = 0; i < poolAccounts.length; i++) {
342
+ if (poolCooldownUntil[i] <= now) {
343
+ pick = i;
344
+ break;
345
+ }
346
+ }
347
+ if (pick === -1) {
348
+ // all cooling down → pick the one that frees up soonest
349
+ let min = Number.POSITIVE_INFINITY;
350
+ for (let i = 0; i < poolCooldownUntil.length; i++) {
351
+ if (poolCooldownUntil[i] < min) {
352
+ min = poolCooldownUntil[i];
353
+ pick = i;
354
+ }
355
+ }
356
+ }
357
+ if (pick !== poolActive) {
358
+ poolActive = pick;
359
+ poolLog(`switched active → ${poolAccounts[poolActive].label}`);
360
+ }
361
+ }
362
+
363
+ async function poolEnsureFresh(i: number): Promise<void> {
364
+ const acct = poolAccounts[i];
365
+ if (!acct || acct.expires > Date.now() + POOL_REFRESH_BUFFER_MS) return;
366
+ try {
367
+ const oauth = (await import("@earendil-works/pi-ai/oauth")) as {
368
+ refreshAnthropicToken: (
369
+ r: string,
370
+ ) => Promise<{ refresh?: string; access: string; expires: number }>;
371
+ };
372
+ const next = await oauth.refreshAnthropicToken(acct.refresh);
373
+ acct.access = next.access;
374
+ acct.expires = next.expires;
375
+ if (next.refresh) acct.refresh = next.refresh;
376
+ persistPool();
377
+ poolLog(`refreshed ${acct.label}`);
378
+ } catch (e) {
379
+ poolLog(
380
+ `refresh FAILED ${acct.label}: ${(e as Error)?.message ?? String(e)}`,
381
+ );
382
+ }
383
+ }
384
+
385
+ function poolMarkRateLimited(headers?: Record<string, string>): void {
386
+ const now = Date.now();
387
+ let until = now + POOL_DEFAULT_COOLDOWN_MS;
388
+ const ra =
389
+ headers?.["retry-after"] ?? headers?.["anthropic-ratelimit-unified-reset"];
390
+ if (ra) {
391
+ const n = Number(ra);
392
+ if (Number.isFinite(n)) until = n > 1e9 ? n * 1000 : now + n * 1000; // epoch-seconds vs delta-seconds
393
+ }
394
+ poolCooldownUntil[poolActive] = until;
395
+ poolLog(
396
+ `rate-limited ${poolAccounts[poolActive].label} until ${new Date(until).toISOString()}`,
397
+ );
398
+ poolSelectActive();
399
+ }
400
+
401
+ // Read the current single-slot anthropic OAuth creds from auth.json.
402
+ function readAnthropicAuth():
403
+ | { refresh: string; access: string; expires: number }
404
+ | undefined {
405
+ try {
406
+ const authPath = join(
407
+ process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"),
408
+ "auth.json",
409
+ );
410
+ if (!existsSync(authPath)) return undefined;
411
+ const a = (
412
+ JSON.parse(readFileSync(authPath, "utf-8")) as { anthropic?: PoolAccount }
413
+ ).anthropic;
414
+ if (!a || !a.access || !a.refresh) return undefined;
415
+ return { refresh: a.refresh, access: a.access, expires: a.expires ?? 0 };
416
+ } catch {
417
+ return undefined;
418
+ }
419
+ }
420
+
421
+ // Upsert an account (by label) into claude-pool.json. Returns total count.
422
+ function poolUpsert(
423
+ label: string,
424
+ creds: { refresh: string; access: string; expires: number },
425
+ ): number {
426
+ let cfg: PoolConfig = { enabled: true, accounts: [] };
427
+ try {
428
+ if (existsSync(POOL_PATH))
429
+ cfg = JSON.parse(readFileSync(POOL_PATH, "utf-8")) as PoolConfig;
430
+ } catch {
431
+ /* start fresh on a corrupt file */
432
+ }
433
+ if (!Array.isArray(cfg.accounts)) cfg.accounts = [];
434
+ const entry: PoolAccount = { label, ...creds };
435
+ const idx = cfg.accounts.findIndex((x) => x.label === label);
436
+ if (idx >= 0) cfg.accounts[idx] = entry;
437
+ else cfg.accounts.push(entry);
438
+ cfg.enabled = cfg.enabled !== false;
439
+ writeFileSync(POOL_PATH, JSON.stringify(cfg, null, 2), { mode: 0o600 });
440
+ return cfg.accounts.length;
441
+ }
442
+
443
+ // /login enrollment + inspection. Always registered (touches files only, not
444
+ // the request path), so you can bootstrap the pool with the native /login.
445
+ function setupPoolCommands(pi: ExtensionAPI): void {
446
+ const register = pi.registerCommand as unknown as (
447
+ name: string,
448
+ def: {
449
+ description: string;
450
+ handler: (
451
+ args: string,
452
+ ctx: { ui: { notify: (m: string, l?: string) => void } },
453
+ ) => Promise<void>;
454
+ },
455
+ ) => void;
456
+
457
+ register("claude-pool-add", {
458
+ description:
459
+ "Snapshot the current '/login anthropic' account into the Claude failover pool. Usage: /claude-pool-add <label>",
460
+ handler: async (args, ctx) => {
461
+ const label = (args || "").trim() || `account-${Date.now()}`;
462
+ const creds = readAnthropicAuth();
463
+ if (!creds) {
464
+ ctx.ui.notify(
465
+ "No anthropic OAuth creds in auth.json — run /login anthropic first.",
466
+ "warning",
467
+ );
468
+ return;
469
+ }
470
+ const n = poolUpsert(label, creds);
471
+ ctx.ui.notify(
472
+ `Added "${label}" to Claude pool (${n} account${n === 1 ? "" : "s"}). ${n >= 2 ? "Restart to activate failover." : "Now /login the other account and run this again."}`,
473
+ "info",
474
+ );
475
+ },
476
+ });
477
+
478
+ register("claude-pool-status", {
479
+ description: "Show the Claude failover pool accounts",
480
+ handler: async (_args, ctx) => {
481
+ if (!existsSync(POOL_PATH)) {
482
+ ctx.ui.notify(
483
+ "No claude-pool.json yet. Use /claude-pool-add <label> after /login.",
484
+ "info",
485
+ );
486
+ return;
487
+ }
488
+ try {
489
+ const cfg = JSON.parse(readFileSync(POOL_PATH, "utf-8")) as PoolConfig;
490
+ const lines = (cfg.accounts || []).map(
491
+ (a, i) =>
492
+ ` ${i}. ${a.label} (exp ${a.expires ? new Date(a.expires).toISOString() : "?"})`,
493
+ );
494
+ ctx.ui.notify(
495
+ `Claude pool (enabled=${cfg.enabled !== false}):\n${lines.join("\n") || " (none)"}`,
496
+ "info",
497
+ );
498
+ } catch (e) {
499
+ ctx.ui.notify(`pool read error: ${(e as Error).message}`, "warning");
500
+ }
501
+ },
502
+ });
503
+ }
504
+
505
+ function setupPool(pi: ExtensionAPI): void {
506
+ if (process.env.PI_CLAUDE_PROVIDER_POOL_DISABLE === "1") return;
507
+ if (!loadPool()) return; // inert unless a valid claude-pool.json exists
508
+ poolLog(`pool active: ${poolAccounts.map((a) => a.label).join(", ")}`);
509
+
510
+ const prep = async () => {
511
+ poolSelectActive();
512
+ await poolEnsureFresh(poolActive);
513
+ };
514
+ pi.on("session_start", async () => {
515
+ await prep();
516
+ });
517
+ pi.on("before_agent_start", async () => {
518
+ await prep();
519
+ });
520
+
521
+ // Observe rate/usage-cap responses → cooldown the active account + flip.
522
+ pi.on("after_provider_response", (event: unknown) => {
523
+ try {
524
+ const e = event as {
525
+ status?: number;
526
+ statusCode?: number;
527
+ headers?: Record<string, string>;
528
+ };
529
+ const status = e.status ?? e.statusCode;
530
+ if (status === 429 || status === 529) poolMarkRateLimited(e.headers);
531
+ } catch {
532
+ /* observation only — never break the response path */
533
+ }
534
+ return undefined;
535
+ });
536
+
537
+ // Supply the active pooled account's token to Pi's Anthropic transport.
538
+ const register = pi.registerProvider as unknown as (
539
+ id: string,
540
+ cfg: unknown,
541
+ ) => void;
542
+ register("anthropic", {
543
+ oauth: {
544
+ name: `Claude (pooled: ${poolAccounts.map((a) => a.label).join("+")})`,
545
+ async login(callbacks: unknown) {
546
+ const m = (await import("@earendil-works/pi-ai/oauth")) as {
547
+ anthropicOAuthProvider: { login: (c: unknown) => Promise<unknown> };
548
+ };
549
+ return m.anthropicOAuthProvider.login(callbacks);
550
+ },
551
+ async refreshToken(_creds: unknown) {
552
+ await poolEnsureFresh(poolActive);
553
+ const a = poolAccounts[poolActive];
554
+ return { refresh: a.refresh, access: a.access, expires: a.expires };
555
+ },
556
+ getApiKey(creds: { access?: string } | undefined) {
557
+ const a = poolAccounts[poolActive];
558
+ return (a && a.access) || creds?.access || "";
559
+ },
560
+ },
561
+ });
562
+ }
563
+
255
564
  export default function piProviderClaude(pi: ExtensionAPI): void {
256
565
  // mcp__pi__* → flat, before the agent loop resolves the tool.
257
566
  pi.on("message_end", async (event, _ctx) => {
@@ -280,4 +589,8 @@ export default function piProviderClaude(pi: ExtensionAPI): void {
280
589
  writeDebugLog({ stage: "after", payload: transformed });
281
590
  return transformed;
282
591
  });
592
+
593
+ // Multi-account failover.
594
+ setupPoolCommands(pi); // /claude-pool-add, /claude-pool-status (always available)
595
+ setupPool(pi); // failover provider override (active once >=2 accounts exist)
283
596
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zgltyq/pi-provider-claude",
3
- "version": "1.0.0",
4
- "description": "Claude (Anthropic OAuth/subscription) compatibility layer for pi-coding-agent — keeps ALL extension tools usable under the Claude subscription by mapping unknown flat tool names to mcp__pi__<name> on the wire instead of dropping them. Self-contained fork of the tool half of @benvargas/pi-claude-code-use.",
3
+ "version": "1.1.0",
4
+ "description": "Claude (Anthropic OAuth/subscription) compatibility layer for pi-coding-agent — keeps ALL extension tools usable under the Claude subscription by mapping unknown flat tool names to mcp__pi__<name> on the wire instead of dropping them, plus optional multi-account failover. Self-contained fork of the tool half of @benvargas/pi-claude-code-use.",
5
5
  "author": "Leechael",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -33,7 +33,8 @@
33
33
  "index.ts",
34
34
  "package.json",
35
35
  "README.md",
36
- "LICENSE"
36
+ "LICENSE",
37
+ "harvest-claude-pool.sh"
37
38
  ],
38
39
  "pi": {
39
40
  "extensions": [