@phren/cli 0.3.35 → 0.3.36

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 (68) hide show
  1. package/dist/bridge/agent-hooks.d.ts +11 -1
  2. package/dist/bridge/agent-hooks.js +56 -19
  3. package/dist/bridge/changes.js +18 -9
  4. package/dist/bridge/dispatch-command.js +3 -1
  5. package/dist/bridge/health.js +3 -1
  6. package/dist/bridge/host-key.d.ts +16 -0
  7. package/dist/bridge/host-key.js +35 -0
  8. package/dist/bridge/launch-brief.d.ts +2 -0
  9. package/dist/bridge/launch-brief.js +5 -0
  10. package/dist/bridge/link.js +11 -4
  11. package/dist/bridge/owner-inbox-sources.d.ts +5 -0
  12. package/dist/bridge/owner-inbox-sources.js +94 -0
  13. package/dist/bridge/owner-inbox-view.js +20 -1
  14. package/dist/bridge/owner-inbox.d.ts +7 -3
  15. package/dist/bridge/owner-inbox.js +113 -69
  16. package/dist/bridge/pair.js +3 -2
  17. package/dist/bridge/server.js +3 -23
  18. package/dist/bridge/sudo.d.ts +36 -6
  19. package/dist/bridge/sudo.js +180 -37
  20. package/dist/bridge/worker-reports.d.ts +8 -1
  21. package/dist/bridge/worker-reports.js +28 -7
  22. package/dist/bridge-hook.mjs +809 -471
  23. package/dist/clanker.d.ts +54 -0
  24. package/dist/clanker.js +188 -0
  25. package/dist/cli/config.js +30 -0
  26. package/dist/cli/hooks-output.d.ts +1 -1
  27. package/dist/cli/hooks-output.js +28 -21
  28. package/dist/cli/hooks.js +1 -1
  29. package/dist/cli/namespaces-skills.js +2 -2
  30. package/dist/cli/namespaces-tasks.js +46 -7
  31. package/dist/cli/session-start.js +12 -3
  32. package/dist/cli/session-stop.js +9 -0
  33. package/dist/cli/team.js +3 -0
  34. package/dist/cli-handlers.js +7 -0
  35. package/dist/cli-registry.js +1 -0
  36. package/dist/data/task-format.d.ts +5 -1
  37. package/dist/data/task-format.js +13 -5
  38. package/dist/index.js +82 -50
  39. package/dist/init/init-configure.d.ts +2 -0
  40. package/dist/init/init-configure.js +12 -0
  41. package/dist/init/init-uninstall.js +21 -2
  42. package/dist/init/init.d.ts +2 -0
  43. package/dist/init/init.js +11 -3
  44. package/dist/init/preferences.d.ts +6 -0
  45. package/dist/init/teardown.js +18 -4
  46. package/dist/link/doctor.js +2 -2
  47. package/dist/link/link.js +9 -0
  48. package/dist/link/refresh.d.ts +10 -0
  49. package/dist/link/refresh.js +34 -0
  50. package/dist/mcp/local-index.d.ts +20 -0
  51. package/dist/mcp/local-index.js +39 -1
  52. package/dist/shared/index.d.ts +14 -0
  53. package/dist/shared/index.js +88 -74
  54. package/dist/shared/retrieval.js +1 -1
  55. package/dist/skill/files.js +40 -11
  56. package/dist/skill/registry.d.ts +6 -0
  57. package/dist/skill/registry.js +21 -5
  58. package/dist/task/lifecycle.js +3 -1
  59. package/dist/tools/dispatch.js +5 -2
  60. package/dist/tools/finding.js +20 -11
  61. package/dist/tools/graph.d.ts +2 -0
  62. package/dist/tools/graph.js +2 -0
  63. package/dist/tools/search.d.ts +2 -0
  64. package/dist/tools/search.js +88 -6
  65. package/dist/tools/tasks.js +45 -0
  66. package/dist/tools/types.d.ts +3 -1
  67. package/dist/tools/types.js +3 -2
  68. package/package.json +1 -1
@@ -123,7 +123,9 @@ export declare class AgentHooks {
123
123
  private pushBindings;
124
124
  /** Held asks that were pushed: action -> when the notification expires. */
125
125
  private pushedHolds;
126
- /** Pushed asks whose hold ended with the request left in the terminal. */
126
+ /** Held asks whose hold ended with the request left in the terminal, by
127
+ * pane: the action keeps answering the pane's dialog, so a phone card,
128
+ * notification or dispatcher holding it is not left with a dead id. */
127
129
  private releasedHolds;
128
130
  /** Terminal dialogs pushed to phones: by pane, the dialog last pushed; by
129
131
  * action, what an answer from the notification types. */
@@ -286,6 +288,10 @@ export declare class AgentHooks {
286
288
  * Claude moves on. True when a held question was cancelled. */
287
289
  cancelHeldQuestion(target: Target): boolean;
288
290
  answerPush(binding: string, decision: unknown): Promise<void>;
291
+ /** Whether this action now answers a terminal dialog: a released hold's
292
+ * pane is read at once rather than at the next tick, and its dialog
293
+ * adopted under the hold's own action. */
294
+ private releasedHoldDialog;
289
295
  /** Where a pushed ask lives, without answering it: the phone opens that
290
296
  * session's details when the notification itself is tapped. */
291
297
  pushTarget(binding: string): Target | undefined;
@@ -321,6 +327,10 @@ export declare class AgentHooks {
321
327
  request: string;
322
328
  requestKind?: RequestKind;
323
329
  }, answer: (decision: "approve" | "deny") => Promise<void>): void;
330
+ /** Moves a released hold onto the dialog its pane now draws, under the
331
+ * hold's action: as the pushed dialog when its notification is on the
332
+ * phone, else as the dialog offered to a dispatching Hook. True when the
333
+ * hold was pushed, so the dialog needs no second notification. */
324
334
  private adoptReleasedHold;
325
335
  private dropDialogPush;
326
336
  /** The dialog a pane's screen shows now. Codex draws "> 1. Yes, proceed (y)"
@@ -193,7 +193,9 @@ export class AgentHooks {
193
193
  pushBindings = new PushBindingStore();
194
194
  /** Held asks that were pushed: action -> when the notification expires. */
195
195
  pushedHolds = new Map();
196
- /** Pushed asks whose hold ended with the request left in the terminal. */
196
+ /** Held asks whose hold ended with the request left in the terminal, by
197
+ * pane: the action keeps answering the pane's dialog, so a phone card,
198
+ * notification or dispatcher holding it is not left with a dead id. */
197
199
  releasedHolds = new Map();
198
200
  /** Terminal dialogs pushed to phones: by pane, the dialog last pushed; by
199
201
  * action, what an answer from the notification types. */
@@ -1054,8 +1056,10 @@ export class AgentHooks {
1054
1056
  this.pushBindings.dropAction(id);
1055
1057
  }
1056
1058
  async answer(target, id, decision, updatedInput) {
1057
- // A terminal dialog offered to a dispatching Hook (`workerApproval`) or pushed: answered with the pane's own keys.
1058
- if (id.startsWith("dialog-")) {
1059
+ // A terminal dialog offered to a dispatching Hook (`workerApproval`) or
1060
+ // pushed, or a held ask whose hold ended with its dialog still on screen:
1061
+ // answered with the pane's own keys.
1062
+ if (id.startsWith("dialog-") || (!this.pending.has(id) && await this.releasedHoldDialog(id))) {
1059
1063
  const dialog = this.dialogActions.get(id);
1060
1064
  if (!dialog || JSON.stringify(dialog.target) !== JSON.stringify(target))
1061
1065
  throw new BridgeError(409, "This approval is no longer pending.");
@@ -1190,16 +1194,7 @@ export class AgentHooks {
1190
1194
  await this.answer(pending.target, linked.action, decision);
1191
1195
  return;
1192
1196
  }
1193
- const released = [...this.releasedHolds].find(([, hold]) => hold.action === linked.action);
1194
- if (released && !this.dialogActions.has(linked.action)) {
1195
- // The hold just ended: read the pane now rather than wait for the tick.
1196
- const target = JSON.parse(released[0]);
1197
- await this.syncTerminalDialog(target, true).catch(() => { });
1198
- const entry = this.terminalPrompts.get(released[0]);
1199
- if (entry?.choice?.title)
1200
- this.adoptReleasedHold(released[0], target, entry.choice, entry.choice.title);
1201
- }
1202
- if (this.dialogActions.has(linked.action)) {
1197
+ if (await this.releasedHoldDialog(linked.action)) {
1203
1198
  await this.answerDialog(linked.action, decision);
1204
1199
  return;
1205
1200
  }
@@ -1221,6 +1216,20 @@ export class AgentHooks {
1221
1216
  }
1222
1217
  throw new BridgeError(409, "This approval is no longer pending.");
1223
1218
  }
1219
+ /** Whether this action now answers a terminal dialog: a released hold's
1220
+ * pane is read at once rather than at the next tick, and its dialog
1221
+ * adopted under the hold's own action. */
1222
+ async releasedHoldDialog(action) {
1223
+ const released = [...this.releasedHolds].find(([, hold]) => hold.action === action);
1224
+ if (released && !this.dialogActions.has(action)) {
1225
+ const target = JSON.parse(released[0]);
1226
+ await this.syncTerminalDialog(target, true).catch(() => { });
1227
+ const entry = this.terminalPrompts.get(released[0]);
1228
+ if (entry?.choice?.title)
1229
+ this.adoptReleasedHold(released[0], target, entry.choice, entry.choice.title);
1230
+ }
1231
+ return this.dialogActions.has(action);
1232
+ }
1224
1233
  /** Where a pushed ask lives, without answering it: the phone opens that
1225
1234
  * session's details when the notification itself is tapped. */
1226
1235
  pushTarget(binding) {
@@ -1283,6 +1292,18 @@ export class AgentHooks {
1283
1292
  .then(delivered => { if (!delivered)
1284
1293
  this.dropDialogPush(key); }).catch(() => this.dropDialogPush(key));
1285
1294
  }
1295
+ // A dialog stays answerable for as long as its pane shows it.
1296
+ const horizon = Date.now() + DIALOG_PUSH_MS;
1297
+ for (const key of waiting) {
1298
+ const hold = this.releasedHolds.get(key);
1299
+ if (hold && hold.expiresAt > Date.now())
1300
+ hold.expiresAt = Math.max(hold.expiresAt, horizon);
1301
+ for (const action of [this.dialogPushes.get(key)?.action, this.forwardedDialogs.get(key)?.action]) {
1302
+ const dialog = action ? this.dialogActions.get(action) : undefined;
1303
+ if (dialog && dialog.expiresAt > Date.now())
1304
+ dialog.expiresAt = Math.max(dialog.expiresAt, horizon);
1305
+ }
1306
+ }
1286
1307
  for (const [key, hold] of this.releasedHolds) {
1287
1308
  // Answered in the terminal, or expired: the notification can no longer act.
1288
1309
  if ((!waiting.has(key) && JSON.parse(key).server === server) || hold.expiresAt <= Date.now()) {
@@ -1348,10 +1369,12 @@ export class AgentHooks {
1348
1369
  const title = entry && (entry.dialog || entry.released) ? entry.choice?.title : undefined;
1349
1370
  if (!entry?.choice || !title)
1350
1371
  return undefined;
1372
+ // The ask was offered while held: keep offering it under the same id.
1373
+ this.adoptReleasedHold(key, target, entry.choice, title);
1351
1374
  const pushedDialog = this.dialogPushes.get(key);
1352
1375
  // A dialog is the same one only with the same title and command: Claude and Codex share generic titles.
1353
1376
  const pushedAction = pushedDialog && this.dialogActions.get(pushedDialog.action);
1354
- let action = pushedDialog?.title === title && pushedAction && pushedAction.choice.body === entry.choice.body ? pushedDialog.action : undefined;
1377
+ let action = pushedDialog?.title === title && pushedAction && pushedAction.choice.body === entry.choice.body && pushedAction.expiresAt > Date.now() ? pushedDialog.action : undefined;
1355
1378
  if (!action) {
1356
1379
  const known = this.forwardedDialogs.get(key);
1357
1380
  if (known?.title === title && known.body === entry.choice.body && (this.dialogActions.get(known.action)?.expiresAt ?? 0) > Date.now())
@@ -1392,14 +1415,27 @@ export class AgentHooks {
1392
1415
  .then(delivered => { if (!delivered)
1393
1416
  drop(); }).catch(drop);
1394
1417
  }
1418
+ /** Moves a released hold onto the dialog its pane now draws, under the
1419
+ * hold's action: as the pushed dialog when its notification is on the
1420
+ * phone, else as the dialog offered to a dispatching Hook. True when the
1421
+ * hold was pushed, so the dialog needs no second notification. */
1395
1422
  adoptReleasedHold(key, target, choice, title) {
1396
1423
  const hold = this.releasedHolds.get(key);
1424
+ if (!hold)
1425
+ return false;
1397
1426
  this.releasedHolds.delete(key);
1398
- if (!hold || hold.expiresAt <= Date.now())
1427
+ if (hold.expiresAt <= Date.now()) {
1428
+ this.dropPushBindings(hold.action);
1399
1429
  return false;
1400
- this.dialogPushes.set(key, { action: hold.action, title });
1430
+ }
1401
1431
  this.dialogActions.set(hold.action, { target, choice, expiresAt: hold.expiresAt });
1402
- return true;
1432
+ if (hold.pushed)
1433
+ this.dialogPushes.set(key, { action: hold.action, title });
1434
+ else {
1435
+ this.dropForwardedDialog(key);
1436
+ this.forwardedDialogs.set(key, { action: hold.action, title, body: choice.body });
1437
+ }
1438
+ return hold.pushed;
1403
1439
  }
1404
1440
  dropDialogPush(key) {
1405
1441
  const pushed = this.dialogPushes.get(key);
@@ -1743,8 +1779,9 @@ export class AgentHooks {
1743
1779
  released = true;
1744
1780
  this.pending.delete(action);
1745
1781
  this.rememberTerminalPrompt(target, body);
1746
- if (this.pushedHolds.has(action))
1747
- this.releasedHolds.set(JSON.stringify(target), { action, expiresAt: this.pushedHolds.get(action) });
1782
+ // The id was already handed out (phone card, push, dispatcher): it keeps answering the dialog.
1783
+ const pushed = this.pushedHolds.get(action);
1784
+ this.releasedHolds.set(JSON.stringify(target), { action, expiresAt: pushed ?? Date.now() + DIALOG_PUSH_MS, pushed: pushed !== undefined });
1748
1785
  this.pushedHolds.delete(action);
1749
1786
  res.end("{}");
1750
1787
  }, APPROVAL_HOLD_MS);
@@ -17,7 +17,11 @@ export const changedFileSchema = z.object({ root: z.string(), path: z.string(),
17
17
  added: z.number().int().nonnegative(), removed: z.number().int().nonnegative(), redacted: z.boolean().optional(), binary: z.boolean().optional(), truncated: z.boolean().optional() });
18
18
  const changeRowSchema = z.object({ toolUseId: z.string(), files: z.array(changedFileSchema) });
19
19
  export const secretName = (file) => /^(?:\.env(?:\..*)?|.*\.(?:pem|key|p12|pfx|keychain-db|tfstate)|id_rsa.*|id_ed25519.*|(?:.*\.)?credentials\.json|\.netrc|\.npmrc|\.pypirc)$/i.test(path.basename(file));
20
- const gitPool = new ProcessPool(2);
20
+ /** Two captures at a time, each holding its slot for all of its Git work. A
21
+ * slot per Git process interleaved every waiting capture, so under load they
22
+ * all finished late together and every one overran the budget; now they finish
23
+ * in turn and only the end of a long queue misses it. */
24
+ const capturePool = new ProcessPool(2);
21
25
  /** Tools whose filesystem changes are captured around the lifecycle callback. */
22
26
  export const SHELL_TOOLS = new Set(["Bash", "bash", "shell", "Shell", "exec_command", "shell_command", "local_shell", "write_stdin"]);
23
27
  const NAMED = /(?<![\w@:/])(?:~\/|\.\/|\/)[\w.@+~-]+(?:\/[\w.@+~-]+)*/g;
@@ -50,10 +54,12 @@ export function namedPaths(command, input = {}) {
50
54
  }
51
55
  return [...found].slice(0, 48);
52
56
  }
57
+ /** Only inside a `capturePool` slot. */
53
58
  async function git(cwd, args, extra = {}, signal) {
54
- return gitPool.run(signal, async () => (countGit("changes"), await exec("git", ["-C", cwd, "--no-pager", ...args], {
59
+ countGit("changes");
60
+ return (await exec("git", ["-C", cwd, "--no-pager", ...args], {
55
61
  signal, timeout: 10_000, maxBuffer: 8_388_608, env: { ...checkoutGitEnv(), ...extra },
56
- })).stdout);
62
+ })).stdout;
57
63
  }
58
64
  /** The repository holding `target` (a file, a folder, or something not yet
59
65
  * created), confined to the user's home; undefined otherwise. */
@@ -258,7 +264,7 @@ export class ToolChanges {
258
264
  const snapshot = { at: Date.now(), conversation, own: new Set(claimed), trees: new Map(), taking: true };
259
265
  this.snapshots.set(key, snapshot);
260
266
  try {
261
- await this.budget(async (signal) => {
267
+ await this.budget(signal => capturePool.run(signal, async () => {
262
268
  await realpath(cwd); // A vanished checkout must not resolve to its parent repository.
263
269
  const roots = new Set();
264
270
  for (const target of [cwd, phrenStoreRoot(), ...namedPaths(command, input)]) {
@@ -273,7 +279,7 @@ export class ToolChanges {
273
279
  snapshot.trees.set(root, await scratchTree(root, signal));
274
280
  }
275
281
  signal.throwIfAborted();
276
- });
282
+ }));
277
283
  snapshot.taking = false;
278
284
  if (snapshot.dropped) {
279
285
  await this.discard(snapshot);
@@ -351,10 +357,13 @@ export class ToolChanges {
351
357
  async compute(snapshot) {
352
358
  try {
353
359
  return await this.budget(async (signal) => {
354
- const files = [];
355
- for (const [root, before] of snapshot.trees) {
356
- files.push(...await treeDiff(root, before.hash, await treeHash(root, before.env, signal), before.env, signal));
357
- }
360
+ const files = await capturePool.run(signal, async () => {
361
+ const found = [];
362
+ for (const [root, before] of snapshot.trees) {
363
+ found.push(...await treeDiff(root, before.hash, await treeHash(root, before.env, signal), before.env, signal));
364
+ }
365
+ return found;
366
+ });
358
367
  // A file another agent's edit named during this call is its change,
359
368
  // not this call's, even though it landed inside the same window.
360
369
  // A call that names its files (an Edit, a Write, a patch) changed
@@ -5,6 +5,7 @@ import { hookRequest } from "./client.js";
5
5
  import { dispatchSchema } from "./dispatch.js";
6
6
  import { handOff } from "./hand-off.js";
7
7
  import { terminalPaneFromEnv } from "./terminal.js";
8
+ import { dispatchIdFromEnv } from "./launch-brief.js";
8
9
  import { addGrant, grantSchema, listNamedGrants, removeGrant } from "./grants.js";
9
10
  import { sessionId } from "./protocol.js";
10
11
  export async function runDispatch(args) {
@@ -13,7 +14,8 @@ export async function runDispatch(args) {
13
14
  const origin = await terminalPaneFromEnv();
14
15
  if (!origin || !values.prs)
15
16
  throw new Error("Usage inside a worker pane: phren dispatch report --prs <JSON array>");
16
- console.log(JSON.stringify(await hookRequest("/v1/dispatch/report", { origin, prs: prsSchema.parse(JSON.parse(values.prs)) }), null, 2));
17
+ const dispatch = dispatchIdFromEnv();
18
+ console.log(JSON.stringify(await hookRequest("/v1/dispatch/report", { origin, prs: prsSchema.parse(JSON.parse(values.prs)), ...(dispatch ? { dispatch } : {}) }), null, 2));
17
19
  return 0;
18
20
  }
19
21
  if (args.length === 1 && args[0] === "status") {
@@ -7,6 +7,7 @@ import { assessSyncOutage, FAILED_PUSH_STATUSES, getRuntimeHealth } from "../gov
7
7
  import { getProjectDirs } from "../phren-paths.js";
8
8
  import { resolveAllStores } from "../store-registry.js";
9
9
  import { publicComputerKey } from "./computers.js";
10
+ import { localHostKeyLine } from "./host-key.js";
10
11
  import { hookPeers, peerRequest } from "./peers.js";
11
12
  import { BridgeError, bridgeRoot, errorCode } from "./protocol.js";
12
13
  import { canonicalComputer, latestScheduleBatch, readScheduleDocument, readScheduleRuns, scheduleRunsFile } from "./schedules.js";
@@ -150,8 +151,9 @@ export async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
150
151
  }
151
152
  /** This computer's public SSH host key, the pin a peer's hooks.yaml holds for it. */
152
153
  export async function ownHostKey() {
154
+ const line = await localHostKeyLine();
153
155
  try {
154
- return publicComputerKey(await readFile("/etc/ssh/ssh_host_ed25519_key.pub", "utf8"));
156
+ return line ? publicComputerKey(line) : undefined;
155
157
  }
156
158
  catch {
157
159
  return undefined;
@@ -0,0 +1,16 @@
1
+ import { BridgeError } from "./protocol.js";
2
+ /**
3
+ * Finding a computer's sshd ed25519 host key. sshd keeps it in /etc/ssh on
4
+ * most systems, but Asustor ADM uses /usr/etc/ssh and Homebrew or Entware
5
+ * builds use their own prefix, so ask sshd first and search the usual
6
+ * directories after.
7
+ */
8
+ export declare const HOST_KEY_DIRS: string[];
9
+ /** A POSIX sh script that prints the first ssh-ed25519 host public key line,
10
+ * from sshd -T's hostkey entries then `dirs`; it prints nothing when there is none. */
11
+ export declare function hostKeyScript(dirs?: string[], sshd?: string): string;
12
+ export declare function noHostKey(where: string, dirs?: string[]): BridgeError;
13
+ /** The first ed25519 host public key line out of hostKeyScript's output. */
14
+ export declare function hostKeyLine(stdout: string): string | undefined;
15
+ /** This computer's ed25519 host public key line, or undefined when it has none. */
16
+ export declare function localHostKeyLine(dirs?: string[], sshd?: string): Promise<string | undefined>;
@@ -0,0 +1,35 @@
1
+ import { execFile } from "node:child_process";
2
+ import { BridgeError } from "./protocol.js";
3
+ /**
4
+ * Finding a computer's sshd ed25519 host key. sshd keeps it in /etc/ssh on
5
+ * most systems, but Asustor ADM uses /usr/etc/ssh and Homebrew or Entware
6
+ * builds use their own prefix, so ask sshd first and search the usual
7
+ * directories after.
8
+ */
9
+ export const HOST_KEY_DIRS = ["/etc/ssh", "/usr/etc/ssh", "/usr/local/etc/ssh", "/opt/etc/ssh"];
10
+ const quote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
11
+ /** A POSIX sh script that prints the first ssh-ed25519 host public key line,
12
+ * from sshd -T's hostkey entries then `dirs`; it prints nothing when there is none. */
13
+ export function hostKeyScript(dirs = HOST_KEY_DIRS, sshd = "sshd") {
14
+ const candidates = dirs.map(dir => quote(`${dir}/ssh_host_ed25519_key`)).join(" ");
15
+ return `keys=$( (PATH="$PATH:/usr/sbin:/sbin:/usr/local/sbin:/opt/sbin" ${quote(sshd)} -T 2>/dev/null) | awk '$1 == "hostkey" { print $2 }')
16
+ for k in $keys ${candidates}; do
17
+ [ -r "$k.pub" ] || continue
18
+ line=$(head -n 1 "$k.pub")
19
+ case "$line" in "ssh-ed25519 "*) printf '%s\\n' "$line"; exit 0;; esac
20
+ done
21
+ true`;
22
+ }
23
+ export function noHostKey(where, dirs = HOST_KEY_DIRS) {
24
+ return new BridgeError(409, `${where} has no ssh-ed25519 host key: none in sshd -T's hostkey entries or ${dirs.join(", ")}. Generate one with sudo ssh-keygen -A and restart sshd.`);
25
+ }
26
+ /** The first ed25519 host public key line out of hostKeyScript's output. */
27
+ export function hostKeyLine(stdout) {
28
+ return stdout.split("\n").map(line => line.trim()).find(line => line.startsWith("ssh-ed25519 "));
29
+ }
30
+ /** This computer's ed25519 host public key line, or undefined when it has none. */
31
+ export function localHostKeyLine(dirs, sshd) {
32
+ return new Promise(resolve => {
33
+ execFile("sh", ["-c", hostKeyScript(dirs, sshd)], { timeout: 10_000 }, (error, stdout) => resolve(hostKeyLine(stdout ?? "")));
34
+ });
35
+ }
@@ -25,6 +25,8 @@ export declare const launchBriefSchema: z.ZodObject<{
25
25
  export type LaunchBrief = z.infer<typeof launchBriefSchema>;
26
26
  /** The variable a launched agent's hooks read its brief id from. */
27
27
  export declare const DISPATCH_ID_ENV = "PHREN_DISPATCH_ID";
28
+ /** The dispatch this process's agent was launched for, when its environment names a valid one. */
29
+ export declare function dispatchIdFromEnv(env?: NodeJS.ProcessEnv): string | undefined;
28
30
  export declare function briefRoot(): string;
29
31
  /** The harnesses whose TUI takes a first prompt as an argument, and the
30
32
  * arguments that carry it. Claude reads outside its working directory only
@@ -27,6 +27,11 @@ export const launchBriefSchema = z.object({
27
27
  }).strict();
28
28
  /** The variable a launched agent's hooks read its brief id from. */
29
29
  export const DISPATCH_ID_ENV = "PHREN_DISPATCH_ID";
30
+ /** The dispatch this process's agent was launched for, when its environment names a valid one. */
31
+ export function dispatchIdFromEnv(env = process.env) {
32
+ const id = env[DISPATCH_ID_ENV];
33
+ return id && briefId.safeParse(id).success ? id : undefined;
34
+ }
30
35
  /** Briefs older than this are removed when the next one is written; a worker
31
36
  * may re-read its brief after a compaction, so it is not removed on arrival. */
32
37
  const KEEP_MS = 7 * 24 * 60 * 60 * 1000;
@@ -8,6 +8,7 @@ import { findPhrenPath } from "../phren-paths.js";
8
8
  import { computerLabel } from "./hand-off.js";
9
9
  import { localNames } from "./computer-names.js";
10
10
  import { acceptComputer, computerName, enrollComputer, publicComputerKey } from "./computers.js";
11
+ import { hostKeyLine, hostKeyScript, localHostKeyLine, noHostKey } from "./host-key.js";
11
12
  import { addHookPeer, optionalHookPeers, peerRequest } from "./peers.js";
12
13
  import { BridgeError, bridgeRoot, object } from "./protocol.js";
13
14
  /**
@@ -16,8 +17,8 @@ import { BridgeError, bridgeRoot, object } from "./protocol.js";
16
17
  * linked until the owner runs `phren bridge link <host>`.
17
18
  */
18
19
  const exec = promisify(execFile);
19
- // A non-login ssh shell often lacks Homebrew's node (macOS) or ~/.local/bin.
20
- const REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"';
20
+ // A non-login ssh shell often lacks Homebrew's node (macOS), Entware's /opt/bin (NAS) or ~/.local/bin.
21
+ const REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/opt/bin:$PATH"';
21
22
  const GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
22
23
  /** Concrete Host aliases from an ssh config: no patterns, no Git hosting services. */
23
24
  export function sshConfigHosts(text) {
@@ -111,8 +112,14 @@ export async function linkComputer(host, options = {}) {
111
112
  // The address the Hook dials skips ~/.ssh/config, so resolve the alias the way ssh does.
112
113
  const resolved = Object.fromEntries((await exec("ssh", ["-G", "--", host], { timeout: 5_000 })).stdout.split("\n")
113
114
  .map(line => line.split(" ")).filter(parts => parts.length >= 2).map(([key, ...rest]) => [key, rest.join(" ")]));
114
- const remoteHostKey = publicComputerKey((await ssh(host, "cat /etc/ssh/ssh_host_ed25519_key.pub")).trim().split(/\s+/).slice(0, 2).join(" "));
115
- const localHostKey = publicComputerKey((await readFile("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
115
+ const remoteKeyLine = hostKeyLine(await ssh(host, hostKeyScript()));
116
+ if (!remoteKeyLine)
117
+ throw noHostKey(host);
118
+ const localLine = await localHostKeyLine();
119
+ if (!localLine)
120
+ throw noHostKey("This computer");
121
+ const remoteHostKey = publicComputerKey(remoteKeyLine.split(/\s+/).slice(0, 2).join(" "));
122
+ const localHostKey = publicComputerKey(localLine.split(/\s+/).slice(0, 2).join(" "));
116
123
  const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
117
124
  await ssh(host, `f=$(mktemp) && cat > "$f" && ${REMOTE_PATH} phren bridge enroll-computer ${as} --accept "$f"; s=$?; rm -f "$f"; exit $s`, await enrollComputer(as));
118
125
  await acceptComputer(name, remoteLine);
@@ -0,0 +1,5 @@
1
+ import type { AgentHooks } from "./agent-hooks.js";
2
+ import { type InboxSnapshot } from "./owner-inbox.js";
3
+ /** Read the actual panes and pending asks, never a stored inbox's live flag.
4
+ * Called on reads and on the Hook's five-second activity tick. */
5
+ export declare function ownerInboxSources(hooks: AgentHooks): Promise<InboxSnapshot>;
@@ -0,0 +1,94 @@
1
+ import { dispatchStatus } from "./dispatch.js";
2
+ import { isLocalComputer } from "./dispatch-hosts.js";
3
+ import { workerReaders, workerStates } from "./dispatch-returns.js";
4
+ import { paneChatState, recentServers, snapshot } from "./herdr.js";
5
+ import { inboxTargetSchema } from "./owner-inbox.js";
6
+ import { hookPeers, peerRequest } from "./peers.js";
7
+ import { ownerQuestion } from "./schedule-watch.js";
8
+ import { objects, object } from "./protocol.js";
9
+ const clean = (text) => String(text).replace(/[\x00-\x1f\x7f]+/g, " ").trim().slice(0, 500);
10
+ /** Read the actual panes and pending asks, never a stored inbox's live flag.
11
+ * Called on reads and on the Hook's five-second activity tick. */
12
+ export async function ownerInboxSources(hooks) {
13
+ const sources = [], unavailableDispatches = [];
14
+ for (const server of await recentServers()) {
15
+ const name = String(server.session), state = await snapshot(name);
16
+ for (const pane of objects(state.panes)) {
17
+ const chat = await paneChatState(name, pane, { tokenWhenIdentified: false });
18
+ const parsed = inboxTargetSchema.safeParse({ server: name, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id, source: pane.agent,
19
+ ...(chat.sessionId ? { session: chat.sessionId } : { starting: true, startingToken: chat.startingToken }) });
20
+ if (!parsed.success)
21
+ continue;
22
+ const target = parsed.data, waiting = ["blocked", "waiting"].includes(String(pane.agent_status));
23
+ if ("session" in target) {
24
+ // Refresh terminal-derived questions even with no phone chat open.
25
+ await hooks.syncTerminalDialog(target, waiting);
26
+ if (!waiting)
27
+ hooks.clearTerminalPrompt(target);
28
+ }
29
+ const approval = "session" in target ? hooks.workerApproval(target) : undefined;
30
+ const question = "session" in target ? hooks.servedQuestion(target) : undefined;
31
+ const terminal = waiting && "session" in target ? hooks.terminalPrompt(target) : undefined;
32
+ const request = approval?.request ?? question?.message ?? terminal?.request ?? terminal?.message
33
+ ?? (waiting ? `${pane.agent} needs terminal input.` : undefined);
34
+ if (!request)
35
+ continue;
36
+ const actionId = approval?.actionId ?? (typeof question?.actionId === "string" ? question.actionId : undefined);
37
+ sources.push({ source: `prompt:${JSON.stringify(target)}:${actionId ?? "waiting"}`, kind: "blocked", title: clean(request), target,
38
+ ...(actionId ? { actionId } : {}) });
39
+ }
40
+ }
41
+ // A saved return/approval is only a candidate: re-observe its worker. In
42
+ // particular a closed pane must not stay live because its last return waits.
43
+ const candidates = (await dispatchStatus()).filter(receipt => !receipt.closedAt && receipt.target
44
+ && receipt.returned && ["needs-you", "blocked"].includes(receipt.returned.state));
45
+ const groups = new Map();
46
+ for (const receipt of candidates) {
47
+ const computer = isLocalComputer(receipt.computer) ? "local" : receipt.computer;
48
+ groups.set(computer, [...(groups.get(computer) ?? []), receipt]);
49
+ }
50
+ const peers = groups.size && [...groups.keys()].some(name => name !== "local") ? await hookPeers() : [];
51
+ for (const [computer, receipts] of groups) {
52
+ for (let offset = 0; offset < receipts.length; offset += 64) {
53
+ const batch = receipts.slice(offset, offset + 64);
54
+ const input = { targets: batch.map(receipt => ({ ...receipt.target, dispatch: receipt.id })) };
55
+ let workers;
56
+ try {
57
+ const peer = peers.find(peer => peer.name === computer);
58
+ const result = computer === "local"
59
+ ? await workerStates(input, { ...workerReaders(target => hooks.workerApproval(target)), snapshot })
60
+ : peer ? await peerRequest(peer, "/v1/dispatch/workers", input) : undefined;
61
+ workers = objects(result?.workers);
62
+ }
63
+ catch {
64
+ workers = [];
65
+ }
66
+ for (const [index, receipt] of batch.entries()) {
67
+ const seen = workers[index];
68
+ if (!seen || ["unavailable", "unknown"].includes(String(seen.state))) {
69
+ unavailableDispatches.push(receipt.id);
70
+ continue;
71
+ }
72
+ if (["gone", "closed"].includes(String(seen.state)))
73
+ continue;
74
+ const approval = object(seen.approval);
75
+ const actionId = typeof approval.actionId === "string" ? approval.actionId : undefined;
76
+ const question = ["idle", "done"].includes(String(seen.state)) && seen.completed && !seen.error && !seen.interrupted
77
+ ? (typeof seen.reply === "string" ? ownerQuestion(seen.reply) : undefined) ?? seen.unfinished : undefined;
78
+ if (!actionId && seen.state !== "blocked" && !question)
79
+ continue;
80
+ const source = { source: `dispatch:${receipt.id}:${actionId ?? "waiting"}`, kind: actionId || seen.state === "blocked" ? "blocked" : "needs-you",
81
+ title: clean(approval.request ?? question ?? `${receipt.label} needs input`),
82
+ project: receipt.project, ...(computer !== "local" ? { computer } : {}), target: receipt.target, dispatch: receipt.id,
83
+ ...(actionId ? { actionId } : {}) };
84
+ // The local prompt and dispatch return describe the same wait. Keep
85
+ // the dispatch's project/receipt metadata as well as its live target.
86
+ const local = sources.findIndex(row => JSON.stringify(row.target) === JSON.stringify(source.target) && !row.computer);
87
+ if (computer === "local" && local >= 0)
88
+ sources.splice(local, 1);
89
+ sources.push(source);
90
+ }
91
+ }
92
+ }
93
+ return { sources, unavailableDispatches };
94
+ }
@@ -28,5 +28,24 @@ export async function ownerInboxView(inbox, input, localOnly = false) {
28
28
  unreachable.push({ computer: peer.name, error: error instanceof Error ? error.message : "Unreachable." });
29
29
  }
30
30
  }));
31
- return { ok: true, items, unreachable };
31
+ // Older peers can still send stale automatic rows during a rolling upgrade.
32
+ // A dispatching Hook and the worker's Hook may also describe the same ask.
33
+ const seen = new Set();
34
+ const current = items.filter(item => {
35
+ if (data.includeResolved || item.kind === "manual")
36
+ return true;
37
+ if (item.live !== true || item.state !== "open")
38
+ return false;
39
+ const t = item.target;
40
+ if (!t)
41
+ return true;
42
+ const computer = String(item.computer ?? item.inboxComputer);
43
+ const key = JSON.stringify([isLocalComputer(computer) ? "local" : computer, t.server, t.workspace, t.tab, t.pane,
44
+ t.source, t.session ?? t.startingToken, item.actionId ?? "waiting"]);
45
+ if (seen.has(key))
46
+ return false;
47
+ seen.add(key);
48
+ return true;
49
+ });
50
+ return { ok: true, items: current, unreachable };
32
51
  }
@@ -103,13 +103,17 @@ export interface InboxSource {
103
103
  dispatch?: string;
104
104
  actionId?: string;
105
105
  }
106
- /** Hook-owned inbox. Return reads do not resolve owner work. Live sources
107
- * disappearing are retained as no-longer-live until explicitly resolved. */
106
+ export interface InboxSnapshot {
107
+ sources: InboxSource[];
108
+ unavailableDispatches?: string[];
109
+ }
110
+ /** Reconcile automatic work against current sources; manual work is owner-owned.
111
+ * The first reconciliation also migrates old stale/duplicate automatic rows. */
108
112
  export declare class OwnerInbox {
109
113
  private readonly sources;
110
114
  private readonly file;
111
115
  private pending;
112
- constructor(sources?: () => Promise<InboxSource[]>, file?: string);
116
+ constructor(sources?: () => Promise<InboxSource[] | InboxSnapshot>, file?: string);
113
117
  private read;
114
118
  run(input: unknown): Promise<Json>;
115
119
  tick(): Promise<void>;