@phren/cli 0.3.69 → 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.
@@ -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
@@ -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;
@@ -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. */
@@ -1,3 +1,4 @@
1
+ import { logicalDialogLines } from "./terminal-dialog-text.js";
1
2
  import { z } from "zod";
2
3
  import { BridgeError, object, objects } from "./protocol.js";
3
4
  import { stripTerminal } from "../terminal-text.js";
@@ -122,7 +123,21 @@ export function unframed(text) {
122
123
  }
123
124
  export function visibleTerminalChoice(text) {
124
125
  text = unframed(text);
125
- const parsed = numberedOptions(text);
126
+ const screenLines = logicalDialogLines(text);
127
+ text = screenLines.join("\n");
128
+ const optionRow = /^\s*[>❯›▸▶»•*]?\s*\d+[.)]\s+/;
129
+ let last = screenLines.length - 1;
130
+ while (last >= 0 && !optionRow.test(screenLines[last]))
131
+ last--;
132
+ if (last < 0 || screenLines.slice(last + 1).some(line => line.trim()
133
+ && !/^\s*(?:press |enter\b|esc\b|[↑↓←→]|tab\b)/i.test(line)))
134
+ return undefined;
135
+ let first = last;
136
+ while (first > 0 && optionRow.test(screenLines[first - 1]))
137
+ first--;
138
+ if (screenLines.slice(0, first).filter(line => /^\s*```/.test(line)).length % 2)
139
+ return undefined;
140
+ const parsed = numberedOptions(screenLines.slice(first, last + 1).join("\n"));
126
141
  const highlights = parsed.flatMap((option, index) => option.highlighted ? [index] : []);
127
142
  const highlightedIndex = highlights.length === 1 ? highlights[0] : undefined;
128
143
  if (parsed.some(option => !option.hasKey) && highlightedIndex === undefined)
@@ -131,7 +146,7 @@ export function visibleTerminalChoice(text) {
131
146
  if (options.length < 2 || new Set(options.map(option => option.key)).size !== options.length)
132
147
  return undefined;
133
148
  const lines = text.split(/\r?\n/);
134
- const firstOption = lines.findIndex(line => /^\s*[>❯›▸▶»•*]?\s*\d+[.)]\s+/.test(line));
149
+ const firstOption = lines.findIndex((line, index) => index === first && /^\s*[>❯›▸▶»•*]?\s*\d+[.)]\s+/.test(line));
135
150
  const above = firstOption < 0 ? lines.slice(0, 1) : lines.slice(0, firstOption);
136
151
  // Only the question's own block: everything above the last blank line is
137
152
  // whatever the agent printed before it asked, and reading a pane of
@@ -145,7 +160,10 @@ export function visibleTerminalChoice(text) {
145
160
  && /^\s*(?:select|choose) (?:model|reasoning (?:level|effort))\b/i.test(line));
146
161
  const question = above.slice(menuStart >= 0 ? menuStart : Math.max(start, above.length - QUESTION_LINES));
147
162
  const title = question.map(line => line.trim()).filter(line => line && !/^press enter\b/i.test(line)).join("\n").trim();
148
- if (!title)
163
+ if (!title || question.some(line => /^\s*>/.test(line)))
164
+ return undefined;
165
+ if (!parsed.some(option => option.hasKey) && !screenLines.slice(last + 1).some(line => /^\s*(?:press |enter\b|esc\b|[↑↓←→]|tab\b)/i.test(line)) && !/[?]/.test(title)
166
+ && !/^(?:select|choose) (?:model|reasoning|permissions)\b/im.test(title))
149
167
  return undefined;
150
168
  return { title: title.slice(0, 4_000), options: options.slice(0, 12),
151
169
  ...(highlightedIndex !== undefined ? { highlightedIndex } : {}) };
@@ -170,6 +188,13 @@ export function opencodePermissionDialog(ansi) {
170
188
  const row = plain.findIndex((line, index) => index > header && OPENCODE_OPTIONS.every(label => line.includes(label)));
171
189
  if (row < 0 || row - header > 24)
172
190
  return undefined;
191
+ if (plain.slice(row + 1).some(line => {
192
+ const tail = content(line);
193
+ return tail.trim() && !/^\s{24,}/.test(tail) && !/^\s*(?:ctrl\+|enter\b|[←→⇆])/.test(tail);
194
+ }))
195
+ return undefined;
196
+ if (plain.slice(0, header).filter(line => /^\s*```/.test(line)).length % 2)
197
+ return undefined;
173
198
  // Lines pushed far right are OpenCode's status column, not the question.
174
199
  const body = plain.slice(header + 1, row).map(content)
175
200
  .filter(line => line.trim() && !/^\s{24,}/.test(line)).map(line => line.trim());
@@ -232,6 +257,37 @@ export function numberedDialog(text) {
232
257
  options.push({ label: "Cancel", key: "Escape" });
233
258
  return { title: title.slice(0, 4_000), options: options.slice(0, 12) };
234
259
  }
260
+ /** Claude's live permission UI, rather than numbered prose in its output.
261
+ * The prompt, contiguous options, selection and final hint belong to one block. */
262
+ export function claudePermissionDialog(text) {
263
+ const lines = logicalDialogLines(stripTerminal(text));
264
+ while (lines.length && !lines.at(-1).trim())
265
+ lines.pop();
266
+ if (!/^\s*(?:Enter to (?:select|confirm).*?·\s*)?Esc to cancel(?:\s*·.*)?$/i.test(lines.at(-1) ?? ""))
267
+ return;
268
+ const footer = lines.length - 1;
269
+ let end = footer - 1;
270
+ while (end >= 0 && !lines[end].trim())
271
+ end--;
272
+ const row = /^\s*(❯)?\s*(\d+)\.\s+(.+)$/;
273
+ let start = end;
274
+ while (start >= 0 && row.test(lines[start]))
275
+ start--;
276
+ const rows = lines.slice(start + 1, end + 1);
277
+ if (rows.length < 2 || rows.filter(line => row.exec(line)?.[1]).length !== 1)
278
+ return;
279
+ if (rows.some((line, index) => Number(row.exec(line)[2]) !== index + 1))
280
+ return;
281
+ while (start >= 0 && !lines[start].trim())
282
+ start--;
283
+ // Claude's permission prompt is a question on its own line. Quoted/fenced
284
+ // examples and composer text are not the harness's prompt.
285
+ if (!/^\s*(?:Do you want to |Would you like to |Allow |Trust |Teach auto mode about your environment|Ready to code).*\?\s*$/i.test(lines[start] ?? ""))
286
+ return;
287
+ if (lines.slice(0, start + 1).filter(line => /^\s*```/.test(line)).length % 2)
288
+ return;
289
+ return numberedDialog(lines.slice(start).join("\n"));
290
+ }
235
291
  /** Read the question a terminal dialog is asking from the request it carries:
236
292
  * an explicit options list, or numbered lines inside its text. Undefined when
237
293
  * there are not at least two answerable choices. */
@@ -0,0 +1,7 @@
1
+ /** Fold the harness's footer, including an unindented soft wrap, without
2
+ * swallowing newer output below it. */
3
+ export declare function joinDialogFooters(lines: string[]): string[];
4
+ /** Physical rows in a narrow pane are not option boundaries. A continuation
5
+ * starts in the label's column; prompt continuations end at the question mark.
6
+ * Keep blank rows, chrome, new composers and hints as block boundaries. */
7
+ export declare function logicalDialogLines(text: string): string[];
@@ -0,0 +1,49 @@
1
+ /** Fold the harness's footer, including an unindented soft wrap, without
2
+ * swallowing newer output below it. */
3
+ export function joinDialogFooters(lines) {
4
+ const result = [];
5
+ let footer = -1;
6
+ for (const line of lines) {
7
+ if (footer >= 0 && /^\s*(?:[↑↓←→/·]+\s*|Esc\b|Tab\b|Enter\b|to\b|cancel\b|select\b|navigate\b|confirm\b|amend\b)/i.test(line)) {
8
+ result[footer] += " " + line.trim();
9
+ continue;
10
+ }
11
+ footer = /^\s*(?:Enter to\b|Press enter\b|Esc to\b|↑\/↓ to\b)/i.test(line) ? result.length : -1;
12
+ result.push(line);
13
+ }
14
+ return result;
15
+ }
16
+ const OPTION = /^(\s*[>❯›▸▶»•*]?\s*\d+[.)]\s+)(.+)$/;
17
+ const PROMPT = /^\s*(?:Do you want to |Would you like to |Allow |Trust |Teach auto mode about your environment|Ready to code)/i;
18
+ /** Physical rows in a narrow pane are not option boundaries. A continuation
19
+ * starts in the label's column; prompt continuations end at the question mark.
20
+ * Keep blank rows, chrome, new composers and hints as block boundaries. */
21
+ export function logicalDialogLines(text) {
22
+ const result = [];
23
+ let option = -1, column = 0, prompt = -1;
24
+ for (const line of text.split(/\r?\n/).map(line => line.trimEnd())) {
25
+ const row = OPTION.exec(line);
26
+ if (row) {
27
+ option = result.length;
28
+ column = row[1].length;
29
+ prompt = -1;
30
+ result.push(line);
31
+ continue;
32
+ }
33
+ const boundary = !line.trim() || /^\s*(?:[❯›>│`─]|Esc\b|Enter\b|Press enter\b|Tab\b|[↑↓←→])/i.test(line);
34
+ if (!boundary && option >= 0 && /^\s*/.exec(line)[0].length >= column) {
35
+ result[option] += " " + line.trim();
36
+ continue;
37
+ }
38
+ option = -1;
39
+ if (!boundary && prompt >= 0) {
40
+ result[prompt] += " " + line.trim();
41
+ if (/\?\s*$/.test(line))
42
+ prompt = -1;
43
+ continue;
44
+ }
45
+ prompt = PROMPT.test(line) && !/\?\s*$/.test(line) ? result.length : -1;
46
+ result.push(line);
47
+ }
48
+ return joinDialogFooters(result);
49
+ }
@@ -122,6 +122,9 @@ export declare class TranscriptReader {
122
122
  private revision?;
123
123
  private nextLine;
124
124
  private ambiguous;
125
+ private questionBoundary?;
126
+ private resolvedQuestionIds;
127
+ resolveClaudeQuestionsThrough(at: number | undefined): void;
125
128
  constructor(file: string, source: Provider, imageLine?: number | undefined, changes?: ChangeLookup | undefined, includeSidechain?: boolean, cwd?: string | undefined,
126
129
  /** The phone delivery bound to each Claude queue row, by byte offset (PromptDeliveries). */
127
130
  queueBindings?: (() => Promise<Map<number, string> | undefined>) | undefined);
@@ -1,3 +1,4 @@
1
+ import { claudeQuestionResolutions, projectClaudeQuestionResolutions } from "./claude-question-lifecycle.js";
1
2
  import { readdir, realpath, lstat } from "node:fs/promises";
2
3
  import { createHash } from "node:crypto";
3
4
  import { homedir } from "node:os";
@@ -396,6 +397,9 @@ export class TranscriptReader {
396
397
  revision;
397
398
  nextLine = 0;
398
399
  ambiguous = new Set();
400
+ questionBoundary;
401
+ resolvedQuestionIds = "";
402
+ resolveClaudeQuestionsThrough(at) { this.questionBoundary = at; }
399
403
  constructor(file, source, imageLine, changes, includeSidechain = false, cwd,
400
404
  /** The phone delivery bound to each Claude queue row, by byte offset (PromptDeliveries). */
401
405
  queueBindings) {
@@ -412,7 +416,9 @@ export class TranscriptReader {
412
416
  /** A fresh opening page with the same reader options, for a reset after an
413
417
  * identity already delivered by this stream became ambiguous. */
414
418
  snapshot(signal) {
415
- return new TranscriptReader(this.file, this.source, this.imageLine, this.changes, this.includeSidechain, this.cwd, this.queueBindings).read(undefined, signal);
419
+ const reader = new TranscriptReader(this.file, this.source, this.imageLine, this.changes, this.includeSidechain, this.cwd, this.queueBindings);
420
+ reader.resolveClaudeQuestionsThrough(this.questionBoundary);
421
+ return reader.read(undefined, signal);
416
422
  }
417
423
  async read(before, signal) {
418
424
  return this.readPage(before, undefined, signal);
@@ -424,6 +430,16 @@ export class TranscriptReader {
424
430
  return this.readPage(undefined, afterLine, signal);
425
431
  }
426
432
  async readPage(before, afterLine, signal) {
433
+ const resolvedQuestions = this.source === "claude" && !this.includeSidechain
434
+ ? await claudeQuestionResolutions(this.file, this.questionBoundary, signal) : new Set();
435
+ const identities = JSON.stringify([...resolvedQuestions]);
436
+ if (identities !== this.resolvedQuestionIds) {
437
+ // A question can resolve without a transcript append (Stop/owner hook).
438
+ // Replace the tail so a client that already saw its call sees its resolution.
439
+ if (this.resolvedQuestionIds)
440
+ this.revision = undefined;
441
+ this.resolvedQuestionIds = identities;
442
+ }
427
443
  return withTranscriptIndex(this.file, async (handle, index) => {
428
444
  const reset = this.revision !== index.revision;
429
445
  const end = Math.min(before ?? index.lines, index.lines);
@@ -506,6 +522,8 @@ export class TranscriptReader {
506
522
  if (Object.keys(attached).length)
507
523
  raw = { ...raw, phren_changes: { ...attached, ...object(raw.phren_changes) } };
508
524
  }
525
+ if (this.source === "claude")
526
+ raw = projectClaudeQuestionResolutions(raw, resolvedQuestions);
509
527
  const projected = projectTranscriptRows(raw, this.source);
510
528
  rows = this.imageLine === row.line ? projected.rows : projected.rows.map(r => chatFrame(r, this.source));
511
529
  if (projected.base)