@phren/cli 0.3.52 → 0.3.54

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 (51) 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/hand-off-queue.d.ts +3 -0
  21. package/dist/bridge/hand-off-queue.js +8 -0
  22. package/dist/bridge/hand-off.d.ts +13 -0
  23. package/dist/bridge/hand-off.js +20 -1
  24. package/dist/bridge/install.js +0 -6
  25. package/dist/bridge/launch-brief.d.ts +2 -0
  26. package/dist/bridge/launch-brief.js +19 -8
  27. package/dist/bridge/move-computers.d.ts +47 -0
  28. package/dist/bridge/move-computers.js +118 -0
  29. package/dist/bridge/peer-handoff.d.ts +5 -0
  30. package/dist/bridge/peer-handoff.js +52 -0
  31. package/dist/bridge/request-origin.d.ts +6 -0
  32. package/dist/bridge/request-origin.js +20 -0
  33. package/dist/bridge/scoped-gateway.d.ts +2 -1
  34. package/dist/bridge/scoped-gateway.js +16 -3
  35. package/dist/bridge/server-launch.d.ts +2 -0
  36. package/dist/bridge/server-launch.js +63 -2
  37. package/dist/bridge/server-routes.d.ts +6 -0
  38. package/dist/bridge/server-routes.js +228 -15
  39. package/dist/bridge/server.js +39 -12
  40. package/dist/bridge/session-move.d.ts +28 -1
  41. package/dist/bridge/session-move.js +269 -26
  42. package/dist/bridge/terminal-herdr.js +14 -0
  43. package/dist/bridge/terminal-tmux.js +1 -0
  44. package/dist/bridge/terminal.d.ts +2 -0
  45. package/dist/bridge/terminal.js +6 -0
  46. package/dist/bridge/worker-relocation.d.ts +5 -0
  47. package/dist/bridge/worker-relocation.js +33 -0
  48. package/dist/bridge-hook.mjs +16386 -14258
  49. package/dist/modules/registry.js +8 -8
  50. package/dist/tools/dispatch.js +2 -1
  51. package/package.json +1 -1
@@ -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
+ }
@@ -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
@@ -26,6 +26,7 @@ import { optionalHookPeers } from "./peers.js";
26
26
  import { AppServerRpcError, AppServerUnsupportedError } from "./codex-app-server.js";
27
27
  import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
28
28
  import { logger } from "../logger.js";
29
+ import { stripTerminal } from "../terminal-text.js";
29
30
  import { JobRegistry } from "./job-registry.js";
30
31
  import { atomic, BridgeError, id, launchEfforts, objects, PERMISSION_MODES, provider } from "./protocol.js";
31
32
  import { CLAUDE_NAMES, CODEX_MODES, codexModeFlags, copilotModeFlags } from "./settings-switch.js";
@@ -171,6 +172,7 @@ export async function localConductor(known) {
171
172
  /** Refuses a second conductor in this computer's set: a live one here on
172
173
  * another pane, or on any member. Members that could not say come back as `unchecked`. */
173
174
  async function requireNoConductor(server, before, except) {
175
+ (await import("./conductor-role.js")).assertRoleMutable(await readRoleState());
174
176
  const existing = await localConductor({ server, snapshot: before });
175
177
  if (existing && !(except && existing.server === server && existing.target?.pane === except)) {
176
178
  throw new BridgeError(409, "A conductor is already running on this computer. Stop it first.", { target: existing.target });
@@ -237,6 +239,61 @@ async function startWhenShellReady(server, pane, agent) {
237
239
  }
238
240
  }
239
241
  }
242
+ /** Retry only a demonstrated exit, and serialize starters: neither terminal
243
+ * provider supports cancelling a start already submitted to its server. */
244
+ async function startCodex(server, pane, agent) {
245
+ const terminal = terminalProvider();
246
+ const screenText = async () => stripTerminal(await terminal.readScreen?.(server, pane, { scope: "pane", source: "recent", lines: 20 }).catch(() => "") ?? "").trim();
247
+ for (let attempt = 0; attempt < 2; attempt++) {
248
+ const before = await screenText();
249
+ const deadline = Date.now() + agent.timeoutMs;
250
+ let ran = false;
251
+ let result;
252
+ const starting = startWhenShellReady(server, pane, agent).then(() => { result = {}; ran = true; }, error => { result = { error }; });
253
+ try {
254
+ for (;;) {
255
+ await Promise.race([starting, new Promise(resolve => setTimeout(resolve, 250))]);
256
+ const processes = await terminal.processes?.(server, pane).catch(() => undefined);
257
+ const state = await terminal.snapshot(server);
258
+ const current = objects(state.panes).find(row => row.pane_id === pane);
259
+ const shell = processes?.shellPid;
260
+ const atShell = processes !== undefined && shell !== undefined && processes.foregroundPids.every(pid => pid === shell);
261
+ if (processes && !atShell && current?.agent === "codex")
262
+ ran = true;
263
+ if (atShell) {
264
+ const screen = await screenText();
265
+ const exitMessage = screen !== before && /please restart codex|codex exited(?: at start)?/i.test(screen);
266
+ if (ran || exitMessage) {
267
+ // A screen or process observation cannot cancel a pending start.
268
+ // Wait for it, then observe again: it might still launch Codex.
269
+ if (!result) {
270
+ await starting;
271
+ continue;
272
+ }
273
+ if (attempt === 0)
274
+ break;
275
+ const last = screen.split(/\r?\n/).map(line => line.trim()).filter(Boolean).at(-1);
276
+ throw new BridgeError(409, `Codex exited at start: ${last || "process returned to its shell"}`);
277
+ }
278
+ }
279
+ if (result && "error" in result)
280
+ throw result.error;
281
+ if (result) {
282
+ if (!processes || ["idle", "working", "blocked", "waiting"].includes(String(current?.agent_status)) || Date.now() >= deadline)
283
+ return;
284
+ await new Promise(resolve => setTimeout(resolve, 250));
285
+ }
286
+ else if (Date.now() >= deadline) {
287
+ await starting;
288
+ }
289
+ }
290
+ }
291
+ finally {
292
+ // Even a failed process/snapshot read must not leave a starter behind.
293
+ await starting;
294
+ }
295
+ }
296
+ }
240
297
  /** The Herdr agent-name slug for a human label: "Conductor smoke 4" becomes "conductor-smoke-4". */
241
298
  export function herdrAgentName(label) {
242
299
  const slug = label.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "").slice(0, 32).replace(/-+$/, "");
@@ -464,6 +521,7 @@ async function startSession(server, data, options) {
464
521
  if (!created)
465
522
  throw new BridgeError(409, `${terminalName(server)} created "${label}" but its pane did not appear. Check ${terminalName(server)} on the computer.`);
466
523
  const place = { workspace: created.workspaceId, tab: created.tabId, pane: created.paneId };
524
+ await options.onPlaced?.({ server, ...place, source: kind });
467
525
  const structuredLaunch = structured ? await codexServers.launch({ server, ...place }, { cwd, ...(model ? { model } : {}),
468
526
  ...(data.effort === undefined ? {} : { effort }), env: { ...(terminalProvider().paneEnv?.(server, place) ?? {}), ...(env ?? {}) },
469
527
  ...(brief ? { dispatchId: brief.id } : {}), startThread: !!brief, ...(permissionMode ? { remoteArgs: codexModeFlags(permissionMode) } : {}) }).catch(error => {
@@ -494,13 +552,16 @@ async function startSession(server, data, options) {
494
552
  briefTurn = error instanceof AppServerRpcError ? undefined : "uncertain";
495
553
  }
496
554
  }
497
- const agentArgs = structuredLaunch ? structuredLaunch.args : [...args, ...(briefLaunch ?? [])];
555
+ const agentArgs = [...(structuredLaunch ? structuredLaunch.args : [...args, ...(briefLaunch ?? [])]),
556
+ ...(kind === "codex" ? ["-c", "check_for_update_on_startup=false"] : [])];
498
557
  try {
499
- await startWhenShellReady(server, created.paneId, { name, kind, args: agentArgs, timeoutMs: timeout, ...(env ? { env } : {}) });
558
+ await (kind === "codex" ? startCodex : startWhenShellReady)(server, created.paneId, { name, kind, args: agentArgs, timeoutMs: timeout, ...(env ? { env } : {}) });
500
559
  }
501
560
  catch (error) {
502
561
  if (appServer && !agentNotReady(error))
503
562
  await codexServers.stop(appServer).catch(() => undefined);
563
+ if (error instanceof BridgeError && error.message.startsWith("Codex exited at start:"))
564
+ throw error;
504
565
  // A first-run screen (Claude's folder trust, a login notice) holds the
505
566
  // agent at startup. It did start: hand the pane back so the owner answers
506
567
  // that screen from the chat instead of stranding the workspace.
@@ -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;