@phren/cli 0.3.11 → 0.3.12

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 (168) hide show
  1. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  2. package/dist/bridge/agent-hook-stores.js +5 -0
  3. package/dist/bridge/agent-hooks.d.ts +159 -5
  4. package/dist/bridge/agent-hooks.js +663 -49
  5. package/dist/bridge/approval-summary.d.ts +16 -0
  6. package/dist/bridge/approval-summary.js +133 -0
  7. package/dist/bridge/authority-command.d.ts +20 -0
  8. package/dist/bridge/authority-command.js +120 -0
  9. package/dist/bridge/authority.d.ts +223 -0
  10. package/dist/bridge/authority.js +231 -0
  11. package/dist/bridge/claude-account-setup.d.ts +14 -0
  12. package/dist/bridge/claude-account-setup.js +69 -0
  13. package/dist/bridge/claude-accounts.d.ts +49 -0
  14. package/dist/bridge/claude-accounts.js +195 -0
  15. package/dist/bridge/code-routes.js +2 -2
  16. package/dist/bridge/codex-app-server.d.ts +144 -0
  17. package/dist/bridge/codex-app-server.js +319 -0
  18. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  19. package/dist/bridge/codex-auth-refresh.js +71 -0
  20. package/dist/bridge/codex-question-reply.d.ts +16 -0
  21. package/dist/bridge/codex-question-reply.js +57 -0
  22. package/dist/bridge/codex-review-mode.d.ts +10 -0
  23. package/dist/bridge/codex-review-mode.js +74 -0
  24. package/dist/bridge/codex-servers.d.ts +217 -0
  25. package/dist/bridge/codex-servers.js +636 -0
  26. package/dist/bridge/command.js +94 -4
  27. package/dist/bridge/computer-identity.d.ts +75 -0
  28. package/dist/bridge/computer-identity.js +166 -0
  29. package/dist/bridge/conductor-group.d.ts +91 -8
  30. package/dist/bridge/conductor-group.js +105 -9
  31. package/dist/bridge/conductor-role.d.ts +94 -0
  32. package/dist/bridge/conductor-role.js +176 -0
  33. package/dist/bridge/conductor-sets.d.ts +20 -0
  34. package/dist/bridge/conductor-sets.js +59 -0
  35. package/dist/bridge/dispatch-command.d.ts +3 -0
  36. package/dist/bridge/dispatch-command.js +75 -11
  37. package/dist/bridge/dispatch-returns.d.ts +123 -19
  38. package/dist/bridge/dispatch-returns.js +357 -50
  39. package/dist/bridge/dispatch.d.ts +103 -2
  40. package/dist/bridge/dispatch.js +272 -40
  41. package/dist/bridge/fanouts.d.ts +7 -1
  42. package/dist/bridge/fanouts.js +39 -4
  43. package/dist/bridge/folder-trust.d.ts +56 -0
  44. package/dist/bridge/folder-trust.js +195 -0
  45. package/dist/bridge/grants.d.ts +22 -1
  46. package/dist/bridge/grants.js +57 -9
  47. package/dist/bridge/hand-off.d.ts +21 -9
  48. package/dist/bridge/hand-off.js +58 -45
  49. package/dist/bridge/harness-status.d.ts +11 -0
  50. package/dist/bridge/harness-status.js +32 -0
  51. package/dist/bridge/harnesses.d.ts +39 -0
  52. package/dist/bridge/harnesses.js +65 -0
  53. package/dist/bridge/health.d.ts +2 -0
  54. package/dist/bridge/health.js +1 -1
  55. package/dist/bridge/herdr.d.ts +11 -2
  56. package/dist/bridge/herdr.js +98 -23
  57. package/dist/bridge/hook-fast.d.ts +4 -0
  58. package/dist/bridge/hook-fast.js +68 -0
  59. package/dist/bridge/install.d.ts +16 -1
  60. package/dist/bridge/install.js +88 -21
  61. package/dist/bridge/launch-brief.d.ts +96 -0
  62. package/dist/bridge/launch-brief.js +164 -0
  63. package/dist/bridge/model-switch.d.ts +3 -0
  64. package/dist/bridge/model-switch.js +17 -1
  65. package/dist/bridge/models.d.ts +8 -4
  66. package/dist/bridge/models.js +24 -8
  67. package/dist/bridge/mux-wire.d.ts +9 -0
  68. package/dist/bridge/mux-wire.js +19 -0
  69. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  70. package/dist/bridge/opencode-pane-server.js +332 -0
  71. package/dist/bridge/opencode-panes.d.ts +111 -0
  72. package/dist/bridge/opencode-panes.js +295 -0
  73. package/dist/bridge/pane-accounts.d.ts +8 -0
  74. package/dist/bridge/pane-accounts.js +46 -0
  75. package/dist/bridge/prompt-startup.d.ts +5 -0
  76. package/dist/bridge/prompt-startup.js +24 -0
  77. package/dist/bridge/protocol.d.ts +5 -0
  78. package/dist/bridge/protocol.js +4 -0
  79. package/dist/bridge/push.d.ts +5 -4
  80. package/dist/bridge/push.js +6 -4
  81. package/dist/bridge/questions.d.ts +37 -2
  82. package/dist/bridge/questions.js +158 -15
  83. package/dist/bridge/resources.d.ts +9 -3
  84. package/dist/bridge/resources.js +24 -8
  85. package/dist/bridge/schedule-format.d.ts +2 -0
  86. package/dist/bridge/schedule-format.js +3 -0
  87. package/dist/bridge/schedule-launch.d.ts +2 -1
  88. package/dist/bridge/schedule-launch.js +23 -53
  89. package/dist/bridge/schedule-watch.d.ts +10 -1
  90. package/dist/bridge/schedule-watch.js +54 -2
  91. package/dist/bridge/server-launch.d.ts +22 -5
  92. package/dist/bridge/server-launch.js +225 -29
  93. package/dist/bridge/server-overview.d.ts +3 -3
  94. package/dist/bridge/server-overview.js +22 -14
  95. package/dist/bridge/server-pane-routes.d.ts +2 -0
  96. package/dist/bridge/server-pane-routes.js +145 -15
  97. package/dist/bridge/server-routes.d.ts +7 -0
  98. package/dist/bridge/server-routes.js +163 -35
  99. package/dist/bridge/server-stream.d.ts +2 -0
  100. package/dist/bridge/server-stream.js +22 -8
  101. package/dist/bridge/server.d.ts +6 -1
  102. package/dist/bridge/server.js +44 -12
  103. package/dist/bridge/session-activity.d.ts +81 -0
  104. package/dist/bridge/session-activity.js +117 -0
  105. package/dist/bridge/session-rename.d.ts +48 -0
  106. package/dist/bridge/session-rename.js +190 -0
  107. package/dist/bridge/session-servers.js +2 -2
  108. package/dist/bridge/settings-switch.d.ts +60 -0
  109. package/dist/bridge/settings-switch.js +287 -0
  110. package/dist/bridge/speech-voice.d.ts +55 -0
  111. package/dist/bridge/speech-voice.js +132 -0
  112. package/dist/bridge/speech.d.ts +70 -11
  113. package/dist/bridge/speech.js +169 -41
  114. package/dist/bridge/terminal-herdr.js +9 -3
  115. package/dist/bridge/terminal-tmux.d.ts +3 -3
  116. package/dist/bridge/terminal-tmux.js +24 -9
  117. package/dist/bridge/terminal.d.ts +27 -4
  118. package/dist/bridge/terminal.js +8 -1
  119. package/dist/bridge/transcript-claude.js +57 -12
  120. package/dist/bridge/transcript-codex.d.ts +0 -2
  121. package/dist/bridge/transcript-codex.js +29 -4
  122. package/dist/bridge/transcript-preview.d.ts +1 -0
  123. package/dist/bridge/transcript-preview.js +24 -4
  124. package/dist/bridge/transcripts.d.ts +15 -2
  125. package/dist/bridge/transcripts.js +47 -16
  126. package/dist/bridge/turn-records.d.ts +85 -0
  127. package/dist/bridge/turn-records.js +143 -0
  128. package/dist/bridge/uploads.d.ts +3 -0
  129. package/dist/bridge/uploads.js +14 -0
  130. package/dist/bridge/usage.d.ts +39 -10
  131. package/dist/bridge/usage.js +155 -44
  132. package/dist/bridge-hook.mjs +19169 -13176
  133. package/dist/cli/claude-unmanaged.d.ts +12 -0
  134. package/dist/cli/claude-unmanaged.js +105 -0
  135. package/dist/cli/schedules.js +2 -1
  136. package/dist/cli/session-start.js +10 -1
  137. package/dist/cli/session-stop.js +9 -1
  138. package/dist/cli-registry.js +24 -5
  139. package/dist/data/task-receipts.d.ts +19 -0
  140. package/dist/data/task-receipts.js +68 -0
  141. package/dist/data/tasks.js +4 -1
  142. package/dist/generated/memory-ui-graph.browser.js +63 -63
  143. package/dist/graph-core/model.js +24 -3
  144. package/dist/graph-core/types.d.ts +4 -1
  145. package/dist/graph-core/types.js +1 -0
  146. package/dist/init/init-preset.js +7 -3
  147. package/dist/init/init-uninstall.js +2 -11
  148. package/dist/init/teardown.d.ts +3 -0
  149. package/dist/init/teardown.js +47 -0
  150. package/dist/link/context.js +21 -9
  151. package/dist/mcp/plugin-mode.js +1 -1
  152. package/dist/memory-ui-graph.runtime.js +63 -63
  153. package/dist/modules/code-package.d.ts +1 -0
  154. package/dist/modules/code-package.js +36 -7
  155. package/dist/modules/registry.js +14 -13
  156. package/dist/profile-store.d.ts +6 -0
  157. package/dist/profile-store.js +25 -1
  158. package/dist/shell/graph/glyphs.js +4 -0
  159. package/dist/shell/graph/graph-view.js +2 -0
  160. package/dist/status.js +7 -1
  161. package/dist/sync/task-claim.js +3 -2
  162. package/dist/task/lifecycle.js +25 -4
  163. package/dist/test-global-setup.js +5 -0
  164. package/dist/tools/dispatch.js +35 -2
  165. package/dist/tools/tasks.js +10 -1
  166. package/package.json +1 -1
  167. package/plugins/opencode/phren-transcript.js +87 -4
  168. package/starter/global/skills/conductor/SKILL.md +17 -2
@@ -15,3 +15,6 @@ export declare function listUploads(session: string): Promise<{
15
15
  * any link) to a regular file inside the uploads folder whose bytes are
16
16
  * an image; anything else — outside, traversal, a note — is 404. */
17
17
  export declare function uploadImage(requested: string): Promise<Buffer>;
18
+ /** A file the phone uploaded for this conversation, by the path `/v1/upload`
19
+ * returned: it must resolve to a regular file inside uploads/<session>/. */
20
+ export declare function sessionUpload(session: string, requested: string): Promise<string>;
@@ -85,3 +85,17 @@ export async function uploadImage(requested) {
85
85
  throw missing;
86
86
  return bytes;
87
87
  }
88
+ /** A file the phone uploaded for this conversation, by the path `/v1/upload`
89
+ * returned: it must resolve to a regular file inside uploads/<session>/. */
90
+ export async function sessionUpload(session, requested) {
91
+ const refused = new BridgeError(400, "An attachment is not one of this conversation's uploads. Attach it again.");
92
+ if (!requested || requested.length > 4096 || !path.isAbsolute(requested))
93
+ throw refused;
94
+ const folder = await realpath(path.join(bridgeRoot(), "uploads", session)).catch(() => undefined);
95
+ const file = await realpath(requested).catch(() => undefined);
96
+ if (!folder || !file || !file.startsWith(folder + path.sep))
97
+ throw refused;
98
+ if (!(await stat(file)).isFile())
99
+ throw refused;
100
+ return file;
101
+ }
@@ -1,4 +1,5 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { type AccountRef, type ClaudeHome } from "./claude-accounts.js";
2
3
  export interface UsageWindow {
3
4
  id: string;
4
5
  name: string;
@@ -8,17 +9,22 @@ export interface UsageWindow {
8
9
  usedUSD?: number;
9
10
  limitUSD?: number;
10
11
  usedTokens?: number;
12
+ /** ElevenLabs' character quota, next to its percentage. */
13
+ usedCharacters?: number;
14
+ limitCharacters?: number;
11
15
  resetsAt?: string;
12
16
  /** The service says this window is refusing requests now (OpenCode Go's `rate-limited`). */
13
17
  limited?: boolean;
14
18
  asOf?: string;
19
+ /** The window's reset time passed after its report: no percent is known, so none is sent. */
20
+ reset?: boolean;
15
21
  }
16
22
  export interface UsageSpend {
17
23
  amountUSD: number;
18
24
  period: "rolling_7_days" | "rolling_30_days" | "calendar_week";
19
25
  }
20
26
  export interface AccountUsage {
21
- source: "codex" | "claude" | "opencode" | "opencode-go" | "openrouter" | "copilot";
27
+ source: "codex" | "claude" | "opencode" | "opencode-go" | "openrouter" | "copilot" | "elevenlabs";
22
28
  windows: UsageWindow[];
23
29
  updatedAt?: string;
24
30
  message?: string;
@@ -29,6 +35,8 @@ export interface AccountUsage {
29
35
  * or the OAuth usage endpoint. Per-model windows the status line never
30
36
  * carries document their own age through each window's asOf instead. */
31
37
  origin?: "status-line" | "oauth";
38
+ /** Which account this row is: a Claude home, or Codex's single one. Older phones ignore it. */
39
+ account?: AccountRef;
32
40
  }
33
41
  export declare function codexUsage(value: unknown, now?: Date): AccountUsage;
34
42
  /** Parse OpenCode's own cost ledger. `stats --days 7` is a rolling local view. */
@@ -70,6 +78,10 @@ export declare function readOpenCodeGoUsage(now?: Date, options?: {
70
78
  }): Promise<AccountUsage>;
71
79
  /** OpenRouter reports the current UTC calendar week's charged usage per key. */
72
80
  export declare function fetchOpenRouterUsage(key: string, fetchImpl?: typeof fetch, now?: Date): Promise<AccountUsage>;
81
+ /** ElevenLabs' subscription: characters used this billing period against the plan's limit. */
82
+ export declare function elevenLabsUsage(value: unknown, now?: Date): AccountUsage;
83
+ /** The key the Hook already uses for /v1/speech, sent only to ElevenLabs; the answer carries counts, never the key. */
84
+ export declare function fetchElevenLabsUsage(key: string, fetchImpl?: typeof fetch, now?: Date): Promise<AccountUsage>;
73
85
  /** Claude Code's documented status-line payload: rate_limits carries the
74
86
  * five_hour and seven_day windows (the 5h/7d unified limits) and, when the
75
87
  * build emits them, per-model keys such as seven_day_fable. Every window
@@ -96,9 +108,10 @@ export declare function claudeOAuthUsage(value: unknown, now?: Date): AccountUsa
96
108
  * Claude Code's own sign-in token, read locally and used only against
97
109
  * Anthropic's usage endpoint — never persisted, logged, or sent elsewhere.
98
110
  * The file is authoritative off macOS; macOS keeps it in the login keychain,
99
- * with the file left stale after a refresh.
111
+ * with the file left stale after a refresh. A non-default `home` reads only its
112
+ * own file, and nothing on macOS (its keychain item name is unverified).
100
113
  */
101
- export declare function readClaudeToken(execSecurity?: typeof execFile.__promisify__, platform?: NodeJS.Platform): Promise<string | undefined>;
114
+ export declare function readClaudeToken(execSecurity?: typeof execFile.__promisify__, platform?: NodeJS.Platform, home?: ClaudeHome): Promise<string | undefined>;
102
115
  /** Fetch live limits; any failure falls back to the local snapshot. */
103
116
  export declare function fetchClaudeUsage(token: string, fetchImpl?: typeof fetch, now?: Date): Promise<AccountUsage>;
104
117
  /** Only initialize and read limits. Never create a thread, prompt, or login. */
@@ -111,6 +124,15 @@ export declare function readCodexLimits(executable?: string): Promise<AccountUsa
111
124
  export declare function copilotUsage(value: unknown, now?: Date): AccountUsage;
112
125
  /** Reads through the GitHub CLI's own sign-in; the token never reaches Phren. */
113
126
  export declare function readCopilotUsage(now?: Date, run?: (file: string, args: string[]) => Promise<string>): Promise<AccountUsage>;
127
+ /** A Claude report older than this says nothing about the account now. */
128
+ export declare const CLAUDE_REPORT_MAX_AGE_MS: number;
129
+ /**
130
+ * What a saved Claude report still says at `now`: a window whose reset time
131
+ * has passed is reported as reset without its old percent, and a report
132
+ * older than three days is dropped, so a stale number never reaches the
133
+ * phone's cards, rings or widgets.
134
+ */
135
+ export declare function settleClaudeUsage(usage: AccountUsage, now: number): AccountUsage;
114
136
  export declare class AccountUsageReader {
115
137
  private readCodex;
116
138
  private now;
@@ -119,19 +141,26 @@ export declare class AccountUsageReader {
119
141
  private readOpenRouter;
120
142
  private readOpenCodeGo;
121
143
  private readCopilot;
144
+ private platform;
145
+ private readElevenLabs;
122
146
  private cached?;
123
147
  private pending?;
124
- private claudeCached?;
125
- private claudePending?;
126
- private spendingCached?;
127
- private spendingPending?;
128
- constructor(readCodex?: typeof readCodexLimits, now?: () => number, readClaudeLive?: (now: Date) => Promise<AccountUsage | undefined>, readOpenCode?: (now: Date) => Promise<AccountUsage>, readOpenRouter?: (now: Date) => Promise<AccountUsage | undefined>, readOpenCodeGo?: (now: Date) => Promise<AccountUsage>, readCopilot?: (now: Date) => Promise<AccountUsage>);
129
- read(): Promise<{
148
+ private claudeCached;
149
+ private claudePending;
150
+ private spendingCached;
151
+ private spendingPending;
152
+ constructor(readCodex?: typeof readCodexLimits, now?: () => number, readClaudeLive?: (now: Date, home: ClaudeHome) => Promise<AccountUsage | undefined>, readOpenCode?: (now: Date) => Promise<AccountUsage>, readOpenRouter?: (now: Date) => Promise<AccountUsage | undefined>, readOpenCodeGo?: (now: Date) => Promise<AccountUsage>, readCopilot?: (now: Date) => Promise<AccountUsage>, platform?: NodeJS.Platform, readElevenLabs?: (now: Date) => Promise<AccountUsage | undefined>);
153
+ /** `allAccounts`: one Claude row per home. Otherwise only the default home's, as
154
+ * before accounts existed, since older phones refuse two rows of one source. */
155
+ read(sources?: Set<string>, allAccounts?: boolean): Promise<{
130
156
  accounts: AccountUsage[];
131
157
  }>;
158
+ /** ElevenLabs is read only when the caller shows it: every read spends a request against the key's quota. */
132
159
  private spending;
133
160
  /** Live first, so the phone's minute-by-minute poll keeps Claude current
134
- * even when Claude Code is not running; the local snapshot is the backup. */
161
+ * even when Claude Code is not running; the local snapshot is the backup.
162
+ * Off macOS a non-default home reads its own credentials file; on macOS it
163
+ * has no live read (the keychain item name for custom homes is unverified). */
135
164
  private claude;
136
165
  private snapshotClaude;
137
166
  }
@@ -3,14 +3,17 @@ import { createHash } from "node:crypto";
3
3
  import { statSync } from "node:fs";
4
4
  import { lstat, open, readFile, readdir } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
- import { claudeConfigDir, homeDir } from "../home-paths.js";
6
+ import { claudeConfigDir } from "../home-paths.js";
7
7
  import path from "node:path";
8
8
  import { promisify } from "node:util";
9
9
  import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
10
10
  import { stripTerminal } from "../terminal-text.js";
11
11
  import { codexExecutable } from "./codex-binary.js";
12
+ import { readSpeechKey } from "./speech-key.js";
13
+ import { CODEX_ACCOUNT, claudeAccountEmail, claudeAccountRef, claudeHomeOfEnv, claudeHomes } from "./claude-accounts.js";
12
14
  const exec = promisify(execFile);
13
- const claudeFile = () => path.join(bridgeRoot(), "usage", "claude.json");
15
+ /** The status-line snapshot: `usage/claude.json` for the default home, `usage/claude-<id>.json` for others. */
16
+ const claudeFile = (home) => path.join(bridgeRoot(), "usage", home && !home.isDefault ? `claude-${home.id}.json` : "claude.json");
14
17
  const safeText = (v) => typeof v === "string" ? v.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 100) : undefined;
15
18
  function window(id, name, percent, reset) {
16
19
  if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100)
@@ -292,6 +295,49 @@ async function liveOpenRouterUsage(now) {
292
295
  return { source: "openrouter", windows: [], message: "Could not read OpenRouter spend. Check its key in OpenCode." };
293
296
  }
294
297
  }
298
+ /** ElevenLabs' subscription: characters used this billing period against the plan's limit. */
299
+ export function elevenLabsUsage(value, now = new Date()) {
300
+ const sub = object(value);
301
+ const used = sub.character_count, limit = sub.character_limit;
302
+ const count = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
303
+ if (!count(used) || !count(limit) || limit === 0) {
304
+ return { source: "elevenlabs", windows: [], updatedAt: now.toISOString(), message: "ElevenLabs did not report a character limit for this key." };
305
+ }
306
+ const entry = window("elevenlabs:characters", "Characters this period", Math.min(100, Math.round(used / limit * 1000) / 10), sub.next_character_count_reset_unix);
307
+ return { source: "elevenlabs", windows: entry ? [{ ...entry, usedCharacters: used, limitCharacters: limit }] : [], updatedAt: now.toISOString() };
308
+ }
309
+ /** The key the Hook already uses for /v1/speech, sent only to ElevenLabs; the answer carries counts, never the key. */
310
+ export async function fetchElevenLabsUsage(key, fetchImpl = fetch, now = new Date()) {
311
+ const controller = new AbortController();
312
+ const timer = setTimeout(() => controller.abort(), 8_000);
313
+ try {
314
+ const response = await fetchImpl("https://api.elevenlabs.io/v1/user/subscription", {
315
+ headers: { "xi-api-key": key, accept: "application/json" },
316
+ redirect: "error",
317
+ signal: controller.signal,
318
+ });
319
+ if (!response.ok)
320
+ throw new Error(`ElevenLabs subscription endpoint returned ${response.status}.`);
321
+ return elevenLabsUsage(await response.json(), now);
322
+ }
323
+ finally {
324
+ clearTimeout(timer);
325
+ }
326
+ }
327
+ /** No row without a key: most computers have no spoken replies set up. `PHREN_ELEVENLABS_USAGE=off` skips it (the test suite does). */
328
+ async function liveElevenLabsUsage(now) {
329
+ if (typeof fetch !== "function" || process.env.PHREN_ELEVENLABS_USAGE === "off")
330
+ return undefined;
331
+ const key = await readSpeechKey().catch(() => undefined);
332
+ if (!key)
333
+ return undefined;
334
+ try {
335
+ return await fetchElevenLabsUsage(key, fetch, now);
336
+ }
337
+ catch {
338
+ return { source: "elevenlabs", windows: [], updatedAt: now.toISOString(), message: "Could not read ElevenLabs usage. Check this computer's ElevenLabs key." };
339
+ }
340
+ }
295
341
  /** "seven_day_fable" → "7-day, Fable"; weekly-all stays explicit. */
296
342
  function claudeWindowName(key) {
297
343
  const spans = [["five_hour", "5-hour"], ["seven_day", "7-day"], ["one_hour", "1-hour"], ["one_day", "1-day"]];
@@ -356,9 +402,7 @@ export function claudeScopedWindows(config, now = new Date()) {
356
402
  }
357
403
  return windows;
358
404
  }
359
- // Claude keeps .claude.json inside CLAUDE_CONFIG_DIR when set, else beside ~/.claude.
360
- const claudeConfigFile = () => path.join(process.env.CLAUDE_CONFIG_DIR?.trim() ? claudeConfigDir() : homeDir(), ".claude.json");
361
- const claudeCredentialsFile = () => path.join(claudeConfigDir(), ".credentials.json");
405
+ const claudeCredentialsFile = (home) => path.join(home?.dir ?? claudeConfigDir(), ".credentials.json");
362
406
  /**
363
407
  * The OAuth usage endpoint Claude Code itself reads, mapped to the same
364
408
  * windows the status-line snapshot produces. `limits` is the structured
@@ -401,9 +445,10 @@ export function claudeOAuthUsage(value, now = new Date()) {
401
445
  * Claude Code's own sign-in token, read locally and used only against
402
446
  * Anthropic's usage endpoint — never persisted, logged, or sent elsewhere.
403
447
  * The file is authoritative off macOS; macOS keeps it in the login keychain,
404
- * with the file left stale after a refresh.
448
+ * with the file left stale after a refresh. A non-default `home` reads only its
449
+ * own file, and nothing on macOS (its keychain item name is unverified).
405
450
  */
406
- export async function readClaudeToken(execSecurity = exec, platform = process.platform) {
451
+ export async function readClaudeToken(execSecurity = exec, platform = process.platform, home) {
407
452
  const parse = (raw) => {
408
453
  if (raw.length > 16_384)
409
454
  return undefined;
@@ -414,6 +459,9 @@ export async function readClaudeToken(execSecurity = exec, platform = process.pl
414
459
  return undefined;
415
460
  return token;
416
461
  };
462
+ const other = home !== undefined && !home.isDefault;
463
+ if (other && platform === "darwin")
464
+ return undefined;
417
465
  if (platform === "darwin") {
418
466
  try {
419
467
  const { stdout } = await execSecurity("security", ["find-generic-password", "-s", "Claude Code-credentials", "-w"], { timeout: 5_000, maxBuffer: 16_384 });
@@ -424,7 +472,7 @@ export async function readClaudeToken(execSecurity = exec, platform = process.pl
424
472
  catch { /* Headless installs can keep credentials in the file instead. */ }
425
473
  }
426
474
  try {
427
- return parse(await readFile(claudeCredentialsFile(), "utf8"));
475
+ return parse(await readFile(claudeCredentialsFile(home), "utf8"));
428
476
  }
429
477
  catch {
430
478
  return undefined;
@@ -448,10 +496,10 @@ export async function fetchClaudeUsage(token, fetchImpl = fetch, now = new Date(
448
496
  clearTimeout(timer);
449
497
  }
450
498
  }
451
- async function liveClaudeUsage(now) {
499
+ async function liveClaudeUsage(now, home) {
452
500
  if (typeof fetch !== "function")
453
501
  return undefined;
454
- const token = await readClaudeToken();
502
+ const token = await readClaudeToken(exec, process.platform, home);
455
503
  if (!token)
456
504
  return undefined;
457
505
  try {
@@ -569,10 +617,40 @@ export async function readCopilotUsage(now = new Date(), run = async (file, args
569
617
  try {
570
618
  return copilotUsage(JSON.parse(await run(ghExecutable(), ["api", "/copilot_internal/user"])), now);
571
619
  }
572
- catch {
573
- return { source: "copilot", windows: [], message: "Could not read Copilot usage. Sign in with gh auth login on this computer (Copilot reports its quotas through GitHub)." };
620
+ catch (error) {
621
+ const failure = object(error);
622
+ const detail = [failure.stderr, failure.message].filter((part) => typeof part === "string").join(" ");
623
+ return { source: "copilot", windows: [], message: /\bHTTP 404\b/i.test(detail)
624
+ ? "No Copilot subscription on this GitHub account"
625
+ : "Could not read Copilot usage. Sign in with gh auth login on this computer (Copilot reports its quotas through GitHub)." };
574
626
  }
575
627
  }
628
+ /** A Claude report older than this says nothing about the account now. */
629
+ export const CLAUDE_REPORT_MAX_AGE_MS = 3 * 86_400_000;
630
+ /**
631
+ * What a saved Claude report still says at `now`: a window whose reset time
632
+ * has passed is reported as reset without its old percent, and a report
633
+ * older than three days is dropped, so a stale number never reaches the
634
+ * phone's cards, rings or widgets.
635
+ */
636
+ export function settleClaudeUsage(usage, now) {
637
+ if (!usage.windows.length)
638
+ return usage;
639
+ const reported = (w) => Date.parse(w.asOf ?? usage.updatedAt ?? "");
640
+ const windows = usage.windows
641
+ .filter(w => { const at = reported(w); return !Number.isFinite(at) || now - at < CLAUDE_REPORT_MAX_AGE_MS; })
642
+ .map(w => {
643
+ const reset = w.resetsAt ? Date.parse(w.resetsAt) : NaN;
644
+ if (!Number.isFinite(reset) || reset > now)
645
+ return w;
646
+ const { usedPercent: _old, ...rest } = w;
647
+ return { ...rest, reset: true };
648
+ });
649
+ if (windows.length)
650
+ return { ...usage, windows };
651
+ const since = usage.updatedAt?.slice(0, 10);
652
+ return { ...usage, windows, message: `No usage report from Claude on this computer${since ? ` since ${since}` : ""}. It updates when Claude Code runs here.` };
653
+ }
576
654
  export class AccountUsageReader {
577
655
  readCodex;
578
656
  now;
@@ -581,13 +659,15 @@ export class AccountUsageReader {
581
659
  readOpenRouter;
582
660
  readOpenCodeGo;
583
661
  readCopilot;
662
+ platform;
663
+ readElevenLabs;
584
664
  cached;
585
665
  pending;
586
- claudeCached;
587
- claudePending;
588
- spendingCached;
589
- spendingPending;
590
- constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = now => readOpenCodeUsage("opencode", now), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage, readCopilot = readCopilotUsage) {
666
+ claudeCached = new Map();
667
+ claudePending = new Map();
668
+ spendingCached = new Map();
669
+ spendingPending = new Map();
670
+ constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = now => readOpenCodeUsage("opencode", now), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage, readCopilot = readCopilotUsage, platform = process.platform, readElevenLabs = liveElevenLabsUsage) {
591
671
  this.readCodex = readCodex;
592
672
  this.now = now;
593
673
  this.readClaudeLive = readClaudeLive;
@@ -595,44 +675,70 @@ export class AccountUsageReader {
595
675
  this.readOpenRouter = readOpenRouter;
596
676
  this.readOpenCodeGo = readOpenCodeGo;
597
677
  this.readCopilot = readCopilot;
678
+ this.platform = platform;
679
+ this.readElevenLabs = readElevenLabs;
598
680
  }
599
- async read() {
681
+ /** `allAccounts`: one Claude row per home. Otherwise only the default home's, as
682
+ * before accounts existed, since older phones refuse two rows of one source. */
683
+ async read(sources, allAccounts = false) {
600
684
  if (!this.cached || this.now() - this.cached.at >= 60_000) {
601
685
  this.pending ??= this.readCodex().then(value => { this.cached = { at: this.now(), value }; return value; }).finally(() => { this.pending = undefined; });
602
686
  }
603
687
  const codex = this.pending ?? Promise.resolve(this.cached.value);
604
- const [codexValue, claude, spending] = await Promise.all([codex, this.claude(), this.spending()]);
605
- return { accounts: [codexValue, claude, ...spending] };
606
- }
607
- async spending() {
608
- if (!this.spendingCached || this.now() - this.spendingCached.at >= 60_000) {
688
+ // Every home, default first; the labels and keys are read once per poll.
689
+ const homes = allAccounts ? claudeHomes() : claudeHomes().slice(0, 1);
690
+ const claudeRow = async (home) => {
691
+ const email = claudeAccountEmail(home);
692
+ return { ...settleClaudeUsage(await this.claude(home), this.now()), account: { ...claudeAccountRef(home), ...(email ? { email } : {}) } };
693
+ };
694
+ const [codexValue, claude, spending] = await Promise.all([codex, Promise.all(homes.map(claudeRow)),
695
+ this.spending(sources?.has("copilot") ?? true, sources?.has("elevenlabs") ?? true)]);
696
+ return { accounts: [{ ...codexValue, account: CODEX_ACCOUNT }, ...claude, ...spending] };
697
+ }
698
+ /** ElevenLabs is read only when the caller shows it: every read spends a request against the key's quota. */
699
+ async spending(includeCopilot, includeElevenLabs) {
700
+ const key = `${includeCopilot}:${includeElevenLabs}`;
701
+ const cached = this.spendingCached.get(key);
702
+ if (!cached || this.now() - cached.at >= 60_000) {
609
703
  const at = this.now();
610
- this.spendingPending ??= Promise.all([this.readOpenCode(new Date(at)), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at)), this.readCopilot(new Date(at))])
611
- .then(([openCode, openCodeGo, openRouter, copilot]) => [openCode, openCodeGo, ...(openRouter ? [openRouter] : []), copilot])
612
- .then(value => { this.spendingCached = { at, value }; return value; })
613
- .finally(() => { this.spendingPending = undefined; });
704
+ if (!this.spendingPending.has(key)) {
705
+ const pending = Promise.all([this.readOpenCode(new Date(at)), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at)),
706
+ includeCopilot ? this.readCopilot(new Date(at)) : Promise.resolve(undefined),
707
+ includeElevenLabs ? this.readElevenLabs(new Date(at)).catch(() => undefined) : Promise.resolve(undefined)])
708
+ .then(([openCode, openCodeGo, openRouter, copilot, elevenLabs]) => [openCode, openCodeGo, ...(openRouter ? [openRouter] : []), ...(copilot ? [copilot] : []), ...(elevenLabs ? [elevenLabs] : [])])
709
+ .then(value => { this.spendingCached.set(key, { at, value }); return value; })
710
+ .finally(() => { this.spendingPending.delete(key); });
711
+ this.spendingPending.set(key, pending);
712
+ }
614
713
  }
615
- return this.spendingPending ? await this.spendingPending : this.spendingCached.value;
714
+ return this.spendingPending.get(key) ?? cached.value;
616
715
  }
617
716
  /** Live first, so the phone's minute-by-minute poll keeps Claude current
618
- * even when Claude Code is not running; the local snapshot is the backup. */
619
- async claude() {
620
- if (!this.claudeCached || this.now() - this.claudeCached.at >= 60_000) {
621
- const at = this.now();
622
- this.claudePending ??= this.readClaudeLive(new Date(at))
623
- .then(value => { this.claudeCached = { at, value }; return value; })
624
- .catch(() => { this.claudeCached = { at, value: undefined }; return undefined; })
625
- .finally(() => { this.claudePending = undefined; });
717
+ * even when Claude Code is not running; the local snapshot is the backup.
718
+ * Off macOS a non-default home reads its own credentials file; on macOS it
719
+ * has no live read (the keychain item name for custom homes is unverified). */
720
+ async claude(home) {
721
+ if (home.isDefault || this.platform !== "darwin") {
722
+ const cached = this.claudeCached.get(home.dir);
723
+ if (!cached || this.now() - cached.at >= 60_000) {
724
+ const at = this.now();
725
+ if (!this.claudePending.has(home.dir))
726
+ this.claudePending.set(home.dir, this.readClaudeLive(new Date(at), home)
727
+ .then(value => { this.claudeCached.set(home.dir, { at, value }); return value; })
728
+ .catch(() => { this.claudeCached.set(home.dir, { at, value: undefined }); return undefined; })
729
+ .finally(() => { this.claudePending.delete(home.dir); }));
730
+ }
731
+ const pending = this.claudePending.get(home.dir);
732
+ const live = pending ? await pending : this.claudeCached.get(home.dir)?.value;
733
+ if (live?.windows.length)
734
+ return live;
626
735
  }
627
- const live = this.claudePending ? await this.claudePending : this.claudeCached?.value;
628
- if (live?.windows.length)
629
- return live;
630
- return this.snapshotClaude();
736
+ return this.snapshotClaude(home);
631
737
  }
632
- async snapshotClaude() {
738
+ async snapshotClaude(home) {
633
739
  let claude = { source: "claude", windows: [], message: "Usage appears after Claude Code replies on this computer. Run phren bridge install if usage reporting is not set up yet." };
634
740
  try {
635
- const handle = await open(claudeFile(), "r");
741
+ const handle = await open(claudeFile(home), "r");
636
742
  try {
637
743
  const stat = await handle.stat();
638
744
  if (!stat.isFile() || stat.size > 16_384)
@@ -649,7 +755,7 @@ export class AccountUsageReader {
649
755
  }
650
756
  catch { /* No status-line report yet. Keep unavailable explicit. */ }
651
757
  try {
652
- const handle = await open(claudeConfigFile(), "r");
758
+ const handle = await open(home.configFile, "r");
653
759
  try {
654
760
  const stat = await handle.stat();
655
761
  if (!stat.isFile() || stat.size > 16_777_216)
@@ -699,12 +805,17 @@ export async function captureClaudeUsage(original) {
699
805
  return;
700
806
  }
701
807
  try {
808
+ // The home Claude runs in names the file; an unknown CLAUDE_CONFIG_DIR records nothing.
809
+ // Homes are resolved without this process's CLAUDE_CONFIG_DIR: that is the account's own dir here, not the default.
810
+ const home = claudeHomeOfEnv(process.env.CLAUDE_CONFIG_DIR, { ...process.env, CLAUDE_CONFIG_DIR: undefined });
811
+ if (!home)
812
+ throw new Error("Unknown Claude home");
702
813
  const snapshot = claudeUsage(JSON.parse(input));
703
814
  // Persist only normalized percentages/reset times; never session content.
704
815
  const rate_limits = Object.fromEntries(snapshot.windows.map(w => [w.id, {
705
816
  used_percentage: w.usedPercent, resets_at: w.resetsAt ? Date.parse(w.resetsAt) / 1000 : undefined,
706
817
  }]));
707
- await atomicInPrivateDir(claudeFile(), JSON.stringify({ rate_limits, updatedAt: snapshot.updatedAt }));
818
+ await atomicInPrivateDir(claudeFile(home), JSON.stringify({ rate_limits, updatedAt: snapshot.updatedAt }));
708
819
  }
709
820
  catch { /* Status line rendering must survive unavailable usage storage. */ }
710
821
  const previous = object(JSON.parse(Buffer.from(original, "base64").toString()));