@phren/cli 0.3.0 → 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 +15 -6
- package/dist/bridge/agent-hooks.js +55 -24
- package/dist/bridge/claude-question-dialog.d.ts +65 -0
- package/dist/bridge/claude-question-dialog.js +210 -0
- 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/hand-off.js +5 -1
- package/dist/bridge/herdr.d.ts +7 -0
- package/dist/bridge/herdr.js +53 -2
- 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/server-launch.d.ts +9 -0
- package/dist/bridge/server-launch.js +34 -11
- package/dist/bridge/server-pane-routes.js +38 -7
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +11 -3
- 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-hook.mjs +1198 -492
- package/dist/cli-handlers.js +6 -0
- package/dist/cli-registry.js +14 -2
- package/dist/content/learning.js +1 -1
- package/dist/data/tasks.d.ts +26 -0
- package/dist/data/tasks.js +72 -1
- package/dist/entrypoint.js +7 -0
- package/dist/governance/rbac.d.ts +1 -1
- package/dist/governance/rbac.js +1 -0
- 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/link/doctor.js +10 -0
- package/dist/mcp/profile.js +2 -1
- package/dist/modules/config.d.ts +7 -0
- package/dist/modules/config.js +17 -0
- package/dist/modules/registry.js +5 -4
- package/dist/sync/task-claim.d.ts +22 -0
- package/dist/sync/task-claim.js +45 -0
- package/dist/tools/dispatch.js +2 -2
- package/dist/tools/tasks.js +40 -1
- package/package.json +2 -1
- 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
|
+
}
|
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
|
|
@@ -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) {
|
|
@@ -78,6 +78,31 @@ export function herdrWorktreeWorkers(s) {
|
|
|
78
78
|
* queue, after which the option key (or typed text) is the answer. */
|
|
79
79
|
const ANSWER_KEYS = ["Escape", "Enter", "Up", "Down", "Tab", "AltUp", "y", "n", "p", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
|
|
80
80
|
const HERDR_KEYS = { Escape: "esc", Enter: "enter", Up: "up", Down: "down", Tab: "tab", AltUp: "alt+Up" };
|
|
81
|
+
// A question or label may wrap onto several lines; the pane shows them joined.
|
|
82
|
+
const questionText = z.string().trim().min(1).max(4000).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
|
|
83
|
+
const claudeQuestionBody = z.object({
|
|
84
|
+
questions: z.array(z.object({ question: questionText, multiSelect: z.boolean().optional(), options: z.array(questionText).min(1).max(8) })).min(1).max(8),
|
|
85
|
+
answers: z.array(z.object({ optionIndexes: z.array(z.number().int().nonnegative()).max(8),
|
|
86
|
+
text: z.string().max(1000).refine(t => !/[\x00-\x1f\x7f]/.test(t)).optional() })).min(1).max(8),
|
|
87
|
+
});
|
|
88
|
+
/** The phone's answer to Claude's AskUserQuestion: one answer per question,
|
|
89
|
+
* a single option or a typed answer for a single-select question, any
|
|
90
|
+
* options plus an optional typed answer for a multi-select one. */
|
|
91
|
+
function claudeQuestionAnswer(data) {
|
|
92
|
+
const body = claudeQuestionBody.parse(data);
|
|
93
|
+
if (body.answers.length !== body.questions.length)
|
|
94
|
+
throw new BridgeError(400, "Answer every question.");
|
|
95
|
+
const answers = body.answers.map((answer, index) => {
|
|
96
|
+
const question = body.questions[index], options = [...new Set(answer.optionIndexes)], text = answer.text?.trim() ?? "";
|
|
97
|
+
if (options.some(option => option >= question.options.length))
|
|
98
|
+
throw new BridgeError(400, "Choose an available answer.");
|
|
99
|
+
if (question.multiSelect ? !options.length && !text : options.length + (text ? 1 : 0) !== 1) {
|
|
100
|
+
throw new BridgeError(400, question.multiSelect ? "Choose at least one answer." : "Choose one answer for each question.");
|
|
101
|
+
}
|
|
102
|
+
return { options, ...(text ? { text } : {}) };
|
|
103
|
+
});
|
|
104
|
+
return { questions: body.questions.map(q => ({ question: q.question, multiSelect: q.multiSelect, options: q.options.map(label => ({ label })) })), answers };
|
|
105
|
+
}
|
|
81
106
|
/** A secret typed into a terminal prompt: printable, bounded, never logged. */
|
|
82
107
|
const secretText = z.string().min(1).max(256).refine(t => !/[\x00-\x1f\x7f]/.test(t));
|
|
83
108
|
/** An idle agent that has not taken typed text within the first wait
|
|
@@ -344,12 +369,10 @@ export async function paneRoute(ctx, url, data, response) {
|
|
|
344
369
|
if (!holding && (keys.every(key => key === "Escape") ? !["working", "blocked", "waiting", "unknown"].includes(status)
|
|
345
370
|
: !["blocked", "waiting", "unknown"].includes(status)))
|
|
346
371
|
throw new BridgeError(409, keys.every(key => key === "Escape") ? "This agent is no longer working." : "This agent is not waiting for an answer.");
|
|
347
|
-
//
|
|
348
|
-
//
|
|
349
|
-
//
|
|
350
|
-
|
|
351
|
-
if (question) {
|
|
352
|
-
await rpc(target.server, "agent.send_keys", { target: target.pane, keys: question.map(key => HERDR_KEYS[key] ?? key) });
|
|
372
|
+
// An older phone answers a released AskUserQuestion one question at
|
|
373
|
+
// a time with its digits; the Hook walks that question in the pane
|
|
374
|
+
// and submits the set after the last.
|
|
375
|
+
if (await agentHooks.answerReleasedQuestion(target, keys)) {
|
|
353
376
|
result = { ok: true };
|
|
354
377
|
}
|
|
355
378
|
else {
|
|
@@ -469,7 +492,15 @@ export async function paneRoute(ctx, url, data, response) {
|
|
|
469
492
|
result = { ok: true };
|
|
470
493
|
}
|
|
471
494
|
else if (url.pathname === "/v1/questions/answer") {
|
|
472
|
-
|
|
495
|
+
if (target.source === "claude") {
|
|
496
|
+
// Claude's AskUserQuestion, answered in its terminal dialog: the
|
|
497
|
+
// phone names the questions it shows, and the Hook answers only a
|
|
498
|
+
// pane that is drawing exactly those.
|
|
499
|
+
const { questions, answers } = claudeQuestionAnswer(data);
|
|
500
|
+
await agentHooks.answerClaudeQuestions(target, questions, answers);
|
|
501
|
+
}
|
|
502
|
+
else
|
|
503
|
+
await codexQuestions.answer(target, data);
|
|
473
504
|
result = { ok: true };
|
|
474
505
|
}
|
|
475
506
|
else
|
|
@@ -93,6 +93,7 @@ export declare const capabilities: {
|
|
|
93
93
|
overviewStream: boolean;
|
|
94
94
|
speech: boolean;
|
|
95
95
|
transcribe: boolean;
|
|
96
|
+
memoryStore: boolean;
|
|
96
97
|
};
|
|
97
98
|
export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
|
|
98
99
|
export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
|
|
@@ -13,6 +13,7 @@ import { optionalHookPeers, peerRequest } from "./peers.js";
|
|
|
13
13
|
import { candidateRepos, enrollProject } from "./enroll.js";
|
|
14
14
|
import { browseFiles } from "./files.js";
|
|
15
15
|
import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
|
|
16
|
+
import { storeRoute } from "./memory-store.js";
|
|
16
17
|
import { paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
|
|
17
18
|
import { locateProject } from "./locate.js";
|
|
18
19
|
import { gitRoot, launchDirectory, repositoryBranch, webServers } from "./projects.js";
|
|
@@ -25,7 +26,7 @@ import { healthDetails, listsCaller } from "./health.js";
|
|
|
25
26
|
import { defaultPhrenPath } from "../shared.js";
|
|
26
27
|
import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
|
|
27
28
|
import { gitRepository, paneRoute, uploadBody } from "./server-pane-routes.js";
|
|
28
|
-
import { launchSession, workspaceAction } from "./server-launch.js";
|
|
29
|
+
import { launchSession, localConductor, workspaceAction } from "./server-launch.js";
|
|
29
30
|
import { hookMetrics } from "./metrics.js";
|
|
30
31
|
import { streamSpeech } from "./speech.js";
|
|
31
32
|
const CHILD_ACTIVITY_CACHE_MS = 5_000;
|
|
@@ -50,7 +51,7 @@ async function childActivity(source, session) {
|
|
|
50
51
|
export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
|
|
51
52
|
terminal: "ssh-pty", shell: "ssh-pty", herdr: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
|
|
52
53
|
approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
|
|
53
|
-
files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, transcribe: true };
|
|
54
|
+
files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, transcribe: true, memoryStore: true };
|
|
54
55
|
export function capabilitiesForModules(snapshot) {
|
|
55
56
|
const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
|
|
56
57
|
const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
|
|
@@ -182,7 +183,10 @@ export function createRouteHandler(ctx) {
|
|
|
182
183
|
throw new BridgeError(400, "Invalid request origin.");
|
|
183
184
|
requireRoute(modules, request.method ?? "", url.pathname);
|
|
184
185
|
let result;
|
|
185
|
-
if (
|
|
186
|
+
if (url.pathname.startsWith("/v1/store/")) {
|
|
187
|
+
result = await storeRoute(modules.store, request.method ?? "", url, request.method === "POST" ? await body(request) : undefined);
|
|
188
|
+
}
|
|
189
|
+
else if (request.method === "GET") {
|
|
186
190
|
switch (url.pathname) {
|
|
187
191
|
case "/v1/health":
|
|
188
192
|
result = { ...info, codePackage: await codePackageStatus(scheduleStore, modules.has("code")) };
|
|
@@ -207,6 +211,10 @@ export function createRouteHandler(ctx) {
|
|
|
207
211
|
case "/v1/conductor/grants":
|
|
208
212
|
result = { grants: await listGrants() };
|
|
209
213
|
break;
|
|
214
|
+
// Asked by linked peers before they start a conductor: one per connected group.
|
|
215
|
+
case "/v1/conductor":
|
|
216
|
+
result = { computer: info.computer, conductor: await localConductor() ?? null };
|
|
217
|
+
break;
|
|
210
218
|
case "/v1/dispatch/capacity": {
|
|
211
219
|
const live = await servers();
|
|
212
220
|
const snapshots = await Promise.all(live.map(server => snapshot(String(server.session))));
|
|
@@ -175,7 +175,10 @@ export function transcriptStreams(ctx) {
|
|
|
175
175
|
compacting: agentHooks.compacting(target),
|
|
176
176
|
...(historyHealth.stalled ? { historyStalled: true, historyStalledSince: historyHealth.since } : {}),
|
|
177
177
|
modules: info.modules, store: info.store, profile: info.profile, generation: info.generation,
|
|
178
|
-
capabilities: { ...activeCapabilities, asyncQuestions: target.source === "codex" && codexQuestions.available
|
|
178
|
+
capabilities: { ...activeCapabilities, asyncQuestions: target.source === "codex" && codexQuestions.available,
|
|
179
|
+
// Claude's AskUserQuestion is answered in its terminal dialog
|
|
180
|
+
// through /v1/questions/answer, whether or not a hold caught it.
|
|
181
|
+
...(target.source === "claude" ? { questions: true } : {}) }, branch } });
|
|
179
182
|
}
|
|
180
183
|
if (sideAnswers && sideQuestions) {
|
|
181
184
|
for (const { revision, ...side } of sideQuestions.list(target)) {
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** The ElevenLabs key for spoken replies and Scribe dictation. It is machine
|
|
2
|
+
* config, like apns.json: it lives in the Hook's own directory, mode 600, and
|
|
3
|
+
* never in the synced store. ELEVENLABS_API_KEY, ElevenLabs' own convention
|
|
4
|
+
* that its SDKs and MCP server read, wins when set. The Hook runs as a service
|
|
5
|
+
* that doesn't see shell env, so the file is the durable source. */
|
|
6
|
+
export declare const SPEECH_KEY_ENV = "ELEVENLABS_API_KEY";
|
|
7
|
+
export type SpeechKeySource = "environment" | "file";
|
|
8
|
+
export declare function speechKeyFile(): string;
|
|
9
|
+
/** Where the key lived before phren kept its own: the mina trailer config. It
|
|
10
|
+
* is read once to migrate and never written or deleted. */
|
|
11
|
+
export declare function legacySpeechKeyFile(env?: NodeJS.ProcessEnv): string;
|
|
12
|
+
export declare function writeSpeechKey(key: string, file?: string): Promise<void>;
|
|
13
|
+
export interface SpeechKeyPaths {
|
|
14
|
+
env?: NodeJS.ProcessEnv;
|
|
15
|
+
file?: string;
|
|
16
|
+
legacy?: string;
|
|
17
|
+
}
|
|
18
|
+
/** ELEVENLABS_API_KEY, else the stored key. When nothing is stored yet and the
|
|
19
|
+
* mina trailer config has a key, it is copied here once and read from here
|
|
20
|
+
* after. */
|
|
21
|
+
export declare function resolveSpeechKey(paths?: SpeechKeyPaths): Promise<{
|
|
22
|
+
key: string;
|
|
23
|
+
source: SpeechKeySource;
|
|
24
|
+
} | undefined>;
|
|
25
|
+
export declare function readSpeechKey(): Promise<string | undefined>;
|
|
26
|
+
export interface SpeechKeyStatus {
|
|
27
|
+
configured: boolean;
|
|
28
|
+
detail: string;
|
|
29
|
+
problem?: boolean;
|
|
30
|
+
}
|
|
31
|
+
/** Whether this computer has a key, for doctor. Never the key itself, and it
|
|
32
|
+
* doesn't migrate: a read-only check. */
|
|
33
|
+
export declare function speechKeyStatus(paths?: SpeechKeyPaths): Promise<SpeechKeyStatus>;
|