@phren/cli 0.3.58 → 0.3.59

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 (75) 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 +18 -0
  11. package/dist/bridge/account-usage.js +57 -1
  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 +5 -1
  23. package/dist/bridge/claude-credits.js +37 -29
  24. package/dist/bridge/command.js +12 -3
  25. package/dist/bridge/dispatch-command.js +22 -0
  26. package/dist/bridge/dispatch-returns.d.ts +23 -0
  27. package/dist/bridge/dispatch-returns.js +57 -0
  28. package/dist/bridge/dispatch.d.ts +26 -4
  29. package/dist/bridge/dispatch.js +100 -11
  30. package/dist/bridge/git-host-gitlab.js +2 -1
  31. package/dist/bridge/hand-off-queue.d.ts +71 -0
  32. package/dist/bridge/hand-off-queue.js +38 -0
  33. package/dist/bridge/harnesses.d.ts +12 -0
  34. package/dist/bridge/harnesses.js +20 -4
  35. package/dist/bridge/helper.d.ts +54 -0
  36. package/dist/bridge/helper.js +186 -0
  37. package/dist/bridge/herdr.js +6 -2
  38. package/dist/bridge/hook-fast.d.ts +3 -0
  39. package/dist/bridge/hook-fast.js +10 -2
  40. package/dist/bridge/move-computers.d.ts +15 -1
  41. package/dist/bridge/move-computers.js +123 -26
  42. package/dist/bridge/prompt-deliveries.d.ts +29 -1
  43. package/dist/bridge/prompt-deliveries.js +146 -10
  44. package/dist/bridge/schedule-watch.js +17 -3
  45. package/dist/bridge/server-routes.d.ts +3 -0
  46. package/dist/bridge/server-routes.js +66 -6
  47. package/dist/bridge/server.js +2 -1
  48. package/dist/bridge/session-move.d.ts +59 -1
  49. package/dist/bridge/session-move.js +266 -18
  50. package/dist/bridge/simulators.d.ts +19 -0
  51. package/dist/bridge/simulators.js +93 -13
  52. package/dist/bridge/speech-live.js +132 -22
  53. package/dist/bridge/task-routes.d.ts +16 -16
  54. package/dist/bridge/terminal-herdr.js +6 -1
  55. package/dist/bridge/terminal-tmux.js +9 -5
  56. package/dist/bridge/terminal.d.ts +9 -2
  57. package/dist/bridge/transcript-claude.d.ts +3 -0
  58. package/dist/bridge/transcript-claude.js +175 -29
  59. package/dist/bridge/transcript-preview.d.ts +11 -2
  60. package/dist/bridge/transcript-preview.js +90 -8
  61. package/dist/bridge/turn-records.d.ts +19 -0
  62. package/dist/bridge/turn-records.js +78 -3
  63. package/dist/bridge-hook.mjs +11394 -9961
  64. package/dist/cli-registry.js +2 -2
  65. package/dist/content/citation.d.ts +4 -0
  66. package/dist/content/citation.js +21 -21
  67. package/dist/data/task-contract.d.ts +4 -4
  68. package/dist/governance/policy.js +5 -2
  69. package/dist/index.js +1 -1
  70. package/dist/modules/registry.js +3 -3
  71. package/dist/project-config.d.ts +14 -0
  72. package/dist/project-config.js +40 -1
  73. package/dist/tools/helper.d.ts +3 -0
  74. package/dist/tools/helper.js +44 -0
  75. package/package.json +1 -1
@@ -18,7 +18,8 @@ import { addPeerFromLink, discoverComputers, linkComputer } from "./link.js";
18
18
  import { ARCHIVE_MAX_FOLDERS, archiveFinishedFanouts, FANOUTS_ARCHIVE_USAGE, parseFanoutArchiveFlags } from "./fanouts.js";
19
19
  import { harnessInventory } from "./harnesses.js";
20
20
  import { addClaudeAccount } from "./claude-account-setup.js";
21
- import { setAccountLabel } from "./claude-accounts.js";
21
+ import { claudeHome, setAccountLabel } from "./claude-accounts.js";
22
+ import { accountPoolsCommand, computerAllowedPools } from "./account-pools.js";
22
23
  import { addClaudeCredit, claudeCredits, removeClaudeCredit } from "./claude-credits.js";
23
24
  import { ModelCatalog } from "./models.js";
24
25
  const CREDIT_USAGE = "Usage: phren bridge accounts credit <id> [--amount <usd> [--expires <yyyy-mm-dd>] [--since <yyyy-mm-dd>] [--label <name>] | --remove <credit>]";
@@ -43,8 +44,16 @@ export async function runBridge(args, version) {
43
44
  for (const harness of (await harnessInventory()).harnesses) {
44
45
  console.log(`${harness.source}: ${harness.installed ? `installed ${harness.version ?? ""}`.trim() : "not installed"}, ${harness.usable ? "usable" : `not usable (${harness.reason ?? "unknown"})`}`);
45
46
  for (const account of harness.accounts ?? [])
46
- console.log(` ${account.id} ${account.label} ${account.signedIn ? "signed in" : "not signed in"} ${account.usable ? "usable" : `not usable (${account.reason ?? "unknown"})`}${account.plan ? ` plan ${account.plan}` : ""}`);
47
+ console.log(` ${account.id} ${account.label} ${account.signedIn ? "signed in" : "not signed in"} ${account.usable ? "usable" : `not usable (${account.reason ?? "unknown"})`}${account.plan ? ` plan ${account.plan}` : ""}${account.pool ? ` pool ${account.pool}` : ""}${account.role ? ` role ${account.role}` : ""}`);
47
48
  }
49
+ const allowed = computerAllowedPools();
50
+ if (allowed)
51
+ console.log(`This computer's accounts work for pools: ${allowed.join(", ")}`);
52
+ }
53
+ else if (args[1] === "pool" || args[1] === "role" || args[1] === "allowed-pools") {
54
+ const { phrenStoreRoot } = await import("./transcripts.js");
55
+ for (const line of await accountPoolsCommand(args.slice(1), phrenStoreRoot, slug => !!claudeHome(slug)))
56
+ console.log(line);
48
57
  }
49
58
  else if (args[1] === "add" && args[2] && !args[2].startsWith("-")) {
50
59
  const at = args.indexOf("--label");
@@ -78,7 +87,7 @@ export async function runBridge(args, version) {
78
87
  }
79
88
  }
80
89
  else
81
- throw new Error("Usage: phren bridge accounts [add <slug> [--label <name>] | label <id> <label> | credit <id> [--amount <usd> [--expires <date>] [--since <date>] [--label <name>] | --remove <credit>]]");
90
+ throw new Error("Usage: phren bridge accounts [add <slug> [--label <name>] | label <id> <label> | credit <id> [--amount <usd> [--expires <date>] [--since <date>] [--label <name>] | --remove <credit>] | pool <id> <tag>|--clear | role <id> helpers|last-resort|off|--clear | allowed-pools [--project <name>] [<tag>… | --clear]]");
82
91
  break;
83
92
  }
84
93
  case "discover": {
@@ -34,6 +34,28 @@ export async function runDispatch(args) {
34
34
  console.log(JSON.stringify(await hookRequest("/v1/dispatch/returns", { ...(origin ? { origin } : {}) }), null, 2));
35
35
  return 0;
36
36
  }
37
+ if (args[0] === "returns" && args.length <= 4 && args.slice(1).every(arg => ["--watch", "--json", "--consume"].includes(arg))) {
38
+ const origin = await terminalPaneFromEnv();
39
+ // The watch peeks (an agent conductor on this Hook still takes its returns) unless told to take them.
40
+ const peek = args.includes("--watch") && !args.includes("--consume");
41
+ const read = async () => {
42
+ const answer = await hookRequest(peek ? "/v1/dispatch/returns?peek=1" : "/v1/dispatch/returns", { ...(origin ? { origin } : {}) });
43
+ return Array.isArray(answer.returns) ? answer.returns : [];
44
+ };
45
+ // `returns --json` is `returns`, whose answer is JSON already.
46
+ if (!args.includes("--watch")) {
47
+ console.log(JSON.stringify({ returns: await read() }, null, 2));
48
+ return 0;
49
+ }
50
+ const { watchReturns } = await import("./dispatch-returns.js");
51
+ const stop = new AbortController();
52
+ // The first Ctrl-C ends the watch after the read in flight (which still prints; with --consume its
53
+ // returns are already marked read); a second one leaves at once.
54
+ process.on("SIGINT", () => { if (stop.signal.aborted)
55
+ process.exit(130); stop.abort(); });
56
+ await watchReturns(read, line => console.log(line), { signal: stop.signal, json: args.includes("--json"), warn: line => console.error(line) });
57
+ return 130;
58
+ }
37
59
  if (args[0] === "usage" && args.slice(1).every(arg => arg === "--json")) {
38
60
  const { readAccountUsage, formatAccountUsage } = await import("./account-usage.js");
39
61
  const view = await readAccountUsage();
@@ -204,6 +204,29 @@ export declare function observe(receipt: Receipt, value: unknown, now: number, p
204
204
  export declare function noticeLine(receipts: readonly Receipt[]): string;
205
205
  /** What `dispatch_returns` lists for one unread return. */
206
206
  export declare function returnRow(receipt: Receipt): Json;
207
+ /** How much of a worker's final reply a watched return line shows. */
208
+ export declare const RETURN_LINE_TAIL = 120;
209
+ /**
210
+ * One return as a terminal line for `phren dispatch returns --watch`: when it landed (local time), the
211
+ * dispatch label, the computer, the state, and a short tail of what it ended with (the final reply, the
212
+ * question it asks, or why it failed or is blocked), on one line.
213
+ */
214
+ export declare function formatReturnLine(row: Json, timeZone?: string): string;
215
+ /**
216
+ * `phren dispatch returns --watch`: the returns this Hook's DispatchReturns has collected, printed as they
217
+ * land, until `signal` aborts. `read` peeks by default (the unread returns, left unread for an agent
218
+ * conductor), so each return is printed once by its id and version (a worker that returns again after
219
+ * more work is printed again); with `--consume` it takes them as `returns` does. Peers are polled by the
220
+ * Hook alone. `json` prints each return as one JSON object per line. A read that fails is said on `warn`
221
+ * once, until a read works again.
222
+ */
223
+ export declare function watchReturns(read: () => Promise<Json[]>, print: (line: string) => void, options: {
224
+ signal: AbortSignal;
225
+ json?: boolean;
226
+ intervalMs?: number;
227
+ timeZone?: string;
228
+ warn?: (line: string) => void;
229
+ }): Promise<void>;
207
230
  export interface DispatchReturnsOptions {
208
231
  /** This Hook's stable identity, for a worker moving back home. */
209
232
  localComputer?: {
@@ -4,6 +4,7 @@ import { prsSchema } from "./return-contract.js";
4
4
  import { sessionStalls } from "./stalls.js";
5
5
  import { execFile } from "node:child_process";
6
6
  import { createHash } from "node:crypto";
7
+ import { setTimeout as sleep } from "node:timers/promises";
7
8
  import { promisify } from "node:util";
8
9
  import { z } from "zod";
9
10
  import { logger } from "../logger.js";
@@ -546,6 +547,62 @@ export function returnRow(receipt) {
546
547
  ...(receipt.continued ? { continued: receipt.continued } : {}), ...(receipt.continues ? { continues: receipt.continues } : {}),
547
548
  ...(receipt.moves ? { moves: receipt.moves } : {}), ...(receipt.target ? { target: receipt.target } : {}) };
548
549
  }
550
+ /** How much of a worker's final reply a watched return line shows. */
551
+ export const RETURN_LINE_TAIL = 120;
552
+ /**
553
+ * One return as a terminal line for `phren dispatch returns --watch`: when it landed (local time), the
554
+ * dispatch label, the computer, the state, and a short tail of what it ended with (the final reply, the
555
+ * question it asks, or why it failed or is blocked), on one line.
556
+ */
557
+ export function formatReturnLine(row, timeZone) {
558
+ const at = typeof row.at === "string" && Number.isFinite(Date.parse(row.at))
559
+ ? new Date(row.at).toLocaleTimeString("en-GB", { hour12: false, ...(timeZone ? { timeZone } : {}) }) : "--:--:--";
560
+ const approval = row.approval && typeof row.approval === "object" ? row.approval : undefined;
561
+ const said = [row.question, row.error, approval ? `waiting on ${String(approval.title ?? approval.tool ?? "an approval")}` : undefined, row.reply]
562
+ .find((value) => typeof value === "string" && value.trim() !== "");
563
+ // A worker's words reach the owner's terminal: no escape sequences (a title, the clipboard, the cursor).
564
+ const flat = (said ?? "").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim();
565
+ // Whole characters, so a cut never splits one.
566
+ const chars = Array.from(flat);
567
+ const tail = chars.length > RETURN_LINE_TAIL ? `…${chars.slice(-(RETURN_LINE_TAIL - 1)).join("")}` : flat;
568
+ return [at, String(row.label ?? row.id ?? "worker"), String(row.computer ?? "?"), String(row.state ?? "?")].join(" ") + (tail ? ` ${tail}` : "");
569
+ }
570
+ /**
571
+ * `phren dispatch returns --watch`: the returns this Hook's DispatchReturns has collected, printed as they
572
+ * land, until `signal` aborts. `read` peeks by default (the unread returns, left unread for an agent
573
+ * conductor), so each return is printed once by its id and version (a worker that returns again after
574
+ * more work is printed again); with `--consume` it takes them as `returns` does. Peers are polled by the
575
+ * Hook alone. `json` prints each return as one JSON object per line. A read that fails is said on `warn`
576
+ * once, until a read works again.
577
+ */
578
+ export async function watchReturns(read, print, options) {
579
+ const interval = options.intervalMs ?? 5_000;
580
+ let failing;
581
+ // The returns already printed that are still unread; one taken by the conductor drops out with its read.
582
+ let printed = new Set();
583
+ const key = (row) => `${String(row.id)}@${String(row.at)}`;
584
+ while (!options.signal.aborted) {
585
+ try {
586
+ const rows = await read();
587
+ if (failing !== undefined) {
588
+ options.warn?.("Phren Hook answers again.");
589
+ failing = undefined;
590
+ }
591
+ for (const row of rows)
592
+ if (!printed.has(key(row)))
593
+ print(options.json ? JSON.stringify(row) : formatReturnLine(row, options.timeZone));
594
+ printed = new Set(rows.map(key));
595
+ }
596
+ catch (error) {
597
+ // A Hook that is restarting answers again on a later read; its first sentence is enough.
598
+ const why = (error instanceof Error ? error.message : String(error)).split(/(?<=\.)\s/)[0];
599
+ if (why !== failing)
600
+ options.warn?.(`Phren Hook did not answer: ${why}`);
601
+ failing = why;
602
+ }
603
+ await sleep(interval, undefined, { signal: options.signal }).catch(() => undefined);
604
+ }
605
+ }
549
606
  const originKey = (origin) => JSON.stringify([origin.server, origin.workspace, origin.tab, origin.pane, origin.terminal]);
550
607
  /** The same returns to the same origin keep their id on retry. A role
551
608
  * hand-over gets a fresh delivery instead of reusing the old chat's receipt. */
@@ -3,7 +3,8 @@ import { type ConductorRecord } from "./conductor-role.js";
3
3
  import { type DispatchHost } from "./dispatch-hosts.js";
4
4
  import { type Json, type Provider, type Target } from "./protocol.js";
5
5
  import { type HarnessInventory } from "./harnesses.js";
6
- import type { AccountRoom, WindowRoom } from "./account-choice.js";
6
+ import { type AccountRoom, type WindowRoom } from "./account-choice.js";
7
+ import { type PolicyRoom, type PoolRule } from "./account-policy.js";
7
8
  import { type BriefArrival } from "./launch-brief.js";
8
9
  export declare const projectName: z.ZodString;
9
10
  /** The harnesses a dispatch, a code note's hand-off or a schedule can start. */
@@ -457,8 +458,23 @@ export declare function outOfQuota(data: {
457
458
  harness: string;
458
459
  account?: string;
459
460
  }, usage: readonly Room[] | undefined, now?: number): string | undefined;
460
- /** A computer's signed-in Claude accounts with their room, from its capacity probe. */
461
- export declare function capacityClaudeRooms(harnesses: HarnessInventory["harnesses"] | undefined, usage: readonly Room[] | undefined): AccountRoom[];
461
+ /** A computer's signed-in Claude accounts with their room, pool and role, from its capacity probe. */
462
+ export declare function capacityClaudeRooms(harnesses: HarnessInventory["harnesses"] | undefined, usage: readonly Room[] | undefined): PolicyRoom[];
463
+ /**
464
+ * The Claude account a dispatch runs under on `computer` once pools and roles apply (account-policy.ts):
465
+ * `account` (and why) to name in the launch, or `refused` with why. Undefined leaves the choice to that
466
+ * computer's launch as before: not Claude, nothing reported, or no pool, role or API login in play.
467
+ * A named account is only checked against the pools; roles bind automatic choices only.
468
+ */
469
+ export declare function policyAccount(data: {
470
+ harness: string;
471
+ account?: string;
472
+ }, harnesses: HarnessInventory["harnesses"] | undefined, usage: readonly Room[] | undefined, computer: string, project: PoolRule, blocked?: (room: AccountRoom) => string | undefined): {
473
+ account?: string;
474
+ reason?: string;
475
+ refused?: string;
476
+ lastResort?: true;
477
+ } | undefined;
462
478
  /** What the worker's own hooks reported for a brief that went with its
463
479
  * launch, or undefined when the receiving Hook has no such brief. */
464
480
  export declare function arrivalOf(peer: Pick<DispatchHost, "request">, id: string): Promise<BriefArrival | undefined>;
@@ -518,7 +534,13 @@ export declare class DispatchService {
518
534
  private confirmLaunched;
519
535
  /** Every connected computer's signed-in Claude accounts and their room, this computer first:
520
536
  * where a worker that hit its usage limit can continue (account-failover.ts). */
521
- claudeRooms(): Promise<Array<{
537
+ claudeRooms(context?: {
538
+ project: string;
539
+ stopped: {
540
+ computer: string;
541
+ account: string;
542
+ };
543
+ }): Promise<Array<{
522
544
  computer: string;
523
545
  local: boolean;
524
546
  rooms: AccountRoom[];
@@ -22,6 +22,8 @@ import { object, atomic, BridgeError, bridgeRoot, id, launchEfforts, PERMISSION_
22
22
  import { phrenStoreRoot } from "./transcripts.js";
23
23
  import { isAccountSlug } from "./claude-accounts.js";
24
24
  import { hasUsable } from "./harnesses.js";
25
+ import { limitedBy, limitKey, readAccountLimits } from "./account-choice.js";
26
+ import { allowedRooms, choosePolicyAccount, computerRule, openRoom, policyApplies, poolRefusal, projectRule, withPolicy } from "./account-policy.js";
25
27
  import { arrivalSchema } from "./launch-brief.js";
26
28
  const text = (max) => z.string().min(1).max(max).refine(value => !!value.trim() && !/[\x00-\x1f\x7f]/.test(value));
27
29
  export const projectName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/);
@@ -348,16 +350,46 @@ export function outOfQuota(data, usage, now = Date.now()) {
348
350
  return undefined;
349
351
  return `Its ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} has no quota left${backIn(room.until, now)}.`;
350
352
  }
351
- /** A computer's signed-in Claude accounts with their room, from its capacity probe. */
353
+ /** A computer's signed-in Claude accounts with their room, pool and role, from its capacity probe. */
352
354
  export function capacityClaudeRooms(harnesses, usage) {
353
355
  const accounts = harnesses?.find(entry => entry.source === "claude")?.accounts ?? [];
354
356
  return accounts.map(account => {
355
357
  const room = usage?.find(item => item.source === "claude" && (item.account ?? "default") === account.id);
356
- return { account: account.id, ...(account.key ? { key: account.key } : {}), usable: account.usable,
358
+ return withPolicy({ account: account.id, ...(account.key ? { key: account.key } : {}), usable: account.usable,
357
359
  ...(room?.fiveHour ? { fiveHour: room.fiveHour } : {}), ...(room?.week ? { week: room.week } : {}),
358
- ...(room?.exhausted ? { exhausted: true, ...(room.until ? { until: room.until } : {}) } : {}) };
360
+ ...(room?.exhausted ? { exhausted: true, ...(room.until ? { until: room.until } : {}) } : {}) }, account);
359
361
  });
360
362
  }
363
+ /**
364
+ * The Claude account a dispatch runs under on `computer` once pools and roles apply (account-policy.ts):
365
+ * `account` (and why) to name in the launch, or `refused` with why. Undefined leaves the choice to that
366
+ * computer's launch as before: not Claude, nothing reported, or no pool, role or API login in play.
367
+ * A named account is only checked against the pools; roles bind automatic choices only.
368
+ */
369
+ export function policyAccount(data, harnesses, usage, computer, project, blocked) {
370
+ if (data.harness !== "claude")
371
+ return undefined;
372
+ // Accounts not reported (a slow read, launch checks off): with the project's pools set they can't be checked.
373
+ if (!harnesses)
374
+ return project.pools ? { refused: `Its Hook did not report its Claude accounts, so ${project.owner}'s allowed pools can't be checked.` } : undefined;
375
+ const rules = [project, claudeComputerRule(computer, harnesses)];
376
+ const rooms = capacityClaudeRooms(harnesses, usage);
377
+ if (data.account) {
378
+ const room = rooms.find(item => item.account === data.account);
379
+ const why = room && poolRefusal(room, rules);
380
+ return why ? { refused: `Claude account ${data.account} may not do this work: ${why}.` } : undefined;
381
+ }
382
+ if (!policyApplies(rooms, rules))
383
+ return undefined;
384
+ const { choice, skipped, lastResort } = choosePolicyAccount(rooms, rules, blocked);
385
+ return choice ? { account: choice.account, reason: choice.reason, ...(lastResort ? { lastResort } : {}) }
386
+ : { refused: `No Claude account there may do this work${skipped.length ? `: ${skipped.join("; ")}` : ""}.`.slice(0, 500) };
387
+ }
388
+ /** A computer's own pool rule from its Claude listing entry. */
389
+ function claudeComputerRule(computer, harnesses) {
390
+ const entry = harnesses?.find(item => item.source === "claude");
391
+ return computerRule(computer, entry?.allowedPools, entry?.poolsUnreadable === true);
392
+ }
361
393
  /** Why a computer cannot run this dispatch's harness and account, or undefined when it can or cannot yet be told.
362
394
  * `unknown` (no `harnesses`) only counts against a computer when a non-default account was asked for. */
363
395
  function unusable(data, harnesses, strictUnknown) {
@@ -604,6 +636,16 @@ export class DispatchService {
604
636
  let remoteComputerID;
605
637
  const skipped = [];
606
638
  let incapable = false, spentSeen = false;
639
+ const pooledOut = [];
640
+ // Pools and roles (account-policy.ts): which Claude account may run this on each computer.
641
+ const projectPools = projectRule(phrenStoreRoot(), data.project);
642
+ const limits = data.harness === "claude" ? await readAccountLimits() : [];
643
+ const pooled = new Map();
644
+ const poolCheck = (host, reported) => {
645
+ const result = policyAccount(data, reported.harnesses, reported.usage, host.name, projectPools, limitedBy(limits, host.name));
646
+ pooled.set(host.name, result);
647
+ return result?.refused;
648
+ };
607
649
  if (data.computer === "anywhere") {
608
650
  const available = await Promise.all(peers.map(async (candidate) => {
609
651
  try {
@@ -633,14 +675,26 @@ export class DispatchService {
633
675
  if (spent) {
634
676
  spentSeen = true;
635
677
  skipped.push({ computer: item.peer.name, reason: spent });
678
+ return false;
679
+ }
680
+ const refused = poolCheck(item.peer, item);
681
+ if (refused) {
682
+ pooledOut.push(item.peer.name);
683
+ skipped.push({ computer: item.peer.name, reason: refused.slice(0, 200) });
636
684
  }
637
- return !spent;
685
+ return !refused;
638
686
  });
639
687
  skipped.sort((a, b) => a.computer.localeCompare(b.computer));
688
+ // A computer that could only use a last-resort account comes after every computer with another account that fits.
689
+ const lastResort = (name) => Number(pooled.get(name)?.lastResort === true);
640
690
  const selected = capable
641
- .sort((a, b) => a.working + this.inFlight(a.peer.name) - b.working - this.inFlight(b.peer.name) || a.peer.name.localeCompare(b.peer.name))[0];
691
+ .sort((a, b) => lastResort(a.peer.name) - lastResort(b.peer.name)
692
+ || a.working + this.inFlight(a.peer.name) - b.working - this.inFlight(b.peer.name) || a.peer.name.localeCompare(b.peer.name))[0];
642
693
  peer = selected?.peer;
643
694
  remoteComputerID = selected?.computerId;
695
+ // Pools ruled some computers out: say so whatever ruled out the rest, with each computer's reason in `skipped`.
696
+ if (!peer && pooledOut.length)
697
+ throw new BridgeError(409, `No connected computer has a Claude account that may do this work: pools and roles rule out ${pooledOut.join(", ")}${spentSeen || incapable ? ", and the others are out of quota or can't run it" : ""}.`.slice(0, 500), { code: "account_pool", skipped });
644
698
  if (!peer && spentSeen)
645
699
  throw new BridgeError(503, `No connected computer has ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} quota left right now.`, { code: "out_of_quota", skipped });
646
700
  if (!peer)
@@ -659,7 +713,12 @@ export class DispatchService {
659
713
  const reason = unusable(data, reported.harnesses, true);
660
714
  if (reason)
661
715
  throw new BridgeError(409, `${peer.name} cannot run ${data.harness}${data.account ? ` account ${data.account}` : ""}: ${reason}`);
716
+ const refused = poolCheck(peer, reported);
717
+ if (refused)
718
+ throw new BridgeError(409, `${peer.name}: ${refused}`, { code: "account_pool" });
662
719
  }
720
+ // Chosen here by pools and roles, the account goes in the launch; otherwise that computer picks, as before.
721
+ const policyChoice = data.account ? undefined : pooled.get(peer.name);
663
722
  const grant = await findGrant({ action: "dispatch", project: data.project, computer: peer.name });
664
723
  // An agent (a call that names its pane) may start a worker only up to its grant's
665
724
  // permission ceiling; the owner, calling from the phone or the CLI without a pane, is not capped.
@@ -686,12 +745,18 @@ export class DispatchService {
686
745
  try {
687
746
  // The brief goes with the launch: a Hook that can start the harness
688
747
  // with it says so, and any other types it below.
689
- const launched = await peer.request(`/v1/workspaces/launch?server=${encodeURIComponent(peer.server)}`, { project: data.project, kind: data.harness, model: data.model, ...(data.effort ? { effort: data.effort } : {}), ...(data.account ? { account: data.account } : {}), ...(data.permissionMode ? { permissionMode: data.permissionMode } : {}), label: peer.local ? data.label : redactPeerHandoff(data.label), brief: { id: receipt.id, text: prompt } });
748
+ const launched = await peer.request(`/v1/workspaces/launch?server=${encodeURIComponent(peer.server)}`, { project: data.project, kind: data.harness, model: data.model, ...(data.effort ? { effort: data.effort } : {}), ...(data.account ?? policyChoice?.account ? { account: data.account ?? policyChoice.account } : {}), ...(data.permissionMode ? { permissionMode: data.permissionMode } : {}), label: peer.local ? data.label : redactPeerHandoff(data.label), brief: { id: receipt.id, text: prompt } });
690
749
  // Placed: the brief is confirmed outside the lock.
691
750
  placed = peer.name;
692
751
  this.placing.set(placed, this.inFlight(placed) + 1);
693
- // The receiving Hook chose the Claude account (the one with the most room) when none was named.
694
- if (!data.account && typeof launched.account === "string" && isAccountSlug(launched.account)) {
752
+ if (policyChoice?.account) {
753
+ receipt.account = policyChoice.account;
754
+ if (policyChoice.reason)
755
+ receipt.accountChoice = policyChoice.reason.slice(0, 400);
756
+ logger.info("dispatch", `${receipt.label} on ${peer.name} runs under Claude account ${policyChoice.account}: ${receipt.accountChoice ?? "pools and roles"}.`);
757
+ // The receiving Hook chose the Claude account (the one with the most room) when none was named.
758
+ }
759
+ else if (!data.account && typeof launched.account === "string" && isAccountSlug(launched.account)) {
695
760
  receipt.account = launched.account;
696
761
  if (typeof launched.accountChoice === "string")
697
762
  receipt.accountChoice = launched.accountChoice.slice(0, 400);
@@ -911,19 +976,43 @@ export class DispatchService {
911
976
  }
912
977
  /** Every connected computer's signed-in Claude accounts and their room, this computer first:
913
978
  * where a worker that hit its usage limit can continue (account-failover.ts). */
914
- async claudeRooms() {
979
+ async claudeRooms(context) {
915
980
  const here = this.local();
916
981
  const hosts = [here, ...(await hookPeers().catch(() => [])).map(candidate => peerHost(candidate))];
982
+ const project = context ? projectRule(phrenStoreRoot(), context.project) : undefined;
917
983
  const found = await Promise.all(hosts.map(async (host) => {
918
984
  try {
919
985
  const reported = await capacity(host);
920
- return { computer: host.name, local: host.local, rooms: capacityClaudeRooms(reported.harnesses, reported.usage) };
986
+ const rooms = capacityClaudeRooms(reported.harnesses, reported.usage);
987
+ // Accounts not reported can't be checked against the project's pools: none of them is offered.
988
+ if (!reported.harnesses && project?.pools)
989
+ return { computer: host.name, local: host.local, rooms: [], all: rooms };
990
+ // Only accounts an automatic choice may take there, under the project's and that computer's pools.
991
+ const rules = [...(project ? [project] : []), claudeComputerRule(host.name, reported.harnesses)];
992
+ return { computer: host.name, local: host.local, rooms: allowedRooms(rooms, rules), all: rooms };
921
993
  }
922
994
  catch {
923
995
  return undefined;
924
996
  }
925
997
  }));
926
- return found.filter((item) => !!item);
998
+ const listed = found.filter((item) => !!item);
999
+ // Last-resort accounts only when no other allowed account anywhere has room: the stopped login and any the
1000
+ // limits ledger holds back have none.
1001
+ const limits = await readAccountLimits();
1002
+ // The stopped login by its key, so the same login signed in on another computer has no room either.
1003
+ const stoppedRoom = context ? listed.find(item => item.computer === context.stopped.computer)?.all.find(room => room.account === context.stopped.account) : undefined;
1004
+ const stoppedKey = context ? limitKey(stoppedRoom ?? { account: context.stopped.account }, context.stopped.computer) : undefined;
1005
+ const held = (computer) => {
1006
+ const blocked = limitedBy(limits, computer);
1007
+ return (room) => !!blocked(room) || limitKey(room, computer) === stoppedKey;
1008
+ };
1009
+ const other = listed.some(item => item.rooms.some(room => room.role !== "last-resort" && openRoom(room, held(item.computer))));
1010
+ // The stopped login stays listed (unchosen, it is held back) so the failover can find its room and reset time.
1011
+ return listed.map(({ all, ...item }) => {
1012
+ const rooms = other ? item.rooms.filter(room => room.role !== "last-resort") : item.rooms;
1013
+ const stopped = context?.stopped.computer === item.computer ? all.find(room => room.account === context.stopped.account) : undefined;
1014
+ return { ...item, rooms: stopped && !rooms.includes(stopped) ? [...rooms, stopped] : rooms };
1015
+ });
927
1016
  }
928
1017
  /** The query a conductor's dispatch sends with each capacity probe; undefined for any other caller. */
929
1018
  async conductorCaller(value) {
@@ -205,7 +205,8 @@ export const gitlab = {
205
205
  // GitLab merges, or rebases, by the project's own merge method; squash is per request.
206
206
  const { json } = await call(ctx, `/merge_requests/${request.number}/merge`, { method: "PUT", body: {
207
207
  squash: request.method === "squash", ...(request.expectedHeadSha ? { sha: request.expectedHeadSha } : {}),
208
- ...(request.deleteBranch ? { should_remove_source_branch: true } : {})
208
+ // Sent either way when asked: the merge request was opened with remove_source_branch, so false must be said.
209
+ ...(request.deleteBranch !== undefined ? { should_remove_source_branch: request.deleteBranch } : {})
209
210
  } });
210
211
  const mr = obj(json);
211
212
  return { ok: true, number: request.number, method: request.method, state: upper(mr.state), ...(safeLink(mr.web_url) ? { url: safeLink(mr.web_url) } : {}) };
@@ -34,6 +34,52 @@ export declare const queuedHandOffSchema: z.ZodObject<{
34
34
  }, z.core.$strip>>;
35
35
  originComputer: z.ZodOptional<z.ZodString>;
36
36
  }, z.core.$strict>;
37
+ declare const rowSchema: z.ZodObject<{
38
+ target: z.ZodObject<{
39
+ server: z.ZodString;
40
+ workspace: z.ZodString;
41
+ tab: z.ZodString;
42
+ pane: z.ZodString;
43
+ source: z.ZodEnum<{
44
+ claude: "claude";
45
+ codex: "codex";
46
+ copilot: "copilot";
47
+ opencode: "opencode";
48
+ phren: "phren";
49
+ }>;
50
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
51
+ }, z.core.$strip>;
52
+ text: z.ZodString;
53
+ origin: z.ZodOptional<z.ZodObject<{
54
+ server: z.ZodString;
55
+ workspace: z.ZodString;
56
+ tab: z.ZodString;
57
+ pane: z.ZodString;
58
+ source: z.ZodEnum<{
59
+ claude: "claude";
60
+ codex: "codex";
61
+ copilot: "copilot";
62
+ opencode: "opencode";
63
+ phren: "phren";
64
+ }>;
65
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
66
+ }, z.core.$strip>>;
67
+ originComputer: z.ZodOptional<z.ZodString>;
68
+ deliveryId: z.ZodString;
69
+ terminal: z.ZodString;
70
+ state: z.ZodEnum<{
71
+ attempting: "attempting";
72
+ delivered: "delivered";
73
+ failed: "failed";
74
+ queued: "queued";
75
+ uncertain: "uncertain";
76
+ }>;
77
+ createdAt: z.ZodString;
78
+ updatedAt: z.ZodString;
79
+ error: z.ZodOptional<z.ZodString>;
80
+ notified: z.ZodOptional<z.ZodBoolean>;
81
+ }, z.core.$strict>;
82
+ type Row = z.infer<typeof rowSchema>;
37
83
  export interface QueueOptions {
38
84
  validate: (target: Target) => Promise<Json>;
39
85
  send: (target: Target, text: string, deliveryId: string, typing: () => Promise<void>) => Promise<Json>;
@@ -97,6 +143,30 @@ export declare class HandOffQueue {
97
143
  private prune;
98
144
  private reply;
99
145
  enqueue(input: unknown): Promise<Json>;
146
+ /**
147
+ * Runs `action` only while the message `id` for `target` has not been typed: its row is still queued,
148
+ * or not made yet. Under the queue's lock, so a sweep cannot type it between the check and the action
149
+ * (a move's "stop and hand off now" sends Escape this way: before the request is typed, never into the
150
+ * hand-off it asked for). Otherwise answers the row's state. `action` gets the row (when made): the
151
+ * terminal it was queued for, and the conversation it is for now (it follows one that replaced the first
152
+ * in the same terminal).
153
+ */
154
+ whileQueued(id: string, target: Target, action: (row?: {
155
+ terminal: string;
156
+ session?: string;
157
+ }) => Promise<void>): Promise<{
158
+ ran: true;
159
+ } | {
160
+ ran: false;
161
+ state: Row["state"];
162
+ }>;
163
+ /**
164
+ * Takes back the message `id` for `target` while it is still queued, never typed: its row fails with
165
+ * `reason`, and no sweep types it later (a move whose hand-off wait ended no longer wants its request in the
166
+ * old agent). Answers the row's state after: `failed` once withdrawn, else what it already came to
167
+ * (`delivered`: the agent took it), or undefined when there is no such row.
168
+ */
169
+ withdraw(id: string, target: Target, reason: string): Promise<Row["state"] | undefined>;
100
170
  status(id: string, target: Target): Promise<Json>;
101
171
  /** Validates the row's target. When the pane's conversation was replaced
102
172
  * in the same terminal (a Codex thread change, a Claude /clear), the row
@@ -115,3 +185,4 @@ export declare class HandOffQueue {
115
185
  whenNoPending(target: Target, close: () => Promise<Json>): Promise<Json>;
116
186
  hasPending(target: Target): Promise<boolean>;
117
187
  }
188
+ export {};
@@ -170,6 +170,44 @@ export class HandOffQueue {
170
170
  return this.reply(row);
171
171
  });
172
172
  }
173
+ /**
174
+ * Runs `action` only while the message `id` for `target` has not been typed: its row is still queued,
175
+ * or not made yet. Under the queue's lock, so a sweep cannot type it between the check and the action
176
+ * (a move's "stop and hand off now" sends Escape this way: before the request is typed, never into the
177
+ * hand-off it asked for). Otherwise answers the row's state. `action` gets the row (when made): the
178
+ * terminal it was queued for, and the conversation it is for now (it follows one that replaced the first
179
+ * in the same terminal).
180
+ */
181
+ whileQueued(id, target, action) {
182
+ return this.serial(async () => {
183
+ const row = await this.read(id);
184
+ if (row && !samePane(row.target, target))
185
+ throw new BridgeError(404, "No hand-off with this id and target.");
186
+ if (row && row.state !== "queued")
187
+ return { ran: false, state: row.state };
188
+ await action(row ? { terminal: row.terminal, ...(row.target.session ? { session: row.target.session } : {}) } : undefined);
189
+ return { ran: true };
190
+ });
191
+ }
192
+ /**
193
+ * Takes back the message `id` for `target` while it is still queued, never typed: its row fails with
194
+ * `reason`, and no sweep types it later (a move whose hand-off wait ended no longer wants its request in the
195
+ * old agent). Answers the row's state after: `failed` once withdrawn, else what it already came to
196
+ * (`delivered`: the agent took it), or undefined when there is no such row.
197
+ */
198
+ withdraw(id, target, reason) {
199
+ return this.serial(async () => {
200
+ const row = await this.read(id);
201
+ if (!row || !samePane(row.target, target))
202
+ return undefined;
203
+ if (row.state === "queued") {
204
+ row.state = "failed";
205
+ row.error = reason.slice(0, 500);
206
+ await this.save(row);
207
+ }
208
+ return row.state;
209
+ });
210
+ }
173
211
  status(id, target) {
174
212
  return this.serial(async () => { const row = await this.read(id); if (!row || !samePane(row.target, target))
175
213
  throw new BridgeError(404, "No hand-off with this id and target."); return this.reply(row); });
@@ -1,11 +1,18 @@
1
1
  import { type AccountRef, type AuthRunner } from "./claude-accounts.js";
2
2
  import { type ToolVersion } from "./health.js";
3
+ import { type AccountRole } from "./account-pools.js";
3
4
  export type HarnessSource = "claude" | "codex" | "opencode" | "copilot" | "phren";
4
5
  export interface HarnessAccount extends AccountRef {
5
6
  signedIn: boolean;
6
7
  usable: boolean;
7
8
  plan?: string;
8
9
  reason?: string;
10
+ signInAvailable?: boolean;
11
+ /** The account's pool and role, when the owner set them (account-pools.ts). */
12
+ pool?: string;
13
+ role?: AccountRole;
14
+ /** Signed in with a Console (API billing) login: with no role it is never chosen automatically. */
15
+ console?: true;
9
16
  }
10
17
  export interface HarnessEntry {
11
18
  source: HarnessSource;
@@ -14,9 +21,14 @@ export interface HarnessEntry {
14
21
  usable: boolean;
15
22
  reason?: string;
16
23
  accounts?: HarnessAccount[];
24
+ /** Claude's entry: this computer's allowed pools, as on the inventory, or that accounts.yaml can't be read. */
25
+ allowedPools?: string[];
26
+ poolsUnreadable?: true;
17
27
  }
28
+ /** `allowedPools`: the pools this computer's accounts may do work for, when the owner set them; none means any. */
18
29
  export interface HarnessInventory {
19
30
  harnesses: HarnessEntry[];
31
+ allowedPools?: string[];
20
32
  }
21
33
  export interface HarnessDeps {
22
34
  toolVersion?: (tool: string) => Promise<ToolVersion>;
@@ -6,6 +6,7 @@ import path from "node:path";
6
6
  import { codexHome } from "../home-paths.js";
7
7
  import { claudeAccountRef, claudeAuthStatus, claudeHomes, CODEX_ACCOUNT } from "./claude-accounts.js";
8
8
  import { toolVersion } from "./health.js";
9
+ import { accountPolicy, accountSettings, computerAllowedPools } from "./account-pools.js";
9
10
  const SOURCES = ["claude", "codex", "opencode", "copilot", "phren"];
10
11
  /** The binary is `phren`; the agent answers `phren agent --version` from the separate @phren/agent package. */
11
12
  const probeSource = (source) => source === "phren" ? toolVersion("phren agent", "phren", ["agent"]) : toolVersion(source);
@@ -23,15 +24,29 @@ export async function harnessInventory(deps = {}) {
23
24
  }
24
25
  const base = { source, installed: true, ...(found.version ? { version: found.version } : {}) };
25
26
  if (source === "claude") {
27
+ const settings = accountSettings();
26
28
  const accounts = await Promise.all(claudeHomes(env).map(async (home) => {
27
29
  const auth = await claudeAuthStatus(home, deps.authRunner);
28
30
  // An unanswered sign-in check stays usable: only Claude saying "logged out" hides an account.
29
31
  const usable = auth.signedIn || auth.unknown === true;
30
- return { ...claudeAccountRef(home), signedIn: auth.signedIn, usable,
31
- ...(auth.plan ? { plan: auth.plan } : {}), ...(auth.signedIn ? {} : { reason: auth.reason ?? "Not signed in" }) };
32
+ return { ...claudeAccountRef(home), ...settings[home.id], signedIn: auth.signedIn, usable,
33
+ ...(auth.plan ? { plan: auth.plan } : {}), ...(auth.console ? { console: true } : {}), ...(auth.signedIn ? {} : { reason: auth.reason ?? "Not signed in" }),
34
+ // Claude said it is signed out: the phone offers Sign in (POST /v1/accounts/claude/add {slug, mode: "sign-in"}).
35
+ ...(!auth.signedIn && !auth.unknown ? { signInAvailable: true } : {}) };
32
36
  }));
33
37
  const usable = accounts.some(account => account.usable);
34
- return { ...base, usable, ...(usable ? {} : { reason: "No signed-in Claude account" }), accounts };
38
+ // On the entry too, so a dispatch's capacity probe (which carries only the entries) knows this computer's pools,
39
+ // and that they can't be known when accounts.yaml can't be read (an automatic choice then takes no account here).
40
+ const allowedPools = computerAllowedPools();
41
+ let poolsUnreadable = false;
42
+ try {
43
+ accountPolicy();
44
+ }
45
+ catch {
46
+ poolsUnreadable = true;
47
+ }
48
+ return { ...base, usable, ...(usable ? {} : { reason: "No signed-in Claude account" }), accounts, ...(allowedPools ? { allowedPools } : {}),
49
+ ...(poolsUnreadable ? { poolsUnreadable: true } : {}) };
35
50
  }
36
51
  if (source === "codex") {
37
52
  const signedIn = existsSync(path.join(codexHome(env), "auth.json"));
@@ -40,7 +55,8 @@ export async function harnessInventory(deps = {}) {
40
55
  }
41
56
  return { ...base, usable: true };
42
57
  }));
43
- return { harnesses };
58
+ const allowedPools = computerAllowedPools();
59
+ return { harnesses, ...(allowedPools ? { allowedPools } : {}) };
44
60
  }
45
61
  /** The inventory, or undefined when it is not ready within `ms` (a cold `claude auth status` can take seconds). */
46
62
  export function harnessInventoryWithin(ms, deps = {}) {