@phren/cli 0.3.58 → 0.3.61

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 (91) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/account-add.d.ts +30 -0
  3. package/dist/bridge/account-add.js +125 -19
  4. package/dist/bridge/account-failover.d.ts +9 -2
  5. package/dist/bridge/account-failover.js +1 -1
  6. package/dist/bridge/account-policy.d.ts +44 -0
  7. package/dist/bridge/account-policy.js +103 -0
  8. package/dist/bridge/account-pools.d.ts +35 -0
  9. package/dist/bridge/account-pools.js +171 -0
  10. package/dist/bridge/account-usage.d.ts +29 -4
  11. package/dist/bridge/account-usage.js +117 -8
  12. package/dist/bridge/agent-hook-callback.d.ts +6 -0
  13. package/dist/bridge/agent-hook-callback.js +10 -2
  14. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  15. package/dist/bridge/agent-hook-stores.js +13 -0
  16. package/dist/bridge/agent-hooks.d.ts +12 -2
  17. package/dist/bridge/agent-hooks.js +41 -4
  18. package/dist/bridge/claude-account-setup.d.ts +16 -0
  19. package/dist/bridge/claude-account-setup.js +46 -2
  20. package/dist/bridge/claude-accounts.d.ts +9 -0
  21. package/dist/bridge/claude-accounts.js +53 -15
  22. package/dist/bridge/claude-credits.d.ts +8 -2
  23. package/dist/bridge/claude-credits.js +52 -31
  24. package/dist/bridge/codex-threads.js +50 -2
  25. package/dist/bridge/command.js +12 -3
  26. package/dist/bridge/continuation-launch.d.ts +32 -0
  27. package/dist/bridge/continuation-launch.js +112 -1
  28. package/dist/bridge/dispatch-command.js +22 -0
  29. package/dist/bridge/dispatch-returns.d.ts +23 -0
  30. package/dist/bridge/dispatch-returns.js +57 -0
  31. package/dist/bridge/dispatch.d.ts +26 -4
  32. package/dist/bridge/dispatch.js +100 -11
  33. package/dist/bridge/git-host-gitlab.js +2 -1
  34. package/dist/bridge/git-hosts.d.ts +8 -0
  35. package/dist/bridge/git-hosts.js +16 -2
  36. package/dist/bridge/git-publish.js +18 -2
  37. package/dist/bridge/git.d.ts +8 -0
  38. package/dist/bridge/git.js +24 -1
  39. package/dist/bridge/hand-off-queue.d.ts +71 -0
  40. package/dist/bridge/hand-off-queue.js +38 -0
  41. package/dist/bridge/harnesses.d.ts +12 -0
  42. package/dist/bridge/harnesses.js +20 -4
  43. package/dist/bridge/helper.d.ts +54 -0
  44. package/dist/bridge/helper.js +186 -0
  45. package/dist/bridge/herdr.js +6 -2
  46. package/dist/bridge/hook-fast.d.ts +3 -0
  47. package/dist/bridge/hook-fast.js +10 -2
  48. package/dist/bridge/move-computers.d.ts +15 -1
  49. package/dist/bridge/move-computers.js +123 -26
  50. package/dist/bridge/owner-inbox-sources.d.ts +12 -1
  51. package/dist/bridge/owner-inbox-sources.js +127 -49
  52. package/dist/bridge/peers.d.ts +2 -0
  53. package/dist/bridge/peers.js +35 -4
  54. package/dist/bridge/prompt-deliveries.d.ts +69 -2
  55. package/dist/bridge/prompt-deliveries.js +342 -28
  56. package/dist/bridge/schedule-watch.js +17 -3
  57. package/dist/bridge/server-routes.d.ts +6 -0
  58. package/dist/bridge/server-routes.js +98 -14
  59. package/dist/bridge/server-stream.js +6 -4
  60. package/dist/bridge/server.js +2 -1
  61. package/dist/bridge/session-move.d.ts +70 -1
  62. package/dist/bridge/session-move.js +311 -19
  63. package/dist/bridge/simulators.d.ts +19 -0
  64. package/dist/bridge/simulators.js +93 -13
  65. package/dist/bridge/speech-live.js +132 -22
  66. package/dist/bridge/task-routes.d.ts +16 -16
  67. package/dist/bridge/terminal-herdr.js +6 -1
  68. package/dist/bridge/terminal-tmux.js +9 -5
  69. package/dist/bridge/terminal.d.ts +9 -2
  70. package/dist/bridge/transcript-claude.d.ts +3 -0
  71. package/dist/bridge/transcript-claude.js +175 -29
  72. package/dist/bridge/transcript-preview.d.ts +11 -2
  73. package/dist/bridge/transcript-preview.js +90 -8
  74. package/dist/bridge/turn-records.d.ts +19 -0
  75. package/dist/bridge/turn-records.js +78 -3
  76. package/dist/bridge/usage.d.ts +17 -0
  77. package/dist/bridge/usage.js +3 -2
  78. package/dist/bridge-hook.mjs +11964 -10084
  79. package/dist/cli-registry.js +2 -2
  80. package/dist/content/citation.d.ts +4 -0
  81. package/dist/content/citation.js +21 -21
  82. package/dist/data/task-contract.d.ts +4 -4
  83. package/dist/governance/policy.js +5 -2
  84. package/dist/index.js +1 -1
  85. package/dist/modules/registry.js +5 -5
  86. package/dist/project-config.d.ts +14 -0
  87. package/dist/project-config.js +40 -1
  88. package/dist/tools/dispatch.js +1 -1
  89. package/dist/tools/helper.d.ts +3 -0
  90. package/dist/tools/helper.js +44 -0
  91. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { type NotLinkedComputer } from "./hand-off.js";
2
2
  import { type HookPeer } from "./peers.js";
3
3
  import { type Json } from "./protocol.js";
4
- import { NEAR_LIMIT_LEFT, type AccountUsage, type Subscription, type UsageCredits, type UsageWindow } from "./usage.js";
4
+ import { NEAR_LIMIT_LEFT, type AccountUsage, type ApiCredit, type Subscription, type UsageCredits, type UsageWindow } from "./usage.js";
5
5
  export { NEAR_LIMIT_LEFT };
6
6
  /**
7
7
  * Every computer's agent usage merged by account, for a conductor choosing
@@ -17,6 +17,12 @@ export { NEAR_LIMIT_LEFT };
17
17
  * one account. A window whose reset time has passed says `reset` and has no
18
18
  * percent, and a report older than STALE_AFTER_MS is flagged stale.
19
19
  *
20
+ * A Claude home with no readable login and nothing to show is a placeholder
21
+ * named only by its label ("work Team"). When that label names an account
22
+ * some computer reports (its own label, its email, or the email's name with
23
+ * its plan), the placeholder's computer joins that account's row instead of
24
+ * standing as a row of its own (`placeholderTarget`).
25
+ *
20
26
  * `nearLimit` is information: the owner often wants quota used before it
21
27
  * resets. Only `exhausted` (a window at 100% or refusing requests) rules an
22
28
  * account out.
@@ -38,6 +44,9 @@ export interface AccountWindow {
38
44
  exhausted?: true;
39
45
  usedUSD?: number;
40
46
  limitUSD?: number;
47
+ /** An API credit window: dollars left and its expiry. */
48
+ remainingUSD?: number;
49
+ expiresAt?: string;
41
50
  }
42
51
  export interface AccountUsageRow {
43
52
  /** `source` or `source|key`, as the phone keys its cards. */
@@ -47,9 +56,9 @@ export interface AccountUsageRow {
47
56
  /** The login's email, else the account's label, when the Hook names one. */
48
57
  account?: string;
49
58
  windows: AccountWindow[];
50
- /** Least room on any window with a percent; `limited` counts as 0. */
59
+ /** Least room on any window with a percent, the API credits counted as one balance; `limited` counts as 0. */
51
60
  leftPercent?: number;
52
- /** Under 20% left on some window. Information, not a reason to avoid the account. */
61
+ /** Under 20% left on some window or the credits together. Information, not a reason to avoid the account. */
53
62
  nearLimit: boolean;
54
63
  /** A window is at 100% or refusing requests: never dispatch to it until `availableIn`. */
55
64
  exhausted: boolean;
@@ -62,6 +71,8 @@ export interface AccountUsageRow {
62
71
  subscription?: Subscription;
63
72
  /** Codex's credit balance from the newest report that has one. */
64
73
  credits?: UsageCredits;
74
+ /** A Claude account's entered API credits added up over its unexpired credit windows (an estimate). */
75
+ apiCredit?: ApiCredit;
65
76
  updatedAt?: string;
66
77
  /** How old the standing report is, as "4m" or "2d 3h". */
67
78
  age?: string;
@@ -105,8 +116,20 @@ export declare function ageText(ms: number): string;
105
116
  export declare function accountIdentity(usage: AccountUsage, computer: string): string;
106
117
  /** Percent used and left, with a passed reset reported as reset rather than as its old percent. */
107
118
  export declare function settleWindow(window: UsageWindow, now: number): AccountWindow;
108
- /** Least room across an account's windows, undefined when none has a percent. */
119
+ /** Least room across an account's windows, its API credits counted as one; undefined when none has a percent. */
109
120
  export declare function roomLeft(windows: readonly AccountWindow[]): number | undefined;
121
+ export interface NamedAccount {
122
+ labels: readonly string[];
123
+ email?: string;
124
+ plan?: string;
125
+ }
126
+ /**
127
+ * Which identified account a placeholder's label names, by index: one whose
128
+ * home carries the same label, else one whose email, email name, or email
129
+ * name and plan ("sam Team") the label spells. Two equally good matches name
130
+ * neither, and the provider's bare name ("Claude") names nothing.
131
+ */
132
+ export declare function placeholderTarget(label: string | undefined, accounts: readonly NamedAccount[], provider?: string): number | undefined;
110
133
  /** One row per account across every computer's report. */
111
134
  export declare function mergeAccountUsage(reports: readonly ComputerUsage[], now?: number): Pick<AccountUsageView, "accounts" | "noData">;
112
135
  export interface ReadAccountUsageOptions {
@@ -126,5 +149,7 @@ export declare function readAccountUsage(options?: ReadAccountUsageOptions): Pro
126
149
  export declare function usageSummary(view: AccountUsageView): string;
127
150
  /** "5-hour 82% left (resets in 2h 10m), weekly 64% left (resets in 3d 4h)": what launch and failover rank Claude accounts by. */
128
151
  export declare function claudeRoom(row: Pick<AccountUsageRow, "windows">): string;
152
+ /** "about $142.50 left of $200.00, the soonest expires 2026-12-31". */
153
+ export declare function apiCreditText(credit: ApiCredit): string;
129
154
  /** `phren dispatch usage` without --json. */
130
155
  export declare function formatAccountUsage(view: AccountUsageView): string;
@@ -3,6 +3,7 @@ import { creditsText, HARNESS_NAMES, resetsIn, USAGE_SOURCES } from "../computer
3
3
  import { hookRequest } from "./client.js";
4
4
  import { notLinkedFrom } from "./hand-off.js";
5
5
  import { optionalHookPeers, peerRequest } from "./peers.js";
6
+ import { creditSummary } from "./claude-credits.js";
6
7
  import { errorCode, object } from "./protocol.js";
7
8
  import { NEAR_LIMIT_LEFT, windowExhausted, windowLeft } from "./usage.js";
8
9
  export { NEAR_LIMIT_LEFT };
@@ -20,6 +21,12 @@ export { NEAR_LIMIT_LEFT };
20
21
  * one account. A window whose reset time has passed says `reset` and has no
21
22
  * percent, and a report older than STALE_AFTER_MS is flagged stale.
22
23
  *
24
+ * A Claude home with no readable login and nothing to show is a placeholder
25
+ * named only by its label ("work Team"). When that label names an account
26
+ * some computer reports (its own label, its email, or the email's name with
27
+ * its plan), the placeholder's computer joins that account's row instead of
28
+ * standing as a row of its own (`placeholderTarget`).
29
+ *
23
30
  * `nearLimit` is information: the owner often wants quota used before it
24
31
  * resets. Only `exhausted` (a window at 100% or refusing requests) rules an
25
32
  * account out.
@@ -70,11 +77,38 @@ export function settleWindow(window, now) {
70
77
  out.usedUSD = window.usedUSD;
71
78
  if (window.limitUSD !== undefined)
72
79
  out.limitUSD = window.limitUSD;
80
+ // A credit's expiry is its `resetsAt`; an older Hook sends only that.
81
+ const credit = window.id.startsWith("credit:");
82
+ const remaining = window.remainingUSD ?? (credit && window.usedUSD !== undefined && window.limitUSD !== undefined
83
+ ? Math.round(Math.max(0, window.limitUSD - window.usedUSD) * 100) / 100 : undefined);
84
+ const expiresAt = window.expiresAt ?? (credit ? window.resetsAt : undefined);
85
+ if (remaining !== undefined)
86
+ out.remainingUSD = remaining;
87
+ if (expiresAt !== undefined)
88
+ out.expiresAt = expiresAt;
73
89
  return out;
74
90
  }
75
- /** Least room across an account's windows, undefined when none has a percent. */
91
+ const isCredit = (window) => window.id.startsWith("credit:");
92
+ const finite = (value) => typeof value === "number" && Number.isFinite(value);
93
+ /** The room in an account's API credits, one balance as capacityRoom counts them: the credits with a percent
94
+ * pool, their limits and spend summed. */
95
+ function creditRoom(windows) {
96
+ const credit = windows.filter(w => isCredit(w) && w.leftPercent !== undefined);
97
+ if (!credit.length)
98
+ return undefined;
99
+ if (credit.every(w => finite(w.usedUSD) && finite(w.limitUSD))) {
100
+ const limit = credit.reduce((sum, w) => sum + w.limitUSD, 0), used = credit.reduce((sum, w) => sum + w.usedUSD, 0);
101
+ return limit > 0 ? Math.max(0, Math.min(100, Math.round((limit - used) / limit * 100))) : 0;
102
+ }
103
+ const lefts = credit.map(w => w.leftPercent).filter((value) => value !== undefined);
104
+ return lefts.length ? Math.max(...lefts) : undefined;
105
+ }
106
+ /** Least room across an account's windows, its API credits counted as one; undefined when none has a percent. */
76
107
  export function roomLeft(windows) {
77
- const known = windows.map(w => w.leftPercent).filter((value) => value !== undefined);
108
+ const known = windows.filter(w => !isCredit(w)).map(w => w.leftPercent).filter((value) => value !== undefined);
109
+ const credit = creditRoom(windows);
110
+ if (credit !== undefined)
111
+ known.push(credit);
78
112
  return known.length ? Math.min(...known) : undefined;
79
113
  }
80
114
  function accountName(usage) {
@@ -83,14 +117,64 @@ function accountName(usage) {
83
117
  return usage.account?.email ?? (typeof named === "string" && named ? named : undefined)
84
118
  ?? (label && label.toLowerCase() !== (HARNESS_NAMES[usage.source] ?? usage.source).toLowerCase() ? label : undefined);
85
119
  }
120
+ const words = (text) => text.trim().toLowerCase().replace(/\s+/g, " ");
121
+ /** A Claude home with no login Phren can read and no numbers: only its label names it. */
122
+ const isPlaceholder = (usage) => usage.source === "claude" && Boolean(usage.account?.key?.startsWith("claude:home:")) && !hasData(usage);
123
+ /**
124
+ * Which identified account a placeholder's label names, by index: one whose
125
+ * home carries the same label, else one whose email, email name, or email
126
+ * name and plan ("sam Team") the label spells. Two equally good matches name
127
+ * neither, and the provider's bare name ("Claude") names nothing.
128
+ */
129
+ export function placeholderTarget(label, accounts, provider = "Claude") {
130
+ const wanted = words(label ?? "");
131
+ if (!wanted || wanted === words(provider))
132
+ return undefined;
133
+ const unique = (found) => found.length === 1 ? found[0] : undefined;
134
+ const same = accounts.flatMap((account, index) => account.labels.some(item => words(item) === wanted) ? [index] : []);
135
+ if (same.length)
136
+ return unique(same);
137
+ const spelled = accounts.flatMap((account, index) => {
138
+ const email = words(account.email ?? ""), name = email.split("@")[0], plan = words(account.plan ?? "");
139
+ if (!email)
140
+ return [];
141
+ if (wanted === email || wanted === name)
142
+ return [{ index, plan: false }];
143
+ if (!wanted.startsWith(`${name} `))
144
+ return [];
145
+ const rest = wanted.slice(name.length + 1);
146
+ // A login whose plan is unknown still answers to "name <plan>".
147
+ return !plan || rest === plan ? [{ index, plan: rest === plan }] : [];
148
+ });
149
+ const exact = spelled.filter(item => item.plan);
150
+ return unique((exact.length ? exact : spelled).map(item => item.index));
151
+ }
86
152
  /** One row per account across every computer's report. */
87
153
  export function mergeAccountUsage(reports, now = Date.now()) {
88
154
  const groups = new Map();
155
+ const placeholders = [];
89
156
  for (const report of reports)
90
157
  for (const usage of report.accounts) {
158
+ if (isPlaceholder(usage)) {
159
+ placeholders.push({ computer: report.computer, usage });
160
+ continue;
161
+ }
91
162
  const id = accountIdentity(usage, report.computer);
92
163
  groups.set(id, [...groups.get(id) ?? [], { computer: report.computer, usage }]);
93
164
  }
165
+ // A placeholder joins the account its label names; one naming none keeps its own group.
166
+ const identified = [...groups].filter(([, group]) => group[0].usage.source === "claude" && group.some(item => hasData(item.usage)) && !group[0].usage.account?.key?.startsWith("claude:home:"));
167
+ const named = identified.map(([, group]) => ({ labels: group.map(item => item.usage.account?.label ?? "").filter(Boolean),
168
+ email: group.find(item => item.usage.account?.email)?.usage.account?.email, plan: group.find(item => item.usage.subscription)?.usage.subscription?.plan }));
169
+ const joined = new Map();
170
+ for (const item of placeholders) {
171
+ const target = placeholderTarget(item.usage.account?.label, named);
172
+ const id = target === undefined ? accountIdentity(item.usage, item.computer) : identified[target][0];
173
+ if (target === undefined)
174
+ groups.set(id, [...groups.get(id) ?? [], item]);
175
+ else
176
+ joined.set(id, [...joined.get(id) ?? [], item]);
177
+ }
94
178
  const accounts = [];
95
179
  const empty = new Map();
96
180
  for (const [id, group] of groups) {
@@ -111,18 +195,24 @@ export function mergeAccountUsage(reports, now = Date.now()) {
111
195
  const subscription = subscriptions.sort((a, b) => (date(b.usage.subscription?.checkedAt) || date(b.usage.updatedAt) || 0) - (date(a.usage.subscription?.checkedAt) || date(a.usage.updatedAt) || 0))[0]?.usage.subscription;
112
196
  const withWindows = reporting.filter(item => item.usage.windows.length);
113
197
  const standing = (withWindows.length ? withWindows : reporting).reduce(newer);
114
- const windows = mergedWindows(withWindows).map(window => settleWindow(window, now));
198
+ // A credit that expired since its report is gone, not reset.
199
+ const windows = mergedWindows(withWindows).filter(window => !(window.id.startsWith("credit:") && date(window.expiresAt ?? window.resetsAt) <= now))
200
+ .map(window => settleWindow(window, now));
201
+ const apiCredit = creditSummary(windows);
115
202
  const spend = mergedSpend(source, reporting);
116
203
  const withCredits = reporting.filter(item => item.usage.credits);
117
204
  const credits = withCredits.length ? withCredits.reduce(newer).usage.credits : undefined;
118
205
  const updated = date(standing.usage.updatedAt);
119
206
  const leftPercent = roomLeft(windows);
120
- const exhausted = windows.filter(w => w.exhausted);
207
+ // An account's API credits are one balance, as capacityRoom counts them: a spent credit exhausts the
208
+ // account only when every credit is spent.
209
+ const creditSpent = windows.filter(w => w.id.startsWith("credit:")).every(w => w.exhausted);
210
+ const exhausted = windows.filter(w => w.exhausted && (!w.id.startsWith("credit:") || creditSpent));
121
211
  // A credit's date is when it expires, not when it comes back.
122
212
  const availableAt = exhausted.filter(w => !w.id.startsWith("credit:")).map(w => w.resetsAt).filter((value) => Boolean(value)).sort().at(-1);
123
213
  const availableIn = availableAt ? resetsIn(availableAt, now) : undefined;
124
214
  const name = accountName(standing.usage);
125
- const computers = reporting.map(item => ({ name: item.computer, ...(source === "claude" && item.usage.account?.id ? { account: item.usage.account.id } : {}) }))
215
+ const computers = [...reporting, ...joined.get(id) ?? []].map(item => ({ name: item.computer, ...(source === "claude" && item.usage.account?.id ? { account: item.usage.account.id } : {}) }))
126
216
  .filter((item, index, list) => list.findIndex(other => other.name === item.name && other.account === item.account) === index);
127
217
  accounts.push({
128
218
  id, harness: source, name: HARNESS_NAMES[source] ?? source, ...(name ? { account: name } : {}), windows,
@@ -132,6 +222,7 @@ export function mergeAccountUsage(reports, now = Date.now()) {
132
222
  ...(spend ? { spend } : {}),
133
223
  ...(subscription ? { subscription } : {}),
134
224
  ...(credits ? { credits } : {}),
225
+ ...(apiCredit ? { apiCredit } : {}),
135
226
  ...(standing.usage.updatedAt ? { updatedAt: standing.usage.updatedAt } : {}),
136
227
  ...(Number.isFinite(updated) ? { age: ageText(now - updated) } : {}),
137
228
  stale: !Number.isFinite(updated) || now - updated > STALE_AFTER_MS || windows.some(w => w.reset),
@@ -231,13 +322,16 @@ export function usageSummary(view) {
231
322
  parts.push(`Out of quota, do not dispatch to: ${out.map(row => `${title(row)}${row.availableIn ? ` (back in ${row.availableIn})` : ""}`).join("; ")}.`);
232
323
  const near = view.accounts.filter(row => row.nearLimit && !row.exhausted);
233
324
  if (near.length)
234
- parts.push(`Low but usable: ${near.map(row => `${title(row)} (${row.leftPercent ?? 0}% left${tightest(row)?.resetsIn ? `, resets in ${tightest(row).resetsIn}` : ""})`).join("; ")}.`);
325
+ parts.push(`Low but usable: ${near.map(row => `${title(row)} (${row.leftPercent ?? 0}% left${tightestChange(row) ? `, ${tightestChange(row)}` : ""})`).join("; ")}.`);
235
326
  const limitedRows = view.accounts.filter(row => row.leftPercent !== undefined || row.exhausted);
236
327
  if (limitedRows.length && limitedRows.every(row => row.exhausted))
237
328
  parts.push("Every account with limits is out of quota: tell the owner before dispatching.");
238
329
  const claude = view.accounts.filter(row => row.harness === "claude" && claudeRoom(row));
239
330
  if (claude.length)
240
331
  parts.push(`Claude room: ${claude.map(row => `${title(row)} ${claudeRoom(row)}`).join("; ")}.`);
332
+ const credit = view.accounts.filter(row => row.apiCredit);
333
+ if (credit.length)
334
+ parts.push(`API credit: ${credit.map(row => `${title(row)} ${apiCreditText(row.apiCredit)}`).join("; ")}.`);
241
335
  const stale = view.accounts.filter(row => row.stale);
242
336
  if (stale.length)
243
337
  parts.push(`Stale: ${stale.map(row => `${title(row)} (${row.windows.some(w => w.reset) ? "a window reset since its report" : `reported ${row.age ? ago(row.age) : "at an unknown time"}`})`).join("; ")}.`);
@@ -259,8 +353,21 @@ export function claudeRoom(row) {
259
353
  };
260
354
  return [part("five_hour", "5-hour"), part("seven_day", "weekly")].filter(Boolean).join(", ");
261
355
  }
262
- function tightest(row) {
263
- return row.windows.filter(w => w.leftPercent !== undefined).sort((a, b) => a.leftPercent - b.leftPercent)[0];
356
+ /** "about $142.50 left of $200.00, the soonest expires 2026-12-31". */
357
+ export function apiCreditText(credit) {
358
+ return `about $${credit.remainingUSD.toFixed(2)} left of $${credit.limitUSD.toFixed(2)}${credit.expiresAt ? `, the soonest expires ${credit.expiresAt.slice(0, 10)}` : ""}`;
359
+ }
360
+ /** When the tightest room changes: a window's reset, or, when the API credits are tightest, the soonest expiry
361
+ * among credits with money left (a credit's expiry is not a reset, and a spent one's says nothing). */
362
+ function tightestChange(row) {
363
+ const window = row.windows.filter(w => !isCredit(w) && w.leftPercent !== undefined).sort((a, b) => a.leftPercent - b.leftPercent)[0];
364
+ const credit = creditRoom(row.windows);
365
+ if (credit !== undefined && (window === undefined || credit < window.leftPercent)) {
366
+ const soonest = row.windows.filter(w => isCredit(w) && w.resetsIn && (w.remainingUSD ?? 0) > 0)
367
+ .sort((a, b) => (a.expiresAt ?? a.resetsAt ?? "").localeCompare(b.expiresAt ?? b.resetsAt ?? ""))[0];
368
+ return soonest ? `credit expires in ${soonest.resetsIn}` : undefined;
369
+ }
370
+ return window?.resetsIn ? `resets in ${window.resetsIn}` : undefined;
264
371
  }
265
372
  /** `phren dispatch usage` without --json. */
266
373
  export function formatAccountUsage(view) {
@@ -282,6 +389,8 @@ export function formatAccountUsage(view) {
282
389
  const used = w.reset ? "reset, no new report" : w.usedPercent !== undefined ? `${w.usedPercent}% used${w.leftPercent !== undefined ? `, ${w.leftPercent}% left` : ""}` : w.usedUSD !== undefined ? `$${w.usedUSD.toFixed(2)}${w.limitUSD !== undefined ? ` of $${w.limitUSD.toFixed(2)}` : ""}` : "";
283
390
  lines.push(` ${w.name.padEnd(30)} ${used.padEnd(22)}${w.limited ? "limited now " : ""}${w.resetsIn ? `resets in ${w.resetsIn}${w.resetsAt ? ` (${w.resetsAt.slice(0, 16).replace("T", " ")} UTC)` : ""}` : ""}`.trimEnd());
284
391
  }
392
+ if (row.apiCredit && row.windows.filter(w => w.id.startsWith("credit:")).length > 1)
393
+ lines.push(` ${"API credit, all".padEnd(30)} ${apiCreditText(row.apiCredit)}`);
285
394
  if (row.credits?.hasCredits)
286
395
  lines.push(` credits${" ".repeat(24)}${creditsText(row.credits)}`);
287
396
  if (row.spend)
@@ -1,12 +1,18 @@
1
1
  import { type Json, type Provider } from "./protocol.js";
2
2
  /** The agent side of the Hook's callbacks: `hook <source>` reads the agent's
3
3
  * payload and posts it to the daemon's local socket (agent-hooks.ts). */
4
+ /** A background task id as Claude Code writes them (an agent id, a shell id). */
5
+ export declare const BACKGROUND_TASK_ID: RegExp;
4
6
  /** What a Stop payload says about the turn it ends: the harness's last
5
7
  * assistant message (Claude, Codex) and, from Claude Code, the background
6
8
  * tasks still in flight, which will wake the conversation again when they
7
9
  * finish. Absent fields are left out, so the Hook falls back to the transcript. */
8
10
  export declare function stopFacts(value: Json): {
9
11
  background?: number;
12
+ backgroundTasks?: {
13
+ id: string;
14
+ running: boolean;
15
+ }[];
10
16
  reply?: string;
11
17
  };
12
18
  /** One agent callback, run as `hook <source>`. Resolves "abandoned" when a
@@ -2,7 +2,7 @@ import { request } from "node:http";
2
2
  import { defaultPhrenPath } from "../shared.js";
3
3
  import { activateModules as moduleSnapshot } from "../modules/runtime.js";
4
4
  import { object, provider, targetSchema } from "./protocol.js";
5
- import { hookOutput, TOOL_HOOK_BUDGET_MS } from "./hook-fast.js";
5
+ import { hookOutput, STOP_TASKS_SENT, TOOL_HOOK_BUDGET_MS } from "./hook-fast.js";
6
6
  import { underCodexDaemon } from "./codex-daemon.js";
7
7
  import { codexAutoReview } from "./codex-review-mode.js";
8
8
  import { claudeHeadlessThread, codexForeignThread } from "./thread-origin.js";
@@ -12,6 +12,8 @@ import { CODEX_SERVER_ENV, codexServerId } from "./codex-servers.js";
12
12
  import { localSocket } from "./agent-hook-stores.js";
13
13
  /** The agent side of the Hook's callbacks: `hook <source>` reads the agent's
14
14
  * payload and posts it to the daemon's local socket (agent-hooks.ts). */
15
+ /** A background task id as Claude Code writes them (an agent id, a shell id). */
16
+ export const BACKGROUND_TASK_ID = /^[A-Za-z0-9._-]{1,128}$/;
15
17
  /** What a Stop payload says about the turn it ends: the harness's last
16
18
  * assistant message (Claude, Codex) and, from Claude Code, the background
17
19
  * tasks still in flight, which will wake the conversation again when they
@@ -19,7 +21,13 @@ import { localSocket } from "./agent-hook-stores.js";
19
21
  export function stopFacts(value) {
20
22
  const tasks = Array.isArray(value.background_tasks)
21
23
  ? value.background_tasks.filter(task => !["completed", "failed", "killed", "stopped"].includes(String(object(task).status))) : undefined;
22
- return { ...(tasks ? { background: tasks.length } : {}),
24
+ // Each task by id, running or not: a sub-agent's task id is its agent id, which the Hook's child tree keys on.
25
+ // Running ones first, so a cut list loses finished tasks before running ones.
26
+ const listed = Array.isArray(value.background_tasks) ? value.background_tasks.map(object)
27
+ .filter(task => typeof task.id === "string" && BACKGROUND_TASK_ID.test(task.id))
28
+ .map(task => ({ id: String(task.id), running: !["completed", "failed", "killed", "stopped"].includes(String(task.status)) }))
29
+ .sort((a, b) => Number(b.running) - Number(a.running)).slice(0, STOP_TASKS_SENT) : undefined;
30
+ return { ...(tasks ? { background: tasks.length } : {}), ...(listed ? { backgroundTasks: listed } : {}),
23
31
  ...(typeof value.last_assistant_message === "string" && value.last_assistant_message.trim() ? { reply: value.last_assistant_message.slice(0, 16_384) } : {}) };
24
32
  }
25
33
  /** One agent callback, run as `hook <source>`. Resolves "abandoned" when a
@@ -4,6 +4,9 @@ import { type Json } from "./protocol.js";
4
4
  export declare const localSocket: () => string;
5
5
  export declare const bindingPath: (server: string, pane: string) => string;
6
6
  export declare function recordedSession(server: string, pane: Json, pids: number[]): Promise<string | undefined>;
7
+ /** The conversation the last callback recorded for this pane's terminal and
8
+ * agent, without the process check: a cheap cross-check of Herdr's report. */
9
+ export declare function boundSession(server: string, pane: Json): Promise<string | undefined>;
7
10
  export interface PushBinding {
8
11
  action: string;
9
12
  expiresAt: number;
@@ -16,6 +16,19 @@ export async function recordedSession(server, pane, pids) {
16
16
  return undefined;
17
17
  }
18
18
  }
19
+ /** The conversation the last callback recorded for this pane's terminal and
20
+ * agent, without the process check: a cheap cross-check of Herdr's report. */
21
+ export async function boundSession(server, pane) {
22
+ try {
23
+ const value = object(JSON.parse(await readFile(bindingPath(server, String(pane.pane_id)), "utf8")));
24
+ if (value.terminal !== pane.terminal_id || value.source !== pane.agent)
25
+ return undefined;
26
+ return sessionId.parse(value.session);
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
19
32
  export class PushBindingStore {
20
33
  now;
21
34
  limit;
@@ -143,8 +143,12 @@ export declare class AgentHooks {
143
143
  /** Keys the phone sends to a served OpenCode pane that its API answers
144
144
  * better than the terminal: Esc declines a pending question or stops a
145
145
  * working turn (`session.abort`), and a digit answers a pending
146
- * single-question, single-choice set. False leaves the keys to the pane. */
147
- servedKeys(target: Target, keys: readonly string[], status: string): Promise<boolean>;
146
+ * single-question, single-choice set. False leaves the keys to the pane.
147
+ * With `abortTurn` (a move's "stop and hand off now"), Esc on a pending question declines it and then
148
+ * stops the turn too: a declined question alone lets the turn carry on. True only once the abort went. */
149
+ servedKeys(target: Target, keys: readonly string[], status: string, options?: {
150
+ abortTurn?: boolean;
151
+ }): Promise<boolean>;
148
152
  /** A session's exact pane. A recorded binding carries the full target; when
149
153
  * there is none, Herdr's explicit session identity names the pane. */
150
154
  private resolveTarget;
@@ -293,6 +297,12 @@ export declare class AgentHooks {
293
297
  /** Approve picks the dialog's yes/allow row (else its first), Deny its
294
298
  * no/deny row (else Escape), typed as the pane's own keys. */
295
299
  private answerDialog;
300
+ /** A held request the owner answered in the pane's own terminal: Claude
301
+ * moves on without closing the hook, so the hold would show its card until
302
+ * it times out. A later callback from the same conversation proves the
303
+ * dialog is gone: the call it held ran (its PostToolUse), the turn ended or
304
+ * took a new prompt, or the agent asked something else. */
305
+ private settleTerminalAnswered;
296
306
  private dropPushBindings;
297
307
  /** A server request from one of the Hook's own Codex app-servers: an
298
308
  * approval card like a held PermissionRequest, pushed the same way, but
@@ -427,8 +427,10 @@ export class AgentHooks {
427
427
  /** Keys the phone sends to a served OpenCode pane that its API answers
428
428
  * better than the terminal: Esc declines a pending question or stops a
429
429
  * working turn (`session.abort`), and a digit answers a pending
430
- * single-question, single-choice set. False leaves the keys to the pane. */
431
- async servedKeys(target, keys, status) {
430
+ * single-question, single-choice set. False leaves the keys to the pane.
431
+ * With `abortTurn` (a move's "stop and hand off now"), Esc on a pending question declines it and then
432
+ * stops the turn too: a declined question alone lets the turn carry on. True only once the abort went. */
433
+ async servedKeys(target, keys, status, options = {}) {
432
434
  if (target.source !== "opencode")
433
435
  return false;
434
436
  const entry = servedPane(target.server, target.pane);
@@ -440,7 +442,10 @@ export class AgentHooks {
440
442
  if (question && escape) {
441
443
  await client.rejectQuestion(question[0]).catch(() => { throw new BridgeError(409, "This question is no longer pending."); });
442
444
  this.servedQuestions.delete(question[0]);
443
- return true;
445
+ if (!options.abortTurn)
446
+ return true;
447
+ // A failed abort leaves Esc to the terminal, as below.
448
+ return client.abort(target.session).then(done => done === true, () => false);
444
449
  }
445
450
  if (question && keys.length === 1 && /^[1-9]$/.test(keys[0]) && question[1].questions.length === 1 && !question[1].questions[0].multiSelect) {
446
451
  const option = question[1].questions[0].options[Number(keys[0]) - 1];
@@ -561,6 +566,7 @@ export class AgentHooks {
561
566
  ...(dispatch ? { dispatch } : {}),
562
567
  ...(body.event === "SessionStart" && typeof body.startSource === "string" ? { start: body.startSource } : {}),
563
568
  ...(typeof body.background === "number" ? { background: body.background } : {}),
569
+ ...(body.event === "Stop" && Array.isArray(body.backgroundTasks) ? { backgroundTasks: body.backgroundTasks } : {}),
564
570
  ...(typeof body.reply === "string" ? { reply: body.reply } : {}),
565
571
  ...(body.event === "Stop" && typeof body.cwd === "string" ? { cwd: body.cwd } : {}) }).catch(() => undefined);
566
572
  }
@@ -569,7 +575,7 @@ export class AgentHooks {
569
575
  const questions = tool === "AskUserQuestion" ? terminalQuestions(body.input) : undefined;
570
576
  const choice = questions ? questionChoice(questions, 0) : terminalChoice(body.input);
571
577
  const summary = approvalSummary({ tool, input: body.input, question: tool === "AskUserQuestion" });
572
- this.terminalPrompts.set(JSON.stringify(target), { tool,
578
+ this.terminalPrompts.set(JSON.stringify(target), { tool, input: body.input,
573
579
  message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...(choice ? { choice } : {}),
574
580
  ...summary,
575
581
  ...(questions ? { questions, questionIndex: 0 } : {}), at: Date.now() });
@@ -1423,6 +1429,36 @@ export class AgentHooks {
1423
1429
  this.clearTerminalPrompt(dialog.target);
1424
1430
  this.dropDialogPush(key);
1425
1431
  }
1432
+ /** A held request the owner answered in the pane's own terminal: Claude
1433
+ * moves on without closing the hook, so the hold would show its card until
1434
+ * it times out. A later callback from the same conversation proves the
1435
+ * dialog is gone: the call it held ran (its PostToolUse), the turn ended or
1436
+ * took a new prompt, or the agent asked something else. */
1437
+ settleTerminalAnswered(target, body) {
1438
+ const event = String(body.event), key = JSON.stringify(target);
1439
+ const asked = event === "PermissionRequest" ? JSON.stringify([body.tool, body.input]) : undefined;
1440
+ const settled = (held) => ["Stop", "UserPromptSubmit"].includes(event)
1441
+ || (event === "PermissionRequest" && JSON.stringify([held.tool, held.input]) !== asked)
1442
+ || (event === "PostToolUse" && held.tool === body.tool && JSON.stringify(held.input) === JSON.stringify(body.input));
1443
+ for (const [action, held] of this.pending) {
1444
+ if (held.appServer || JSON.stringify(held.target) !== key || !settled(held))
1445
+ continue;
1446
+ clearTimeout(held.timer);
1447
+ this.pending.delete(action);
1448
+ this.pushedHolds.delete(action);
1449
+ this.dropPushBindings(action);
1450
+ if (!held.response.destroyed)
1451
+ held.response.end("{}");
1452
+ }
1453
+ const hold = this.releasedHolds.get(key), remembered = this.terminalPrompts.get(key);
1454
+ if (remembered && !remembered.questions?.length && settled({ tool: remembered.tool, input: remembered.input })) {
1455
+ this.terminalPrompts.delete(key);
1456
+ if (hold) {
1457
+ this.dropPushBindings(hold.action);
1458
+ this.releasedHolds.delete(key);
1459
+ }
1460
+ }
1461
+ }
1426
1462
  dropPushBindings(action) {
1427
1463
  this.pushBindings.dropAction(action);
1428
1464
  }
@@ -1610,6 +1646,7 @@ export class AgentHooks {
1610
1646
  // had taken (before thread-origin.ts) back to the TUI's thread.
1611
1647
  if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)) && target.source === "codex" && !daemon)
1612
1648
  codexServers.follow(target.server, target.pane, target.session);
1649
+ this.settleTerminalAnswered(target, body);
1613
1650
  if (body.event === "PreCompact") {
1614
1651
  this.startCompacting(target);
1615
1652
  res.end("{}");
@@ -7,8 +7,24 @@ export interface AddedAccount {
7
7
  dir: string;
8
8
  linked: string[];
9
9
  created: boolean;
10
+ warning?: string;
10
11
  }
12
+ /** A valid account name for `name`, or for the account's email when one is known: its user and the
13
+ * first part of its domain (`sam@example.com` is `sam-example`), lowercase, runs of anything else as one dash. */
14
+ export declare function suggestAccountSlug(name: string, email?: string): string;
15
+ /** Why `slug` is not an account name, with one that is. */
16
+ export declare function badAccountSlug(slug: string, email?: string): string;
17
+ /** `locked`: an ssh session on a Mac whose login keychain it cannot use (Claude keeps a Mac's login there,
18
+ * so a /login made in it is never saved). `unknown`: the check itself failed. A local session is never checked. */
19
+ export type KeychainState = "usable" | "locked" | "unknown";
20
+ export declare function sshKeychainState(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform, exec?: (file: string, args: string[], options: {
21
+ timeout: number;
22
+ }) => Promise<unknown>): Promise<KeychainState>;
23
+ export declare const KEYCHAIN_UNKNOWN_WARNING = "Couldn't check this Mac's login keychain from this ssh session; if /login doesn't stick, run this on the Mac itself.";
24
+ export declare function keychainLockedMessage(slug: string, label?: string): string;
11
25
  export declare function addClaudeAccount(slug: string, opts?: {
12
26
  label?: string;
27
+ email?: string;
13
28
  env?: NodeJS.ProcessEnv;
29
+ keychainState?: () => Promise<KeychainState>;
14
30
  }): Promise<AddedAccount>;
@@ -1,6 +1,8 @@
1
1
  // `phren bridge accounts add`: a new Claude home that shares the default home's setup.
2
+ import { execFile } from "node:child_process";
2
3
  import { chmod, lstat, mkdir, readFile, symlink } from "node:fs/promises";
3
4
  import path from "node:path";
5
+ import { promisify } from "node:util";
4
6
  import { homeDir } from "../home-paths.js";
5
7
  import { claudeHome, claudeHomes, DEFAULT_ACCOUNT, isAccountSlug, setAccountLabel } from "./claude-accounts.js";
6
8
  import { atomic } from "./protocol.js";
@@ -43,15 +45,57 @@ export async function syncAccountMcpServers(env = process.env) {
43
45
  changed.push(home.id);
44
46
  return changed;
45
47
  }
48
+ /** A valid account name for `name`, or for the account's email when one is known: its user and the
49
+ * first part of its domain (`sam@example.com` is `sam-example`), lowercase, runs of anything else as one dash. */
50
+ export function suggestAccountSlug(name, email) {
51
+ const [user, domain = ""] = email?.includes("@") ? email.trim().split("@") : [name];
52
+ const from = domain ? `${user}-${domain.split(".")[0]}` : user;
53
+ const slug = from.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+/, "").slice(0, 32).replace(/-+$/, "");
54
+ return !slug ? "account" : slug === DEFAULT_ACCOUNT ? "default-2" : slug;
55
+ }
56
+ /** Why `slug` is not an account name, with one that is. */
57
+ export function badAccountSlug(slug, email) {
58
+ return `"${slug}" is not an account name: use 1 to 32 lowercase letters, digits and dashes, and not "default". Try "${suggestAccountSlug(slug, email)}".`;
59
+ }
60
+ const run = promisify(execFile);
61
+ /** errSecInteractionNotAllowed (-25308): what the keychain answers a session it is locked to. */
62
+ const INTERACTION_NOT_ALLOWED = /User interaction is not allowed|-25308/;
63
+ export async function sshKeychainState(env = process.env, platform = process.platform, exec = run) {
64
+ if (platform !== "darwin" || !(env.SSH_CONNECTION || env.SSH_CLIENT))
65
+ return "usable";
66
+ try {
67
+ await exec("security", ["show-keychain-info"], { timeout: 5_000 });
68
+ return "usable";
69
+ }
70
+ catch (error) {
71
+ // Only the keychain's own refusal says it is locked; a timeout, a missing `security` or any other failure says nothing.
72
+ const { stderr, message } = (error ?? {});
73
+ return INTERACTION_NOT_ALLOWED.test(`${String(stderr ?? "")}\n${String(message ?? "")}`) ? "locked" : "unknown";
74
+ }
75
+ }
76
+ export const KEYCHAIN_UNKNOWN_WARNING = "Couldn't check this Mac's login keychain from this ssh session; if /login doesn't stick, run this on the Mac itself.";
77
+ export function keychainLockedMessage(slug, label) {
78
+ const labelArg = label ? ` --label '${label.replace(/'/g, "'\\''")}'` : "";
79
+ return "This Mac's login keychain is locked to this ssh session, so Claude can't save a login made here. "
80
+ + `On the Mac itself, run: phren bridge accounts add ${slug}${labelArg}. `
81
+ + "Or unlock the keychain for this session first (security unlock-keychain ~/Library/Keychains/login.keychain-db) and run it again.";
82
+ }
46
83
  export async function addClaudeAccount(slug, opts = {}) {
47
84
  const env = opts.env ?? process.env;
85
+ // A label given as the account's email names the account well.
86
+ const email = opts.email ?? (opts.label?.includes("@") ? opts.label : undefined);
48
87
  if (slug === DEFAULT_ACCOUNT || !isAccountSlug(slug))
49
- throw new Error(`"${slug}" is not an account name: use 1 to 32 lowercase letters, digits and dashes, and not "default".`);
88
+ throw new Error(badAccountSlug(slug, email));
50
89
  const source = claudeHome(DEFAULT_ACCOUNT, env);
51
90
  const dir = path.join(homeDir(env), `.claude-${slug}`);
52
91
  if (dir === source.dir)
53
92
  throw new Error(`~/.claude-${slug} is the default Claude home.`);
54
93
  const created = !(await exists(dir));
94
+ // Checked before a new home is made: it would wait on a login this session can't save. Refreshing an
95
+ // existing home's links and label needs no keychain. A check that failed goes ahead, with a warning.
96
+ const keychain = created ? await (opts.keychainState ?? (() => sshKeychainState(env)))() : "usable";
97
+ if (keychain === "locked")
98
+ throw new Error(keychainLockedMessage(slug, opts.label));
55
99
  await mkdir(dir, { recursive: true, mode: 0o700 });
56
100
  await chmod(dir, 0o700); // An existing home keeps its login: tighten it too.
57
101
  const linked = [];
@@ -65,5 +109,5 @@ export async function addClaudeAccount(slug, opts = {}) {
65
109
  await mergeMcpServers(path.join(dir, ".claude.json"), await mcpServersOf(source.configFile));
66
110
  if (opts.label)
67
111
  await setAccountLabel(slug, opts.label);
68
- return { id: slug, dir, linked, created };
112
+ return { id: slug, dir, linked, created, ...(keychain === "unknown" ? { warning: KEYCHAIN_UNKNOWN_WARNING } : {}) };
69
113
  }
@@ -27,6 +27,15 @@ export declare function claudeLaunchEnv(home: ClaudeHome): Record<string, string
27
27
  /** The config home a running Claude process uses, from its CLAUDE_CONFIG_DIR. */
28
28
  export declare function claudeHomeOfEnv(value: string | undefined, env?: NodeJS.ProcessEnv): ClaudeHome | undefined;
29
29
  export declare const accountsFile: () => string;
30
+ /** `accounts.yaml` as an object: empty when there is none (or it is blank), an error when it is there but is
31
+ * not a mapping, so a write never replaces what it couldn't read. */
32
+ export declare function parseAccountsYaml(text: string | undefined): Record<string, unknown>;
33
+ /**
34
+ * The one way `accounts.yaml` is changed (labels, credits, pools): reads it, applies `change`, and writes it back
35
+ * atomically. Writes in this process run one at a time, and each holds the file's lock against other processes
36
+ * (the CLI beside the Hook), so no write drops another's change. A file that can't be read is never replaced.
37
+ */
38
+ export declare function updateAccountsFile(change: (parsed: Record<string, unknown>) => void): Promise<void>;
30
39
  export declare function accountLabel(id: string, labels?: Record<string, string>): string;
31
40
  export declare function setAccountLabel(id: string, label: string): Promise<void>;
32
41
  /**