@phren/cli 0.3.53 → 0.3.55

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 (55) hide show
  1. package/dist/bridge/account-add.d.ts +7 -0
  2. package/dist/bridge/account-add.js +39 -0
  3. package/dist/bridge/claude-accounts.js +1 -1
  4. package/dist/bridge/client.js +1 -1
  5. package/dist/bridge/command.js +2 -0
  6. package/dist/bridge/computers.js +3 -2
  7. package/dist/bridge/conductor-role.d.ts +162 -2
  8. package/dist/bridge/conductor-role.js +56 -23
  9. package/dist/bridge/conductor-succession.d.ts +100 -0
  10. package/dist/bridge/conductor-succession.js +649 -0
  11. package/dist/bridge/continuation-launch.d.ts +54 -0
  12. package/dist/bridge/continuation-launch.js +106 -0
  13. package/dist/bridge/dispatch-command.js +11 -4
  14. package/dist/bridge/dispatch-hosts.d.ts +3 -0
  15. package/dist/bridge/dispatch-hosts.js +6 -1
  16. package/dist/bridge/dispatch-returns.d.ts +21 -3
  17. package/dist/bridge/dispatch-returns.js +169 -39
  18. package/dist/bridge/dispatch.d.ts +11 -0
  19. package/dist/bridge/dispatch.js +70 -5
  20. package/dist/bridge/git.js +82 -8
  21. package/dist/bridge/hand-off-queue.d.ts +3 -0
  22. package/dist/bridge/hand-off-queue.js +8 -0
  23. package/dist/bridge/hand-off.d.ts +13 -0
  24. package/dist/bridge/hand-off.js +20 -1
  25. package/dist/bridge/install.js +0 -6
  26. package/dist/bridge/launch-brief.d.ts +2 -0
  27. package/dist/bridge/launch-brief.js +19 -8
  28. package/dist/bridge/move-computers.d.ts +47 -0
  29. package/dist/bridge/move-computers.js +118 -0
  30. package/dist/bridge/peer-handoff.d.ts +5 -0
  31. package/dist/bridge/peer-handoff.js +52 -0
  32. package/dist/bridge/projects.js +13 -8
  33. package/dist/bridge/request-origin.d.ts +6 -0
  34. package/dist/bridge/request-origin.js +20 -0
  35. package/dist/bridge/scoped-gateway.d.ts +2 -1
  36. package/dist/bridge/scoped-gateway.js +16 -3
  37. package/dist/bridge/server-launch.d.ts +2 -0
  38. package/dist/bridge/server-launch.js +2 -0
  39. package/dist/bridge/server-routes.d.ts +6 -0
  40. package/dist/bridge/server-routes.js +228 -15
  41. package/dist/bridge/server.js +46 -24
  42. package/dist/bridge/session-move.d.ts +28 -1
  43. package/dist/bridge/session-move.js +266 -25
  44. package/dist/bridge/socket-budget.d.ts +29 -0
  45. package/dist/bridge/socket-budget.js +62 -0
  46. package/dist/bridge/terminal-herdr.js +14 -0
  47. package/dist/bridge/terminal-tmux.js +1 -0
  48. package/dist/bridge/terminal.d.ts +2 -0
  49. package/dist/bridge/terminal.js +6 -0
  50. package/dist/bridge/worker-relocation.d.ts +5 -0
  51. package/dist/bridge/worker-relocation.js +33 -0
  52. package/dist/bridge-hook.mjs +16480 -14296
  53. package/dist/modules/registry.js +8 -8
  54. package/dist/tools/dispatch.js +2 -1
  55. package/package.json +1 -1
@@ -36,6 +36,9 @@ export declare const queuedHandOffSchema: z.ZodObject<{
36
36
  export interface QueueOptions {
37
37
  validate: (target: Target) => Promise<Json>;
38
38
  send: (target: Target, text: string, deliveryId: string, typing: () => Promise<void>) => Promise<Json>;
39
+ forward?: (target: Target, text: string, deliveryId: string) => Promise<{
40
+ delivered: boolean;
41
+ } | undefined>;
39
42
  notify?: (target: Target, text: string, deliveryId: string, computer: string) => Promise<Json>;
40
43
  /** The conversation the target's pane shows now, and its terminal. */
41
44
  current?: (target: Target) => Promise<{
@@ -242,6 +242,14 @@ export class HandOffQueue {
242
242
  remote.push(row);
243
243
  continue;
244
244
  }
245
+ const forwarded = await this.options.forward?.(row.origin, `Hand-off ${row.deliveryId}: ${row.state}.`, this.noticeId(row)).catch(() => ({ delivered: false }));
246
+ if (forwarded) {
247
+ if (forwarded.delivered) {
248
+ row.notified = true;
249
+ await this.save(row);
250
+ }
251
+ continue;
252
+ }
245
253
  // A notice is itself an idempotent queued hand-off, without an origin.
246
254
  const id = this.noticeId(row);
247
255
  if (!await this.read(id)) {
@@ -30,6 +30,7 @@ export type HandOffInput = z.infer<typeof handOffSchema>;
30
30
  export declare function handOff(input: unknown, options?: {
31
31
  deliveryId?: string;
32
32
  notifySender?: boolean;
33
+ bypassConductor?: boolean;
33
34
  }): Promise<{
34
35
  ok: boolean;
35
36
  delivered: boolean;
@@ -137,6 +138,18 @@ export interface ClaudeAccountRoom extends ClaudeQuota {
137
138
  }
138
139
  /** Each Claude account's room in one computer's usage answer. */
139
140
  export declare function claudeAccountRooms(answer: Json, computer: string, now?: number): ClaudeAccountRoom[];
141
+ /** Owner-visible login metadata and remaining allowance for continuation.
142
+ * Config paths, identity hashes and provider credentials stay on the Hook. */
143
+ export declare function claudeMoveAccounts(answer: Json): Array<{
144
+ id: string;
145
+ email?: string;
146
+ plan?: string;
147
+ fiveHourLeft?: number;
148
+ weekLeft?: number;
149
+ resetsAt?: string;
150
+ fiveHourResetsAt?: string;
151
+ weekResetsAt?: string;
152
+ }>;
140
153
  /** A registered computer this Hook cannot see, with the other names the store
141
154
  * registers it under. */
142
155
  export interface NotLinkedComputer {
@@ -1,3 +1,4 @@
1
+ import { redactPeerHandoff } from "./peer-handoff.js";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { deliveryIdSchema } from "./prompt-once.js";
3
4
  import { terminalPaneFromEnv } from "./terminal.js";
@@ -83,6 +84,11 @@ async function hookFor(computer) {
83
84
  }
84
85
  export async function handOff(input, options = {}) {
85
86
  const data = handOffSchema.parse(input);
87
+ if (!options.bypassConductor) {
88
+ const here = await terminalPaneFromEnv();
89
+ if (here)
90
+ return await hookRequest("/v1/conductor/call", { action: "hand_off", data, origin: here });
91
+ }
86
92
  const { request, peer } = await hookFor(data.computer);
87
93
  const resolved = data.target ? undefined : await targetFromOverview(request, data.session, peer?.server, data.account);
88
94
  const target = data.target ?? resolved.target;
@@ -98,7 +104,7 @@ export async function handOff(input, options = {}) {
98
104
  const originComputer = peer && origin ? await hookRequest("/v1/health").then(health => object(health.computer).name, () => undefined) : undefined;
99
105
  const deliveryId = data.deliveryId ?? options.deliveryId ?? randomUUID().replaceAll("-", "");
100
106
  const result = await request(data.status ? "/v1/hand-off/status" : "/v1/hand-off", { target, deliveryId,
101
- ...(!data.status ? { text: data.text, ...(origin ? { origin, ...(typeof originComputer === "string" ? { originComputer } : {}) } : {}) } : {}) });
107
+ ...(!data.status ? { text: peer ? redactPeerHandoff(data.text) : data.text, ...(origin ? { origin, ...(typeof originComputer === "string" ? { originComputer } : {}) } : {}) } : {}) });
102
108
  // A bare ok only acknowledges typing. Even an unchanged, busy Codex pane
103
109
  // may have kept the text in its composer instead of submitting a turn.
104
110
  const delivered = result.ok === true && result.delivered === true && result.deliveryUncertain !== true && result.unsubmitted !== true;
@@ -189,6 +195,19 @@ export function claudeAccountRooms(answer, computer, now = Date.now()) {
189
195
  ...(usage.account?.email ? { email: usage.account.email } : {}), ...(five ? { fiveHour: five } : {}), ...(seven ? { week: seven } : {}) };
190
196
  });
191
197
  }
198
+ /** Owner-visible login metadata and remaining allowance for continuation.
199
+ * Config paths, identity hashes and provider credentials stay on the Hook. */
200
+ export function claudeMoveAccounts(answer) {
201
+ return claudeAccountRooms(answer, "local").map(room => ({ id: room.account,
202
+ ...(room.email ? { email: room.email } : {}),
203
+ ...(typeof object(objects(answer.accounts).find(row => row.source === "claude" && object(row.account).id === room.account)?.subscription).plan === "string" ? { plan: String(object(objects(answer.accounts).find(row => row.source === "claude" && object(row.account).id === room.account)?.subscription).plan) } : {}),
204
+ ...(room.fiveHour?.resetsAt ? { fiveHourResetsAt: room.fiveHour.resetsAt } : {}),
205
+ ...(room.week?.resetsAt ? { weekResetsAt: room.week.resetsAt } : {}),
206
+ ...(room.fiveHour?.leftPercent !== undefined ? { fiveHourLeft: room.fiveHour.leftPercent } : {}),
207
+ ...(room.week?.leftPercent !== undefined ? { weekLeft: room.week.leftPercent } : {}),
208
+ ...(room.fiveHour?.resetsAt ?? room.week?.resetsAt ? { resetsAt: room.fiveHour?.resetsAt ?? room.week?.resetsAt } : {}),
209
+ }));
210
+ }
192
211
  function sessionsFrom(overview, computer, local, now = Date.now()) {
193
212
  const sessions = [];
194
213
  for (const group of objects(overview.groups))
@@ -53,12 +53,6 @@ export function upgradeKeys(text) {
53
53
  let changed = 0;
54
54
  const result = text.split(/(?<=\n)/).map(line => {
55
55
  const parsed = keyOptions(line);
56
- if (parsed && parsed.options[0] === "restrict" && /^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-computer:[A-Za-z0-9_.-]+\s*$/.test(parsed.rest)
57
- && parsed.options.includes(forcedCommand)) {
58
- changed++;
59
- return parsed.options.filter(option => option !== "pty" && option.toLowerCase() !== "port-forwarding" && !option.toLowerCase().startsWith("permitopen="))
60
- .map(option => option === forcedCommand ? peerForcedCommand : option).join(",") + parsed.rest;
61
- }
62
56
  if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest))
63
57
  return line;
64
58
  const old = /^command="(?:\/usr\/bin\/false|python3 ~\/\.local\/share\/phren\/chat-progress\.py|sh ~\/\.local\/share\/phren\/bridge\/dispatch)"$/;
@@ -41,6 +41,8 @@ export declare function launchesWithBrief(kind: string): boolean;
41
41
  * Undefined for an id this computer wrote no label for (older dispatches).
42
42
  */
43
43
  export declare function briefLabel(id: string): Promise<string | undefined>;
44
+ /** Moves occupy the launch namespace as well as their own move ledger. */
45
+ export declare function assertUnusedLaunchId(id: string): Promise<void>;
44
46
  /**
45
47
  * Writes the brief (0600, in a 0700 folder of its own) and returns its path.
46
48
  * A `label` is written beside it, inside the same folder, so it is published
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { lstat, mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { z } from "zod";
5
- import { atomic, bridgeRoot, targetSchema } from "./protocol.js";
5
+ import { atomic, BridgeError, bridgeRoot, targetSchema } from "./protocol.js";
6
6
  /**
7
7
  * A worker's first prompt carried by its launch instead of typed into a
8
8
  * starting pane. The brief is written to a private file on the computer that
@@ -85,6 +85,14 @@ export async function briefLabel(id) {
85
85
  return undefined;
86
86
  }
87
87
  }
88
+ /** Moves occupy the launch namespace as well as their own move ledger. */
89
+ export async function assertUnusedLaunchId(id) {
90
+ briefId.parse(id);
91
+ const entries = await Promise.all([briefDirectory(id), path.join(bridgeRoot(), "dispatches", `${id}.json`)].map(file => lstat(file).catch(error => { if (error.code !== "ENOENT")
92
+ throw error; return undefined; })));
93
+ if (entries.some(Boolean))
94
+ throw new BridgeError(409, "This move id already belongs to an existing dispatch or brief.");
95
+ }
88
96
  /**
89
97
  * Writes the brief (0600, in a 0700 folder of its own) and returns its path.
90
98
  * A `label` is written beside it, inside the same folder, so it is published
@@ -96,7 +104,6 @@ export async function briefLabel(id) {
96
104
  */
97
105
  export async function writeLaunchBrief(brief, now = Date.now(), label) {
98
106
  await mkdir(briefRoot(), { recursive: true, mode: 0o700 });
99
- await prune(now);
100
107
  const directory = briefDirectory(brief.id);
101
108
  const file = path.join(directory, "brief.md");
102
109
  const text = brief.text.endsWith("\n") ? brief.text : `${brief.text}\n`;
@@ -106,11 +113,15 @@ export async function writeLaunchBrief(brief, now = Date.now(), label) {
106
113
  if (named)
107
114
  await atomic(path.join(folder, LABEL_FILE), named);
108
115
  };
109
- // The same id again (a retried launch) replaces the text and label in the existing folder.
110
- if (await stat(directory).catch(() => undefined)) {
111
- await fill(directory);
116
+ // A retry may reuse identical bytes; it must never replace another launch.
117
+ const existing = async () => {
118
+ if (await readFile(file, "utf8").catch(() => undefined) !== text)
119
+ throw new BridgeError(409, "This brief id already belongs to another launch.");
112
120
  return file;
113
- }
121
+ };
122
+ if (await stat(directory).catch(() => undefined))
123
+ return existing();
124
+ await prune(now);
114
125
  const staging = path.join(bridgeRoot(), "briefs-staging");
115
126
  await mkdir(staging, { recursive: true, mode: 0o700 });
116
127
  const draft = path.join(staging, `${brief.id}.${randomUUID()}`);
@@ -121,10 +132,10 @@ export async function writeLaunchBrief(brief, now = Date.now(), label) {
121
132
  }
122
133
  catch (error) {
123
134
  await rm(draft, { recursive: true, force: true }).catch(() => undefined);
124
- // Another writer published the same id first: write into its folder.
135
+ // Another writer published the same id first: only identical retries are safe.
125
136
  if (!(await stat(path.join(directory, "brief.md")).catch(() => undefined)))
126
137
  throw error;
127
- await fill(directory);
138
+ return existing();
128
139
  }
129
140
  return file;
130
141
  }
@@ -0,0 +1,47 @@
1
+ import { z } from "zod";
2
+ import { type moveToSchema } from "./dispatch.js";
3
+ type MoveTo = z.infer<typeof moveToSchema>;
4
+ import { type DispatchHost } from "./dispatch-hosts.js";
5
+ import { type Json } from "./protocol.js";
6
+ declare const availability: z.ZodObject<{
7
+ computerId: z.ZodOptional<z.ZodString>;
8
+ hasCheckout: z.ZodBoolean;
9
+ harnesses: z.ZodArray<z.ZodObject<{
10
+ source: z.ZodEnum<{
11
+ claude: "claude";
12
+ codex: "codex";
13
+ copilot: "copilot";
14
+ opencode: "opencode";
15
+ }>;
16
+ usable: z.ZodBoolean;
17
+ reason: z.ZodOptional<z.ZodString>;
18
+ accounts: z.ZodOptional<z.ZodArray<z.ZodObject<{
19
+ id: z.ZodString;
20
+ label: z.ZodString;
21
+ usable: z.ZodBoolean;
22
+ signedIn: z.ZodBoolean;
23
+ email: z.ZodOptional<z.ZodString>;
24
+ plan: z.ZodOptional<z.ZodString>;
25
+ current: z.ZodDefault<z.ZodBoolean>;
26
+ fiveHourResetsAt: z.ZodOptional<z.ZodString>;
27
+ weekResetsAt: z.ZodOptional<z.ZodString>;
28
+ fiveHourLeft: z.ZodOptional<z.ZodNumber>;
29
+ weekLeft: z.ZodOptional<z.ZodNumber>;
30
+ resetsAt: z.ZodOptional<z.ZodString>;
31
+ }, z.core.$strip>>>;
32
+ }, z.core.$strip>>;
33
+ }, z.core.$strip>;
34
+ export type MoveAvailability = z.infer<typeof availability>;
35
+ export declare function localMoveAvailability(project: unknown, usage: () => Promise<Json>, conductor?: boolean): Promise<MoveAvailability>;
36
+ /** Exact verified names only; self also accepts the name health displays. */
37
+ export declare function movePeer(computer: string | undefined, self?: string): Promise<DispatchHost | undefined>;
38
+ export declare function peerMoveAvailability(peer: DispatchHost, project: string, conductor?: boolean): Promise<MoveAvailability>;
39
+ export declare function checkMovePeer(peer: DispatchHost, project: string, to: MoveTo, conductor?: boolean): Promise<{
40
+ account?: string;
41
+ accountChoice?: string;
42
+ computerId?: string;
43
+ }>;
44
+ export declare function moveComputers(project: unknown, self: string, local: () => Promise<MoveAvailability>, currentAccount?: string, conductor?: boolean): Promise<Json>;
45
+ /** Re-read enrollment before every request that may transmit a brief. */
46
+ export declare function currentMovePeer(captured: DispatchHost): Promise<DispatchHost>;
47
+ export {};
@@ -0,0 +1,118 @@
1
+ // Continuation destinations expose login labels and quota, never auth material.
2
+ import { z } from "zod";
3
+ import { dispatchProjectDirectory, PEER_COPILOT_REASON, projectName } from "./dispatch.js";
4
+ import { chooseAccount } from "./account-choice.js";
5
+ import { harnessInventoryWithin } from "./harnesses.js";
6
+ import { peerHost, isLocalComputer } from "./dispatch-hosts.js";
7
+ import { hookPeers, optionalHookPeers } from "./peers.js";
8
+ import { BridgeError } from "./protocol.js";
9
+ const account = z.object({ id: z.string().max(64), label: z.string().max(200), usable: z.boolean(), signedIn: z.boolean(), email: z.string().optional(), plan: z.string().optional(), current: z.boolean().default(false),
10
+ fiveHourResetsAt: z.string().optional(), weekResetsAt: z.string().optional(),
11
+ fiveHourLeft: z.number().min(0).max(100).optional(), weekLeft: z.number().min(0).max(100).optional(), resetsAt: z.string().optional() });
12
+ const availability = z.object({ computerId: z.string().uuid().optional(), hasCheckout: z.boolean(), harnesses: z.array(z.object({
13
+ source: z.enum(["claude", "codex", "opencode", "copilot"]), usable: z.boolean(), reason: z.string().optional(), accounts: z.array(account).optional(),
14
+ })) });
15
+ export async function localMoveAvailability(project, usage, conductor = false) {
16
+ const name = project === null || project === undefined || project === "" ? undefined : projectName.parse(project);
17
+ const [checkout, found, limits] = await Promise.all([
18
+ conductor ? Promise.resolve(true) : name ? dispatchProjectDirectory(name).then(() => true, () => false) : Promise.resolve(false),
19
+ harnessInventoryWithin(2_500),
20
+ usage().catch(() => ({})),
21
+ ]);
22
+ const { claudeMoveAccounts } = await import("./hand-off.js");
23
+ const rooms = claudeMoveAccounts(limits);
24
+ const { claudeHomes, claudeAccountRef, claudeAccountEmail, claudeAccountSubscription } = await import("./claude-accounts.js");
25
+ const discovered = found?.harnesses ?? [];
26
+ const claude = discovered.find(row => row.source === "claude");
27
+ const accounts = [...claude?.accounts ?? []];
28
+ for (const home of claudeHomes())
29
+ if (!accounts.some(login => login.id === home.id)) {
30
+ const ref = claudeAccountRef(home), email = claudeAccountEmail(home), subscription = claudeAccountSubscription(home);
31
+ accounts.push({ ...ref, usable: false, signedIn: false, ...(email ? { email } : {}), ...(subscription?.plan ? { plan: subscription.plan } : {}) });
32
+ }
33
+ const inventory = claude ? discovered.map(row => row.source === "claude" ? { ...row, accounts } : row) : [...discovered, { source: "claude", installed: false, usable: false, accounts }];
34
+ return availability.parse({ hasCheckout: checkout, harnesses: inventory.filter(row => row.source !== "phren").map(row => ({
35
+ source: row.source, usable: row.usable, ...(row.accounts ? { accounts: row.accounts.map(login => {
36
+ const room = row.source === "claude" ? rooms.find(item => item.id === login.id) : undefined;
37
+ return { ...room, id: login.id, label: login.label ?? login.id, usable: login.usable && room?.fiveHourLeft !== 0 && room?.weekLeft !== 0, signedIn: login.signedIn, ...(login.email ? { email: login.email } : {}), ...(login.plan ? { plan: login.plan } : {}) };
38
+ }) } : {}),
39
+ })) });
40
+ }
41
+ /** Exact verified names only; self also accepts the name health displays. */
42
+ export async function movePeer(computer, self) {
43
+ if (computer === undefined || computer === self)
44
+ return undefined;
45
+ const peers = await hookPeers().catch(error => {
46
+ if (error instanceof BridgeError && error.details?.hooksYaml === "missing")
47
+ return [];
48
+ throw error;
49
+ });
50
+ const peer = peers.find(row => row.name === computer);
51
+ if (peer)
52
+ return peerHost(peer);
53
+ if (isLocalComputer(computer))
54
+ return undefined;
55
+ throw new BridgeError(404, "Unknown computer. Add its verified connection to hooks.yaml.");
56
+ }
57
+ export async function peerMoveAvailability(peer, project, conductor = false) {
58
+ try {
59
+ return availability.parse(await peer.request(`/v1/sessions/move/availability?project=${encodeURIComponent(project)}${conductor ? "&conductor=1" : ""}`, undefined, 10_000));
60
+ }
61
+ catch {
62
+ throw new BridgeError(409, `Computer ${peer.name} is offline or cannot report continuation availability.`);
63
+ }
64
+ }
65
+ function chosenLogin(accounts) {
66
+ return chooseAccount(accounts.map(login => ({ account: login.id, usable: login.usable,
67
+ exhausted: login.fiveHourLeft === 0 || login.weekLeft === 0,
68
+ fiveHour: { leftPercent: login.fiveHourLeft }, week: { leftPercent: login.weekLeft },
69
+ }))).choice;
70
+ }
71
+ export async function checkMovePeer(peer, project, to, conductor = false) {
72
+ if (to.harness === "copilot")
73
+ throw new BridgeError(409, PEER_COPILOT_REASON);
74
+ const facts = await peerMoveAvailability(peer, project, conductor);
75
+ if (!facts.hasCheckout)
76
+ throw new BridgeError(409, `Computer ${peer.name} has no checkout of ${project}.`);
77
+ const harness = facts.harnesses.find(row => row.source === to.harness);
78
+ const choice = to.harness === "claude" && !to.account && harness?.accounts ? chosenLogin(harness.accounts) : undefined;
79
+ const login = harness?.accounts?.find(row => row.id === (to.account ?? choice?.account ?? "default"));
80
+ if (!harness?.usable || (harness.accounts && !login?.usable) || login?.fiveHourLeft === 0 || login?.weekLeft === 0) {
81
+ throw new BridgeError(409, `The harness or account is not usable on ${peer.name}.`);
82
+ }
83
+ if (!facts.computerId)
84
+ throw new BridgeError(409, `Update ${peer.name}'s Hook to verify its continuation identity.`);
85
+ return { ...(facts.computerId ? { computerId: facts.computerId } : {}), ...(choice ? { account: choice.account, accountChoice: choice.reason } : {}) };
86
+ }
87
+ export async function moveComputers(project, self, local, currentAccount, conductor = false) {
88
+ const name = project === null || project === undefined || project === "" ? "" : projectName.parse(project);
89
+ const { peers } = await optionalHookPeers();
90
+ const here = await local();
91
+ const publicFacts = (facts, remote = false) => ({ ...(facts.computerId ? { computerId: facts.computerId } : {}), hasCheckout: facts.hasCheckout, harnesses: facts.harnesses.map(row => ({
92
+ source: row.source, usable: remote && row.source === "copilot" ? false : row.usable,
93
+ ...(remote && row.source === "copilot" ? { reason: PEER_COPILOT_REASON } : {}),
94
+ ...(row.source === "claude" && row.accounts ? { selectedAccount: chosenLogin(row.accounts)?.account } : {}), ...(row.accounts ? { accounts: row.accounts.map(({ signedIn: _signedIn, ...login }) => ({ ...login, current: !remote && row.source === "claude" && login.id === currentAccount })) } : {}),
95
+ })) });
96
+ const computers = await Promise.all(peers.map(async (peer) => {
97
+ try {
98
+ return { name: peer.name, self: false, online: true, ...publicFacts(await peerMoveAvailability(peerHost(peer), name, conductor), true) };
99
+ }
100
+ catch {
101
+ return { name: peer.name, self: false, online: false, hasCheckout: false, harnesses: [] };
102
+ }
103
+ }));
104
+ return { computers: [{ name: self, self: true, online: true, ...publicFacts(here) }, ...computers],
105
+ localClaudeLogins: here.harnesses.find(row => row.source === "claude")?.accounts?.filter(login => login.signedIn).length ?? 0 };
106
+ }
107
+ /** Re-read enrollment before every request that may transmit a brief. */
108
+ export async function currentMovePeer(captured) {
109
+ const current = await movePeer(captured.name).catch(() => undefined);
110
+ if (!current || !current.fingerprint || current.fingerprint !== captured.fingerprint)
111
+ throw new BridgeError(409, "The destination enrollment was revoked or changed; no brief was sent.");
112
+ return { ...current, request: async (route, data, timeout) => {
113
+ const enrolled = await movePeer(captured.name).catch(() => undefined);
114
+ if (!enrolled || enrolled.fingerprint !== captured.fingerprint)
115
+ throw new BridgeError(409, "The destination enrollment was revoked or changed; no brief was sent.");
116
+ return enrolled.request(route, data, timeout);
117
+ } };
118
+ }
@@ -0,0 +1,5 @@
1
+ /** Only human/agent prose is redacted. Opaque protocol fields (tokens, paths,
2
+ * capabilities, identities and grants) must retain their exact values. */
3
+ export declare function redactPeerHandoff(input: string): string;
4
+ /** Conductor operation envelopes contain prose beside opaque routing data. */
5
+ export declare function redactPeerPayload<T>(data: T): T;
@@ -0,0 +1,52 @@
1
+ /** Only human/agent prose is redacted. Opaque protocol fields (tokens, paths,
2
+ * capabilities, identities and grants) must retain their exact values. */
3
+ export function redactPeerHandoff(input) {
4
+ const value = String.raw `(?:\[redacted\]|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s]+)`;
5
+ let text = input.replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "")
6
+ .replace(/(?<![\w.+-])([a-z][a-z0-9+.-]*:\/\/)[^/\s?#]+@/gi, "$1[redacted]@")
7
+ .replace(/(\b(?:Authorization|Cookie|Set-Cookie|X-API-Key)[\t ]*:[\t ]*)[^\r\n]*/gi, "$1[redacted]")
8
+ .replace(new RegExp(String.raw `(\bBearer[\t ]+)${value}`, "gi"), "$1[redacted]")
9
+ .replace(/\b(?:mysql|curl)\b[^\r\n]*/gi, line => {
10
+ if (/\bmysql\b/i.test(line))
11
+ line = line.replace(/([\t ]-p)(?![\t ]|$)[^\s]+/g, "$1[redacted]");
12
+ if (/\bcurl\b/i.test(line))
13
+ line = line.replace(new RegExp(String.raw `([\t ](?:-u|--user)[\t ]+)${value}`, "g"), "$1[redacted]");
14
+ return line;
15
+ });
16
+ // Consume each identifier once, then inspect its name. Requiring a genuine
17
+ // token boundary prevents restarting a greedy search at each dot in a path.
18
+ const keys = /(?<![\w.-])(?:"([\w.-]+)"|'([\w.-]+)'|([\w.-]+))([\t ]*(?:[:=][\t ]*|[\t ]+))/g;
19
+ const secretName = /pass|pwd|token|secret|api[-_]?key|auth|bearer|credential/i;
20
+ const values = new RegExp(value, "y");
21
+ const parts = [];
22
+ let copied = 0;
23
+ for (let match; (match = keys.exec(text));) {
24
+ const name = match[1] ?? match[2] ?? match[3];
25
+ const cleanName = name.replace(/^--/, "");
26
+ if (!secretName.test(cleanName) || /^(?:author|authority)$/i.test(cleanName) || !name.startsWith("--") && !/[:=]/.test(match[4]) && cleanName.toLowerCase() !== "bearer")
27
+ continue;
28
+ const start = keys.lastIndex;
29
+ values.lastIndex = start;
30
+ let found = values.exec(text);
31
+ if (found?.[0] === "-p") {
32
+ values.lastIndex = start + 2 + (/^[\t ]*/.exec(text.slice(start + 2))?.[0].length ?? 0);
33
+ found = values.exec(text);
34
+ }
35
+ if (!found && text[start] !== "\n" && text[start] !== "\r" && start !== text.length)
36
+ continue;
37
+ const end = found ? values.lastIndex : start;
38
+ parts.push(text.slice(copied, start), "[redacted]");
39
+ copied = end;
40
+ keys.lastIndex = end;
41
+ }
42
+ parts.push(text.slice(copied));
43
+ text = parts.join("");
44
+ // Recognizable credential formats are excised, never inferred from the
45
+ // length/base64 shape of ordinary paths or used to refuse a continuation.
46
+ return text.replace(/-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----[\s\S]*?(?:-----END (?:[A-Z0-9 ]+ )?PRIVATE KEY-----|$)|\b(?:AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{22,}|AIza[0-9A-Za-z_-]{35}|sk-ant-api\d{2}-[\w-]{10,}|sk-proj-[\w-]{30,}|[sp]k_live_[A-Za-z0-9]{24,}|npm_[A-Za-z0-9]{36}|xox[bp]-[0-9]+-[A-Za-z0-9-]+)|(?<![\w-])eyJ[\w-]+\.[\w-]+\.[\w-]+|https:\/\/hooks\.slack\.com\/services\/T\w+\/B\w+\/\w+/g, "[redacted]");
47
+ }
48
+ const proseFields = new Set(["text", "prompt", "reply", "error", "message", "notice", "reason", "description", "title", "label", "question", "request"]);
49
+ /** Conductor operation envelopes contain prose beside opaque routing data. */
50
+ export function redactPeerPayload(data) {
51
+ return JSON.parse(JSON.stringify(data, (key, value) => typeof value === "string" && proseFields.has(key) ? redactPeerHandoff(value) : value));
52
+ }
@@ -417,7 +417,7 @@ export async function webServers() {
417
417
  const servers = await serversCache.get("listeners", scanWebServers);
418
418
  if (!servers.some(server => server.pid !== undefined) || Date.now() - (scanStarted.get(servers) ?? 0) < LISTENER_TRUST_MS)
419
419
  return servers;
420
- const live = await readListeners().catch(() => undefined);
420
+ const live = await sharedListeners();
421
421
  // The table could not be read (ss timed out, no lsof): ownership cannot be verified, so none is claimed.
422
422
  if (!live)
423
423
  return servers.map(({ pid: _pid, ...server }) => ({ ...server, unverified: true }));
@@ -426,6 +426,11 @@ export async function webServers() {
426
426
  serversCache.invalidate(() => true);
427
427
  return kept;
428
428
  }
429
+ /** Concurrent ownership checks share one socket-table read; a read is never reused once it has settled. */
430
+ let listenersInFlight;
431
+ function sharedListeners() {
432
+ return listenersInFlight ??= readListeners().catch(() => undefined).finally(() => { listenersInFlight = undefined; });
433
+ }
429
434
  /** The key `addListener` files a server under: its host with the port always spelled out (a URL's host drops the default one). */
430
435
  export function listenerKey(server) {
431
436
  return `${server.origin.includes("[::1]") ? "[::1]" : "127.0.0.1"}:${server.port}`;
@@ -459,13 +464,13 @@ async function scanWebServers() {
459
464
  .sort((a, b) => Number(a.port >= EPHEMERAL_PORT) - Number(b.port >= EPHEMERAL_PORT) || a.port - b.port)
460
465
  .slice(0, 64);
461
466
  const found = [];
462
- for (let i = 0; i < candidates.length; i += 8) {
463
- await Promise.all(candidates.slice(i, i + 8).map(async (server) => {
464
- const name = await probe(server.port, server.origin.includes("[::1]") ? "::1" : "127.0.0.1");
465
- if (name !== null)
466
- found.push({ ...server, name });
467
- }));
468
- }
467
+ // Every probe is bounded (1.2 s) and loopback-only, so they all run at once: in groups of eight
468
+ // a handful of listeners that accept and never answer cost 1.2 s per group.
469
+ await Promise.all(candidates.map(async (server) => {
470
+ const name = await probe(server.port, server.origin.includes("[::1]") ? "::1" : "127.0.0.1");
471
+ if (name !== null)
472
+ found.push({ ...server, name });
473
+ }));
469
474
  const listing = found.sort((a, b) => a.port - b.port);
470
475
  scanStarted.set(listing, started);
471
476
  return listing;
@@ -4,3 +4,9 @@ import type { Json } from "./protocol.js";
4
4
  * peer origin. Peer keys are forced through the peer scope, which rebuilds
5
5
  * the request with its own origin header; MCP calls carry an agent origin. */
6
6
  export declare function ownerRequest(request: Pick<IncomingMessage, "headers">, data: Json): boolean;
7
+ export interface PeerIdentity {
8
+ name?: string;
9
+ id?: string;
10
+ fingerprint: string;
11
+ }
12
+ export declare function requestPeer(request: Pick<IncomingMessage, "headers">): PeerIdentity | undefined;
@@ -4,3 +4,23 @@
4
4
  export function ownerRequest(request, data) {
5
5
  return request.headers?.["x-phren-origin"] === undefined && data.origin === undefined;
6
6
  }
7
+ export function requestPeer(request) {
8
+ if (request.headers?.["x-phren-origin"] !== "peer")
9
+ return undefined;
10
+ const encoded = request.headers?.["x-phren-peer"];
11
+ if (typeof encoded !== "string")
12
+ return undefined;
13
+ try {
14
+ const value = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
15
+ if (!/^[a-f0-9]{64}$/.test(value.fingerprint) || value.id !== undefined && !/^[a-f0-9-]{36}$/i.test(value.id))
16
+ return undefined;
17
+ if (value.name !== undefined && (typeof value.name !== "string" || !/^[A-Za-z0-9_.-]{1,253}$/.test(value.name)))
18
+ return undefined;
19
+ if (value.name === undefined && value.id === undefined)
20
+ return undefined;
21
+ return { ...(value.name ? { name: value.name } : {}), ...(value.id ? { id: value.id } : {}), fingerprint: value.fingerprint };
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
@@ -1,3 +1,4 @@
1
+ import { type PeerIdentity } from "./request-origin.js";
1
2
  import type { Readable, Writable } from "node:stream";
2
3
  export declare const GATEWAY_SCOPES: readonly ["gitboy-read", "gitboy-write"];
3
4
  export type GatewayScope = typeof GATEWAY_SCOPES[number];
@@ -18,7 +19,7 @@ export type Admission = {
18
19
  export declare function admitScopedRequest(scope: GatewayScope, rawHead: string, rest?: Buffer): Admission;
19
20
  /** A computer key's forced scope rebuilds the HTTP envelope. Client headers
20
21
  * cannot impersonate the owner gateway, and peer keys cannot open terminals. */
21
- export declare function admitPeerRequest(rawHead: string, rest?: Buffer): Admission;
22
+ export declare function admitPeerRequest(rawHead: string, rest?: Buffer, identity?: PeerIdentity): Admission;
22
23
  export interface ScopedIO {
23
24
  input: Readable;
24
25
  output: Writable;
@@ -1,3 +1,5 @@
1
+ import { hookPeers } from "./peers.js";
2
+ import { peerFingerprint } from "./dispatch-hosts.js";
1
3
  import { connect } from "node:net";
2
4
  import { BridgeError } from "./protocol.js";
3
5
  import { findingWriteSchema, taskCompleteSchema, isBranchName, isRepoPath, isSearchText, MAX_FILE_PATHS, MAX_FINDING_BODY, PROJECT_NAME, } from "./gitboy-contract.js";
@@ -167,7 +169,7 @@ export function admitScopedRequest(scope, rawHead, rest = Buffer.alloc(0)) {
167
169
  }
168
170
  /** A computer key's forced scope rebuilds the HTTP envelope. Client headers
169
171
  * cannot impersonate the owner gateway, and peer keys cannot open terminals. */
170
- export function admitPeerRequest(rawHead, rest = Buffer.alloc(0)) {
172
+ export function admitPeerRequest(rawHead, rest = Buffer.alloc(0), identity) {
171
173
  const head = parseHead(rawHead);
172
174
  if ("ok" in head)
173
175
  return head;
@@ -179,7 +181,7 @@ export function admitPeerRequest(rawHead, rest = Buffer.alloc(0)) {
179
181
  return refuse(415, "Send Content-Type: application/json.");
180
182
  const body = rest.toString("utf8");
181
183
  const target = head.path + (head.query === null ? "" : `?${head.query}`);
182
- return { ok: true, request: `${head.method} ${target} HTTP/1.1\r\nHost: phren.local\r\nX-Phren-Origin: peer\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}` };
184
+ return { ok: true, request: `${head.method} ${target} HTTP/1.1\r\nHost: phren.local\r\nX-Phren-Origin: peer\r\n${identity ? `X-Phren-Peer: ${Buffer.from(JSON.stringify(identity)).toString("base64url")}\r\n` : ""}Connection: close\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}` };
183
185
  }
184
186
  const REASONS = { 400: "Bad Request", 403: "Forbidden", 408: "Request Timeout", 413: "Content Too Large", 415: "Unsupported Media Type", 503: "Service Unavailable" };
185
187
  function httpResponse(status, error) {
@@ -232,12 +234,23 @@ function readRequest(scope, input) {
232
234
  * reads a normal response.
233
235
  */
234
236
  export async function scopedDispatch(scope, command, io) {
237
+ let identity;
238
+ if (scope.startsWith("peer:")) {
239
+ const peer = (await hookPeers().catch(() => [])).find(peer => peer.name === scope.slice(5));
240
+ // The forced-command enrollment binds this client key to the reverse
241
+ // host-key + OS account pin. The Hook verifies its stable computer ID
242
+ // over that pin when authorizing a move. Do not probe here: two gateways
243
+ // probing one another's /health would recursively open SSH sessions.
244
+ if (peer)
245
+ identity = { name: peer.name, fingerprint: peerFingerprint(peer) };
246
+ scope = "peer";
247
+ }
235
248
  if (scope !== "peer" && !isGatewayScope(scope))
236
249
  throw new BridgeError(403, "Unknown key scope.");
237
250
  if (command !== SCOPED_COMMAND)
238
251
  throw new BridgeError(403, `This SSH key only permits \`${SCOPED_COMMAND}\` with ${scope === "peer" ? "Hook API requests" : DESCRIBE[scope]}.`);
239
252
  const read = await readRequest(scope, io.input);
240
- const admission = "head" in read ? (scope === "peer" ? admitPeerRequest(read.head, read.rest) : admitScopedRequest(scope, read.head, read.rest)) : refuse(read.status, read.error);
253
+ const admission = "head" in read ? (scope === "peer" ? admitPeerRequest(read.head, read.rest, identity) : admitScopedRequest(scope, read.head, read.rest)) : refuse(read.status, read.error);
241
254
  if (!admission.ok) {
242
255
  await new Promise(done => io.output.write(httpResponse(admission.status, admission.error), () => done()));
243
256
  return;
@@ -42,6 +42,8 @@ type InventoryReader = () => Promise<HarnessInventory>;
42
42
  /** Only for tests: what this computer can launch. Without one, `PHREN_LAUNCH_CHECK=off` skips the early availability check. */
43
43
  export declare function setLaunchInventory(reader: InventoryReader | undefined): void;
44
44
  export interface LaunchOptions {
45
+ /** Persist a newly created pane before starting or prompting its harness. */
46
+ onPlaced?: (paneTarget: Json) => Promise<void>;
45
47
  canary?: boolean;
46
48
  /** `data.cwd` is a folder the Hook resolved itself (a dispatched or
47
49
  * scheduled project's source folder), so it may be marked trusted for the
@@ -172,6 +172,7 @@ export async function localConductor(known) {
172
172
  /** Refuses a second conductor in this computer's set: a live one here on
173
173
  * another pane, or on any member. Members that could not say come back as `unchecked`. */
174
174
  async function requireNoConductor(server, before, except) {
175
+ (await import("./conductor-role.js")).assertRoleMutable(await readRoleState());
175
176
  const existing = await localConductor({ server, snapshot: before });
176
177
  if (existing && !(except && existing.server === server && existing.target?.pane === except)) {
177
178
  throw new BridgeError(409, "A conductor is already running on this computer. Stop it first.", { target: existing.target });
@@ -520,6 +521,7 @@ async function startSession(server, data, options) {
520
521
  if (!created)
521
522
  throw new BridgeError(409, `${terminalName(server)} created "${label}" but its pane did not appear. Check ${terminalName(server)} on the computer.`);
522
523
  const place = { workspace: created.workspaceId, tab: created.tabId, pane: created.paneId };
524
+ await options.onPlaced?.({ server, ...place, source: kind });
523
525
  const structuredLaunch = structured ? await codexServers.launch({ server, ...place }, { cwd, ...(model ? { model } : {}),
524
526
  ...(data.effort === undefined ? {} : { effort }), env: { ...(terminalProvider().paneEnv?.(server, place) ?? {}), ...(env ?? {}) },
525
527
  ...(brief ? { dispatchId: brief.id } : {}), startThread: !!brief, ...(permissionMode ? { remoteArgs: codexModeFlags(permissionMode) } : {}) }).catch(error => {
@@ -1,3 +1,4 @@
1
+ import type { ConductorSuccessionService } from "./conductor-succession.js";
1
2
  import type { StorePulls } from "./store-pull.js";
2
3
  import type { GitboyWebhooks } from "./gitboy-webhooks.js";
3
4
  import { type SessionMover } from "./session-move.js";
@@ -61,6 +62,7 @@ export interface RouteContext {
61
62
  handOffs?: HandOffQueue;
62
63
  inbox?: OwnerInbox;
63
64
  mover?: SessionMover;
65
+ succession?: ConductorSuccessionService;
64
66
  agentHooks: AgentHooks;
65
67
  journal: ActivityJournal;
66
68
  tabActivity: TabActivityStore;
@@ -140,6 +142,10 @@ export declare const capabilities: {
140
142
  sessionMove: boolean;
141
143
  moveNewChat: boolean;
142
144
  moveConductor: boolean;
145
+ moveToComputer: boolean;
146
+ moveConductorToComputer: boolean;
147
+ claudeAccountAdd: boolean;
148
+ workerRelocation: number;
143
149
  projectMemory: boolean;
144
150
  fileWrite: boolean;
145
151
  fileSearch: boolean;