@phren/cli 0.3.39 → 0.3.40

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.
@@ -1,3 +1,4 @@
1
+ import { type LinkResult, linkComputer } from "./link.js";
1
2
  import { type Json } from "./protocol.js";
2
3
  /** The Hook routes for linked computer sets (docs/conductor-sets.md). */
3
4
  interface LocalInfo {
@@ -17,4 +18,8 @@ export declare function readSets(info: LocalInfo): Promise<Json>;
17
18
  * on to every reachable member; a member's relay (with `namedAt`) is kept
18
19
  * when newer than the name held, and goes no further. */
19
20
  export declare function nameSet(data: Json): Promise<Json>;
21
+ /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
22
+ * on the computer whose set lists `name` as indirect or one-way, over this
23
+ * computer's own ssh login, one link at a time. */
24
+ export declare function linkSetMember(data: Json, link?: typeof linkComputer): Promise<LinkResult>;
20
25
  export {};
@@ -1,11 +1,12 @@
1
1
  import { z } from "zod";
2
- import { askPeers, buildSets, indirectMembers, localCaller } from "./conductor-group.js";
3
- import { readSetName, saveSetName } from "./conductor-role.js";
4
2
  import { computerLabel, readComputers } from "./computer-identity.js";
5
3
  import { localNames } from "./computer-names.js";
4
+ import { askPeers, buildSets, indirectMembers, localCaller } from "./conductor-group.js";
5
+ import { readSetName, saveSetName } from "./conductor-role.js";
6
6
  import { listsCaller } from "./health.js";
7
+ import { linkComputer } from "./link.js";
7
8
  import { optionalHookPeers, peerRequest } from "./peers.js";
8
- import { object } from "./protocol.js";
9
+ import { BridgeError, object } from "./protocol.js";
9
10
  import { localConductor } from "./server-launch.js";
10
11
  const callerSchema = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() });
11
12
  /** `GET /v1/conductor`: this computer's live conductor and what a peer needs
@@ -77,3 +78,22 @@ export async function nameSet(data) {
77
78
  }));
78
79
  return { ok: true, name: input.name, namedAt, told: told.sort(), unreachable: unreachable.sort((a, b) => a.computer.localeCompare(b.computer)) };
79
80
  }
81
+ const linkInput = z.object({ name: z.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,252}$/, "A computer name or ssh host.") }).strict();
82
+ let linking;
83
+ /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
84
+ * on the computer whose set lists `name` as indirect or one-way, over this
85
+ * computer's own ssh login, one link at a time. */
86
+ export async function linkSetMember(data, link = linkComputer) {
87
+ if (data && typeof data === "object" && "origin" in data)
88
+ throw new BridgeError(403, "Only the owner links computers, from the phone or `phren bridge link` in their own terminal.");
89
+ const { name } = linkInput.parse(data);
90
+ if (linking)
91
+ throw new BridgeError(409, `Already linking ${linking}. Try again when it finishes.`);
92
+ linking = name;
93
+ try {
94
+ return await link(name);
95
+ }
96
+ finally {
97
+ linking = undefined;
98
+ }
99
+ }
@@ -106,11 +106,29 @@ export async function candidateRepos(activity, env = process.env) {
106
106
  return undefined;
107
107
  }
108
108
  };
109
+ // The journal repeats a few folders hundreds of times: one git call each.
110
+ const roots = new Map();
111
+ const rootOf = (directory) => {
112
+ let root = roots.get(directory);
113
+ if (!root) {
114
+ root = toplevel(directory);
115
+ roots.set(directory, root);
116
+ }
117
+ return root;
118
+ };
119
+ const activityDirectory = (event) => typeof event.directory === "string" && path.isAbsolute(event.directory) ? event.directory : undefined;
120
+ // Look the folders up eight at a time: a folder where git stalls (macOS can
121
+ // hold ~/Downloads from a background process) costs its 5 s timeout once.
122
+ const pending = [...new Set(activity.map(activityDirectory).filter((d) => !!d))];
123
+ await Promise.all(Array.from({ length: Math.min(8, pending.length) }, async () => {
124
+ for (let directory = pending.shift(); directory !== undefined; directory = pending.shift())
125
+ await rootOf(directory);
126
+ }));
109
127
  for (const event of [...activity].reverse()) {
110
- const directory = typeof event.directory === "string" ? event.directory : undefined;
111
- if (!directory || !path.isAbsolute(directory))
128
+ const directory = activityDirectory(event);
129
+ if (!directory)
112
130
  continue;
113
- const root = await toplevel(directory);
131
+ const root = await rootOf(directory);
114
132
  if (root)
115
133
  await offer(root, "activity", typeof event.at === "string" ? event.at : undefined);
116
134
  }
@@ -120,7 +138,7 @@ export async function candidateRepos(activity, env = process.env) {
120
138
  const directory = JSON.parse(`"${match[1]}"`);
121
139
  if (!path.isAbsolute(directory))
122
140
  continue;
123
- const root = await toplevel(directory);
141
+ const root = await rootOf(directory);
124
142
  if (root)
125
143
  await offer(root, "herdr");
126
144
  }
@@ -105,6 +105,7 @@ export declare const capabilities: {
105
105
  sideQuestions: boolean;
106
106
  dispatch: boolean;
107
107
  conductorSets: boolean;
108
+ setLink: boolean;
108
109
  ownerInbox: boolean;
109
110
  workerReports: boolean;
110
111
  queuedHandOff: boolean;
@@ -46,7 +46,7 @@ import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
46
46
  import { gitRepository, paneRoute, uploadBody } from "./server-pane-routes.js";
47
47
  import { renameSession } from "./session-rename.js";
48
48
  import { launchSession, makeConductor, stopConductor, workspaceAction } from "./server-launch.js";
49
- import { conductorAnswer, nameSet, readSets } from "./conductor-sets.js";
49
+ import { conductorAnswer, linkSetMember, nameSet, readSets } from "./conductor-sets.js";
50
50
  import { conductorPane } from "./conductor-role.js";
51
51
  import { hookMetrics } from "./metrics.js";
52
52
  import { SPEECH_FORMATS, streamSpeech } from "./speech.js";
@@ -78,7 +78,7 @@ async function childActivity(source, session) {
78
78
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
79
79
  terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
80
80
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
81
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true };
81
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true };
82
82
  export function capabilitiesForModules(snapshot) {
83
83
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
84
84
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -829,6 +829,9 @@ export function createRouteHandler(ctx) {
829
829
  else if (url.pathname === "/v1/sets/name") {
830
830
  result = await nameSet(data);
831
831
  }
832
+ else if (url.pathname === "/v1/sets/link") {
833
+ result = await linkSetMember(data);
834
+ }
832
835
  else if (url.pathname === "/v1/push/register") {
833
836
  // Registration is kept for when a key is added; the reply says whether push works now.
834
837
  await agentHooks.push.register(data);
@@ -37849,7 +37849,7 @@ var init_package_metadata = __esm({
37849
37849
  __dirname = path37.dirname(fileURLToPath2(import.meta.url));
37850
37850
  ROOT = path37.join(__dirname, "..");
37851
37851
  PACKAGE_JSON_PATH = path37.join(ROOT, "package.json");
37852
- BUNDLED_VERSION = true ? "0.3.39" : "0.0.0";
37852
+ BUNDLED_VERSION = true ? "0.3.40" : "0.0.0";
37853
37853
  PACKAGE_JSON = readPackageJson();
37854
37854
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
37855
37855
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -39150,10 +39150,10 @@ var init_registry = __esm({
39150
39150
  agentHooks: [],
39151
39151
  hookRoutes: [
39152
39152
  ...routes("GET", ["/v1/dispatch", "/v1/dispatch/capacity", "/v1/dispatch/arrival", "/v1/dispatch/brief", "/v1/conductor", "/v1/conductor/grants", "/v1/computers", "/v1/sets", "/v1/authority", "/v1/owner-inbox", "/v1/conductor/integrator"]),
39153
- ...routes("POST", ["/v1/dispatch", "/v1/dispatch/workers", "/v1/dispatch/returns", "/v1/dispatch/approve", "/v1/dispatch/report", "/v1/dispatch/close", "/v1/owner-inbox", "/v1/conductor/integrator", "/v1/hand-off", "/v1/hand-off/status", "/v1/conductor/grants", "/v1/conductor/make", "/v1/conductor/stop", "/v1/sets/name", "/v1/authority", "/v1/authority/confirm"]),
39153
+ ...routes("POST", ["/v1/dispatch", "/v1/dispatch/workers", "/v1/dispatch/returns", "/v1/dispatch/approve", "/v1/dispatch/report", "/v1/dispatch/close", "/v1/owner-inbox", "/v1/conductor/integrator", "/v1/hand-off", "/v1/hand-off/status", "/v1/conductor/grants", "/v1/conductor/make", "/v1/conductor/stop", "/v1/sets/name", "/v1/sets/link", "/v1/authority", "/v1/authority/confirm"]),
39154
39154
  ...routes("DELETE", ["/v1/conductor/grants", "/v1/authority"])
39155
39155
  ],
39156
- capabilities: ["dispatch", "conductorSets", "ownerInbox", "workerReports", "queuedHandOff"],
39156
+ capabilities: ["dispatch", "conductorSets", "setLink", "ownerInbox", "workerReports", "queuedHandOff"],
39157
39157
  storeFiles: ["global/skills/conductor/**"],
39158
39158
  localFiles: ["<bridge>/hooks.yaml", "<bridge>/conductor.yaml", "<bridge>/conductor-role.json", "<bridge>/conductor/brief.md", "<bridge>/authority.yaml", "<bridge>/authority-confirmations.json", "<bridge>/dispatches/*.json", "<bridge>/hand-offs/*.json", "<bridge>/worker-reports/*.json", "<bridge>/closed-workers/*.json", "<bridge>/owner-inbox.json", "<bridge>/integrator.json"],
39159
39159
  phoneScreens: [],
@@ -66033,10 +66033,24 @@ async function candidateRepos(activity, env = process.env) {
66033
66033
  return void 0;
66034
66034
  }
66035
66035
  };
66036
+ const roots = /* @__PURE__ */ new Map();
66037
+ const rootOf = (directory) => {
66038
+ let root = roots.get(directory);
66039
+ if (!root) {
66040
+ root = toplevel(directory);
66041
+ roots.set(directory, root);
66042
+ }
66043
+ return root;
66044
+ };
66045
+ const activityDirectory = (event) => typeof event.directory === "string" && path125.isAbsolute(event.directory) ? event.directory : void 0;
66046
+ const pending = [...new Set(activity.map(activityDirectory).filter((d) => !!d))];
66047
+ await Promise.all(Array.from({ length: Math.min(8, pending.length) }, async () => {
66048
+ for (let directory = pending.shift(); directory !== void 0; directory = pending.shift()) await rootOf(directory);
66049
+ }));
66036
66050
  for (const event of [...activity].reverse()) {
66037
- const directory = typeof event.directory === "string" ? event.directory : void 0;
66038
- if (!directory || !path125.isAbsolute(directory)) continue;
66039
- const root = await toplevel(directory);
66051
+ const directory = activityDirectory(event);
66052
+ if (!directory) continue;
66053
+ const root = await rootOf(directory);
66040
66054
  if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
66041
66055
  }
66042
66056
  try {
@@ -66044,7 +66058,7 @@ async function candidateRepos(activity, env = process.env) {
66044
66058
  for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
66045
66059
  const directory = JSON.parse(`"${match[1]}"`);
66046
66060
  if (!path125.isAbsolute(directory)) continue;
66047
- const root = await toplevel(directory);
66061
+ const root = await rootOf(directory);
66048
66062
  if (root) await offer(root, "herdr");
66049
66063
  }
66050
66064
  } catch {
@@ -71911,6 +71925,135 @@ var init_session_rename = __esm({
71911
71925
  }
71912
71926
  });
71913
71927
 
71928
+ // src/bridge/link.ts
71929
+ import { execFile as execFile29 } from "node:child_process";
71930
+ import { readFile as readFile55 } from "node:fs/promises";
71931
+ import { homedir as homedir21, hostname as hostname12, userInfo as userInfo5 } from "node:os";
71932
+ import path135 from "node:path";
71933
+ import { promisify as promisify27 } from "node:util";
71934
+ function sshConfigHosts(text5) {
71935
+ const hosts = [];
71936
+ let block = [], skip = false;
71937
+ const flush = () => {
71938
+ if (!skip) hosts.push(...block);
71939
+ block = [];
71940
+ skip = false;
71941
+ };
71942
+ for (const raw of text5.split(/\r?\n/)) {
71943
+ const match = /^\s*([A-Za-z]+)(?:\s*=\s*|\s+)(.+?)\s*$/.exec(raw.replace(/\s#.*$|^\s*#.*$/, ""));
71944
+ if (!match) continue;
71945
+ const [key4, value2] = [match[1].toLowerCase(), match[2]];
71946
+ if (key4 === "host" || key4 === "match") {
71947
+ flush();
71948
+ if (key4 === "host") block = value2.split(/\s+/).filter((alias) => !/[*?!]/.test(alias));
71949
+ } else if (key4 === "hostname" && GIT_HOSTS.test(value2)) skip = true;
71950
+ }
71951
+ flush();
71952
+ return [...new Set(hosts.filter((alias) => !GIT_HOSTS.test(alias)))];
71953
+ }
71954
+ async function ssh(host, command, input2, timeout = 2e4) {
71955
+ return new Promise((resolve16, reject) => {
71956
+ const child = execFile29(
71957
+ "ssh",
71958
+ ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", host, command],
71959
+ { timeout, maxBuffer: 1048576 },
71960
+ (error62, stdout, stderr) => {
71961
+ if (error62) reject(new BridgeError(503, `ssh ${host}: ${(stderr || error62.message).split("\n").find(Boolean)?.slice(0, 200) ?? "failed"}`));
71962
+ else resolve16(stdout);
71963
+ }
71964
+ );
71965
+ child.stdin?.end(input2 ?? "");
71966
+ });
71967
+ }
71968
+ async function probe2(host) {
71969
+ const out = await ssh(host, `printf 'id=%s\\nuser=%s\\nclient=%s\\n' "$(cat ~/.local/share/phren/bridge/computer-id 2>/dev/null)" "$(id -un)" "\${SSH_CONNECTION%% *}"`, void 0, 12e3);
71970
+ const field = (name) => new RegExp(`^${name}=(.*)$`, "m").exec(out)?.[1]?.trim() || void 0;
71971
+ const computerId = field("id");
71972
+ return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
71973
+ }
71974
+ async function discoverComputers(options = {}) {
71975
+ const config4 = options.sshConfig ?? await readFile55(path135.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
71976
+ const store = options.store !== void 0 ? options.store : findPhrenPath();
71977
+ const machines = store ? listMachines(store) : void 0;
71978
+ const { peers } = await optionalHookPeers();
71979
+ const own2 = (await readFile55(path135.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
71980
+ const known2 = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
71981
+ const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config4), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known2.has(computerLabel(host))).slice(0, 32);
71982
+ const [found, peerIds] = await Promise.all([
71983
+ Promise.all(candidates.map((host) => probe2(host).catch(() => void 0))),
71984
+ Promise.all(peers.map((peer) => peerRequest(peer, "/v1/health").then((health2) => object2(health2.computer).id, () => void 0)))
71985
+ ]);
71986
+ const seen = /* @__PURE__ */ new Set([own2, ...peerIds.filter((id2) => typeof id2 === "string")]);
71987
+ const reachable = found.filter((item) => {
71988
+ if (!item || seen.has(item.computerId)) return false;
71989
+ seen.add(item.computerId);
71990
+ return true;
71991
+ });
71992
+ return { reachable, checked: candidates };
71993
+ }
71994
+ function slugName(value2) {
71995
+ const label2 = computerLabel(value2).replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^[^A-Za-z0-9_]+/, "") || "computer";
71996
+ return computerName.parse(label2.slice(0, 100));
71997
+ }
71998
+ async function linkComputer(host, options = {}) {
71999
+ const remote = await probe2(host);
72000
+ if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
72001
+ const own2 = (await readFile55(path135.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
72002
+ if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
72003
+ const name = computerName.parse(options.name ?? slugName(host));
72004
+ const as2 = computerName.parse(options.as ?? slugName(hostname12()));
72005
+ const backAddress = options.backAddress ?? remote.client;
72006
+ if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
72007
+ const resolved = Object.fromEntries((await exec25("ssh", ["-G", "--", host], { timeout: 5e3 })).stdout.split("\n").map((line) => line.split(" ")).filter((parts) => parts.length >= 2).map(([key4, ...rest]) => [key4, rest.join(" ")]));
72008
+ const remoteKeyLine = hostKeyLine(await ssh(host, hostKeyScript()));
72009
+ if (!remoteKeyLine) throw noHostKey(host);
72010
+ const localLine = await localHostKeyLine();
72011
+ if (!localLine) throw noHostKey("This computer");
72012
+ const remoteHostKey = publicComputerKey(remoteKeyLine.split(/\s+/).slice(0, 2).join(" "));
72013
+ const localHostKey = publicComputerKey(localLine.split(/\s+/).slice(0, 2).join(" "));
72014
+ const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
72015
+ await ssh(host, `f=$(mktemp) && cat > "$f" && ${REMOTE_PATH} phren bridge enroll-computer ${as2} --accept "$f"; s=$?; rm -f "$f"; exit $s`, await enrollComputer(as2));
72016
+ await acceptComputer(name, remoteLine);
72017
+ const peer = { name, address: String(resolved.hostname || host), username: remote.user || String(resolved.user), port: Number(resolved.port) || 22, server: "default", hostKey: remoteHostKey };
72018
+ const local = await addHookPeer(peer);
72019
+ const back = { name: as2, address: backAddress, username: userInfo5().username, port: 22, server: "default", hostKey: localHostKey };
72020
+ const answer = JSON.parse(await ssh(host, `${REMOTE_PATH} phren bridge add-peer`, JSON.stringify(back), 45e3).catch((error62) => {
72021
+ if (/Usage: phren bridge/.test(error62.message)) throw new BridgeError(409, `phren on ${host} is too old to finish linking. Update it there and run this again; the keys already exchanged are reused.`);
72022
+ throw error62;
72023
+ }));
72024
+ const reached = await peerRequest(peer, "/v1/health").then(() => void 0, (error62) => error62.message);
72025
+ return {
72026
+ name,
72027
+ as: as2,
72028
+ local: { added: local.added },
72029
+ remote: { added: !!answer.added, reachable: !!answer.reachable, ...answer.error ? { error: String(answer.error) } : {} },
72030
+ reachable: !reached,
72031
+ ...reached ? { error: reached } : {}
72032
+ };
72033
+ }
72034
+ async function addPeerFromLink(input2) {
72035
+ const { added, peer } = await addHookPeer(JSON.parse(input2));
72036
+ const error62 = await peerRequest(peer, "/v1/health").then(() => void 0, (failure2) => failure2.message);
72037
+ return { added, reachable: !error62, ...error62 ? { error: error62 } : {} };
72038
+ }
72039
+ var exec25, REMOTE_PATH, GIT_HOSTS;
72040
+ var init_link = __esm({
72041
+ "src/bridge/link.ts"() {
72042
+ "use strict";
72043
+ init_profile_store();
72044
+ init_phren_paths();
72045
+ init_hand_off();
72046
+ init_computer_names();
72047
+ init_computers();
72048
+ init_host_key();
72049
+ init_peers();
72050
+ init_protocol();
72051
+ exec25 = promisify27(execFile29);
72052
+ REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/opt/bin:$PATH"';
72053
+ GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
72054
+ }
72055
+ });
72056
+
71914
72057
  // src/bridge/conductor-sets.ts
71915
72058
  async function conductorAnswer(info, url2) {
71916
72059
  const caller = callerSchema.parse({ name: url2.searchParams.get("name") ?? void 0, hostKey: url2.searchParams.get("hostKey") ?? void 0 });
@@ -71980,21 +72123,34 @@ async function nameSet(data) {
71980
72123
  }));
71981
72124
  return { ok: true, name: input2.name, namedAt, told: told.sort(), unreachable: unreachable.sort((a, b) => a.computer.localeCompare(b.computer)) };
71982
72125
  }
71983
- var callerSchema, setNameValue;
72126
+ async function linkSetMember(data, link = linkComputer) {
72127
+ if (data && typeof data === "object" && "origin" in data) throw new BridgeError(403, "Only the owner links computers, from the phone or `phren bridge link` in their own terminal.");
72128
+ const { name } = linkInput.parse(data);
72129
+ if (linking) throw new BridgeError(409, `Already linking ${linking}. Try again when it finishes.`);
72130
+ linking = name;
72131
+ try {
72132
+ return await link(name);
72133
+ } finally {
72134
+ linking = void 0;
72135
+ }
72136
+ }
72137
+ var callerSchema, setNameValue, linkInput, linking;
71984
72138
  var init_conductor_sets = __esm({
71985
72139
  "src/bridge/conductor-sets.ts"() {
71986
72140
  "use strict";
71987
72141
  init_zod();
71988
- init_conductor_group();
71989
- init_conductor_role();
71990
72142
  init_computer_identity();
71991
72143
  init_computer_names();
72144
+ init_conductor_group();
72145
+ init_conductor_role();
71992
72146
  init_health();
72147
+ init_link();
71993
72148
  init_peers();
71994
72149
  init_protocol();
71995
72150
  init_server_launch();
71996
72151
  callerSchema = external_exports.object({ name: external_exports.string().max(253).optional(), hostKey: external_exports.string().max(512).optional() });
71997
72152
  setNameValue = external_exports.string().trim().min(1).max(60).refine((t) => !/[\x00-\x1f\x7f]/.test(t)).nullable();
72153
+ linkInput = external_exports.object({ name: external_exports.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,252}$/, "A computer name or ssh host.") }).strict();
71998
72154
  }
71999
72155
  });
72000
72156
 
@@ -72023,7 +72179,7 @@ var init_mux_wire = __esm({
72023
72179
  });
72024
72180
 
72025
72181
  // src/bridge/server-routes.ts
72026
- import path135 from "node:path";
72182
+ import path136 from "node:path";
72027
72183
  async function childActivity(source, session) {
72028
72184
  const key4 = `${source}\0${session}`, now = Date.now(), cached3 = childActivityCache.get(key4);
72029
72185
  if (cached3 && (cached3.pending || now - cached3.at < CHILD_ACTIVITY_CACHE_MS)) return cached3.result;
@@ -72414,7 +72570,7 @@ function createRouteHandler(ctx) {
72414
72570
  case "/v1/files/range": {
72415
72571
  let root;
72416
72572
  if (url2.searchParams.get("scope") === "uploads") {
72417
- root = path135.join(bridgeRoot(), "uploads");
72573
+ root = path136.join(bridgeRoot(), "uploads");
72418
72574
  } else if (url2.searchParams.has("session")) {
72419
72575
  const target = targetFromURL(url2), pane = await validateTarget(target);
72420
72576
  const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
@@ -72721,6 +72877,8 @@ function createRouteHandler(ctx) {
72721
72877
  result = await launches.run(async () => stopConductor(data));
72722
72878
  } else if (url2.pathname === "/v1/sets/name") {
72723
72879
  result = await nameSet(data);
72880
+ } else if (url2.pathname === "/v1/sets/link") {
72881
+ result = await linkSetMember(data);
72724
72882
  } else if (url2.pathname === "/v1/push/register") {
72725
72883
  await agentHooks.push.register(data);
72726
72884
  result = { ok: true, configured: agentHooks.push.status.configured };
@@ -72893,6 +73051,7 @@ var init_server_routes = __esm({
72893
73051
  sideQuestions: true,
72894
73052
  dispatch: true,
72895
73053
  conductorSets: true,
73054
+ setLink: true,
72896
73055
  ownerInbox: true,
72897
73056
  workerReports: true,
72898
73057
  queuedHandOff: true,
@@ -73715,11 +73874,11 @@ var init_server_overview = __esm({
73715
73874
  });
73716
73875
 
73717
73876
  // src/bridge/codex-auth-refresh.ts
73718
- import { readFile as readFile55 } from "node:fs/promises";
73719
- import path136 from "node:path";
73720
- async function lastCodexRefresh(file4 = path136.join(codexHome(), "auth.json")) {
73877
+ import { readFile as readFile56 } from "node:fs/promises";
73878
+ import path137 from "node:path";
73879
+ async function lastCodexRefresh(file4 = path137.join(codexHome(), "auth.json")) {
73721
73880
  try {
73722
- const auth = object2(JSON.parse(await readFile55(file4, "utf8")));
73881
+ const auth = object2(JSON.parse(await readFile56(file4, "utf8")));
73723
73882
  if (!object2(auth.tokens).refresh_token) return void 0;
73724
73883
  const at2 = Date.parse(String(auth.last_refresh ?? ""));
73725
73884
  return Number.isFinite(at2) ? at2 : 0;
@@ -73775,11 +73934,11 @@ var init_codex_auth_refresh = __esm({
73775
73934
 
73776
73935
  // src/bridge/server.ts
73777
73936
  import { randomUUID as randomUUID29 } from "node:crypto";
73778
- import { chmod as chmod6, lstat as lstat36, mkdir as mkdir35, readFile as readFile56, rm as rm18, unlink as unlink10, writeFile as writeFile13 } from "node:fs/promises";
73937
+ import { chmod as chmod6, lstat as lstat36, mkdir as mkdir35, readFile as readFile57, rm as rm18, unlink as unlink10, writeFile as writeFile13 } from "node:fs/promises";
73779
73938
  import { readFileSync as readFileSync53 } from "node:fs";
73780
73939
  import { createServer as createServer4 } from "node:http";
73781
- import { cpus as cpus2, hostname as hostname12, loadavg as loadavg2 } from "node:os";
73782
- import path137 from "node:path";
73940
+ import { cpus as cpus2, hostname as hostname13, loadavg as loadavg2 } from "node:os";
73941
+ import path138 from "node:path";
73783
73942
  async function serve(version2, options = {}) {
73784
73943
  process.umask(63);
73785
73944
  const modules = activateModules(defaultPhrenPath(), void 0, true);
@@ -73789,9 +73948,9 @@ async function serve(version2, options = {}) {
73789
73948
  await mkdir35(root, { recursive: true, mode: 448 });
73790
73949
  await chmod6(root, 448);
73791
73950
  let computerID2;
73792
- const identityFile = path137.join(root, "computer-id");
73951
+ const identityFile = path138.join(root, "computer-id");
73793
73952
  try {
73794
- computerID2 = (await readFile56(identityFile, "utf8")).trim();
73953
+ computerID2 = (await readFile57(identityFile, "utf8")).trim();
73795
73954
  } catch {
73796
73955
  computerID2 = randomUUID29();
73797
73956
  await writeFile13(identityFile, computerID2, { flag: "wx", mode: 384 });
@@ -73808,7 +73967,7 @@ async function serve(version2, options = {}) {
73808
73967
  }) : void 0;
73809
73968
  const locatedDirectories = /* @__PURE__ */ new Set();
73810
73969
  const journal = new ActivityJournal();
73811
- const agentHooks = new AgentHooks(void 0, modules, path137.join(bridgeRoot(), "deliveries.json"));
73970
+ const agentHooks = new AgentHooks(void 0, modules, path138.join(bridgeRoot(), "deliveries.json"));
73812
73971
  const returns = dispatches ? new DispatchReturns({
73813
73972
  // Continue on another signed-in account when a Claude worker stops at its usage limit: opt-in, `phren config account-failover on`.
73814
73973
  failover: new AccountFailover({ rooms: () => dispatches.claudeRooms(), dispatch: (input2, origin, continues) => dispatches.dispatch(input2, origin, continues) }),
@@ -73910,7 +74069,7 @@ async function serve(version2, options = {}) {
73910
74069
  if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
73911
74070
  function gatewayTiming() {
73912
74071
  try {
73913
- const parsed = JSON.parse(readFileSync53(path137.join(root, "gateway.json"), "utf8"));
74072
+ const parsed = JSON.parse(readFileSync53(path138.join(root, "gateway.json"), "utf8"));
73914
74073
  if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
73915
74074
  } catch {
73916
74075
  }
@@ -73920,7 +74079,7 @@ async function serve(version2, options = {}) {
73920
74079
  product: "phren-hook",
73921
74080
  protocol: PROTOCOL,
73922
74081
  version: version2,
73923
- computer: { id: computerID2, name: hostname12(), aliases: localNames() },
74082
+ computer: { id: computerID2, name: hostname13(), aliases: localNames() },
73924
74083
  capabilities: activeCapabilities,
73925
74084
  modules: Object.fromEntries(modules.modules.map((module) => [module.name, module.version])),
73926
74085
  store: modules.store,
@@ -73956,7 +74115,7 @@ async function serve(version2, options = {}) {
73956
74115
  }
73957
74116
  const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
73958
74117
  };
73959
- if (modules.has("git")) await rm18(path137.join(root, "changes-scratch"), { recursive: true, force: true });
74118
+ if (modules.has("git")) await rm18(path138.join(root, "changes-scratch"), { recursive: true, force: true });
73960
74119
  const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
73961
74120
  const { stream } = streams;
73962
74121
  const overview = overviewStream({
@@ -74212,135 +74371,6 @@ var init_server = __esm({
74212
74371
  }
74213
74372
  });
74214
74373
 
74215
- // src/bridge/link.ts
74216
- import { execFile as execFile29 } from "node:child_process";
74217
- import { readFile as readFile57 } from "node:fs/promises";
74218
- import { homedir as homedir21, hostname as hostname13, userInfo as userInfo5 } from "node:os";
74219
- import path138 from "node:path";
74220
- import { promisify as promisify27 } from "node:util";
74221
- function sshConfigHosts(text5) {
74222
- const hosts = [];
74223
- let block = [], skip = false;
74224
- const flush = () => {
74225
- if (!skip) hosts.push(...block);
74226
- block = [];
74227
- skip = false;
74228
- };
74229
- for (const raw of text5.split(/\r?\n/)) {
74230
- const match = /^\s*([A-Za-z]+)(?:\s*=\s*|\s+)(.+?)\s*$/.exec(raw.replace(/\s#.*$|^\s*#.*$/, ""));
74231
- if (!match) continue;
74232
- const [key4, value2] = [match[1].toLowerCase(), match[2]];
74233
- if (key4 === "host" || key4 === "match") {
74234
- flush();
74235
- if (key4 === "host") block = value2.split(/\s+/).filter((alias) => !/[*?!]/.test(alias));
74236
- } else if (key4 === "hostname" && GIT_HOSTS.test(value2)) skip = true;
74237
- }
74238
- flush();
74239
- return [...new Set(hosts.filter((alias) => !GIT_HOSTS.test(alias)))];
74240
- }
74241
- async function ssh(host, command, input2, timeout = 2e4) {
74242
- return new Promise((resolve16, reject) => {
74243
- const child = execFile29(
74244
- "ssh",
74245
- ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", host, command],
74246
- { timeout, maxBuffer: 1048576 },
74247
- (error62, stdout, stderr) => {
74248
- if (error62) reject(new BridgeError(503, `ssh ${host}: ${(stderr || error62.message).split("\n").find(Boolean)?.slice(0, 200) ?? "failed"}`));
74249
- else resolve16(stdout);
74250
- }
74251
- );
74252
- child.stdin?.end(input2 ?? "");
74253
- });
74254
- }
74255
- async function probe2(host) {
74256
- const out = await ssh(host, `printf 'id=%s\\nuser=%s\\nclient=%s\\n' "$(cat ~/.local/share/phren/bridge/computer-id 2>/dev/null)" "$(id -un)" "\${SSH_CONNECTION%% *}"`, void 0, 12e3);
74257
- const field = (name) => new RegExp(`^${name}=(.*)$`, "m").exec(out)?.[1]?.trim() || void 0;
74258
- const computerId = field("id");
74259
- return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
74260
- }
74261
- async function discoverComputers(options = {}) {
74262
- const config4 = options.sshConfig ?? await readFile57(path138.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
74263
- const store = options.store !== void 0 ? options.store : findPhrenPath();
74264
- const machines = store ? listMachines(store) : void 0;
74265
- const { peers } = await optionalHookPeers();
74266
- const own2 = (await readFile57(path138.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
74267
- const known2 = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
74268
- const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config4), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known2.has(computerLabel(host))).slice(0, 32);
74269
- const [found, peerIds] = await Promise.all([
74270
- Promise.all(candidates.map((host) => probe2(host).catch(() => void 0))),
74271
- Promise.all(peers.map((peer) => peerRequest(peer, "/v1/health").then((health2) => object2(health2.computer).id, () => void 0)))
74272
- ]);
74273
- const seen = /* @__PURE__ */ new Set([own2, ...peerIds.filter((id2) => typeof id2 === "string")]);
74274
- const reachable = found.filter((item) => {
74275
- if (!item || seen.has(item.computerId)) return false;
74276
- seen.add(item.computerId);
74277
- return true;
74278
- });
74279
- return { reachable, checked: candidates };
74280
- }
74281
- function slugName(value2) {
74282
- const label2 = computerLabel(value2).replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^[^A-Za-z0-9_]+/, "") || "computer";
74283
- return computerName.parse(label2.slice(0, 100));
74284
- }
74285
- async function linkComputer(host, options = {}) {
74286
- const remote = await probe2(host);
74287
- if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
74288
- const own2 = (await readFile57(path138.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
74289
- if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
74290
- const name = computerName.parse(options.name ?? slugName(host));
74291
- const as2 = computerName.parse(options.as ?? slugName(hostname13()));
74292
- const backAddress = options.backAddress ?? remote.client;
74293
- if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
74294
- const resolved = Object.fromEntries((await exec25("ssh", ["-G", "--", host], { timeout: 5e3 })).stdout.split("\n").map((line) => line.split(" ")).filter((parts) => parts.length >= 2).map(([key4, ...rest]) => [key4, rest.join(" ")]));
74295
- const remoteKeyLine = hostKeyLine(await ssh(host, hostKeyScript()));
74296
- if (!remoteKeyLine) throw noHostKey(host);
74297
- const localLine = await localHostKeyLine();
74298
- if (!localLine) throw noHostKey("This computer");
74299
- const remoteHostKey = publicComputerKey(remoteKeyLine.split(/\s+/).slice(0, 2).join(" "));
74300
- const localHostKey = publicComputerKey(localLine.split(/\s+/).slice(0, 2).join(" "));
74301
- const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
74302
- await ssh(host, `f=$(mktemp) && cat > "$f" && ${REMOTE_PATH} phren bridge enroll-computer ${as2} --accept "$f"; s=$?; rm -f "$f"; exit $s`, await enrollComputer(as2));
74303
- await acceptComputer(name, remoteLine);
74304
- const peer = { name, address: String(resolved.hostname || host), username: remote.user || String(resolved.user), port: Number(resolved.port) || 22, server: "default", hostKey: remoteHostKey };
74305
- const local = await addHookPeer(peer);
74306
- const back = { name: as2, address: backAddress, username: userInfo5().username, port: 22, server: "default", hostKey: localHostKey };
74307
- const answer = JSON.parse(await ssh(host, `${REMOTE_PATH} phren bridge add-peer`, JSON.stringify(back), 45e3).catch((error62) => {
74308
- if (/Usage: phren bridge/.test(error62.message)) throw new BridgeError(409, `phren on ${host} is too old to finish linking. Update it there and run this again; the keys already exchanged are reused.`);
74309
- throw error62;
74310
- }));
74311
- const reached = await peerRequest(peer, "/v1/health").then(() => void 0, (error62) => error62.message);
74312
- return {
74313
- name,
74314
- as: as2,
74315
- local: { added: local.added },
74316
- remote: { added: !!answer.added, reachable: !!answer.reachable, ...answer.error ? { error: String(answer.error) } : {} },
74317
- reachable: !reached,
74318
- ...reached ? { error: reached } : {}
74319
- };
74320
- }
74321
- async function addPeerFromLink(input2) {
74322
- const { added, peer } = await addHookPeer(JSON.parse(input2));
74323
- const error62 = await peerRequest(peer, "/v1/health").then(() => void 0, (failure2) => failure2.message);
74324
- return { added, reachable: !error62, ...error62 ? { error: error62 } : {} };
74325
- }
74326
- var exec25, REMOTE_PATH, GIT_HOSTS;
74327
- var init_link = __esm({
74328
- "src/bridge/link.ts"() {
74329
- "use strict";
74330
- init_profile_store();
74331
- init_phren_paths();
74332
- init_hand_off();
74333
- init_computer_names();
74334
- init_computers();
74335
- init_host_key();
74336
- init_peers();
74337
- init_protocol();
74338
- exec25 = promisify27(execFile29);
74339
- REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/opt/bin:$PATH"';
74340
- GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
74341
- }
74342
- });
74343
-
74344
74374
  // src/bridge/device-enroll.ts
74345
74375
  var device_enroll_exports = {};
74346
74376
  __export(device_enroll_exports, {
@@ -74754,7 +74784,7 @@ async function main() {
74754
74784
  return askpass2(args[1]);
74755
74785
  }
74756
74786
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
74757
- return runBridge2(args, "0.3.39");
74787
+ return runBridge2(args, "0.3.40");
74758
74788
  }
74759
74789
  main().then((code) => {
74760
74790
  process.exitCode = code;
@@ -132,8 +132,8 @@ export const BUILTIN_MODULES = [
132
132
  schemaVersion: 1, name: "conductor", version: VERSION, defaultEnabled: false, requires: ["memory", "hook"],
133
133
  tools: full(["dispatch", "dispatch_returns", "dispatch_approve", "hand_off", "live_sessions", "account_usage", "authority", "dispatch_report", "owner_inbox", "move_session"]), cliCommands: ["dispatch", "dispatch status", "dispatch returns", "dispatch sessions", "dispatch usage", "dispatch report", "hand-off", "move", "conductor", "conductor grants", "conductor status", "conductor make", "conductor stop", "conductor sets", "conductor integrator", "owner-inbox", "authority", "bridge enroll-computer"], agentHooks: [],
134
134
  hookRoutes: [...routes("GET", ["/v1/dispatch", "/v1/dispatch/capacity", "/v1/dispatch/arrival", "/v1/dispatch/brief", "/v1/conductor", "/v1/conductor/grants", "/v1/computers", "/v1/sets", "/v1/authority", "/v1/owner-inbox", "/v1/conductor/integrator"]),
135
- ...routes("POST", ["/v1/dispatch", "/v1/dispatch/workers", "/v1/dispatch/returns", "/v1/dispatch/approve", "/v1/dispatch/report", "/v1/dispatch/close", "/v1/owner-inbox", "/v1/conductor/integrator", "/v1/hand-off", "/v1/hand-off/status", "/v1/conductor/grants", "/v1/conductor/make", "/v1/conductor/stop", "/v1/sets/name", "/v1/authority", "/v1/authority/confirm"]), ...routes("DELETE", ["/v1/conductor/grants", "/v1/authority"])],
136
- capabilities: ["dispatch", "conductorSets", "ownerInbox", "workerReports", "queuedHandOff"], storeFiles: ["global/skills/conductor/**"],
135
+ ...routes("POST", ["/v1/dispatch", "/v1/dispatch/workers", "/v1/dispatch/returns", "/v1/dispatch/approve", "/v1/dispatch/report", "/v1/dispatch/close", "/v1/owner-inbox", "/v1/conductor/integrator", "/v1/hand-off", "/v1/hand-off/status", "/v1/conductor/grants", "/v1/conductor/make", "/v1/conductor/stop", "/v1/sets/name", "/v1/sets/link", "/v1/authority", "/v1/authority/confirm"]), ...routes("DELETE", ["/v1/conductor/grants", "/v1/authority"])],
136
+ capabilities: ["dispatch", "conductorSets", "setLink", "ownerInbox", "workerReports", "queuedHandOff"], storeFiles: ["global/skills/conductor/**"],
137
137
  localFiles: ["<bridge>/hooks.yaml", "<bridge>/conductor.yaml", "<bridge>/conductor-role.json", "<bridge>/conductor/brief.md", "<bridge>/authority.yaml", "<bridge>/authority-confirmations.json", "<bridge>/dispatches/*.json", "<bridge>/hand-offs/*.json", "<bridge>/worker-reports/*.json", "<bridge>/closed-workers/*.json", "<bridge>/owner-inbox.json", "<bridge>/integrator.json"], phoneScreens: [], skills: ["conductor"],
138
138
  },
139
139
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.39",
3
+ "version": "0.3.40",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {