@phren/cli 0.3.11 → 0.3.13

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 (182) hide show
  1. package/dist/bridge/account-usage.d.ts +124 -0
  2. package/dist/bridge/account-usage.js +258 -0
  3. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  4. package/dist/bridge/agent-hook-stores.js +5 -0
  5. package/dist/bridge/agent-hooks.d.ts +162 -5
  6. package/dist/bridge/agent-hooks.js +682 -49
  7. package/dist/bridge/approval-summary.d.ts +16 -0
  8. package/dist/bridge/approval-summary.js +133 -0
  9. package/dist/bridge/authority-command.d.ts +20 -0
  10. package/dist/bridge/authority-command.js +120 -0
  11. package/dist/bridge/authority.d.ts +223 -0
  12. package/dist/bridge/authority.js +231 -0
  13. package/dist/bridge/claude-account-setup.d.ts +14 -0
  14. package/dist/bridge/claude-account-setup.js +69 -0
  15. package/dist/bridge/claude-accounts.d.ts +49 -0
  16. package/dist/bridge/claude-accounts.js +195 -0
  17. package/dist/bridge/code-routes.js +2 -2
  18. package/dist/bridge/codex-app-server.d.ts +144 -0
  19. package/dist/bridge/codex-app-server.js +319 -0
  20. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  21. package/dist/bridge/codex-auth-refresh.js +71 -0
  22. package/dist/bridge/codex-hook-trust.d.ts +27 -0
  23. package/dist/bridge/codex-hook-trust.js +237 -0
  24. package/dist/bridge/codex-question-reply.d.ts +16 -0
  25. package/dist/bridge/codex-question-reply.js +57 -0
  26. package/dist/bridge/codex-review-mode.d.ts +10 -0
  27. package/dist/bridge/codex-review-mode.js +74 -0
  28. package/dist/bridge/codex-servers.d.ts +217 -0
  29. package/dist/bridge/codex-servers.js +636 -0
  30. package/dist/bridge/command.js +97 -4
  31. package/dist/bridge/computer-identity.d.ts +75 -0
  32. package/dist/bridge/computer-identity.js +166 -0
  33. package/dist/bridge/conductor-group.d.ts +91 -8
  34. package/dist/bridge/conductor-group.js +105 -9
  35. package/dist/bridge/conductor-role.d.ts +94 -0
  36. package/dist/bridge/conductor-role.js +176 -0
  37. package/dist/bridge/conductor-sets.d.ts +20 -0
  38. package/dist/bridge/conductor-sets.js +59 -0
  39. package/dist/bridge/dispatch-command.d.ts +3 -0
  40. package/dist/bridge/dispatch-command.js +82 -12
  41. package/dist/bridge/dispatch-returns.d.ts +128 -19
  42. package/dist/bridge/dispatch-returns.js +371 -54
  43. package/dist/bridge/dispatch.d.ts +128 -3
  44. package/dist/bridge/dispatch.js +303 -42
  45. package/dist/bridge/fanouts.d.ts +7 -1
  46. package/dist/bridge/fanouts.js +39 -4
  47. package/dist/bridge/folder-trust.d.ts +56 -0
  48. package/dist/bridge/folder-trust.js +195 -0
  49. package/dist/bridge/grants.d.ts +22 -1
  50. package/dist/bridge/grants.js +57 -9
  51. package/dist/bridge/hand-off-queue.d.ts +74 -0
  52. package/dist/bridge/hand-off-queue.js +235 -0
  53. package/dist/bridge/hand-off.d.ts +30 -10
  54. package/dist/bridge/hand-off.js +79 -46
  55. package/dist/bridge/harness-status.d.ts +11 -0
  56. package/dist/bridge/harness-status.js +32 -0
  57. package/dist/bridge/harnesses.d.ts +39 -0
  58. package/dist/bridge/harnesses.js +65 -0
  59. package/dist/bridge/health.d.ts +2 -0
  60. package/dist/bridge/health.js +1 -1
  61. package/dist/bridge/herdr.d.ts +11 -2
  62. package/dist/bridge/herdr.js +98 -23
  63. package/dist/bridge/hook-fast.d.ts +4 -0
  64. package/dist/bridge/hook-fast.js +68 -0
  65. package/dist/bridge/install.d.ts +16 -1
  66. package/dist/bridge/install.js +102 -21
  67. package/dist/bridge/launch-brief.d.ts +96 -0
  68. package/dist/bridge/launch-brief.js +164 -0
  69. package/dist/bridge/model-switch.d.ts +3 -0
  70. package/dist/bridge/model-switch.js +17 -1
  71. package/dist/bridge/models.d.ts +8 -4
  72. package/dist/bridge/models.js +24 -8
  73. package/dist/bridge/mux-wire.d.ts +9 -0
  74. package/dist/bridge/mux-wire.js +19 -0
  75. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  76. package/dist/bridge/opencode-pane-server.js +332 -0
  77. package/dist/bridge/opencode-panes.d.ts +111 -0
  78. package/dist/bridge/opencode-panes.js +295 -0
  79. package/dist/bridge/pane-accounts.d.ts +8 -0
  80. package/dist/bridge/pane-accounts.js +46 -0
  81. package/dist/bridge/pane-status.d.ts +12 -0
  82. package/dist/bridge/pane-status.js +50 -1
  83. package/dist/bridge/prompt-startup.d.ts +5 -0
  84. package/dist/bridge/prompt-startup.js +24 -0
  85. package/dist/bridge/protocol.d.ts +5 -0
  86. package/dist/bridge/protocol.js +4 -0
  87. package/dist/bridge/push.d.ts +11 -4
  88. package/dist/bridge/push.js +27 -4
  89. package/dist/bridge/questions.d.ts +37 -2
  90. package/dist/bridge/questions.js +158 -15
  91. package/dist/bridge/resources.d.ts +9 -3
  92. package/dist/bridge/resources.js +24 -8
  93. package/dist/bridge/schedule-format.d.ts +2 -0
  94. package/dist/bridge/schedule-format.js +3 -0
  95. package/dist/bridge/schedule-launch.d.ts +2 -1
  96. package/dist/bridge/schedule-launch.js +27 -53
  97. package/dist/bridge/schedule-watch.d.ts +24 -1
  98. package/dist/bridge/schedule-watch.js +89 -2
  99. package/dist/bridge/server-launch.d.ts +22 -5
  100. package/dist/bridge/server-launch.js +238 -32
  101. package/dist/bridge/server-overview.d.ts +10 -3
  102. package/dist/bridge/server-overview.js +32 -15
  103. package/dist/bridge/server-pane-routes.d.ts +3 -0
  104. package/dist/bridge/server-pane-routes.js +150 -18
  105. package/dist/bridge/server-routes.d.ts +11 -0
  106. package/dist/bridge/server-routes.js +214 -36
  107. package/dist/bridge/server-stream.d.ts +2 -0
  108. package/dist/bridge/server-stream.js +22 -8
  109. package/dist/bridge/server.d.ts +6 -1
  110. package/dist/bridge/server.js +58 -13
  111. package/dist/bridge/session-activity.d.ts +93 -0
  112. package/dist/bridge/session-activity.js +139 -0
  113. package/dist/bridge/session-rename.d.ts +48 -0
  114. package/dist/bridge/session-rename.js +190 -0
  115. package/dist/bridge/session-servers.js +2 -2
  116. package/dist/bridge/settings-switch.d.ts +60 -0
  117. package/dist/bridge/settings-switch.js +287 -0
  118. package/dist/bridge/speech-voice.d.ts +55 -0
  119. package/dist/bridge/speech-voice.js +132 -0
  120. package/dist/bridge/speech.d.ts +70 -11
  121. package/dist/bridge/speech.js +169 -41
  122. package/dist/bridge/stalls.d.ts +22 -0
  123. package/dist/bridge/stalls.js +57 -0
  124. package/dist/bridge/sudo.d.ts +209 -0
  125. package/dist/bridge/sudo.js +501 -0
  126. package/dist/bridge/terminal-herdr.js +9 -3
  127. package/dist/bridge/terminal-tmux.d.ts +15 -3
  128. package/dist/bridge/terminal-tmux.js +103 -13
  129. package/dist/bridge/terminal.d.ts +27 -4
  130. package/dist/bridge/terminal.js +8 -1
  131. package/dist/bridge/transcript-claude.d.ts +4 -0
  132. package/dist/bridge/transcript-claude.js +186 -16
  133. package/dist/bridge/transcript-codex.d.ts +0 -2
  134. package/dist/bridge/transcript-codex.js +29 -4
  135. package/dist/bridge/transcript-preview.d.ts +1 -0
  136. package/dist/bridge/transcript-preview.js +24 -4
  137. package/dist/bridge/transcripts.d.ts +15 -2
  138. package/dist/bridge/transcripts.js +47 -16
  139. package/dist/bridge/turn-records.d.ts +85 -0
  140. package/dist/bridge/turn-records.js +143 -0
  141. package/dist/bridge/uploads.d.ts +3 -0
  142. package/dist/bridge/uploads.js +14 -0
  143. package/dist/bridge/usage.d.ts +56 -10
  144. package/dist/bridge/usage.js +190 -45
  145. package/dist/bridge-hook.mjs +27975 -20636
  146. package/dist/cli/claude-unmanaged.d.ts +12 -0
  147. package/dist/cli/claude-unmanaged.js +105 -0
  148. package/dist/cli/schedules.js +2 -1
  149. package/dist/cli/session-start.js +10 -1
  150. package/dist/cli/session-stop.js +9 -1
  151. package/dist/cli-registry.js +31 -6
  152. package/dist/data/task-receipts.d.ts +19 -0
  153. package/dist/data/task-receipts.js +68 -0
  154. package/dist/data/tasks.js +4 -1
  155. package/dist/generated/memory-ui-graph.browser.js +63 -63
  156. package/dist/graph-core/model.js +24 -3
  157. package/dist/graph-core/types.d.ts +4 -1
  158. package/dist/graph-core/types.js +1 -0
  159. package/dist/init/init-preset.js +7 -3
  160. package/dist/init/init-uninstall.js +2 -11
  161. package/dist/init/teardown.d.ts +3 -0
  162. package/dist/init/teardown.js +47 -0
  163. package/dist/link/context.js +21 -9
  164. package/dist/mcp/plugin-mode.js +1 -1
  165. package/dist/memory-ui-graph.runtime.js +63 -63
  166. package/dist/modules/code-package.d.ts +1 -0
  167. package/dist/modules/code-package.js +36 -7
  168. package/dist/modules/registry.js +17 -16
  169. package/dist/profile-store.d.ts +6 -0
  170. package/dist/profile-store.js +25 -1
  171. package/dist/shell/graph/glyphs.js +4 -0
  172. package/dist/shell/graph/graph-view.js +2 -0
  173. package/dist/status.js +7 -1
  174. package/dist/sync/task-claim.js +3 -2
  175. package/dist/task/lifecycle.js +25 -4
  176. package/dist/test-global-setup.js +5 -0
  177. package/dist/tools/dispatch.js +52 -4
  178. package/dist/tools/tasks.js +10 -1
  179. package/package.json +1 -1
  180. package/plugins/opencode/phren-transcript.js +87 -4
  181. package/starter/global/AGENTS.md +4 -0
  182. package/starter/global/skills/conductor/SKILL.md +51 -4
@@ -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,30 @@ 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
+ /** Under this much left on any window, an account is near its limit: information for the owner, never a reason to avoid it. */
128
+ export declare const NEAR_LIMIT_LEFT = 20;
129
+ /** No quota on this window now: at 100% or refused by the service, and its reset not yet passed. */
130
+ export declare function windowExhausted(window: UsageWindow, now: number): boolean;
131
+ /** Percent left on a window at `now`: none once its reset passed or with no percent, 0 while the service refuses requests. */
132
+ export declare function windowLeft(window: UsageWindow, now: number): number | undefined;
133
+ /** What a capacity probe says about room: each Codex and Claude account's least room left, and whether it has none
134
+ * (`exhausted`, with `until` the last reset that frees it). */
135
+ export declare function capacityRoom(accounts: readonly AccountUsage[], now: number): Array<{
136
+ source: string;
137
+ account?: string;
138
+ leftPercent?: number;
139
+ exhausted?: true;
140
+ until?: string;
141
+ }>;
142
+ /** A Claude report older than this says nothing about the account now. */
143
+ export declare const CLAUDE_REPORT_MAX_AGE_MS: number;
144
+ /**
145
+ * What a saved Claude report still says at `now`: a window whose reset time
146
+ * has passed is reported as reset without its old percent, and a report
147
+ * older than three days is dropped, so a stale number never reaches the
148
+ * phone's cards, rings or widgets.
149
+ */
150
+ export declare function settleClaudeUsage(usage: AccountUsage, now: number): AccountUsage;
114
151
  export declare class AccountUsageReader {
115
152
  private readCodex;
116
153
  private now;
@@ -119,19 +156,28 @@ export declare class AccountUsageReader {
119
156
  private readOpenRouter;
120
157
  private readOpenCodeGo;
121
158
  private readCopilot;
159
+ private platform;
160
+ private readElevenLabs;
122
161
  private cached?;
123
162
  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<{
163
+ private claudeCached;
164
+ private claudePending;
165
+ private spendingCached;
166
+ private spendingPending;
167
+ 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>);
168
+ /** `allAccounts`: one Claude row per home. Otherwise only the default home's, as
169
+ * before accounts existed, since older phones refuse two rows of one source. */
170
+ read(sources?: Set<string>, allAccounts?: boolean): Promise<{
130
171
  accounts: AccountUsage[];
131
172
  }>;
173
+ /** Codex and every Claude home, without the spend readers: what a dispatch capacity probe asks. */
174
+ limits(allAccounts?: boolean): Promise<AccountUsage[]>;
175
+ /** ElevenLabs is read only when the caller shows it: every read spends a request against the key's quota. */
132
176
  private spending;
133
177
  /** 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. */
178
+ * even when Claude Code is not running; the local snapshot is the backup.
179
+ * Off macOS a non-default home reads its own credentials file; on macOS it
180
+ * has no live read (the keychain item name for custom homes is unverified). */
135
181
  private claude;
136
182
  private snapshotClaude;
137
183
  }
@@ -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,69 @@ 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
+ /** Under this much left on any window, an account is near its limit: information for the owner, never a reason to avoid it. */
629
+ export const NEAR_LIMIT_LEFT = 20;
630
+ /** No quota on this window now: at 100% or refused by the service, and its reset not yet passed. */
631
+ export function windowExhausted(window, now) {
632
+ const reset = window.resetsAt ? Date.parse(window.resetsAt) : NaN;
633
+ if (window.reset || Number.isFinite(reset) && reset <= now)
634
+ return false;
635
+ return window.limited === true || typeof window.usedPercent === "number" && window.usedPercent >= 100;
636
+ }
637
+ /** Percent left on a window at `now`: none once its reset passed or with no percent, 0 while the service refuses requests. */
638
+ export function windowLeft(window, now) {
639
+ const reset = window.resetsAt ? Date.parse(window.resetsAt) : NaN;
640
+ if (window.reset || Number.isFinite(reset) && reset <= now)
641
+ return undefined;
642
+ if (window.limited)
643
+ return 0;
644
+ return typeof window.usedPercent === "number" ? Math.max(0, Math.min(100, Math.round(100 - window.usedPercent))) : undefined;
645
+ }
646
+ /** What a capacity probe says about room: each Codex and Claude account's least room left, and whether it has none
647
+ * (`exhausted`, with `until` the last reset that frees it). */
648
+ export function capacityRoom(accounts, now) {
649
+ return accounts.map(usage => {
650
+ const left = usage.windows.map(window => windowLeft(window, now)).filter((value) => value !== undefined);
651
+ const out = usage.windows.filter(window => windowExhausted(window, now));
652
+ const until = out.map(window => window.resetsAt).filter((value) => Boolean(value)).sort().at(-1);
653
+ return { source: usage.source, ...(usage.account?.id ? { account: usage.account.id } : {}), ...(left.length ? { leftPercent: Math.min(...left) } : {}),
654
+ ...(out.length ? { exhausted: true, ...(until ? { until } : {}) } : {}) };
655
+ });
656
+ }
657
+ /** A Claude report older than this says nothing about the account now. */
658
+ export const CLAUDE_REPORT_MAX_AGE_MS = 3 * 86_400_000;
659
+ /**
660
+ * What a saved Claude report still says at `now`: a window whose reset time
661
+ * has passed is reported as reset without its old percent, and a report
662
+ * older than three days is dropped, so a stale number never reaches the
663
+ * phone's cards, rings or widgets.
664
+ */
665
+ export function settleClaudeUsage(usage, now) {
666
+ if (!usage.windows.length)
667
+ return usage;
668
+ const reported = (w) => Date.parse(w.asOf ?? usage.updatedAt ?? "");
669
+ const windows = usage.windows
670
+ .filter(w => { const at = reported(w); return !Number.isFinite(at) || now - at < CLAUDE_REPORT_MAX_AGE_MS; })
671
+ .map(w => {
672
+ const reset = w.resetsAt ? Date.parse(w.resetsAt) : NaN;
673
+ if (!Number.isFinite(reset) || reset > now)
674
+ return w;
675
+ const { usedPercent: _old, ...rest } = w;
676
+ return { ...rest, reset: true };
677
+ });
678
+ if (windows.length)
679
+ return { ...usage, windows };
680
+ const since = usage.updatedAt?.slice(0, 10);
681
+ return { ...usage, windows, message: `No usage report from Claude on this computer${since ? ` since ${since}` : ""}. It updates when Claude Code runs here.` };
682
+ }
576
683
  export class AccountUsageReader {
577
684
  readCodex;
578
685
  now;
@@ -581,13 +688,15 @@ export class AccountUsageReader {
581
688
  readOpenRouter;
582
689
  readOpenCodeGo;
583
690
  readCopilot;
691
+ platform;
692
+ readElevenLabs;
584
693
  cached;
585
694
  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) {
695
+ claudeCached = new Map();
696
+ claudePending = new Map();
697
+ spendingCached = new Map();
698
+ spendingPending = new Map();
699
+ 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
700
  this.readCodex = readCodex;
592
701
  this.now = now;
593
702
  this.readClaudeLive = readClaudeLive;
@@ -595,44 +704,75 @@ export class AccountUsageReader {
595
704
  this.readOpenRouter = readOpenRouter;
596
705
  this.readOpenCodeGo = readOpenCodeGo;
597
706
  this.readCopilot = readCopilot;
598
- }
599
- async read() {
707
+ this.platform = platform;
708
+ this.readElevenLabs = readElevenLabs;
709
+ }
710
+ /** `allAccounts`: one Claude row per home. Otherwise only the default home's, as
711
+ * before accounts existed, since older phones refuse two rows of one source. */
712
+ async read(sources, allAccounts = false) {
713
+ const [limits, spending] = await Promise.all([this.limits(allAccounts),
714
+ this.spending(sources?.has("copilot") ?? true, sources?.has("elevenlabs") ?? true)]);
715
+ return { accounts: [...limits, ...spending] };
716
+ }
717
+ /** Codex and every Claude home, without the spend readers: what a dispatch capacity probe asks. */
718
+ async limits(allAccounts = true) {
600
719
  if (!this.cached || this.now() - this.cached.at >= 60_000) {
601
720
  this.pending ??= this.readCodex().then(value => { this.cached = { at: this.now(), value }; return value; }).finally(() => { this.pending = undefined; });
602
721
  }
603
722
  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) {
723
+ // Every home, default first; the labels and keys are read once per poll.
724
+ const homes = allAccounts ? claudeHomes() : claudeHomes().slice(0, 1);
725
+ const claudeRow = async (home) => {
726
+ const email = claudeAccountEmail(home);
727
+ return { ...settleClaudeUsage(await this.claude(home), this.now()), account: { ...claudeAccountRef(home), ...(email ? { email } : {}) } };
728
+ };
729
+ const [codexValue, claude] = await Promise.all([codex, Promise.all(homes.map(claudeRow))]);
730
+ return [{ ...codexValue, account: CODEX_ACCOUNT }, ...claude];
731
+ }
732
+ /** ElevenLabs is read only when the caller shows it: every read spends a request against the key's quota. */
733
+ async spending(includeCopilot, includeElevenLabs) {
734
+ const key = `${includeCopilot}:${includeElevenLabs}`;
735
+ const cached = this.spendingCached.get(key);
736
+ if (!cached || this.now() - cached.at >= 60_000) {
609
737
  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; });
738
+ if (!this.spendingPending.has(key)) {
739
+ const pending = Promise.all([this.readOpenCode(new Date(at)), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at)),
740
+ includeCopilot ? this.readCopilot(new Date(at)) : Promise.resolve(undefined),
741
+ includeElevenLabs ? this.readElevenLabs(new Date(at)).catch(() => undefined) : Promise.resolve(undefined)])
742
+ .then(([openCode, openCodeGo, openRouter, copilot, elevenLabs]) => [openCode, openCodeGo, ...(openRouter ? [openRouter] : []), ...(copilot ? [copilot] : []), ...(elevenLabs ? [elevenLabs] : [])])
743
+ .then(value => { this.spendingCached.set(key, { at, value }); return value; })
744
+ .finally(() => { this.spendingPending.delete(key); });
745
+ this.spendingPending.set(key, pending);
746
+ }
614
747
  }
615
- return this.spendingPending ? await this.spendingPending : this.spendingCached.value;
748
+ return this.spendingPending.get(key) ?? cached.value;
616
749
  }
617
750
  /** 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; });
751
+ * even when Claude Code is not running; the local snapshot is the backup.
752
+ * Off macOS a non-default home reads its own credentials file; on macOS it
753
+ * has no live read (the keychain item name for custom homes is unverified). */
754
+ async claude(home) {
755
+ if (home.isDefault || this.platform !== "darwin") {
756
+ const cached = this.claudeCached.get(home.dir);
757
+ if (!cached || this.now() - cached.at >= 60_000) {
758
+ const at = this.now();
759
+ if (!this.claudePending.has(home.dir))
760
+ this.claudePending.set(home.dir, this.readClaudeLive(new Date(at), home)
761
+ .then(value => { this.claudeCached.set(home.dir, { at, value }); return value; })
762
+ .catch(() => { this.claudeCached.set(home.dir, { at, value: undefined }); return undefined; })
763
+ .finally(() => { this.claudePending.delete(home.dir); }));
764
+ }
765
+ const pending = this.claudePending.get(home.dir);
766
+ const live = pending ? await pending : this.claudeCached.get(home.dir)?.value;
767
+ if (live?.windows.length)
768
+ return live;
626
769
  }
627
- const live = this.claudePending ? await this.claudePending : this.claudeCached?.value;
628
- if (live?.windows.length)
629
- return live;
630
- return this.snapshotClaude();
770
+ return this.snapshotClaude(home);
631
771
  }
632
- async snapshotClaude() {
772
+ async snapshotClaude(home) {
633
773
  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
774
  try {
635
- const handle = await open(claudeFile(), "r");
775
+ const handle = await open(claudeFile(home), "r");
636
776
  try {
637
777
  const stat = await handle.stat();
638
778
  if (!stat.isFile() || stat.size > 16_384)
@@ -649,7 +789,7 @@ export class AccountUsageReader {
649
789
  }
650
790
  catch { /* No status-line report yet. Keep unavailable explicit. */ }
651
791
  try {
652
- const handle = await open(claudeConfigFile(), "r");
792
+ const handle = await open(home.configFile, "r");
653
793
  try {
654
794
  const stat = await handle.stat();
655
795
  if (!stat.isFile() || stat.size > 16_777_216)
@@ -699,12 +839,17 @@ export async function captureClaudeUsage(original) {
699
839
  return;
700
840
  }
701
841
  try {
842
+ // The home Claude runs in names the file; an unknown CLAUDE_CONFIG_DIR records nothing.
843
+ // Homes are resolved without this process's CLAUDE_CONFIG_DIR: that is the account's own dir here, not the default.
844
+ const home = claudeHomeOfEnv(process.env.CLAUDE_CONFIG_DIR, { ...process.env, CLAUDE_CONFIG_DIR: undefined });
845
+ if (!home)
846
+ throw new Error("Unknown Claude home");
702
847
  const snapshot = claudeUsage(JSON.parse(input));
703
848
  // Persist only normalized percentages/reset times; never session content.
704
849
  const rate_limits = Object.fromEntries(snapshot.windows.map(w => [w.id, {
705
850
  used_percentage: w.usedPercent, resets_at: w.resetsAt ? Date.parse(w.resetsAt) / 1000 : undefined,
706
851
  }]));
707
- await atomicInPrivateDir(claudeFile(), JSON.stringify({ rate_limits, updatedAt: snapshot.updatedAt }));
852
+ await atomicInPrivateDir(claudeFile(home), JSON.stringify({ rate_limits, updatedAt: snapshot.updatedAt }));
708
853
  }
709
854
  catch { /* Status line rendering must survive unavailable usage storage. */ }
710
855
  const previous = object(JSON.parse(Buffer.from(original, "base64").toString()));