@kapybara/zerosub 1.5.1 → 1.18.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.
Files changed (56) hide show
  1. package/README.md +220 -26
  2. package/client/accounts-surface.tsx +344 -110
  3. package/client/add-account.tsx +335 -23
  4. package/client/api-account.tsx +250 -0
  5. package/client/azure-account.tsx +311 -0
  6. package/client/commands.ts +44 -8
  7. package/client/composer-item.tsx +203 -0
  8. package/client/fork-confirm.tsx +71 -0
  9. package/client/fork-settings.tsx +148 -0
  10. package/client/pace.tsx +196 -0
  11. package/client/pi-accounts.tsx +571 -0
  12. package/client/pills.ts +63 -25
  13. package/client/reset-confirm.tsx +12 -3
  14. package/client/settings-screen.tsx +48 -9
  15. package/client/store.ts +148 -19
  16. package/client/switch-row.tsx +28 -8
  17. package/client/ui.tsx +11 -0
  18. package/index.client.tsx +4 -1
  19. package/index.server.ts +53 -10
  20. package/package.json +5 -2
  21. package/server/account-identity.ts +11 -0
  22. package/server/adapter.ts +115 -8
  23. package/server/api-usage.ts +144 -0
  24. package/server/azure.ts +346 -0
  25. package/server/binaries.ts +41 -3
  26. package/server/claude.ts +276 -21
  27. package/server/codex-same-conversation.ts +71 -0
  28. package/server/codex.ts +35 -7
  29. package/server/continuations.ts +67 -17
  30. package/server/cursor.ts +222 -0
  31. package/server/families.ts +105 -8
  32. package/server/grok.ts +225 -0
  33. package/server/handoff.ts +211 -29
  34. package/server/homes.ts +1263 -35
  35. package/server/json-file.ts +39 -8
  36. package/server/launchers.ts +319 -0
  37. package/server/limits.ts +80 -3
  38. package/server/main-proxy.ts +238 -0
  39. package/server/modes.ts +20 -4
  40. package/server/paths.ts +81 -1
  41. package/server/pi.ts +528 -0
  42. package/server/placement.ts +133 -0
  43. package/server/process.ts +18 -1
  44. package/server/processes.ts +66 -0
  45. package/server/provider-env.ts +28 -0
  46. package/server/proxy.ts +282 -0
  47. package/server/reopen.ts +50 -8
  48. package/server/routing.ts +337 -30
  49. package/server/service.ts +4320 -805
  50. package/server/state.ts +303 -24
  51. package/server/usage.ts +2 -0
  52. package/shared/format.ts +170 -2
  53. package/shared/model.ts +339 -2
  54. package/shared/preferences.ts +22 -1
  55. package/shared/rpc.ts +130 -8
  56. package/shared/timeline.ts +11 -0
package/server/claude.ts CHANGED
@@ -3,7 +3,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
3
3
  import { readFile, rm } from "node:fs/promises";
4
4
  import { homedir, tmpdir, userInfo } from "node:os";
5
5
  import { join } from "node:path";
6
- import type { LoginMethod, Usage, UsageWindow } from "../shared/model";
6
+ import type { ApiSummary, ExtraUsage, LoginMethod, Usage, UsageWindow } from "../shared/model";
7
7
  import {
8
8
  ProgressEmitter,
9
9
  spawnEnv,
@@ -11,18 +11,28 @@ import {
11
11
  type FamilyAdapter,
12
12
  type Identity,
13
13
  type LoginHandle,
14
+ type ProxyState,
14
15
  type RedeemReply,
15
16
  type UsageRead,
16
17
  } from "./adapter";
17
18
  import { browserCaptureScript, providerCommand } from "./binaries";
18
19
  import { CLAUDE_RESET_PROGRAM, describeResetBlock, parseClaudeResets, readClaimReply } from "./claude-resets";
19
- import { prepareClaudeHome } from "./homes";
20
+ import { claudeClearTextProxy, claudeHomeHoldsAccount, prepareClaudeHome, readAccountApi, readAccountProxy, writeAccountApi, writeAccountProxy, type ApiConfig } from "./homes";
21
+ import { readJson } from "./json-file";
20
22
  import { detectClaudeLimit, detectClaudeSignOut } from "./limits";
23
+ import { inheritedClaudeProxy, mainProxyBlock, mainProxyEnv, mainSettingsEnv, readMainProxy, writeMainProxy } from "./main-proxy";
21
24
  import { mainClaudeGlobalConfig } from "./paths";
22
25
  import { firstUrl, run, stripAnsi } from "./process";
26
+ import { eachProcessEnvironment, homesInEnvironment as inEnvironment, parseTrace } from "./processes";
27
+ import { providerEnv } from "./provider-env";
28
+ import { bypassesProxy, noProxyFromEnv, proxiedFetch, proxyFromEnv } from "./proxy";
23
29
  import { retryDelayMs } from "./usage";
24
30
 
25
31
  const API = "https://api.anthropic.com";
32
+ /** Usage plus banked resets, and extra-usage spend (Claude Code's own /usage reads spend too). */
33
+ const USAGE_WITH_SPEND = `${API}/api/oauth/usage?cedar_ember=1`;
34
+ /** The same read without spend: the fallback, and all a reset redeem needs. */
35
+ const USAGE_WITHOUT_SPEND = `${USAGE_WITH_SPEND}&skip_spend=1`;
26
36
 
27
37
  function apiHeaders(token: string): Record<string, string> {
28
38
  return {
@@ -60,8 +70,15 @@ export class ClaudeAdapter implements FamilyAdapter {
60
70
  private readonly renewing = new Map<string, Promise<Credentials | null>>();
61
71
  private readonly resetNotes = new Map<string, string>();
62
72
 
73
+ constructor() {
74
+ // Off macOS and Linux, which processes run on a home can't be told (see `eachProcessEnvironment`),
75
+ // so `homesInUse` isn't offered: the service then keeps the accounts in `homes/`, without an error.
76
+ if (process.platform !== "darwin" && process.platform !== "linux") Object.defineProperty(this, "homesInUse", { value: undefined });
77
+ }
78
+
63
79
  async env(home: string | null): Promise<EnvPatch> {
64
- if (!home) return { CLAUDE_CONFIG_DIR: null, CLAUDE_SECURESTORAGE_CONFIG_DIR: null };
80
+ // The CLI login's proxy set here, unless main's settings set one (see `mainProxyEnv`).
81
+ if (!home) return { CLAUDE_CONFIG_DIR: null, CLAUDE_SECURESTORAGE_CONFIG_DIR: null, ...(await mainProxyEnv()) };
65
82
  // Both point at the home so the keychain entry and refresh locks follow it even when the
66
83
  // daemon itself runs with CLAUDE_SECURESTORAGE_CONFIG_DIR set.
67
84
  const patch: EnvPatch = { CLAUDE_CONFIG_DIR: home, CLAUDE_SECURESTORAGE_CONFIG_DIR: home };
@@ -76,19 +93,51 @@ export class ClaudeAdapter implements FamilyAdapter {
76
93
  return { ok: false, detail: (result.stderr || result.stdout).trim().split("\n")[0] || `${command} not found` };
77
94
  }
78
95
 
79
- prepareHome(home: string): Promise<void> {
80
- return prepareClaudeHome(home);
96
+ prepareHome(home: string, wanted?: () => Promise<boolean>): Promise<void> {
97
+ return prepareClaudeHome(home, false, wanted);
98
+ }
99
+
100
+ async proxyState(home: string | null): Promise<ProxyState> {
101
+ if (home) return { own: await readAccountProxy(home), file: null, inherited: await inheritedClaudeProxy(), blocked: null };
102
+ const { proxy, file } = await readMainProxy();
103
+ return { own: proxy, file, inherited: await inheritedClaudeProxy(true), blocked: await mainProxyBlock() };
104
+ }
105
+
106
+ setProxy(home: string | null, proxy: string | null, wanted?: () => Promise<boolean>): Promise<void> {
107
+ return home ? writeAccountProxy(home, proxy, wanted) : writeMainProxy(proxy);
108
+ }
109
+
110
+ egress(home: string | null): Promise<{ ip: string; country: string | null } | null> {
111
+ return claudeEgress(home);
112
+ }
113
+
114
+ api(home: string | null): Promise<ApiSummary | null> {
115
+ return home ? readAccountApi(home) : Promise.resolve(null);
116
+ }
117
+
118
+ clearTextProxy(home: string, baseUrl: string | null, through?: string): Promise<string | null> {
119
+ return claudeClearTextProxy(home, baseUrl, through);
120
+ }
121
+
122
+ setApi(home: string | null, config: ApiConfig, wanted?: () => Promise<boolean>): Promise<void> {
123
+ if (!home) return Promise.reject(new Error("Your Claude CLI login's key isn't set here."));
124
+ return writeAccountApi(home, config, wanted);
81
125
  }
82
126
 
83
127
  async identity(home: string | null): Promise<Identity> {
84
128
  const { command, prefix } = await providerCommand("claude");
85
129
  const result = await run(command, [...prefix, "auth", "status", "--json"], {
86
- env: spawnEnv(await this.env(home)),
130
+ env: spawnEnv(await this.env(home), "claude"),
87
131
  timeoutMs: 30_000,
88
132
  });
89
133
  const status = parseJsonObject(result.stdout);
90
134
  if (!status) throw new Error(result.stderr.trim() || "Could not read Claude sign-in status");
91
135
  const signedIn = status.loggedIn === true;
136
+ // Claude Code takes a Keychain entry it couldn't read (keychain locked, `security` slower than its
137
+ // 2 s limit) for no sign-in, so "signed out" only stands once the entry says so too.
138
+ if (!signedIn && (await keychainSignIn(home)) !== false) {
139
+ throw new Error("Claude reported no sign-in, but its keychain entry couldn't be read or still holds one");
140
+ }
92
141
  const email = str(status.email);
93
142
  const orgId = str(status.orgId);
94
143
  return {
@@ -108,15 +157,21 @@ export class ClaudeAdapter implements FamilyAdapter {
108
157
  if (credentials?.accessToken && isFresh(credentials) && profileScope) {
109
158
  try {
110
159
  // The `cedar_ember` read is the one Claude Code's /limit-reset makes: usage plus banked resets.
111
- const response = await fetch(`${API}/api/oauth/usage?cedar_ember=1&skip_spend=1`, {
112
- headers: apiHeaders(credentials.accessToken),
113
- signal: AbortSignal.timeout(15_000),
114
- });
160
+ // Spend (`extra_usage`) costs Anthropic another lookup, which `skip_spend` avoids; ask for it,
161
+ // and if it fails (except auth or rate limits), take the windows without it rather than none.
162
+ const token = credentials.accessToken;
163
+ const read = (url: string) => apiFetch(home, url, { headers: apiHeaders(token), signal: AbortSignal.timeout(15_000) });
164
+ let response = await read(USAGE_WITH_SPEND);
165
+ const withSpend = response.ok || [401, 403, 429].includes(response.status);
166
+ if (!withSpend) response = await read(USAGE_WITHOUT_SPEND);
115
167
  if (response.ok) {
116
- const body = (await response.json()) as { cedar_ember?: unknown };
168
+ const body = (await response.json()) as { cedar_ember?: unknown; extra_usage?: unknown };
117
169
  const windows = parseUsage(body);
118
170
  this.noteResetStatus(home, body.cedar_ember);
119
- return { fetchedAt, windows, error: null, cached: false, resets: parseClaudeResets(body.cedar_ember).offer, credits: null };
171
+ return {
172
+ fetchedAt, windows, error: null, cached: false, resets: parseClaudeResets(body.cedar_ember).offer, credits: null,
173
+ ...(withSpend ? { extraUsage: parseExtraUsage(body.extra_usage) } : {}),
174
+ };
120
175
  }
121
176
  // Anthropic rate-limits this endpoint (Claude Code and Paseo read it too). Wait as long as it
122
177
  // asks; meanwhile the last reading stays up, or Claude Code's own cached copy if it's newer.
@@ -160,7 +215,7 @@ export class ClaudeAdapter implements FamilyAdapter {
160
215
  pending = (async () => {
161
216
  const { command, prefix } = await providerCommand("claude");
162
217
  await run(command, [...prefix, "-p", "/usage", "--no-session-persistence", "--output-format", "json"], {
163
- env: spawnEnv(await this.env(home)),
218
+ env: spawnEnv(await this.env(home), "claude"),
164
219
  cwd: tmpdir(),
165
220
  timeoutMs: 90_000,
166
221
  });
@@ -182,7 +237,7 @@ export class ClaudeAdapter implements FamilyAdapter {
182
237
  // Ask which grant is next: the server only accepts that one.
183
238
  let status: ReturnType<typeof parseClaudeResets>;
184
239
  try {
185
- const response = await fetch(`${API}/api/oauth/usage?cedar_ember=1&skip_spend=1`, {
240
+ const response = await apiFetch(home, USAGE_WITHOUT_SPEND, {
186
241
  headers: apiHeaders(token),
187
242
  signal: AbortSignal.timeout(15_000),
188
243
  });
@@ -207,7 +262,7 @@ export class ClaudeAdapter implements FamilyAdapter {
207
262
  const organization = await this.organizationId(home);
208
263
  if (!organization) return { outcome: "error", message: "Couldn't tell which Claude organization this account belongs to.", left: null };
209
264
  try {
210
- const response = await fetch(`${API}/api/organizations/${organization}/reset_rate_limits`, {
265
+ const response = await apiFetch(home, `${API}/api/organizations/${organization}/reset_rate_limits`, {
211
266
  method: "POST",
212
267
  headers: apiHeaders(token),
213
268
  body: JSON.stringify({ program: CLAUDE_RESET_PROGRAM, grant_id: status.nextGrantId, request_id: randomUUID() }),
@@ -231,7 +286,7 @@ export class ClaudeAdapter implements FamilyAdapter {
231
286
  let id = typeof account?.organizationUuid === "string" ? account.organizationUuid : null;
232
287
  if (!id) {
233
288
  const { command, prefix } = await providerCommand("claude");
234
- const result = await run(command, [...prefix, "auth", "status", "--json"], { env: spawnEnv(await this.env(home)), timeoutMs: 30_000 });
289
+ const result = await run(command, [...prefix, "auth", "status", "--json"], { env: spawnEnv(await this.env(home), "claude"), timeoutMs: 30_000 });
235
290
  id = str(parseJsonObject(result.stdout)?.orgId);
236
291
  }
237
292
  return id && /^[0-9a-f-]{8,64}$/i.test(id) ? id : null;
@@ -241,7 +296,7 @@ export class ClaudeAdapter implements FamilyAdapter {
241
296
  const { command, prefix } = await providerCommand("claude");
242
297
  const shim = await browserCaptureScript();
243
298
  const capture = join(tmpdir(), `zerosub-login-${randomBytes(6).toString("hex")}.url`);
244
- const env = spawnEnv(await this.env(home));
299
+ const env = spawnEnv(await this.env(home), "claude");
245
300
  if (shim) {
246
301
  env.BROWSER = shim;
247
302
  env.ZEROSUB_BROWSER_OUT = capture;
@@ -251,12 +306,71 @@ export class ClaudeAdapter implements FamilyAdapter {
251
306
 
252
307
  async logout(home: string): Promise<void> {
253
308
  const { command, prefix } = await providerCommand("claude");
254
- const result = await run(command, [...prefix, "auth", "logout"], { env: spawnEnv(await this.env(home)), timeoutMs: 30_000 });
255
- if (result.code === 0 || process.platform !== "darwin") return; // Elsewhere the login lives in the home itself.
256
- // Don't leave a live refresh token behind in the keychain for a home that is about to be deleted.
257
- await run("/usr/bin/security", ["delete-generic-password", "-a", keychainAccount(), "-s", keychainService(home)], {
309
+ const result = await run(command, [...prefix, "auth", "logout"], { env: spawnEnv(await this.env(home), "claude"), timeoutMs: 30_000 });
310
+ if (process.platform !== "darwin") return; // Elsewhere the login lives in the home itself.
311
+ // Don't leave a live refresh token behind in the keychain for a home that is about to be deleted. The
312
+ // CLI's logout exits 0 even when its own delete of the entry failed, so the entry is checked either way.
313
+ const service = keychainService(home);
314
+ const removed = await run("/usr/bin/security", ["delete-generic-password", "-a", keychainAccount(), "-s", service], {
258
315
  timeoutMs: 10_000,
259
316
  });
317
+ if (removed.code === 0 || removed.code === KEYCHAIN_ITEM_NOT_FOUND) return;
318
+ // Thrown so the cleanup tries again later, rather than deleting the home over a live entry.
319
+ const why = removed.timedOut ? "timed out" : removed.stderr.trim() || `exit ${removed.code}`;
320
+ const signedOut = result.code === 0 ? "Signed" : "Couldn't sign";
321
+ throw new Error(`${signedOut} ${home} out, but couldn't remove its keychain entry "${service}" (${why})`);
322
+ }
323
+
324
+ /**
325
+ * Which of `homes` a Claude process runs on right now (started with that `CLAUDE_CONFIG_DIR`: by
326
+ * Paseo, or its script in a terminal), so its home isn't moved under it (see `Service.placeHomes`).
327
+ */
328
+ async homesInUse(homes: readonly string[]): Promise<Set<string>> {
329
+ const found = new Set<string>();
330
+ if (homes.length === 0) return found;
331
+ await eachProcessEnvironment((line) => {
332
+ for (const home of homesInEnvironment(line, homes)) found.add(home);
333
+ });
334
+ return found;
335
+ }
336
+
337
+ holdsAccount(home: string): Promise<boolean> {
338
+ return claudeHomeHoldsAccount(home);
339
+ }
340
+
341
+ async copyCredentials(from: string, to: string): Promise<void> {
342
+ if (process.platform !== "darwin") return; // Elsewhere the login lives in the home itself.
343
+ const secret = await readKeychainEntry(from);
344
+ // Signed out, or copied before and the old entry already gone: nothing to carry over.
345
+ if (secret === null) return;
346
+ if (!secret.trimStart().startsWith("{") || !parseJsonObject(secret)) {
347
+ throw new Error(`the Keychain entry "${keychainService(from)}" isn't what Claude Code writes, so ZeroSub left it where it is`);
348
+ }
349
+ const there = await readKeychainEntry(to);
350
+ if (there === secret) return;
351
+ if (there !== null) {
352
+ throw new Error(
353
+ `the Keychain entry "${keychainService(to)}", where Claude Code looks for ${to}'s sign-in, already holds another one. Delete it if nothing uses it any more, or pick another folder.`,
354
+ );
355
+ }
356
+ await writeKeychainEntry(to, secret);
357
+ if ((await readKeychainEntry(to)) !== secret) {
358
+ await deleteKeychainEntry(to).catch(() => undefined);
359
+ throw new Error(`copying the Keychain entry "${keychainService(from)}" to "${keychainService(to)}" didn't read back the same`);
360
+ }
361
+ }
362
+
363
+ async dropCopiedCredentials(from: string, to: string): Promise<void> {
364
+ if (process.platform !== "darwin") return;
365
+ const copy = await readKeychainEntry(to);
366
+ if (copy !== null && copy === (await readKeychainEntry(from))) await deleteKeychainEntry(to);
367
+ }
368
+
369
+ async dropOldCredentials(from: string, to: string): Promise<boolean> {
370
+ if (process.platform !== "darwin") return true;
371
+ if ((await readKeychainEntry(to)) === null) return (await readKeychainEntry(from)) === null;
372
+ await deleteKeychainEntry(from);
373
+ return true;
260
374
  }
261
375
 
262
376
  detectLimit = detectClaudeLimit;
@@ -358,6 +472,71 @@ function friendlyFailure(message: string): string {
358
472
  return message.replace(/^Login failed:\s*/i, "Sign-in failed: ");
359
473
  }
360
474
 
475
+ // --------------------------------------------------------------------------- network
476
+
477
+ /**
478
+ * The proxy Claude Code would use for this account to reach `target`, or null when it goes direct:
479
+ * the environment Paseo starts it with (the daemon's, with the provider's configured `env` over it,
480
+ * and for the CLI login the proxy set for it here) and the account's `settings.json` `env` applied
481
+ * on top, as Claude Code does at startup, then its no-proxy list. An added account's settings file
482
+ * that doesn't parse is an error, not "no proxy", so the token never leaves from the daemon's own
483
+ * address. Main's sets nothing then (see `mainSettingsEnv`), and the CLI login keeps the proxy set
484
+ * for it here.
485
+ */
486
+ export async function accountProxy(home: string | null, target: string): Promise<string | null> {
487
+ return proxyFor(await accountEnv(home), target);
488
+ }
489
+
490
+ /** The environment Claude Code starts with for this account (see `accountProxy`). */
491
+ async function accountEnv(home: string | null): Promise<Record<string, string | undefined>> {
492
+ const env: Record<string, string | undefined> = { ...process.env, ...providerEnv("claude") };
493
+ if (!home) return { ...env, ...(await mainProxyEnv()), ...(await mainSettingsEnv()) };
494
+ const settings = await readJson(join(home, "settings.json"));
495
+ const overrides = settings && typeof settings === "object" && !Array.isArray(settings) ? (settings as { env?: unknown }).env : undefined;
496
+ if (overrides && typeof overrides === "object" && !Array.isArray(overrides)) {
497
+ for (const [key, value] of Object.entries(overrides)) if (typeof value === "string") env[key] = value;
498
+ }
499
+ return env;
500
+ }
501
+
502
+ function proxyFor(env: Record<string, string | undefined>, target: string): string | null {
503
+ const proxy = proxyFromEnv(env);
504
+ return proxy && !bypassesProxy(noProxyFromEnv(env), target) ? proxy : null;
505
+ }
506
+
507
+ /** Anthropic's edge (Cloudflare) answers this with the address it sees the request come from. */
508
+ const TRACE = `${API}/cdn-cgi/trace`;
509
+
510
+ /**
511
+ * The address Anthropic sees this account's requests come from: asked of its own host through the
512
+ * account's proxy, so a proxy that routes by domain takes the way Claude Code's requests take (an
513
+ * IP service elsewhere could go another way). Null when the account's requests go to another base
514
+ * URL: whatever is there reaches Anthropic from its own address.
515
+ */
516
+ export async function claudeEgress(home: string | null): Promise<{ ip: string; country: string | null } | null> {
517
+ const env = await accountEnv(home);
518
+ const base = env.ANTHROPIC_BASE_URL?.trim();
519
+ if (base && hostOf(base) !== hostOf(API)) return null;
520
+ const response = await proxiedFetch(proxyFor(env, TRACE), TRACE, { signal: AbortSignal.timeout(10_000) });
521
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
522
+ const seen = parseTrace(await response.text());
523
+ if (!seen) throw new Error("The answer didn't say");
524
+ return seen;
525
+ }
526
+
527
+ function hostOf(url: string): string | null {
528
+ try {
529
+ return new URL(url).host;
530
+ } catch {
531
+ return null;
532
+ }
533
+ }
534
+
535
+ /** Calls Anthropic with an account's token from the address that account's Claude Code uses. */
536
+ async function apiFetch(home: string | null, url: string, init: { method?: string; headers: Record<string, string>; body?: string; signal: AbortSignal }): Promise<Response> {
537
+ return proxiedFetch(await accountProxy(home, url), url, init);
538
+ }
539
+
361
540
  // --------------------------------------------------------------------------- credentials (read-only)
362
541
 
363
542
  interface Credentials {
@@ -392,6 +571,68 @@ export function keychainService(home: string | null): string {
392
571
  return `Claude Code-credentials-${createHash("sha256").update(path.normalize("NFC")).digest("hex").slice(0, 8)}`;
393
572
  }
394
573
 
574
+ /** `security`'s exit code when there's no such keychain item (errSecItemNotFound). */
575
+ const KEYCHAIN_ITEM_NOT_FOUND = 44;
576
+
577
+ function keychainFailure(result: { code: number | null; stderr: string; timedOut: boolean }): string {
578
+ return result.timedOut ? "timed out" : result.stderr.trim() || `exit ${result.code}`;
579
+ }
580
+
581
+ /**
582
+ * The home's Keychain entry exactly as Claude Code wrote it, null when there's none. Only read to
583
+ * move it with its home (see `copyCredentials`); never logged or stored.
584
+ */
585
+ async function readKeychainEntry(home: string): Promise<string | null> {
586
+ const service = keychainService(home);
587
+ const result = await run("/usr/bin/security", ["find-generic-password", "-a", keychainAccount(), "-w", "-s", service], { timeoutMs: 10_000 });
588
+ if (result.code === KEYCHAIN_ITEM_NOT_FOUND) return null;
589
+ if (result.code !== 0) throw new Error(`couldn't read the Keychain entry "${service}" (${keychainFailure(result)})`);
590
+ return result.stdout.endsWith("\n") ? result.stdout.slice(0, -1) : result.stdout;
591
+ }
592
+
593
+ /** Longest command `security -i` takes on one line. */
594
+ const SECURITY_LINE_MAX = 4_000;
595
+
596
+ /**
597
+ * Writes the home's Keychain entry the way Claude Code does: through `security -i`'s standard
598
+ * input, so the secret never shows in the process list.
599
+ */
600
+ async function writeKeychainEntry(home: string, secret: string): Promise<void> {
601
+ const service = keychainService(home);
602
+ const line = `add-generic-password -U -a "${keychainAccount()}" -s "${service}" -X "${Buffer.from(secret, "utf8").toString("hex")}"\n`;
603
+ if (line.length > SECURITY_LINE_MAX) throw new Error(`the sign-in is too long to write to the Keychain entry "${service}" without showing it in the process list`);
604
+ const result = await run("/usr/bin/security", ["-i"], { input: line, timeoutMs: 10_000 });
605
+ if (result.code !== 0) throw new Error(`couldn't write the Keychain entry "${service}" (${keychainFailure(result)})`);
606
+ }
607
+
608
+ async function deleteKeychainEntry(home: string): Promise<void> {
609
+ const service = keychainService(home);
610
+ const result = await run("/usr/bin/security", ["delete-generic-password", "-a", keychainAccount(), "-s", service], { timeoutMs: 10_000 });
611
+ if (result.code !== 0 && result.code !== KEYCHAIN_ITEM_NOT_FOUND) {
612
+ throw new Error(`couldn't remove the Keychain entry "${service}" (${keychainFailure(result)})`);
613
+ }
614
+ }
615
+
616
+ /** The homes in `homes` a Claude process was started with (see `processes.ts`). */
617
+ export function homesInEnvironment(line: string, homes: readonly string[]): string[] {
618
+ return inEnvironment(line, homes, ["CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR"]);
619
+ }
620
+
621
+ /**
622
+ * Whether the home's Keychain entry holds a Claude sign-in: false once it's gone or holds none, null
623
+ * when it can't be read. Off macOS Claude Code keeps the sign-in in a file, and its answer stands.
624
+ * The token read here is only looked at, never logged or stored.
625
+ */
626
+ async function keychainSignIn(home: string | null): Promise<boolean | null> {
627
+ if (process.platform !== "darwin") return false;
628
+ const result = await run("/usr/bin/security", ["find-generic-password", "-a", keychainAccount(), "-w", "-s", keychainService(home)], {
629
+ timeoutMs: 10_000,
630
+ });
631
+ if (result.code === KEYCHAIN_ITEM_NOT_FOUND) return false;
632
+ if (result.code !== 0) return null;
633
+ return Boolean(parseCredentials(result.stdout)?.accessToken);
634
+ }
635
+
395
636
  function parseCredentials(raw: string): Credentials | null {
396
637
  let text = raw.trim();
397
638
  if (/^[0-9a-f]+$/i.test(text) && text.length % 2 === 0) text = Buffer.from(text, "hex").toString("utf8");
@@ -438,6 +679,20 @@ const WINDOW_LABELS: Array<[key: string, label: string]> = [
438
679
  ["seven_day_sonnet", "Weekly · Sonnet"],
439
680
  ];
440
681
 
682
+ /** The usage response's `extra_usage` block, or `null` when it's missing or says nothing usable. */
683
+ export function parseExtraUsage(block: unknown): ExtraUsage | null {
684
+ if (!block || typeof block !== "object") return null;
685
+ const record = block as Record<string, unknown>;
686
+ if (typeof record.is_enabled !== "boolean") return null;
687
+ const amount = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : null);
688
+ return {
689
+ enabled: record.is_enabled,
690
+ spend: amount(record.used_credits),
691
+ limit: amount(record.monthly_limit),
692
+ currency: typeof record.currency === "string" && record.currency ? record.currency : null,
693
+ };
694
+ }
695
+
441
696
  export function parseUsage(body: unknown): UsageWindow[] {
442
697
  if (!body || typeof body !== "object") return [];
443
698
  const record = body as Record<string, unknown>;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Opt-in handoff for two ChatGPT members of one workspace. `sameAccountIdentity` stays exact:
3
+ * different emails in one workspace are different accounts. This only asks whether the workspace
4
+ * id is the same, and only for keys shaped `chatgpt|<workspace>|<email>`.
5
+ */
6
+
7
+ import type { AgentTimelineItem } from "./adapter";
8
+ import { isTurnPrompt } from "./handoff";
9
+
10
+ /** `chatgpt|<workspace>|<email>`. An email-only key, or a workspace id with no member, is not one. */
11
+ const WORKSPACE_MEMBER = /^chatgpt\|([^|]+)\|([^|]+)$/;
12
+ const WORKSPACE_CREDITS = /^Your workspace is out of credits\b/i;
13
+ const RESUME_FAILURE =
14
+ /invalid_encrypted_content|organization[_ ]id mismatch|unable to decrypt|could not decrypt|can(?:no|')t decrypt|decryption failed|failed to decrypt|failed to verify (?:the )?encrypted|Native account resume selected a different thread or provider|Native resume selected a different provider/i;
15
+
16
+ export type CodexHandoff = "same-agent" | "new-tab";
17
+
18
+ export function sameWorkspace(left: string | null | undefined, right: string | null | undefined): boolean {
19
+ const a = left ? WORKSPACE_MEMBER.exec(left) : null;
20
+ const b = right ? WORKSPACE_MEMBER.exec(right) : null;
21
+ if (!a?.[1] || !b?.[1]) return false;
22
+ return a[1] === b[1];
23
+ }
24
+
25
+ export function workspaceOutOfCredits(message: string): boolean {
26
+ return WORKSPACE_CREDITS.test(message.trim());
27
+ }
28
+
29
+ /**
30
+ * Same-agent only when the option is on, both accounts are members of one workspace, the
31
+ * destination home really shares `sessions/`, and the limit is not the workspace credit pool.
32
+ * Anything else keeps today's new tab.
33
+ */
34
+ export function codexHandoffMode(input: {
35
+ enabled: boolean;
36
+ sameWorkspace: boolean;
37
+ sessionsShared: boolean;
38
+ limitMessage: string;
39
+ }): CodexHandoff {
40
+ if (!input.enabled || !input.sameWorkspace || !input.sessionsShared) return "new-tab";
41
+ if (workspaceOutOfCredits(input.limitMessage)) return "new-tab";
42
+ return "same-agent";
43
+ }
44
+
45
+ /** Text Codex or a native resume shows when the other account cannot read this thread. */
46
+ export function encryptedResumeFailure(text: string): boolean {
47
+ return RESUME_FAILURE.test(text);
48
+ }
49
+
50
+ /**
51
+ * The failure notices of one turn, not its ordinary replies. Paseo 0.12 and earlier send the whole
52
+ * conversation, so like `notices` in limits.ts the timeline is read back to this turn's prompt, and
53
+ * a turn that failed before it started has only its failure.
54
+ */
55
+ export function turnFailedText(event: {
56
+ outcome: { kind: string; error?: { message?: string } | null };
57
+ timeline?: readonly AgentTimelineItem[];
58
+ turnId?: string | null;
59
+ }): string {
60
+ const parts: string[] = [];
61
+ if (event.outcome.kind === "failed" && event.outcome.error?.message) parts.push(event.outcome.error.message);
62
+ const timeline = event.turnId === null ? [] : (event.timeline ?? []);
63
+ for (let index = timeline.length - 1; index >= 0; index -= 1) {
64
+ const item = timeline[index];
65
+ if (!item) continue;
66
+ if (isTurnPrompt(item)) break;
67
+ if (item.type === "error" && item.message) parts.push(item.message);
68
+ else if (item.type === "assistant_message" && item.text && /^\[System Error\]/.test(item.text)) parts.push(item.text);
69
+ }
70
+ return parts.join("\n");
71
+ }
package/server/codex.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  type RedeemReply,
12
12
  } from "./adapter";
13
13
  import { providerCommand } from "./binaries";
14
+ import { AZURE_KEY_ENV, azureIdentity, isAzureHome, readAzureAccount, syncAzureConfig } from "./azure";
14
15
  import { codexSqliteHome, prepareCodexHome } from "./homes";
15
16
  import { detectCodexLimit, detectCodexSignOut } from "./limits";
16
17
  import { run } from "./process";
@@ -70,7 +71,7 @@ class AppServer {
70
71
  try {
71
72
  await server.request(
72
73
  "initialize",
73
- { clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.5.1" }, capabilities: { experimentalApi: false } },
74
+ { clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.18.2" }, capabilities: { experimentalApi: false } },
74
75
  60_000,
75
76
  );
76
77
  server.send({ method: "initialized" });
@@ -204,6 +205,7 @@ export class CodexAdapter implements FamilyAdapter {
204
205
 
205
206
  async env(home: string | null): Promise<EnvPatch> {
206
207
  if (!home) return { CODEX_HOME: null, CODEX_SQLITE_HOME: null };
208
+ if (isAzureHome(home)) return this.azureEnv(home);
207
209
  const patch: EnvPatch = { CODEX_HOME: home };
208
210
  // Share thread metadata with the main home so every account sees the same threads.
209
211
  const sqlite = await codexSqliteHome();
@@ -212,6 +214,19 @@ export class CodexAdapter implements FamilyAdapter {
212
214
  return patch;
213
215
  }
214
216
 
217
+ /**
218
+ * An Azure OpenAI account's session: its home (whose `config.toml` selects ZeroSub's Azure provider,
219
+ * remade now if the shared one changed) and the key in the variable that provider reads. Throws when
220
+ * the key can't be read, so the session isn't opened on Azure without it.
221
+ */
222
+ private async azureEnv(home: string): Promise<EnvPatch> {
223
+ const { key } = await readAzureAccount(home);
224
+ await syncAzureConfig(home);
225
+ const patch: EnvPatch = { CODEX_HOME: home, CODEX_SQLITE_HOME: await codexSqliteHome(), [AZURE_KEY_ENV]: key };
226
+ if (process.env.CODEX_ACCESS_TOKEN) patch.CODEX_ACCESS_TOKEN = "";
227
+ return patch;
228
+ }
229
+
215
230
  async available(): Promise<{ ok: boolean; detail: string | null }> {
216
231
  const { command, prefix } = await providerCommand("codex");
217
232
  const result = await run(command, [...prefix, "--version"], { timeoutMs: 30_000 });
@@ -219,15 +234,24 @@ export class CodexAdapter implements FamilyAdapter {
219
234
  return { ok: false, detail: (result.stderr || result.stdout).trim().split("\n")[0] || `${command} not found` };
220
235
  }
221
236
 
222
- prepareHome(home: string): Promise<void> {
223
- return prepareCodexHome(home);
237
+ prepareHome(home: string, wanted?: () => Promise<boolean>): Promise<void> {
238
+ return prepareCodexHome(home, false, wanted);
224
239
  }
225
240
 
226
241
  async identity(home: string | null): Promise<Identity> {
242
+ if (isAzureHome(home)) {
243
+ // Nothing signs in: the key is checked when it's saved, and a refused one is learned from a turn.
244
+ const { endpoint, key } = await readAzureAccount(home);
245
+ return { signedIn: true, email: null, plan: "Azure OpenAI", organization: null, identity: azureIdentity(endpoint, key) };
246
+ }
227
247
  return (await this.snapshot(home)).identity;
228
248
  }
229
249
 
230
250
  async usage(home: string | null): Promise<Usage> {
251
+ if (isAzureHome(home)) {
252
+ // No plan windows: its tokens are counted per turn instead (see Service.countAzureTurn).
253
+ return { fetchedAt: new Date().toISOString(), windows: [], error: null, cached: false, resets: null, credits: null };
254
+ }
231
255
  return (await this.snapshot(home, true)).usage;
232
256
  }
233
257
 
@@ -267,7 +291,7 @@ export class CodexAdapter implements FamilyAdapter {
267
291
  }
268
292
 
269
293
  private async readSnapshot(home: string | null, signal: AbortSignal): Promise<Snapshot> {
270
- const server = await AppServer.open(spawnEnv(await this.env(home)), signal);
294
+ const server = await AppServer.open(spawnEnv(await this.env(home), "codex"), signal);
271
295
  try {
272
296
  const account = ((await server.request("account/read", {})) ?? {}) as Json;
273
297
  const details = account.account as { type?: unknown; email?: unknown; planType?: unknown } | null;
@@ -328,14 +352,17 @@ export class CodexAdapter implements FamilyAdapter {
328
352
  }
329
353
 
330
354
  async login(home: string | null, method: LoginMethod): Promise<LoginHandle> {
355
+ if (isAzureHome(home)) throw new Error("Azure OpenAI accounts use an API key: change it from the account's card.");
331
356
  this.snapshots.delete(home ?? "");
332
- const server = await AppServer.open(spawnEnv(await this.env(home)));
357
+ const server = await AppServer.open(spawnEnv(await this.env(home), "codex"));
333
358
  return new CodexLogin(server, method, () => this.snapshots.delete(home ?? ""));
334
359
  }
335
360
 
336
361
  async logout(home: string): Promise<void> {
362
+ // Nothing is signed in: deleting the home (and its azure.json) is all removing it takes.
363
+ if (isAzureHome(home)) return;
337
364
  this.snapshots.delete(home);
338
- const server = await AppServer.open(spawnEnv(await this.env(home)));
365
+ const server = await AppServer.open(spawnEnv(await this.env(home), "codex"));
339
366
  try {
340
367
  await server.request("account/logout");
341
368
  } finally {
@@ -348,8 +375,9 @@ export class CodexAdapter implements FamilyAdapter {
348
375
  * credit while nothing is used up (`nothingToReset`), so automatic use needs no extra check.
349
376
  */
350
377
  async redeemReset(home: string | null): Promise<RedeemReply> {
378
+ if (isAzureHome(home)) return { outcome: "none", message: "Azure OpenAI accounts have no banked resets.", left: 0 };
351
379
  this.snapshots.delete(home ?? "");
352
- const server = await AppServer.open(spawnEnv(await this.env(home)));
380
+ const server = await AppServer.open(spawnEnv(await this.env(home), "codex"));
353
381
  try {
354
382
  // One idempotency key per attempt, so a retried request can never spend a second credit.
355
383
  const reply = (await server.request(