@phren/cli 0.3.4 → 0.3.6

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 (79) hide show
  1. package/dist/bridge/agent-hooks.d.ts +6 -0
  2. package/dist/bridge/agent-hooks.js +63 -23
  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.js +5 -4
  23. package/dist/bridge/models.js +3 -2
  24. package/dist/bridge/pane-status.d.ts +37 -0
  25. package/dist/bridge/pane-status.js +139 -0
  26. package/dist/bridge/pane-text.d.ts +3 -11
  27. package/dist/bridge/pane-text.js +9 -16
  28. package/dist/bridge/peers.js +9 -6
  29. package/dist/bridge/prompt-once.d.ts +26 -0
  30. package/dist/bridge/prompt-once.js +69 -0
  31. package/dist/bridge/protocol.d.ts +10 -0
  32. package/dist/bridge/protocol.js +10 -0
  33. package/dist/bridge/schedule-format.d.ts +2 -0
  34. package/dist/bridge/schedule-launch.d.ts +10 -1
  35. package/dist/bridge/schedule-launch.js +29 -3
  36. package/dist/bridge/schedule-watch.js +1 -1
  37. package/dist/bridge/schedules.d.ts +10 -0
  38. package/dist/bridge/schedules.js +40 -0
  39. package/dist/bridge/server-launch.js +12 -10
  40. package/dist/bridge/server-pane-routes.js +23 -9
  41. package/dist/bridge/server-routes.d.ts +1 -0
  42. package/dist/bridge/server-routes.js +1 -1
  43. package/dist/bridge/session-servers.js +5 -6
  44. package/dist/bridge/side-questions.js +6 -5
  45. package/dist/bridge/terminal-choice.d.ts +11 -0
  46. package/dist/bridge/terminal-choice.js +37 -0
  47. package/dist/bridge/terminal-herdr.d.ts +5 -0
  48. package/dist/bridge/terminal-herdr.js +57 -0
  49. package/dist/bridge/terminal-tmux.d.ts +111 -0
  50. package/dist/bridge/terminal-tmux.js +549 -0
  51. package/dist/bridge/terminal.d.ts +119 -0
  52. package/dist/bridge/terminal.js +66 -0
  53. package/dist/bridge/transcript-claude.d.ts +6 -0
  54. package/dist/bridge/transcript-claude.js +20 -0
  55. package/dist/bridge/transcript-opencode.js +1 -1
  56. package/dist/bridge/transcript-preview.js +1 -1
  57. package/dist/bridge/transport.js +10 -4
  58. package/dist/bridge-hook.mjs +4800 -3397
  59. package/dist/cli-registry.js +7 -0
  60. package/dist/entrypoint.d.ts +2 -0
  61. package/dist/entrypoint.js +5 -1
  62. package/dist/index.js +8 -2
  63. package/dist/init/init.js +4 -0
  64. package/dist/link/doctor.js +33 -30
  65. package/dist/mcp/plugin-mode.d.ts +16 -0
  66. package/dist/mcp/plugin-mode.js +106 -0
  67. package/dist/modules/agent-package.d.ts +35 -0
  68. package/dist/modules/agent-package.js +133 -0
  69. package/dist/modules/registry.js +2 -2
  70. package/dist/session/utils.js +1 -1
  71. package/dist/tools/dispatch.js +2 -2
  72. package/package.json +1 -1
  73. package/plugins/opencode/phren-transcript.js +97 -6
  74. package/starter/global/skills/phren-consolidate/SKILL.md +1 -1
  75. package/starter/global/skills/phren-discover/SKILL.md +1 -1
  76. package/starter/global/skills/phren-init/SKILL.md +6 -8
  77. package/starter/global/skills/phren-profiles/SKILL.md +1 -1
  78. package/starter/global/skills/phren-summarize/SKILL.md +1 -1
  79. package/starter/global/skills/phren-sync/SKILL.md +1 -1
@@ -1,3 +1,4 @@
1
+ import { type TmuxHealth } from "./terminal-tmux.js";
1
2
  /** One tool's installed version, or why there is none. */
2
3
  export interface ToolVersion {
3
4
  tool: string;
@@ -35,6 +36,8 @@ export interface PeerHealth {
35
36
  ms: number;
36
37
  error?: string;
37
38
  version?: string;
39
+ /** Why an unreachable peer failed, as a stable offline code (docs/phren-hook.md#offline-reasons). */
40
+ code?: string;
38
41
  /** Whether the peer's own hooks.yaml lists this computer; null when its Hook is too old to say. */
39
42
  listsBack: boolean | null;
40
43
  }
@@ -79,7 +82,22 @@ export interface HealthDetails {
79
82
  devices?: number;
80
83
  };
81
84
  canary: CanaryResult | null;
85
+ terminal: TerminalHealth;
82
86
  }
87
+ /** Which terminal multiplexer the Hook drives, per running server, and tmux's state. */
88
+ export interface TerminalHealth {
89
+ /** "herdr" while a Herdr server answers, else "tmux" when tmux can host agents, else "none". */
90
+ provider: "herdr" | "tmux" | "none";
91
+ servers: {
92
+ name: string;
93
+ provider: "herdr" | "tmux";
94
+ }[];
95
+ tmux: TmuxHealth;
96
+ }
97
+ /** The running servers the Hook lists (Herdr's, else tmux's) and tmux's own state. */
98
+ export declare function terminalHealth(): Promise<TerminalHealth>;
99
+ /** One line on the terminal: the provider, its servers and tmux's state. */
100
+ export declare function describeTerminal(terminal: TerminalHealth): string;
83
101
  export interface HealthOptions {
84
102
  /** The running Hook's own version; undefined when asked from outside a Hook. */
85
103
  hookVersion?: string;
@@ -8,10 +8,32 @@ import { getProjectDirs } from "../phren-paths.js";
8
8
  import { resolveAllStores } from "../store-registry.js";
9
9
  import { publicComputerKey } from "./computers.js";
10
10
  import { hookPeers, peerRequest } from "./peers.js";
11
- import { BridgeError, bridgeRoot } from "./protocol.js";
11
+ import { BridgeError, bridgeRoot, errorCode } from "./protocol.js";
12
12
  import { canonicalComputer, readScheduleDocument, readScheduleRuns, scheduleRunsFile } from "./schedules.js";
13
13
  import { countGit } from "./metrics.js";
14
+ import { tmuxHealth } from "./terminal-tmux.js";
14
15
  const exec = promisify(execFile);
16
+ /** The running servers the Hook lists (Herdr's, else tmux's) and tmux's own state. */
17
+ export async function terminalHealth() {
18
+ const [{ servers }, tmux] = await Promise.all([import("./herdr.js"), tmuxHealth()]);
19
+ const running = (await servers().catch(() => [])).map(server => ({ name: String(server.session),
20
+ provider: server.terminal === "tmux" ? "tmux" : "herdr" }));
21
+ const provider = running.some(server => server.provider === "herdr") ? "herdr" : running.length ? "tmux" : "none";
22
+ return { provider, servers: running, tmux };
23
+ }
24
+ /** One line on the terminal: the provider, its servers and tmux's state. */
25
+ export function describeTerminal(terminal) {
26
+ const tmux = terminal.tmux;
27
+ const hidden = tmux.hidden ? `hidden server ${tmux.hidden.running ? `running (${tmux.hidden.sessions ?? 0} session${tmux.hidden.sessions === 1 ? "" : "s"})` : "not started"}` : undefined;
28
+ const tmuxText = tmux.state === "off" ? "tmux off (PHREN_TMUX=off)" : tmux.state === "missing" ? "tmux not installed"
29
+ : [`tmux ${tmux.version ?? "(version unknown)"}`, tmux.launches === false ? "too old to start agents (needs 3.0)" : undefined, hidden].filter(Boolean).join(", ");
30
+ const names = terminal.servers.map(server => server.name).join(", ");
31
+ if (terminal.provider === "herdr")
32
+ return `herdr (${names}); ${tmuxText}`;
33
+ if (terminal.provider === "tmux")
34
+ return `tmux (${names}); ${tmuxText}`;
35
+ return `none: Herdr is not running; ${tmuxText}`;
36
+ }
15
37
  const VERSION_TIMEOUT_MS = 3_000;
16
38
  const VERSION_CACHE_MS = 5 * 60_000;
17
39
  const PEER_TIMEOUT_MS = 5_000;
@@ -171,7 +193,8 @@ async function probePeer(peer, caller) {
171
193
  catch (error) {
172
194
  const reason = error instanceof BridgeError && error.status === 504 ? "No answer within 5 seconds."
173
195
  : error instanceof Error ? error.message : "Unreachable.";
174
- return { name: peer.name, reachable: false, ms: Date.now() - started, error: plainError(reason), listsBack: null };
196
+ const code = errorCode(error);
197
+ return { name: peer.name, reachable: false, ms: Date.now() - started, error: plainError(reason), ...(code ? { code } : {}), listsBack: null };
175
198
  }
176
199
  }
177
200
  export function canaryFile(root = bridgeRoot()) { return path.join(root, "canary.json"); }
@@ -210,7 +233,7 @@ export async function healthDetails(options) {
210
233
  }
211
234
  return { configured: true, computers: await Promise.all(peers.map(peer => probePeer(peer, { name, hostKey }))) };
212
235
  })();
213
- const [versions, stores, lastRun, peers, canary, push] = await Promise.all([
236
+ const [versions, stores, lastRun, peers, canary, push, terminal] = await Promise.all([
214
237
  Promise.all([
215
238
  Promise.resolve(options.hookVersion ? { tool: "hook", status: "ok", version: options.hookVersion } : { tool: "hook", status: "missing", detail: "Phren Hook is not running." }),
216
239
  ...["herdr", "claude", "codex", "copilot", "opencode"].map(tool => toolVersion(tool)),
@@ -220,13 +243,14 @@ export async function healthDetails(options) {
220
243
  peersPromise,
221
244
  readCanary(),
222
245
  options.push ? Promise.resolve(options.push) : pushConfigured(),
246
+ terminalHealth(),
223
247
  ]);
224
248
  return {
225
249
  product: "phren-hook", computer: { name, ...(options.computerId ? { id: options.computerId } : {}) }, checkedAt: new Date().toISOString(),
226
250
  versions, stores,
227
251
  schedules: { running: options.scheduler ? options.scheduler.running : null,
228
252
  ...(options.scheduler?.lastTickAt ? { lastTickAt: options.scheduler.lastTickAt.toISOString() } : {}), lastRun },
229
- peers, push, canary,
253
+ peers, push, canary, terminal,
230
254
  };
231
255
  }
232
256
  /** Plain lines for `phren status`. */
@@ -251,6 +275,8 @@ export function formatHealth(health, color) {
251
275
  : peer.listsBack === false ? `${yellow}one-way${reset} ${dim}(${peer.name} does not list this computer)${reset}` : `${green}ok${reset} ${dim}${peer.ms} ms${reset}`;
252
276
  lines.push(` ${dim}peer${reset} ${peer.name} ${state}`);
253
277
  }
278
+ if (health.terminal)
279
+ lines.push(` ${dim}terminal${reset} ${health.terminal.provider === "none" ? `${yellow}${describeTerminal(health.terminal)}${reset}` : describeTerminal(health.terminal)}`);
254
280
  lines.push(` ${dim}push${reset} ${health.push.configured ? `${green}configured${reset}` : `${dim}not configured${reset}`}`);
255
281
  if (health.canary) {
256
282
  const failed = health.canary.steps.filter(step => step.status === "failed");
@@ -1,5 +1,7 @@
1
1
  import { BridgeError, type Json, type Target, type StartingTarget } from "./protocol.js";
2
2
  export declare function herdrRoot(): string;
3
+ /** Where Herdr's socket for `server` lives. */
4
+ export declare function herdrSocketPath(server: string): string;
3
5
  /** The Herdr pane this process runs in, from the variables Herdr sets for
4
6
  * every pane: the server its socket belongs to plus the pane's ids. */
5
7
  export declare function herdrPaneFromEnv(env?: NodeJS.ProcessEnv): {
@@ -72,6 +74,10 @@ export declare function paneIdentity(server: string, pane: Json, fresh?: boolean
72
74
  * lands in the new one and its UserPromptSubmit check refuses it, every time.
73
75
  * The process log Copilot names by PID records each switch as it happens. */
74
76
  export declare function copilotForegroundSession(pids: number[], home?: string): Promise<string | undefined>;
77
+ /** The conversation phren's OpenCode plugin says this process shows (it
78
+ * records it by PID on each prompt), when its transcript exists. Herdr's own
79
+ * OpenCode integration may be missing; this does not depend on it. */
80
+ export declare function opencodePidSession(pids: number[], root?: string): Promise<string | undefined>;
75
81
  /** Bind first-send permission to the actual terminal/process, never a cwd or
76
82
  * a guessed conversation. Tokens expire naturally when the Hook/process restarts. */
77
83
  export declare function paneChatState(server: string, pane: Json, options?: {
@@ -11,8 +11,14 @@ import { recordedSession } from "./agent-hook-stores.js";
11
11
  import { tabActivityKey } from "./tab-activity.js";
12
12
  import { intervalFromEnv } from "./limits.js";
13
13
  import { countHerdr, countIdentity } from "./metrics.js";
14
+ import { phrenStoreRoot } from "./transcripts.js";
15
+ // terminal.ts and terminal-tmux.ts import this module, so it reaches them at
16
+ // call time; a static import back would be an import cycle.
17
+ const terminal = () => import("./terminal.js");
14
18
  const exec = promisify(execFile);
15
19
  export function herdrRoot() { return process.env.PHREN_HERDR_HOME || path.join(homedir(), ".config/herdr"); }
20
+ /** Where Herdr's socket for `server` lives. */
21
+ export function herdrSocketPath(server) { return herdrSocket(server); }
16
22
  function herdrSocket(server) {
17
23
  serverName.parse(server);
18
24
  return path.join(herdrRoot(), ...(server === "default" ? [] : ["sessions", server]), "herdr.sock");
@@ -38,7 +44,9 @@ export function herdrSocketError(error) {
38
44
  : code === "EACCES" || code === "EPERM" ? "this user may not open Herdr's socket"
39
45
  : undefined;
40
46
  const tag = code && /^[A-Z0-9_]{1,32}$/.test(code) ? code : "unknown error";
41
- return new BridgeError(503, `Herdr is not reachable on this computer (${tag}${reason ? `: ${reason}` : ""}).`);
47
+ const offline = code === "ENOENT" ? "herdr-not-running" : code === "ECONNREFUSED" ? "herdr-stale-socket"
48
+ : code === "EACCES" || code === "EPERM" ? "herdr-permission" : "herdr-unreachable";
49
+ return new BridgeError(503, `Herdr is not reachable on this computer (${tag}${reason ? `: ${reason}` : ""}).`, { code: offline });
42
50
  }
43
51
  const optionalReadFailures = new Map();
44
52
  /**
@@ -60,7 +68,7 @@ export async function rpc(server, method, params = {}, signal, timeoutMs = 10_00
60
68
  countHerdr(method);
61
69
  const metadata = await stat(socket).catch(error => { throw herdrSocketError(error); });
62
70
  if (!metadata.isSocket() || (process.getuid && metadata.uid !== process.getuid()))
63
- throw new BridgeError(503, "The Herdr socket is unavailable.");
71
+ throw new BridgeError(503, "The Herdr socket is unavailable.", { code: "herdr-permission" });
64
72
  return new Promise((resolve, reject) => {
65
73
  const client = connect(socket);
66
74
  const key = requestID();
@@ -79,7 +87,7 @@ export async function rpc(server, method, params = {}, signal, timeoutMs = 10_00
79
87
  return;
80
88
  }
81
89
  signal?.addEventListener("abort", abort, { once: true });
82
- client.setTimeout(timeoutMs, () => finish(new BridgeError(504, "Herdr did not answer. Refresh before trying again.")));
90
+ client.setTimeout(timeoutMs, () => finish(new BridgeError(504, "Herdr did not answer. Refresh before trying again.", { code: "herdr-timeout" })));
83
91
  client.on("error", error => finish(herdrSocketError(error)));
84
92
  client.on("end", () => finish(new BridgeError(503, "Herdr closed the request before confirming it.")));
85
93
  client.on("connect", () => client.write(JSON.stringify({ id: key, method, params }) + "\n"));
@@ -139,7 +147,10 @@ export async function servers() {
139
147
  }
140
148
  }));
141
149
  const running = results.filter((v) => v !== null);
142
- knownServers = running.map(server => server.session);
150
+ // Without a running Herdr, tmux: the owner's server and the Hook's hidden one.
151
+ if (!running.length)
152
+ running.push(...await import("./terminal-tmux.js").then(tmux => tmux.tmuxServers()).catch(() => []));
153
+ knownServers = running.map(server => String(server.session));
143
154
  return running;
144
155
  }
145
156
  /** How old a shared `session.snapshot` may be for readers that poll: open
@@ -151,7 +162,7 @@ const inFlightSnapshots = new Map();
151
162
  /** A fresh snapshot. Its answer also becomes the shared one, so pollers reuse it. */
152
163
  export async function snapshot(server) {
153
164
  const started = Date.now();
154
- const value = object((await rpc(server, "session.snapshot")).snapshot);
165
+ const value = await (await terminal()).terminalProvider().snapshot(server);
155
166
  const current = sharedSnapshots.get(server);
156
167
  // A slower request that started before the current answer never replaces it.
157
168
  if (!current || current.at <= started) {
@@ -253,8 +264,7 @@ export function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChan
253
264
  /** Only file descriptors held by this pane's foreground processes establish identity.
254
265
  * A directory match, latest log, or focused tab must never select a conversation. */
255
266
  async function foregroundPids(server, pane) {
256
- const info = object((await rpc(server, "pane.process_info", { pane_id: pane.pane_id })).process_info);
257
- const pids = objects(info.foreground_processes).map(p => p.pid).filter((p) => Number.isSafeInteger(p) && Number(p) > 0).slice(0, 16);
267
+ const pids = (await (await terminal()).terminalProvider().processes(server, String(pane.pane_id))).foregroundPids.filter(p => Number.isSafeInteger(p) && p > 0).slice(0, 16);
258
268
  return pids.sort((a, b) => a - b);
259
269
  }
260
270
  async function processLogs(pids) {
@@ -295,7 +305,13 @@ async function resolveIdentity(server, pane, fresh) {
295
305
  const result = identityFromProcesses(server, pane, pids);
296
306
  if (identities.size >= 128)
297
307
  identities.delete(identities.keys().next().value);
298
- identities.set(key, { at: Date.now(), result });
308
+ const entry = { at: Date.now(), result };
309
+ // The evidence is as old as its answer, not its question: lsof on a busy
310
+ // Mac can outlast the cache window, and a probe stamped when it started
311
+ // would already be stale to paneChatState, which then never reports the
312
+ // brand-new conversation it just proved as starting.
313
+ void result.then(() => { entry.at = Date.now(); }, () => { });
314
+ identities.set(key, entry);
299
315
  return { sessionId: (await result).sessionId, pids };
300
316
  }
301
317
  export async function paneIdentity(server, pane, fresh = false) {
@@ -339,7 +355,45 @@ export async function copilotForegroundSession(pids, home = copilotHome()) {
339
355
  }
340
356
  return current;
341
357
  }
358
+ /** The conversation phren's OpenCode plugin says this process shows (it
359
+ * records it by PID on each prompt), when its transcript exists. Herdr's own
360
+ * OpenCode integration may be missing; this does not depend on it. */
361
+ export async function opencodePidSession(pids, root = phrenStoreRoot()) {
362
+ const folder = path.join(root, ".runtime", "sessions");
363
+ let current, latest = -Infinity;
364
+ for (const pid of pids) {
365
+ const file = await open(path.join(folder, `opencode-pid-${pid}.json`), "r").catch(() => undefined);
366
+ if (!file)
367
+ continue;
368
+ try {
369
+ const { size } = await file.stat();
370
+ if (size > 4_096)
371
+ continue;
372
+ const value = object(JSON.parse((await file.readFile()).toString("utf8")));
373
+ const session = typeof value.session === "string" && /^ses_[0-9A-Za-z]{1,64}$/.test(value.session) ? value.session : undefined;
374
+ const at = Date.parse(String(value.at));
375
+ if (!session || !(at > latest))
376
+ continue;
377
+ if (!(await stat(path.join(folder, `opencode-${session}.events.jsonl`)).catch(() => undefined)))
378
+ continue;
379
+ current = session;
380
+ latest = at;
381
+ }
382
+ catch {
383
+ continue;
384
+ }
385
+ finally {
386
+ await file.close();
387
+ }
388
+ }
389
+ return current;
390
+ }
342
391
  async function identityFromProcesses(server, pane, pids) {
392
+ if (pane.agent === "opencode") {
393
+ const bound = await opencodePidSession(pids).catch(() => undefined);
394
+ if (bound)
395
+ return { sessionId: bound, noTranscriptLogs: false };
396
+ }
343
397
  if (pane.agent === "copilot") {
344
398
  const current = await copilotForegroundSession(pids).catch(() => undefined);
345
399
  // A conversation nothing was sent to yet has no transcript: the pane is
@@ -239,6 +239,10 @@ export async function install(version, noService = false) {
239
239
  if (await applyOpencodePlugin()) {
240
240
  console.log("opencode chat: restart any opencode session started before now so it loads the transcript plugin.");
241
241
  }
242
+ // phren-agent calls the installed bundle itself, so it has no settings to edit.
243
+ if ((await import("../modules/agent-package.js")).agentInstalled()) {
244
+ console.log("phren-agent chat: found; it reports to this Hook itself, so restart any phren-agent session started before now.");
245
+ }
242
246
  const keys = path.join(homedir(), ".ssh/authorized_keys");
243
247
  const keyStat = await lstat(keys).catch(() => null);
244
248
  if (keyStat && !keyStat.isSymbolicLink() && keyStat.isFile()) {
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { visibleTerminalChoice } from "./agent-hooks.js";
3
- import { rpc, validateTarget } from "./herdr.js";
3
+ import { validateTarget } from "./herdr.js";
4
+ import { terminalProvider } from "./terminal.js";
4
5
  import { ModelCatalog } from "./models.js";
5
6
  import { BridgeError } from "./protocol.js";
6
7
  import { sideQuestionText } from "./side-questions.js";
@@ -130,7 +131,7 @@ export class ModelSwitcher {
130
131
  };
131
132
  const keys = async (values) => {
132
133
  await validate();
133
- await rpc(target.server, "agent.send_keys", { target: target.pane, keys: values });
134
+ await terminalProvider().sendKeys(target.server, target.pane, values);
134
135
  };
135
136
  const waitFor = async (read, step, ansi = false) => {
136
137
  const deadline = Date.now() + this.timeout;
@@ -172,7 +173,7 @@ export class ModelSwitcher {
172
173
  await validate(true);
173
174
  opened = true;
174
175
  this.hooks.menuOpened(target, "/model");
175
- await rpc(target.server, "agent.prompt", { target: target.pane, text: target.source === "codex" ? "/model" : `/model ${id}` });
176
+ await terminalProvider().prompt(target.server, target.pane, target.source === "codex" ? "/model" : `/model ${id}`);
176
177
  if (target.source === "codex") {
177
178
  let menu = await waitFor(text => {
178
179
  const choice = visibleTerminalChoice(text);
@@ -218,7 +219,7 @@ export class ModelSwitcher {
218
219
  // `/effort` after the model, so the new model's own default never
219
220
  // replaces the chosen level.
220
221
  await validate(true);
221
- await rpc(target.server, "agent.prompt", { target: target.pane, text: `/effort ${chosenEffort}` });
222
+ await terminalProvider().prompt(target.server, target.pane, `/effort ${chosenEffort}`);
222
223
  const reply = await waitFor(text => claudeEffortReply(text), "Claude's effort confirmation");
223
224
  if ("error" in reply)
224
225
  throw new BridgeError(409, reply.error);
@@ -176,7 +176,7 @@ function claudeVersion(executable = "claude") {
176
176
  child.stdout.on("data", (chunk) => { if (out.length < 4_096)
177
177
  out += chunk; });
178
178
  child.on("error", () => { clearTimeout(timer); resolve(undefined); });
179
- child.on("exit", () => { clearTimeout(timer); resolve(/\d+\.\d+\.\d+/.exec(out)?.[0]); });
179
+ child.on("close", () => { clearTimeout(timer); resolve(/\d+\.\d+\.\d+/.exec(out)?.[0]); });
180
180
  });
181
181
  }
182
182
  /** The live catalogue when Claude Code has one cached on this computer,
@@ -202,8 +202,9 @@ export async function readOpenCodeModels(executable = "opencode", configDir = pa
202
202
  child.stdout.setEncoding("utf8");
203
203
  child.stdout.on("data", (chunk) => { if (out.length < 262_144)
204
204
  out += chunk; });
205
+ // "close", not "exit": the process can exit before its stdout is read.
205
206
  child.on("error", finish);
206
- child.on("exit", finish);
207
+ child.on("close", finish);
207
208
  });
208
209
  const ids = [...new Set(listed.split(/\r?\n/).map(line => line.trim()).filter(line => /^[a-z0-9~.-]+\/[^\s]+$/i.test(line)))].slice(0, 400);
209
210
  if (!ids.length)
@@ -0,0 +1,37 @@
1
+ /** The status a lifecycle event leaves the agent in; undefined for events that say nothing about it. */
2
+ export declare function eventStatus(event: unknown): string | undefined;
3
+ /** Records the status of the agent in `pane`, which runs in terminal instance
4
+ * `terminal`, and answers it with its sequence number. */
5
+ export declare function notePaneStatus(server: string, pane: string, terminal: string, status: string, at?: number): {
6
+ status: string;
7
+ seq: number;
8
+ };
9
+ /** A blocked pane whose dialog is gone was answered in the terminal: the
10
+ * agent went back to work. Only after `minimumMs`, so a request whose
11
+ * dialog is still being drawn is not settled early. */
12
+ export declare function settleBlockedPane(server: string, pane: string, minimumMs?: number): void;
13
+ /** The pane's last known status while `terminal` still runs there: from
14
+ * memory, else from the binding file the last lifecycle event wrote. */
15
+ export declare function paneStatus(server: string, pane: string, terminal: string): Promise<{
16
+ status: string;
17
+ seq: number;
18
+ } | undefined>;
19
+ /** Whether `screen` (a pane's visible lines, with or without colors) shows a
20
+ * dialog waiting for `agent`'s owner. Stricter than the readers that answer
21
+ * a dialog, because it runs while the agent is still writing: Claude's and
22
+ * phren-agent's numbered rows count only with their "Esc to cancel" footer,
23
+ * OpenCode's only as its own permission prompt. */
24
+ export declare function screenDialog(agent: string, screen: string): boolean;
25
+ /** The status of a pane after a look at its screen: blocked while a working
26
+ * agent shows a dialog there (`screenDialog`), else `base` unchanged. `read`
27
+ * answers the pane's visible lines; it runs only for a working pane, at most
28
+ * once per DIALOG_READ_MS per pane. */
29
+ export declare function dialogStatus(server: string, pane: string, terminal: string, agent: string, base: {
30
+ status: string;
31
+ seq: number;
32
+ } | undefined, read: () => Promise<string>): Promise<{
33
+ status: string;
34
+ seq: number;
35
+ } | undefined>;
36
+ /** For tests. */
37
+ export declare function resetPaneStatus(): void;
@@ -0,0 +1,139 @@
1
+ // Agent status for panes whose terminal does not report one (tmux). Herdr
2
+ // watches its agents and says "working", "idle" or "blocked"; tmux knows only
3
+ // processes. Claude, Codex and phren-agent tell the Hook themselves through
4
+ // their lifecycle hooks (agent-hooks.ts), so the last event a pane's agent
5
+ // sent is its status: a submitted prompt or a tool call means working, a
6
+ // finished turn or a fresh session idle, a permission request blocked. The
7
+ // event is also kept in the pane's binding file, so a restarted Hook does not
8
+ // forget a pane's status. OpenCode and Copilot say it elsewhere
9
+ // (harness-status.ts); the snapshot notes what they say here, so every change
10
+ // gets a sequence number too.
11
+ //
12
+ // A harness that draws a permission dialog in its terminal with no hook
13
+ // behind it (Codex, OpenCode, Copilot, Claude's auto-mode fallback) still
14
+ // looks "working" to all of that. While a pane is working its screen is read,
15
+ // at most once per DIALOG_READ_MS, and a dialog there makes the pane blocked
16
+ // until the dialog is gone.
17
+ import { readFile } from "node:fs/promises";
18
+ import { stripTerminal } from "../terminal-text.js";
19
+ import { bindingPath } from "./agent-hook-stores.js";
20
+ import { claudeQuestionDialog } from "./claude-question-dialog.js";
21
+ import { intervalFromEnv } from "./limits.js";
22
+ import { object } from "./protocol.js";
23
+ import { numberedDialog, opencodePermissionDialog, visibleTerminalChoice } from "./terminal-choice.js";
24
+ /** A working pane's screen is read for a dialog at most once per this window. */
25
+ const DIALOG_READ_MS = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3_000);
26
+ const EVENT_STATUS = {
27
+ SessionStart: "idle", UserPromptSubmit: "working", PreToolUse: "working", PostToolUse: "working",
28
+ PreCompact: "working", Stop: "idle", PermissionRequest: "blocked",
29
+ };
30
+ /** The status a lifecycle event leaves the agent in; undefined for events that say nothing about it. */
31
+ export function eventStatus(event) {
32
+ return typeof event === "string" && Object.hasOwn(EVENT_STATUS, event) ? EVENT_STATUS[event] : undefined;
33
+ }
34
+ const entries = new Map();
35
+ /** Climbs with every change, like Herdr's state_change_seq, so the phone can order "just finished" first. */
36
+ let sequence = 0;
37
+ const key = (server, pane) => `${server}\0${pane}`;
38
+ /** Records the status of the agent in `pane`, which runs in terminal instance
39
+ * `terminal`, and answers it with its sequence number. */
40
+ export function notePaneStatus(server, pane, terminal, status, at = Date.now()) {
41
+ const id = key(server, pane), current = entries.get(id);
42
+ if (current && current.terminal === terminal && current.status === status) {
43
+ current.at = at;
44
+ return { status, seq: current.seq };
45
+ }
46
+ entries.delete(id);
47
+ while (entries.size >= 512)
48
+ entries.delete(entries.keys().next().value);
49
+ const entry = { terminal, status, seq: ++sequence, at };
50
+ entries.set(id, entry);
51
+ return { status, seq: entry.seq };
52
+ }
53
+ /** A blocked pane whose dialog is gone was answered in the terminal: the
54
+ * agent went back to work. Only after `minimumMs`, so a request whose
55
+ * dialog is still being drawn is not settled early. */
56
+ export function settleBlockedPane(server, pane, minimumMs = 3_000) {
57
+ const id = key(server, pane), current = entries.get(id), dialog = dialogs.get(id);
58
+ if (current?.status === "blocked" && Date.now() - current.at >= minimumMs)
59
+ notePaneStatus(server, pane, current.terminal, "working");
60
+ if (dialog?.shown && Date.now() - dialog.shown.at >= minimumMs) {
61
+ // The screen can show the answered dialog a moment longer: the next read
62
+ // waits a whole window.
63
+ dialog.shown = undefined;
64
+ dialog.cleared = ++sequence;
65
+ dialog.readAt = Date.now();
66
+ }
67
+ }
68
+ /** The pane's last known status while `terminal` still runs there: from
69
+ * memory, else from the binding file the last lifecycle event wrote. */
70
+ export async function paneStatus(server, pane, terminal) {
71
+ const current = entries.get(key(server, pane));
72
+ if (current && current.terminal === terminal)
73
+ return { status: current.status, seq: current.seq };
74
+ if (current)
75
+ return undefined;
76
+ try {
77
+ const value = object(JSON.parse(await readFile(bindingPath(server, pane), "utf8")));
78
+ const status = eventStatus(value.event);
79
+ if (value.terminal !== terminal || !status)
80
+ return undefined;
81
+ const at = Date.parse(String(value.at));
82
+ return notePaneStatus(server, pane, terminal, status, Number.isFinite(at) ? at : Date.now());
83
+ }
84
+ catch {
85
+ return undefined;
86
+ }
87
+ }
88
+ /** Whether `screen` (a pane's visible lines, with or without colors) shows a
89
+ * dialog waiting for `agent`'s owner. Stricter than the readers that answer
90
+ * a dialog, because it runs while the agent is still writing: Claude's and
91
+ * phren-agent's numbered rows count only with their "Esc to cancel" footer,
92
+ * OpenCode's only as its own permission prompt. */
93
+ export function screenDialog(agent, screen) {
94
+ const text = stripTerminal(screen);
95
+ if (agent === "opencode")
96
+ return !!opencodePermissionDialog(screen);
97
+ if (agent === "codex" || agent === "copilot")
98
+ return !!visibleTerminalChoice(text);
99
+ if (agent === "claude" && claudeQuestionDialog(text))
100
+ return true;
101
+ return /Esc to cancel/i.test(text) && !!numberedDialog(text);
102
+ }
103
+ const dialogs = new Map();
104
+ /** The status of a pane after a look at its screen: blocked while a working
105
+ * agent shows a dialog there (`screenDialog`), else `base` unchanged. `read`
106
+ * answers the pane's visible lines; it runs only for a working pane, at most
107
+ * once per DIALOG_READ_MS per pane. */
108
+ export async function dialogStatus(server, pane, terminal, agent, base, read) {
109
+ const id = key(server, pane);
110
+ if (base?.status !== "working") {
111
+ dialogs.delete(id);
112
+ return base;
113
+ }
114
+ let entry = dialogs.get(id);
115
+ if (!entry || entry.terminal !== terminal) {
116
+ entry = { terminal, readAt: 0 };
117
+ dialogs.delete(id);
118
+ while (dialogs.size >= 512)
119
+ dialogs.delete(dialogs.keys().next().value);
120
+ dialogs.set(id, entry);
121
+ }
122
+ const now = Date.now();
123
+ if (now - entry.readAt >= DIALOG_READ_MS) {
124
+ entry.readAt = now;
125
+ // A failed read says nothing: the pane keeps what it had.
126
+ const shown = await read().then(screen => screenDialog(agent, screen), () => undefined);
127
+ if (shown === true && !entry.shown)
128
+ entry.shown = { at: now, seq: ++sequence };
129
+ else if (shown === false && entry.shown) {
130
+ entry.shown = undefined;
131
+ entry.cleared = ++sequence;
132
+ }
133
+ }
134
+ if (entry.shown)
135
+ return { status: "blocked", seq: entry.shown.seq };
136
+ return { status: base.status, seq: Math.max(base.seq, entry.cleared ?? 0) };
137
+ }
138
+ /** For tests. */
139
+ export function resetPaneStatus() { entries.clear(); dialogs.clear(); }
@@ -1,15 +1,7 @@
1
- export interface PaneTextRequest {
2
- /** `agent.read` addresses the pane's agent; `pane.read` reads any pane,
3
- * including one whose agent is still starting. */
4
- method: "agent.read" | "pane.read";
5
- source: "visible" | "recent";
6
- lines: number;
7
- stripAnsi?: boolean;
8
- /** Herdr 0.9 answers plain text whatever `strip_ansi` says; "ansi" keeps the styles. */
9
- format?: "ansi";
10
- timeoutMs?: number;
1
+ import { type ScreenRead } from "./terminal.js";
2
+ export interface PaneTextRequest extends ScreenRead {
11
3
  /** Names the read in the once-per-target warning; without it a failure is silent. */
12
4
  what?: string;
13
5
  }
14
- /** What a pane draws, or "" when Herdr cannot say: callers treat the text as optional. */
6
+ /** What a pane draws, or "" when the terminal cannot say. */
15
7
  export declare function readPaneText(server: string, pane: string, request: PaneTextRequest): Promise<string>;
@@ -1,23 +1,16 @@
1
- // The one reader of pane text. It sits beside herdr.ts rather than inside it so
2
- // it calls Herdr through herdr.ts's exported rpc, the seam the bridge tests fake.
3
- import { noteOptionalReadFailure, rpc } from "./herdr.js";
4
- import { object } from "./protocol.js";
5
- /** `pane.read` and `agent.read` both answer with a `read` object carrying the text. */
6
- function readText(result) {
7
- const read = object(result.read ?? result);
8
- return typeof read.text === "string" ? read.text : "";
9
- }
10
- /** What a pane draws, or "" when Herdr cannot say: callers treat the text as optional. */
1
+ // The one reader of pane text. It reads through the terminal provider and
2
+ // turns a failure into "": every caller treats the text as optional.
3
+ import { noteOptionalReadFailure } from "./herdr.js";
4
+ import { terminalProvider } from "./terminal.js";
5
+ /** What a pane draws, or "" when the terminal cannot say. */
11
6
  export async function readPaneText(server, pane, request) {
12
- const params = { ...(request.method === "agent.read" ? { target: pane } : { pane_id: pane }),
13
- source: request.source, lines: request.lines, strip_ansi: request.stripAnsi ?? true,
14
- ...(request.format ? { format: request.format } : {}) };
7
+ const { what, ...read } = request;
15
8
  try {
16
- return readText(await rpc(server, request.method, params, undefined, request.timeoutMs));
9
+ return await terminalProvider().readScreen(server, pane, read);
17
10
  }
18
11
  catch (error) {
19
- if (request.what)
20
- noteOptionalReadFailure(request.what, `${server}/${pane}`, error);
12
+ if (what)
13
+ noteOptionalReadFailure(what, `${server}/${pane}`, error);
21
14
  return "";
22
15
  }
23
16
  }
@@ -7,7 +7,7 @@ import { z } from "zod";
7
7
  import { logger } from "../logger.js";
8
8
  import { hookRequest } from "./client.js";
9
9
  import { computerName, dispatchKeyPath, publicComputerKey } from "./computers.js";
10
- import { atomic, BridgeError, bridgeRoot, serverName } from "./protocol.js";
10
+ import { atomic, BridgeError, bridgeRoot, serverName, withErrorCode } from "./protocol.js";
11
11
  const peerSchema = z.object({
12
12
  name: computerName,
13
13
  address: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9.:-]{0,252}$/),
@@ -105,7 +105,7 @@ export async function peerRequest(peer, route, data, timeout) {
105
105
  const root = bridgeRoot(), key = dispatchKeyPath(root);
106
106
  const info = await lstat(key).catch(() => undefined);
107
107
  if (!info?.isFile() || info.isSymbolicLink() || (info.mode & 0o077))
108
- throw new BridgeError(409, "Run phren bridge enroll-computer on this computer first (private key mode 0600).");
108
+ throw new BridgeError(409, "Run phren bridge enroll-computer on this computer first (private key mode 0600).", { code: "dispatch-key-missing" });
109
109
  const temporary = await mkdtemp(path.join(root, "peer-"));
110
110
  let child, stream;
111
111
  try {
@@ -127,7 +127,7 @@ export async function peerRequest(peer, route, data, timeout) {
127
127
  let diagnostic = "";
128
128
  child.stderr.on("data", bytes => { diagnostic = (diagnostic + bytes.toString()).slice(-4096); });
129
129
  const exited = new Promise(resolve => ssh.once("exit", code => resolve(code)));
130
- child.on("error", error => stream?.destroy(new BridgeError(503, `SSH is unavailable (${error.code ?? "spawn failed"}).`)));
130
+ child.on("error", error => stream?.destroy(new BridgeError(503, `SSH is unavailable (${error.code ?? "spawn failed"}).`, { code: "ssh-unavailable" })));
131
131
  try {
132
132
  return await hookRequest(route, data, { createConnection: () => stream }, timeout ?? (data === undefined ? 15_000 : 65_000));
133
133
  }
@@ -136,12 +136,15 @@ export async function peerRequest(peer, route, data, timeout) {
136
136
  // ssh's stderr and exit status usually land just after the stream ends.
137
137
  const exitCode = await Promise.race([exited, new Promise(resolve => { setTimeout(() => resolve(undefined), 250).unref(); })]);
138
138
  if (!/Permission denied|Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(diagnostic))
139
- throw new BridgeError(503, peerOfflineMessage(diagnostic, exitCode));
139
+ throw new BridgeError(503, peerOfflineMessage(diagnostic, exitCode), { code: "peer-offline" });
140
140
  }
141
141
  if (/Permission denied/i.test(diagnostic))
142
- throw new BridgeError(403, "The remote computer has not enrolled this dispatch key.");
142
+ throw new BridgeError(403, "The remote computer has not enrolled this dispatch key.", { code: "peer-key-not-enrolled" });
143
143
  if (/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(diagnostic))
144
- throw new BridgeError(403, "The remote SSH host key does not match its pin.");
144
+ throw new BridgeError(403, "The remote SSH host key does not match its pin.", { code: "peer-host-key-mismatch" });
145
+ // Our own wait ran out (client.ts); a remote Hook's own 504 keeps its code.
146
+ if (error instanceof BridgeError && error.status === 504 && error.message.startsWith("Hook did not confirm"))
147
+ throw withErrorCode(error, "peer-timeout");
145
148
  throw error;
146
149
  }
147
150
  }
@@ -0,0 +1,26 @@
1
+ import { z } from "zod";
2
+ import { type Json } from "./protocol.js";
3
+ /** The phone's own name for one message it composed, kept on every attempt to
4
+ * send it. Optional: a client that sends none gets the old, single-attempt behavior. */
5
+ export declare const deliveryIdSchema: z.ZodOptional<z.ZodString>;
6
+ /** Types one phone message at most once per delivery id. A dropped
7
+ * connection (the phone left the app, SSH closed before the reply) made the
8
+ * phone offer Retry for a prompt the Hook had already typed, and the retry
9
+ * typed it a second time. The same id again, for the same pane and text:
10
+ * - while the first attempt runs, waits for it and answers with its reply;
11
+ * - after it typed anything, answers with the first reply (or its error),
12
+ * marked `replayed`, and types nothing;
13
+ * - after it failed before typing (a stale target, a busy agent), runs again.
14
+ * The same id for another pane or other text is refused. */
15
+ export declare class PromptOnce {
16
+ private now;
17
+ private attempts;
18
+ constructor(now?: () => number);
19
+ run(id: string | undefined, scope: string, send: (typing: () => void) => Promise<Json>): Promise<Json>;
20
+ private prune;
21
+ }
22
+ /** What a delivery id is bound to: the pane, its agent and the exact text.
23
+ * Not the conversation: a first message that started one is retried against
24
+ * the new conversation's target and must still find its first attempt.
25
+ * Hashed so the table never holds the prompt. */
26
+ export declare function promptScope(target: Json, text: string): string;