@phren/cli 0.3.57 → 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 (83) 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/computer-identity.d.ts +4 -2
  26. package/dist/bridge/computer-identity.js +7 -3
  27. package/dist/bridge/conductor-group.d.ts +1 -1
  28. package/dist/bridge/conductor-group.js +2 -2
  29. package/dist/bridge/conductor-sets.d.ts +6 -0
  30. package/dist/bridge/conductor-sets.js +8 -2
  31. package/dist/bridge/dispatch-command.js +22 -0
  32. package/dist/bridge/dispatch-returns.d.ts +23 -0
  33. package/dist/bridge/dispatch-returns.js +57 -0
  34. package/dist/bridge/dispatch.d.ts +26 -4
  35. package/dist/bridge/dispatch.js +100 -11
  36. package/dist/bridge/git-host-gitlab.js +2 -1
  37. package/dist/bridge/hand-off-queue.d.ts +71 -0
  38. package/dist/bridge/hand-off-queue.js +38 -0
  39. package/dist/bridge/harnesses.d.ts +12 -0
  40. package/dist/bridge/harnesses.js +20 -4
  41. package/dist/bridge/helper.d.ts +54 -0
  42. package/dist/bridge/helper.js +186 -0
  43. package/dist/bridge/herdr.js +6 -2
  44. package/dist/bridge/hook-fast.d.ts +3 -0
  45. package/dist/bridge/hook-fast.js +10 -2
  46. package/dist/bridge/move-computers.d.ts +15 -1
  47. package/dist/bridge/move-computers.js +123 -26
  48. package/dist/bridge/prompt-deliveries.d.ts +29 -1
  49. package/dist/bridge/prompt-deliveries.js +146 -10
  50. package/dist/bridge/schedule-watch.js +17 -3
  51. package/dist/bridge/server-routes.d.ts +4 -0
  52. package/dist/bridge/server-routes.js +66 -6
  53. package/dist/bridge/server.js +8 -2
  54. package/dist/bridge/session-move.d.ts +59 -1
  55. package/dist/bridge/session-move.js +266 -18
  56. package/dist/bridge/simulator-stream.d.ts +118 -0
  57. package/dist/bridge/simulator-stream.js +284 -0
  58. package/dist/bridge/simulators.d.ts +31 -0
  59. package/dist/bridge/simulators.js +126 -40
  60. package/dist/bridge/speech-live.js +132 -22
  61. package/dist/bridge/task-routes.d.ts +16 -16
  62. package/dist/bridge/terminal-herdr.js +6 -1
  63. package/dist/bridge/terminal-tmux.js +9 -5
  64. package/dist/bridge/terminal.d.ts +9 -2
  65. package/dist/bridge/transcript-claude.d.ts +3 -0
  66. package/dist/bridge/transcript-claude.js +175 -29
  67. package/dist/bridge/transcript-preview.d.ts +11 -2
  68. package/dist/bridge/transcript-preview.js +90 -8
  69. package/dist/bridge/turn-records.d.ts +19 -0
  70. package/dist/bridge/turn-records.js +78 -3
  71. package/dist/bridge-hook.mjs +12129 -10324
  72. package/dist/cli-registry.js +2 -2
  73. package/dist/content/citation.d.ts +4 -0
  74. package/dist/content/citation.js +21 -21
  75. package/dist/data/task-contract.d.ts +4 -4
  76. package/dist/governance/policy.js +5 -2
  77. package/dist/index.js +1 -1
  78. package/dist/modules/registry.js +4 -4
  79. package/dist/project-config.d.ts +14 -0
  80. package/dist/project-config.js +40 -1
  81. package/dist/tools/helper.d.ts +3 -0
  82. package/dist/tools/helper.js +44 -0
  83. 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": {
@@ -39,8 +39,10 @@ export declare function computerLabel(name: string): string;
39
39
  /** Folds what this Hook knows into one row per real computer. A machines.yaml
40
40
  * name joins a computer when its first label matches any name that computer
41
41
  * has, or when it shares a profile with names already folded into exactly one
42
- * computer (a profile two computers claim folds nothing). The rest become
43
- * unlinked rows: names sharing a label or a profile are one computer. */
42
+ * peer (a profile two computers claim folds nothing). This computer knows its
43
+ * own names, so a name matching none of them is another machine even when it
44
+ * shares this computer's profile. The rest become unlinked rows: names
45
+ * sharing a label or a profile are one computer. */
44
46
  export declare function foldComputers(facts: IdentityFacts, options?: {
45
47
  trusted?: boolean;
46
48
  }): Computer[];
@@ -28,8 +28,10 @@ function addAlias(row, name, rows = [row]) {
28
28
  /** Folds what this Hook knows into one row per real computer. A machines.yaml
29
29
  * name joins a computer when its first label matches any name that computer
30
30
  * has, or when it shares a profile with names already folded into exactly one
31
- * computer (a profile two computers claim folds nothing). The rest become
32
- * unlinked rows: names sharing a label or a profile are one computer. */
31
+ * peer (a profile two computers claim folds nothing). This computer knows its
32
+ * own names, so a name matching none of them is another machine even when it
33
+ * shares this computer's profile. The rest become unlinked rows: names
34
+ * sharing a label or a profile are one computer. */
33
35
  export function foldComputers(facts, options = {}) {
34
36
  const localName = facts.local.names.find(name => !name.includes(".")) ?? facts.local.names[0] ?? "local";
35
37
  const linked = [{ ...(facts.local.id ? { id: facts.local.id } : {}), name: localName, aliases: [], local: true, linked: true, reachable: true }];
@@ -73,7 +75,9 @@ export function foldComputers(facts, options = {}) {
73
75
  const unfolded = [];
74
76
  for (const [name, profile] of rest) {
75
77
  const claimed = claims.get(profile);
76
- if (claimed?.size === 1)
78
+ // A MacBook Air set up with this Linux box's profile is not this box: it
79
+ // became an alias here and the box called itself "air" in its own set.
80
+ if (claimed?.size === 1 && ![...claimed][0].local)
77
81
  fold([...claimed][0], name, profile, false);
78
82
  else
79
83
  unfolded.push([name, profile]);
@@ -37,7 +37,7 @@ export type PeerAnswer = {
37
37
  /** Its conductor module is off, so it cannot run a conductor. */
38
38
  disabled?: boolean;
39
39
  });
40
- export declare function askPeers(peers: readonly HookPeer[], caller: Caller, ask?: Ask): Promise<PeerAnswer[]>;
40
+ export declare function askPeers(peers: readonly HookPeer[], caller: Caller, ask?: Ask, timeout?: number): Promise<PeerAnswer[]>;
41
41
  export interface GroupConductor {
42
42
  /** A live conductor on a member of this computer's set. */
43
43
  found?: {
@@ -11,10 +11,10 @@ export async function localCaller() {
11
11
  export function callerQuery(caller) {
12
12
  return new URLSearchParams({ name: caller.name, ...(caller.hostKey ? { hostKey: caller.hostKey } : {}) }).toString();
13
13
  }
14
- export async function askPeers(peers, caller, ask = peerRequest) {
14
+ export async function askPeers(peers, caller, ask = peerRequest, timeout = 8_000) {
15
15
  return Promise.all(peers.map(async (peer) => {
16
16
  try {
17
- const answer = await ask(peer, `/v1/conductor?${callerQuery(caller)}`, undefined, 8_000);
17
+ const answer = await ask(peer, `/v1/conductor?${callerQuery(caller)}`, undefined, timeout);
18
18
  const computer = object(answer.computer);
19
19
  const conductor = answer.conductor && typeof answer.conductor === "object" ? object(answer.conductor) : undefined;
20
20
  const set = object(answer.set);
@@ -13,6 +13,12 @@ interface LocalInfo {
13
13
  * says whether this computer lists the caller back. */
14
14
  export declare function conductorAnswer(info: LocalInfo, url: URL): Promise<Json>;
15
15
  /** `GET /v1/sets`: this computer's set and every set its one-way peers are in, plus unlinked computers. */
16
+ /** How long the sets view waits for each peer. A live peer answers in a
17
+ * second or two; an unreachable one held every reading of the view for the
18
+ * full 8 s, and the phone, which reads every computer's sets, gave up on
19
+ * the slow ones and showed linked computers as unlinked. A peer past this
20
+ * shows as unreachable in this reading only; conductor checks keep 8 s. */
21
+ export declare const SETS_PEER_TIMEOUT_MS = 4000;
16
22
  export declare function readSets(info: LocalInfo): Promise<Json>;
17
23
  /** `POST /v1/sets/name`: names this computer's set. The owner's call is sent
18
24
  * on to every reachable member; a member's relay (with `namedAt`) is kept
@@ -19,10 +19,16 @@ export async function conductorAnswer(info, url) {
19
19
  ...(caller.name || caller.hostKey ? { knowsCaller: links.knowsCaller } : {}), ...(set ? { set } : {}) };
20
20
  }
21
21
  /** `GET /v1/sets`: this computer's set and every set its one-way peers are in, plus unlinked computers. */
22
+ /** How long the sets view waits for each peer. A live peer answers in a
23
+ * second or two; an unreachable one held every reading of the view for the
24
+ * full 8 s, and the phone, which reads every computer's sets, gave up on
25
+ * the slow ones and showed linked computers as unlinked. A peer past this
26
+ * shows as unreachable in this reading only; conductor checks keep 8 s. */
27
+ export const SETS_PEER_TIMEOUT_MS = 4_000;
22
28
  export async function readSets(info) {
23
29
  const [{ peers, peerError }, conductor, set, { computers }] = await Promise.all([optionalHookPeers(), localConductor(), readSetName(),
24
30
  readComputers({ local: { id: info.computer.id } })]);
25
- const answers = await askPeers(peers, await localCaller());
31
+ const answers = await askPeers(peers, await localCaller(), undefined, SETS_PEER_TIMEOUT_MS);
26
32
  // Old /v1/conductor replies list peer names without ids. Resolve unknown
27
33
  // names through the existing identity directory, also on older Hooks.
28
34
  // Skip this extra round when names already identify every member.
@@ -31,7 +37,7 @@ export async function readSets(info) {
31
37
  if (!answer.ok || answer.knowsCaller === false || !answer.peers?.some(name => indirect.has(computerLabel(name))))
32
38
  return [];
33
39
  try {
34
- const directory = await peerRequest(answer.peer, "/v1/computers", undefined, 12_000);
40
+ const directory = await peerRequest(answer.peer, "/v1/computers", undefined, 2 * SETS_PEER_TIMEOUT_MS);
35
41
  return (Array.isArray(directory.computers) ? directory.computers.slice(0, 64) : []).flatMap(value => {
36
42
  const row = object(value);
37
43
  return typeof row.id === "string" && typeof row.name === "string" ? [{ id: row.id, name: row.name,
@@ -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 {};