@phren/cli 0.2.16 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/bridge/agent-hooks.d.ts +17 -6
  2. package/dist/bridge/agent-hooks.js +59 -24
  3. package/dist/bridge/claude-question-dialog.d.ts +65 -0
  4. package/dist/bridge/claude-question-dialog.js +210 -0
  5. package/dist/bridge/code-note.d.ts +2 -1
  6. package/dist/bridge/code-note.js +13 -4
  7. package/dist/bridge/code-routes.d.ts +32 -14
  8. package/dist/bridge/code-routes.js +131 -8
  9. package/dist/bridge/command.js +92 -2
  10. package/dist/bridge/computers.d.ts +5 -0
  11. package/dist/bridge/computers.js +10 -4
  12. package/dist/bridge/conductor-group.d.ts +23 -0
  13. package/dist/bridge/conductor-group.js +25 -0
  14. package/dist/bridge/dispatch-returns.d.ts +2 -0
  15. package/dist/bridge/dispatch-returns.js +12 -8
  16. package/dist/bridge/dispatch.d.ts +4 -1
  17. package/dist/bridge/dispatch.js +30 -5
  18. package/dist/bridge/hand-off.js +5 -1
  19. package/dist/bridge/herdr.d.ts +7 -0
  20. package/dist/bridge/herdr.js +53 -2
  21. package/dist/bridge/install.d.ts +0 -4
  22. package/dist/bridge/install.js +3 -3
  23. package/dist/bridge/link.d.ts +48 -0
  24. package/dist/bridge/link.js +136 -0
  25. package/dist/bridge/memory-store.d.ts +23 -0
  26. package/dist/bridge/memory-store.js +152 -0
  27. package/dist/bridge/pair.d.ts +46 -0
  28. package/dist/bridge/pair.js +240 -0
  29. package/dist/bridge/peers.d.ts +9 -0
  30. package/dist/bridge/peers.js +25 -2
  31. package/dist/bridge/protocol.js +20 -1
  32. package/dist/bridge/schedule-watch.d.ts +2 -0
  33. package/dist/bridge/schedule-watch.js +16 -3
  34. package/dist/bridge/server-launch.d.ts +9 -0
  35. package/dist/bridge/server-launch.js +34 -11
  36. package/dist/bridge/server-pane-routes.d.ts +7 -0
  37. package/dist/bridge/server-pane-routes.js +128 -18
  38. package/dist/bridge/server-routes.d.ts +3 -0
  39. package/dist/bridge/server-routes.js +55 -29
  40. package/dist/bridge/server-stream.js +4 -1
  41. package/dist/bridge/speech-key.d.ts +33 -0
  42. package/dist/bridge/speech-key.js +106 -0
  43. package/dist/bridge/speech-transcribe.js +1 -1
  44. package/dist/bridge/speech.d.ts +1 -3
  45. package/dist/bridge/speech.js +2 -16
  46. package/dist/bridge/transcript-preview.d.ts +2 -0
  47. package/dist/bridge/transcript-preview.js +15 -0
  48. package/dist/bridge-hook.mjs +9940 -3601
  49. package/dist/cli/config-policy.js +25 -0
  50. package/dist/cli/extract.d.ts +0 -8
  51. package/dist/cli/extract.js +1 -1
  52. package/dist/cli-handlers.js +6 -0
  53. package/dist/cli-registry.js +21 -9
  54. package/dist/content/learning.js +1 -1
  55. package/dist/content/validate.d.ts +14 -3
  56. package/dist/content/validate.js +174 -114
  57. package/dist/data/access.d.ts +9 -0
  58. package/dist/data/access.js +18 -0
  59. package/dist/data/tasks.d.ts +26 -0
  60. package/dist/data/tasks.js +72 -1
  61. package/dist/entrypoint.js +7 -0
  62. package/dist/generated/memory-ui-graph.browser.js +520 -410
  63. package/dist/governance/policy.js +4 -3
  64. package/dist/governance/rbac.d.ts +1 -1
  65. package/dist/governance/rbac.js +1 -0
  66. package/dist/hooks.d.ts +0 -15
  67. package/dist/hooks.js +1 -1
  68. package/dist/init/init-uninstall.js +13 -3
  69. package/dist/init/init-walkthrough.d.ts +10 -0
  70. package/dist/init/init-walkthrough.js +24 -1
  71. package/dist/init/init.d.ts +5 -0
  72. package/dist/init/init.js +54 -32
  73. package/dist/init/setup.js +19 -5
  74. package/dist/init/store-gitignore.d.ts +0 -5
  75. package/dist/init/store-gitignore.js +0 -8
  76. package/dist/link/context-imports.d.ts +15 -0
  77. package/dist/link/context-imports.js +101 -0
  78. package/dist/link/doctor.js +38 -4
  79. package/dist/mcp/profile.d.ts +0 -4
  80. package/dist/mcp/profile.js +2 -14
  81. package/dist/memory-ui-graph.runtime.js +520 -410
  82. package/dist/modules/code-package.js +10 -2
  83. package/dist/modules/config.d.ts +7 -0
  84. package/dist/modules/config.js +17 -0
  85. package/dist/modules/registry.js +6 -5
  86. package/dist/profile-store.js +39 -3
  87. package/dist/project-topics.d.ts +1 -0
  88. package/dist/project-topics.js +9 -6
  89. package/dist/shared/retrieval.d.ts +0 -2
  90. package/dist/shared/retrieval.js +1 -1
  91. package/dist/sync/task-claim.d.ts +22 -0
  92. package/dist/sync/task-claim.js +45 -0
  93. package/dist/tools/code.js +29 -21
  94. package/dist/tools/config.js +3 -0
  95. package/dist/tools/dispatch.js +3 -3
  96. package/dist/tools/finding.d.ts +11 -0
  97. package/dist/tools/finding.js +154 -99
  98. package/dist/tools/tasks.js +40 -1
  99. package/dist/ui/server.js +18 -1
  100. package/dist/update.js +21 -10
  101. package/package.json +8 -7
  102. package/starter/global/skills/conductor/SKILL.md +42 -10
@@ -10,7 +10,7 @@ const indexProject = async (store, ...args) => (await requireCodePackage(store))
10
10
  import { isValidProjectName } from "../utils-paths.js";
11
11
  import { errorMessage } from "../utils.js";
12
12
  import { logger } from "../logger.js";
13
- import { BridgeError } from "./protocol.js";
13
+ import { BridgeError, bridgeRoot } from "./protocol.js";
14
14
  export async function requireCodePackage(store) {
15
15
  const code = await loadCodePackage(store);
16
16
  if (!code)
@@ -107,12 +107,135 @@ export class CodeRoutes {
107
107
  throw noIndex(project);
108
108
  return { project, ...result.value };
109
109
  }
110
- async recent(projectValue, directoryValue) {
111
- const project = projectSchema.parse(projectValue ?? "");
112
- const result = await (await requireCodePackage(this.store)).recentSymbols(this.store, project, optionalPath(directoryValue));
110
+ /** The checkout this computer indexes for `project`, or a 404 naming the project. */
111
+ async checkout(project) {
112
+ try {
113
+ return fs.realpathSync((await requireCodePackage(this.store)).resolveRepoRoot(this.store, project));
114
+ }
115
+ catch {
116
+ throw new BridgeError(404, `${project} has no checkout on this computer.`);
117
+ }
118
+ }
119
+ async changedIn(project, added) {
120
+ const code = await requireCodePackage(this.store);
121
+ if (typeof code.changedDeclarations !== "function")
122
+ throw new BridgeError(503, "Update @phren/code to see what changed.");
123
+ const result = await code.changedDeclarations(this.store, project, new Map([...added].map(([file, lines]) => [file, [...lines].sort((a, b) => a - b)])));
113
124
  if (!result.available)
114
125
  throw noIndex(project);
115
- return { project, entries: result.value };
126
+ return result.value;
127
+ }
128
+ /**
129
+ * What changed: the functions, types and variables that today's agent
130
+ * sessions edited in this project's checkout, and its last 10 commits,
131
+ * grouped by file, most recent work first. Session edits carry the line
132
+ * numbers they had when made, so a later edit to the same file can shift one.
133
+ */
134
+ async whatChanged(projectValue, now = new Date()) {
135
+ const project = projectSchema.parse(projectValue ?? "");
136
+ const root = await this.checkout(project);
137
+ const code = await requireCodePackage(this.store);
138
+ const added = new Map();
139
+ const take = (patch) => {
140
+ for (const [file, lines] of code.addedLinesByFile(patch)) {
141
+ const set = added.get(file) ?? new Set();
142
+ for (const line of lines)
143
+ set.add(line);
144
+ added.set(file, set);
145
+ }
146
+ };
147
+ const midnight = new Date(now);
148
+ midnight.setHours(0, 0, 0, 0);
149
+ const dir = path.join(bridgeRoot(), "changes");
150
+ const logs = fs.existsSync(dir) ? fs.readdirSync(dir).filter(name => name.endsWith(".jsonl")) : [];
151
+ const today = logs.map(name => ({ file: path.join(dir, name), at: fs.statSync(path.join(dir, name)).mtimeMs }))
152
+ .filter(entry => entry.at >= midnight.getTime()).sort((a, b) => b.at - a.at);
153
+ for (const log of today) {
154
+ for (const line of fs.readFileSync(log.file, "utf8").split("\n")) {
155
+ if (!line.trim())
156
+ continue;
157
+ let record;
158
+ try {
159
+ record = JSON.parse(line);
160
+ }
161
+ catch {
162
+ continue;
163
+ }
164
+ for (const file of record.files ?? []) {
165
+ if (typeof file.root !== "string" || typeof file.patch !== "string")
166
+ continue;
167
+ let same = false;
168
+ try {
169
+ same = fs.realpathSync(file.root) === root;
170
+ }
171
+ catch {
172
+ same = false;
173
+ }
174
+ if (same)
175
+ take(file.patch);
176
+ }
177
+ }
178
+ }
179
+ // A repository's first commit adds every file; it is the import, not work.
180
+ try {
181
+ take(await git(root, "-c", "log.showRoot=false", "log", "-10", "--format=", "-p", "-U0", "--no-color", "--no-ext-diff"));
182
+ }
183
+ catch { /* A checkout without commits yet has only its session edits. */ }
184
+ const items = await this.changedIn(project, added);
185
+ const files = [];
186
+ for (const item of items) {
187
+ let group = files.find(entry => entry.path === item.file);
188
+ if (!group) {
189
+ group = { path: item.file, items: [] };
190
+ files.push(group);
191
+ }
192
+ group.items.push(item);
193
+ }
194
+ return { project, files };
195
+ }
196
+ /**
197
+ * Per-file counts for the Changes tree's chips: functions and types the
198
+ * working tree changes or adds (variables stay out to keep a chip short).
199
+ * An untracked file is new throughout.
200
+ */
201
+ async changeCounts(projectValue, pathsValue) {
202
+ const project = projectSchema.parse(projectValue ?? "");
203
+ let raw;
204
+ try {
205
+ raw = JSON.parse(pathsValue ?? "[]");
206
+ }
207
+ catch {
208
+ throw new BridgeError(400, "Choose valid paths.");
209
+ }
210
+ const paths = [...new Set(z.array(relativePathSchema).min(1).max(200).parse(raw))];
211
+ const root = await this.checkout(project);
212
+ const code = await requireCodePackage(this.store);
213
+ const added = new Map();
214
+ for (const [file, lines] of code.addedLinesByFile(await git(root, "diff", "HEAD", "-U0", "--no-color", "--no-ext-diff", "--", ...paths).catch(() => "")))
215
+ added.set(file, new Set(lines));
216
+ const untracked = (await git(root, "ls-files", "--others", "--exclude-standard", "--", ...paths).catch(() => "")).split("\n").filter(Boolean);
217
+ for (const file of untracked) {
218
+ let count = 0;
219
+ try {
220
+ count = fs.readFileSync(path.join(root, file), "utf8").split("\n").length;
221
+ }
222
+ catch {
223
+ continue;
224
+ }
225
+ added.set(file, new Set(Array.from({ length: count }, (_, index) => index + 1)));
226
+ }
227
+ const items = await this.changedIn(project, added);
228
+ const entries = paths.map(file => {
229
+ const mine = items.filter(item => item.file === file || item.file.startsWith(file + "/"));
230
+ const tally = (family) => ({
231
+ changed: mine.filter(item => item.family === family && !item.isNew).length,
232
+ added: mine.filter(item => item.family === family && item.isNew).length,
233
+ });
234
+ const first = mine.find(item => item.family !== "variable");
235
+ return { path: file, functions: tally("function"), types: tally("type"),
236
+ ...(first ? { first: `${first.file}::${first.parent ? first.parent + "." : ""}${first.name}` } : {}) };
237
+ });
238
+ return { project, entries };
116
239
  }
117
240
  /** Turns code intelligence off for a project: its index is deleted, and
118
241
  * the reindexer follows only projects that have one, so nothing rebuilds it
@@ -173,7 +296,7 @@ export class CodeRoutes {
173
296
  if (!result.available)
174
297
  throw noIndex(project);
175
298
  if (!result.value)
176
- throw new BridgeError(404, `No symbol "${symbol}" in ${project}.`);
299
+ throw new BridgeError(404, `Nothing named "${symbol}" in ${project}.`);
177
300
  return { project, definition: { ...result.value, findings: (await requireCodePackage(this.store)).findingsCitingSymbol(this.store, project, (await requireCodePackage(this.store)).citationSymbolName(result.value.symbol)) } };
178
301
  }
179
302
  async references(projectValue, symbolValue, limitValue) {
@@ -184,7 +307,7 @@ export class CodeRoutes {
184
307
  if (!result.available)
185
308
  throw noIndex(project);
186
309
  if (!result.value)
187
- throw new BridgeError(404, `No symbol "${symbol}" in ${project}.`);
310
+ throw new BridgeError(404, `Nothing named "${symbol}" in ${project}.`);
188
311
  return { project, references: result.value };
189
312
  }
190
313
  async usage(projectValue, topValue) {
@@ -286,7 +409,7 @@ export class CodeReindexer {
286
409
  this.running.add(project);
287
410
  try {
288
411
  const result = await this.index(this.store, project, { full });
289
- this.log(`re-indexed ${project}${full ? " (full)" : ""}: ${result.parsed} parsed, ${result.symbols} symbols, ${result.durationMs} ms`);
412
+ this.log(`re-indexed ${project}${full ? " (full)" : ""}: ${result.parsed} parsed, ${result.symbols} declarations, ${result.durationMs} ms`);
290
413
  }
291
414
  catch (error) {
292
415
  this.log(`re-index of ${project} failed: ${errorMessage(error)}`);
@@ -6,9 +6,12 @@ import { servers } from "./herdr.js";
6
6
  import { agentHook } from "./agent-hooks.js";
7
7
  import { object, provider } from "./protocol.js";
8
8
  import { apnsSetupSteps } from "./push.js";
9
+ import { speechKeyFile, speechKeyStatus, writeSpeechKey } from "./speech-key.js";
9
10
  import { AccountUsageReader, captureClaudeUsage } from "./usage.js";
10
11
  import { acceptComputer, enrollComputer } from "./computers.js";
12
+ import { addPeerFromLink, discoverComputers, linkComputer } from "./link.js";
11
13
  import { ARCHIVE_MAX_FOLDERS, archiveFinishedFanouts, FANOUTS_ARCHIVE_USAGE, parseFanoutArchiveFlags } from "./fanouts.js";
14
+ const LINK_USAGE = "Usage: phren bridge link <ssh-host> [--name <its name here>] [--as <this computer's name there>] [--back-address <address it dials>] [--yes]";
12
15
  export async function runBridge(args, version) {
13
16
  switch (args[0]) {
14
17
  case "enroll-computer": {
@@ -22,6 +25,46 @@ export async function runBridge(args, version) {
22
25
  throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
23
26
  break;
24
27
  }
28
+ case "discover": {
29
+ const { reachable, checked } = await discoverComputers();
30
+ if (!reachable.length)
31
+ console.log(`No unlinked computers running Phren Hook answered over ssh (checked ${checked.length}: ${checked.join(", ") || "none"}).`);
32
+ else {
33
+ console.log("Reachable over ssh, running Phren Hook, and not linked:");
34
+ for (const item of reachable)
35
+ console.log(` ${item.host} (${item.user}) link with: phren bridge link ${item.host}`);
36
+ }
37
+ break;
38
+ }
39
+ case "link": {
40
+ const host = args[1];
41
+ const flag = (name) => { const index = args.indexOf(name); return index > 1 ? args[index + 1] : undefined; };
42
+ if (!host || host.startsWith("-"))
43
+ throw new Error(LINK_USAGE);
44
+ if (!args.includes("--yes")) {
45
+ if (!process.stdin.isTTY)
46
+ throw new Error(`Linking ${host} lets each computer run agents on the other. Pass --yes to confirm.`);
47
+ const { createInterface } = await import("node:readline/promises");
48
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
49
+ const answer = await prompt.question(`Link this computer and ${host} both ways, so each can list and start agents on the other? [y/N] `);
50
+ prompt.close();
51
+ if (!/^y(es)?$/i.test(answer.trim())) {
52
+ console.log("Not linked.");
53
+ return 1;
54
+ }
55
+ }
56
+ const result = await linkComputer(host, { name: flag("--name"), as: flag("--as"), backAddress: flag("--back-address") });
57
+ console.log(JSON.stringify(result, null, 2));
58
+ return result.reachable && result.remote.reachable ? 0 : 1;
59
+ }
60
+ case "add-peer": {
61
+ // The receiving half of `phren bridge link`, run by the linking computer over ssh.
62
+ const chunks = [];
63
+ for await (const chunk of process.stdin)
64
+ chunks.push(chunk);
65
+ console.log(JSON.stringify(await addPeerFromLink(Buffer.concat(chunks).toString("utf8"))));
66
+ break;
67
+ }
25
68
  case "fanouts": {
26
69
  if (args[1] !== "archive")
27
70
  throw new Error(FANOUTS_ARCHIVE_USAGE);
@@ -33,6 +76,14 @@ export async function runBridge(args, version) {
33
76
  console.log(`${doing} ${moved.length} fan-out job(s); ${removal} ${deleted} past the ${ARCHIVE_MAX_FOLDERS}-folder cap.`);
34
77
  break;
35
78
  }
79
+ case "speech-key": {
80
+ // The key comes from stdin, never argv, so it stays out of ps and shell history.
81
+ if (args[1] !== "set" || args.length !== 2)
82
+ throw new Error(SPEECH_KEY_USAGE);
83
+ await writeSpeechKey(await readSecret("ElevenLabs API key: "));
84
+ console.log(`Stored the ElevenLabs key in ${speechKeyFile()} (mode 600).`);
85
+ break;
86
+ }
36
87
  case "usage-statusline":
37
88
  await captureClaudeUsage(args[1] || "");
38
89
  break;
@@ -63,19 +114,20 @@ export async function runBridge(args, version) {
63
114
  break;
64
115
  case "doctor": {
65
116
  const helper = await health(), muxes = await servers();
66
- const push = approvalPushCheck(helper);
117
+ const push = approvalPushCheck(helper), speech = await speechKeyStatus();
67
118
  // Chat needs Herdr; a plain project shell or agent over SSH does not.
68
119
  console.log(JSON.stringify({ ok: true, helper, herdr: muxes, checks: {
69
120
  privateSocket: true, protocol: true, independentHelper: true,
70
121
  herdrRunning: muxes.length > 0, terminal: "SSH PTY; authorize the Phren device key with pty",
71
122
  shell: muxes.length > 0 ? "available" : "Herdr is not running: chat is unavailable, project shells and agents still open over SSH",
72
123
  approvalPush: push.configured ? "configured" : "not configured",
124
+ speechKey: speech.configured ? "configured" : "not configured", speechKeyDetail: speech.detail,
73
125
  }, ...(push.warning ? { warnings: [push.warning] } : {}) }, null, 2));
74
126
  if (push.warning)
75
127
  console.error(`warning: ${push.warning}`);
76
128
  break;
77
129
  }
78
- default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|fanouts archive>");
130
+ default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|discover|link|fanouts archive|speech-key set>");
79
131
  }
80
132
  return 0;
81
133
  }
@@ -85,3 +137,41 @@ export function approvalPushCheck(helper) {
85
137
  const configured = object(helper.capabilities).approvalPush === "direct-apns";
86
138
  return configured ? { configured } : { configured, warning: apnsSetupSteps() };
87
139
  }
140
+ const SPEECH_KEY_USAGE = "Usage: phren bridge speech-key set (paste the key when asked, or pipe it on stdin)";
141
+ /** One line from stdin: piped as is, or typed at a prompt without echo. */
142
+ async function readSecret(prompt) {
143
+ const stdin = process.stdin;
144
+ if (!stdin.isTTY) {
145
+ let text = "";
146
+ for await (const chunk of stdin)
147
+ text += chunk;
148
+ return text;
149
+ }
150
+ process.stderr.write(prompt);
151
+ stdin.setEncoding("utf8");
152
+ stdin.setRawMode(true);
153
+ stdin.resume();
154
+ return new Promise((resolve, reject) => {
155
+ let value = "";
156
+ const finish = () => { stdin.off("data", onData); stdin.setRawMode(false); stdin.pause(); process.stderr.write("\n"); };
157
+ const onData = (chunk) => {
158
+ for (const char of chunk) {
159
+ if (char === "\r" || char === "\n") {
160
+ finish();
161
+ resolve(value);
162
+ return;
163
+ }
164
+ if (char === "\u0003") {
165
+ finish();
166
+ reject(new Error("Cancelled."));
167
+ return;
168
+ }
169
+ if (char === "\u007f" || char === "\b")
170
+ value = value.slice(0, -1);
171
+ else
172
+ value += char;
173
+ }
174
+ };
175
+ stdin.on("data", onData);
176
+ });
177
+ }
@@ -7,3 +7,8 @@ export declare function computerKeyLine(name: string, publicKey: string): string
7
7
  export declare function enrollComputer(name: string, root?: string): Promise<string>;
8
8
  /** Accept a public key, rebuilding the restrictions rather than trusting supplied options. */
9
9
  export declare function acceptComputer(name: string, input: string, sshDirectory?: string): Promise<void>;
10
+ /**
11
+ * Append one authorized_keys line under a lock, refusing when `conflicts`
12
+ * matches an existing line and leaving an identical line in place.
13
+ */
14
+ export declare function appendAuthorizedKey(line: string, conflicts: (existing: string) => boolean, conflictMessage: string, sshDirectory?: string): Promise<void>;
@@ -74,6 +74,14 @@ export async function acceptComputer(name, input, sshDirectory = path.join(homed
74
74
  const raw = input.trim();
75
75
  const publicKey = publicComputerKey(raw.startsWith(prefix) ? raw.slice(prefix.length) : raw);
76
76
  const line = computerKeyLine(name, publicKey);
77
+ const encoded = publicKey.split(" ")[1];
78
+ await appendAuthorizedKey(line, existing => existing.endsWith(` phren-computer:${name}`) || existing.split(/\s+/).includes(encoded), "This name or key is already enrolled differently. Revoke the old line explicitly first.", sshDirectory);
79
+ }
80
+ /**
81
+ * Append one authorized_keys line under a lock, refusing when `conflicts`
82
+ * matches an existing line and leaving an identical line in place.
83
+ */
84
+ export async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory = path.join(homedir(), ".ssh")) {
77
85
  const directory = await lstat(sshDirectory).catch(() => undefined);
78
86
  if (directory && (!directory.isDirectory() || directory.isSymbolicLink()))
79
87
  throw new BridgeError(409, "Refusing an unexpected SSH directory.");
@@ -95,10 +103,8 @@ export async function acceptComputer(name, input, sshDirectory = path.join(homed
95
103
  await chmod(file, 0o600);
96
104
  return;
97
105
  }
98
- const encoded = publicKey.split(" ")[1];
99
- if (lines.some(existing => existing.endsWith(` phren-computer:${name}`) || existing.split(/\s+/).includes(encoded))) {
100
- throw new BridgeError(409, "This name or key is already enrolled differently. Revoke the old line explicitly first.");
101
- }
106
+ if (lines.some(conflicts))
107
+ throw new BridgeError(409, conflictMessage);
102
108
  await writeFile(temporary, before + (before && !before.endsWith("\n") ? "\n" : "") + line + "\n", { mode: 0o600, flag: "wx" });
103
109
  const current = await regularFile(file) ? await readFile(file, "utf8") : "";
104
110
  if (current !== before)
@@ -0,0 +1,23 @@
1
+ import { type HookPeer } from "./peers.js";
2
+ import { type Json } from "./protocol.js";
3
+ /**
4
+ * One conductor per connected group. A group is this computer and the peers
5
+ * in its hooks.yaml; `phren bridge link` links a new computer with every
6
+ * member, so one hop reaches the whole group. Each peer answers
7
+ * `GET /v1/conductor` with its own live conductor, if any.
8
+ */
9
+ export interface GroupConductor {
10
+ /** A live conductor on a linked peer. */
11
+ found?: {
12
+ computer: string;
13
+ target?: Json;
14
+ };
15
+ /** Peers that could not say, so a conductor there cannot be ruled out. */
16
+ unchecked: {
17
+ computer: string;
18
+ error: string;
19
+ }[];
20
+ }
21
+ type Ask = (peer: HookPeer, route: string, data?: Json, timeout?: number) => Promise<Json>;
22
+ export declare function groupConductor(peers: readonly HookPeer[], ask?: Ask): Promise<GroupConductor>;
23
+ export {};
@@ -0,0 +1,25 @@
1
+ import { disabledHint } from "../modules/registry.js";
2
+ import { peerRequest } from "./peers.js";
3
+ import { BridgeError, object } from "./protocol.js";
4
+ export async function groupConductor(peers, ask = peerRequest) {
5
+ const answers = await Promise.all(peers.map(async (peer) => {
6
+ try {
7
+ const conductor = (await ask(peer, "/v1/conductor", undefined, 8_000)).conductor;
8
+ return { peer, conductor: conductor && typeof conductor === "object" ? object(conductor) : undefined };
9
+ }
10
+ catch (error) {
11
+ // With its conductor module off, a peer cannot run a conductor. An
12
+ // older Hook has no /v1/conductor and cannot rule one out.
13
+ if (error instanceof BridgeError && error.status === 404 && error.message === disabledHint("conductor"))
14
+ return { peer };
15
+ const message = error instanceof BridgeError && error.status === 404 ? "Its Hook is too old to report a conductor."
16
+ : error instanceof Error ? error.message : "Unreachable.";
17
+ return { peer, error: message };
18
+ }
19
+ }));
20
+ const hit = answers.find(answer => answer.conductor);
21
+ return {
22
+ ...(hit ? { found: { computer: hit.peer.name, ...(hit.conductor.target ? { target: object(hit.conductor.target) } : {}) } } : {}),
23
+ unchecked: answers.flatMap(answer => "error" in answer && answer.error ? [{ computer: answer.peer.name, error: answer.error }] : []),
24
+ };
25
+ }
@@ -59,6 +59,8 @@ export interface WorkerObservation {
59
59
  completed?: boolean;
60
60
  reply?: string;
61
61
  truncated?: boolean;
62
+ /** The error the harness ended the turn on (Codex's usage limit). */
63
+ error?: string;
62
64
  }
63
65
  export interface WorkerReaders {
64
66
  snapshot: (server: string) => Promise<Json>;
@@ -74,7 +74,7 @@ export async function workerStates(input, readers = defaultReaders) {
74
74
  return { state, ...(session ? { session } : {}) };
75
75
  const turn = await readers.finalTurn(target.source, session).catch(() => undefined);
76
76
  const reply = turn?.lastAssistant ? truncateUtf8(turn.lastAssistant) : undefined;
77
- return { state, session, completed: turn?.completed === true,
77
+ return { state, session, completed: turn?.completed === true, ...(turn?.error ? { error: turn.error } : {}),
78
78
  ...(reply ? { reply: reply.text, ...(reply.truncated ? { truncated: true } : {}) } : {}) };
79
79
  }));
80
80
  return { workers };
@@ -82,7 +82,7 @@ export async function workerStates(input, readers = defaultReaders) {
82
82
  const observationSchema = z.object({
83
83
  state: z.enum(["working", "idle", "done", "blocked", "unknown", "gone", "unavailable"]),
84
84
  session: z.string().max(200).optional(), completed: z.boolean().optional(),
85
- reply: z.string().max(REPLY_LIMIT).optional(), truncated: z.boolean().optional(),
85
+ reply: z.string().max(REPLY_LIMIT).optional(), truncated: z.boolean().optional(), error: z.string().max(500).optional(),
86
86
  }).passthrough();
87
87
  function turnKey(reply) {
88
88
  return reply ? createHash("sha256").update(reply).digest("hex").slice(0, 16) : undefined;
@@ -104,7 +104,9 @@ export function observe(receipt, value, now) {
104
104
  }
105
105
  }
106
106
  const sawWorking = receipt.worker?.sawWorking === true || seen.state === "working" || seen.state === "blocked";
107
- const question = seen.completed && seen.reply ? ownerQuestion(seen.reply) : undefined;
107
+ // A turn the harness ended on an error (a usage limit) failed, reply or not.
108
+ const failed = seen.completed && seen.error ? seen.error : undefined;
109
+ const question = seen.completed && seen.reply && !failed ? ownerQuestion(seen.reply) : undefined;
108
110
  let next;
109
111
  if (seen.state === "gone")
110
112
  next = "gone";
@@ -112,11 +114,13 @@ export function observe(receipt, value, now) {
112
114
  next = "working";
113
115
  else if (seen.state === "blocked")
114
116
  next = "blocked";
117
+ else if (failed)
118
+ next = "failed";
115
119
  else if (seen.completed)
116
120
  next = question ? "needs-you" : "done";
117
121
  else
118
122
  next = sawWorking || now - Date.parse(receipt.createdAt) > IDLE_GRACE_MS ? "done" : "working";
119
- const turn = next === "done" || next === "needs-you" ? turnKey(seen.reply) : undefined;
123
+ const turn = next === "done" || next === "needs-you" ? turnKey(seen.reply) : next === "failed" ? turnKey(failed) : undefined;
120
124
  const previous = receipt.worker?.state;
121
125
  // The same finished state with a different final reply is a new turn: the
122
126
  // worker took more work (a hand_off) and finished again between two polls.
@@ -132,17 +136,17 @@ export function observe(receipt, value, now) {
132
136
  if (next !== "working") {
133
137
  receipt.returned = { state: next, at, read: false,
134
138
  ...(seen.reply && (next === "done" || next === "needs-you") ? { reply: seen.reply, ...(seen.truncated ? { truncated: true } : {}) } : {}),
135
- ...(question ? { question } : {}), ...(turn ? { turn } : {}) };
139
+ ...(failed ? { error: failed } : {}), ...(question ? { question } : {}), ...(turn ? { turn } : {}) };
136
140
  }
137
141
  return true;
138
142
  }
139
143
  /** One line for the dispatching agent: who returned, how, and where to read it. */
140
144
  export function noticeLine(receipts) {
141
145
  const clean = (value, max) => value.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
142
- const word = { "done": "done", "needs-you": "needs you", "blocked": "blocked", "gone": "gone" };
146
+ const word = { "done": "done", "needs-you": "needs you", "failed": "failed", "blocked": "blocked", "gone": "gone" };
143
147
  const describe = (receipt, room) => {
144
148
  const returned = receipt.returned;
145
- const detail = returned.state === "needs-you" ? returned.question
149
+ const detail = returned.state === "needs-you" ? returned.question : returned.state === "failed" ? returned.error
146
150
  : returned.state === "done" ? returned.reply?.split("\n").find(line => line.trim()) : undefined;
147
151
  const excerpt = detail ? clean(detail.replace(/[*_`#>]+/g, ""), room) : "";
148
152
  return `${clean(receipt.computer, 60)} ${clean(receipt.label, 80)} ${word[returned.state]}${excerpt ? `, ${excerpt}` : ""}`;
@@ -157,7 +161,7 @@ export function returnRow(receipt) {
157
161
  const returned = receipt.returned;
158
162
  return { id: receipt.id, computer: receipt.computer, project: receipt.project, label: receipt.label, harness: receipt.harness,
159
163
  state: returned.state, at: returned.at, ...(returned.reply !== undefined ? { reply: returned.reply } : {}),
160
- ...(returned.truncated ? { truncated: true } : {}), ...(returned.question ? { question: returned.question } : {}),
164
+ ...(returned.truncated ? { truncated: true } : {}), ...(returned.error ? { error: returned.error } : {}), ...(returned.question ? { question: returned.question } : {}),
161
165
  ...(receipt.target ? { target: receipt.target } : {}) };
162
166
  }
163
167
  const originKey = (origin) => JSON.stringify([origin.server, origin.workspace, origin.tab, origin.pane, origin.terminal]);
@@ -48,7 +48,7 @@ export declare const originPaneSchema: z.ZodObject<{
48
48
  pane: z.ZodString;
49
49
  }, z.core.$strict>;
50
50
  export type OriginPane = z.infer<typeof originPaneSchema>;
51
- export declare const workerStates: readonly ["working", "done", "needs-you", "blocked", "gone"];
51
+ export declare const workerStates: readonly ["working", "done", "needs-you", "failed", "blocked", "gone"];
52
52
  export type WorkerState = typeof workerStates[number];
53
53
  declare const receiptSchema: z.ZodObject<{
54
54
  computer: z.ZodUnion<readonly [z.ZodLiteral<"anywhere">, z.ZodString]>;
@@ -148,6 +148,7 @@ declare const receiptSchema: z.ZodObject<{
148
148
  state: z.ZodEnum<{
149
149
  blocked: "blocked";
150
150
  done: "done";
151
+ failed: "failed";
151
152
  gone: "gone";
152
153
  "needs-you": "needs-you";
153
154
  working: "working";
@@ -160,11 +161,13 @@ declare const receiptSchema: z.ZodObject<{
160
161
  state: z.ZodEnum<{
161
162
  blocked: "blocked";
162
163
  done: "done";
164
+ failed: "failed";
163
165
  gone: "gone";
164
166
  "needs-you": "needs-you";
165
167
  }>;
166
168
  at: z.ZodString;
167
169
  reply: z.ZodOptional<z.ZodString>;
170
+ error: z.ZodOptional<z.ZodString>;
168
171
  truncated: z.ZodOptional<z.ZodBoolean>;
169
172
  question: z.ZodOptional<z.ZodString>;
170
173
  turn: z.ZodOptional<z.ZodString>;
@@ -26,7 +26,7 @@ export const dispatchSchema = z.object({
26
26
  const remoteTarget = z.union([targetSchema, startingTargetSchema]);
27
27
  /** The local pane that asked for the dispatch, where return notices go. */
28
28
  export const originPaneSchema = z.object({ server: serverName, workspace: id, tab: id, pane: id }).strict();
29
- export const workerStates = ["working", "done", "needs-you", "blocked", "gone"];
29
+ export const workerStates = ["working", "done", "needs-you", "failed", "blocked", "gone"];
30
30
  const timestamp = z.string().datetime();
31
31
  const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
32
32
  id: z.string().uuid(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
@@ -41,10 +41,10 @@ const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
41
41
  worker: z.object({ state: z.enum(workerStates), since: timestamp, checkedAt: timestamp, sawWorking: z.boolean() }).strict().optional()
42
42
  .describe("The worker pane's last observed state."),
43
43
  returned: z.object({
44
- state: z.enum(["done", "needs-you", "blocked", "gone"]), at: timestamp,
45
- reply: z.string().max(4000).optional(), truncated: z.boolean().optional(), question: z.string().max(200).optional(),
44
+ state: z.enum(["done", "needs-you", "failed", "blocked", "gone"]), at: timestamp,
45
+ reply: z.string().max(4000).optional(), error: z.string().max(500).optional(), truncated: z.boolean().optional(), question: z.string().max(200).optional(),
46
46
  turn: z.string().regex(/^[a-f0-9]{16}$/).optional(), read: z.boolean(), notifiedAt: timestamp.optional(),
47
- }).strict().optional().describe("The latest return: the worker finished, needs the owner, is blocked or is gone."),
47
+ }).strict().optional().describe("The latest return: the worker finished, needs the owner, failed, is blocked or is gone."),
48
48
  });
49
49
  export async function dispatchProjectDirectory(project) {
50
50
  const name = projectName.parse(project);
@@ -159,6 +159,31 @@ async function settledTarget(peer, launched, harness) {
159
159
  }
160
160
  return undefined;
161
161
  }
162
+ /**
163
+ * Sends the brief. A fresh agent can read `unknown` to Herdr for a while (long
164
+ * on a loaded machine), and the Hook refuses a prompt to such a pane before
165
+ * typing anything. So that refusal is retried while the pane is still
166
+ * unclassified; a pane that is blocked or waiting really needs its terminal,
167
+ * and that refusal stands.
168
+ */
169
+ async function sendBrief(peer, target, text) {
170
+ for (let attempt = 0;; attempt++) {
171
+ try {
172
+ return await peer.request("/v1/prompt", { target, text });
173
+ }
174
+ catch (error) {
175
+ const unsettled = error instanceof BridgeError && error.status === 409 && /needs input in the terminal first/.test(error.message);
176
+ if (!unsettled || attempt >= 20)
177
+ throw error;
178
+ const panes = await peer.request(`/v1/workspaces/panes?server=${encodeURIComponent(peer.server)}&groupId=${encodeURIComponent(String(target.workspace))}&childId=${encodeURIComponent(String(target.tab))}`).catch(() => undefined);
179
+ const pane = (Array.isArray(panes?.panes) ? panes.panes : []).find((p) => p && typeof p === "object" && p.id === target.pane);
180
+ const status = pane?.agentStatus;
181
+ if (typeof status === "string" && ["blocked", "waiting"].includes(status))
182
+ throw error;
183
+ await new Promise(resolve => setTimeout(resolve, 1_000));
184
+ }
185
+ }
186
+ }
162
187
  export class DispatchService {
163
188
  identity;
164
189
  local;
@@ -236,7 +261,7 @@ export class DispatchService {
236
261
  receipt.state = "sending";
237
262
  receipt.updatedAt = new Date().toISOString();
238
263
  await save(receipt);
239
- const result = await peer.request("/v1/prompt", { target: receipt.target, text: prompt });
264
+ const result = await sendBrief(peer, receipt.target, prompt);
240
265
  receipt.state = result.ok === true && result.deliveryUncertain !== true ? "accepted" : "uncertain";
241
266
  }
242
267
  catch (error) {
@@ -74,12 +74,16 @@ function sessionsFrom(overview, computer, local, now = Date.now()) {
74
74
  for (const tab of objects(group.children)) {
75
75
  if (typeof tab.agent !== "string")
76
76
  continue;
77
+ // A worker opened as a tab in the conductor's workspace is named by its
78
+ // tab (Herdr's bare tab numbers do not count), never as the conductor.
79
+ const inConductorWorkspace = tab.role !== "conductor" && objects(group.children).some(other => other.role === "conductor");
80
+ const label = inConductorWorkspace ? (typeof tab.label === "string" && !/^\d+$/.test(tab.label) ? tab.label : undefined) : group.label;
77
81
  const target = targetSchema.safeParse(tab.target);
78
82
  const cwd = typeof tab.cwd === "string" ? tab.cwd : "";
79
83
  const text = (value) => typeof value === "string" && value ? value : undefined;
80
84
  const changedAt = typeof tab.lastChangedAt === "string" ? Date.parse(tab.lastChangedAt) : NaN;
81
85
  // A conductor sits in the store, not a project.
82
- sessions.push({ computer, local, project: tab.role === "conductor" ? undefined : text(cwd.split("/").filter(Boolean).at(-1)), label: text(group.label),
86
+ sessions.push({ computer, local, project: tab.role === "conductor" ? undefined : text(cwd.split("/").filter(Boolean).at(-1)), label: text(label),
83
87
  title: text(tab.title), agent: tab.agent, status: text(tab.agentStatus), role: text(tab.role),
84
88
  branch: text(tab.branch), model: text(tab.model), ...(target.success ? { target: target.data } : {}),
85
89
  ...(Number.isFinite(changedAt) ? { idleFor: Math.max(0, Math.floor((now - changedAt) / 1000)) } : {}) });
@@ -65,6 +65,13 @@ export declare function findPane(s: Json, address: PaneAddress): Json | undefine
65
65
  export declare function isConductorName(name: string | undefined): boolean;
66
66
  export declare function workspaceSnapshot(s: Json, contextUsedPercent?: ReadonlyMap<Json, number>, approvalPanes?: ReadonlySet<string>, lastChanged?: ReadonlyMap<string, string>): Json;
67
67
  export declare function paneIdentity(server: string, pane: Json, fresh?: boolean): Promise<string | undefined>;
68
+ /** Copilot CLI changes conversation inside one process (/new, /clear,
69
+ * /resume) and runs its sessionStart hook only once that conversation's first
70
+ * prompt is submitted. Until then Herdr's reported session and the recorded
71
+ * binding still name the previous conversation, so a phone send aimed there
72
+ * lands in the new one and its UserPromptSubmit check refuses it, every time.
73
+ * The process log Copilot names by PID records each switch as it happens. */
74
+ export declare function copilotForegroundSession(pids: number[], home?: string): Promise<string | undefined>;
68
75
  /** Bind first-send permission to the actual terminal/process, never a cwd or
69
76
  * a guessed conversation. Tokens expire naturally when the Hook/process restarts. */
70
77
  export declare function paneChatState(server: string, pane: Json, options?: {