@phren/cli 0.3.3 → 0.3.5

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 (71) hide show
  1. package/dist/bridge/agent-hooks.d.ts +6 -0
  2. package/dist/bridge/agent-hooks.js +66 -25
  3. package/dist/bridge/canary.d.ts +4 -0
  4. package/dist/bridge/canary.js +17 -4
  5. package/dist/bridge/changes.d.ts +7 -0
  6. package/dist/bridge/changes.js +6 -1
  7. package/dist/bridge/client.js +2 -1
  8. package/dist/bridge/command.js +7 -5
  9. package/dist/bridge/conductor-group.d.ts +1 -0
  10. package/dist/bridge/conductor-group.js +4 -3
  11. package/dist/bridge/dispatch-command.js +2 -2
  12. package/dist/bridge/fanouts.js +6 -2
  13. package/dist/bridge/hand-off.d.ts +1 -0
  14. package/dist/bridge/hand-off.js +3 -2
  15. package/dist/bridge/harness-status.d.ts +12 -0
  16. package/dist/bridge/harness-status.js +153 -0
  17. package/dist/bridge/health.d.ts +18 -0
  18. package/dist/bridge/health.js +30 -4
  19. package/dist/bridge/herdr.d.ts +6 -0
  20. package/dist/bridge/herdr.js +62 -8
  21. package/dist/bridge/install.js +4 -0
  22. package/dist/bridge/model-switch.d.ts +4 -1
  23. package/dist/bridge/model-switch.js +12 -7
  24. package/dist/bridge/models.js +3 -2
  25. package/dist/bridge/pane-status.d.ts +37 -0
  26. package/dist/bridge/pane-status.js +139 -0
  27. package/dist/bridge/pane-text.d.ts +3 -11
  28. package/dist/bridge/pane-text.js +9 -16
  29. package/dist/bridge/peers.js +9 -6
  30. package/dist/bridge/prompt-once.d.ts +26 -0
  31. package/dist/bridge/prompt-once.js +69 -0
  32. package/dist/bridge/protocol.d.ts +10 -0
  33. package/dist/bridge/protocol.js +10 -0
  34. package/dist/bridge/schedule-format.d.ts +2 -0
  35. package/dist/bridge/schedule-launch.d.ts +10 -1
  36. package/dist/bridge/schedule-launch.js +29 -3
  37. package/dist/bridge/schedule-watch.js +1 -1
  38. package/dist/bridge/schedules.d.ts +10 -0
  39. package/dist/bridge/schedules.js +40 -0
  40. package/dist/bridge/server-launch.js +12 -10
  41. package/dist/bridge/server-pane-routes.js +23 -9
  42. package/dist/bridge/server-routes.d.ts +1 -0
  43. package/dist/bridge/server-routes.js +1 -1
  44. package/dist/bridge/session-servers.js +5 -6
  45. package/dist/bridge/side-questions.js +6 -5
  46. package/dist/bridge/terminal-choice.d.ts +12 -5
  47. package/dist/bridge/terminal-choice.js +66 -0
  48. package/dist/bridge/terminal-herdr.d.ts +5 -0
  49. package/dist/bridge/terminal-herdr.js +57 -0
  50. package/dist/bridge/terminal-tmux.d.ts +111 -0
  51. package/dist/bridge/terminal-tmux.js +549 -0
  52. package/dist/bridge/terminal.d.ts +119 -0
  53. package/dist/bridge/terminal.js +66 -0
  54. package/dist/bridge/transcript-claude.d.ts +6 -0
  55. package/dist/bridge/transcript-claude.js +20 -0
  56. package/dist/bridge/transcript-opencode.js +1 -1
  57. package/dist/bridge/transcript-preview.d.ts +5 -0
  58. package/dist/bridge/transcript-preview.js +52 -2
  59. package/dist/bridge/transport.js +10 -4
  60. package/dist/bridge-hook.mjs +4852 -3391
  61. package/dist/cli-registry.js +7 -0
  62. package/dist/entrypoint.js +2 -1
  63. package/dist/init/init.js +4 -0
  64. package/dist/link/doctor.js +33 -30
  65. package/dist/modules/agent-package.d.ts +35 -0
  66. package/dist/modules/agent-package.js +133 -0
  67. package/dist/modules/registry.js +2 -2
  68. package/dist/session/utils.js +1 -1
  69. package/dist/tools/dispatch.js +2 -2
  70. package/package.json +1 -1
  71. package/plugins/opencode/phren-transcript.js +97 -6
@@ -144,6 +144,10 @@ export declare class AgentHooks {
144
144
  * keyless rows are reached and verified before returning Enter to the route. */
145
145
  dialogAnswerKeys<K extends string>(target: Target, keys: readonly K[]): Promise<(K | "Enter")[]>;
146
146
  moveDialogHighlight(target: Target, expected: TerminalChoice, key: string, beforeKeys?: () => Promise<void>): Promise<void>;
147
+ /** Put OpenCode's cursor on Allow once, the row's first option: ← as many
148
+ * times as the cursor sits to its right, then read the colors again. The
149
+ * same prompt must still be showing, or nothing more is sent. */
150
+ private selectOpencodeOnce;
147
151
  /** Answer Claude's AskUserQuestion dialog in the pane: every question in
148
152
  * `answers` from `from` on, then the set's submission when `submit`. The
149
153
  * walk reads the pane before and after each key, so a dialog on another
@@ -168,6 +172,8 @@ export declare class AgentHooks {
168
172
  /** The bare slash command that opened this pane's current menu window. */
169
173
  menuCommand(target: Target): string | undefined;
170
174
  menuClosed(target: Target): void;
175
+ /** The pane with its colors, for dialogs whose cursor is only a color. */
176
+ paneAnsi(target: Target): Promise<string>;
171
177
  /** Read what the pane draws, stripping ANSI unless placeholder styling is needed. */
172
178
  paneLines(target: Target, stripAnsi?: boolean): Promise<string>;
173
179
  /** After the phone walks Codex's /permissions menu onto Full Access, the
@@ -8,7 +8,8 @@ import { watch } from "node:fs";
8
8
  import path from "node:path";
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { atomicInPrivateDir, BridgeError, bridgeRoot, object, objects, provider, targetSchema } from "./protocol.js";
11
- import { findPane, herdrPaneFromEnv, knownPanes, rpc, servers, snapshot, trustedDirectory, validateTarget } from "./herdr.js";
11
+ import { findPane, knownPanes, servers, snapshot, trustedDirectory, validateTarget } from "./herdr.js";
12
+ import { terminalPaneFromEnv, terminalProvider } from "./terminal.js";
12
13
  import { readPaneText } from "./pane-text.js";
13
14
  import { capturesChanges, ToolChanges } from "./changes.js";
14
15
  import { phrenStoreRoot, unwrapPastedContent } from "./transcripts.js";
@@ -17,9 +18,10 @@ import { ensureGrant, listGrants, matchGrant } from "./grants.js";
17
18
  import { ApprovalPushService } from "./push.js";
18
19
  import { intervalFromEnv } from "./limits.js";
19
20
  import { answerClaudeQuestionDialog, claudeQuestionDialog } from "./claude-question-dialog.js";
20
- import { answeredQuestionInput, numberedDialog, passwordLine, permissionPrompt, questionChoice, terminalChoice, terminalQuestions, visibleTerminalChoice } from "./terminal-choice.js";
21
+ import { answeredQuestionInput, numberedDialog, opencodePermissionDialog, passwordLine, permissionPrompt, questionChoice, terminalChoice, terminalQuestions, visibleTerminalChoice } from "./terminal-choice.js";
21
22
  import { directoryNames, opencodeApprovalFile, opencodeRequest, readOpencodeRequest } from "./opencode-approvals.js";
22
23
  import { ApprovalWatchLeases, bindingPath, localSocket, PushBindingStore } from "./agent-hook-stores.js";
24
+ import { eventStatus, notePaneStatus, settleBlockedPane } from "./pane-status.js";
23
25
  import { countTick } from "./metrics.js";
24
26
  export { permissionPrompt, terminalChoice, visibleTerminalChoice } from "./terminal-choice.js";
25
27
  export { ApprovalWatchLeases, PushBindingStore, recordedSession } from "./agent-hook-stores.js";
@@ -472,9 +474,13 @@ export class AgentHooks {
472
474
  this.terminalPrompts.delete(key);
473
475
  return;
474
476
  }
475
- // Codex draws "> 1. Yes, proceed (y)" rows; the other fallbacks number
476
- // rows without a key in the label.
477
- const dialog = target.source === "codex" ? visibleTerminalChoice(text) : numberedDialog(text);
477
+ // Codex draws "> 1. Yes, proceed (y)" rows and Copilot a boxed select
478
+ // with a cursor row, both answered by moving to a row; the other
479
+ // fallbacks number rows without a key in the label.
480
+ const dialog = ["codex", "copilot"].includes(target.source) ? visibleTerminalChoice(text)
481
+ // OpenCode's prompt is one row of options; its cursor is only a color.
482
+ : target.source === "opencode" ? opencodePermissionDialog(await this.paneAnsi(target))?.choice ?? numberedDialog(text)
483
+ : numberedDialog(text);
478
484
  if (entry && !entry.dialog) {
479
485
  // The permission the pane still shows after its hook let go: keep the
480
486
  // request's own details and answer it with the dialog's rows, so the
@@ -485,15 +491,20 @@ export class AgentHooks {
485
491
  entry.choice = dialog;
486
492
  entry.released = true;
487
493
  }
488
- else if (entry.released) {
489
- delete entry.choice;
490
- delete entry.released;
494
+ else {
495
+ if (entry.released) {
496
+ delete entry.choice;
497
+ delete entry.released;
498
+ }
499
+ settleBlockedPane(target.server, target.pane);
491
500
  }
492
501
  return;
493
502
  }
503
+ // No dialog left: a request answered in the terminal itself.
494
504
  if (!dialog?.title) {
495
505
  if (entry)
496
506
  this.terminalPrompts.delete(key);
507
+ settleBlockedPane(target.server, target.pane);
497
508
  return;
498
509
  }
499
510
  this.terminalPrompts.set(key, { tool: "Question", message: dialog.title, choice: dialog, dialog: true, at: now });
@@ -519,6 +530,10 @@ export class AgentHooks {
519
530
  return entry?.dialog && digit ? [...keys, "Enter"] : [...keys];
520
531
  }
521
532
  async moveDialogHighlight(target, expected, key, beforeKeys) {
533
+ if (target.source === "opencode") {
534
+ await this.selectOpencodeOnce(target, expected, beforeKeys);
535
+ return;
536
+ }
522
537
  const intended = expected.options.findIndex(option => option.key === key);
523
538
  let current = visibleTerminalChoice(await this.paneLines(target));
524
539
  // A held permission can expose just the asking sentence from the title.
@@ -536,8 +551,7 @@ export class AgentHooks {
536
551
  if (!difference)
537
552
  return;
538
553
  await beforeKeys?.();
539
- await rpc(target.server, "agent.send_keys", { target: target.pane,
540
- keys: Array(Math.abs(difference)).fill(difference > 0 ? "down" : "up") });
554
+ await terminalProvider().sendKeys(target.server, target.pane, Array(Math.abs(difference)).fill(difference > 0 ? "down" : "up"));
541
555
  await new Promise(resolve => setTimeout(resolve, 150));
542
556
  current = visibleTerminalChoice(await this.paneLines(target));
543
557
  if (matches(current) && current.highlightedIndex === intended) {
@@ -549,6 +563,27 @@ export class AgentHooks {
549
563
  }
550
564
  throw new BridgeError(409, "Could not move and verify the terminal selection. Open terminal to choose this option.");
551
565
  }
566
+ /** Put OpenCode's cursor on Allow once, the row's first option: ← as many
567
+ * times as the cursor sits to its right, then read the colors again. The
568
+ * same prompt must still be showing, or nothing more is sent. */
569
+ async selectOpencodeOnce(target, expected, beforeKeys) {
570
+ const read = async () => opencodePermissionDialog(await this.paneAnsi(target));
571
+ const current = await read();
572
+ if (current && current.choice.title === expected.title && current.selected !== undefined) {
573
+ await validateTarget(target, false, true);
574
+ if (current.selected > 0) {
575
+ await beforeKeys?.();
576
+ await terminalProvider().sendKeys(target.server, target.pane, Array(current.selected).fill("left"));
577
+ await new Promise(resolve => setTimeout(resolve, 150));
578
+ }
579
+ const moved = current.selected > 0 ? await read() : current;
580
+ if (moved && moved.choice.title === expected.title && moved.selected === 0) {
581
+ await validateTarget(target, false, true);
582
+ return;
583
+ }
584
+ }
585
+ throw new BridgeError(409, "Could not move and verify the terminal selection. Open terminal to choose this option.");
586
+ }
552
587
  /** Answer Claude's AskUserQuestion dialog in the pane: every question in
553
588
  * `answers` from `from` on, then the set's submission when `submit`. The
554
589
  * walk reads the pane before and after each key, so a dialog on another
@@ -562,7 +597,7 @@ export class AgentHooks {
562
597
  if (!keys.length)
563
598
  return;
564
599
  await validateTarget(target, false, true);
565
- await rpc(target.server, "agent.send_keys", { target: target.pane, keys });
600
+ await terminalProvider().sendKeys(target.server, target.pane, keys);
566
601
  },
567
602
  }, questions, answers, options);
568
603
  this.dialogReads.delete(key);
@@ -621,9 +656,13 @@ export class AgentHooks {
621
656
  return entry && Date.now() - entry.at < 30_000 ? entry.command : undefined;
622
657
  }
623
658
  menuClosed(target) { this.menus.delete(JSON.stringify(target)); }
659
+ /** The pane with its colors, for dialogs whose cursor is only a color. */
660
+ paneAnsi(target) {
661
+ return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines: 40, stripAnsi: false, format: "ansi", timeoutMs: 2_000 });
662
+ }
624
663
  /** Read what the pane draws, stripping ANSI unless placeholder styling is needed. */
625
664
  paneLines(target, stripAnsi = true) {
626
- return readPaneText(target.server, target.pane, { method: "agent.read", source: "visible", lines: 40, stripAnsi, timeoutMs: 2_000 });
665
+ return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines: 40, stripAnsi, timeoutMs: 2_000 });
627
666
  }
628
667
  /** After the phone walks Codex's /permissions menu onto Full Access, the
629
668
  * agent draws a second "Enable full access?" confirmation. Watch the pane's
@@ -645,8 +684,7 @@ export class AgentHooks {
645
684
  if (option.hasKey === false)
646
685
  await this.moveDialogHighlight(target, choice, option.key);
647
686
  await validateTarget(target, false, true);
648
- await rpc(target.server, "agent.send_keys", { target: target.pane,
649
- keys: option.hasKey === false ? ["enter"] : [option.key.toLowerCase(), "enter"] });
687
+ await terminalProvider().sendKeys(target.server, target.pane, option.hasKey === false ? ["enter"] : [option.key.toLowerCase(), "enter"]);
650
688
  this.clearTerminalPrompt(target);
651
689
  this.menuClosed(target);
652
690
  return { menuClosed: true };
@@ -790,6 +828,7 @@ export class AgentHooks {
790
828
  this.pending.delete(id);
791
829
  this.dropPushBindings(id);
792
830
  clearTimeout(entry.timer);
831
+ settleBlockedPane(entry.target.server, entry.target.pane, 0);
793
832
  entry.response.end(JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: {
794
833
  behavior: effective === "approve" ? "allow" : "deny", ...(effective === "deny" ? { message: "Declined in Phren." } : {}),
795
834
  ...(answered ? { updatedInput: answered } : {}),
@@ -970,8 +1009,7 @@ export class AgentHooks {
970
1009
  ? live.options.find(row => /^(yes|allow|approve|proceed|continue|run)\b/i.test(row.label)) ?? live.options[0]
971
1010
  : live.options.find(row => /^(no|deny|reject|don'?t|cancel|skip)\b/i.test(row.label));
972
1011
  const keys = option ? await this.dialogAnswerKeys(dialog.target, [option.key]) : ["Escape"];
973
- await rpc(dialog.target.server, "agent.send_keys", { target: dialog.target.pane,
974
- keys: keys.map(key => key === "Enter" ? "enter" : key === "Escape" ? "esc" : key.toLowerCase()) });
1012
+ await terminalProvider().sendKeys(dialog.target.server, dialog.target.pane, keys.map(key => key === "Enter" ? "enter" : key === "Escape" ? "esc" : key.toLowerCase()));
975
1013
  this.clearTerminalPrompt(dialog.target);
976
1014
  this.dropDialogPush(key);
977
1015
  }
@@ -1010,12 +1048,16 @@ export class AgentHooks {
1010
1048
  const pane = findPane(s, { workspace: target.workspace, tab: target.tab, pane: target.pane });
1011
1049
  if (!pane || (pane.agent && pane.agent !== target.source))
1012
1050
  throw new Error("The pane changed");
1013
- const info = object((await rpc(target.server, "pane.process_info", { pane_id: target.pane })).process_info);
1014
- const pids = objects(info.foreground_processes).map(p => p.pid).filter(p => Number.isSafeInteger(p));
1051
+ const pids = (await terminalProvider().processes(target.server, target.pane)).foregroundPids;
1015
1052
  if (!pids.length)
1016
1053
  throw new Error("No foreground process");
1017
1054
  await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({ terminal: pane.terminal_id, source: target.source,
1018
- session: target.session, pids, workspace: target.workspace, tab: target.tab }));
1055
+ session: target.session, pids, workspace: target.workspace, tab: target.tab, event: String(body.event).slice(0, 64), at: new Date().toISOString() }));
1056
+ // A terminal that does not watch its agents (tmux) takes the agent's
1057
+ // status from these events.
1058
+ const status = eventStatus(body.event);
1059
+ if (status && typeof pane.terminal_id === "string")
1060
+ notePaneStatus(target.server, target.pane, pane.terminal_id, status);
1019
1061
  // What a shell call changed on disk: snapshot before, diff after.
1020
1062
  const input = typeof body.input === "string" ? { patch: body.input } : object(body.input), command = [input.command, input.cmd].find(v => typeof v === "string");
1021
1063
  // A shell call by name, or any tool whose input is a command line —
@@ -1180,10 +1222,9 @@ export class AgentHooks {
1180
1222
  export async function agentHook(source) {
1181
1223
  provider.parse(source);
1182
1224
  // A missing helper must never prevent the coding agent from running.
1183
- if (process.env.HERDR_ENV !== "1" || !process.env.HERDR_SOCKET_PATH)
1184
- return;
1185
- const server = herdrPaneFromEnv()?.server;
1186
- if (!server)
1225
+ // Inside Herdr only Herdr's pane counts; elsewhere a tmux pane does.
1226
+ const place = await terminalPaneFromEnv();
1227
+ if (!place)
1187
1228
  return;
1188
1229
  let input = "";
1189
1230
  for await (const chunk of process.stdin) {
@@ -1194,8 +1235,8 @@ export async function agentHook(source) {
1194
1235
  const value = object(JSON.parse(input));
1195
1236
  if (value.agent_id || value.agentId || value.isSidechain || value.is_sidechain)
1196
1237
  return;
1197
- const target = targetSchema.parse({ server, workspace: process.env.HERDR_WORKSPACE_ID, tab: process.env.HERDR_TAB_ID,
1198
- pane: process.env.HERDR_PANE_ID, source, session: value.session_id || value.sessionId });
1238
+ const target = targetSchema.parse({ server: place.server, workspace: place.workspace, tab: place.tab,
1239
+ pane: place.pane, source, session: value.session_id || value.sessionId });
1199
1240
  const event = String(value.hook_event_name || "SessionStart");
1200
1241
  const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
1201
1242
  if (!modules.has("hook") || (event.endsWith("ToolUse") && !modules.has("git")))
@@ -14,6 +14,10 @@ export interface CanaryOptions {
14
14
  server?: string;
15
15
  root?: string;
16
16
  }
17
+ /** Where the canary's conductor starts: Herdr's default server, else the
18
+ * first Herdr server running; on a computer without Herdr, tmux's hidden
19
+ * server, so nothing opens where the owner is working. Undefined with neither. */
20
+ export declare function canaryServer(): Promise<string | undefined>;
17
21
  /** Exercise the real launch, schedule, transcript and session paths once and
18
22
  * save the outcome to canary.json. Everything it opens is closed again, even on
19
23
  * failure; it never sends input to an existing pane and never runs or edits the
@@ -4,7 +4,9 @@ import path from "node:path";
4
4
  import { getProjectDirs } from "../phren-paths.js";
5
5
  import { listLiveSessions } from "./hand-off.js";
6
6
  import { canaryFile, readCanary } from "./health.js";
7
- import { paneIdentity, rpc, servers, snapshot } from "./herdr.js";
7
+ import { paneIdentity, servers, snapshot } from "./herdr.js";
8
+ import { terminalProvider } from "./terminal.js";
9
+ import { TMUX_HIDDEN } from "./terminal-tmux.js";
8
10
  import { atomic, BridgeError, bridgeRoot, id, objects, provider } from "./protocol.js";
9
11
  import { readScheduleDocument } from "./schedules.js";
10
12
  import { TranscriptReader, transcriptPath } from "./transcripts.js";
@@ -42,7 +44,7 @@ async function closeCanaryWorkspaces(server, before, created) {
42
44
  if (!id.safeParse(workspace.workspace_id).success)
43
45
  continue;
44
46
  try {
45
- await rpc(server, "workspace.close", { workspace_id: workspace.workspace_id });
47
+ await terminalProvider().groupAction(server, "close", { workspace: String(workspace.workspace_id) });
46
48
  }
47
49
  catch (error) {
48
50
  failures.push(`${String(workspace.workspace_id)}: ${reason(error)}`);
@@ -128,6 +130,16 @@ async function sessionsStep() {
128
130
  return { status: "failed", detail, reason: `Unreachable: ${live.unreachable.map(item => `${item.computer} (${item.error})`).join("; ")}` };
129
131
  return { status: "ok", detail };
130
132
  }
133
+ /** Where the canary's conductor starts: Herdr's default server, else the
134
+ * first Herdr server running; on a computer without Herdr, tmux's hidden
135
+ * server, so nothing opens where the owner is working. Undefined with neither. */
136
+ export async function canaryServer() {
137
+ const live = await servers().catch(() => []);
138
+ const herdr = live.filter(server => server.terminal !== "tmux").map(server => String(server.session));
139
+ if (herdr.length)
140
+ return herdr.includes("default") ? "default" : herdr[0];
141
+ return live.some(server => server.session === TMUX_HIDDEN) ? TMUX_HIDDEN : undefined;
142
+ }
131
143
  let running;
132
144
  /** Exercise the real launch, schedule, transcript and session paths once and
133
145
  * save the outcome to canary.json. Everything it opens is closed again, even on
@@ -137,8 +149,9 @@ export function runCanary(options) {
137
149
  if (running)
138
150
  throw new BridgeError(409, "A canary is already running on this computer.");
139
151
  running = (async () => {
140
- const started = new Date(), steps = [], server = options.server ?? "default";
141
- await step(steps, "conductor", () => conductorStep(options, server));
152
+ const started = new Date(), steps = [], server = options.server ?? await canaryServer();
153
+ await step(steps, "conductor", async () => server ? conductorStep(options, server)
154
+ : { status: "failed", reason: "No terminal to start an agent in: Herdr is not running and tmux is not installed (or PHREN_TMUX=off)." });
142
155
  await step(steps, "schedules", () => scheduleStep(options));
143
156
  await step(steps, "transcript", () => transcriptStep());
144
157
  await step(steps, "sessions", () => sessionsStep());
@@ -33,6 +33,13 @@ export declare class ToolChanges {
33
33
  private results;
34
34
  private controllers;
35
35
  private claims;
36
+ /** A hook callback's wall-clock cap on Git work; past it the call records
37
+ * no change. Tests about what is captured raise it, since a loaded Windows
38
+ * runner's Git can take longer than a person's machine ever does. */
39
+ private readonly budgetMs;
40
+ constructor(options?: {
41
+ budgetMs?: number;
42
+ });
36
43
  private file;
37
44
  private budget;
38
45
  private discard;
@@ -192,11 +192,16 @@ export class ToolChanges {
192
192
  results = new Map();
193
193
  controllers = new Set();
194
194
  claims = [];
195
+ /** A hook callback's wall-clock cap on Git work; past it the call records
196
+ * no change. Tests about what is captured raise it, since a loaded Windows
197
+ * runner's Git can take longer than a person's machine ever does. */
198
+ budgetMs;
199
+ constructor(options = {}) { this.budgetMs = options.budgetMs ?? BUDGET; }
195
200
  file(conversation) { return path.join(bridgeRoot(), "changes", conversation.replace(/[^A-Za-z0-9._-]/g, "_") + ".jsonl"); }
196
201
  async budget(work) {
197
202
  const controller = new AbortController();
198
203
  this.controllers.add(controller);
199
- const timer = setTimeout(() => controller.abort(), BUDGET);
204
+ const timer = setTimeout(() => controller.abort(), this.budgetMs);
200
205
  try {
201
206
  return await work(controller.signal);
202
207
  }
@@ -19,8 +19,9 @@ export async function hookRequest(route, data, options = { socketPath: socketPat
19
19
  response.on("end", () => {
20
20
  try {
21
21
  const value = object(JSON.parse(Buffer.concat(chunks).toString()));
22
+ // A remote Hook's `code` (why its Herdr is offline, say) travels on with its text.
22
23
  if (response.statusCode !== 200)
23
- throw new BridgeError(response.statusCode ?? 502, typeof value.error === "string" ? value.error.slice(0, 500) : "Hook rejected the request.");
24
+ throw new BridgeError(response.statusCode ?? 502, typeof value.error === "string" ? value.error.slice(0, 500) : "Hook rejected the request.", typeof value.code === "string" && /^[a-z][a-z0-9-]{0,39}$/.test(value.code) ? { code: value.code } : undefined);
24
25
  resolve(value);
25
26
  }
26
27
  catch (error) {
@@ -3,6 +3,7 @@ import { serve } from "./server.js";
3
3
  import { dispatch, health } from "./transport.js";
4
4
  import { install, rollback, uninstall } from "./install.js";
5
5
  import { servers } from "./herdr.js";
6
+ import { describeTerminal, terminalHealth } from "./health.js";
6
7
  import { agentHook } from "./agent-hooks.js";
7
8
  import { object, provider } from "./protocol.js";
8
9
  import { apnsSetupSteps } from "./push.js";
@@ -113,13 +114,14 @@ export async function runBridge(args, version) {
113
114
  console.log(JSON.stringify(await health(), null, 2));
114
115
  break;
115
116
  case "doctor": {
116
- const helper = await health(), muxes = await servers();
117
+ const helper = await health(), muxes = await servers(), terminal = await terminalHealth();
117
118
  const push = approvalPushCheck(helper), speech = await speechKeyStatus();
118
- // Chat needs Herdr; a plain project shell or agent over SSH does not.
119
- console.log(JSON.stringify({ ok: true, helper, herdr: muxes, checks: {
119
+ // Chat needs Herdr or tmux; a plain project shell or agent over SSH does not.
120
+ console.log(JSON.stringify({ ok: true, helper, herdr: muxes, terminal, checks: {
120
121
  privateSocket: true, protocol: true, independentHelper: true,
121
- herdrRunning: muxes.length > 0, terminal: "SSH PTY; authorize the Phren device key with pty",
122
- shell: muxes.length > 0 ? "available" : "Herdr is not running: chat is unavailable, project shells and agents still open over SSH",
122
+ herdrRunning: terminal.servers.some(server => server.provider === "herdr"), terminal: "SSH PTY; authorize the Phren device key with pty",
123
+ multiplexer: describeTerminal(terminal),
124
+ shell: muxes.length > 0 ? "available" : "Neither Herdr nor tmux is available: chat is unavailable, project shells and agents still open over SSH",
123
125
  approvalPush: push.configured ? "configured" : "not configured",
124
126
  speechKey: speech.configured ? "configured" : "not configured", speechKeyDetail: speech.detail,
125
127
  }, ...(push.warning ? { warnings: [push.warning] } : {}) }, null, 2));
@@ -16,6 +16,7 @@ export interface GroupConductor {
16
16
  unchecked: {
17
17
  computer: string;
18
18
  error: string;
19
+ code?: string;
19
20
  }[];
20
21
  }
21
22
  type Ask = (peer: HookPeer, route: string, data?: Json, timeout?: number) => Promise<Json>;
@@ -1,6 +1,6 @@
1
1
  import { disabledHint } from "../modules/registry.js";
2
2
  import { peerRequest } from "./peers.js";
3
- import { BridgeError, object } from "./protocol.js";
3
+ import { BridgeError, errorCode, object } from "./protocol.js";
4
4
  export async function groupConductor(peers, ask = peerRequest) {
5
5
  const answers = await Promise.all(peers.map(async (peer) => {
6
6
  try {
@@ -14,12 +14,13 @@ export async function groupConductor(peers, ask = peerRequest) {
14
14
  return { peer };
15
15
  const message = error instanceof BridgeError && error.status === 404 ? "Its Hook is too old to report a conductor."
16
16
  : error instanceof Error ? error.message : "Unreachable.";
17
- return { peer, error: message };
17
+ const code = errorCode(error);
18
+ return { peer, error: message, ...(code ? { code } : {}) };
18
19
  }
19
20
  }));
20
21
  const hit = answers.find(answer => answer.conductor);
21
22
  return {
22
23
  ...(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
+ unchecked: answers.flatMap(answer => "error" in answer && answer.error ? [{ computer: answer.peer.name, error: answer.error, ...("code" in answer && answer.code ? { code: answer.code } : {}) }] : []),
24
25
  };
25
26
  }
@@ -2,7 +2,7 @@ import { parseArgs } from "node:util";
2
2
  import { hookRequest } from "./client.js";
3
3
  import { dispatchSchema } from "./dispatch.js";
4
4
  import { handOff } from "./hand-off.js";
5
- import { herdrPaneFromEnv } from "./herdr.js";
5
+ import { terminalPaneFromEnv } from "./terminal.js";
6
6
  import { addGrant, grantSchema, listGrants, removeGrant } from "./grants.js";
7
7
  import { sessionId } from "./protocol.js";
8
8
  export async function runDispatch(args) {
@@ -39,7 +39,7 @@ export async function runDispatch(args) {
39
39
  const input = dispatchSchema.parse({ computer: positionals[0], project: positionals[1], ...ordinary,
40
40
  ...(parent ? { parent, parentTarget } : {}) });
41
41
  // Run inside an agent's pane, the dispatch remembers that pane for return notices.
42
- const origin = herdrPaneFromEnv();
42
+ const origin = await terminalPaneFromEnv();
43
43
  const result = await hookRequest("/v1/dispatch", { ...input, ...(origin ? { origin } : {}) }, undefined, 180_000);
44
44
  console.log(JSON.stringify(result, null, 2));
45
45
  return result.ok === true ? 0 : 1;
@@ -402,9 +402,13 @@ export async function archiveFinishedFanouts(env = process.env, options = {}) {
402
402
  }
403
403
  // Cap the archive: after the moves it may hold ARCHIVE_MAX_FOLDERS + n folders.
404
404
  const archived = (await readdir(archive).catch(() => [])).filter(name => jobID.safeParse(name).success);
405
+ // Up to ARCHIVE_MAX_FOLDERS + n folders at two or three file reads each:
406
+ // one at a time that takes seconds on Windows, where every stat is slow.
405
407
  const entries = [];
406
- for (const name of archived)
407
- entries.push({ name, age: await archivedFinishedAt(path.join(archive, name)) });
408
+ for (let index = 0; index < archived.length; index += 32) {
409
+ entries.push(...await Promise.all(archived.slice(index, index + 32)
410
+ .map(async (name) => ({ name, age: await archivedFinishedAt(path.join(archive, name)) }))));
411
+ }
408
412
  // On a dry run the moves never landed, so weigh them at their finish stamp.
409
413
  if (dryRun)
410
414
  for (const move of moves)
@@ -65,6 +65,7 @@ export interface LiveSessions {
65
65
  unreachable: {
66
66
  computer: string;
67
67
  error: string;
68
+ code?: string;
68
69
  }[];
69
70
  /** Registered in the store but not linked in hooks.yaml: unknown, not idle. */
70
71
  notLinked: NotLinkedComputer[];
@@ -4,7 +4,7 @@ import { hookRequest } from "./client.js";
4
4
  import { projectName } from "./dispatch.js";
5
5
  import { grantLabel, listGrants, matchGrant } from "./grants.js";
6
6
  import { hookPeers, optionalHookPeers, peerRequest } from "./peers.js";
7
- import { BridgeError, object, objects, sessionId, targetSchema } from "./protocol.js";
7
+ import { BridgeError, errorCode, object, objects, sessionId, targetSchema } from "./protocol.js";
8
8
  import { findPhrenPath } from "../phren-paths.js";
9
9
  import { listMachines } from "../profile-store.js";
10
10
  import { localNames } from "./computer-names.js";
@@ -146,7 +146,8 @@ export async function listLiveSessions(options = {}) {
146
146
  peerNames.push(name);
147
147
  }
148
148
  catch (error) {
149
- unreachable.push({ computer: peer.name, error: error instanceof Error ? error.message : "Unreachable." });
149
+ const code = errorCode(error);
150
+ unreachable.push({ computer: peer.name, error: error instanceof Error ? error.message : "Unreachable.", ...(code ? { code } : {}) });
150
151
  }
151
152
  }));
152
153
  const store = options.store !== undefined ? options.store : findPhrenPath();
@@ -0,0 +1,12 @@
1
+ /** What phren's OpenCode plugin last recorded for any of `pids`, newest first. */
2
+ export declare function opencodeProcessStatus(pids: number[], root?: string): Promise<string | undefined>;
3
+ /** The status a Copilot session log's lines leave the session in; undefined
4
+ * when none of them says. Copilot writes a turn_start/turn_end pair per model
5
+ * call, so only the turn that carried the final answer ends the work. */
6
+ export declare function copilotStatusFromEvents(lines: string[]): string | undefined;
7
+ /** The status of the Copilot conversation a process shows, from the tail of
8
+ * its session log; unchanged files are not read again. */
9
+ export declare function copilotProcessStatus(pids: number[], home?: string): Promise<string | undefined>;
10
+ /** The status `agent`'s own records give for a pane running `pids`, for the
11
+ * harnesses whose lifecycle hooks say nothing about turns. */
12
+ export declare function harnessStatus(agent: string, pids: number[]): Promise<string | undefined>;
@@ -0,0 +1,153 @@
1
+ // Agent status for the harnesses whose lifecycle hooks do not report turns,
2
+ // read from what they write themselves. The tmux snapshot asks; Herdr watches
3
+ // its agents and never needs this.
4
+ //
5
+ // OpenCode: phren's OpenCode plugin records the process's state by PID
6
+ // (`opencode-status-<pid>.json` beside the PID binding) from OpenCode's own
7
+ // session.status, session.idle and permission events.
8
+ // Copilot: its session log (`~/.copilot/session-state/<id>/events.jsonl`)
9
+ // brackets every prompt: a user message starts work, a permission request
10
+ // waits for an answer, the final answer's turn end (or session.idle, abort)
11
+ // finishes it.
12
+ import { open, stat } from "node:fs/promises";
13
+ import { homedir } from "node:os";
14
+ import path from "node:path";
15
+ import { copilotForegroundSession } from "./herdr.js";
16
+ import { object } from "./protocol.js";
17
+ import { phrenStoreRoot } from "./transcripts.js";
18
+ const STATUSES = new Set(["working", "idle", "blocked"]);
19
+ /** What phren's OpenCode plugin last recorded for any of `pids`, newest first. */
20
+ export async function opencodeProcessStatus(pids, root = phrenStoreRoot()) {
21
+ const folder = path.join(root, ".runtime", "sessions");
22
+ let current, latest = -Infinity;
23
+ for (const pid of pids.slice(0, 16)) {
24
+ const file = await open(path.join(folder, `opencode-status-${pid}.json`), "r").catch(() => undefined);
25
+ if (!file)
26
+ continue;
27
+ try {
28
+ if ((await file.stat()).size > 4_096)
29
+ continue;
30
+ const value = object(JSON.parse((await file.readFile()).toString("utf8")));
31
+ const at = Date.parse(String(value.at));
32
+ if (typeof value.status !== "string" || !STATUSES.has(value.status) || !(at > latest))
33
+ continue;
34
+ current = value.status;
35
+ latest = at;
36
+ }
37
+ catch {
38
+ continue;
39
+ }
40
+ finally {
41
+ await file.close();
42
+ }
43
+ }
44
+ return current;
45
+ }
46
+ /** The status a Copilot session log's lines leave the session in; undefined
47
+ * when none of them says. Copilot writes a turn_start/turn_end pair per model
48
+ * call, so only the turn that carried the final answer ends the work. */
49
+ export function copilotStatusFromEvents(lines) {
50
+ let status, final = false;
51
+ const asking = new Set();
52
+ const working = () => asking.size ? "blocked" : "working";
53
+ for (const line of lines) {
54
+ let raw;
55
+ try {
56
+ raw = object(JSON.parse(line));
57
+ }
58
+ catch {
59
+ continue;
60
+ }
61
+ const data = object(raw.data), type = String(raw.type ?? ""), sub = !!raw.agentId;
62
+ switch (type) {
63
+ case "session.start":
64
+ case "session.resume":
65
+ status = "idle";
66
+ final = false;
67
+ asking.clear();
68
+ break;
69
+ case "user.message":
70
+ final = false;
71
+ status = working();
72
+ break;
73
+ case "assistant.turn_start":
74
+ case "tool.execution_start":
75
+ case "tool.execution_complete":
76
+ status = working();
77
+ break;
78
+ case "assistant.message":
79
+ if (!sub && data.phase === "final_answer")
80
+ final = true;
81
+ status = working();
82
+ break;
83
+ case "assistant.turn_end":
84
+ if (!sub && final && !asking.size)
85
+ status = "idle";
86
+ break;
87
+ case "permission.requested":
88
+ asking.add(String(data.requestId ?? ""));
89
+ status = "blocked";
90
+ break;
91
+ case "permission.completed":
92
+ asking.delete(String(data.requestId ?? ""));
93
+ status = working();
94
+ break;
95
+ case "session.idle":
96
+ case "abort":
97
+ case "session.error":
98
+ case "session.shutdown":
99
+ status = "idle";
100
+ final = false;
101
+ asking.clear();
102
+ break;
103
+ }
104
+ }
105
+ return status;
106
+ }
107
+ const TAIL_BYTES = 262_144;
108
+ const copilotCache = new Map();
109
+ /** The status of the Copilot conversation a process shows, from the tail of
110
+ * its session log; unchanged files are not read again. */
111
+ export async function copilotProcessStatus(pids, home = process.env.COPILOT_HOME || path.join(homedir(), ".copilot")) {
112
+ const session = await copilotForegroundSession(pids, home);
113
+ if (!session)
114
+ return undefined;
115
+ const file = path.join(home, "session-state", session, "events.jsonl");
116
+ const info = await stat(file).catch(() => undefined);
117
+ if (!info?.isFile())
118
+ return undefined;
119
+ const cached = copilotCache.get(file);
120
+ if (cached && cached.size === info.size && cached.mtime === info.mtimeMs)
121
+ return cached.status;
122
+ const handle = await open(file, "r");
123
+ let text;
124
+ try {
125
+ const length = Math.min(info.size, TAIL_BYTES);
126
+ const { buffer, bytesRead } = await handle.read(Buffer.alloc(length), 0, length, info.size - length);
127
+ text = buffer.subarray(0, bytesRead).toString("utf8");
128
+ }
129
+ finally {
130
+ await handle.close();
131
+ }
132
+ const lines = text.split("\n");
133
+ // A tail that starts mid-line drops that line.
134
+ if (info.size > TAIL_BYTES)
135
+ lines.shift();
136
+ const status = copilotStatusFromEvents(lines);
137
+ copilotCache.delete(file);
138
+ while (copilotCache.size >= 64)
139
+ copilotCache.delete(copilotCache.keys().next().value);
140
+ copilotCache.set(file, { size: info.size, mtime: info.mtimeMs, status });
141
+ return status;
142
+ }
143
+ /** The status `agent`'s own records give for a pane running `pids`, for the
144
+ * harnesses whose lifecycle hooks say nothing about turns. */
145
+ export async function harnessStatus(agent, pids) {
146
+ if (!pids.length)
147
+ return undefined;
148
+ if (agent === "opencode")
149
+ return opencodeProcessStatus(pids);
150
+ if (agent === "copilot")
151
+ return copilotProcessStatus(pids);
152
+ return undefined;
153
+ }