@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.
@@ -19,6 +19,7 @@ import { clearConductor, conductorPane, noteConductorSession, readRoleState, rec
19
19
  import { localNames } from "./computer-names.js";
20
20
  import { pretrustFolder } from "./folder-trust.js";
21
21
  import { claudeHome, claudeLaunchEnv, isAccountSlug, DEFAULT_ACCOUNT } from "./claude-accounts.js";
22
+ import { pickClaudeAccount } from "./account-choice.js";
22
23
  import { harnessInventoryWithin, hasUsable, launchCheckOff } from "./harnesses.js";
23
24
  import { paneAccountKey, recordPaneAccount } from "./pane-accounts.js";
24
25
  import { optionalHookPeers } from "./peers.js";
@@ -328,7 +329,7 @@ async function startSession(server, data, options) {
328
329
  const label = plainText(200).parse(data.label);
329
330
  const kind = z.enum(launchKinds).parse(data.kind);
330
331
  const effort = z.enum(launchEfforts).default("medium").parse(data.effort);
331
- const account = data.account === undefined || data.account === null ? undefined : z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").parse(data.account);
332
+ const named = data.account === undefined || data.account === null ? undefined : z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").parse(data.account);
332
333
  const permissionMode = z.enum(PERMISSION_MODES).optional().parse(data.permissionMode ?? undefined);
333
334
  if (permissionMode && role === "conductor")
334
335
  throw new BridgeError(400, "A conductor starts with its own permissions; permissionMode is for workers.");
@@ -362,6 +363,9 @@ async function startSession(server, data, options) {
362
363
  // Herdr 0.9.1 refuses a start timeout of 3000 ms or less (invalid_agent_timeout).
363
364
  const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
364
365
  // Checked before anything is created, so a refusal leaves no pane, worktree or brief file behind.
366
+ // A Claude launch that names no account runs under the signed-in one with the most room left.
367
+ const choice = kind === "claude" && named === undefined ? await pickClaudeAccount(`Launch "${label}"`).catch(() => undefined) : undefined;
368
+ const account = named ?? choice?.account;
365
369
  await requireAvailable(kind, account);
366
370
  const home = kind === "claude" && account && account !== DEFAULT_ACCOUNT ? claudeHome(account) : undefined;
367
371
  if (kind === "claude" && account && account !== DEFAULT_ACCOUNT && !home)
@@ -536,7 +540,7 @@ async function startSession(server, data, options) {
536
540
  await new JobRegistry().register({ pane: { server, pane: created.paneId, ...(created.workspaceId ? { workspace: created.workspaceId } : {}), agent: kind, label },
537
541
  ...(sessionId ? { session: sessionId } : {}), agent: kind, label, command: kind }).catch(() => undefined);
538
542
  }
539
- return { ok: true, ...created, cwd, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
543
+ return { ok: true, ...created, cwd, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(choice ? { accountChoice: choice.reason } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
540
544
  // The caller types the brief itself unless it went with the launch.
541
545
  ...(brief ? { briefLaunched: appServer ? briefTurn !== undefined : !!briefLaunch || !!servedBrief,
542
546
  briefState: appServer ? briefTurn ?? "unconfirmed" : served ? (servedBrief?.delivered ? "sent" : "uncertain") : briefLaunch ? "sent" : "unconfirmed" } : {}),
@@ -15,7 +15,7 @@ import { resolveCodeStore, CodeRoutes } from "./code-routes.js";
15
15
  import { dispatchProjectDirectory, dispatchStatus, originPaneSchema } from "./dispatch.js";
16
16
  import { hookWorkers } from "./dispatch-returns.js";
17
17
  import { remoteChildren } from "./dispatch-tree.js";
18
- import { briefArrival, briefId } from "./launch-brief.js";
18
+ import { briefArrival, briefId, readLaunchBrief } from "./launch-brief.js";
19
19
  import { listApprovalRules, changeApprovalRule } from "./approval-rules.js";
20
20
  import { addGrant, listNamedGrants, removeGrant } from "./grants.js";
21
21
  import { clearProjectAuthority, confirmAuthority, listConfirmations, projectAuthority, readAuthority, setProjectAuthority } from "./authority.js";
@@ -347,6 +347,10 @@ export function createRouteHandler(ctx) {
347
347
  case "/v1/dispatch/arrival":
348
348
  result = { arrival: await briefArrival(briefId.parse(url.searchParams.get("id"))) ?? null };
349
349
  break;
350
+ // Asked by the dispatching Hook when this computer's worker hit its usage limit and continues on another account.
351
+ case "/v1/dispatch/brief":
352
+ result = { text: await readLaunchBrief(briefId.parse(url.searchParams.get("id"))) ?? null };
353
+ break;
350
354
  case "/v1/approval-rules":
351
355
  result = { rules: await listApprovalRules(undefined, z.string().regex(/^[A-Za-z0-9+/]{43}=$/).optional().parse(url.searchParams.get("pairedKey") ?? undefined)) };
352
356
  break;
@@ -1,3 +1,5 @@
1
+ import { setChoiceReaders } from "./account-choice.js";
2
+ import { AccountFailover } from "./account-failover.js";
1
3
  import { ownerInboxSources } from "./owner-inbox-sources.js";
2
4
  import { OwnerInbox } from "./owner-inbox.js";
3
5
  import { closeFinishedWorker } from "./worker-close.js";
@@ -88,6 +90,8 @@ export async function serve(version, options = {}) {
88
90
  const agentHooks = new AgentHooks(undefined, modules, path.join(bridgeRoot(), "deliveries.json"));
89
91
  // Follows what dispatched workers do and tells the dispatching agent.
90
92
  const returns = dispatches ? new DispatchReturns({
93
+ // Continue on another signed-in account when a Claude worker stops at its usage limit: opt-in, `phren config account-failover on`.
94
+ failover: new AccountFailover({ rooms: () => dispatches.claudeRooms(), dispatch: (input, origin, continues) => dispatches.dispatch(input, origin, continues) }),
91
95
  localWorkers: hookWorkers(agentHooks),
92
96
  close: async (receipt) => {
93
97
  const data = { target: receipt.target, dispatch: receipt.id, turn: receipt.closePending.turn };
@@ -130,6 +134,8 @@ export async function serve(version, options = {}) {
130
134
  }) : undefined;
131
135
  const contextUsage = new WorkspaceContextUsage();
132
136
  const accountUsage = options.accountUsage ?? new AccountUsageReader();
137
+ // A Claude launch that names no account runs under the one with the most room (account-choice.ts).
138
+ setChoiceReaders({ usage: () => accountUsage.limits(true) });
133
139
  const resources = new ResourceMonitor();
134
140
  const tabActivity = new TabActivityStore();
135
141
  const codexQuestions = new CodexQuestions(undefined, codexServers);
@@ -1,4 +1,5 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { accountWindows } from "./account-choice.js";
2
3
  import { type AccountRef, type ClaudeHome } from "./claude-accounts.js";
3
4
  import { type Subscription } from "./subscription.js";
4
5
  export type { Subscription } from "./subscription.js";
@@ -137,14 +138,15 @@ export declare function windowExhausted(window: UsageWindow, now: number): boole
137
138
  /** Percent left on a window at `now`: none once its reset passed or with no percent, 0 while the service refuses requests. */
138
139
  export declare function windowLeft(window: UsageWindow, now: number): number | undefined;
139
140
  /** What a capacity probe says about room: each Codex and Claude account's least room left, and whether it has none
140
- * (`exhausted`, with `until` the last reset that frees it). */
141
+ * (`exhausted`, with `until` the last reset that frees it). Claude rows add their 5-hour and weekly rooms, which
142
+ * launch and failover rank accounts by (account-choice.ts). */
141
143
  export declare function capacityRoom(accounts: readonly AccountUsage[], now: number): Array<{
142
144
  source: string;
143
145
  account?: string;
144
146
  leftPercent?: number;
145
147
  exhausted?: true;
146
148
  until?: string;
147
- }>;
149
+ } & ReturnType<typeof accountWindows>>;
148
150
  /** A Claude report older than this says nothing about the account now. */
149
151
  export declare const CLAUDE_REPORT_MAX_AGE_MS: number;
150
152
  /**
@@ -11,6 +11,7 @@ import { stripTerminal } from "../terminal-text.js";
11
11
  import { codexExecutable } from "./codex-binary.js";
12
12
  import { readSpeechKey } from "./speech-key.js";
13
13
  import { resolveSpeechRegion, SPEECH_REGIONS } from "./speech-voice.js";
14
+ import { accountWindows } from "./account-choice.js";
14
15
  import { CODEX_ACCOUNT, claudeAccountSubscription, claudeAccountEmail, claudeAccountRef, claudeHomeOfEnv, claudeHomes } from "./claude-accounts.js";
15
16
  import { planName, subscriptionDate } from "./subscription.js";
16
17
  const exec = promisify(execFile);
@@ -691,14 +692,15 @@ export function windowLeft(window, now) {
691
692
  return typeof window.usedPercent === "number" ? Math.max(0, Math.min(100, Math.round(100 - window.usedPercent))) : undefined;
692
693
  }
693
694
  /** What a capacity probe says about room: each Codex and Claude account's least room left, and whether it has none
694
- * (`exhausted`, with `until` the last reset that frees it). */
695
+ * (`exhausted`, with `until` the last reset that frees it). Claude rows add their 5-hour and weekly rooms, which
696
+ * launch and failover rank accounts by (account-choice.ts). */
695
697
  export function capacityRoom(accounts, now) {
696
698
  return accounts.map(usage => {
697
699
  const left = usage.windows.map(window => windowLeft(window, now)).filter((value) => value !== undefined);
698
700
  const out = usage.windows.filter(window => windowExhausted(window, now));
699
701
  const until = out.map(window => window.resetsAt).filter((value) => Boolean(value)).sort().at(-1);
700
702
  return { source: usage.source, ...(usage.account?.id ? { account: usage.account.id } : {}), ...(left.length ? { leftPercent: Math.min(...left) } : {}),
701
- ...(out.length ? { exhausted: true, ...(until ? { until } : {}) } : {}) };
703
+ ...(out.length ? { exhausted: true, ...(until ? { until } : {}) } : {}), ...(usage.source === "claude" ? accountWindows(usage, now) : {}) };
702
704
  });
703
705
  }
704
706
  /** A Claude report older than this says nothing about the account now. */