@phren/cli 0.3.4 → 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 (69) 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.js +2 -1
  61. package/dist/init/init.js +4 -0
  62. package/dist/link/doctor.js +33 -30
  63. package/dist/modules/agent-package.d.ts +35 -0
  64. package/dist/modules/agent-package.js +133 -0
  65. package/dist/modules/registry.js +2 -2
  66. package/dist/session/utils.js +1 -1
  67. package/dist/tools/dispatch.js +2 -2
  68. package/package.json +1 -1
  69. package/plugins/opencode/phren-transcript.js +97 -6
@@ -0,0 +1,69 @@
1
+ import { createHash } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { BridgeError } from "./protocol.js";
4
+ /** The phone's own name for one message it composed, kept on every attempt to
5
+ * send it. Optional: a client that sends none gets the old, single-attempt behavior. */
6
+ export const deliveryIdSchema = z.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional();
7
+ const REMEMBER_MS = 600_000, MAX_ATTEMPTS = 512;
8
+ /** Types one phone message at most once per delivery id. A dropped
9
+ * connection (the phone left the app, SSH closed before the reply) made the
10
+ * phone offer Retry for a prompt the Hook had already typed, and the retry
11
+ * typed it a second time. The same id again, for the same pane and text:
12
+ * - while the first attempt runs, waits for it and answers with its reply;
13
+ * - after it typed anything, answers with the first reply (or its error),
14
+ * marked `replayed`, and types nothing;
15
+ * - after it failed before typing (a stale target, a busy agent), runs again.
16
+ * The same id for another pane or other text is refused. */
17
+ export class PromptOnce {
18
+ now;
19
+ attempts = new Map();
20
+ constructor(now = Date.now) {
21
+ this.now = now;
22
+ }
23
+ async run(id, scope, send) {
24
+ if (!id)
25
+ return send(() => { });
26
+ this.prune();
27
+ for (let prior = this.attempts.get(id); prior; prior = this.attempts.get(id)) {
28
+ if (prior.scope !== scope)
29
+ throw new BridgeError(409, "This message id was already used for a different message.");
30
+ const outcome = await prior.done;
31
+ // One that failed before typing was removed; look again (nothing, or a newer attempt).
32
+ if ("error" in outcome && !prior.typed)
33
+ continue;
34
+ if ("error" in outcome)
35
+ throw outcome.error;
36
+ return { ...outcome.result, replayed: true };
37
+ }
38
+ let finish;
39
+ const attempt = { scope, typed: false, done: new Promise(resolve => { finish = resolve; }), at: this.now() };
40
+ this.attempts.set(id, attempt);
41
+ try {
42
+ const result = await send(() => { attempt.typed = true; });
43
+ finish({ result });
44
+ return result;
45
+ }
46
+ catch (error) {
47
+ if (!attempt.typed && this.attempts.get(id) === attempt)
48
+ this.attempts.delete(id);
49
+ finish({ error });
50
+ throw error;
51
+ }
52
+ }
53
+ prune() {
54
+ const cutoff = this.now() - REMEMBER_MS;
55
+ for (const [id, attempt] of this.attempts)
56
+ if (attempt.at < cutoff)
57
+ this.attempts.delete(id);
58
+ while (this.attempts.size >= MAX_ATTEMPTS)
59
+ this.attempts.delete(this.attempts.keys().next().value);
60
+ }
61
+ }
62
+ /** What a delivery id is bound to: the pane, its agent and the exact text.
63
+ * Not the conversation: a first message that started one is retried against
64
+ * the new conversation's target and must still find its first attempt.
65
+ * Hashed so the table never holds the prompt. */
66
+ export function promptScope(target, text) {
67
+ const { server, workspace, tab, pane, source } = target;
68
+ return createHash("sha256").update(JSON.stringify([server, workspace, tab, pane, source, text])).digest("hex");
69
+ }
@@ -55,6 +55,16 @@ export declare class BridgeError extends Error {
55
55
  details?: Json | undefined;
56
56
  constructor(status: number, message: string, details?: Json | undefined);
57
57
  }
58
+ /**
59
+ * Why a computer's Herdr or a linked peer could not be reached, as a stable
60
+ * `code` beside the human `error` text, so a client can explain the offline
61
+ * state without matching sentences. See docs/phren-hook.md#offline-reasons.
62
+ */
63
+ export type OfflineCode = "herdr-not-running" | "herdr-stale-socket" | "herdr-permission" | "herdr-unreachable" | "herdr-timeout" | "ssh-unavailable" | "dispatch-key-missing" | "peer-offline" | "peer-timeout" | "peer-key-not-enrolled" | "peer-host-key-mismatch";
64
+ /** The machine-readable `code` an error carries, if any. */
65
+ export declare function errorCode(error: unknown): string | undefined;
66
+ /** A BridgeError that keeps `error`'s status and text and adds `code` when it has none yet. */
67
+ export declare function withErrorCode(error: BridgeError, code: OfflineCode): BridgeError;
58
68
  export declare const requestID: () => `${string}-${string}-${string}-${string}-${string}`;
59
69
  /**
60
70
  * Write a file atomically: serialize to a fresh temp name, then rename it over
@@ -41,6 +41,16 @@ export class BridgeError extends Error {
41
41
  this.details = details;
42
42
  }
43
43
  }
44
+ const ERROR_CODE = /^[a-z][a-z0-9-]{0,39}$/;
45
+ /** The machine-readable `code` an error carries, if any. */
46
+ export function errorCode(error) {
47
+ const code = error instanceof BridgeError ? error.details?.code : undefined;
48
+ return typeof code === "string" && ERROR_CODE.test(code) ? code : undefined;
49
+ }
50
+ /** A BridgeError that keeps `error`'s status and text and adds `code` when it has none yet. */
51
+ export function withErrorCode(error, code) {
52
+ return errorCode(error) ? error : new BridgeError(error.status, error.message, { ...(error.details ?? {}), code });
53
+ }
44
54
  export const requestID = () => randomUUID();
45
55
  /**
46
56
  * Write a file atomically: serialize to a fresh temp name, then rename it over
@@ -72,6 +72,8 @@ export interface ScheduleLaunchContext {
72
72
  }
73
73
  export type ScheduleLauncher = ((context: ScheduleLaunchContext) => Promise<ScheduleLaunchResult>) & {
74
74
  close?: () => void;
75
+ /** Follows a run a previous Hook process launched and never saw finish. */
76
+ resume?: (run: ScheduleRun, schedule: Schedule) => Promise<ScheduleRunOutcome>;
75
77
  };
76
78
  export interface SchedulePushSender {
77
79
  notify(value: SchedulePush): Promise<SchedulePushResult>;
@@ -1,7 +1,16 @@
1
1
  import { type Json } from "./protocol.js";
2
- import type { Schedule, ScheduleLauncher } from "./schedule-format.js";
2
+ import type { Schedule, ScheduleLauncher, ScheduleRun, ScheduleRunOutcome } from "./schedule-format.js";
3
+ import { watchHerdrRun } from "./schedule-watch.js";
3
4
  type HerdrLauncher = (server: string, data: Json) => Promise<Json>;
4
5
  export declare function createScheduleLauncher(launchHerdr: HerdrLauncher, store?: string): ScheduleLauncher;
6
+ /**
7
+ * The outcome of a run a previous Hook process launched and never saw finish
8
+ * (a restart or crash mid-run). A Herdr pane is followed again to its real
9
+ * end; a headless job's manifest says how it ended, if it got that far. A run
10
+ * whose end cannot be known fails with that reason rather than staying open,
11
+ * since an open run blocks its schedule for good.
12
+ */
13
+ export declare function resumeScheduleRun(run: ScheduleRun, schedule: Schedule, signal: AbortSignal, watch?: typeof watchHerdrRun): Promise<ScheduleRunOutcome>;
5
14
  export declare function headlessCommand(schedule: Schedule, cwd: string): {
6
15
  file: string;
7
16
  args: string[];
@@ -5,7 +5,8 @@ import { codexHome } from "../home-paths.js";
5
5
  import path from "node:path";
6
6
  import { finished as streamFinished } from "node:stream/promises";
7
7
  import { fanoutRoot } from "./fanouts.js";
8
- import { findPane, paneIdentity, rpc, servers, snapshot } from "./herdr.js";
8
+ import { findPane, paneIdentity, servers, snapshot } from "./herdr.js";
9
+ import { agentNotReady, terminalProvider } from "./terminal.js";
9
10
  import { atomic, atomicInPrivateDir, BridgeError } from "./protocol.js";
10
11
  import { logger } from "../logger.js";
11
12
  import { defaultPhrenPath } from "../shared.js";
@@ -23,8 +24,33 @@ export function createScheduleLauncher(launchHerdr, store = defaultPhrenPath())
23
24
  };
24
25
  launcher.close = () => { abort.abort(); for (const child of children)
25
26
  child.kill("SIGTERM"); children.clear(); };
27
+ launcher.resume = (run, schedule) => resumeScheduleRun(run, schedule, abort.signal);
26
28
  return launcher;
27
29
  }
30
+ /**
31
+ * The outcome of a run a previous Hook process launched and never saw finish
32
+ * (a restart or crash mid-run). A Herdr pane is followed again to its real
33
+ * end; a headless job's manifest says how it ended, if it got that far. A run
34
+ * whose end cannot be known fails with that reason rather than staying open,
35
+ * since an open run blocks its schedule for good.
36
+ */
37
+ export async function resumeScheduleRun(run, schedule, signal, watch = watchHerdrRun) {
38
+ const launch = run.launch;
39
+ if (run.status === "launched")
40
+ return { status: "failed", reason: "Phren Hook restarted before this run finished launching." };
41
+ if (launch.mode === "herdr" && launch.server && launch.workspaceId && launch.tabId && launch.paneId) {
42
+ return watch(launch.server, { workspaceId: launch.workspaceId, tabId: launch.tabId, paneId: launch.paneId }, signal, { source: schedule.harness, startedAt: Date.parse(run.startedAt), sessionId: launch.sessionId });
43
+ }
44
+ if (launch.mode === "headless" && launch.jobDir) {
45
+ const manifest = await readFile(path.join(launch.jobDir, "manifest.json"), "utf8").then(text => JSON.parse(text)).catch(() => undefined);
46
+ if (manifest?.status === "completed")
47
+ return { status: "finished" };
48
+ if (manifest?.status === "failed") {
49
+ return { status: "failed", reason: typeof manifest.exitCode === "number" ? `The scheduled agent exited with code ${manifest.exitCode}.` : "The scheduled agent failed." };
50
+ }
51
+ }
52
+ return { status: "failed", reason: "Phren Hook restarted while this run was going, so its end was not observed." };
53
+ }
28
54
  async function launchInHerdr(server, context, launchHerdr, signal) {
29
55
  const launched = await launchHerdr(server, { cwd: context.cwd, label: context.schedule.name, kind: context.schedule.harness, model: context.schedule.model });
30
56
  const workspaceId = String(launched.workspaceId), tabId = String(launched.tabId), paneId = String(launched.paneId);
@@ -47,11 +73,11 @@ async function promptWhenReady(server, paneId, text, signal, waitMs = 60_000) {
47
73
  const deadline = Date.now() + waitMs;
48
74
  for (;;) {
49
75
  try {
50
- await rpc(server, "agent.prompt", { target: paneId, text }, signal);
76
+ await terminalProvider().prompt(server, paneId, text, signal);
51
77
  return;
52
78
  }
53
79
  catch (error) {
54
- const starting = error instanceof BridgeError && error.details?.herdrCode === "agent_not_ready";
80
+ const starting = agentNotReady(error);
55
81
  if (!starting || signal.aborted)
56
82
  throw error;
57
83
  if (Date.now() >= deadline)
@@ -27,7 +27,7 @@ export function classifyStartupBlock(input) {
27
27
  return text.slice(0, 4000);
28
28
  }
29
29
  async function paneRecentLines(server, paneId) {
30
- const text = await readPaneText(server, paneId, { method: "pane.read", source: "recent", lines: 40, what: "Scheduled run pane read" });
30
+ const text = await readPaneText(server, paneId, { scope: "pane", source: "recent", lines: 40, what: "Scheduled run pane read" });
31
31
  return text ? text.split(/\r?\n/) : [];
32
32
  }
33
33
  /** The watch loop's own words for a failure, instead of assuming Herdr went away. */
@@ -13,6 +13,9 @@ export declare class Scheduler {
13
13
  private readonly log;
14
14
  private serial;
15
15
  private ticking;
16
+ /** Runs this process launched; any other open run was left by an earlier Hook. */
17
+ private readonly own;
18
+ private recovered;
16
19
  /** When the scheduler last looked for due work; a health read shows it. */
17
20
  lastTickAt?: Date;
18
21
  constructor(options: {
@@ -43,6 +46,13 @@ export declare class Scheduler {
43
46
  private finishRun;
44
47
  private recordBlockedStartup;
45
48
  private notifyRun;
49
+ /**
50
+ * Settles the runs an earlier Hook process left open (a restart or crash
51
+ * mid-run). Each is followed to its real end where the launcher can, and
52
+ * otherwise failed with the reason, since an open run blocks its schedule
53
+ * for good. Runs once, on the first tick, with a launcher that can resume.
54
+ */
55
+ recoverOpenRuns(): Promise<void>;
46
56
  tick(): Promise<void>;
47
57
  close(): void;
48
58
  }
@@ -19,6 +19,9 @@ export class Scheduler {
19
19
  log;
20
20
  serial = Promise.resolve();
21
21
  ticking = false;
22
+ /** Runs this process launched; any other open run was left by an earlier Hook. */
23
+ own = new Set();
24
+ recovered = false;
22
25
  /** When the scheduler last looked for due work; a health read shows it. */
23
26
  lastTickAt;
24
27
  constructor(options) {
@@ -97,6 +100,7 @@ export class Scheduler {
97
100
  throw new BridgeError(409, `Schedule "${schedule.name}" is already running.`);
98
101
  }
99
102
  const run = { id: randomUUID(), scheduleId: id, project, startedAt: this.now().toISOString(), status: "launched", launch: { mode: "headless" } };
103
+ this.own.add(run.id);
100
104
  await writeScheduleRuns(this.runsFile, [...runs, run]);
101
105
  if (schedule.every === "once" && schedule.enabled) {
102
106
  const updatedAt = this.now().toISOString();
@@ -184,12 +188,48 @@ export class Scheduler {
184
188
  this.log(`[schedule] ${kind} notification for run ${run.id}: ${result.reason ?? "not delivered"}`);
185
189
  return result.notified;
186
190
  }
191
+ /**
192
+ * Settles the runs an earlier Hook process left open (a restart or crash
193
+ * mid-run). Each is followed to its real end where the launcher can, and
194
+ * otherwise failed with the reason, since an open run blocks its schedule
195
+ * for good. Runs once, on the first tick, with a launcher that can resume.
196
+ */
197
+ async recoverOpenRuns() {
198
+ const resume = this.launch.resume;
199
+ if (this.recovered || !resume)
200
+ return;
201
+ this.recovered = true;
202
+ const open = (await readScheduleRuns(this.runsFile)).filter(run => runningStatuses.has(run.status) && !this.own.has(run.id));
203
+ for (const run of open) {
204
+ this.own.add(run.id);
205
+ let schedule;
206
+ try {
207
+ schedule = (await readScheduleDocument(this.projectDirectory(run.project))).schedules.find(item => item.id === run.scheduleId);
208
+ }
209
+ catch {
210
+ schedule = undefined;
211
+ }
212
+ if (!schedule) {
213
+ await this.updateRun(run.id, { status: "failed", finishedAt: this.now().toISOString(),
214
+ reason: "Phren Hook restarted during this run, and its schedule no longer exists." })
215
+ .catch(error => this.log(`[schedule] Could not close run ${run.id}: ${String(error)}`));
216
+ continue;
217
+ }
218
+ const known = schedule;
219
+ this.log(`[schedule] Following run ${run.id} of "${known.name}", left ${run.status} by an earlier Hook process.`);
220
+ void resume(run, known)
221
+ .catch((error) => ({ status: "failed", reason: error instanceof Error ? error.message : "The scheduled agent failed." }))
222
+ .then(result => this.finishRun(run.id, known, result.status, result.reason))
223
+ .catch(error => this.log(`[schedule] Could not finish run ${run.id}: ${String(error)}`));
224
+ }
225
+ }
187
226
  async tick() {
188
227
  if (this.ticking)
189
228
  return;
190
229
  this.ticking = true;
191
230
  this.lastTickAt = this.now();
192
231
  try {
232
+ await this.recoverOpenRuns().catch(error => this.log(`[schedule] Recovering open runs failed: ${String(error)}`));
193
233
  const status = await this.statuses(), now = this.now();
194
234
  for (const schedule of status.schedules) {
195
235
  if (!schedule.enabled || schedule.running || !schedule.nextRun || new Date(schedule.nextRun) > now)
@@ -3,7 +3,8 @@ import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { z } from "zod";
5
5
  import { homeDir } from "../home-paths.js";
6
- import { agentNames, findPane, isConductorName, paneAgentName, paneChatState, paneIdentity, rpc, servers, snapshot } from "./herdr.js";
6
+ import { agentNames, findPane, isConductorName, paneAgentName, paneChatState, paneIdentity, servers, snapshot } from "./herdr.js";
7
+ import { agentNotReady, terminalName, terminalProvider } from "./terminal.js";
7
8
  import { createLaunchWorktree, launchWorktreeSchema } from "./launch-worktree.js";
8
9
  import { groupConductor } from "./conductor-group.js";
9
10
  import { optionalHookPeers } from "./peers.js";
@@ -164,7 +165,7 @@ export async function launchSession(server, data, options = {}) {
164
165
  const worktree = worktreeRequest ? await createLaunchWorktree(projectDirectory, worktreeRequest) : undefined;
165
166
  const cwd = worktree?.cwd ?? projectDirectory;
166
167
  try {
167
- await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label, cwd, focus: false, env: {} });
168
+ await terminalProvider().create(server, { workspace, label, cwd });
168
169
  }
169
170
  catch (error) {
170
171
  await worktree?.discard();
@@ -186,19 +187,20 @@ export async function launchSession(server, data, options = {}) {
186
187
  await new Promise(resolve => setTimeout(resolve, 200));
187
188
  }
188
189
  if (!created)
189
- throw new BridgeError(409, `Herdr created "${label}" but its pane did not appear. Check Herdr on the computer.`);
190
+ throw new BridgeError(409, `${terminalName(server)} created "${label}" but its pane did not appear. Check ${terminalName(server)} on the computer.`);
190
191
  try {
191
- await rpc(server, "agent.start", { name, kind, pane_id: created.paneId, timeout_ms: timeout, ...(args.length ? { args } : {}) }, undefined, timeout + 5_000);
192
+ await terminalProvider().startAgent(server, created.paneId, { name, kind, args, timeoutMs: timeout });
192
193
  }
193
194
  catch (error) {
194
195
  // A first-run screen (Claude's folder trust, a login notice) holds the
195
196
  // agent at startup. It did start: hand the pane back so the owner answers
196
197
  // that screen from the chat instead of stranding the workspace.
197
- const blocked = error instanceof BridgeError && error.details?.herdrCode === "agent_not_ready";
198
+ const blocked = agentNotReady(error);
198
199
  if (!blocked) {
200
+ const host = terminalName(server);
199
201
  const reason = error instanceof BridgeError && error.status === 504 ? "it did not become ready in time"
200
- : error instanceof BridgeError && error.message.startsWith("Herdr: ") ? error.message.slice(7) : "Herdr reported an error";
201
- throw new BridgeError(409, `Herdr couldn't start ${kind} in the new "${label}" pane (${reason}). The workspace was created and is still open on the computer — open it from Herdr workspaces.`);
202
+ : error instanceof BridgeError && error.message.startsWith(`${host}: `) ? error.message.slice(host.length + 2) : `${host} reported an error`;
203
+ throw new BridgeError(409, `${host} couldn't start ${kind} in the new "${label}" pane (${reason}). The workspace was created and is still open on the computer — open it from ${host === "Herdr" ? "Herdr workspaces" : "its tmux session"}.`);
202
204
  }
203
205
  }
204
206
  const after = await snapshot(server);
@@ -228,14 +230,14 @@ export async function workspaceAction(server, operation, data) {
228
230
  const label = data.label === undefined ? undefined : z.string().min(1).max(200).refine(t => !/[\x00-\x1f\x7f]/.test(t)).parse(data.label);
229
231
  const cwd = data.cwd === undefined ? undefined : z.string().max(4096).refine(t => path.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
230
232
  if (operation === "create")
231
- await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label, cwd, focus: false, env: {} });
233
+ await terminalProvider().create(server, { workspace, label, cwd });
232
234
  else if (!workspace && !tab && !pane)
233
235
  throw new BridgeError(400, "Choose a Herdr destination.");
234
236
  else if (pane && operation === "focus")
235
- await rpc(server, "pane.focus", { pane_id: pane });
237
+ await terminalProvider().focusPane(server, pane);
236
238
  else if (pane)
237
239
  throw new BridgeError(400, "This pane action is not available.");
238
240
  else
239
- await rpc(server, `${tab ? "tab" : "workspace"}.${operation}`, { ...(tab ? { tab_id: tab } : { workspace_id: workspace }), ...(label ? { label } : {}) });
241
+ await terminalProvider().groupAction(server, operation, { workspace, tab }, label);
240
242
  return { ok: true };
241
243
  }
@@ -5,7 +5,8 @@ import { gitBranches, gitDiscard, gitLog, gitPulls, gitStage, gitStatus, gitTree
5
5
  import { fanoutWorktrees } from "./fanouts.js";
6
6
  import { gitWorktrees, resolveWorktree } from "./git-worktrees.js";
7
7
  import { gitCommit, gitPullRequest, gitPush } from "./git-publish.js";
8
- import { findPane, paneAgentName, paneChatState, paneIdentity, rpc, snapshot, startingPane, trustedDirectory, validateStartingTarget, validateTarget } from "./herdr.js";
8
+ import { findPane, paneAgentName, paneChatState, paneIdentity, snapshot, startingPane, trustedDirectory, validateStartingTarget, validateTarget } from "./herdr.js";
9
+ import { terminalProvider } from "./terminal.js";
9
10
  import { refuseWorkingSlash } from "./model-switch.js";
10
11
  import { sessionWebServers } from "./session-servers.js";
11
12
  import { repositoryDiff } from "./projects.js";
@@ -13,6 +14,7 @@ import { BridgeError, MAX_FRAME, object, objects, startingTargetSchema, targetSc
13
14
  import { childAgent, childAgentTree, conversationNamedPaths, transcriptPath } from "./transcripts.js";
14
15
  import { sideQuestionText } from "./side-questions.js";
15
16
  import { saveUpload } from "./uploads.js";
17
+ import { deliveryIdSchema, PromptOnce, promptScope } from "./prompt-once.js";
16
18
  export /** A file from the phone: a plain name and base64 bytes, bounded. */ function uploadBody(data) {
17
19
  const name = z.string().regex(/^[A-Za-z0-9_][A-Za-z0-9_ .()-]{0,199}$/).refine(n => !n.includes("..")).parse(data.name);
18
20
  const encoded = z.string().max(11_184_812).regex(/^[A-Za-z0-9+/]*={0,2}$/).parse(data.data);
@@ -120,7 +122,7 @@ async function resubmitIfIdle(agentHooks, target, text) {
120
122
  if (await status() === "working")
121
123
  return "pending";
122
124
  const late = agentHooks.awaitLateDelivery(target, text);
123
- await rpc(target.server, "agent.send_keys", { target: target.pane, keys: ["enter"] });
125
+ await terminalProvider().sendKeys(target.server, target.pane, ["enter"]);
124
126
  const outcome = await late;
125
127
  if (outcome !== "pending")
126
128
  return outcome;
@@ -188,7 +190,7 @@ async function submitStartingPrompt(server, target, terminal, looks = 4, interva
188
190
  const first = await settled();
189
191
  if (first !== "idle")
190
192
  return first !== "gone";
191
- await rpc(server, "agent.send_keys", { target: target.pane, keys: ["enter"] });
193
+ await terminalProvider().sendKeys(server, target.pane, ["enter"]);
192
194
  const second = await settled();
193
195
  return second !== "idle" && second !== "gone";
194
196
  }
@@ -204,7 +206,7 @@ async function typeSecret(server, pane, text) {
204
206
  let sent = false;
205
207
  for (let index = 0; index < keys.length; index += 32) {
206
208
  try {
207
- await rpc(server, "agent.send_keys", { target: pane, keys: keys.slice(index, index + 32) });
209
+ await terminalProvider().sendKeys(server, pane, keys.slice(index, index + 32));
208
210
  sent = true;
209
211
  }
210
212
  catch (error) {
@@ -214,7 +216,7 @@ async function typeSecret(server, pane, text) {
214
216
  }
215
217
  }
216
218
  try {
217
- await rpc(server, "agent.send_keys", { target: pane, keys: ["enter"] });
219
+ await terminalProvider().sendKeys(server, pane, ["enter"]);
218
220
  }
219
221
  catch (error) {
220
222
  if (sent)
@@ -222,7 +224,16 @@ async function typeSecret(server, pane, text) {
222
224
  throw error;
223
225
  }
224
226
  }
227
+ const promptOnce = new PromptOnce();
225
228
  export async function paneRoute(ctx, url, data, response) {
229
+ if (url.pathname !== "/v1/prompt")
230
+ return paneRouteOnce(ctx, url, data, response, () => { });
231
+ // A retried send carries its first attempt's id; the Hook answers it with
232
+ // that attempt's reply instead of typing the message a second time.
233
+ const id = deliveryIdSchema.parse(data.deliveryId);
234
+ return promptOnce.run(id, promptScope(object(data.target), String(data.text ?? "")), async (typing) => object(await paneRouteOnce(ctx, url, data, response, typing)));
235
+ }
236
+ async function paneRouteOnce(ctx, url, data, response, typing) {
226
237
  const { agentHooks, modelSwitcher, codexQuestions, sideQuestions } = ctx;
227
238
  let result;
228
239
  if (url.pathname === "/v1/keys" && object(data.target).starting === true) {
@@ -233,7 +244,7 @@ export async function paneRoute(ctx, url, data, response) {
233
244
  const keys = z.array(z.enum(ANSWER_KEYS)).min(1).max(4).parse(data.keys);
234
245
  if (!["blocked", "waiting", "unknown"].includes(String(pane.agent_status)))
235
246
  throw new BridgeError(409, "This agent is not waiting for an answer.");
236
- await rpc(target.server, "agent.send_keys", { target: target.pane, keys: keys.map(key => HERDR_KEYS[key] ?? key) });
247
+ await terminalProvider().sendKeys(target.server, target.pane, keys.map(key => HERDR_KEYS[key] ?? key));
237
248
  result = { ok: true };
238
249
  }
239
250
  else if (url.pathname === "/v1/secret" && object(data.target).starting === true) {
@@ -252,7 +263,8 @@ export async function paneRoute(ctx, url, data, response) {
252
263
  const pane = await validateStartingTarget(target);
253
264
  const text = z.string().min(1).max(32768).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t)).parse(data.text);
254
265
  refuseWorkingSlash(pane, text);
255
- await rpc(target.server, "agent.prompt", { target: target.pane, text });
266
+ typing();
267
+ await terminalProvider().prompt(target.server, target.pane, text);
256
268
  // A dispatched worker's brief is often long enough for Claude Code to
257
269
  // swallow the Enter; a slash command opens a menu an Enter would answer.
258
270
  const submitted = target.source !== "claude" || text.trim().startsWith("/")
@@ -309,13 +321,15 @@ export async function paneRoute(ctx, url, data, response) {
309
321
  if (sideQuestionText(target.source, text) !== undefined) {
310
322
  // Claude's `/btw` runs beside the turn and never reaches the transcript:
311
323
  // the Hook reads its panel and the answer arrives as a side-answer frame.
324
+ typing();
312
325
  return { ok: true, delivered: true, sideQuestion: await sideQuestions.ask(target, pane, text) };
313
326
  }
314
327
  if (target.source === "codex" && /^\s*\/model\s+\S/i.test(text))
315
328
  throw new BridgeError(422, "Use the model picker to switch Codex models.");
316
329
  const busy = String(pane.agent_status) === "working";
317
330
  const expected = agentHooks.expectDelivery(target, text, busy ? 300 : 1_500);
318
- await rpc(target.server, "agent.prompt", { target: target.pane, text });
331
+ typing();
332
+ await terminalProvider().prompt(target.server, target.pane, text);
319
333
  let outcome = await expected;
320
334
  // Only Claude confirms plain prompts through its hook, and a slash
321
335
  // command opens a menu that a second Enter would answer.
@@ -385,7 +399,7 @@ export async function paneRoute(ctx, url, data, response) {
385
399
  // Keyless choices move and verify the highlight before Enter;
386
400
  // the phone sends the option identifier through the same route.
387
401
  const answerKeys = await agentHooks.dialogAnswerKeys(target, keys);
388
- await rpc(target.server, "agent.send_keys", { target: target.pane, keys: answerKeys.map(key => HERDR_KEYS[key] ?? key) });
402
+ await terminalProvider().sendKeys(target.server, target.pane, answerKeys.map(key => HERDR_KEYS[key] ?? key));
389
403
  // A remembered prompt is answered by any key but a cursor move; the
390
404
  // menu window stays open through Enter because some choices (Codex
391
405
  // full access) open a second confirmation the Hook now walks itself.
@@ -95,6 +95,7 @@ export declare const capabilities: {
95
95
  speechTimestamps: boolean;
96
96
  transcribe: boolean;
97
97
  memoryStore: boolean;
98
+ promptOnce: boolean;
98
99
  };
99
100
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
100
101
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
@@ -51,7 +51,7 @@ async function childActivity(source, session) {
51
51
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
52
52
  terminal: "ssh-pty", shell: "ssh-pty", herdr: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
53
53
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
54
- files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, transcribe: true, memoryStore: true };
54
+ files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, transcribe: true, memoryStore: true, promptOnce: true };
55
55
  export function capabilitiesForModules(snapshot) {
56
56
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
57
57
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -1,8 +1,9 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { open, stat } from "node:fs/promises";
3
3
  import { promisify } from "node:util";
4
- import { object, objects } from "./protocol.js";
5
- import { rpc, snapshot } from "./herdr.js";
4
+ import { objects } from "./protocol.js";
5
+ import { snapshot } from "./herdr.js";
6
+ import { terminalProvider } from "./terminal.js";
6
7
  import { webServers } from "./projects.js";
7
8
  import { transcriptPath } from "./transcripts.js";
8
9
  /**
@@ -83,10 +84,8 @@ async function processTable(session) {
83
84
  return { parents, runners };
84
85
  }
85
86
  async function paneRoots(server, paneId) {
86
- const answer = await rpc(server, "pane.process_info", { pane_id: paneId }).catch(() => ({}));
87
- const info = object(answer.process_info);
88
- const pids = [info.shell_pid, ...objects(info.foreground_processes).map(process => process.pid)];
89
- return pids.filter((pid) => Number.isSafeInteger(pid) && Number(pid) > 1);
87
+ const { shellPid, foregroundPids } = await terminalProvider().processes(server, String(paneId)).catch(() => ({ foregroundPids: [] }));
88
+ return [shellPid, ...foregroundPids].filter((pid) => pid !== undefined && pid > 1);
90
89
  }
91
90
  /** Processes holding the transcript open: a background-job agent's own process. */
92
91
  async function transcriptHolders(file) {
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { rpc, validateTarget } from "./herdr.js";
2
+ import { validateTarget } from "./herdr.js";
3
+ import { terminalProvider } from "./terminal.js";
3
4
  import { readPaneText } from "./pane-text.js";
4
5
  import { BridgeError } from "./protocol.js";
5
6
  const MAX_QUESTION = 4_000;
@@ -98,7 +99,7 @@ export class SideQuestions {
98
99
  }
99
100
  paneKey(target) { return `${target.server}\0${target.pane}`; }
100
101
  read(target) {
101
- return readPaneText(target.server, target.pane, { method: "agent.read", source: "visible", lines: 80, timeoutMs: 2_000 });
102
+ return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines: 80, timeoutMs: 2_000 });
102
103
  }
103
104
  /** While a side question owns the pane, typed input would land in its panel
104
105
  * (`x` clears the history, `f` forks), so every other input waits. */
@@ -136,7 +137,7 @@ export class SideQuestions {
136
137
  // A panel the person opened in the terminal takes keys, not a prompt.
137
138
  if (sidePanel(await this.read(target)))
138
139
  throw new BridgeError(409, "The terminal already shows a side question. Close it there first.");
139
- await rpc(target.server, "agent.prompt", { target: target.pane, text: `/btw ${question}` });
140
+ await terminalProvider().prompt(target.server, target.pane, `/btw ${question}`);
140
141
  }
141
142
  catch (error) {
142
143
  this.open.delete(key);
@@ -177,7 +178,7 @@ export class SideQuestions {
177
178
  for (let attempt = 0; attempt < 3; attempt++) {
178
179
  if (!sidePanel(await this.read(target)))
179
180
  return;
180
- await rpc(target.server, "agent.send_keys", { target: target.pane, keys: ["esc"] });
181
+ await terminalProvider().sendKeys(target.server, target.pane, ["esc"]);
181
182
  await sleep(Math.min(this.options.intervalMs ?? 700, 300));
182
183
  }
183
184
  }
@@ -187,7 +188,7 @@ export class SideQuestions {
187
188
  let window = first.body, perKey = 0, size = lines.join("\n").length;
188
189
  for (let step = 0; step < 200 && size < MAX_ANSWER; step++) {
189
190
  const presses = perKey > 0 ? Math.max(1, Math.floor((window.length - 2) / perKey)) : 1;
190
- await rpc(target.server, "agent.send_keys", { target: target.pane, keys: Array(presses).fill("down") });
191
+ await terminalProvider().sendKeys(target.server, target.pane, Array(presses).fill("down"));
191
192
  await sleep(Math.min(this.options.intervalMs ?? 700, 150));
192
193
  const panel = sidePanel(await this.read(target));
193
194
  if (!panel || panel.answering)
@@ -17,6 +17,17 @@ export interface TerminalChoice {
17
17
  }
18
18
  export declare function unframed(text: string): string;
19
19
  export declare function visibleTerminalChoice(text: string): TerminalChoice | undefined;
20
+ /** OpenCode's permission prompt, read from the pane with its colors:
21
+ * "△ Permission required", what it asks, then one row "Allow once Allow
22
+ * always Reject" answered with ←/→ and Enter (Escape rejects). The row's
23
+ * selected option is the one drawn on a background the others don't share.
24
+ * The phone gets Allow once and Reject: Allow always opens OpenCode's own
25
+ * second confirmation. `selected` is the cursor's index in the three-option
26
+ * row; undefined when the colors do not say. */
27
+ export declare function opencodePermissionDialog(ansi: string): {
28
+ choice: TerminalChoice;
29
+ selected?: number;
30
+ } | undefined;
20
31
  /** The pane's last non-empty line is a password read: sudo's "[sudo] password
21
32
  * for user", or any "… Password:" prompt. */
22
33
  export declare function passwordLine(text: string): boolean;
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { BridgeError, object, objects } from "./protocol.js";
3
+ import { stripTerminal } from "../terminal-text.js";
3
4
  /** Reading the question a terminal dialog or held permission is asking:
4
5
  * numbered option rows, the highlighted row, password reads, and a released
5
6
  * AskUserQuestion's questions and answers. Pure functions over text and input. */
@@ -149,6 +150,42 @@ export function visibleTerminalChoice(text) {
149
150
  return { title: title.slice(0, 4_000), options: options.slice(0, 12),
150
151
  ...(highlightedIndex !== undefined ? { highlightedIndex } : {}) };
151
152
  }
153
+ const OPENCODE_OPTIONS = ["Allow once", "Allow always", "Reject"];
154
+ /** OpenCode's permission prompt, read from the pane with its colors:
155
+ * "△ Permission required", what it asks, then one row "Allow once Allow
156
+ * always Reject" answered with ←/→ and Enter (Escape rejects). The row's
157
+ * selected option is the one drawn on a background the others don't share.
158
+ * The phone gets Allow once and Reject: Allow always opens OpenCode's own
159
+ * second confirmation. `selected` is the cursor's index in the three-option
160
+ * row; undefined when the colors do not say. */
161
+ export function opencodePermissionDialog(ansi) {
162
+ const raw = ansi.split(/\r?\n/);
163
+ const plain = raw.map(line => stripTerminal(line).replace(/\r/g, ""));
164
+ const content = (line) => line.replace(/^\s*[┃│]?/, "");
165
+ let header = -1;
166
+ plain.forEach((line, index) => { if (/^\s*△\s*Permission required\s*$/.test(content(line)))
167
+ header = index; });
168
+ if (header < 0)
169
+ return undefined;
170
+ const row = plain.findIndex((line, index) => index > header && OPENCODE_OPTIONS.every(label => line.includes(label)));
171
+ if (row < 0 || row - header > 24)
172
+ return undefined;
173
+ // Lines pushed far right are OpenCode's status column, not the question.
174
+ const body = plain.slice(header + 1, row).map(content)
175
+ .filter(line => line.trim() && !/^\s{24,}/.test(line)).map(line => line.trim());
176
+ const title = ["Permission required", ...body].join("\n").slice(0, 4_000);
177
+ const backgrounds = OPENCODE_OPTIONS.map(label => {
178
+ const at = raw[row].indexOf(label);
179
+ if (at < 0)
180
+ return undefined;
181
+ const before = [...raw[row].slice(0, at).matchAll(/\x1b\[[0-9;]*48;2;(\d+;\d+;\d+)[0-9;]*m/g)];
182
+ return before.at(-1)?.[1];
183
+ });
184
+ const unique = backgrounds.flatMap((background, index) => background !== undefined && backgrounds.filter(other => other === background).length === 1 ? [index] : []);
185
+ const selected = unique.length === 1 && backgrounds.every(background => background !== undefined) ? unique[0] : undefined;
186
+ return { choice: { title, options: [{ label: "Allow once", key: "1", hasKey: false }, { label: "Reject", key: "Escape", hasKey: true }],
187
+ ...(selected === 0 ? { highlightedIndex: 0 } : {}) }, ...(selected !== undefined ? { selected } : {}) };
188
+ }
152
189
  /** The pane's last non-empty line is a password read: sudo's "[sudo] password
153
190
  * for user", or any "… Password:" prompt. */
154
191
  export function passwordLine(text) {