@phren/cli 0.3.0 → 0.3.2

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 (64) hide show
  1. package/dist/bridge/agent-hooks.d.ts +20 -6
  2. package/dist/bridge/agent-hooks.js +74 -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/command.d.ts +3 -2
  6. package/dist/bridge/command.js +97 -5
  7. package/dist/bridge/computers.d.ts +5 -0
  8. package/dist/bridge/computers.js +10 -4
  9. package/dist/bridge/conductor-group.d.ts +23 -0
  10. package/dist/bridge/conductor-group.js +25 -0
  11. package/dist/bridge/hand-off.js +5 -1
  12. package/dist/bridge/herdr.d.ts +7 -0
  13. package/dist/bridge/herdr.js +53 -2
  14. package/dist/bridge/link.d.ts +48 -0
  15. package/dist/bridge/link.js +136 -0
  16. package/dist/bridge/memory-store.d.ts +23 -0
  17. package/dist/bridge/memory-store.js +152 -0
  18. package/dist/bridge/pair.d.ts +46 -0
  19. package/dist/bridge/pair.js +240 -0
  20. package/dist/bridge/peers.d.ts +9 -0
  21. package/dist/bridge/peers.js +25 -2
  22. package/dist/bridge/push.d.ts +42 -3
  23. package/dist/bridge/push.js +90 -20
  24. package/dist/bridge/server-launch.d.ts +9 -0
  25. package/dist/bridge/server-launch.js +34 -11
  26. package/dist/bridge/server-pane-routes.js +45 -8
  27. package/dist/bridge/server-routes.d.ts +1 -0
  28. package/dist/bridge/server-routes.js +11 -3
  29. package/dist/bridge/server-stream.js +4 -1
  30. package/dist/bridge/speech-key.d.ts +33 -0
  31. package/dist/bridge/speech-key.js +106 -0
  32. package/dist/bridge/speech-transcribe.js +1 -1
  33. package/dist/bridge/speech.d.ts +7 -3
  34. package/dist/bridge/speech.js +36 -17
  35. package/dist/bridge-hook.mjs +1356 -514
  36. package/dist/cli/namespaces-store.js +21 -0
  37. package/dist/cli-handlers.js +6 -0
  38. package/dist/cli-registry.js +14 -2
  39. package/dist/content/learning.js +1 -1
  40. package/dist/data/tasks.d.ts +26 -0
  41. package/dist/data/tasks.js +72 -1
  42. package/dist/entrypoint.js +7 -0
  43. package/dist/governance/rbac.d.ts +1 -1
  44. package/dist/governance/rbac.js +1 -0
  45. package/dist/init/init-walkthrough.d.ts +10 -0
  46. package/dist/init/init-walkthrough.js +25 -2
  47. package/dist/init/init.d.ts +5 -0
  48. package/dist/init/init.js +54 -32
  49. package/dist/link/doctor.js +10 -0
  50. package/dist/link/link.js +9 -3
  51. package/dist/link/refresh.js +11 -10
  52. package/dist/mcp/profile.js +2 -1
  53. package/dist/modules/config.d.ts +7 -0
  54. package/dist/modules/config.js +17 -0
  55. package/dist/modules/registry.js +5 -4
  56. package/dist/sync/conflict-resolve.d.ts +1 -1
  57. package/dist/sync/conflict-resolve.js +44 -7
  58. package/dist/sync/task-claim.d.ts +22 -0
  59. package/dist/sync/task-claim.js +45 -0
  60. package/dist/tools/dispatch.js +2 -2
  61. package/dist/tools/search.js +1 -1
  62. package/dist/tools/tasks.js +40 -1
  63. package/package.json +2 -1
  64. package/starter/global/skills/conductor/SKILL.md +41 -9
@@ -0,0 +1,240 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash, createHmac, randomInt, timingSafeEqual } from "node:crypto";
3
+ import { lstat, readFile } from "node:fs/promises";
4
+ import { createServer } from "node:http";
5
+ import { connect } from "node:net";
6
+ import { homedir, hostname, networkInterfaces, userInfo } from "node:os";
7
+ import path from "node:path";
8
+ import { promisify } from "node:util";
9
+ import { z } from "zod";
10
+ import { appendAuthorizedKey, publicComputerKey } from "./computers.js";
11
+ import { forcedCommand, install } from "./install.js";
12
+ import { BridgeError, bridgeRoot } from "./protocol.js";
13
+ // `phren pair` connects a phone in one scan. The QR code carries where to
14
+ // reach this computer, its SSH host key fingerprint and a one-time code. The
15
+ // phone makes its own key and posts the public half here with an HMAC keyed
16
+ // by the code, so the code itself never crosses the network; this computer
17
+ // answers with an HMAC over its fingerprint, which lets a phone that typed
18
+ // the code by hand trust the host key too. One success, five bad proofs or
19
+ // the time limit closes the listener.
20
+ const exec = promisify(execFile);
21
+ export const PAIR_PORT = 47291;
22
+ const ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
23
+ const MAX_FAILURES = 5;
24
+ export function newPairingCode() {
25
+ return Array.from({ length: 6 }, () => ALPHABET[randomInt(ALPHABET.length)]).join("");
26
+ }
27
+ /** Codes are typed as ABC-234 or abc234; both mean the same code. */
28
+ export function normalizeCode(code) {
29
+ return code.toUpperCase().replace(/[^A-Z0-9]/g, "");
30
+ }
31
+ export function pairingProof(code, label, ...parts) {
32
+ return createHmac("sha256", `phren-pair-v1:${normalizeCode(code)}`).update([label, ...parts].join("\n")).digest("base64url");
33
+ }
34
+ function sameProof(expected, received) {
35
+ const a = Buffer.from(expected), b = Buffer.from(received);
36
+ return a.length === b.length && timingSafeEqual(a, b);
37
+ }
38
+ /** OpenSSH's SHA256 fingerprint of a public key line, as the phone computes it. */
39
+ export function keyFingerprint(publicKeyLine) {
40
+ const blob = publicKeyLine.trim().split(/\s+/)[1];
41
+ if (!blob)
42
+ return undefined;
43
+ return "SHA256:" + createHash("sha256").update(Buffer.from(blob, "base64")).digest("base64").replace(/=+$/, "");
44
+ }
45
+ export async function hostFingerprint(file = "/etc/ssh/ssh_host_ed25519_key.pub") {
46
+ return keyFingerprint(await readFile(file, "utf8").catch(() => ""));
47
+ }
48
+ /** Addresses the phone can try, best first: Tailscale name and address, then LAN IPv4. */
49
+ export async function pairingHosts() {
50
+ const hosts = [];
51
+ for (const binary of ["tailscale", "/Applications/Tailscale.app/Contents/MacOS/Tailscale"]) {
52
+ try {
53
+ const { stdout } = await exec(binary, ["status", "--json", "--peers=false"], { timeout: 3000, maxBuffer: 4 * 1024 * 1024 });
54
+ const self = JSON.parse(stdout).Self;
55
+ if (self?.DNSName)
56
+ hosts.push(self.DNSName.replace(/\.$/, ""));
57
+ const ipv4 = self?.TailscaleIPs?.find(ip => /^\d+\.\d+\.\d+\.\d+$/.test(ip));
58
+ if (ipv4)
59
+ hosts.push(ipv4);
60
+ break;
61
+ }
62
+ catch { /* not installed here */ }
63
+ }
64
+ for (const entries of Object.values(networkInterfaces())) {
65
+ for (const entry of entries ?? []) {
66
+ if (entry.family === "IPv4" && !entry.internal && !hosts.includes(entry.address))
67
+ hosts.push(entry.address);
68
+ }
69
+ }
70
+ return hosts.slice(0, 5);
71
+ }
72
+ /** The name people call this computer: macOS's Computer Name, else the host name. */
73
+ export async function computerDisplayName() {
74
+ if (process.platform === "darwin") {
75
+ const name = await exec("scutil", ["--get", "ComputerName"], { timeout: 2000 }).then(({ stdout }) => stdout.trim()).catch(() => "");
76
+ if (name)
77
+ return name.slice(0, 64);
78
+ }
79
+ return hostname().replace(/\.local$/i, "").split(".")[0] || "Computer";
80
+ }
81
+ /** The QR payload; the phone opens phren://pair links from the camera too. */
82
+ export function pairingURL(offer) {
83
+ const query = new URLSearchParams({ v: "1", h: offer.hosts.join(","), p: String(offer.port), u: offer.user,
84
+ s: String(offer.sshPort), c: offer.code, n: offer.name });
85
+ if (offer.fingerprint)
86
+ query.set("fp", offer.fingerprint);
87
+ return `phren://pair?${query.toString()}`;
88
+ }
89
+ const request = z.object({
90
+ v: z.literal(1), publicKey: z.string().max(512), proof: z.string().max(128),
91
+ device: z.enum(["ios", "android"]).default("ios"), name: z.string().max(80).optional(),
92
+ });
93
+ /** Listen for one phone. Resolves once its key is authorized; rejects on timeout or too many bad proofs. */
94
+ export async function startPairing(options) {
95
+ let failures = 0, finished = false, timer;
96
+ let resolve, reject;
97
+ const done = new Promise((yes, no) => { resolve = yes; reject = no; });
98
+ const server = createServer((incoming, response) => { void handle(incoming, response); });
99
+ const finish = (error, paired) => {
100
+ if (finished)
101
+ return;
102
+ finished = true;
103
+ clearTimeout(timer);
104
+ server.close();
105
+ if (error)
106
+ reject(error);
107
+ else
108
+ resolve(paired);
109
+ };
110
+ const reply = (response, status, body) => {
111
+ response.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
112
+ response.end(JSON.stringify(body));
113
+ };
114
+ async function handle(incoming, response) {
115
+ try {
116
+ if (finished)
117
+ throw new BridgeError(410, "Pairing is closed. Run phren pair again.");
118
+ if (incoming.method !== "POST" || incoming.url !== "/v1/pair")
119
+ throw new BridgeError(404, "Not found.");
120
+ let size = 0;
121
+ const chunks = [];
122
+ for await (const chunk of incoming) {
123
+ size += chunk.length;
124
+ if (size > 4096)
125
+ throw new BridgeError(413, "Request is too large.");
126
+ chunks.push(chunk);
127
+ }
128
+ const input = request.parse(JSON.parse(Buffer.concat(chunks).toString() || "{}"));
129
+ const publicKey = publicComputerKey(input.publicKey);
130
+ if (!sameProof(pairingProof(options.code, "phone", publicKey), input.proof)) {
131
+ failures++;
132
+ if (failures >= MAX_FAILURES)
133
+ setImmediate(() => finish(new Error("Too many wrong pairing codes; pairing closed. Run phren pair again.")));
134
+ throw new BridgeError(403, "That pairing code doesn't match this computer.");
135
+ }
136
+ const comment = input.device === "android" ? "phren-android" : "phren-iphone";
137
+ const encoded = publicKey.split(" ")[1];
138
+ await appendAuthorizedKey(`restrict,pty,${forcedCommand} ${publicKey} ${comment}`, existing => existing.split(/\s+/).includes(encoded), "This phone key is already authorized with different options.", options.sshDirectory);
139
+ reply(response, 200, {
140
+ v: 1, name: options.name, user: options.user, sshPort: options.sshPort, fingerprint: options.fingerprint ?? null,
141
+ proof: pairingProof(options.code, "computer", options.fingerprint ?? "", publicKey),
142
+ });
143
+ setImmediate(() => finish(undefined, { device: input.device, name: input.name, publicKey }));
144
+ }
145
+ catch (error) {
146
+ const status = error instanceof BridgeError ? error.status : error instanceof z.ZodError || error instanceof SyntaxError ? 400 : 500;
147
+ reply(response, status, { error: error instanceof z.ZodError ? "Invalid pairing request." : error.message });
148
+ }
149
+ }
150
+ const listen = (port) => new Promise((ok, fail) => {
151
+ server.once("error", fail);
152
+ server.listen(port, () => { server.off("error", fail); ok(server.address().port); });
153
+ });
154
+ let port;
155
+ try {
156
+ port = await listen(options.port ?? PAIR_PORT);
157
+ }
158
+ catch (error) {
159
+ if (error.code !== "EADDRINUSE" || options.port === 0)
160
+ throw error;
161
+ port = await listen(0);
162
+ }
163
+ timer = setTimeout(() => finish(new Error("Pairing timed out. Run phren pair again.")), options.timeoutMs ?? 5 * 60_000);
164
+ return { port, done, close: () => finish(new Error("Pairing cancelled.")) };
165
+ }
166
+ async function sshListening(port) {
167
+ return new Promise(ok => {
168
+ const socket = connect({ host: "127.0.0.1", port, timeout: 1500 });
169
+ socket.once("connect", () => { socket.destroy(); ok(true); });
170
+ socket.once("timeout", () => { socket.destroy(); ok(false); });
171
+ socket.once("error", () => ok(false));
172
+ });
173
+ }
174
+ function sshHint() {
175
+ return process.platform === "darwin"
176
+ ? "Turn on Remote Login: System Settings → General → Sharing → Remote Login."
177
+ : "Start the SSH server, for example: sudo systemctl enable --now sshd";
178
+ }
179
+ export const PAIR_USAGE = "phren pair [--minutes <1-30>] [--port <n>] [--no-install]";
180
+ export async function runPair(args, version) {
181
+ let minutes = 5, port, installHook = true;
182
+ for (let i = 0; i < args.length; i++) {
183
+ if (args[i] === "--minutes" && args[i + 1])
184
+ minutes = Number(args[++i]);
185
+ else if (args[i] === "--port" && args[i + 1])
186
+ port = Number(args[++i]);
187
+ else if (args[i] === "--no-install")
188
+ installHook = false;
189
+ else {
190
+ console.error(`Usage: ${PAIR_USAGE}`);
191
+ return 1;
192
+ }
193
+ }
194
+ if (!Number.isInteger(minutes) || minutes < 1 || minutes > 30 || (port !== undefined && (!Number.isInteger(port) || port < 0 || port > 65535))) {
195
+ console.error(`Usage: ${PAIR_USAGE}`);
196
+ return 1;
197
+ }
198
+ if (!["darwin", "linux"].includes(process.platform)) {
199
+ console.error("Phone pairing supports macOS and Linux.");
200
+ return 1;
201
+ }
202
+ if (installHook && !await lstat(path.join(bridgeRoot(), "installed.json")).catch(() => undefined)) {
203
+ console.log("Installing Phren Hook, which your phone talks to…");
204
+ await install(version);
205
+ }
206
+ const sshPort = 22;
207
+ if (!await sshListening(sshPort))
208
+ console.log(`\n⚠ SSH isn't answering on this computer. ${sshHint()}\n Pairing can finish now; the phone connects once SSH is on.`);
209
+ const code = newPairingCode();
210
+ const name = await computerDisplayName(), user = userInfo().username, fingerprint = await hostFingerprint();
211
+ const hosts = await pairingHosts();
212
+ if (!hosts.length) {
213
+ console.error("No network address found. Connect to Wi-Fi or Tailscale and try again.");
214
+ return 1;
215
+ }
216
+ const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000 });
217
+ const url = pairingURL({ hosts, port: session.port, user, sshPort, fingerprint, code, name });
218
+ const { renderUnicodeCompact } = await import("uqr");
219
+ console.log(`\nConnect your phone to ${name}`);
220
+ console.log(" In the Phren app: Agents → Add computer → Scan pairing code\n");
221
+ console.log(renderUnicodeCompact(url, { border: 2 }));
222
+ const typed = `${code.slice(0, 3)}-${code.slice(3)}`;
223
+ console.log(`\n Can't scan? Choose "Enter code" and type: ${hosts[0]}${session.port === PAIR_PORT ? "" : `:${session.port}`} ${typed}`);
224
+ console.log(` Waiting for your phone (${minutes} min). Ctrl-C cancels.`);
225
+ const cancel = () => session.close();
226
+ process.once("SIGINT", cancel);
227
+ try {
228
+ const paired = await session.done;
229
+ console.log(`\n✓ Paired ${paired.name ?? "your phone"}. It can reach Phren Hook on ${name} as ${user}.`);
230
+ console.log(` To revoke it later, remove its ${paired.device === "android" ? "phren-android" : "phren-iphone"} line from ${path.join(homedir(), ".ssh/authorized_keys")}.`);
231
+ return 0;
232
+ }
233
+ catch (error) {
234
+ console.error(`\n${error.message}`);
235
+ return 1;
236
+ }
237
+ finally {
238
+ process.off("SIGINT", cancel);
239
+ }
240
+ }
@@ -10,6 +10,15 @@ declare const peerSchema: z.ZodObject<{
10
10
  }, z.core.$strict>;
11
11
  export type HookPeer = z.infer<typeof peerSchema>;
12
12
  export declare function hookPeers(root?: string): Promise<HookPeer[]>;
13
+ /**
14
+ * Adds one verified peer to hooks.yaml, creating the file (0600) if needed.
15
+ * Linking again with the same details is a no-op; a different computer under
16
+ * the same name or address is refused rather than replaced.
17
+ */
18
+ export declare function addHookPeer(input: unknown, root?: string): Promise<{
19
+ added: boolean;
20
+ peer: HookPeer;
21
+ }>;
13
22
  /**
14
23
  * Peers for reads that keep working without them. No hooks.yaml means no
15
24
  * peers; a broken one is logged and returned as `peerError` so the response
@@ -2,12 +2,12 @@ import { spawn } from "node:child_process";
2
2
  import { lstat, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { Duplex } from "node:stream";
5
- import { load } from "js-yaml";
5
+ import { dump, load } from "js-yaml";
6
6
  import { z } from "zod";
7
7
  import { logger } from "../logger.js";
8
8
  import { hookRequest } from "./client.js";
9
9
  import { computerName, dispatchKeyPath, publicComputerKey } from "./computers.js";
10
- import { BridgeError, bridgeRoot, serverName } from "./protocol.js";
10
+ import { atomic, BridgeError, bridgeRoot, serverName } from "./protocol.js";
11
11
  const peerSchema = z.object({
12
12
  name: computerName,
13
13
  address: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9.:-]{0,252}$/),
@@ -32,6 +32,29 @@ export async function hookPeers(root = bridgeRoot()) {
32
32
  throw new BridgeError(409, "hooks.yaml has duplicate computer names.");
33
33
  return computers;
34
34
  }
35
+ /**
36
+ * Adds one verified peer to hooks.yaml, creating the file (0600) if needed.
37
+ * Linking again with the same details is a no-op; a different computer under
38
+ * the same name or address is refused rather than replaced.
39
+ */
40
+ export async function addHookPeer(input, root = bridgeRoot()) {
41
+ const peer = peerSchema.parse(input);
42
+ const existing = await hookPeers(root).catch(error => {
43
+ if (error instanceof BridgeError && error.details?.hooksYaml === "missing")
44
+ return [];
45
+ throw error;
46
+ });
47
+ const same = (other) => JSON.stringify(peerSchema.parse(other)) === JSON.stringify(peer);
48
+ if (existing.some(same))
49
+ return { added: false, peer };
50
+ const clash = existing.find(other => other.name === peer.name || (other.address === peer.address && other.port === peer.port && other.server === peer.server));
51
+ if (clash)
52
+ throw new BridgeError(409, `hooks.yaml already has ${clash.name} at ${clash.address}; remove that entry first to link it differently.`);
53
+ if (existing.length >= 32)
54
+ throw new BridgeError(409, "hooks.yaml already has 32 computers.");
55
+ await atomic(path.join(root, "hooks.yaml"), dump({ version: 1, computers: [...existing, peer] }, { lineWidth: -1 }));
56
+ return { added: true, peer };
57
+ }
35
58
  /**
36
59
  * Peers for reads that keep working without them. No hooks.yaml means no
37
60
  * peers; a broken one is logged and returned as `peerError` so the response
@@ -1,8 +1,23 @@
1
1
  import { z } from "zod";
2
+ /** A phone registered through the phren push relay: the relay knows where to
3
+ * deliver, and `key` (32 bytes, base64url) encrypts what the notification says
4
+ * so only the phone reads it. The phone made the key and sent it over SSH. */
5
+ declare const relaySchema: z.ZodObject<{
6
+ url: z.ZodString;
7
+ relayId: z.ZodString;
8
+ secret: z.ZodString;
9
+ key: z.ZodString;
10
+ }, z.core.$strip>;
2
11
  declare const deviceSchema: z.ZodObject<{
3
12
  deviceID: z.ZodString;
4
13
  hostID: z.ZodString;
5
- token: z.ZodString;
14
+ token: z.ZodOptional<z.ZodString>;
15
+ relay: z.ZodOptional<z.ZodObject<{
16
+ url: z.ZodString;
17
+ relayId: z.ZodString;
18
+ secret: z.ZodString;
19
+ key: z.ZodString;
20
+ }, z.core.$strip>>;
6
21
  environment: z.ZodEnum<{
7
22
  development: "development";
8
23
  production: "production";
@@ -54,11 +69,29 @@ export declare function fanoutBlockedPushPayload(value: FanoutBlockedPush): Reco
54
69
  export declare function schedulePushPayload(value: SchedulePush): Record<string, unknown>;
55
70
  /** What `phren bridge doctor` prints when the Hook has no APNs sender. */
56
71
  export declare function apnsSetupSteps(configFile?: string): string;
57
- /** The capability a phone reads: only a Hook with a loaded APNs sender offers push. */
72
+ /** The capability a phone reads: a Hook with its own APNs key sends direct;
73
+ * one whose phones registered through the relay sends through it. */
58
74
  export declare function approvalPushCapability(status: {
59
75
  configured: boolean;
60
- }): "direct-apns" | undefined;
76
+ direct?: boolean;
77
+ }): "direct-apns" | "relay" | undefined;
61
78
  export declare function upsertPushDevice(devices: PushDevice[], value: unknown): PushDevice[];
79
+ /** The relay refuses ciphertext longer than this (it keeps the APNs payload under 4 KB). */
80
+ export declare const RELAY_MAX_CIPHERTEXT = 2800;
81
+ /** What the phone's notification extension shows, encrypted with the phone's
82
+ * key: ChaCha20-Poly1305, base64url of nonce (12) + ciphertext + tag (16), the
83
+ * layout CryptoKit's `ChaChaPoly.SealedBox(combined:)` reads. A long body is
84
+ * shortened until it fits the relay's limit. */
85
+ export declare function relayCiphertext(key: string, payload: Record<string, unknown>, nonce?: NonSharedBuffer): string;
86
+ /** Signs a relay send: base64url HMAC-SHA256 of `${timestamp}.${body}` under the phone's send secret. */
87
+ export declare function relaySignature(secret: string, timestamp: string, body: string): string;
88
+ type RelayRegistration = z.infer<typeof relaySchema>;
89
+ /** "gone" means the relay (Apple) no longer knows the phone: stop sending until it registers again. */
90
+ export type RelayResult = "sent" | "failed" | "gone";
91
+ export declare function sendThroughRelay(relay: RelayRegistration, payload: Record<string, unknown>, headers: {
92
+ expiration: string;
93
+ collapseId: string;
94
+ }, fetcher?: typeof fetch, now?: () => number): Promise<RelayResult>;
62
95
  /** Direct Hook -> APNs delivery. Apple receives only a short-lived opaque
63
96
  * binding; conversation identity, action id, command and SSH key stay local. */
64
97
  export declare class ApprovalPushService {
@@ -66,13 +99,19 @@ export declare class ApprovalPushService {
66
99
  private sender?;
67
100
  private readonly devicesFile;
68
101
  start(): Promise<void>;
102
+ /** Phones this Hook can reach: through the relay, or direct with its own key. */
103
+ private get reachable();
69
104
  get available(): boolean;
70
105
  get status(): {
71
106
  supported: boolean;
72
107
  configured: boolean;
108
+ direct: boolean;
73
109
  devices: number;
110
+ relay: number;
74
111
  };
75
112
  register(value: unknown): Promise<void>;
113
+ /** One phone: the relay when it registered through one, otherwise direct. */
114
+ private send;
76
115
  notify(value: ApprovalPush): Promise<boolean>;
77
116
  /** A headless worker whose permission the plugin refused. Approval-registered
78
117
  * phones already accept agent alerts; the payload carries the reason so the
@@ -1,16 +1,27 @@
1
- import { createPrivateKey, sign } from "node:crypto";
1
+ import { createCipheriv, createHmac, createPrivateKey, randomBytes, sign } from "node:crypto";
2
2
  import { readFile, stat } from "node:fs/promises";
3
3
  import { connect } from "node:http2";
4
4
  import path from "node:path";
5
5
  import { z } from "zod";
6
6
  import { atomic, bridgeRoot } from "./protocol.js";
7
+ /** A phone registered through the phren push relay: the relay knows where to
8
+ * deliver, and `key` (32 bytes, base64url) encrypts what the notification says
9
+ * so only the phone reads it. The phone made the key and sent it over SSH. */
10
+ const relaySchema = z.object({
11
+ url: z.string().url().refine(value => /^https:\/\//.test(value) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${value}/`), "The relay must use https."),
12
+ relayId: z.string().regex(/^[A-Za-z0-9_-]{40,400}$/),
13
+ secret: z.string().regex(/^[A-Za-z0-9_-]{20,100}$/),
14
+ key: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
15
+ });
7
16
  const deviceSchema = z.object({
8
17
  deviceID: z.string().uuid(),
9
18
  hostID: z.string().uuid(),
10
- token: z.string().regex(/^[0-9a-f]{64}$/),
19
+ /** The APNs token, for a Hook with its own key (apns.json). */
20
+ token: z.string().regex(/^[0-9a-f]{64}$/).optional(),
21
+ relay: relaySchema.optional(),
11
22
  environment: z.enum(["development", "production"]),
12
23
  kinds: z.array(z.enum(["approval", "scheduleStarted", "scheduleFinished", "scheduleFailed", "scheduleBlocked"])).max(5).default(["approval"]),
13
- });
24
+ }).refine(device => device.token !== undefined || device.relay !== undefined, "A phone needs an APNs token or a relay registration.");
14
25
  const configSchema = z.object({
15
26
  keyId: z.string().regex(/^[A-Z0-9]{10}$/),
16
27
  teamId: z.string().regex(/^[A-Z0-9]{10}$/),
@@ -83,15 +94,59 @@ export function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || pat
83
94
  "4. Restart the Hook (phren bridge install), then run phren bridge doctor again.",
84
95
  ].join("\n");
85
96
  }
86
- /** The capability a phone reads: only a Hook with a loaded APNs sender offers push. */
97
+ /** The capability a phone reads: a Hook with its own APNs key sends direct;
98
+ * one whose phones registered through the relay sends through it. */
87
99
  export function approvalPushCapability(status) {
88
- return status.configured ? "direct-apns" : undefined;
100
+ if (!status.configured)
101
+ return undefined;
102
+ return status.direct === false ? "relay" : "direct-apns";
89
103
  }
90
104
  export function upsertPushDevice(devices, value) {
91
105
  const device = deviceSchema.parse(value);
92
106
  return [...devices.filter(item => item.deviceID !== device.deviceID), device].slice(-16);
93
107
  }
94
108
  const base64url = (value) => Buffer.from(value).toString("base64url");
109
+ /** The relay refuses ciphertext longer than this (it keeps the APNs payload under 4 KB). */
110
+ export const RELAY_MAX_CIPHERTEXT = 2_800;
111
+ /** What the phone's notification extension shows, encrypted with the phone's
112
+ * key: ChaCha20-Poly1305, base64url of nonce (12) + ciphertext + tag (16), the
113
+ * layout CryptoKit's `ChaChaPoly.SealedBox(combined:)` reads. A long body is
114
+ * shortened until it fits the relay's limit. */
115
+ export function relayCiphertext(key, payload, nonce = randomBytes(12)) {
116
+ const aps = (payload.aps ?? {});
117
+ let body = aps.alert?.body ?? "";
118
+ for (;;) {
119
+ const content = JSON.stringify({ t: aps.alert?.title ?? "phren", b: body, ...(aps.category ? { c: aps.category } : {}),
120
+ ...(aps["interruption-level"] ? { i: aps["interruption-level"] } : {}), ...(payload.phren ? { p: payload.phren } : {}) });
121
+ const cipher = createCipheriv("chacha20-poly1305", Buffer.from(key, "base64url"), nonce, { authTagLength: 16 });
122
+ const sealed = Buffer.concat([nonce, cipher.update(content, "utf8"), cipher.final(), cipher.getAuthTag()]).toString("base64url");
123
+ if (sealed.length <= RELAY_MAX_CIPHERTEXT || !body)
124
+ return sealed;
125
+ body = body.length > 40 ? `${body.slice(0, Math.floor(body.length * 0.8))}…` : "";
126
+ }
127
+ }
128
+ /** Signs a relay send: base64url HMAC-SHA256 of `${timestamp}.${body}` under the phone's send secret. */
129
+ export function relaySignature(secret, timestamp, body) {
130
+ return createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("base64url");
131
+ }
132
+ export async function sendThroughRelay(relay, payload, headers, fetcher = fetch, now = Date.now) {
133
+ const aps = (payload.aps ?? {});
134
+ const body = JSON.stringify({ kind: "alert", ciphertext: relayCiphertext(relay.key, payload),
135
+ collapseId: headers.collapseId.slice(0, 64), expiration: Number(headers.expiration) || 0,
136
+ ...(aps.category ? { category: aps.category } : {}) });
137
+ const timestamp = String(Math.floor(now() / 1000));
138
+ try {
139
+ const response = await fetcher(`${relay.url.replace(/\/+$/, "")}/v1/send`, {
140
+ method: "POST", body, signal: AbortSignal.timeout(10_000),
141
+ headers: { "content-type": "application/json", "x-phren-relay": relay.relayId, "x-phren-timestamp": timestamp,
142
+ "x-phren-signature": relaySignature(relay.secret, timestamp, body) },
143
+ });
144
+ return response.status === 410 ? "gone" : response.ok ? "sent" : "failed";
145
+ }
146
+ catch {
147
+ return "failed";
148
+ }
149
+ }
95
150
  class APNsSender {
96
151
  config;
97
152
  key;
@@ -149,19 +204,35 @@ export class ApprovalPushService {
149
204
  if (key)
150
205
  this.sender = new APNsSender(config, key);
151
206
  }
152
- get available() { return this.sender !== undefined && this.devices.length > 0; }
153
- get status() { return { supported: true, configured: this.sender !== undefined, devices: this.devices.length }; }
207
+ /** Phones this Hook can reach: through the relay, or direct with its own key. */
208
+ get reachable() { return this.devices.filter(device => device.relay || (this.sender && device.token)); }
209
+ get available() { return this.reachable.length > 0; }
210
+ get status() {
211
+ const relay = this.devices.filter(device => device.relay).length;
212
+ return { supported: true, configured: this.sender !== undefined || relay > 0, direct: this.sender !== undefined,
213
+ devices: this.devices.length, relay };
214
+ }
154
215
  async register(value) {
155
216
  this.devices = upsertPushDevice(this.devices, value);
156
217
  await atomic(this.devicesFile, JSON.stringify(this.devices));
157
218
  }
219
+ /** One phone: the relay when it registered through one, otherwise direct. */
220
+ async send(device, payload, headers) {
221
+ if (device.relay) {
222
+ const result = await sendThroughRelay(device.relay, payload, headers);
223
+ if (result === "gone") {
224
+ this.devices = this.devices.filter(item => item.deviceID !== device.deviceID);
225
+ await atomic(this.devicesFile, JSON.stringify(this.devices)).catch(() => { });
226
+ }
227
+ return result === "sent";
228
+ }
229
+ return this.sender && device.token ? this.sender.send(device, payload, headers) : false;
230
+ }
158
231
  async notify(value) {
159
- if (!this.sender || !this.devices.length)
160
- return false;
161
- const devices = this.devices.filter(device => device.kinds.includes("approval"));
232
+ const devices = this.reachable.filter(device => device.kinds.includes("approval"));
162
233
  if (!devices.length)
163
234
  return false;
164
- return (await Promise.all(devices.map(device => this.sender.send(device, approvalPushPayload(value, device.hostID), {
235
+ return (await Promise.all(devices.map(device => this.send(device, approvalPushPayload(value, device.hostID), {
165
236
  expiration: String(Math.floor(Date.parse(value.expiresAt) / 1000)), collapseId: value.binding,
166
237
  })))).some(Boolean);
167
238
  }
@@ -169,25 +240,24 @@ export class ApprovalPushService {
169
240
  * phones already accept agent alerts; the payload carries the reason so the
170
241
  * notification is actionable on its own. */
171
242
  async notifyFanoutBlocked(value) {
172
- if (!this.sender || !this.devices.length)
173
- return false;
174
- const devices = this.devices.filter(device => device.kinds.includes("approval"));
243
+ const devices = this.reachable.filter(device => device.kinds.includes("approval"));
175
244
  if (!devices.length)
176
245
  return false;
177
- return (await Promise.all(devices.map(device => this.sender.send(device, fanoutBlockedPushPayload(value), {
246
+ return (await Promise.all(devices.map(device => this.send(device, fanoutBlockedPushPayload(value), {
178
247
  expiration: "0", collapseId: `fanout-${value.job}`,
179
248
  })))).some(Boolean);
180
249
  }
181
250
  async notifySchedule(value) {
182
- if (!this.sender)
183
- return { notified: false, reason: "no push config" };
184
- let devices = this.devices.filter(device => device.kinds.includes(value.kind));
251
+ const reachable = this.reachable;
252
+ if (!reachable.length)
253
+ return { notified: false, reason: this.sender || this.devices.length ? "no registered devices" : "no push config" };
254
+ let devices = reachable.filter(device => device.kinds.includes(value.kind));
185
255
  if (!devices.length && value.kind === "scheduleBlocked")
186
- devices = this.devices.filter(device => device.kinds.includes("scheduleFailed"));
256
+ devices = reachable.filter(device => device.kinds.includes("scheduleFailed"));
187
257
  if (!devices.length)
188
258
  return { notified: false, reason: "no registered devices" };
189
259
  try {
190
- const notified = (await Promise.all(devices.map(device => this.sender.send(device, schedulePushPayload(value), {
260
+ const notified = (await Promise.all(devices.map(device => this.send(device, schedulePushPayload(value), {
191
261
  expiration: "0", collapseId: scheduleCollapseId(value.kind, value.runId),
192
262
  })))).some(Boolean);
193
263
  return notified ? { notified: true } : { notified: false, reason: "push delivery failed" };
@@ -1,4 +1,13 @@
1
1
  import { type Json } from "./protocol.js";
2
+ /** The live conductor on this computer, on any Herdr server, as a target.
3
+ * `known` reuses a snapshot the caller already took. */
4
+ export declare function localConductor(known?: {
5
+ server: string;
6
+ snapshot: Json;
7
+ }): Promise<{
8
+ server: string;
9
+ target?: Json;
10
+ } | undefined>;
2
11
  /** The Herdr agent-name slug for a human label: "Conductor smoke 4" becomes "conductor-smoke-4". */
3
12
  export declare function herdrAgentName(label: string): string;
4
13
  /**
@@ -5,6 +5,8 @@ import { z } from "zod";
5
5
  import { homeDir } from "../home-paths.js";
6
6
  import { agentNames, findPane, isConductorName, paneAgentName, paneChatState, paneIdentity, rpc, servers, snapshot } from "./herdr.js";
7
7
  import { createLaunchWorktree, launchWorktreeSchema } from "./launch-worktree.js";
8
+ import { groupConductor } from "./conductor-group.js";
9
+ import { optionalHookPeers } from "./peers.js";
8
10
  import { atomic, BridgeError, bridgeRoot, id, objects, provider } from "./protocol.js";
9
11
  /** Starting agents in Herdr from the phone: the launch route's harness
10
12
  * arguments, the conductor brief, and workspace, tab and pane actions. */
@@ -78,6 +80,19 @@ async function targetForPane(server, pane) {
78
80
  const chat = await paneChatState(server, pane).catch(() => ({}));
79
81
  return chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : undefined;
80
82
  }
83
+ /** The live conductor on this computer, on any Herdr server, as a target.
84
+ * `known` reuses a snapshot the caller already took. */
85
+ export async function localConductor(known) {
86
+ const names = [...new Set([...(known ? [known.server] : []), ...(await servers()).map(item => String(item.session))])];
87
+ for (const name of names) {
88
+ const value = known && name === known.server ? known.snapshot : await snapshot(name);
89
+ const existing = objects(value.panes).find(pane => isConductorName(paneAgentName(value, pane))
90
+ && provider.safeParse(pane.agent).success && !["completed", "exited", "failed", "stopped"].includes(String(pane.agent_status)));
91
+ if (existing)
92
+ return { server: name, target: await targetForPane(name, existing) };
93
+ }
94
+ return undefined;
95
+ }
81
96
  /** The Herdr agent-name slug for a human label: "Conductor smoke 4" becomes "conductor-smoke-4". */
82
97
  export function herdrAgentName(label) {
83
98
  const slug = label.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "").slice(0, 32).replace(/-+$/, "");
@@ -107,10 +122,13 @@ export async function launchSession(server, data, options = {}) {
107
122
  // "Conductor" stays "conductor", never "conductor-conductor".
108
123
  // The canary's conductor is not the store's conductor: it keeps its own
109
124
  // name, so the phone never pins it and a real conductor is never refused.
110
- const wanted = options.canary ? "phren-canary" : role === "conductor" ? (baseName === "conductor" || baseName.startsWith("conductor-") ? baseName : herdrAgentName(`conductor-${baseName}`)) : baseName;
125
+ // A worker never takes a conductor's name, whatever its label says:
126
+ // "Conductor voice fluency" would otherwise read as role=conductor.
127
+ const wanted = options.canary ? "phren-canary" : role === "conductor" ? (isConductorName(baseName) ? baseName : herdrAgentName(`conductor-${baseName}`))
128
+ : isConductorName(baseName) ? herdrAgentName(`worker-${baseName}`) : baseName;
111
129
  const model = typeof data.model === "string" && data.model.trim() ? plainText(200).parse(data.model.trim()) : undefined;
112
130
  const modelFlag = { codex: "--model", claude: "--model", opencode: "--model" };
113
- const workspace = data.workspaceId === undefined ? undefined : id.parse(data.workspaceId);
131
+ let workspace = data.workspaceId === undefined ? undefined : id.parse(data.workspaceId);
114
132
  // Herdr 0.9.1 refuses a start timeout of 3000 ms or less (invalid_agent_timeout).
115
133
  const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
116
134
  const before = await snapshot(server);
@@ -120,16 +138,21 @@ export async function launchSession(server, data, options = {}) {
120
138
  let name = wanted;
121
139
  for (let n = 2; taken.has(name) && n < 100; n++)
122
140
  name = `${wanted.slice(0, 32 - String(n).length - 1)}-${n}`;
141
+ // One conductor per connected group: this computer and every linked peer.
142
+ let unchecked = [];
123
143
  if (role === "conductor" && !options.canary) {
124
- const otherServers = (await servers()).map(item => String(item.session)).filter(name => name !== server);
125
- const overviews = [{ name: server, value: before }, ...await Promise.all(otherServers.map(async (name) => ({ name, value: await snapshot(name) })))];
126
- for (const overview of overviews) {
127
- const existing = objects(overview.value.panes).find(pane => isConductorName(paneAgentName(overview.value, pane))
128
- && provider.safeParse(pane.agent).success && !["completed", "exited", "failed", "stopped"].includes(String(pane.agent_status)));
129
- if (existing)
130
- throw new BridgeError(409, "A conductor is already running for this store.", { target: await targetForPane(overview.name, existing) });
131
- }
144
+ const existing = await localConductor({ server, snapshot: before });
145
+ if (existing)
146
+ throw new BridgeError(409, "A conductor is already running on this computer.", { target: existing.target });
147
+ const group = await groupConductor((await optionalHookPeers()).peers);
148
+ if (group.found)
149
+ throw new BridgeError(409, `A conductor is already running on ${group.found.computer}, which is linked with this computer. A connected group shares one conductor.`, { computer: group.found.computer, target: group.found.target });
150
+ unchecked = group.unchecked;
132
151
  }
152
+ // A worker opened in the conductor's workspace would be listed under the
153
+ // conductor's name; it gets its own workspace instead.
154
+ if (role === "agent" && workspace && objects(before.panes).some(pane => pane.workspace_id === workspace && isConductorName(paneAgentName(before, pane))))
155
+ workspace = undefined;
133
156
  const args = role === "conductor" ? await prepareConductor(kind, effort, model)
134
157
  : [...(model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort))];
135
158
  if (workspace && !objects(before.workspaces).some(w => w.workspace_id === workspace))
@@ -186,7 +209,7 @@ export async function launchSession(server, data, options = {}) {
186
209
  const binding = { server, workspace: created.workspaceId, tab: created.tabId, pane: created.paneId, source: kind };
187
210
  const target = sessionId ? { ...binding, session: sessionId }
188
211
  : chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : undefined;
189
- return { ok: true, ...created, agent: kind, agentStatus, role, sessionId, target,
212
+ return { ok: true, ...created, agent: kind, agentStatus, role, sessionId, target, ...(unchecked.length ? { unchecked } : {}),
190
213
  ...(worktree ? { worktree: { path: worktree.path, branch: worktree.branch } } : {}) };
191
214
  }
192
215
  export async function workspaceAction(server, operation, data) {