@phren/cli 0.2.16 → 0.3.1

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 (102) hide show
  1. package/dist/bridge/agent-hooks.d.ts +17 -6
  2. package/dist/bridge/agent-hooks.js +59 -24
  3. package/dist/bridge/claude-question-dialog.d.ts +65 -0
  4. package/dist/bridge/claude-question-dialog.js +210 -0
  5. package/dist/bridge/code-note.d.ts +2 -1
  6. package/dist/bridge/code-note.js +13 -4
  7. package/dist/bridge/code-routes.d.ts +32 -14
  8. package/dist/bridge/code-routes.js +131 -8
  9. package/dist/bridge/command.js +92 -2
  10. package/dist/bridge/computers.d.ts +5 -0
  11. package/dist/bridge/computers.js +10 -4
  12. package/dist/bridge/conductor-group.d.ts +23 -0
  13. package/dist/bridge/conductor-group.js +25 -0
  14. package/dist/bridge/dispatch-returns.d.ts +2 -0
  15. package/dist/bridge/dispatch-returns.js +12 -8
  16. package/dist/bridge/dispatch.d.ts +4 -1
  17. package/dist/bridge/dispatch.js +30 -5
  18. package/dist/bridge/hand-off.js +5 -1
  19. package/dist/bridge/herdr.d.ts +7 -0
  20. package/dist/bridge/herdr.js +53 -2
  21. package/dist/bridge/install.d.ts +0 -4
  22. package/dist/bridge/install.js +3 -3
  23. package/dist/bridge/link.d.ts +48 -0
  24. package/dist/bridge/link.js +136 -0
  25. package/dist/bridge/memory-store.d.ts +23 -0
  26. package/dist/bridge/memory-store.js +152 -0
  27. package/dist/bridge/pair.d.ts +46 -0
  28. package/dist/bridge/pair.js +240 -0
  29. package/dist/bridge/peers.d.ts +9 -0
  30. package/dist/bridge/peers.js +25 -2
  31. package/dist/bridge/protocol.js +20 -1
  32. package/dist/bridge/schedule-watch.d.ts +2 -0
  33. package/dist/bridge/schedule-watch.js +16 -3
  34. package/dist/bridge/server-launch.d.ts +9 -0
  35. package/dist/bridge/server-launch.js +34 -11
  36. package/dist/bridge/server-pane-routes.d.ts +7 -0
  37. package/dist/bridge/server-pane-routes.js +128 -18
  38. package/dist/bridge/server-routes.d.ts +3 -0
  39. package/dist/bridge/server-routes.js +55 -29
  40. package/dist/bridge/server-stream.js +4 -1
  41. package/dist/bridge/speech-key.d.ts +33 -0
  42. package/dist/bridge/speech-key.js +106 -0
  43. package/dist/bridge/speech-transcribe.js +1 -1
  44. package/dist/bridge/speech.d.ts +1 -3
  45. package/dist/bridge/speech.js +2 -16
  46. package/dist/bridge/transcript-preview.d.ts +2 -0
  47. package/dist/bridge/transcript-preview.js +15 -0
  48. package/dist/bridge-hook.mjs +9940 -3601
  49. package/dist/cli/config-policy.js +25 -0
  50. package/dist/cli/extract.d.ts +0 -8
  51. package/dist/cli/extract.js +1 -1
  52. package/dist/cli-handlers.js +6 -0
  53. package/dist/cli-registry.js +21 -9
  54. package/dist/content/learning.js +1 -1
  55. package/dist/content/validate.d.ts +14 -3
  56. package/dist/content/validate.js +174 -114
  57. package/dist/data/access.d.ts +9 -0
  58. package/dist/data/access.js +18 -0
  59. package/dist/data/tasks.d.ts +26 -0
  60. package/dist/data/tasks.js +72 -1
  61. package/dist/entrypoint.js +7 -0
  62. package/dist/generated/memory-ui-graph.browser.js +520 -410
  63. package/dist/governance/policy.js +4 -3
  64. package/dist/governance/rbac.d.ts +1 -1
  65. package/dist/governance/rbac.js +1 -0
  66. package/dist/hooks.d.ts +0 -15
  67. package/dist/hooks.js +1 -1
  68. package/dist/init/init-uninstall.js +13 -3
  69. package/dist/init/init-walkthrough.d.ts +10 -0
  70. package/dist/init/init-walkthrough.js +24 -1
  71. package/dist/init/init.d.ts +5 -0
  72. package/dist/init/init.js +54 -32
  73. package/dist/init/setup.js +19 -5
  74. package/dist/init/store-gitignore.d.ts +0 -5
  75. package/dist/init/store-gitignore.js +0 -8
  76. package/dist/link/context-imports.d.ts +15 -0
  77. package/dist/link/context-imports.js +101 -0
  78. package/dist/link/doctor.js +38 -4
  79. package/dist/mcp/profile.d.ts +0 -4
  80. package/dist/mcp/profile.js +2 -14
  81. package/dist/memory-ui-graph.runtime.js +520 -410
  82. package/dist/modules/code-package.js +10 -2
  83. package/dist/modules/config.d.ts +7 -0
  84. package/dist/modules/config.js +17 -0
  85. package/dist/modules/registry.js +6 -5
  86. package/dist/profile-store.js +39 -3
  87. package/dist/project-topics.d.ts +1 -0
  88. package/dist/project-topics.js +9 -6
  89. package/dist/shared/retrieval.d.ts +0 -2
  90. package/dist/shared/retrieval.js +1 -1
  91. package/dist/sync/task-claim.d.ts +22 -0
  92. package/dist/sync/task-claim.js +45 -0
  93. package/dist/tools/code.js +29 -21
  94. package/dist/tools/config.js +3 -0
  95. package/dist/tools/dispatch.js +3 -3
  96. package/dist/tools/finding.d.ts +11 -0
  97. package/dist/tools/finding.js +154 -99
  98. package/dist/tools/tasks.js +40 -1
  99. package/dist/ui/server.js +18 -1
  100. package/dist/update.js +21 -10
  101. package/package.json +8 -7
  102. package/starter/global/skills/conductor/SKILL.md +42 -10
@@ -2,7 +2,7 @@ import { createHmac, randomBytes } from "node:crypto";
2
2
  import { execFile } from "node:child_process";
3
3
  import { connect } from "node:net";
4
4
  import { homedir } from "node:os";
5
- import { readdir, readlink, realpath, stat } from "node:fs/promises";
5
+ import { open, readdir, readlink, realpath, stat } from "node:fs/promises";
6
6
  import path from "node:path";
7
7
  import { promisify } from "node:util";
8
8
  import { BridgeError, id, object, objects, requestID, serverName, provider, sessionId } from "./protocol.js";
@@ -278,7 +278,9 @@ const identityKey = (server, pane, pids) => JSON.stringify([server, pane.pane_id
278
278
  * so a caller that also needs them does not ask Herdr a second time. */
279
279
  async function resolveIdentity(server, pane, fresh) {
280
280
  const reported = object(pane.agent_session);
281
- if (reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) {
281
+ // Copilot's report lags a conversation switch (see copilotForegroundSession);
282
+ // its own process log is read first and the report is the fallback.
283
+ if (pane.agent !== "copilot" && reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) {
282
284
  countIdentity("reported");
283
285
  return { sessionId: reported.value };
284
286
  }
@@ -299,7 +301,56 @@ async function resolveIdentity(server, pane, fresh) {
299
301
  export async function paneIdentity(server, pane, fresh = false) {
300
302
  return (await resolveIdentity(server, pane, fresh)).sessionId;
301
303
  }
304
+ const copilotHome = () => process.env.COPILOT_HOME || path.join(homedir(), ".copilot");
305
+ /** Copilot CLI changes conversation inside one process (/new, /clear,
306
+ * /resume) and runs its sessionStart hook only once that conversation's first
307
+ * prompt is submitted. Until then Herdr's reported session and the recorded
308
+ * binding still name the previous conversation, so a phone send aimed there
309
+ * lands in the new one and its UserPromptSubmit check refuses it, every time.
310
+ * The process log Copilot names by PID records each switch as it happens. */
311
+ export async function copilotForegroundSession(pids, home = copilotHome()) {
312
+ if (!pids.length)
313
+ return undefined;
314
+ const folder = path.join(home, "logs");
315
+ const names = await readdir(folder).catch(() => []);
316
+ const logs = names.filter(name => pids.some(pid => name.startsWith("process-") && name.endsWith(`-${pid}.log`)));
317
+ let current, latest = -1;
318
+ for (const name of logs) {
319
+ const file = await open(path.join(folder, name), "r").catch(() => undefined);
320
+ if (!file)
321
+ continue;
322
+ try {
323
+ // The switch lines are short and rare; the log's tail holds the last one.
324
+ const { size } = await file.stat(), length = Math.min(size, 262_144);
325
+ const { buffer, bytesRead } = await file.read(Buffer.alloc(length), 0, length, size - length);
326
+ const lines = [...buffer.subarray(0, bytesRead).toString("utf8").matchAll(/^(\S+) \[INFO\] (Registering|Unregistering) foreground session: ([0-9a-f-]{36})\s*$/gim)];
327
+ const last = lines.at(-1);
328
+ if (!last)
329
+ continue;
330
+ const at = Date.parse(last[1]);
331
+ if (at <= latest)
332
+ continue;
333
+ latest = at;
334
+ current = last[2] === "Registering" && sessionId.safeParse(last[3]).success ? last[3] : undefined;
335
+ }
336
+ finally {
337
+ await file.close();
338
+ }
339
+ }
340
+ return current;
341
+ }
302
342
  async function identityFromProcesses(server, pane, pids) {
343
+ if (pane.agent === "copilot") {
344
+ const current = await copilotForegroundSession(pids).catch(() => undefined);
345
+ // A conversation nothing was sent to yet has no transcript: the pane is
346
+ // starting, and its first prompt goes through the starting binding.
347
+ if (current)
348
+ return await stat(path.join(copilotHome(), "session-state", current, "events.jsonl"))
349
+ .then(() => ({ sessionId: current, noTranscriptLogs: false }), () => ({ noTranscriptLogs: true }));
350
+ const reported = object(pane.agent_session);
351
+ if (reported.kind === "id" && reported.agent === "copilot" && typeof reported.value === "string" && sessionId.safeParse(reported.value).success)
352
+ return { sessionId: reported.value, noTranscriptLogs: false };
353
+ }
303
354
  const files = await processLogs(pids);
304
355
  const candidates = files.flatMap(file => {
305
356
  const match = pane.agent === "codex" ? (/rollout-.*-([a-f0-9-]{36})\.jsonl$/i.exec(file) ?? /thread-writer-locks\/([a-f0-9-]{36})\.lock$/i.exec(file))
@@ -23,10 +23,6 @@ export declare function detectGateway(env?: NodeJS.ProcessEnv): Promise<GatewayK
23
23
  * socket through a tiny forwarder, so a loaded machine never pays for a fresh
24
24
  * node process; every other SSH command falls through to the node gateway. */
25
25
  export declare function gatewayScript(gateway: GatewayKind, environment: GatewayEnvironment): string;
26
- /** The launchd domain for the LaunchAgent: the GUI session when someone is
27
- * logged in at the screen, else the per-user background domain an SSH login
28
- * has (gui/<uid> does not exist there, so a bootstrap into it fails). */
29
- export declare function launchDomain(uid: number, guiSession: boolean): string;
30
26
  /** The commands that restart the Hook in `domain`, printed when launchd refuses. */
31
27
  export declare function launchCommands(domain: string, plist: string): string[];
32
28
  export declare function install(version: string, noService?: boolean): Promise<void>;
@@ -42,7 +42,7 @@ export function upgradeKeys(text) {
42
42
  let changed = 0;
43
43
  const result = text.split(/(?<=\n)/).map(line => {
44
44
  const parsed = keyOptions(line);
45
- if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-iphone\s*$/.test(parsed.rest))
45
+ if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest))
46
46
  return line;
47
47
  const old = /^command="(?:\/usr\/bin\/false|python3 ~\/\.local\/share\/phren\/chat-progress\.py|sh ~\/\.local\/share\/phren\/bridge\/dispatch)"$/;
48
48
  if (!parsed.options.some(option => old.test(option)))
@@ -114,7 +114,7 @@ async function activate(version) {
114
114
  /** The launchd domain for the LaunchAgent: the GUI session when someone is
115
115
  * logged in at the screen, else the per-user background domain an SSH login
116
116
  * has (gui/<uid> does not exist there, so a bootstrap into it fails). */
117
- export function launchDomain(uid, guiSession) {
117
+ function launchDomain(uid, guiSession) {
118
118
  return guiSession ? `gui/${uid}` : `user/${uid}`;
119
119
  }
120
120
  /** The commands that restart the Hook in `domain`, printed when launchd refuses. */
@@ -284,7 +284,7 @@ export async function uninstall() {
284
284
  await applyAgentHooks(await planAgentHooks(path.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
285
285
  await applyOpencodePlugin(true);
286
286
  // Preserve journal, settings, uploaded images, rollback version and SSH backups.
287
- console.log("Phren Hook stopped and its background service removed. Remove phren-iphone and phren-computer keys from authorized_keys to revoke device access. Local data remains in " + bridgeRoot());
287
+ console.log("Phren Hook stopped and its background service removed. Remove phren-iphone, phren-android and phren-computer keys from authorized_keys to revoke device access. Local data remains in " + bridgeRoot());
288
288
  }
289
289
  async function missingFile(operation) {
290
290
  try {
@@ -0,0 +1,48 @@
1
+ /** Concrete Host aliases from an ssh config: no patterns, no Git hosting services. */
2
+ export declare function sshConfigHosts(text: string): string[];
3
+ export interface ReachableComputer {
4
+ host: string;
5
+ computerId: string;
6
+ user: string;
7
+ client?: string;
8
+ }
9
+ /** Hosts from ~/.ssh/config and the store's machines.yaml that answer over ssh,
10
+ * run Phren Hook and are not this computer or an already linked peer. */
11
+ export declare function discoverComputers(options?: {
12
+ sshConfig?: string;
13
+ store?: string | null;
14
+ }): Promise<{
15
+ reachable: ReachableComputer[];
16
+ checked: string[];
17
+ }>;
18
+ export interface LinkResult {
19
+ name: string;
20
+ as: string;
21
+ local: {
22
+ added: boolean;
23
+ };
24
+ remote: {
25
+ added: boolean;
26
+ reachable: boolean;
27
+ error?: string;
28
+ };
29
+ reachable: boolean;
30
+ error?: string;
31
+ }
32
+ /**
33
+ * Links this computer and `host` in both directions over the owner's existing
34
+ * ssh login: each side's dispatch key is enrolled on the other, and each
35
+ * side's ed25519 host key is read over that login (never keyscanned) and
36
+ * pinned in the other's hooks.yaml. Both sides then check the link.
37
+ */
38
+ export declare function linkComputer(host: string, options?: {
39
+ name?: string;
40
+ as?: string;
41
+ backAddress?: string;
42
+ }): Promise<LinkResult>;
43
+ /** The receiving half of a link: pin the caller in hooks.yaml, then dial it back. */
44
+ export declare function addPeerFromLink(input: string): Promise<{
45
+ added: boolean;
46
+ reachable: boolean;
47
+ error?: string;
48
+ }>;
@@ -0,0 +1,136 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { homedir, hostname, userInfo } from "node:os";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { listMachines } from "../profile-store.js";
7
+ import { findPhrenPath } from "../phren-paths.js";
8
+ import { computerLabel } from "./hand-off.js";
9
+ import { localNames } from "./computer-names.js";
10
+ import { acceptComputer, computerName, enrollComputer, publicComputerKey } from "./computers.js";
11
+ import { addHookPeer, optionalHookPeers, peerRequest } from "./peers.js";
12
+ import { BridgeError, bridgeRoot, object } from "./protocol.js";
13
+ /**
14
+ * Computers the owner already reaches over plain ssh that run phren, and
15
+ * linking one in a single explicit step. Discovery only reports; nothing is
16
+ * linked until the owner runs `phren bridge link <host>`.
17
+ */
18
+ const exec = promisify(execFile);
19
+ // A non-login ssh shell often lacks Homebrew's node (macOS) or ~/.local/bin.
20
+ const REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"';
21
+ const GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
22
+ /** Concrete Host aliases from an ssh config: no patterns, no Git hosting services. */
23
+ export function sshConfigHosts(text) {
24
+ const hosts = [];
25
+ let block = [], skip = false;
26
+ const flush = () => { if (!skip)
27
+ hosts.push(...block); block = []; skip = false; };
28
+ for (const raw of text.split(/\r?\n/)) {
29
+ const match = /^\s*([A-Za-z]+)(?:\s*=\s*|\s+)(.+?)\s*$/.exec(raw.replace(/\s#.*$|^\s*#.*$/, ""));
30
+ if (!match)
31
+ continue;
32
+ const [key, value] = [match[1].toLowerCase(), match[2]];
33
+ if (key === "host" || key === "match") {
34
+ flush();
35
+ if (key === "host")
36
+ block = value.split(/\s+/).filter(alias => !/[*?!]/.test(alias));
37
+ }
38
+ else if (key === "hostname" && GIT_HOSTS.test(value))
39
+ skip = true;
40
+ }
41
+ flush();
42
+ return [...new Set(hosts.filter(alias => !GIT_HOSTS.test(alias)))];
43
+ }
44
+ async function ssh(host, command, input, timeout = 20_000) {
45
+ return new Promise((resolve, reject) => {
46
+ const child = execFile("ssh", ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", host, command], { timeout, maxBuffer: 1_048_576 }, (error, stdout, stderr) => {
47
+ if (error)
48
+ reject(new BridgeError(503, `ssh ${host}: ${(stderr || error.message).split("\n").find(Boolean)?.slice(0, 200) ?? "failed"}`));
49
+ else
50
+ resolve(stdout);
51
+ });
52
+ child.stdin?.end(input ?? "");
53
+ });
54
+ }
55
+ /** What a host reports over the owner's own ssh login: its Hook's computer id
56
+ * (present once Phren Hook is installed), login user and this computer's
57
+ * address as that host sees it. */
58
+ async function probe(host) {
59
+ 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%% *}"`, undefined, 12_000);
60
+ const field = (name) => new RegExp(`^${name}=(.*)$`, "m").exec(out)?.[1]?.trim() || undefined;
61
+ const computerId = field("id");
62
+ return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : undefined;
63
+ }
64
+ /** Hosts from ~/.ssh/config and the store's machines.yaml that answer over ssh,
65
+ * run Phren Hook and are not this computer or an already linked peer. */
66
+ export async function discoverComputers(options = {}) {
67
+ const config = options.sshConfig ?? await readFile(path.join(homedir(), ".ssh", "config"), "utf8").catch(() => "");
68
+ const store = options.store !== undefined ? options.store : findPhrenPath();
69
+ const machines = store ? listMachines(store) : undefined;
70
+ const { peers } = await optionalHookPeers();
71
+ const own = (await readFile(path.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
72
+ const known = new Set([...localNames(), ...peers.flatMap(peer => [peer.name, peer.address])].map(computerLabel));
73
+ const candidates = [...new Set([...sshConfigHosts(config), ...(machines?.ok ? Object.keys(machines.data) : [])])]
74
+ .filter(host => !known.has(computerLabel(host))).slice(0, 32);
75
+ // A linked peer registered under another name is still linked: match it by its Hook's computer id.
76
+ const [found, peerIds] = await Promise.all([
77
+ Promise.all(candidates.map(host => probe(host).catch(() => undefined))),
78
+ Promise.all(peers.map(peer => peerRequest(peer, "/v1/health").then(health => object(health.computer).id, () => undefined))),
79
+ ]);
80
+ const seen = new Set([own, ...peerIds.filter((id) => typeof id === "string")]);
81
+ const reachable = found.filter((item) => {
82
+ if (!item || seen.has(item.computerId))
83
+ return false;
84
+ seen.add(item.computerId);
85
+ return true;
86
+ });
87
+ return { reachable, checked: candidates };
88
+ }
89
+ function slugName(value) {
90
+ const label = computerLabel(value).replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^[^A-Za-z0-9_]+/, "") || "computer";
91
+ return computerName.parse(label.slice(0, 100));
92
+ }
93
+ /**
94
+ * Links this computer and `host` in both directions over the owner's existing
95
+ * ssh login: each side's dispatch key is enrolled on the other, and each
96
+ * side's ed25519 host key is read over that login (never keyscanned) and
97
+ * pinned in the other's hooks.yaml. Both sides then check the link.
98
+ */
99
+ export async function linkComputer(host, options = {}) {
100
+ const remote = await probe(host);
101
+ if (!remote)
102
+ throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
103
+ const own = (await readFile(path.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
104
+ if (remote.computerId === own)
105
+ throw new BridgeError(409, `${host} is this computer.`);
106
+ const name = computerName.parse(options.name ?? slugName(host));
107
+ const as = computerName.parse(options.as ?? slugName(hostname()));
108
+ const backAddress = options.backAddress ?? remote.client;
109
+ if (!backAddress)
110
+ throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
111
+ // The address the Hook dials skips ~/.ssh/config, so resolve the alias the way ssh does.
112
+ const resolved = Object.fromEntries((await exec("ssh", ["-G", "--", host], { timeout: 5_000 })).stdout.split("\n")
113
+ .map(line => line.split(" ")).filter(parts => parts.length >= 2).map(([key, ...rest]) => [key, rest.join(" ")]));
114
+ const remoteHostKey = publicComputerKey((await ssh(host, "cat /etc/ssh/ssh_host_ed25519_key.pub")).trim().split(/\s+/).slice(0, 2).join(" "));
115
+ const localHostKey = publicComputerKey((await readFile("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
116
+ const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
117
+ await ssh(host, `f=$(mktemp) && cat > "$f" && ${REMOTE_PATH} phren bridge enroll-computer ${as} --accept "$f"; s=$?; rm -f "$f"; exit $s`, await enrollComputer(as));
118
+ await acceptComputer(name, remoteLine);
119
+ const peer = { name, address: String(resolved.hostname || host), username: remote.user || String(resolved.user), port: Number(resolved.port) || 22, server: "default", hostKey: remoteHostKey };
120
+ const local = await addHookPeer(peer);
121
+ const back = { name: as, address: backAddress, username: userInfo().username, port: 22, server: "default", hostKey: localHostKey };
122
+ const answer = JSON.parse(await ssh(host, `${REMOTE_PATH} phren bridge add-peer`, JSON.stringify(back), 45_000).catch((error) => {
123
+ if (/Usage: phren bridge/.test(error.message))
124
+ 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.`);
125
+ throw error;
126
+ }));
127
+ const reached = await peerRequest(peer, "/v1/health").then(() => undefined, (error) => error.message);
128
+ return { name, as, local: { added: local.added }, remote: { added: !!answer.added, reachable: !!answer.reachable, ...(answer.error ? { error: String(answer.error) } : {}) },
129
+ reachable: !reached, ...(reached ? { error: reached } : {}) };
130
+ }
131
+ /** The receiving half of a link: pin the caller in hooks.yaml, then dial it back. */
132
+ export async function addPeerFromLink(input) {
133
+ const { added, peer } = await addHookPeer(JSON.parse(input));
134
+ const error = await peerRequest(peer, "/v1/health").then(() => undefined, (failure) => failure.message);
135
+ return { added, reachable: !error, ...(error ? { error } : {}) };
136
+ }
@@ -0,0 +1,23 @@
1
+ import { type Json } from "./protocol.js";
2
+ /** The sha git gives these bytes as a blob; GitHub reports the same one. */
3
+ export declare function blobSha(content: Buffer): string;
4
+ /** A tree sha for the store's current working tree, written through a private index. */
5
+ export declare function storeHead(store: string, indexFile?: string): Promise<{
6
+ sha: string;
7
+ }>;
8
+ /** The recursive tree for a head, with the fields the phone's GitTree decodes. */
9
+ export declare function storeTree(store: string, sha: string): Promise<Json>;
10
+ export declare function storeBlob(store: string, sha: string): Promise<Json>;
11
+ /** Resolve a store-relative path, refusing escapes, .git and symlinked parents. */
12
+ export declare function storeFile(store: string, relative: string): Promise<string>;
13
+ /** Write one file if it still has the sha the phone last saw (null: must not exist). */
14
+ export declare function putStoreFile(store: string, data: Json): Promise<Json>;
15
+ export declare function deleteStoreFile(store: string, data: Json): Promise<Json>;
16
+ export declare const STORE_ROUTES: {
17
+ readonly head: "/v1/store/head";
18
+ readonly tree: "/v1/store/tree";
19
+ readonly blob: "/v1/store/blob";
20
+ readonly file: "/v1/store/file";
21
+ readonly delete: "/v1/store/delete";
22
+ };
23
+ export declare function storeRoute(store: string, method: string, url: URL, data?: Json): Promise<Json>;
@@ -0,0 +1,152 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { lstat, mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { z } from "zod";
7
+ import { BridgeError, bridgeRoot } from "./protocol.js";
8
+ // The phone reads memory from a paired computer through these routes, in the
9
+ // same git terms its sync engine uses with GitHub: a head, a recursive tree,
10
+ // blobs by sha, and compare-and-swap file writes. The head is the store's
11
+ // working tree (committed or not), so the phone sees what agents on this
12
+ // computer see, and .gitignore keeps machine-local files off the phone.
13
+ const exec = promisify(execFile);
14
+ const SHA = /^[0-9a-f]{40}$/;
15
+ const MAX_FILE = 4 * 1024 * 1024;
16
+ let queue = Promise.resolve();
17
+ /** Serialize git work on the snapshot index; two phone polls share one index. */
18
+ function serialized(work) {
19
+ const next = queue.then(work, work);
20
+ queue = next.catch(() => undefined);
21
+ return next;
22
+ }
23
+ async function git(store, args, env = {}) {
24
+ try {
25
+ const { stdout } = await exec("git", ["-C", store, ...args], {
26
+ env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" }, maxBuffer: 64 * 1024 * 1024, timeout: 60_000,
27
+ });
28
+ return stdout;
29
+ }
30
+ catch (error) {
31
+ const stderr = String(error.stderr ?? "").trim();
32
+ throw new BridgeError(500, `git ${args[0]} failed in the store${stderr ? `: ${stderr.split("\n")[0]}` : "."}`);
33
+ }
34
+ }
35
+ /** The sha git gives these bytes as a blob; GitHub reports the same one. */
36
+ export function blobSha(content) {
37
+ return createHash("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
38
+ }
39
+ async function isRepository(store) {
40
+ return (await lstat(path.join(store, ".git")).catch(() => undefined)) !== undefined;
41
+ }
42
+ /** A tree sha for the store's current working tree, written through a private index. */
43
+ export function storeHead(store, indexFile = path.join(bridgeRoot(), "store-snapshot.index")) {
44
+ return serialized(async () => {
45
+ if (!await isRepository(store))
46
+ throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
47
+ await mkdir(path.dirname(indexFile), { recursive: true, mode: 0o700 });
48
+ const env = { GIT_INDEX_FILE: indexFile };
49
+ if (!await lstat(indexFile).catch(() => undefined)) {
50
+ const head = await git(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
51
+ await git(store, head.trim() ? ["read-tree", "HEAD"] : ["read-tree", "--empty"], env);
52
+ }
53
+ await git(store, ["add", "--all", "--", "."], env);
54
+ return { sha: (await git(store, ["write-tree"], env)).trim() };
55
+ });
56
+ }
57
+ /** The recursive tree for a head, with the fields the phone's GitTree decodes. */
58
+ export async function storeTree(store, sha) {
59
+ if (!SHA.test(sha))
60
+ throw new BridgeError(400, "Invalid tree sha.");
61
+ if ((await git(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "tree")
62
+ throw new BridgeError(404, "Unknown tree.");
63
+ const tree = (await git(store, ["ls-tree", "-r", "-l", "-z", sha])).split("\0").filter(Boolean).flatMap(line => {
64
+ const match = /^(\d+) (\w+) ([0-9a-f]{40}) +(\d+|-)\t(.+)$/s.exec(line);
65
+ // Symlinks and submodules never reach the phone.
66
+ if (!match || match[2] !== "blob" || match[1] === "120000")
67
+ return [];
68
+ return [{ path: match[5], type: "blob", sha: match[3], size: Number(match[4]) }];
69
+ });
70
+ return { sha, truncated: false, tree };
71
+ }
72
+ export async function storeBlob(store, sha) {
73
+ if (!SHA.test(sha))
74
+ throw new BridgeError(400, "Invalid blob sha.");
75
+ if ((await git(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "blob")
76
+ throw new BridgeError(404, "Unknown blob.");
77
+ const { stdout } = await exec("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE * 4 });
78
+ return { sha, encoding: "base64", content: stdout.toString("base64") };
79
+ }
80
+ /** Resolve a store-relative path, refusing escapes, .git and symlinked parents. */
81
+ export async function storeFile(store, relative) {
82
+ const normalized = path.posix.normalize(relative);
83
+ if (!relative || relative !== normalized || normalized.startsWith("../") || normalized === ".." || path.posix.isAbsolute(normalized)
84
+ || normalized.split("/").some(part => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
85
+ throw new BridgeError(400, "Invalid store path.");
86
+ }
87
+ const root = await realpath(store);
88
+ let parent = path.dirname(path.join(root, normalized));
89
+ // Missing parents are created later; the nearest existing one must stay inside the store.
90
+ for (;;) {
91
+ const real = await realpath(parent).catch(() => undefined);
92
+ if (real) {
93
+ if (real !== root && !real.startsWith(root + path.sep))
94
+ throw new BridgeError(400, "Invalid store path.");
95
+ break;
96
+ }
97
+ parent = path.dirname(parent);
98
+ }
99
+ const file = path.join(root, normalized);
100
+ const info = await lstat(file).catch(() => undefined);
101
+ if (info && !info.isFile())
102
+ throw new BridgeError(400, "Invalid store path.");
103
+ return file;
104
+ }
105
+ async function currentSha(file) {
106
+ const content = await readFile(file).catch((error) => { if (error.code === "ENOENT")
107
+ return null; throw error; });
108
+ return content === null ? null : blobSha(content);
109
+ }
110
+ const putSchema = z.object({ path: z.string().max(1024), content: z.string(), sha: z.string().regex(SHA).nullable().optional() });
111
+ const deleteSchema = z.object({ path: z.string().max(1024), sha: z.string().regex(SHA) });
112
+ /** Write one file if it still has the sha the phone last saw (null: must not exist). */
113
+ export function putStoreFile(store, data) {
114
+ const input = putSchema.parse(data);
115
+ const content = Buffer.from(input.content, "base64");
116
+ if (content.length > MAX_FILE)
117
+ throw new BridgeError(413, "This file is too large for the phone to write.");
118
+ return serialized(async () => {
119
+ const file = await storeFile(store, input.path);
120
+ if (await currentSha(file) !== (input.sha ?? null))
121
+ throw new BridgeError(409, `${input.path} changed on this computer.`);
122
+ await mkdir(path.dirname(file), { recursive: true });
123
+ const temporary = `${file}.phren-${process.pid}-${Date.now()}`;
124
+ await writeFile(temporary, content, { flag: "wx" });
125
+ await rename(temporary, file);
126
+ return { content: { sha: blobSha(content), path: input.path }, commit: { sha: blobSha(content) } };
127
+ });
128
+ }
129
+ export function deleteStoreFile(store, data) {
130
+ const input = deleteSchema.parse(data);
131
+ return serialized(async () => {
132
+ const file = await storeFile(store, input.path);
133
+ if (await currentSha(file) !== input.sha)
134
+ throw new BridgeError(409, `${input.path} changed on this computer.`);
135
+ await rm(file);
136
+ return { ok: true };
137
+ });
138
+ }
139
+ export const STORE_ROUTES = { head: "/v1/store/head", tree: "/v1/store/tree", blob: "/v1/store/blob", file: "/v1/store/file", delete: "/v1/store/delete" };
140
+ export async function storeRoute(store, method, url, data) {
141
+ if (method === "GET" && url.pathname === STORE_ROUTES.head)
142
+ return storeHead(store);
143
+ if (method === "GET" && url.pathname === STORE_ROUTES.tree)
144
+ return storeTree(store, url.searchParams.get("sha") ?? "");
145
+ if (method === "GET" && url.pathname === STORE_ROUTES.blob)
146
+ return storeBlob(store, url.searchParams.get("sha") ?? "");
147
+ if (method === "POST" && url.pathname === STORE_ROUTES.file)
148
+ return putStoreFile(store, data ?? {});
149
+ if (method === "POST" && url.pathname === STORE_ROUTES.delete)
150
+ return deleteStoreFile(store, data ?? {});
151
+ throw new BridgeError(404, "Unknown Phren Hook route.");
152
+ }
@@ -0,0 +1,46 @@
1
+ export declare const PAIR_PORT = 47291;
2
+ export declare function newPairingCode(): string;
3
+ /** Codes are typed as ABC-234 or abc234; both mean the same code. */
4
+ export declare function normalizeCode(code: string): string;
5
+ export declare function pairingProof(code: string, label: "phone" | "computer", ...parts: string[]): string;
6
+ /** OpenSSH's SHA256 fingerprint of a public key line, as the phone computes it. */
7
+ export declare function keyFingerprint(publicKeyLine: string): string | undefined;
8
+ export declare function hostFingerprint(file?: string): Promise<string | undefined>;
9
+ /** Addresses the phone can try, best first: Tailscale name and address, then LAN IPv4. */
10
+ export declare function pairingHosts(): Promise<string[]>;
11
+ /** The name people call this computer: macOS's Computer Name, else the host name. */
12
+ export declare function computerDisplayName(): Promise<string>;
13
+ export interface PairingOffer {
14
+ hosts: string[];
15
+ port: number;
16
+ user: string;
17
+ sshPort: number;
18
+ fingerprint?: string;
19
+ code: string;
20
+ name: string;
21
+ }
22
+ /** The QR payload; the phone opens phren://pair links from the camera too. */
23
+ export declare function pairingURL(offer: PairingOffer): string;
24
+ export interface Paired {
25
+ device: "ios" | "android";
26
+ name?: string;
27
+ publicKey: string;
28
+ }
29
+ export interface PairingSession {
30
+ port: number;
31
+ done: Promise<Paired>;
32
+ close(): void;
33
+ }
34
+ /** Listen for one phone. Resolves once its key is authorized; rejects on timeout or too many bad proofs. */
35
+ export declare function startPairing(options: {
36
+ code: string;
37
+ user: string;
38
+ sshPort: number;
39
+ fingerprint?: string;
40
+ name: string;
41
+ port?: number;
42
+ timeoutMs?: number;
43
+ sshDirectory?: string;
44
+ }): Promise<PairingSession>;
45
+ export declare const PAIR_USAGE = "phren pair [--minutes <1-30>] [--port <n>] [--no-install]";
46
+ export declare function runPair(args: string[], version: string): Promise<number>;