@phren/cli 0.3.68 → 0.3.70

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 (37) hide show
  1. package/dist/bridge/account-choice.js +3 -5
  2. package/dist/bridge/agent-hooks.d.ts +10 -4
  3. package/dist/bridge/agent-hooks.js +140 -68
  4. package/dist/bridge/claude-footer-mode.d.ts +7 -0
  5. package/dist/bridge/claude-footer-mode.js +24 -0
  6. package/dist/bridge/claude-question-dialog.js +10 -2
  7. package/dist/bridge/claude-question-lifecycle.d.ts +8 -0
  8. package/dist/bridge/claude-question-lifecycle.js +87 -0
  9. package/dist/bridge/claude-suggestion.d.ts +3 -0
  10. package/dist/bridge/claude-suggestion.js +10 -0
  11. package/dist/bridge/codex-threads.d.ts +9 -0
  12. package/dist/bridge/codex-threads.js +104 -37
  13. package/dist/bridge/conversation-search.js +29 -22
  14. package/dist/bridge/dialog-observation.d.ts +5 -0
  15. package/dist/bridge/dialog-observation.js +20 -0
  16. package/dist/bridge/pane-status.d.ts +3 -0
  17. package/dist/bridge/pane-status.js +66 -18
  18. package/dist/bridge/permission-mode.d.ts +1 -6
  19. package/dist/bridge/permission-mode.js +2 -23
  20. package/dist/bridge/prompt-deliveries.d.ts +1 -1
  21. package/dist/bridge/prompt-deliveries.js +6 -1
  22. package/dist/bridge/schedule-launch.js +2 -2
  23. package/dist/bridge/server-launch.js +1 -1
  24. package/dist/bridge/server-pane-routes.d.ts +5 -8
  25. package/dist/bridge/server-pane-routes.js +85 -77
  26. package/dist/bridge/server-stream.js +8 -12
  27. package/dist/bridge/session-activity.d.ts +1 -1
  28. package/dist/bridge/session-activity.js +2 -2
  29. package/dist/bridge/session-evidence.js +1 -1
  30. package/dist/bridge/terminal-choice.d.ts +3 -0
  31. package/dist/bridge/terminal-choice.js +59 -3
  32. package/dist/bridge/terminal-dialog-text.d.ts +7 -0
  33. package/dist/bridge/terminal-dialog-text.js +49 -0
  34. package/dist/bridge/transcripts.d.ts +3 -0
  35. package/dist/bridge/transcripts.js +19 -1
  36. package/dist/bridge-hook.mjs +3195 -2815
  37. package/package.json +1 -1
@@ -23,11 +23,10 @@ import { readFile } from "node:fs/promises";
23
23
  import { stripTerminal } from "../terminal-text.js";
24
24
  import { bindingPath } from "./agent-hook-stores.js";
25
25
  import { claudeQuestionDialog } from "./claude-question-dialog.js";
26
- import { intervalFromEnv } from "./limits.js";
26
+ import { confirmDialogRead, DIALOG_READ_MS } from "./dialog-observation.js";
27
27
  import { object } from "./protocol.js";
28
- import { numberedDialog, opencodePermissionDialog, visibleTerminalChoice } from "./terminal-choice.js";
29
- /** A working or blocked pane's screen is read for a dialog at most once per this window. */
30
- const DIALOG_READ_MS = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3_000);
28
+ import { claudeFooterMode } from "./claude-footer-mode.js";
29
+ import { claudePermissionDialog, opencodePermissionDialog, visibleTerminalChoice } from "./terminal-choice.js";
31
30
  const EVENT_STATUS = {
32
31
  SessionStart: "idle", UserPromptSubmit: "working", PreToolUse: "working", PostToolUse: "working",
33
32
  PreCompact: "working", Stop: "idle", PermissionRequest: "blocked",
@@ -46,6 +45,8 @@ const key = (server, pane) => `${server}\0${pane}`;
46
45
  * `terminal`, and answers it with its sequence number. */
47
46
  export function notePaneStatus(server, pane, terminal, status, at = Date.now()) {
48
47
  const id = key(server, pane), current = entries.get(id);
48
+ if (status === "idle" || status === "done")
49
+ dialogs.delete(id);
49
50
  if (current && current.terminal === terminal && current.status === status) {
50
51
  current.at = at;
51
52
  return { status, seq: current.seq };
@@ -64,9 +65,10 @@ export function settleBlockedPane(server, pane, minimumMs = 3_000) {
64
65
  const id = key(server, pane), current = entries.get(id), dialog = dialogs.get(id);
65
66
  if (current?.status === "blocked" && Date.now() - current.at >= minimumMs)
66
67
  notePaneStatus(server, pane, current.terminal, "working");
67
- if (dialog?.shown && Date.now() - dialog.shown.at >= minimumMs) {
68
+ if (dialog && (minimumMs === 0 || (dialog.shown && Date.now() - dialog.shown.at >= minimumMs))) {
68
69
  // The screen can show the answered dialog a moment longer: the next read
69
70
  // waits a whole window.
71
+ dialog.generation = {};
70
72
  dialog.shown = undefined;
71
73
  dialog.cleared = ++sequence;
72
74
  dialog.readAt = Date.now();
@@ -96,7 +98,7 @@ export async function paneStatus(server, pane, terminal) {
96
98
  }
97
99
  /** Claude's optional "Teach auto mode about your environment?" dialog. */
98
100
  export function claudeTeachAutoModeDialog(screen) {
99
- return /Teach auto mode about your environment/i.test(stripTerminal(screen));
101
+ return /^Teach auto mode about your environment\?$/i.test(claudePermissionDialog(screen)?.title ?? "");
100
102
  }
101
103
  /** Whether `screen` (a pane's visible lines, with or without colors) shows a
102
104
  * dialog waiting for `agent`'s owner. Stricter than the readers that answer
@@ -111,7 +113,30 @@ export function screenDialog(agent, screen) {
111
113
  return !!visibleTerminalChoice(text);
112
114
  if (agent === "claude" && (claudeQuestionDialog(text) || claudeTeachAutoModeDialog(text)))
113
115
  return true;
114
- return /Esc to cancel/i.test(text) && !!numberedDialog(text);
116
+ return !!claudePermissionDialog(text);
117
+ }
118
+ /** Failure to parse a resize/redraw is not evidence that a dialog was answered.
119
+ * Only a newer composer or the harness's working hint proves disappearance. */
120
+ export function screenDialogState(agent, screen) {
121
+ if (screenDialog(agent, screen))
122
+ return "shown";
123
+ const lines = stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean);
124
+ const composer = (line) => /^[❯›](?!\s*\d+[.)])(?:\s|$)/.test(line);
125
+ const chrome = (line) => /^[─━═]+$/.test(line) || claudeFooterMode(line) !== undefined
126
+ || /^(?:[←→?].*(?:agents|shortcuts)|(?:gpt-|GPT-|claude-|Claude ).*)/i.test(line);
127
+ const liveTail = (index) => lines.slice(index + 1).every(line => composer(line) || chrome(line));
128
+ let cue = -1;
129
+ for (let index = 0; index < lines.length; index++) {
130
+ if (/^(?:[>❯›]?\s*\d+[.)]|Do you want|Would you like|Ready to code|Allow\b|Trust\b|Teach auto|△\s*Permission|[☐☒]|.*Esc to cancel)/i.test(lines[index]))
131
+ cue = index;
132
+ }
133
+ for (let index = lines.length - 1; index > cue; index--) {
134
+ if (/\besc to interrupt\b/i.test(lines[index]) && liveTail(index))
135
+ return "gone";
136
+ if (index >= lines.length - 3 && composer(lines[index]) && liveTail(index))
137
+ return "gone";
138
+ }
139
+ return "unknown";
115
140
  }
116
141
  const dialogs = new Map();
117
142
  /** The status of a pane after a look at its screen: blocked while its agent
@@ -133,21 +158,44 @@ export async function dialogStatus(server, pane, terminal, agent, base, read) {
133
158
  dialogs.set(id, entry);
134
159
  }
135
160
  const now = Date.now();
136
- if (now - entry.readAt >= DIALOG_READ_MS) {
161
+ if (!entry.reading && now - entry.readAt >= DIALOG_READ_MS) {
137
162
  entry.readAt = now;
138
- // A failed read says nothing: the pane keeps what it had.
139
- const shown = await read().then(screen => screenDialog(agent, screen), () => undefined);
140
- if (shown === true && !entry.shown)
141
- entry.shown = { at: now, seq: ++sequence };
142
- else if (shown === false && entry.shown && now - entry.shown.at >= 3_000) {
143
- if (base.status === "blocked") {
144
- settleBlockedPane(server, pane);
145
- base = await paneStatus(server, pane, terminal) ?? base;
163
+ const observed = entry;
164
+ const generation = observed.generation;
165
+ const current = () => dialogs.get(id) === observed && observed.generation === generation;
166
+ const work = async () => {
167
+ let state = await read().then(screen => screenDialogState(agent, screen), () => "unknown");
168
+ if (state === "shown" && !observed.shown && base?.status !== "blocked") {
169
+ const confirmation = await confirmDialogRead(read, current);
170
+ state = confirmation === undefined ? "unknown" : screenDialogState(agent, confirmation);
171
+ }
172
+ if (!current())
173
+ return;
174
+ if (state === "shown" && !observed.shown)
175
+ observed.shown = { at: now, seq: ++sequence };
176
+ if (state === "gone" && observed.shown) {
177
+ if (base?.status === "blocked") {
178
+ settleBlockedPane(server, pane, 0);
179
+ base = await paneStatus(server, pane, terminal) ?? base;
180
+ }
181
+ observed.shown = undefined;
182
+ observed.cleared = ++sequence;
146
183
  }
147
- entry.shown = undefined;
148
- entry.cleared = ++sequence;
184
+ };
185
+ observed.reading = work();
186
+ }
187
+ if (entry.reading) {
188
+ const work = entry.reading;
189
+ try {
190
+ await work;
191
+ }
192
+ finally {
193
+ if (entry.reading === work)
194
+ entry.reading = undefined;
149
195
  }
150
196
  }
197
+ if (dialogs.get(id) !== entry)
198
+ return await paneStatus(server, pane, terminal) ?? base;
151
199
  if (entry.shown)
152
200
  return { status: "blocked", seq: entry.shown.seq };
153
201
  return { status: base.status, seq: Math.max(base.seq, entry.cleared ?? 0) };
@@ -1,3 +1,4 @@
1
+ export { claudeFooterMode } from "./claude-footer-mode.js";
1
2
  import type { AgentHooks } from "./agent-hooks.js";
2
3
  import { type Json, type Target } from "./protocol.js";
3
4
  /** An agent's permission mode as its own footer names it, and the route that
@@ -15,12 +16,6 @@ export type PermissionModeName = (typeof PERMISSION_MODE_VALUES)[number];
15
16
  /** The modes a Claude pane offers, in Shift+Tab cycle order. `bypass` adds the
16
17
  * one only a session launched with --allow-dangerously-skip-permissions has. */
17
18
  export declare function permissionModes(bypass: boolean): PermissionModeName[];
18
- /** Claude's permission mode from the footer line its TUI draws under the
19
- * composer. The transcript lags it: a `permission-mode` row is written only
20
- * when a prompt is submitted, and a fresh session has no file yet. The line may
21
- * trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. A
22
- * mode the footer does not mark is `undefined`: "manual mode on" is default. */
23
- export declare function claudeFooterMode(screen: string): PermissionModeName | undefined;
24
19
  /** Only the owner changes a session's permission mode, from the phone. An
25
20
  * agent's call names its own pane (`origin`), and none is accepted: an agent
26
21
  * could otherwise lift itself or another pane past the per-grant
@@ -1,4 +1,6 @@
1
1
  import { stripTerminal } from "../terminal-text.js";
2
+ import { claudeFooterMode } from "./claude-footer-mode.js";
3
+ export { claudeFooterMode } from "./claude-footer-mode.js";
2
4
  import { validateTarget } from "./herdr.js";
3
5
  import { BridgeError } from "./protocol.js";
4
6
  import { terminalProvider } from "./terminal.js";
@@ -19,29 +21,6 @@ export const PERMISSION_MODE_VALUES = [...PERMISSION_CYCLE, "bypassPermissions"]
19
21
  export function permissionModes(bypass) {
20
22
  return [...PERMISSION_CYCLE, ...(bypass ? ["bypassPermissions"] : [])];
21
23
  }
22
- /** Claude's permission mode from the footer line its TUI draws under the
23
- * composer. The transcript lags it: a `permission-mode` row is written only
24
- * when a prompt is submitted, and a fresh session has no file yet. The line may
25
- * trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. A
26
- * mode the footer does not mark is `undefined`: "manual mode on" is default. */
27
- export function claudeFooterMode(screen) {
28
- for (const line of stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean).slice(-8).reverse()) {
29
- const text = line.replace(/^[⏵⏸]+\s*/, "");
30
- if (text === line)
31
- continue;
32
- if (/bypass permissions on/i.test(text))
33
- return "bypassPermissions";
34
- if (/^manual mode on\b/i.test(text))
35
- return "default";
36
- if (/^accept edits on\b/i.test(text))
37
- return "acceptEdits";
38
- if (/^plan mode on\b/i.test(text))
39
- return "plan";
40
- if (/^auto mode on\b/i.test(text))
41
- return "auto";
42
- }
43
- return undefined;
44
- }
45
24
  /** Only the owner changes a session's permission mode, from the phone. An
46
25
  * agent's call names its own pane (`origin`), and none is accepted: an agent
47
26
  * could otherwise lift itself or another pane past the per-grant
@@ -109,7 +109,7 @@ export declare class PromptDeliveries {
109
109
  private release;
110
110
  private open;
111
111
  /** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
112
- pending(target: Target, text: string): boolean;
112
+ pending(target: Target, text: string, id?: string): boolean;
113
113
  /** Whether `record` still holds its pane: open, and either young or in a pane whose hooks will settle it. */
114
114
  private inFlight;
115
115
  /** Whether any message typed into `target`'s pane is still waiting to be taken or refused.
@@ -261,7 +261,12 @@ export class PromptDeliveries {
261
261
  return this.records.find(record => record.hash === hash && this.samePane(record, target) && (record.state === "typed" || record.state === "queued"));
262
262
  }
263
263
  /** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
264
- pending(target, text) { return !!this.open(target, text); }
264
+ pending(target, text, id) {
265
+ if (!id)
266
+ return !!this.open(target, text);
267
+ const record = this.find(id, target);
268
+ return !!record && PromptDeliveries.open(record) && record.session === target.session && record.hash === promptHash(text);
269
+ }
265
270
  /** Whether `record` still holds its pane: open, and either young or in a pane whose hooks will settle it. */
266
271
  inFlight(record) {
267
272
  return PromptDeliveries.open(record) && (this.now() - record.at < IN_FLIGHT_MS || this.hookPanes.has(this.paneKey(record)));
@@ -200,9 +200,9 @@ export function headlessEnv(schedule, env = process.env) {
200
200
  return { ...env, ...claudeLaunchEnv(home) };
201
201
  }
202
202
  async function launchHeadless(context, store, started) {
203
- // A Claude schedule that names no account runs under the one with the most room, as a Herdr launch does.
203
+ // Use the same pool and role decision as a phone or Herdr launch, in this launcher's store.
204
204
  const choice = context.schedule.harness === "claude" && !context.schedule.account
205
- ? await pickClaudeAccount(`Schedule "${context.schedule.name}"`, { project: context.project, cwd: context.cwd }) : undefined;
205
+ ? await pickClaudeAccount(`Schedule "${context.schedule.name}"`, { project: context.project, cwd: context.cwd, phrenPath: store }) : undefined;
206
206
  const env = headlessEnv(choice ? { ...context.schedule, account: choice.account } : context.schedule);
207
207
  const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path.join(root, context.runId);
208
208
  await mkdir(jobDir, { recursive: true, mode: 0o700 });
@@ -425,7 +425,7 @@ async function startSession(server, data, options) {
425
425
  // Herdr 0.9.1 refuses a start timeout of 3000 ms or less (invalid_agent_timeout).
426
426
  const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
427
427
  // Checked before anything is created, so a refusal leaves no pane, worktree or brief file behind.
428
- // A Claude launch that names no account runs under the signed-in one with the most room left.
428
+ // Share the unnamed-account decision with headless schedules, including when usage is unavailable.
429
429
  // Pools and roles apply as in dispatch: a 409 account_pool when no account may do this project's work.
430
430
  const project = typeof data.project === "string" && data.project ? data.project : undefined;
431
431
  const choice = kind === "claude" && named === undefined ? await pickClaudeAccount(`Launch "${label}"`, { project, cwd: projectDirectory }) : undefined;
@@ -37,7 +37,7 @@ export declare function gitRepository(pane: Json, target: Target, child: unknown
37
37
  export declare function herdrWorktreeWorkers(s: Json): WorktreeWorker[];
38
38
  /** What `takesPrompt` checks before typing into a Claude pane Herdr reads working: nothing structured
39
39
  * pending there and no dialog on its screen. */
40
- export declare function promptGuards(agentHooks: Pick<AgentHooks, "approval" | "terminalPrompt" | "servedQuestion">, target: Target): PromptGuards;
40
+ export declare function promptGuards(agentHooks: Pick<AgentHooks, "approval" | "terminalPrompt" | "servedQuestion">, target: Target): Required<PromptGuards>;
41
41
  /** A Claude pane showing a subagent's view (its empty input reads "Message
42
42
  * @<agent>…") takes typed text for that subagent, so a phone message never
43
43
  * reached the turn and failed when it ended (owner, 2026-10-21). Escape returns
@@ -50,12 +50,9 @@ export declare function leaveClaudeSubagentView(agentHooks: Pick<AgentHooks, "pa
50
50
  * it again under the same delivery id, once. Any other outcome, a changed
51
51
  * pane, or ten minutes end the watch. */
52
52
  export declare function retryAfterSubagentView(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, id: string, intervalMs?: number, limitMs?: number, escapeWaitMs?: number): void;
53
- /** A busy Claude Code queues typed text on Enter, but after a long paste
54
- * ("paste again to expand") it can swallow that Enter and leave the text in
55
- * its input line, where it stays after the turn ends. Follow the pane: once
56
- * it has stayed finished for two looks while the prompt is still unsubmitted,
57
- * press Enter once. A closed or replaced pane, a delivery the conversation
58
- * took, or ten minutes end the watch; a pane asking for input is never answered. */
59
- export declare function followQueuedDelivery(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, intervalMs?: number): void;
53
+ /** Observe while the original conversation works, then allow 30 seconds for
54
+ * its submission acknowledgement after it finishes. A new legitimate turn
55
+ * resets that window. No observation sends input to the terminal. */
56
+ export declare function followQueuedDelivery(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, id?: string, intervalMs?: number): void;
60
57
  export declare function paneRoute(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse, headers?: IncomingHttpHeaders): Promise<unknown>;
61
58
  export declare function paneRouteOnce(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse, typing: () => void | Promise<void>): Promise<unknown>;
@@ -5,7 +5,8 @@ import path from "node:path";
5
5
  import { setTimeout as sleep } from "node:timers/promises";
6
6
  import { z } from "zod";
7
7
  import { TURN_ENDED_WITHOUT_IT } from "./prompt-deliveries.js";
8
- import { claudeSubagentView } from "./claude-suggestion.js";
8
+ import { screenDialog } from "./pane-status.js";
9
+ import { claudeInputMatches, claudeSubagentView } from "./claude-suggestion.js";
9
10
  import { gitBranches, gitDiscard, gitLog, gitPulls, gitShow, gitStage, gitStatus, gitTree, gitUnstage } from "./git.js";
10
11
  import { fanoutWorktrees } from "./fanouts.js";
11
12
  import { gitWorktrees, resolveWorktree } from "./git-worktrees.js";
@@ -222,28 +223,46 @@ async function relaysSuggestion(target, text) {
222
223
  }
223
224
  /** Herdr answered the request with a refusal (a 409 carrying its own error code): it performed nothing. */
224
225
  const herdrRefused = (error) => error instanceof BridgeError && error.status === 409 && typeof error.details?.herdrCode === "string";
225
- /** An idle agent that has not taken typed text within the first wait
226
- * likely lost the Enter while it redrew (an update notice, a resize): the
227
- * text sits in its input line. Press Enter once more and wait again. A
228
- * pane that turned working took it; one still idle is reported unsubmitted,
229
- * so the phone shows the message as not sent instead of waiting forever. */
230
- async function resubmitIfIdle(agentHooks, target, text) {
231
- const status = async () => { try {
232
- return String(findPane(await snapshot(target.server), target)?.agent_status ?? "unknown");
226
+ /** Fresh terminal and conversation evidence for a delivery follow-up. Failure
227
+ * ends recovery; a later valid submission can still settle the failed receipt. */
228
+ async function deliveryPane(target, terminal) {
229
+ const pane = findPane(await snapshot(target.server), target);
230
+ if (!pane || typeof terminal !== "string" || pane.terminal_id !== terminal || pane.agent !== target.source)
231
+ throw new Error("The terminal instance changed or could not be verified.");
232
+ if (await paneIdentity(target.server, pane, true) !== target.session)
233
+ throw new Error("The conversation changed or could not be verified.");
234
+ return pane;
235
+ }
236
+ /** Screen reads cannot authorize a later key write: neither tmux nor Herdr
237
+ * exposes an atomic Claude composer/identity/held-state check-and-submit.
238
+ * Observe the receipt and report what can be verified, without writing keys.
239
+ * In particular, expanding a collapsed paste with keys would have the same
240
+ * race and still would not expose authoritative full composer text. */
241
+ async function observeIdleDelivery(agentHooks, target, terminal, text, id) {
242
+ const fail = (reason) => { agentHooks.deliveries.fail(id, target, reason); return "unsubmitted"; };
243
+ const guards = promptGuards(agentHooks, target);
244
+ try {
245
+ if (!id)
246
+ return fail("No delivery identity is available; check the terminal.");
247
+ const pane = await deliveryPane(target, terminal);
248
+ if (pane.agent_status === "working" && !guards.held())
249
+ return await agentHooks.deliveries.awaitLate(target, text);
250
+ if (!["idle", "done"].includes(String(pane.agent_status)))
251
+ return fail("The agent is not idle or done; observation stopped.");
252
+ if (guards.held())
253
+ return fail("The agent has a held approval, question or terminal prompt; observation stopped.");
254
+ const screen = await guards.screen();
255
+ // These are observations only. The owner or harness may change the input
256
+ // even before readScreen resolves; no screen result permits an Enter.
257
+ if (!agentHooks.deliveries.pending(target, text, id))
258
+ return agentHooks.deliveries.status(id, target).state === "delivered" ? "delivered" : "unsubmitted";
259
+ if (screenDialog(target.source, screen) || !claudeInputMatches(screen, text))
260
+ return fail("The full message cannot be verified in the input box; check the terminal.");
261
+ return fail("The message is visible but cannot be safely resubmitted; check and submit it in the terminal.");
262
+ }
263
+ catch (error) {
264
+ return fail(error instanceof Error ? error.message : "The delivery checks failed; check the terminal.");
233
265
  }
234
- catch {
235
- return "unknown";
236
- } };
237
- // A pane that turned working started a turn: its UserPromptSubmit is on its way (the agent runs its
238
- // other hooks too). Wait for it rather than answering "queued" for a message the agent took.
239
- if (await status() === "working")
240
- return await agentHooks.deliveries.awaitLate(target, text);
241
- const late = agentHooks.deliveries.awaitLate(target, text);
242
- await terminalProvider().sendKeys(target.server, target.pane, ["enter"]);
243
- const outcome = await late;
244
- if (outcome !== "pending")
245
- return outcome;
246
- return await status() === "working" ? "pending" : "unsubmitted";
247
266
  }
248
267
  /** A Claude pane showing a subagent's view (its empty input reads "Message
249
268
  * @<agent>…") takes typed text for that subagent, so a phone message never
@@ -322,76 +341,64 @@ export function retryAfterSubagentView(agentHooks, target, terminal, text, id, i
322
341
  const expected = agentHooks.deliveries.expect(target, text, 1_500, undefined, id, typeof terminal === "string" ? terminal : undefined);
323
342
  await terminalProvider().prompt(target.server, target.pane, text);
324
343
  if (await expected === "pending")
325
- await resubmitIfIdle(agentHooks, target, text);
344
+ await observeIdleDelivery(agentHooks, target, terminal, text, id);
326
345
  };
327
346
  const schedule = () => { const timer = setTimeout(() => void look().catch(() => undefined), intervalMs); timer.unref?.(); };
328
347
  schedule();
329
348
  }
330
- /** A busy Claude Code queues typed text on Enter, but after a long paste
331
- * ("paste again to expand") it can swallow that Enter and leave the text in
332
- * its input line, where it stays after the turn ends. Follow the pane: once
333
- * it has stayed finished for two looks while the prompt is still unsubmitted,
334
- * press Enter once. A closed or replaced pane, a delivery the conversation
335
- * took, or ten minutes end the watch; a pane asking for input is never answered. */
336
- export function followQueuedDelivery(agentHooks, target, terminal, text, intervalMs = 2_000) {
337
- const started = Date.now();
338
- let finishedLooks = 0;
349
+ /** Observe while the original conversation works, then allow 30 seconds for
350
+ * its submission acknowledgement after it finishes. A new legitimate turn
351
+ * resets that window. No observation sends input to the terminal. */
352
+ export function followQueuedDelivery(agentHooks, target, terminal, text, id, intervalMs = 2_000) {
353
+ let finishedAt;
354
+ const fail = (reason) => agentHooks.deliveries.fail(id, target, reason);
339
355
  const look = async () => {
340
- if (!agentHooks.deliveries.pending(target, text) || Date.now() - started > 600_000)
356
+ if (!id || !agentHooks.deliveries.pending(target, text, id))
341
357
  return;
342
- let pane;
343
358
  try {
344
- pane = findPane(await snapshot(target.server), target);
345
- }
346
- catch {
347
- pane = undefined;
348
- }
349
- if (!pane) {
359
+ const pane = await deliveryPane(target, terminal);
360
+ const status = String(pane.agent_status);
361
+ if (promptGuards(agentHooks, target).held() || !["working", "idle", "done"].includes(status)) {
362
+ fail("The agent needs input or its status is unknown; observation stopped.");
363
+ return;
364
+ }
365
+ if (status === "working")
366
+ finishedAt = undefined;
367
+ else {
368
+ finishedAt ??= Date.now();
369
+ if (Date.now() - finishedAt >= 30_000) {
370
+ await observeIdleDelivery(agentHooks, target, terminal, text, id);
371
+ return;
372
+ }
373
+ }
350
374
  schedule();
351
- return;
352
375
  }
353
- if (pane.terminal_id !== terminal)
354
- return;
355
- const status = String(pane.agent_status);
356
- finishedLooks = status === "idle" || status === "done" ? finishedLooks + 1 : 0;
357
- if (finishedLooks >= 2) {
358
- await resubmitIfIdle(agentHooks, target, text).catch(() => undefined);
359
- return;
376
+ catch {
377
+ fail("The terminal or conversation could not be verified; observation stopped.");
360
378
  }
361
- schedule();
362
379
  };
363
380
  const schedule = () => { const timer = setTimeout(() => void look(), intervalMs); timer.unref?.(); };
364
381
  schedule();
365
382
  }
366
- /** A fresh Claude Code that took its first prompt starts working. One that
367
- * stays idle kept the brief in its input line (a long paste can swallow the
368
- * Enter): press Enter once, only while it is idle, so a dialog is never
369
- * answered. False when it still has not started. */
383
+ /** A starting pane has no verified conversation/delivery binding yet, so
384
+ * observe its initial submission without sending delayed keys. */
370
385
  async function submitStartingPrompt(server, target, terminal, looks = 4, intervalMs = 500) {
371
- const status = async () => {
386
+ for (let look = 0; look < looks; look++) {
387
+ await sleep(intervalMs);
372
388
  try {
373
389
  const pane = findPane(await snapshot(server), target);
374
- return pane && pane.terminal_id === terminal ? String(pane.agent_status) : "gone";
390
+ if (!pane || pane.terminal_id !== terminal)
391
+ return false;
392
+ if (pane.agent_status === "working")
393
+ return true;
394
+ if (!["idle", "done"].includes(String(pane.agent_status)))
395
+ return false;
375
396
  }
376
397
  catch {
377
- return "unknown";
398
+ return false;
378
399
  }
379
- };
380
- const settled = async () => {
381
- for (let look = 0; look < looks; look++) {
382
- await sleep(intervalMs);
383
- const current = await status();
384
- if (current !== "idle" && current !== "done")
385
- return current;
386
- }
387
- return "idle";
388
- };
389
- const first = await settled();
390
- if (first !== "idle")
391
- return first !== "gone";
392
- await terminalProvider().sendKeys(server, target.pane, ["enter"]);
393
- const second = await settled();
394
- return second !== "idle" && second !== "gone";
400
+ }
401
+ return false;
395
402
  }
396
403
  /** One key per character; Herdr's send_keys takes single characters and named
397
404
  * keys only, and a tty password read is corrupted by a bracketed paste. */
@@ -544,8 +551,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
544
551
  }
545
552
  refuseWorkingSlash(current, text);
546
553
  });
547
- // A dispatched worker's brief is often long enough for Claude Code to
548
- // swallow the Enter; a slash command opens a menu an Enter would answer.
554
+ // Observe a fresh Claude pane without adding keys to its initial send;
555
+ // a slash command opens a menu and needs no submission observation.
549
556
  const submitted = target.source !== "claude" || text.trim().startsWith("/")
550
557
  || await submitStartingPrompt(target.server, target, pane.terminal_id);
551
558
  if (!submitted)
@@ -701,9 +708,9 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
701
708
  // command opens a menu that a second Enter would answer.
702
709
  if (outcome === "pending" && target.source === "claude" && !text.trim().startsWith("/")) {
703
710
  if (!busy)
704
- outcome = await resubmitIfIdle(agentHooks, target, text);
711
+ outcome = await observeIdleDelivery(agentHooks, target, pane.terminal_id, text, deliveryId);
705
712
  else
706
- followQueuedDelivery(agentHooks, target, pane.terminal_id, text);
713
+ followQueuedDelivery(agentHooks, target, pane.terminal_id, text, deliveryId);
707
714
  }
708
715
  if (deliveryId && target.source === "claude" && outcome !== "delivered")
709
716
  retryAfterSubagentView(agentHooks, target, pane.terminal_id, text, deliveryId);
@@ -715,7 +722,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
715
722
  if (outcome === "delivered")
716
723
  result = { ok: true, delivered: true, state: "delivered" };
717
724
  else if (outcome === "unsubmitted") {
718
- const reason = "The agent did not take the message; it may still be in its input line.";
725
+ const failed = deliveryId ? agentHooks.deliveries.status(deliveryId, target) : undefined;
726
+ const reason = failed?.state === "failed" && failed.reason ? failed.reason : "The agent did not take the message; it may still be in its input line.";
719
727
  if (deliveryId)
720
728
  agentHooks.deliveries.fail(deliveryId, target, reason);
721
729
  result = { ok: true, deliveryUncertain: true, unsubmitted: true, ...(deliveryId ? { state: "failed", reason } : {}) };
@@ -143,6 +143,10 @@ export function transcriptStreams(ctx) {
143
143
  send(client, { ...emptyPage, type: "backlog", ...conversation });
144
144
  }
145
145
  else if (reader) {
146
+ if (child === null && target.source === "claude") {
147
+ const boundary = Math.max(agentHooks.questionResolution?.(target) ?? 0, Date.parse(evidence.record?.prompt?.at ?? "") || 0, Date.parse(evidence.record?.stop?.at ?? "") || 0);
148
+ reader.resolveClaudeQuestionsThrough(boundary || undefined);
149
+ }
146
150
  await refreshTranscript(reader.file, conversation.source, conversation.session);
147
151
  const resumingClaude = first && conversation.source === "claude" && resumeAfterLine !== undefined;
148
152
  let page = resumeAfterLine === undefined
@@ -192,21 +196,13 @@ export function transcriptStreams(ctx) {
192
196
  send(client, { type: "preview", ...conversation, ...preview, ...activity });
193
197
  }
194
198
  else {
195
- let pendingApproval = agentHooks.approval(target);
199
+ const pendingApproval = agentHooks.approval(target);
196
200
  const pendingQuestions = target.source === "codex" ? await codexQuestions.pending(target).catch(() => undefined) : undefined;
197
201
  const cwd = await trustedDirectory(pane).catch(() => undefined);
198
202
  const branch = modules.has("git") && cwd ? await repositoryBranch(cwd) : undefined;
199
203
  const waiting = !pendingApproval && ["blocked", "waiting"].includes(String(resolvedStatus));
200
- // Claude Code's auto-mode fallback, opencode and Codex draw a
201
- // numbered dialog in the pane with no PermissionRequest hook
202
- // behind it: read the pane (at most once per three seconds) and
203
- // publish the dialog as the same terminal choice shape the phone
204
- // answers. Codex also resolves the real terminal choices for a held
205
- // approval; a structured question keeps its own answer channel.
206
- if (["claude", "opencode", "codex"].includes(target.source)) {
207
- await agentHooks.syncTerminalDialog(target, waiting && !pendingQuestions?.length);
208
- pendingApproval = agentHooks.approval(target);
209
- }
204
+ // effectivePaneEvidence already reconciled this tick's dialog.
205
+ // Reusing that observation keeps status and prompt in agreement.
210
206
  // A served OpenCode pane's question comes from its own API, whatever
211
207
  // status its terminal reports.
212
208
  const servedQuestion = agentHooks.servedQuestion(target);
@@ -337,7 +333,7 @@ export function transcriptStreams(ctx) {
337
333
  return;
338
334
  }
339
335
  ready = true;
340
- timer = setInterval(() => { countTick(url.pathname === "/v1/transcripts" ? "stream-transcripts" : "stream-status"); void tick(); }, reader || awaitingTranscript ? 500 : 1500);
336
+ timer = setInterval(() => { countTick(url.pathname === "/v1/transcripts" ? "stream-transcripts" : "stream-status"); void tick(); }, 500);
341
337
  await tick();
342
338
  }
343
339
  catch (error) {
@@ -45,7 +45,7 @@ export declare function recordedBackground(record: TurnRecord | undefined, finis
45
45
  export interface PromptGuards {
46
46
  /** An approval the Hook holds, a terminal prompt or a question it serves for this pane. */
47
47
  held?: () => boolean;
48
- /** The pane's visible screen; a dialog there (pane-status.ts `screenDialog`) or a failed read refuses. */
48
+ /** The pane's visible screen; a dialog, uncertain screen or failed read refuses. */
49
49
  screen?: () => Promise<string>;
50
50
  }
51
51
  /**
@@ -1,5 +1,5 @@
1
1
  import { briefLabel } from "./launch-brief.js";
2
- import { screenDialog } from "./pane-status.js";
2
+ import { screenDialogState } from "./pane-status.js";
3
3
  import { provider } from "./protocol.js";
4
4
  import { backgroundLeft, readTurn, turnPhase } from "./turn-records.js";
5
5
  /**
@@ -77,7 +77,7 @@ export async function takesPrompt(server, pane, session, guards = {}, now = Date
77
77
  if (!guards.screen)
78
78
  return true;
79
79
  const screen = await guards.screen().catch(() => undefined);
80
- return screen !== undefined && !screenDialog("claude", screen);
80
+ return screen !== undefined && screenDialogState("claude", screen) === "gone";
81
81
  }
82
82
  /** The background shells and monitors a turn still awaits, from its transcript
83
83
  * final turn. A recorded ended turn bounds `FinalTurn.awaited` by the Stop's
@@ -36,7 +36,7 @@ async function bounded(work, ms = 100) {
36
36
  export function availablePaneEvidence(server, pane, session, record, hooks) {
37
37
  const target = { server, pane: String(pane.pane_id), workspace: String(pane.workspace_id), tab: String(pane.tab_id), source: pane.agent, session };
38
38
  const held = !!(hooks?.approval?.(target) || hooks?.servedQuestion?.(target));
39
- return { paneStatus: pane.agent_status, record, held, dialog: !!hooks?.terminalPrompt?.(target) };
39
+ return { paneStatus: pane.agent_status, record, held, dialog: !!hooks?.confirmedTerminalDialog?.(target) };
40
40
  }
41
41
  const finalReads = new Map();
42
42
  function finalEvidence(record) {
@@ -38,6 +38,9 @@ export declare function passwordLine(text: string): boolean;
38
38
  * " · ", and a footer offering "Esc to cancel" gains the Escape option.
39
39
  * Undefined without two numbered rows and a question. */
40
40
  export declare function numberedDialog(text: string): TerminalChoice | undefined;
41
+ /** Claude's live permission UI, rather than numbered prose in its output.
42
+ * The prompt, contiguous options, selection and final hint belong to one block. */
43
+ export declare function claudePermissionDialog(text: string): TerminalChoice | undefined;
41
44
  /** Read the question a terminal dialog is asking from the request it carries:
42
45
  * an explicit options list, or numbered lines inside its text. Undefined when
43
46
  * there are not at least two answerable choices. */