@phren/cli 0.3.36 → 0.3.37

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.
@@ -2,7 +2,9 @@ import { intentionallyClosed } from "./worker-close.js";
2
2
  import { workerPrs, readIntegrator } from "./worker-reports.js";
3
3
  import { prsSchema } from "./return-contract.js";
4
4
  import { sessionStalls } from "./stalls.js";
5
+ import { execFile } from "node:child_process";
5
6
  import { createHash } from "node:crypto";
7
+ import { promisify } from "node:util";
6
8
  import { z } from "zod";
7
9
  import { logger } from "../logger.js";
8
10
  import { arrivalOf, dispatchStatus, updateReceipt } from "./dispatch.js";
@@ -14,7 +16,7 @@ import { handOff } from "./hand-off.js";
14
16
  import { hookPeers, peerRequest } from "./peers.js";
15
17
  import { isLocalComputer } from "./dispatch-hosts.js";
16
18
  import { BridgeError, objects, startingTargetSchema, targetSchema } from "./protocol.js";
17
- import { ownerQuestion, readFinalTurn } from "./schedule-watch.js";
19
+ import { isClaudeUsageLimit, ownerQuestion, readFinalTurn } from "./schedule-watch.js";
18
20
  import { liveWork, runningTasks } from "./session-activity.js";
19
21
  import { terminalProvider } from "./terminal.js";
20
22
  import { childAgentTree, runningChildAgents } from "./transcripts.js";
@@ -54,6 +56,19 @@ const SNAPSHOT_AGE_MS = 5_000;
54
56
  // older Hook's target schema strips it, so it is safe to send to any peer.
55
57
  const workerTarget = z.union([targetSchema.extend({ dispatch: briefId.optional() }), startingTargetSchema.extend({ dispatch: briefId.optional() })]);
56
58
  export const workerRequestSchema = z.object({ targets: z.array(workerTarget).min(1).max(64) }).strict();
59
+ const run = promisify(execFile);
60
+ async function checkedOutBranch(directory) {
61
+ const { stdout } = await run("git", ["-C", directory, "rev-parse", "--abbrev-ref", "HEAD"], { timeout: 3_000 });
62
+ const branch = stdout.trim();
63
+ return branch && branch !== "HEAD" ? branch.slice(0, 256) : undefined;
64
+ }
65
+ /** A worker stopped by its Claude usage limit: where it was working, so another account can pick it up there. */
66
+ async function limitCheckout(seen, directory, readers) {
67
+ if (!isClaudeUsageLimit(seen.error) || typeof directory !== "string" || !directory)
68
+ return {};
69
+ const branch = await (readers.branch ?? checkedOutBranch)(directory).catch(() => undefined);
70
+ return { checkout: { path: directory.slice(0, 4096), ...(branch ? { branch } : {}) } };
71
+ }
57
72
  export async function paneTurn(server, pane, source) {
58
73
  if (source !== "opencode")
59
74
  return readTurn(server, String(pane.pane_id));
@@ -72,6 +87,7 @@ const defaultReaders = {
72
87
  lost: (server, pane, session) => codexServers.lostTurn(server, pane, session),
73
88
  uncommitted: directory => recentUncommitted(directory),
74
89
  shared: sharedCheckout,
90
+ branch: checkedOutBranch,
75
91
  };
76
92
  /** The default readers with the approval reader of the Hook that runs the workers. */
77
93
  export const workerReaders = (approval) => ({ ...defaultReaders, approval });
@@ -222,7 +238,8 @@ export async function workerStates(input, readers = defaultReaders) {
222
238
  const seen = await fromTurn(own, own.session, status, target.source, readers);
223
239
  const full = targetSchema.safeParse({ ...target, session: seen.session });
224
240
  const prs = full.success && seen.state === "done" ? await workerPrs(full.data, own) : undefined;
225
- return { ...seen, ...(prs ? { prs } : {}), ...await unfinished(seen, own.stop?.cwd ?? paneDirectory(pane), readers, s, pane, prs), ...(full.success && seen.state === "working" ? await readers.stall?.(full.data, { ...pane, agent_status: "working" }, liveReader(own, target.source, own.session, readers)) : {}) };
241
+ return { ...seen, ...(prs ? { prs } : {}), ...await unfinished(seen, own.stop?.cwd ?? paneDirectory(pane), readers, s, pane, prs),
242
+ ...await limitCheckout(seen, own.stop?.cwd ?? paneDirectory(pane), readers), ...(full.success && seen.state === "working" ? await readers.stall?.(full.data, { ...pane, agent_status: "working" }, liveReader(own, target.source, own.session, readers)) : {}) };
226
243
  }
227
244
  const session = expected ?? current;
228
245
  const state = ["working", "idle", "done", "blocked"].find(value => value === status) ?? "unknown";
@@ -243,7 +260,7 @@ export async function workerStates(input, readers = defaultReaders) {
243
260
  }
244
261
  const seen = { state, session, completed: turn?.completed === true, ...(end?.background ? { background: end.background } : {}), ...(turn?.error ? { error: turn.error } : {}),
245
262
  ...(turn?.interrupted ? { interrupted: true } : {}), ...replyFields(turn?.lastAssistant) };
246
- return { ...seen, ...await unfinished(seen, paneDirectory(pane), readers, s, pane) };
263
+ return { ...seen, ...await unfinished(seen, paneDirectory(pane), readers, s, pane), ...await limitCheckout(seen, paneDirectory(pane), readers) };
247
264
  }));
248
265
  // Only a conversation this dispatch named can be answered; a starting target has no session yet.
249
266
  return { workers: workers.map((seen, index) => {
@@ -262,6 +279,7 @@ const observationSchema = z.object({
262
279
  prs: prsSchema.optional(),
263
280
  stalled: z.boolean().optional(), stalledSince: z.string().datetime().optional(), stallFor: z.number().nonnegative().optional(),
264
281
  interrupted: z.boolean().optional(), approval: z.unknown().optional(), unfinished: z.string().max(200).optional(), unchecked: z.boolean().optional(),
282
+ checkout: z.object({ path: z.string().max(4096), branch: z.string().max(256).optional() }).strict().optional(),
265
283
  }).passthrough();
266
284
  /** A worker's forwarded permission request as its Hook sent it; an invalid one is ignored, not a reason to drop the state. */
267
285
  const approvalObservation = z.object({
@@ -402,7 +420,9 @@ function observeState(receipt, parsed, now) {
402
420
  ...(next === "working" && waitingSince ? { waitingSince } : {}) };
403
421
  if (next !== "working") {
404
422
  receipt.returned = { state: next, at, read: false,
405
- ...(seen.reply && (next === "done" || next === "needs-you") ? { reply: seen.reply, ...(seen.truncated ? { truncated: true } : {}) } : {}),
423
+ // A worker stopped by its usage limit keeps its last reply: the dispatch that continues it hands it over.
424
+ ...(seen.reply && (next === "done" || next === "needs-you" || next === "failed" && isClaudeUsageLimit(failed)) ? { reply: seen.reply, ...(seen.truncated ? { truncated: true } : {}) } : {}),
425
+ ...(next === "failed" && seen.checkout ? { checkout: seen.checkout } : {}),
406
426
  ...(next === "done" && seen.prs ? { prs: seen.prs } : {}),
407
427
  ...(next === "stalled" ? { stalledSince: seen.stalledSince, stallFor: seen.stallFor } : {}),
408
428
  ...(failed ? { error: failed } : {}), ...(question ? { question } : {}), ...(turn ? { turn } : {}),
@@ -447,6 +467,8 @@ export function returnRow(receipt) {
447
467
  ...(receipt.approval && returned.state === "blocked" ? { approval: { actionId: receipt.approval.actionId, tool: receipt.approval.tool,
448
468
  ...(receipt.approval.request ? { request: receipt.approval.request } : {}), ...(receipt.approval.title ? { title: receipt.approval.title } : {}),
449
469
  ...(receipt.approval.terminal ? { terminal: true } : {}) } } : {}),
470
+ ...(receipt.account ? { account: receipt.account } : {}), ...(receipt.accountChoice ? { accountChoice: receipt.accountChoice } : {}),
471
+ ...(receipt.continued ? { continued: receipt.continued } : {}), ...(receipt.continues ? { continues: receipt.continues } : {}),
450
472
  ...(receipt.target ? { target: receipt.target } : {}) };
451
473
  }
452
474
  const originKey = (origin) => JSON.stringify([origin.server, origin.workspace, origin.tab, origin.pane, origin.terminal]);
@@ -469,6 +491,7 @@ export class DispatchReturns {
469
491
  localAnswer;
470
492
  onApproval;
471
493
  close;
494
+ failover;
472
495
  lastPoll = -Infinity;
473
496
  lastNotice = new Map();
474
497
  /** A return is waiting for a dispatching agent that was busy: try again on
@@ -477,6 +500,7 @@ export class DispatchReturns {
477
500
  running;
478
501
  constructor(options = {}) {
479
502
  this.close = options.close;
503
+ this.failover = options.failover;
480
504
  this.peers = options.peers ?? hookPeers;
481
505
  this.request = options.request ?? peerRequest;
482
506
  this.localWorkers = options.localWorkers ?? (input => workerStates(input));
@@ -546,8 +570,15 @@ export class DispatchReturns {
546
570
  return Promise.resolve();
547
571
  if (poll)
548
572
  this.lastPoll = this.now();
549
- this.running = (async () => { if (poll)
550
- await this.poll(); await this.forwardPrs(); await this.cleanup(); await this.notify(); })()
573
+ this.running = (async () => {
574
+ if (poll) {
575
+ await this.poll();
576
+ await this.failover?.run().catch(error => logger.warn("dispatch", `Account failover: ${error instanceof Error ? error.message : String(error)}`));
577
+ }
578
+ await this.forwardPrs();
579
+ await this.cleanup();
580
+ await this.notify();
581
+ })()
551
582
  .catch(() => { }).finally(() => { this.running = undefined; });
552
583
  return this.running;
553
584
  }
@@ -1,6 +1,8 @@
1
1
  import { z } from "zod";
2
2
  import { type DispatchHost } from "./dispatch-hosts.js";
3
3
  import { type Json, type Provider, type Target } from "./protocol.js";
4
+ import { type HarnessInventory } from "./harnesses.js";
5
+ import type { AccountRoom, WindowRoom } from "./account-choice.js";
4
6
  import { type BriefArrival } from "./launch-brief.js";
5
7
  export declare const projectName: z.ZodString;
6
8
  /** The harnesses a dispatch, a code note's hand-off or a schedule can start. */
@@ -214,6 +216,15 @@ declare const receiptSchema: z.ZodObject<{
214
216
  launch: "launch";
215
217
  typed: "typed";
216
218
  }>>;
219
+ accountChoice: z.ZodOptional<z.ZodString>;
220
+ continued: z.ZodOptional<z.ZodObject<{
221
+ id: z.ZodOptional<z.ZodString>;
222
+ computer: z.ZodOptional<z.ZodString>;
223
+ account: z.ZodOptional<z.ZodString>;
224
+ at: z.ZodString;
225
+ error: z.ZodOptional<z.ZodString>;
226
+ }, z.core.$strict>>;
227
+ continues: z.ZodOptional<z.ZodString>;
217
228
  granted: z.ZodOptional<z.ZodString>;
218
229
  authority: z.ZodOptional<z.ZodString>;
219
230
  authorityConfirmed: z.ZodOptional<z.ZodString>;
@@ -270,6 +281,10 @@ declare const receiptSchema: z.ZodObject<{
270
281
  error: z.ZodOptional<z.ZodString>;
271
282
  truncated: z.ZodOptional<z.ZodBoolean>;
272
283
  question: z.ZodOptional<z.ZodString>;
284
+ checkout: z.ZodOptional<z.ZodObject<{
285
+ path: z.ZodString;
286
+ branch: z.ZodOptional<z.ZodString>;
287
+ }, z.core.$strict>>;
273
288
  prs: z.ZodOptional<z.ZodArray<z.ZodObject<{
274
289
  url: z.ZodURL;
275
290
  repo: z.ZodString;
@@ -365,6 +380,8 @@ type Room = {
365
380
  leftPercent?: number;
366
381
  exhausted?: boolean;
367
382
  until?: string;
383
+ fiveHour?: WindowRoom;
384
+ week?: WindowRoom;
368
385
  };
369
386
  /** The account this dispatch would run under there, as its capacity probe reports it: Codex's one, or the named Claude home. */
370
387
  export declare function roomFor(data: {
@@ -372,11 +389,14 @@ export declare function roomFor(data: {
372
389
  account?: string;
373
390
  }, usage: readonly Room[] | undefined): Room | undefined;
374
391
  /** Why `anywhere` must not pick a computer for quota: only an account with none left (at 100% or refusing requests).
375
- * Low quota is not a reason; the owner often wants it used before it resets. */
392
+ * Low quota is not a reason; the owner often wants it used before it resets. A Claude dispatch that names no
393
+ * account runs under whichever has room there, so with several accounts that computer is out only when all are. */
376
394
  export declare function outOfQuota(data: {
377
395
  harness: string;
378
396
  account?: string;
379
397
  }, usage: readonly Room[] | undefined, now?: number): string | undefined;
398
+ /** A computer's signed-in Claude accounts with their room, from its capacity probe. */
399
+ export declare function capacityClaudeRooms(harnesses: HarnessInventory["harnesses"] | undefined, usage: readonly Room[] | undefined): AccountRoom[];
380
400
  /** What the worker's own hooks reported for a brief that went with its
381
401
  * launch, or undefined when the receiving Hook has no such brief. */
382
402
  export declare function arrivalOf(peer: Pick<DispatchHost, "request">, id: string): Promise<BriefArrival | undefined>;
@@ -404,8 +424,9 @@ export declare class DispatchService {
404
424
  * socket); tests replace it so they never reach a real Hook. */
405
425
  constructor(identity?: DispatchIdentity | undefined, local?: () => DispatchHost, settleIntervalMs?: number);
406
426
  /** `originValue` is the local pane the request came from, as its agent's
407
- * Herdr variables name it; a pane without a running agent is left out. */
408
- dispatch(input: unknown, originValue?: unknown): Promise<Json>;
427
+ * Herdr variables name it; a pane without a running agent is left out.
428
+ * `continues` names the dispatch whose worker hit its usage limit (account-failover.ts). */
429
+ dispatch(input: unknown, originValue?: unknown, continues?: string): Promise<Json>;
409
430
  /** Launches placed on `computer` whose brief is still being confirmed. */
410
431
  private inFlight;
411
432
  /**
@@ -427,6 +448,13 @@ export declare class DispatchService {
427
448
  * uncertain, and the returns loop keeps asking.
428
449
  */
429
450
  private confirmLaunched;
451
+ /** Every connected computer's signed-in Claude accounts and their room, this computer first:
452
+ * where a worker that hit its usage limit can continue (account-failover.ts). */
453
+ claudeRooms(): Promise<Array<{
454
+ computer: string;
455
+ local: boolean;
456
+ rooms: AccountRoom[];
457
+ }>>;
430
458
  /** The query a conductor's dispatch sends with each capacity probe; undefined for any other caller. */
431
459
  private conductorCaller;
432
460
  private origin;
@@ -32,7 +32,7 @@ export const dispatchSchema = z.object({
32
32
  model: text(200).optional().describe("Explicit model, otherwise the remote harness default."),
33
33
  effort: z.enum(launchEfforts).optional().describe("Reasoning effort for the worker (minimal, low, medium, high, xhigh, max), otherwise the harness default."),
34
34
  account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
35
- .describe("Claude account id to run the worker under (default, or a slug from `phren bridge accounts`). anywhere only picks computers where that account is signed in; a named computer without it fails."),
35
+ .describe("Claude account id to run the worker under (default, or a slug from `phren bridge accounts`). anywhere only picks computers where that account is signed in; a named computer without it fails. Without it, a computer with several signed-in Claude accounts picks the one with the most 5-hour room, then weekly; the receipt's accountChoice says why."),
36
36
  permissionMode: z.enum(PERMISSION_MODES).optional().describe("Permission mode the worker starts in: supervised, auto-edits, auto or full-access (Claude, Codex and Copilot; not OpenCode); otherwise the receiving computer's own default."),
37
37
  releaseActions: z.array(releaseAction).min(1).max(RELEASE_ACTIONS.length).optional()
38
38
  .describe("Release-type actions the brief asks the worker to do (merge, publish, deploy, app-store, github-admin). Ask-first projects refuse them from an agent unless the owner confirmed."),
@@ -55,6 +55,11 @@ const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
55
55
  target: remoteTarget.optional(), error: z.string().max(500).optional(),
56
56
  brief: z.enum(["launch", "typed"]).optional()
57
57
  .describe("How the brief reached the worker: as its first prompt at launch (confirmed by the worker's hook), or typed into its pane."),
58
+ accountChoice: z.string().max(400).optional().describe("Why the receiving Hook ran the worker under `account` when the dispatch named none."),
59
+ continued: z.object({ id: z.string().uuid().optional(), computer: z.string().max(200).optional(), account: z.string().max(64).optional(),
60
+ at: timestamp, error: z.string().max(500).optional() }).strict().optional()
61
+ .describe("The worker hit its Claude usage limit: the dispatch that continues it on another account, or why none could."),
62
+ continues: z.string().uuid().optional().describe("The dispatch this one continues after its worker hit its usage limit."),
58
63
  granted: z.string().max(200).optional().describe("Scope of the conductor grant that allowed this call."),
59
64
  authority: z.string().max(600).optional().describe("The release authority policy's line for this project, as a conductor quotes it."),
60
65
  authorityConfirmed: z.string().datetime().optional().describe("When the owner confirmed the ask-first release actions this agent dispatch used."),
@@ -71,6 +76,8 @@ const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
71
76
  returned: z.object({
72
77
  state: z.enum(["done", "needs-you", "failed", "blocked", "stalled", "gone"]), at: timestamp,
73
78
  reply: z.string().max(4000).optional(), error: z.string().max(500).optional(), truncated: z.boolean().optional(), question: z.string().max(200).optional(),
79
+ checkout: z.object({ path: z.string().max(4096), branch: z.string().max(256).optional() }).strict().optional()
80
+ .describe("Where a worker that failed was working, for the dispatch that continues it."),
74
81
  prs: prsSchema.optional(),
75
82
  integratorDelivery: z.object({ deliveryId: z.string(), state: z.enum(["pending", "queued", "delivered", "uncertain", "failed"]), at: timestamp, integrator: integratorSchema.optional() }).strict().optional(),
76
83
  stalledSince: timestamp.optional(), stallFor: z.number().nonnegative().optional(),
@@ -182,6 +189,7 @@ export async function dispatchStatus() {
182
189
  }
183
190
  return receipts.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
184
191
  }
192
+ const windowRoom = z.object({ leftPercent: z.number().min(0).max(100).optional(), resetsAt: z.string().max(40).optional() }).passthrough().optional();
185
193
  async function capacity(host, caller) {
186
194
  const value = await host.request(caller && !host.local ? `/v1/dispatch/capacity?${caller}` : "/v1/dispatch/capacity");
187
195
  const result = z.object({ product: z.literal("phren-hook"), protocol: z.literal(PROTOCOL), working: z.number().int().nonnegative(),
@@ -191,7 +199,7 @@ async function capacity(host, caller) {
191
199
  accounts: z.array(z.object({ id: z.string(), usable: z.boolean(), reason: z.string().optional() }).passthrough()).optional() }).passthrough()).optional(),
192
200
  // Missing from an older Hook or a slow read: that computer's quota is unknown, so it is never ruled out by it.
193
201
  usage: z.array(z.object({ source: z.string(), account: z.string().optional(), leftPercent: z.number().min(0).max(100).optional(),
194
- exhausted: z.boolean().optional(), until: z.string().max(40).optional() }).passthrough()).max(64).optional(),
202
+ exhausted: z.boolean().optional(), until: z.string().max(40).optional(), fiveHour: windowRoom, week: windowRoom }).passthrough()).max(64).optional(),
195
203
  knowsCaller: z.boolean().optional() }).parse(value);
196
204
  // This computer places on whichever Herdr server its own Hook runs.
197
205
  if (host.local && !result.servers.includes(host.server) && result.servers[0])
@@ -207,22 +215,48 @@ export function roomFor(data, usage) {
207
215
  const account = data.account ?? "default";
208
216
  return usage?.find(item => item.source === data.harness && (data.harness !== "claude" || (item.account ?? "default") === account));
209
217
  }
218
+ /** " for about 3 more hours" until `until`, or nothing when it is unknown. */
219
+ function backIn(until, now) {
220
+ const at = until ? Date.parse(until) : NaN;
221
+ const minutes = Number.isFinite(at) ? Math.max(1, Math.round((at - now) / 60_000)) : undefined;
222
+ return minutes === undefined ? "" : minutes >= 1440 ? ` for about ${Math.round(minutes / 1440)} more days` : minutes >= 60 ? ` for about ${Math.round(minutes / 60)} more hours` : ` for about ${minutes} more minutes`;
223
+ }
210
224
  /** Why `anywhere` must not pick a computer for quota: only an account with none left (at 100% or refusing requests).
211
- * Low quota is not a reason; the owner often wants it used before it resets. */
225
+ * Low quota is not a reason; the owner often wants it used before it resets. A Claude dispatch that names no
226
+ * account runs under whichever has room there, so with several accounts that computer is out only when all are. */
212
227
  export function outOfQuota(data, usage, now = Date.now()) {
228
+ const claude = usage?.filter(item => item.source === "claude") ?? [];
229
+ if (data.harness === "claude" && !data.account && claude.length > 1) {
230
+ if (claude.some(item => !item.exhausted))
231
+ return undefined;
232
+ return `Its claude accounts all have no quota left${backIn(claude.map(item => item.until).filter((value) => Boolean(value)).sort()[0], now)}.`;
233
+ }
213
234
  const room = roomFor(data, usage);
214
235
  if (!room?.exhausted)
215
236
  return undefined;
216
- const until = room.until ? Date.parse(room.until) : NaN;
217
- const minutes = Number.isFinite(until) ? Math.max(1, Math.round((until - now) / 60_000)) : undefined;
218
- const back = minutes === undefined ? "" : minutes >= 1440 ? ` for about ${Math.round(minutes / 1440)} more days` : minutes >= 60 ? ` for about ${Math.round(minutes / 60)} more hours` : ` for about ${minutes} more minutes`;
219
- return `Its ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} has no quota left${back}.`;
237
+ return `Its ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} has no quota left${backIn(room.until, now)}.`;
238
+ }
239
+ /** A computer's signed-in Claude accounts with their room, from its capacity probe. */
240
+ export function capacityClaudeRooms(harnesses, usage) {
241
+ const accounts = harnesses?.find(entry => entry.source === "claude")?.accounts ?? [];
242
+ return accounts.map(account => {
243
+ const room = usage?.find(item => item.source === "claude" && (item.account ?? "default") === account.id);
244
+ return { account: account.id, ...(account.key ? { key: account.key } : {}), usable: account.usable,
245
+ ...(room?.fiveHour ? { fiveHour: room.fiveHour } : {}), ...(room?.week ? { week: room.week } : {}),
246
+ ...(room?.exhausted ? { exhausted: true, ...(room.until ? { until: room.until } : {}) } : {}) };
247
+ });
220
248
  }
221
249
  /** Why a computer cannot run this dispatch's harness and account, or undefined when it can or cannot yet be told.
222
250
  * `unknown` (no `harnesses`) only counts against a computer when a non-default account was asked for. */
223
251
  function unusable(data, harnesses, strictUnknown) {
224
252
  if (!harnesses)
225
253
  return strictUnknown && data.account && data.account !== "default" ? "Its Hook does not report harnesses or accounts (update it)." : undefined;
254
+ // No account named: any signed-in Claude account there will do (the launch picks one).
255
+ if (data.harness === "claude" && !data.account) {
256
+ const usable = harnesses.find(entry => entry.source === "claude")?.accounts?.find(account => account.usable);
257
+ if (usable)
258
+ return unusable({ harness: "claude", account: usable.id }, harnesses, strictUnknown);
259
+ }
226
260
  const availability = hasUsable({ harnesses }, data.harness, data.account);
227
261
  return availability.ok ? undefined : availability.reason;
228
262
  }
@@ -419,8 +453,9 @@ export class DispatchService {
419
453
  this.settleIntervalMs = settleIntervalMs;
420
454
  }
421
455
  /** `originValue` is the local pane the request came from, as its agent's
422
- * Herdr variables name it; a pane without a running agent is left out. */
423
- async dispatch(input, originValue) {
456
+ * Herdr variables name it; a pane without a running agent is left out.
457
+ * `continues` names the dispatch whose worker hit its usage limit (account-failover.ts). */
458
+ async dispatch(input, originValue, continues) {
424
459
  const data = dispatchSchema.parse(input);
425
460
  if (data.permissionMode && data.harness === "opencode")
426
461
  throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude, Codex and Copilot workers.");
@@ -532,7 +567,7 @@ export class DispatchService {
532
567
  createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), state: "launching",
533
568
  ...(grant ? { granted: grantLabel(grant) } : {}), ...(authority?.listed ? { authority: authority.line.slice(0, 600) } : {}),
534
569
  ...(checked?.confirmation ? { authorityConfirmed: checked.confirmation.confirmedAt } : {}),
535
- ...(skipped.length ? { skipped } : {}), ...(origin ? { origin } : {}) };
570
+ ...(skipped.length ? { skipped } : {}), ...(origin ? { origin } : {}), ...(continues ? { continues } : {}) };
536
571
  await save(receipt);
537
572
  try {
538
573
  // The brief goes with the launch: a Hook that can start the harness
@@ -541,6 +576,13 @@ export class DispatchService {
541
576
  // Placed: the brief is confirmed outside the lock.
542
577
  placed = peer.name;
543
578
  this.placing.set(placed, this.inFlight(placed) + 1);
579
+ // The receiving Hook chose the Claude account (the one with the most room) when none was named.
580
+ if (!data.account && typeof launched.account === "string" && isAccountSlug(launched.account)) {
581
+ receipt.account = launched.account;
582
+ if (typeof launched.accountChoice === "string")
583
+ receipt.accountChoice = launched.accountChoice.slice(0, 400);
584
+ logger.info("dispatch", `${receipt.label} on ${peer.name} runs under Claude account ${launched.account}${receipt.accountChoice ? `: ${receipt.accountChoice}` : ""}.`);
585
+ }
544
586
  release();
545
587
  // An older Hook ignores the field and starts the worker in its own default mode.
546
588
  const ignored = data.permissionMode && launched.permissionMode !== data.permissionMode ? IGNORED_MODE : undefined;
@@ -695,6 +737,22 @@ export class DispatchService {
695
737
  }
696
738
  receipt.error = `${receipt.harness} started with the brief on ${receipt.computer} but has not confirmed it yet (last status ${status ?? "unknown"}). The Hook keeps checking.`.slice(0, 500);
697
739
  }
740
+ /** Every connected computer's signed-in Claude accounts and their room, this computer first:
741
+ * where a worker that hit its usage limit can continue (account-failover.ts). */
742
+ async claudeRooms() {
743
+ const here = this.local();
744
+ const hosts = [here, ...(await hookPeers().catch(() => [])).map(candidate => peerHost(candidate))];
745
+ const found = await Promise.all(hosts.map(async (host) => {
746
+ try {
747
+ const reported = await capacity(host);
748
+ return { computer: host.name, local: host.local, rooms: capacityClaudeRooms(reported.harnesses, reported.usage) };
749
+ }
750
+ catch {
751
+ return undefined;
752
+ }
753
+ }));
754
+ return found.filter((item) => !!item);
755
+ }
698
756
  /** The query a conductor's dispatch sends with each capacity probe; undefined for any other caller. */
699
757
  async conductorCaller(value) {
700
758
  const pane = originPaneSchema.safeParse(value);
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
- import { type Target } from "./protocol.js";
2
+ import { type WindowRoom } from "./account-choice.js";
3
+ import { type Json, type Target } from "./protocol.js";
3
4
  import { computerLabel, type PeerFacts } from "./computer-identity.js";
4
5
  export { computerLabel };
5
6
  export declare const handOffSchema: z.ZodObject<{
@@ -65,7 +66,26 @@ export interface LiveSession {
65
66
  stalled?: boolean;
66
67
  stallFor?: number;
67
68
  stalledSince?: string;
69
+ /** A Claude session's account room: its 5-hour and weekly windows. */
70
+ quota?: ClaudeQuota;
68
71
  }
72
+ /** One window's room as live_sessions shows it. */
73
+ export type QuotaWindow = WindowRoom & {
74
+ resetsIn?: string;
75
+ };
76
+ export interface ClaudeQuota {
77
+ fiveHour?: QuotaWindow;
78
+ week?: QuotaWindow;
79
+ }
80
+ /** One signed-in Claude account on one computer, with its room. */
81
+ export interface ClaudeAccountRoom extends ClaudeQuota {
82
+ computer: string;
83
+ account: string;
84
+ label?: string;
85
+ email?: string;
86
+ }
87
+ /** Each Claude account's room in one computer's usage answer. */
88
+ export declare function claudeAccountRooms(answer: Json, computer: string, now?: number): ClaudeAccountRoom[];
69
89
  /** A registered computer this Hook cannot see, with the other names the store
70
90
  * registers it under. */
71
91
  export interface NotLinkedComputer {
@@ -90,6 +110,8 @@ export interface LiveSessions {
90
110
  /** Registered in the store but not linked in hooks.yaml: unknown, not idle. */
91
111
  notLinked: NotLinkedComputer[];
92
112
  enrolled: number;
113
+ /** Every signed-in Claude account on each computer that answered, with its 5-hour and weekly room. */
114
+ claudeAccounts?: ClaudeAccountRoom[];
93
115
  peerError?: string;
94
116
  }
95
117
  /** Every live agent the conductor could hand work to: this computer's Herdr
@@ -7,6 +7,8 @@ import { hookRequest } from "./client.js";
7
7
  import { projectName } from "./dispatch.js";
8
8
  import { paneProject } from "./approval-summary.js";
9
9
  import { isAccountSlug } from "./claude-accounts.js";
10
+ import { accountWindows } from "./account-choice.js";
11
+ import { resetsIn } from "../computers/read.js";
10
12
  import { grantLabel, findGrant } from "./grants.js";
11
13
  import { hookPeers, optionalHookPeers, peerRequest } from "./peers.js";
12
14
  import { BridgeError, errorCode, object, objects, sessionId, targetSchema } from "./protocol.js";
@@ -117,6 +119,23 @@ export async function handOff(input, options = {}) {
117
119
  ...(result.unsubmitted === true ? { unsubmitted: true } : {}),
118
120
  ...(label ? { label } : {}), ...(grant ? { granted: grantLabel(grant) } : {}) };
119
121
  }
122
+ const CLAUDE_USAGE_ROUTE = "/v1/usage?sources=claude&accounts=all";
123
+ /** Each Claude account's room in one computer's usage answer. */
124
+ export function claudeAccountRooms(answer, computer, now = Date.now()) {
125
+ const window = (room) => {
126
+ if (!room)
127
+ return undefined;
128
+ const until = room.resetsAt ? resetsIn(room.resetsAt, now) : undefined;
129
+ return { ...room, ...(until ? { resetsIn: until } : {}) };
130
+ };
131
+ return objects(answer.accounts).filter(row => row.source === "claude" && Array.isArray(row.windows)).map(row => {
132
+ const usage = row;
133
+ const { fiveHour, week } = accountWindows(usage, now);
134
+ const five = window(fiveHour), seven = window(week);
135
+ return { computer, account: usage.account?.id ?? "default", ...(usage.account?.label ? { label: usage.account.label } : {}),
136
+ ...(usage.account?.email ? { email: usage.account.email } : {}), ...(five ? { fiveHour: five } : {}), ...(seven ? { week: seven } : {}) };
137
+ });
138
+ }
120
139
  function sessionsFrom(overview, computer, local, now = Date.now()) {
121
140
  const sessions = [];
122
141
  for (const group of objects(overview.groups))
@@ -165,7 +184,9 @@ export function notLinkedComputers(store, here, linked) {
165
184
  export async function listLiveSessions(options = {}) {
166
185
  const health = await hookRequest("/v1/health");
167
186
  const here = typeof object(health.computer).name === "string" ? String(object(health.computer).name) : "this computer";
168
- const sessions = sessionsFrom(await hookRequest("/v1/workspaces"), here, true);
187
+ const [overview, localUsage] = await Promise.all([hookRequest("/v1/workspaces"), hookRequest(CLAUDE_USAGE_ROUTE, undefined, undefined, 10_000).catch(() => undefined)]);
188
+ const sessions = sessionsFrom(overview, here, true);
189
+ const claudeAccounts = localUsage ? claudeAccountRooms(localUsage, here) : [];
169
190
  const { peers, peerError } = await optionalHookPeers();
170
191
  const unreachable = [];
171
192
  // Names each peer answers to (its hostname, Bonjour name), so a computer
@@ -174,8 +195,11 @@ export async function listLiveSessions(options = {}) {
174
195
  await Promise.all(peers.map(async (peer) => {
175
196
  try {
176
197
  const route = peer.server && peer.server !== "default" ? `/v1/workspaces?server=${encodeURIComponent(peer.server)}` : "/v1/workspaces";
177
- const [overview, health] = await Promise.all([peerRequest(peer, route), peerRequest(peer, "/v1/health").catch(() => ({}))]);
198
+ const [overview, health, usage] = await Promise.all([peerRequest(peer, route), peerRequest(peer, "/v1/health").catch(() => ({})),
199
+ peerRequest(peer, CLAUDE_USAGE_ROUTE, undefined, 10_000).catch(() => undefined)]);
178
200
  sessions.push(...sessionsFrom(overview, peer.name, false));
201
+ if (usage)
202
+ claudeAccounts.push(...claudeAccountRooms(usage, peer.name));
179
203
  const computer = object(object(health).computer);
180
204
  peerNames.set(peer.name, [computer.name, ...(Array.isArray(computer.aliases) ? computer.aliases : [])].filter((name) => typeof name === "string"));
181
205
  }
@@ -186,5 +210,14 @@ export async function listLiveSessions(options = {}) {
186
210
  }));
187
211
  const store = options.store !== undefined ? options.store : findPhrenPath();
188
212
  const notLinked = notLinkedFrom(store, here, peers.map(peer => ({ name: peer.name, address: peer.address, names: peerNames.get(peer.name) })));
189
- return { sessions, unreachable, notLinked, enrolled: peers.length, ...(peerError ? { peerError } : {}) };
213
+ // Each Claude session carries its account's room, so the conductor and phone see how long it can keep working.
214
+ for (const session of sessions) {
215
+ if (session.agent !== "claude")
216
+ continue;
217
+ const room = claudeAccounts.find(item => item.computer === session.computer && item.account === (session.account ?? "default"));
218
+ if (room?.fiveHour || room?.week)
219
+ session.quota = { ...(room.fiveHour ? { fiveHour: room.fiveHour } : {}), ...(room.week ? { week: room.week } : {}) };
220
+ }
221
+ claudeAccounts.sort((a, b) => a.computer.localeCompare(b.computer) || a.account.localeCompare(b.account));
222
+ return { sessions, unreachable, notLinked, enrolled: peers.length, ...(claudeAccounts.length ? { claudeAccounts } : {}), ...(peerError ? { peerError } : {}) };
190
223
  }
@@ -51,6 +51,9 @@ export declare function briefLabel(id: string): Promise<string | undefined>;
51
51
  * it in place left a moment where the folder was there and the file was not.
52
52
  */
53
53
  export declare function writeLaunchBrief(brief: LaunchBrief, now?: number, label?: string): Promise<string>;
54
+ /** The text of a brief this computer wrote, for the dispatch that continues its worker on another
55
+ * account (account-failover.ts); undefined once pruned or for an id it never wrote. */
56
+ export declare function readLaunchBrief(id: string): Promise<string | undefined>;
54
57
  export declare const arrivalSchema: z.ZodObject<{
55
58
  started: z.ZodOptional<z.ZodObject<{
56
59
  at: z.ZodString;
@@ -128,6 +128,22 @@ export async function writeLaunchBrief(brief, now = Date.now(), label) {
128
128
  }
129
129
  return file;
130
130
  }
131
+ /** The text of a brief this computer wrote, for the dispatch that continues its worker on another
132
+ * account (account-failover.ts); undefined once pruned or for an id it never wrote. */
133
+ export async function readLaunchBrief(id) {
134
+ if (!briefId.safeParse(id).success)
135
+ return undefined;
136
+ const file = path.join(briefDirectory(id), "brief.md");
137
+ try {
138
+ const info = await lstat(file);
139
+ if (!info.isFile() || info.size > 65_536)
140
+ return undefined;
141
+ return await readFile(file, "utf8");
142
+ }
143
+ catch {
144
+ return undefined;
145
+ }
146
+ }
131
147
  const arrivalEvent = z.object({ at: z.string().datetime(), target: targetSchema }).strict();
132
148
  export const arrivalSchema = z.object({ started: arrivalEvent.optional(), accepted: arrivalEvent.optional() }).strict();
133
149
  /** What the worker's own hooks have said about its brief: `started` at its
@@ -6,8 +6,10 @@ import { dump, load } from "js-yaml";
6
6
  import { z } from "zod";
7
7
  import { logger } from "../logger.js";
8
8
  import { hookRequest } from "./client.js";
9
- import { computerName, dispatchKeyPath, publicComputerKey } from "./computers.js";
10
- import { atomic, BridgeError, bridgeRoot, serverName, withErrorCode } from "./protocol.js";
9
+ import { dispatchKeyPath, publicComputerKey } from "./computers.js";
10
+ // computerName comes from protocol.js, where it is defined: through computers.js it can still be
11
+ // undefined when an import cycle (usage -> account-choice -> health -> peers) loads this file first.
12
+ import { atomic, BridgeError, bridgeRoot, computerName, serverName, withErrorCode } from "./protocol.js";
11
13
  const peerSchema = z.object({
12
14
  name: computerName,
13
15
  address: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9.:-]{0,252}$/),
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import { finished as streamFinished } from "node:stream/promises";
6
6
  import { askpassEnv } from "./sudo.js";
7
7
  import { claudeHome, claudeLaunchEnv } from "./claude-accounts.js";
8
+ import { pickClaudeAccount } from "./account-choice.js";
8
9
  import { fanoutRoot } from "./fanouts.js";
9
10
  import { pretrustFolder } from "./folder-trust.js";
10
11
  import { findPane, paneIdentity, servers, snapshot } from "./herdr.js";
@@ -104,7 +105,10 @@ export function headlessEnv(schedule, env = process.env) {
104
105
  return { ...env, ...claudeLaunchEnv(home) };
105
106
  }
106
107
  async function launchHeadless(context, store, started) {
107
- const env = headlessEnv(context.schedule);
108
+ // A Claude schedule that names no account runs under the one with the most room, as a Herdr launch does.
109
+ const choice = context.schedule.harness === "claude" && !context.schedule.account
110
+ ? await pickClaudeAccount(`Schedule "${context.schedule.name}"`).catch(() => undefined) : undefined;
111
+ const env = headlessEnv(choice ? { ...context.schedule, account: choice.account } : context.schedule);
108
112
  const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path.join(root, context.runId);
109
113
  await mkdir(jobDir, { recursive: true, mode: 0o700 });
110
114
  const eventLog = "events.jsonl", now = new Date().toISOString();
@@ -54,6 +54,9 @@ export interface FinalTurn {
54
54
  }
55
55
  /** The public text of one assistant row, without reasoning or tool output. */
56
56
  export declare function publicAssistant(raw: Json, source: Provider): string | undefined;
57
+ /** How a Claude usage-limit error starts, so dispatch can tell it from any other failure (account-failover.ts). */
58
+ export declare const CLAUDE_USAGE_LIMIT = "Claude usage limit:";
59
+ export declare const isClaudeUsageLimit: (error: string | undefined) => boolean;
57
60
  /** Claude Code background work a transcript line starts or ends, by task id:
58
61
  * a backgrounded Bash call, an async subagent or a Monitor start one; a
59
62
  * task-notification with a final status, or a TaskStop, ends it. A
@@ -99,6 +99,22 @@ function turnError(raw, source) {
99
99
  const error = object(object(raw.payload).error), message = typeof error.message === "string" ? error.message.replace(/\s+/g, " ").trim() : "";
100
100
  return message ? message.slice(0, 500) : undefined;
101
101
  }
102
+ /** How a Claude usage-limit error starts, so dispatch can tell it from any other failure (account-failover.ts). */
103
+ export const CLAUDE_USAGE_LIMIT = "Claude usage limit:";
104
+ export const isClaudeUsageLimit = (error) => !!error?.startsWith(CLAUDE_USAGE_LIMIT);
105
+ /** Claude Code's own record of a subscription limit ending the turn: a synthetic assistant row
106
+ * (`isApiErrorMessage`, `error: "rate_limit"`) whose text says which limit and when it resets,
107
+ * as "You've hit your session limit · resets 3pm". A transient 429 Claude Code retries by itself never ends the turn. */
108
+ function claudeUsageLimit(raw) {
109
+ if (raw.type !== "assistant" || raw.isApiErrorMessage !== true || raw.error !== "rate_limit")
110
+ return undefined;
111
+ const content = object(raw.message).content;
112
+ const text = (typeof content === "string" ? content : objects(content).filter(block => block.type === "text").map(block => String(block.text ?? "")).join(" "))
113
+ .replace(/\s+/g, " ").trim();
114
+ if (!/\b(?:hit your|usage limit|limit reached|out of (?:extra )?usage)\b/i.test(text) && !raw.quotaLimits)
115
+ return undefined;
116
+ return `${CLAUDE_USAGE_LIMIT} ${text || "the subscription refused the request"}`.slice(0, 500);
117
+ }
102
118
  /** The owner stopping a turn: Claude's interruption marker, Codex's aborted turn, Copilot's abort. */
103
119
  function turnInterrupted(raw, source) {
104
120
  if (source === "codex")
@@ -216,18 +232,28 @@ export function finalTurnFromLines(lines, source) {
216
232
  copilotFinal = false;
217
233
  continue;
218
234
  }
235
+ // The limit ends the turn; its own text is the error, not the worker's last reply.
236
+ const limit = source === "claude" ? claudeUsageLimit(raw) : undefined;
237
+ if (limit) {
238
+ completed = true;
239
+ interrupted = false;
240
+ error = limit;
241
+ continue;
242
+ }
219
243
  const text = publicAssistant(raw, source);
220
244
  if (text) {
221
245
  lastAssistant = text;
222
246
  completed = false;
223
247
  interrupted = false;
248
+ error = undefined;
224
249
  }
225
250
  if (source === "copilot" && raw.type === "assistant.message" && !raw.agentId)
226
251
  copilotFinal = object(raw.data).phase === "final_answer";
252
+ // Claude's turn_duration after its limit row keeps that error.
227
253
  if (turnEnded(raw, source, copilotFinal)) {
228
254
  completed = true;
229
255
  interrupted = false;
230
- error = turnError(raw, source);
256
+ error = turnError(raw, source) ?? (source === "claude" ? error : undefined);
231
257
  copilotFinal = false;
232
258
  }
233
259
  }