@phren/cli 0.3.58 → 0.3.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/account-add.d.ts +30 -0
  3. package/dist/bridge/account-add.js +125 -19
  4. package/dist/bridge/account-failover.d.ts +9 -2
  5. package/dist/bridge/account-failover.js +1 -1
  6. package/dist/bridge/account-policy.d.ts +44 -0
  7. package/dist/bridge/account-policy.js +103 -0
  8. package/dist/bridge/account-pools.d.ts +35 -0
  9. package/dist/bridge/account-pools.js +171 -0
  10. package/dist/bridge/account-usage.d.ts +29 -4
  11. package/dist/bridge/account-usage.js +117 -8
  12. package/dist/bridge/agent-hook-callback.d.ts +6 -0
  13. package/dist/bridge/agent-hook-callback.js +10 -2
  14. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  15. package/dist/bridge/agent-hook-stores.js +13 -0
  16. package/dist/bridge/agent-hooks.d.ts +12 -2
  17. package/dist/bridge/agent-hooks.js +41 -4
  18. package/dist/bridge/claude-account-setup.d.ts +16 -0
  19. package/dist/bridge/claude-account-setup.js +46 -2
  20. package/dist/bridge/claude-accounts.d.ts +9 -0
  21. package/dist/bridge/claude-accounts.js +53 -15
  22. package/dist/bridge/claude-credits.d.ts +8 -2
  23. package/dist/bridge/claude-credits.js +52 -31
  24. package/dist/bridge/codex-threads.js +50 -2
  25. package/dist/bridge/command.js +12 -3
  26. package/dist/bridge/continuation-launch.d.ts +32 -0
  27. package/dist/bridge/continuation-launch.js +112 -1
  28. package/dist/bridge/dispatch-command.js +22 -0
  29. package/dist/bridge/dispatch-returns.d.ts +23 -0
  30. package/dist/bridge/dispatch-returns.js +57 -0
  31. package/dist/bridge/dispatch.d.ts +26 -4
  32. package/dist/bridge/dispatch.js +100 -11
  33. package/dist/bridge/git-host-gitlab.js +2 -1
  34. package/dist/bridge/git-hosts.d.ts +8 -0
  35. package/dist/bridge/git-hosts.js +16 -2
  36. package/dist/bridge/git-publish.js +18 -2
  37. package/dist/bridge/git.d.ts +8 -0
  38. package/dist/bridge/git.js +24 -1
  39. package/dist/bridge/hand-off-queue.d.ts +71 -0
  40. package/dist/bridge/hand-off-queue.js +38 -0
  41. package/dist/bridge/harnesses.d.ts +12 -0
  42. package/dist/bridge/harnesses.js +20 -4
  43. package/dist/bridge/helper.d.ts +54 -0
  44. package/dist/bridge/helper.js +186 -0
  45. package/dist/bridge/herdr.js +6 -2
  46. package/dist/bridge/hook-fast.d.ts +3 -0
  47. package/dist/bridge/hook-fast.js +10 -2
  48. package/dist/bridge/move-computers.d.ts +15 -1
  49. package/dist/bridge/move-computers.js +123 -26
  50. package/dist/bridge/owner-inbox-sources.d.ts +12 -1
  51. package/dist/bridge/owner-inbox-sources.js +127 -49
  52. package/dist/bridge/peers.d.ts +2 -0
  53. package/dist/bridge/peers.js +35 -4
  54. package/dist/bridge/prompt-deliveries.d.ts +69 -2
  55. package/dist/bridge/prompt-deliveries.js +342 -28
  56. package/dist/bridge/schedule-watch.js +17 -3
  57. package/dist/bridge/server-routes.d.ts +6 -0
  58. package/dist/bridge/server-routes.js +98 -14
  59. package/dist/bridge/server-stream.js +6 -4
  60. package/dist/bridge/server.js +2 -1
  61. package/dist/bridge/session-move.d.ts +70 -1
  62. package/dist/bridge/session-move.js +311 -19
  63. package/dist/bridge/simulators.d.ts +19 -0
  64. package/dist/bridge/simulators.js +93 -13
  65. package/dist/bridge/speech-live.js +132 -22
  66. package/dist/bridge/task-routes.d.ts +16 -16
  67. package/dist/bridge/terminal-herdr.js +6 -1
  68. package/dist/bridge/terminal-tmux.js +9 -5
  69. package/dist/bridge/terminal.d.ts +9 -2
  70. package/dist/bridge/transcript-claude.d.ts +3 -0
  71. package/dist/bridge/transcript-claude.js +175 -29
  72. package/dist/bridge/transcript-preview.d.ts +11 -2
  73. package/dist/bridge/transcript-preview.js +90 -8
  74. package/dist/bridge/turn-records.d.ts +19 -0
  75. package/dist/bridge/turn-records.js +78 -3
  76. package/dist/bridge/usage.d.ts +17 -0
  77. package/dist/bridge/usage.js +3 -2
  78. package/dist/bridge-hook.mjs +11964 -10084
  79. package/dist/cli-registry.js +2 -2
  80. package/dist/content/citation.d.ts +4 -0
  81. package/dist/content/citation.js +21 -21
  82. package/dist/data/task-contract.d.ts +4 -4
  83. package/dist/governance/policy.js +5 -2
  84. package/dist/index.js +1 -1
  85. package/dist/modules/registry.js +5 -5
  86. package/dist/project-config.d.ts +14 -0
  87. package/dist/project-config.js +40 -1
  88. package/dist/tools/dispatch.js +1 -1
  89. package/dist/tools/helper.d.ts +3 -0
  90. package/dist/tools/helper.js +44 -0
  91. package/package.json +1 -1
@@ -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) } : {}) };
@@ -43,6 +43,8 @@ export interface RequestList {
43
43
  source: string;
44
44
  user?: string;
45
45
  };
46
+ /** The hosted repository the requests were listed from, when the host's tool chose it (see `repository`). */
47
+ repository?: string;
46
48
  }
47
49
  export interface GitHostProvider {
48
50
  readonly kind: HostKind;
@@ -57,6 +59,10 @@ export interface GitHostProvider {
57
59
  * when one is given. The host's own refusal (checks, approvals, conflicts)
58
60
  * comes back as `{ ok: false, reason: "blocked", message }`. */
59
61
  merge(root: string, request: MergeRequest, host: GitHost): Promise<Json>;
62
+ /** The hosted repository `list` and `merge` act on, as a URL or `domain/owner/repo`, when the host's own
63
+ * tool picks it rather than the remote (gh prefers an `upstream` or its `repo set-default`). Without it,
64
+ * the remote's `webUrl` is that repository. Null when it cannot be told. */
65
+ repository?(root: string, host: GitHost): Promise<string | null>;
60
66
  /** Who a token signs in as, for Connect; HTTP hosts only. */
61
67
  whoami?(root: string, host: GitHost, token: string, api?: string): Promise<{
62
68
  user: string;
@@ -68,6 +74,8 @@ export interface MergeRequest {
68
74
  method: MergeMethod;
69
75
  expectedHeadSha?: string;
70
76
  deleteBranch?: boolean;
77
+ /** `domain/owner/repo` checked against the reviewed card: the merge acts there and nowhere else. */
78
+ repository?: string;
71
79
  }
72
80
  /** `git@host:owner/repo.git`, `ssh://git@host:2222/owner/repo.git`,
73
81
  * `https://user@host/owner/repo` → the domain and the repository path. */
@@ -198,7 +198,9 @@ const github = {
198
198
  return { number: pull.number, title: pull.title, head: pull.headRefName, base: pull.baseRefName,
199
199
  author: String(author.login ?? author.name ?? ""), url: pull.url, draft: pull.isDraft === true, state: pull.state, updated: pull.updatedAt };
200
200
  });
201
- return { available: true, pulls, current: mine };
201
+ // gh picked the repository itself; its pull request URLs name it, without asking gh again.
202
+ const listed = [mine, ...pulls].map(pull => /^(https:\/\/[^\s?#]+?)\/pull\/\d+$/.exec(String(pull?.url ?? ""))?.[1]).find(Boolean);
203
+ return { available: true, pulls, current: mine, ...(listed ? { repository: listed } : {}) };
202
204
  }
203
205
  catch {
204
206
  return { available: false, reason: "auth", message: "The GitHub CLI (gh) is missing or not signed in on this computer. Install it, then run gh auth login there.", pulls: [], current: null };
@@ -226,8 +228,10 @@ const github = {
226
228
  async merge(root, request, host) {
227
229
  // No --delete-branch: gh would also delete and leave the local branch,
228
230
  // which may be an agent's checkout.
231
+ // A checked repository is named, so gh cannot resolve another one between the check and the merge.
229
232
  const args = ["pr", "merge", String(request.number), `--${request.method}`,
230
- ...(request.expectedHeadSha ? ["--match-head-commit", request.expectedHeadSha] : [])];
233
+ ...(request.expectedHeadSha ? ["--match-head-commit", request.expectedHeadSha] : []),
234
+ ...(request.repository ? ["--repo", request.repository] : [])];
231
235
  const result = await runCombined("gh", args, root, 60_000, ghEnv(host));
232
236
  if (result.missing)
233
237
  return { ok: false, reason: "missing", message: "The GitHub CLI (gh) is not installed on this computer." };
@@ -240,5 +244,15 @@ const github = {
240
244
  return { ok: false, reason: "auth", message: "The GitHub CLI is not signed in on this computer, or the account can't merge here. Run gh auth login there." };
241
245
  return { ok: false, reason: "failed", message: output.slice(0, 1000) || "gh pr merge failed." };
242
246
  },
247
+ async repository(root, host) {
248
+ // The repository gh's own pr commands resolve here, which for a fork is usually its upstream.
249
+ try {
250
+ const { stdout } = await exec("gh", ["repo", "view", "--json", "url", "--jq", ".url"], { cwd: root, timeout: 15_000, maxBuffer: 65_536, env: ghEnv(host) });
251
+ return stdout.trim() || null;
252
+ }
253
+ catch {
254
+ return null;
255
+ }
256
+ },
243
257
  };
244
258
  export const PROVIDERS = { github, gitlab, gitboy };
@@ -3,7 +3,7 @@ import { nonInteractiveGitEnv } from "../utils-helpers.js";
3
3
  import { BridgeError } from "./protocol.js";
4
4
  import { git, gitRoot } from "./projects.js";
5
5
  import { countGit } from "./metrics.js";
6
- import { defaultBranch, invalidatePulls, invalidateTree } from "./git.js";
6
+ import { defaultBranch, invalidatePulls, invalidateTree, normalizeRemote, remoteIdentity } from "./git.js";
7
7
  import { z } from "zod";
8
8
  import { detectHost, providerFor, unknownHost } from "./git-hosts.js";
9
9
  import { writeHostToken } from "./git-host-auth.js";
@@ -206,6 +206,8 @@ const MergeBody = z.object({
206
206
  method: z.enum(["merge", "squash", "rebase"]).default("merge"),
207
207
  expectedHeadSha: z.string().regex(/^[0-9a-f]{7,64}$/i).optional(),
208
208
  deleteBranch: z.boolean().optional(),
209
+ /** The pulls listing's `remote` the reviewed card came from; a different remote now is refused. */
210
+ expectedRemote: z.string().trim().min(1).max(512).optional(),
209
211
  });
210
212
  /** Merge one pull or merge request on the remote's host. The host decides:
211
213
  * its refusal (checks, approvals, conflicts, a head that moved past
@@ -215,13 +217,27 @@ export async function gitMergeRequest(cwd, data) {
215
217
  const root = await repository(cwd);
216
218
  const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
217
219
  const host = await detectHost(root, branch);
220
+ const { expectedRemote, ...rest } = request;
221
+ const merge = rest;
222
+ if (expectedRemote !== undefined) {
223
+ const current = await remoteIdentity(root, host);
224
+ // Not merged unchecked: the host's tool could not say (gh signed out, offline), which is not a moved remote.
225
+ if (!current)
226
+ return { ok: false, reason: "failed", message: `Phren could not tell which repository ${host.name} merges in from this checkout, so nothing was merged. Check that its sign-in works, then try again.`, host };
227
+ if (current !== normalizeRemote(expectedRemote)) {
228
+ // The refresh the error asks for must read again: gh's choice of repository is not part of the cached listing's key.
229
+ invalidatePulls(root);
230
+ throw new BridgeError(409, "This checkout's remote is not the repository this pull request was reviewed in. Refresh pull requests before merging.", { code: "git-remote-changed" });
231
+ }
232
+ merge.repository = current;
233
+ }
218
234
  const provider = providerFor(host);
219
235
  if (!provider) {
220
236
  const { reason, message } = unknownHost(host);
221
237
  return { ok: false, reason, message, host };
222
238
  }
223
239
  try {
224
- return { ...await provider.merge(root, request, host), host };
240
+ return { ...await provider.merge(root, merge, host), host };
225
241
  }
226
242
  finally {
227
243
  invalidatePulls(root);
@@ -54,6 +54,14 @@ export declare function gitBranches(cwd: string): Promise<Json>;
54
54
  export declare function invalidatePulls(root: string): void;
55
55
  /** Tokens belong to a domain, so revoke every checkout and pending generation. */
56
56
  export declare function invalidatePullsForDomain(domain: string): void;
57
+ /** Which hosted repository the host's requests are listed and merged in, as `domain/owner/repo` in lower
58
+ * case: what a reviewed pull request card binds to, so a retargeted remote or a pane moved to another
59
+ * checkout cannot merge a same-number request in a different repository. It is the one the host's own tool
60
+ * resolves when it picks (gh: an `upstream`, or `gh repo set-default`), else the remote's. Null with no
61
+ * parsable remote, or when the tool cannot say. */
62
+ export declare function remoteIdentity(root: string, host: Awaited<ReturnType<typeof detectHost>>): Promise<string | null>;
63
+ /** `https://GitHub.com/Owner/Repo/`, `github.com/owner/repo` → `github.com/owner/repo`. */
64
+ export declare function normalizeRemote(value: string): string;
57
65
  /** Open pull or merge requests and the checked-out branch's own (any state)
58
66
  * with its checks, from whichever host the remote is on (git-hosts.ts). A
59
67
  * host that cannot answer (a missing CLI, a stubbed provider, an unknown
@@ -406,6 +406,22 @@ async function pullsTarget(cwd) {
406
406
  throw error;
407
407
  }
408
408
  }
409
+ /** Which hosted repository the host's requests are listed and merged in, as `domain/owner/repo` in lower
410
+ * case: what a reviewed pull request card binds to, so a retargeted remote or a pane moved to another
411
+ * checkout cannot merge a same-number request in a different repository. It is the one the host's own tool
412
+ * resolves when it picks (gh: an `upstream`, or `gh repo set-default`), else the remote's. Null with no
413
+ * parsable remote, or when the tool cannot say. */
414
+ export async function remoteIdentity(root, host) {
415
+ if (!host.domain)
416
+ return null;
417
+ const provider = providerFor(host);
418
+ const named = provider?.repository ? await provider.repository(root, host).catch(() => null) : host.webUrl;
419
+ return named ? normalizeRemote(named) : null;
420
+ }
421
+ /** `https://GitHub.com/Owner/Repo/`, `github.com/owner/repo` → `github.com/owner/repo`. */
422
+ export function normalizeRemote(value) {
423
+ return value.trim().toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//, "").replace(/\/+$/, "");
424
+ }
409
425
  /** Open pull or merge requests and the checked-out branch's own (any state)
410
426
  * with its checks, from whichever host the remote is on (git-hosts.ts). A
411
427
  * host that cannot answer (a missing CLI, a stubbed provider, an unknown
@@ -423,7 +439,14 @@ export async function gitPulls(cwd, retried = false) {
423
439
  pullsCache.invalidate(candidate => candidate === key);
424
440
  throw new CredentialsChanged();
425
441
  }
426
- return { ...list, branch: branch || null, host };
442
+ // `remote` is what `expectedRemote` is checked against on merge: the repository the requests came from
443
+ // when the host's tool picked it, else the remote's. With no requests listed there is no card to bind.
444
+ const { repository: listed, ...rest } = list;
445
+ const remote = host.domain ? listed ?? host.webUrl : null;
446
+ return { ...rest, branch: branch || null, host, remote: remote ? normalizeRemote(remote) : null };
447
+ })).then(list => ({
448
+ // Outside the cache, which worktrees of one repository share: this checkout, what `expectedRepository` is checked against.
449
+ ...list, repository: root,
427
450
  }));
428
451
  }
429
452
  catch (error) {
@@ -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 = {}) {