@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.
- package/dist/bridge/agent-hooks.d.ts +17 -6
- package/dist/bridge/agent-hooks.js +59 -24
- package/dist/bridge/claude-question-dialog.d.ts +65 -0
- package/dist/bridge/claude-question-dialog.js +210 -0
- package/dist/bridge/code-note.d.ts +2 -1
- package/dist/bridge/code-note.js +13 -4
- package/dist/bridge/code-routes.d.ts +32 -14
- package/dist/bridge/code-routes.js +131 -8
- package/dist/bridge/command.js +92 -2
- package/dist/bridge/computers.d.ts +5 -0
- package/dist/bridge/computers.js +10 -4
- package/dist/bridge/conductor-group.d.ts +23 -0
- package/dist/bridge/conductor-group.js +25 -0
- package/dist/bridge/dispatch-returns.d.ts +2 -0
- package/dist/bridge/dispatch-returns.js +12 -8
- package/dist/bridge/dispatch.d.ts +4 -1
- package/dist/bridge/dispatch.js +30 -5
- package/dist/bridge/hand-off.js +5 -1
- package/dist/bridge/herdr.d.ts +7 -0
- package/dist/bridge/herdr.js +53 -2
- package/dist/bridge/install.d.ts +0 -4
- package/dist/bridge/install.js +3 -3
- package/dist/bridge/link.d.ts +48 -0
- package/dist/bridge/link.js +136 -0
- package/dist/bridge/memory-store.d.ts +23 -0
- package/dist/bridge/memory-store.js +152 -0
- package/dist/bridge/pair.d.ts +46 -0
- package/dist/bridge/pair.js +240 -0
- package/dist/bridge/peers.d.ts +9 -0
- package/dist/bridge/peers.js +25 -2
- package/dist/bridge/protocol.js +20 -1
- package/dist/bridge/schedule-watch.d.ts +2 -0
- package/dist/bridge/schedule-watch.js +16 -3
- package/dist/bridge/server-launch.d.ts +9 -0
- package/dist/bridge/server-launch.js +34 -11
- package/dist/bridge/server-pane-routes.d.ts +7 -0
- package/dist/bridge/server-pane-routes.js +128 -18
- package/dist/bridge/server-routes.d.ts +3 -0
- package/dist/bridge/server-routes.js +55 -29
- package/dist/bridge/server-stream.js +4 -1
- package/dist/bridge/speech-key.d.ts +33 -0
- package/dist/bridge/speech-key.js +106 -0
- package/dist/bridge/speech-transcribe.js +1 -1
- package/dist/bridge/speech.d.ts +1 -3
- package/dist/bridge/speech.js +2 -16
- package/dist/bridge/transcript-preview.d.ts +2 -0
- package/dist/bridge/transcript-preview.js +15 -0
- package/dist/bridge-hook.mjs +9940 -3601
- package/dist/cli/config-policy.js +25 -0
- package/dist/cli/extract.d.ts +0 -8
- package/dist/cli/extract.js +1 -1
- package/dist/cli-handlers.js +6 -0
- package/dist/cli-registry.js +21 -9
- package/dist/content/learning.js +1 -1
- package/dist/content/validate.d.ts +14 -3
- package/dist/content/validate.js +174 -114
- package/dist/data/access.d.ts +9 -0
- package/dist/data/access.js +18 -0
- package/dist/data/tasks.d.ts +26 -0
- package/dist/data/tasks.js +72 -1
- package/dist/entrypoint.js +7 -0
- package/dist/generated/memory-ui-graph.browser.js +520 -410
- package/dist/governance/policy.js +4 -3
- package/dist/governance/rbac.d.ts +1 -1
- package/dist/governance/rbac.js +1 -0
- package/dist/hooks.d.ts +0 -15
- package/dist/hooks.js +1 -1
- package/dist/init/init-uninstall.js +13 -3
- package/dist/init/init-walkthrough.d.ts +10 -0
- package/dist/init/init-walkthrough.js +24 -1
- package/dist/init/init.d.ts +5 -0
- package/dist/init/init.js +54 -32
- package/dist/init/setup.js +19 -5
- package/dist/init/store-gitignore.d.ts +0 -5
- package/dist/init/store-gitignore.js +0 -8
- package/dist/link/context-imports.d.ts +15 -0
- package/dist/link/context-imports.js +101 -0
- package/dist/link/doctor.js +38 -4
- package/dist/mcp/profile.d.ts +0 -4
- package/dist/mcp/profile.js +2 -14
- package/dist/memory-ui-graph.runtime.js +520 -410
- package/dist/modules/code-package.js +10 -2
- package/dist/modules/config.d.ts +7 -0
- package/dist/modules/config.js +17 -0
- package/dist/modules/registry.js +6 -5
- package/dist/profile-store.js +39 -3
- package/dist/project-topics.d.ts +1 -0
- package/dist/project-topics.js +9 -6
- package/dist/shared/retrieval.d.ts +0 -2
- package/dist/shared/retrieval.js +1 -1
- package/dist/sync/task-claim.d.ts +22 -0
- package/dist/sync/task-claim.js +45 -0
- package/dist/tools/code.js +29 -21
- package/dist/tools/config.js +3 -0
- package/dist/tools/dispatch.js +3 -3
- package/dist/tools/finding.d.ts +11 -0
- package/dist/tools/finding.js +154 -99
- package/dist/tools/tasks.js +40 -1
- package/dist/ui/server.js +18 -1
- package/dist/update.js +21 -10
- package/package.json +8 -7
- package/starter/global/skills/conductor/SKILL.md +42 -10
|
@@ -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
|
+
}
|
package/dist/bridge/peers.d.ts
CHANGED
|
@@ -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
|
package/dist/bridge/peers.js
CHANGED
|
@@ -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
|
package/dist/bridge/protocol.js
CHANGED
|
@@ -53,12 +53,31 @@ export async function atomic(file, value, mode = 0o600) {
|
|
|
53
53
|
const text = typeof value === "string" ? value : JSON.stringify(value);
|
|
54
54
|
await writeFile(temporary, text, { mode, flag: "wx" });
|
|
55
55
|
try {
|
|
56
|
-
await
|
|
56
|
+
await renameOver(temporary, file);
|
|
57
57
|
}
|
|
58
58
|
finally {
|
|
59
59
|
await unlink(temporary).catch(() => { });
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* Windows refuses to replace a file another handle holds open (a concurrent
|
|
64
|
+
* reader, or another writer's rename landing at the same moment) with EPERM,
|
|
65
|
+
* EACCES or EBUSY, where POSIX replaces it atomically. Those holds last
|
|
66
|
+
* milliseconds, so retry briefly before giving up.
|
|
67
|
+
*/
|
|
68
|
+
async function renameOver(from, to) {
|
|
69
|
+
for (let attempt = 0;; attempt++) {
|
|
70
|
+
try {
|
|
71
|
+
return await rename(from, to);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
const code = error.code ?? "";
|
|
75
|
+
if (process.platform !== "win32" || attempt >= 20 || !["EPERM", "EACCES", "EBUSY"].includes(code))
|
|
76
|
+
throw error;
|
|
77
|
+
await new Promise(resolve => setTimeout(resolve, 5 * (attempt + 1)));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
62
81
|
/** {@link atomic}, first creating the file's directory (0700 where it is new). */
|
|
63
82
|
export async function atomicInPrivateDir(file, value, mode) {
|
|
64
83
|
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
@@ -30,9 +30,11 @@ export interface StartupWatchEnv {
|
|
|
30
30
|
panes?: (server: string) => Promise<Json[]>;
|
|
31
31
|
finalTurn?: (source: ScheduleHarness, sessionId: string | undefined) => Promise<FinalTurn | undefined>;
|
|
32
32
|
}
|
|
33
|
+
/** `error`: the harness ended the turn on an error (Codex's usage limit) instead of a reply. */
|
|
33
34
|
export interface FinalTurn {
|
|
34
35
|
completed: boolean;
|
|
35
36
|
lastAssistant?: string;
|
|
37
|
+
error?: string;
|
|
36
38
|
}
|
|
37
39
|
/** The public text of one assistant row, without reasoning or tool output. */
|
|
38
40
|
export declare function publicAssistant(raw: Json, source: Provider): string | undefined;
|
|
@@ -75,10 +75,18 @@ function turnEnded(raw, source) {
|
|
|
75
75
|
return raw.type === "event_msg" && ["task_complete", "task_completed"].includes(String(payload.type));
|
|
76
76
|
return data.stop_reason === "end_turn";
|
|
77
77
|
}
|
|
78
|
+
/** The error a turn ended on, when the harness records one: Codex's
|
|
79
|
+
* task_complete carries `error.message` (a usage limit, a failed compaction). */
|
|
80
|
+
function turnError(raw, source) {
|
|
81
|
+
if (source !== "codex")
|
|
82
|
+
return;
|
|
83
|
+
const error = object(object(raw.payload).error), message = typeof error.message === "string" ? error.message.replace(/\s+/g, " ").trim() : "";
|
|
84
|
+
return message ? message.slice(0, 500) : undefined;
|
|
85
|
+
}
|
|
78
86
|
/** The last assistant reply in a transcript and whether its turn finished.
|
|
79
87
|
* A person's message after the reply opens a new turn, so it clears both. */
|
|
80
88
|
export function finalTurnFromLines(lines, source) {
|
|
81
|
-
let completed = false, lastAssistant;
|
|
89
|
+
let completed = false, lastAssistant, error;
|
|
82
90
|
for (const line of lines) {
|
|
83
91
|
if (!line.trim())
|
|
84
92
|
continue;
|
|
@@ -96,6 +104,7 @@ export function finalTurnFromLines(lines, source) {
|
|
|
96
104
|
if (userTurn) {
|
|
97
105
|
completed = false;
|
|
98
106
|
lastAssistant = undefined;
|
|
107
|
+
error = undefined;
|
|
99
108
|
continue;
|
|
100
109
|
}
|
|
101
110
|
const text = publicAssistant(raw, source);
|
|
@@ -103,10 +112,12 @@ export function finalTurnFromLines(lines, source) {
|
|
|
103
112
|
lastAssistant = text;
|
|
104
113
|
completed = false;
|
|
105
114
|
}
|
|
106
|
-
if (turnEnded(raw, source))
|
|
115
|
+
if (turnEnded(raw, source)) {
|
|
107
116
|
completed = true;
|
|
117
|
+
error = turnError(raw, source);
|
|
118
|
+
}
|
|
108
119
|
}
|
|
109
|
-
return { completed, ...(lastAssistant ? { lastAssistant } : {}) };
|
|
120
|
+
return { completed, ...(lastAssistant ? { lastAssistant } : {}), ...(completed && error ? { error } : {}) };
|
|
110
121
|
}
|
|
111
122
|
/** The final turn of a conversation, read from the tail of its transcript. */
|
|
112
123
|
export async function readFinalTurn(source, sessionId) {
|
|
@@ -198,6 +209,8 @@ export async function watchHerdrRun(server, target, signal, startup, env = {}) {
|
|
|
198
209
|
if (!sessionId)
|
|
199
210
|
sessionId = await resolveSession(server, pane);
|
|
200
211
|
const turn = await finalTurn(startup.source, sessionId).catch(() => undefined);
|
|
212
|
+
if (turn?.completed && turn.error)
|
|
213
|
+
return { status: "failed", reason: turn.error };
|
|
201
214
|
const question = turn?.completed && turn.lastAssistant ? ownerQuestion(turn.lastAssistant) : undefined;
|
|
202
215
|
return question ? { status: "needs-you", reason: question } : { status: "finished" };
|
|
203
216
|
}
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
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) {
|
|
@@ -26,4 +26,11 @@ export declare function gitRepository(pane: Json, target: Target, child: unknown
|
|
|
26
26
|
* an agent launched into a new worktree from the phone is named here. Listed
|
|
27
27
|
* last, so a sub-agent or fan-out manifest for the same folder wins a tie. */
|
|
28
28
|
export declare function herdrWorktreeWorkers(s: Json): WorktreeWorker[];
|
|
29
|
+
/** A busy Claude Code queues typed text on Enter, but after a long paste
|
|
30
|
+
* ("paste again to expand") it can swallow that Enter and leave the text in
|
|
31
|
+
* its input line, where it stays after the turn ends. Follow the pane: once
|
|
32
|
+
* it has stayed finished for two looks while the prompt is still unsubmitted,
|
|
33
|
+
* press Enter once. A closed or replaced pane, a delivery the conversation
|
|
34
|
+
* took, or ten minutes end the watch; a pane asking for input is never answered. */
|
|
35
|
+
export declare function followQueuedDelivery(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, intervalMs?: number): void;
|
|
29
36
|
export declare function paneRoute(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse): Promise<unknown>;
|