@phren/cli 0.3.55 → 0.3.56

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.
@@ -26058,6 +26058,597 @@ var init_launch_brief = __esm({
26058
26058
  }
26059
26059
  });
26060
26060
 
26061
+ // src/terminal-text.ts
26062
+ function stripTerminal(text5) {
26063
+ return text5.replace(TERMINAL_CONTROL, "");
26064
+ }
26065
+ var TERMINAL_CONTROL;
26066
+ var init_terminal_text = __esm({
26067
+ "src/terminal-text.ts"() {
26068
+ "use strict";
26069
+ TERMINAL_CONTROL = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\r/g;
26070
+ }
26071
+ });
26072
+
26073
+ // src/bridge/claude-question-dialog.ts
26074
+ function claudeQuestionDialog(text5) {
26075
+ const lines = text5.split(/\r?\n/);
26076
+ let bar = -1;
26077
+ for (let index2 = lines.length - 1; index2 >= 0; index2--) if (TAB_BAR.test(lines[index2]) && /[☐☒]/.test(lines[index2])) {
26078
+ bar = index2;
26079
+ break;
26080
+ }
26081
+ if (bar < 0) return void 0;
26082
+ const tabs = [...lines[bar].matchAll(/[☐☒]\s+([^☐☒✔→]+?)(?=\s{2,}|\s*[☐☒✔→]|\s*$)/g)].map((match) => match[1].trim());
26083
+ const body2 = lines.slice(bar + 1);
26084
+ const content = body2.map((line) => line.replace(GUTTER, "$1").trim()).filter((line) => line && !/^─+$/.test(line));
26085
+ if (content[0] === "Review your answers") {
26086
+ if (!body2.some((line) => /^\s*❯?\s*1\.\s+Submit answers\s*$/.test(line))) return void 0;
26087
+ const answers = [];
26088
+ for (const line of content.slice(1)) {
26089
+ if (/^Ready to submit/.test(line)) break;
26090
+ const question2 = /^●\s+(.+)$/.exec(line), answer2 = /^→\s+(.+)$/.exec(line), last = answers[answers.length - 1];
26091
+ if (question2) answers.push({ question: question2[1], answer: "" });
26092
+ else if (answer2 && last) last.answer = answer2[1];
26093
+ else if (last) {
26094
+ if (last.answer) last.answer += " " + line;
26095
+ else last.question += " " + line;
26096
+ }
26097
+ }
26098
+ return { kind: "review", tabs, answers };
26099
+ }
26100
+ if (!content.some((line) => /Esc to cancel/.test(line))) return void 0;
26101
+ const first = body2.findIndex((line) => ROW.test(line));
26102
+ if (first < 0) return void 0;
26103
+ const title2 = normalize(body2.slice(0, first).map((line) => line.replace(GUTTER, "$1")).filter((line) => line.trim()).join(" "));
26104
+ const rows2 = [];
26105
+ let cursor, chat = false;
26106
+ for (const line of body2.slice(first)) {
26107
+ const next = NEXT.exec(line);
26108
+ if (next) {
26109
+ if (next[1]) cursor = "next";
26110
+ continue;
26111
+ }
26112
+ const match = ROW.exec(line);
26113
+ if (!match) continue;
26114
+ const number4 = Number(match[2]);
26115
+ if (match[1]) cursor = number4;
26116
+ if (/^Chat about this$/.test(match[4])) {
26117
+ chat = true;
26118
+ continue;
26119
+ }
26120
+ const answered = !match[3] && / ✔$/.test(match[4]);
26121
+ rows2.push({
26122
+ number: number4,
26123
+ label: answered ? match[4].slice(0, -2).trim() : match[4],
26124
+ answered,
26125
+ cursor: !!match[1],
26126
+ ...match[3] ? { checked: match[3] === "\u2714" } : {}
26127
+ });
26128
+ }
26129
+ if (!title2 || !chat || rows2.length < 2) return void 0;
26130
+ const other = rows2.pop();
26131
+ return { kind: "question", tabs, title: title2, multiSelect: rows2.some((row) => row.checked !== void 0), options: rows2, other, ...cursor !== void 0 ? { cursor } : {} };
26132
+ }
26133
+ async function answerClaudeQuestionDialog(io, questions, answers, options = {}) {
26134
+ const from = options.from ?? 0, submit = options.submit ?? true;
26135
+ let sent = false;
26136
+ const changed = (message) => refusal(message, sent);
26137
+ const realKeys = io.keys.bind(io);
26138
+ io = { ...io, keys: async (keys2) => {
26139
+ sent = true;
26140
+ await realKeys(keys2);
26141
+ } };
26142
+ const sleep5 = io.sleep ?? ((ms2) => new Promise((resolve17) => setTimeout(resolve17, ms2)));
26143
+ const matches = (screen, index2) => screen?.kind === "question" && sameTitle(screen.title, questions[index2].question);
26144
+ const settle2 = async (check2, ms2 = 2e3) => {
26145
+ for (let waited = 0; ; waited += 120) {
26146
+ const value2 = check2(claudeQuestionDialog(await io.read()));
26147
+ if (value2 !== void 0 || waited >= ms2) return value2;
26148
+ await sleep5(120);
26149
+ }
26150
+ };
26151
+ const ANSWERED_MS = 8e3;
26152
+ const initial = await settle2((screen) => screen);
26153
+ if (!initial) throw changed("The terminal is not showing Claude's question.");
26154
+ if (initial.tabs.length !== questions.length) throw changed("The terminal is asking a different set of questions.");
26155
+ const reach = async (index2) => {
26156
+ const screen = await settle2((value2) => value2);
26157
+ if (screen?.kind === "question" && sameTitle(screen.title, questions[index2].question)) return screen;
26158
+ const at2 = screen?.kind === "review" ? questions.length : screen?.kind === "question" ? questions.findIndex((question2) => sameTitle(screen.title, question2.question)) : -1;
26159
+ if (at2 < 0) throw changed("The terminal is showing a different question.");
26160
+ if (screen?.kind === "question" && screen.other && screen.cursor === screen.other.number) await io.keys(["up"]);
26161
+ await io.keys(Array(Math.abs(index2 - at2)).fill(index2 > at2 ? "right" : "left"));
26162
+ const moved = await settle2((value2) => matches(value2, index2) ? value2 : void 0);
26163
+ if (!moved) throw changed("Could not move the terminal to the question being answered.");
26164
+ return moved;
26165
+ };
26166
+ const leaves = (index2) => (value2) => value2 === void 0 ? "gone" : !matches(value2, index2) ? "moved" : void 0;
26167
+ for (const [offset, answer2] of answers.entries()) {
26168
+ const index2 = from + offset, question2 = questions[index2];
26169
+ if (!question2) throw new BridgeError(400, "The answer names a question that was not asked.");
26170
+ const typed = answer2.text?.trim() ?? "";
26171
+ let screen = await reach(index2);
26172
+ if (screen.multiSelect !== !!question2.multiSelect || screen.options.length !== question2.options.length || screen.options.some((row, position) => !sameLabel(row.label, question2.options[position].label))) {
26173
+ throw changed("The terminal's options differ from the question being answered.");
26174
+ }
26175
+ if (!screen.multiSelect) {
26176
+ if (typed) {
26177
+ const other = screen.other;
26178
+ await io.keys([String(other.number)]);
26179
+ const focused = await settle2((value2) => matches(value2, index2) && value2.cursor === other.number ? value2 : void 0);
26180
+ if (!focused) throw changed("Could not open the typed answer.");
26181
+ await io.keys(typedKeys(typed));
26182
+ const shown = await settle2((value2) => matches(value2, index2) && value2.other && normalize(value2.other.label).startsWith(normalize(typed).slice(0, 20)) ? value2 : void 0);
26183
+ if (!shown) throw changed("The typed answer did not appear in the terminal.");
26184
+ await io.keys(["enter"]);
26185
+ } else {
26186
+ await io.keys([String(screen.options[answer2.options[0]].number)]);
26187
+ }
26188
+ if (!await settle2(leaves(index2), ANSWERED_MS)) throw changed("The terminal did not take the answer.");
26189
+ continue;
26190
+ }
26191
+ const rows2 = [...screen.options, ...screen.other ? [screen.other] : []];
26192
+ for (const [position, row] of rows2.entries()) {
26193
+ const wanted = position < screen.options.length ? answer2.options.includes(position) : !!row.checked && !!typed;
26194
+ if (wanted === !!row.checked) continue;
26195
+ const box = (value2) => matches(value2, index2) ? !!(position < value2.options.length ? value2.options[position] : value2.other)?.checked : void 0;
26196
+ for (let attempt = 0; attempt < 2 && box(screen) !== wanted; attempt++) {
26197
+ await io.keys([String(row.number)]);
26198
+ screen = await settle2((value2) => box(value2) === wanted ? value2 : void 0, 1e3) ?? screen;
26199
+ }
26200
+ if (box(screen) !== wanted) throw changed("The terminal's checkboxes did not match the answer.");
26201
+ }
26202
+ if (typed) {
26203
+ const other = screen.other, cursor = typeof screen.cursor === "number" ? screen.cursor : 1;
26204
+ if (cursor !== other.number) await io.keys(Array(Math.abs(other.number - cursor)).fill(other.number > cursor ? "down" : "up"));
26205
+ if (!await settle2((value2) => matches(value2, index2) && value2.cursor === other.number ? value2 : void 0)) throw changed("Could not reach the typed answer row.");
26206
+ await io.keys(typedKeys(typed));
26207
+ const shown = await settle2((value2) => matches(value2, index2) && value2.other?.checked && normalize(value2.other.label).startsWith(normalize(typed).slice(0, 20)) ? value2 : void 0);
26208
+ if (!shown) throw changed("The typed answer did not appear in the terminal.");
26209
+ await io.keys(["tab"]);
26210
+ if (!await settle2((value2) => matches(value2, index2) && value2.cursor === "next" ? value2 : void 0)) throw changed("Could not reach the question's Next row.");
26211
+ await io.keys(["enter"]);
26212
+ } else {
26213
+ await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
26214
+ }
26215
+ if (!await settle2(leaves(index2), ANSWERED_MS)) throw changed("The terminal did not move past the question.");
26216
+ }
26217
+ if (!submit) return;
26218
+ const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0, ANSWERED_MS);
26219
+ if (review === "gone") return;
26220
+ if (!review) throw changed("The terminal did not reach the review of the answers.");
26221
+ if (review.answers.length !== questions.length || review.answers.some((row, position) => !sameTitle(normalize(row.question), questions[position].question) || !row.answer)) {
26222
+ throw changed("Not every question has an answer in the terminal.");
26223
+ }
26224
+ await io.keys(["1"]);
26225
+ if (await settle2((value2) => value2 === void 0 ? "gone" : void 0, ANSWERED_MS) !== "gone") throw changed("The terminal did not submit the answers.");
26226
+ }
26227
+ var TAB_BAR, ROW, NEXT, normalize, sameTitle, sameLabel, GUTTER, refusal, typedKeys;
26228
+ var init_claude_question_dialog = __esm({
26229
+ "src/bridge/claude-question-dialog.ts"() {
26230
+ "use strict";
26231
+ init_protocol();
26232
+ TAB_BAR = /^\s*(?:←\s+)?((?:[☐☒]\s+\S[^☐☒✔→]*?\s*)+)(?:✔\s+Submit\s*)?(?:→\s*)?$/;
26233
+ ROW = /^\s*(❯)?\s*(\d)\.\s+(?:\[([ ✔])\]\s+)?(.*?)\s*$/;
26234
+ NEXT = /^\s*(❯)?\s+(?:Next|Submit)\s*$/;
26235
+ normalize = (text5) => text5.replace(/\s+/g, " ").trim();
26236
+ sameTitle = (shown, asked) => {
26237
+ const want = normalize(asked);
26238
+ if (shown === want) return true;
26239
+ return shown.endsWith("\u2026") && shown.length > 200 && want.startsWith(shown.slice(0, -1).trimEnd());
26240
+ };
26241
+ sameLabel = (shown, asked) => {
26242
+ const want = normalize(asked);
26243
+ return shown === want || shown.length >= 30 && want.startsWith(shown);
26244
+ };
26245
+ GUTTER = /^(\s*)│(?: |$)/;
26246
+ refusal = (message, sent) => sent ? new BridgeError(409, `${message} Some keys were already sent, so check the terminal before answering again, or cancel the question.`, { code: "question-unconfirmed" }) : new BridgeError(409, `${message} Nothing was sent; check the question and answer again, or cancel it.`, { code: "question-not-shown" });
26247
+ typedKeys = (text5) => [...text5].map((character) => character === " " ? "space" : character);
26248
+ }
26249
+ });
26250
+
26251
+ // src/bridge/terminal-choice.ts
26252
+ function choiceKey(value2) {
26253
+ if (typeof value2 !== "string") return void 0;
26254
+ const text5 = value2.trim().toLowerCase();
26255
+ if (!text5) return void 0;
26256
+ if (text5 === "esc" || text5 === "escape") return "Escape";
26257
+ if (text5 === "enter" || text5 === "return") return "Enter";
26258
+ if (text5 === "up" || text5 === "down" || text5 === "tab") return text5[0].toUpperCase() + text5.slice(1);
26259
+ return choiceKeys.has(text5) ? text5 : void 0;
26260
+ }
26261
+ function commandText(value2) {
26262
+ if (typeof value2 === "string" && value2.trim()) return value2.trim();
26263
+ if (Array.isArray(value2)) {
26264
+ const parts = value2.filter((part) => typeof part === "string" && !!part.trim());
26265
+ if (parts.length) return parts.join(" ");
26266
+ }
26267
+ return void 0;
26268
+ }
26269
+ function optionLabel(value2) {
26270
+ if (typeof value2 === "string") return value2.trim() || void 0;
26271
+ const fields2 = object2(value2);
26272
+ for (const key4 of ["label", "name", "title", "text", "value"]) {
26273
+ if (typeof fields2[key4] === "string" && fields2[key4].trim()) return fields2[key4].trim();
26274
+ }
26275
+ return void 0;
26276
+ }
26277
+ function labeledOption(label2, key4) {
26278
+ let resolved = choiceKey(key4);
26279
+ const trailing = /^(.+?)\s*\(([A-Za-z0-9]+)\)\s*$/.exec(label2);
26280
+ if (!resolved && trailing) resolved = choiceKey(trailing[2]);
26281
+ return resolved ? { label: label2, key: resolved } : void 0;
26282
+ }
26283
+ function structuredOptions(value2) {
26284
+ if (!Array.isArray(value2)) return [];
26285
+ return value2.flatMap((item) => {
26286
+ const label2 = optionLabel(item);
26287
+ if (!label2) return [];
26288
+ const fields2 = object2(item);
26289
+ const key4 = ["key", "shortcut", "hotkey", "accelerator", "value"].map((name) => choiceKey(fields2[name])).find(Boolean);
26290
+ const option = labeledOption(label2, key4);
26291
+ return option ? [{ ...option, ...typeof fields2.description === "string" && fields2.description.trim() ? { description: fields2.description.trim().slice(0, 4e3) } : {} }] : [];
26292
+ });
26293
+ }
26294
+ function numberedOptions(text5) {
26295
+ return text5.split(/\r?\n/).flatMap((line) => {
26296
+ const match = /^\s*([>❯›▸▶»•*])?\s*(\d+)[.)]\s+(.+?)\s*$/.exec(line);
26297
+ if (!match) return [];
26298
+ const columns = /^(.+?)\s{2,}(.+)$/.exec(match[3].trim());
26299
+ const label2 = columns?.[1] ?? match[3].trim();
26300
+ const description = columns?.[2].trim();
26301
+ const trailing = /^(.+?)\s*\(([A-Za-z0-9]+)\)\s*$/.exec(label2);
26302
+ const descriptionKey = description ? /^(.+?)\s*\(([A-Za-z0-9]+)\)\s*$/.exec(description) : null;
26303
+ const labelKey = trailing ? choiceKey(trailing[2]) : void 0;
26304
+ const endKey = descriptionKey ? choiceKey(descriptionKey[2]) : void 0;
26305
+ const key4 = labelKey ?? endKey ?? choiceKey(match[2]);
26306
+ return key4 ? [{
26307
+ label: labelKey && trailing ? trailing[1].trim() : label2,
26308
+ key: key4,
26309
+ highlighted: !!match[1],
26310
+ hasKey: !!(labelKey ?? endKey),
26311
+ ...description ? { description: endKey && descriptionKey ? descriptionKey[1].trim() : description } : {}
26312
+ }] : [];
26313
+ });
26314
+ }
26315
+ function unframed(text5) {
26316
+ let lines = text5.split(/\r?\n/);
26317
+ const filled = lines.filter((line) => line.trim());
26318
+ if (filled.length && filled.filter((line) => /┃\s*$/.test(line)).length * 2 > filled.length) {
26319
+ lines = lines.map((line) => line.replace(/\s*┃\s*$/, ""));
26320
+ }
26321
+ if (!lines.some((line) => framed.test(line))) return lines.join("\n");
26322
+ return lines.flatMap((line) => {
26323
+ if (!framed.test(line)) return [border.test(line) ? "" : line];
26324
+ let inner = line, match;
26325
+ while (match = framed.exec(inner)) inner = match[1];
26326
+ return border.test(inner) ? [] : [inner];
26327
+ }).join("\n");
26328
+ }
26329
+ function visibleTerminalChoice(text5) {
26330
+ text5 = unframed(text5);
26331
+ const parsed = numberedOptions(text5);
26332
+ const highlights = parsed.flatMap((option, index2) => option.highlighted ? [index2] : []);
26333
+ const highlightedIndex = highlights.length === 1 ? highlights[0] : void 0;
26334
+ if (parsed.some((option) => !option.hasKey) && highlightedIndex === void 0) return void 0;
26335
+ const options = parsed.map(({ highlighted: _highlighted, ...option }) => option);
26336
+ if (options.length < 2 || new Set(options.map((option) => option.key)).size !== options.length) return void 0;
26337
+ const lines = text5.split(/\r?\n/);
26338
+ const firstOption = lines.findIndex((line) => /^\s*[>❯›▸▶»•*]?\s*\d+[.)]\s+/.test(line));
26339
+ const above = firstOption < 0 ? lines.slice(0, 1) : lines.slice(0, firstOption);
26340
+ while (above.length && !above[above.length - 1].trim()) above.pop();
26341
+ let start = above.length;
26342
+ while (start > 0 && above[start - 1].trim()) start -= 1;
26343
+ const menuStart = above.findIndex((line, index2) => index2 >= above.length - QUESTION_LINES && /^\s*(?:select|choose) (?:model|reasoning (?:level|effort))\b/i.test(line));
26344
+ const question2 = above.slice(menuStart >= 0 ? menuStart : Math.max(start, above.length - QUESTION_LINES));
26345
+ const title2 = question2.map((line) => line.trim()).filter((line) => line && !/^press enter\b/i.test(line)).join("\n").trim();
26346
+ if (!title2) return void 0;
26347
+ return {
26348
+ title: title2.slice(0, 4e3),
26349
+ options: options.slice(0, 12),
26350
+ ...highlightedIndex !== void 0 ? { highlightedIndex } : {}
26351
+ };
26352
+ }
26353
+ function opencodePermissionDialog(ansi) {
26354
+ const raw = ansi.split(/\r?\n/);
26355
+ const plain2 = raw.map((line) => stripTerminal(line).replace(/\r/g, ""));
26356
+ const content = (line) => line.replace(/^\s*[┃│]?/, "");
26357
+ let header2 = -1;
26358
+ plain2.forEach((line, index2) => {
26359
+ if (/^\s*△\s*Permission required\s*$/.test(content(line))) header2 = index2;
26360
+ });
26361
+ if (header2 < 0) return void 0;
26362
+ const row = plain2.findIndex((line, index2) => index2 > header2 && OPENCODE_OPTIONS.every((label2) => line.includes(label2)));
26363
+ if (row < 0 || row - header2 > 24) return void 0;
26364
+ const body2 = plain2.slice(header2 + 1, row).map(content).filter((line) => line.trim() && !/^\s{24,}/.test(line)).map((line) => line.trim());
26365
+ const [asks, ...rest] = body2;
26366
+ const title2 = (asks?.replace(/^[←→]\s*/, "") || "Permission required").slice(0, 4e3);
26367
+ const patterns = rest.indexOf("Patterns");
26368
+ const details = patterns < 0 ? rest : [...rest.slice(0, patterns), ...rest.slice(patterns + 1).map((line) => line.replace(/^-\s+/, ""))];
26369
+ const detail = details.join("\n").slice(0, 4e3);
26370
+ const backgrounds = OPENCODE_OPTIONS.map((label2) => {
26371
+ const at2 = raw[row].indexOf(label2);
26372
+ if (at2 < 0) return void 0;
26373
+ const before = [...raw[row].slice(0, at2).matchAll(/\x1b\[[0-9;]*48;2;(\d+;\d+;\d+)[0-9;]*m/g)];
26374
+ return before.at(-1)?.[1];
26375
+ });
26376
+ const unique = backgrounds.flatMap((background, index2) => background !== void 0 && backgrounds.filter((other) => other === background).length === 1 ? [index2] : []);
26377
+ const selected = unique.length === 1 && backgrounds.every((background) => background !== void 0) ? unique[0] : void 0;
26378
+ return { choice: {
26379
+ title: title2,
26380
+ ...detail ? { body: detail } : {},
26381
+ options: [{ label: "Allow once", key: "1", hasKey: false }, { label: "Reject", key: "Escape", hasKey: true }],
26382
+ ...selected === 0 ? { highlightedIndex: 0 } : {}
26383
+ }, ...selected !== void 0 ? { selected } : {} };
26384
+ }
26385
+ function passwordLine(text5) {
26386
+ if (text5.includes("[sudo] password for")) return true;
26387
+ const last = text5.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).pop() ?? "";
26388
+ return /password[^\n]*:\s*$/i.test(last);
26389
+ }
26390
+ function numberedDialog(text5) {
26391
+ text5 = unframed(text5);
26392
+ const row = /^\s*[>❯›▸▶»•*]?\s*(\d+)\.\s+(.+?)\s*$/;
26393
+ const lines = text5.split(/\r?\n/);
26394
+ const first = lines.findIndex((line) => row.test(line));
26395
+ if (first < 0) return void 0;
26396
+ const title2 = lines.slice(0, first).map((line) => line.trim()).filter(Boolean).pop();
26397
+ if (!title2) return void 0;
26398
+ const options = [];
26399
+ for (const line of lines.slice(first)) {
26400
+ const match = row.exec(line);
26401
+ if (!match) continue;
26402
+ const label2 = match[2].split(" \xB7 ")[0].trim();
26403
+ if (label2) options.push({ label: label2, key: match[1] });
26404
+ }
26405
+ if (options.length < 2) return void 0;
26406
+ if (lines.some((line) => line.includes("Esc to cancel"))) options.push({ label: "Cancel", key: "Escape" });
26407
+ return { title: title2.slice(0, 4e3), options: options.slice(0, 12) };
26408
+ }
26409
+ function terminalChoice(input2) {
26410
+ const fields2 = object2(input2), command = commandText(fields2.command ?? fields2.cmd);
26411
+ let options = [fields2.options, fields2.choices, fields2.actions, fields2.answers].map(structuredOptions).find((list) => list.length >= 2) ?? [];
26412
+ if (options.length < 2) {
26413
+ const text5 = [fields2.question, fields2.description, fields2.justification, fields2.prompt, fields2.message, fields2.text, fields2.content, fields2.display].filter((value2) => typeof value2 === "string").join("\n");
26414
+ const parsed = numberedOptions(text5);
26415
+ if (parsed.length >= 2) options = parsed.map(({ highlighted: _highlighted, hasKey: _hasKey, ...option }) => option);
26416
+ }
26417
+ if (options.length < 2) return void 0;
26418
+ const title2 = [fields2.question, fields2.description, fields2.justification, fields2.prompt].find((value2) => typeof value2 === "string" && !!value2.trim() && value2.trim() !== command);
26419
+ if (!title2 && !command) return void 0;
26420
+ return { ...title2 ? { title: String(title2).slice(0, 4e3) } : {}, ...command ? { body: command.slice(0, 4e3) } : {}, options: options.slice(0, 12) };
26421
+ }
26422
+ function permissionTitle(tool, input2) {
26423
+ const fields2 = object2(input2);
26424
+ const sentence = [fields2.question, fields2.prompt, fields2.description, fields2.justification, fields2.message].find((value2) => typeof value2 === "string" && !!value2.trim() && !/^[{[]/.test(value2.trim()));
26425
+ if (sentence) return sentence.trim().slice(0, 4e3);
26426
+ const mcp = /^mcp__([^_]+)__(.+)$/.exec(tool);
26427
+ const server = mcp?.[1] ?? fields2.server;
26428
+ const name = mcp?.[2] ?? fields2.tool;
26429
+ if (typeof server === "string" && typeof name === "string") return `Allow the ${server} MCP server to run tool ${name}?`;
26430
+ return tool && tool !== "action" ? `Allow ${tool}?` : void 0;
26431
+ }
26432
+ function samePermission(choice, title2, tool, input2) {
26433
+ const text5 = choice.title?.toLowerCase() ?? "";
26434
+ if (title2 && text5.includes(title2.toLowerCase())) return true;
26435
+ const command = commandText(object2(input2).command ?? object2(input2).cmd);
26436
+ if (command && text5.includes(command.toLowerCase())) return true;
26437
+ const name = tool.split("__").pop();
26438
+ return !!name && name !== "action" && text5.includes(name.toLowerCase());
26439
+ }
26440
+ function permissionPrompt(tool, input2, terminalText = "") {
26441
+ const title2 = permissionTitle(tool, input2);
26442
+ const dialog = visibleTerminalChoice(terminalText);
26443
+ const matched = dialog && samePermission(dialog, title2, tool, input2) ? dialog : void 0;
26444
+ const sentence = matched?.title?.split("\n").find((line) => /\?\s*$/.test(line) && !/^[{[]/.test(line.trim()));
26445
+ const choice = matched ? { ...matched, title: sentence ?? title2 } : terminalChoice(input2);
26446
+ return {
26447
+ title: choice?.title ?? title2,
26448
+ details: JSON.stringify(input2 ?? {}, null, 2).slice(0, 32768),
26449
+ ...choice ? { choice } : {},
26450
+ terminalOnly: !choice
26451
+ };
26452
+ }
26453
+ function terminalQuestions(input2) {
26454
+ const questions = objects(object2(input2).questions).flatMap((raw) => {
26455
+ const question2 = typeof raw.question === "string" ? raw.question.trim() : "";
26456
+ if (!question2 || question2.length > 4e3) return [];
26457
+ const options = objects(raw.options).flatMap((option) => {
26458
+ const label2 = typeof option.label === "string" ? option.label.trim() : "";
26459
+ if (!label2 || label2.length > 2e3) return [];
26460
+ return [{
26461
+ label: label2,
26462
+ ...typeof option.description === "string" && option.description ? { description: option.description.slice(0, 4e3) } : {},
26463
+ ...typeof option.preview === "string" && option.preview ? { preview: option.preview.slice(0, 4e3) } : {}
26464
+ }];
26465
+ });
26466
+ if (!options.length || options.length > 12) return [];
26467
+ return [{
26468
+ question: question2,
26469
+ ...typeof raw.header === "string" && raw.header ? { header: raw.header.slice(0, 200) } : {},
26470
+ ...raw.multiSelect === true ? { multiSelect: true } : {},
26471
+ options
26472
+ }];
26473
+ });
26474
+ return questions.length >= 1 && questions.length <= 8 ? questions : void 0;
26475
+ }
26476
+ function questionChoice(questions, index2) {
26477
+ const question2 = questions[index2];
26478
+ if (!question2) return void 0;
26479
+ const options = question2.options.map((option, position) => ({ label: option.label, key: String(position + 1) }));
26480
+ if (question2.multiSelect) options.push({ label: "Done", key: "Enter" });
26481
+ return { title: question2.question, options: options.slice(0, 12) };
26482
+ }
26483
+ function canonical(value2) {
26484
+ if (Array.isArray(value2)) return "[" + value2.map(canonical).join(",") + "]";
26485
+ if (value2 !== null && typeof value2 === "object") return "{" + Object.keys(value2).sort().map((k2) => JSON.stringify(k2) + ":" + canonical(value2[k2])).join(",") + "}";
26486
+ return JSON.stringify(value2) ?? "null";
26487
+ }
26488
+ function answeredQuestionInput(tool, input2, updatedInput) {
26489
+ if (tool !== "AskUserQuestion") throw new BridgeError(400, "Only a question can be answered with input.");
26490
+ if (updatedInput === null || typeof updatedInput !== "object" || Array.isArray(updatedInput)) throw new BridgeError(400, "The answer is not an object.");
26491
+ const raw = JSON.stringify(updatedInput);
26492
+ if (Buffer.byteLength(raw) > 32768) throw new BridgeError(400, "The answer is too large.");
26493
+ const parsed = questionAnswers.safeParse(updatedInput);
26494
+ if (!parsed.success) throw new BridgeError(400, "The answer must add an answers object.");
26495
+ const { answers, response, ...rest } = parsed.data;
26496
+ if (canonical(rest) !== canonical(object2(input2))) throw new BridgeError(400, "The answer must keep the original questions.");
26497
+ const asked = new Set(objects(object2(input2).questions).map((q2) => q2.question).filter((q2) => typeof q2 === "string"));
26498
+ if (Object.keys(answers).some((q2) => !asked.has(q2))) throw new BridgeError(400, "The answer names a question that was not asked.");
26499
+ return { ...object2(input2), answers, ...response === void 0 ? {} : { response } };
26500
+ }
26501
+ var choiceKeys, QUESTION_LINES, BAR, framed, border, OPENCODE_OPTIONS, questionAnswers;
26502
+ var init_terminal_choice = __esm({
26503
+ "src/bridge/terminal-choice.ts"() {
26504
+ "use strict";
26505
+ init_zod();
26506
+ init_protocol();
26507
+ init_terminal_text();
26508
+ choiceKeys = /* @__PURE__ */ new Set(["Escape", "Enter", "Up", "Down", "Tab", "y", "n", "p", "1", "2", "3", "4", "5", "6", "7", "8", "9"]);
26509
+ QUESTION_LINES = 12;
26510
+ BAR = "\u2502\u2503\u2551";
26511
+ framed = new RegExp(`^\\s*[${BAR}] ?(.*?)\\s*[${BAR}]\\s*$`);
26512
+ border = /^[\s╭╮╰╯┌┐└┘├┤─━═│┃║]*$/;
26513
+ OPENCODE_OPTIONS = ["Allow once", "Allow always", "Reject"];
26514
+ questionAnswers = external_exports.looseObject({
26515
+ answers: external_exports.record(external_exports.string().min(1).max(4e3), external_exports.union([external_exports.string().max(4e3), external_exports.array(external_exports.string().max(4e3)).min(1).max(24)])).refine((a) => Object.keys(a).length > 0),
26516
+ response: external_exports.string().max(4e3).optional()
26517
+ });
26518
+ }
26519
+ });
26520
+
26521
+ // src/bridge/pane-status.ts
26522
+ import { readFile as readFile4 } from "node:fs/promises";
26523
+ function eventStatus(event) {
26524
+ return typeof event === "string" && Object.hasOwn(EVENT_STATUS, event) ? EVENT_STATUS[event] : void 0;
26525
+ }
26526
+ function notePaneStatus(server, pane, terminal2, status, at2 = Date.now()) {
26527
+ const id2 = key(server, pane), current2 = entries.get(id2);
26528
+ if (current2 && current2.terminal === terminal2 && current2.status === status) {
26529
+ current2.at = at2;
26530
+ return { status, seq: current2.seq };
26531
+ }
26532
+ entries.delete(id2);
26533
+ while (entries.size >= 512) entries.delete(entries.keys().next().value);
26534
+ const entry2 = { terminal: terminal2, status, seq: ++sequence, at: at2 };
26535
+ entries.set(id2, entry2);
26536
+ return { status, seq: entry2.seq };
26537
+ }
26538
+ function settleBlockedPane(server, pane, minimumMs = 3e3) {
26539
+ const id2 = key(server, pane), current2 = entries.get(id2), dialog = dialogs.get(id2);
26540
+ if (current2?.status === "blocked" && Date.now() - current2.at >= minimumMs) notePaneStatus(server, pane, current2.terminal, "working");
26541
+ if (dialog?.shown && Date.now() - dialog.shown.at >= minimumMs) {
26542
+ dialog.shown = void 0;
26543
+ dialog.cleared = ++sequence;
26544
+ dialog.readAt = Date.now();
26545
+ }
26546
+ }
26547
+ async function paneStatus(server, pane, terminal2) {
26548
+ const current2 = entries.get(key(server, pane));
26549
+ if (current2 && current2.terminal === terminal2) return { status: current2.status, seq: current2.seq };
26550
+ if (current2) return void 0;
26551
+ try {
26552
+ const value2 = object2(JSON.parse(await readFile4(bindingPath(server, pane), "utf8")));
26553
+ const status = eventStatus(value2.event);
26554
+ if (value2.terminal !== terminal2 || !status) return void 0;
26555
+ const at2 = Date.parse(String(value2.at));
26556
+ return notePaneStatus(server, pane, terminal2, status, Number.isFinite(at2) ? at2 : Date.now());
26557
+ } catch {
26558
+ return void 0;
26559
+ }
26560
+ }
26561
+ function claudeTeachAutoModeDialog(screen) {
26562
+ return /Teach auto mode about your environment/i.test(stripTerminal(screen));
26563
+ }
26564
+ function screenDialog(agent, screen) {
26565
+ const text5 = stripTerminal(screen);
26566
+ if (agent === "opencode") return !!opencodePermissionDialog(screen);
26567
+ if (agent === "codex" || agent === "copilot") return !!visibleTerminalChoice(text5);
26568
+ if (agent === "claude" && (claudeQuestionDialog(text5) || claudeTeachAutoModeDialog(text5))) return true;
26569
+ return /Esc to cancel/i.test(text5) && !!numberedDialog(text5);
26570
+ }
26571
+ async function dialogStatus(server, pane, terminal2, agent, base, read) {
26572
+ const id2 = key(server, pane);
26573
+ if (base?.status !== "working") {
26574
+ dialogs.delete(id2);
26575
+ return base;
26576
+ }
26577
+ let entry2 = dialogs.get(id2);
26578
+ if (!entry2 || entry2.terminal !== terminal2) {
26579
+ entry2 = { terminal: terminal2, readAt: 0 };
26580
+ dialogs.delete(id2);
26581
+ while (dialogs.size >= 512) dialogs.delete(dialogs.keys().next().value);
26582
+ dialogs.set(id2, entry2);
26583
+ }
26584
+ const now = Date.now();
26585
+ if (now - entry2.readAt >= DIALOG_READ_MS) {
26586
+ entry2.readAt = now;
26587
+ const shown = await read().then((screen) => screenDialog(agent, screen), () => void 0);
26588
+ if (shown === true && !entry2.shown) entry2.shown = { at: now, seq: ++sequence };
26589
+ else if (shown === false && entry2.shown) {
26590
+ entry2.shown = void 0;
26591
+ entry2.cleared = ++sequence;
26592
+ }
26593
+ }
26594
+ if (entry2.shown) return { status: "blocked", seq: entry2.shown.seq };
26595
+ return { status: base.status, seq: Math.max(base.seq, entry2.cleared ?? 0) };
26596
+ }
26597
+ function codexStartupStatus(screen) {
26598
+ const text5 = stripTerminal(screen);
26599
+ if (visibleTerminalChoice(text5)) return "blocked";
26600
+ if (/\besc to interrupt\b/i.test(text5)) return "working";
26601
+ const lines = text5.split(/\r?\n/).map((line) => line.trimEnd()).filter((line) => line.trim());
26602
+ let composer = lines.length - 1;
26603
+ while (composer >= 0 && !/^\u203a(?:\s|$)/.test(lines[composer])) composer -= 1;
26604
+ return composer >= 0 && composer >= lines.length - 3 && lines.length - composer > 1 ? "idle" : void 0;
26605
+ }
26606
+ async function startupStatus(server, pane, terminal2, agent, read) {
26607
+ if (agent !== "codex") return void 0;
26608
+ const id2 = key(server, pane);
26609
+ let entry2 = startups.get(id2);
26610
+ if (!entry2 || entry2.terminal !== terminal2) {
26611
+ entry2 = { terminal: terminal2, readAt: 0 };
26612
+ startups.delete(id2);
26613
+ while (startups.size >= 512) startups.delete(startups.keys().next().value);
26614
+ startups.set(id2, entry2);
26615
+ }
26616
+ const now = Date.now();
26617
+ if (now - entry2.readAt >= DIALOG_READ_MS) {
26618
+ entry2.readAt = now;
26619
+ const seen = await read().then(codexStartupStatus, () => entry2.status?.status);
26620
+ if (seen !== entry2.status?.status) entry2.status = seen ? { status: seen, seq: ++sequence } : void 0;
26621
+ }
26622
+ return entry2.status;
26623
+ }
26624
+ var DIALOG_READ_MS, EVENT_STATUS, entries, sequence, key, dialogs, startups;
26625
+ var init_pane_status = __esm({
26626
+ "src/bridge/pane-status.ts"() {
26627
+ "use strict";
26628
+ init_terminal_text();
26629
+ init_agent_hook_stores();
26630
+ init_claude_question_dialog();
26631
+ init_limits();
26632
+ init_protocol();
26633
+ init_terminal_choice();
26634
+ DIALOG_READ_MS = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3e3);
26635
+ EVENT_STATUS = {
26636
+ SessionStart: "idle",
26637
+ UserPromptSubmit: "working",
26638
+ PreToolUse: "working",
26639
+ PostToolUse: "working",
26640
+ PreCompact: "working",
26641
+ Stop: "idle",
26642
+ PermissionRequest: "blocked"
26643
+ };
26644
+ entries = /* @__PURE__ */ new Map();
26645
+ sequence = 0;
26646
+ key = (server, pane) => `${server}\0${pane}`;
26647
+ dialogs = /* @__PURE__ */ new Map();
26648
+ startups = /* @__PURE__ */ new Map();
26649
+ }
26650
+ });
26651
+
26061
26652
  // src/bridge/transcript-index.ts
26062
26653
  import { open as open2 } from "node:fs/promises";
26063
26654
  import { randomUUID as randomUUID5 } from "node:crypto";
@@ -26191,7 +26782,7 @@ var init_transcript_index = __esm({
26191
26782
 
26192
26783
  // src/bridge/codex-threads.ts
26193
26784
  import { createHash as createHash4 } from "node:crypto";
26194
- import { mkdir as mkdir4, open as open3, readFile as readFile4, stat as stat2 } from "node:fs/promises";
26785
+ import { mkdir as mkdir4, open as open3, readFile as readFile5, stat as stat2 } from "node:fs/promises";
26195
26786
  import path15 from "node:path";
26196
26787
  function materializedRoot() {
26197
26788
  return path15.join(bridgeRoot(), "codex-threads");
@@ -26213,7 +26804,7 @@ async function threadHealth(session, agentStatus2) {
26213
26804
  const stateFile = materializedPath(session) + ".state.json";
26214
26805
  let cursor, cursorMtime;
26215
26806
  try {
26216
- cursor = { lastOrdinal: -1, maxUpdated: -1, count: 0, done: {}, ...object2(JSON.parse(await readFile4(stateFile, "utf8"))) };
26807
+ cursor = { lastOrdinal: -1, maxUpdated: -1, count: 0, done: {}, ...object2(JSON.parse(await readFile5(stateFile, "utf8"))) };
26217
26808
  cursorMtime = (await stat2(stateFile)).mtimeMs;
26218
26809
  } catch {
26219
26810
  return { stalled: false };
@@ -26292,7 +26883,7 @@ async function materializeThread(session) {
26292
26883
  await mkdir4(materializedRoot(), { recursive: true, mode: 448 });
26293
26884
  let state = { lastOrdinal: -1, maxUpdated: -1, count: 0, done: {} };
26294
26885
  try {
26295
- state = { ...state, ...object2(JSON.parse(await readFile4(stateFile, "utf8"))) };
26886
+ state = { ...state, ...object2(JSON.parse(await readFile5(stateFile, "utf8"))) };
26296
26887
  } catch {
26297
26888
  }
26298
26889
  const fresh2 = state.count === 0;
@@ -26564,7 +27155,7 @@ var init_codex_threads = __esm({
26564
27155
 
26565
27156
  // src/bridge/locate.ts
26566
27157
  import { realpathSync as realpathSync2 } from "node:fs";
26567
- import { readFile as readFile5, stat as stat3 } from "node:fs/promises";
27158
+ import { readFile as readFile6, stat as stat3 } from "node:fs/promises";
26568
27159
  import { homedir as homedir4 } from "node:os";
26569
27160
  import path16 from "node:path";
26570
27161
  function realHome() {
@@ -26605,7 +27196,7 @@ async function locateProject(project, activity, env = process.env) {
26605
27196
  }
26606
27197
  }
26607
27198
  try {
26608
- const session = JSON.parse(await readFile5(path16.join(herdrRoot(), "session.json"), "utf8"));
27199
+ const session = JSON.parse(await readFile6(path16.join(herdrRoot(), "session.json"), "utf8"));
26609
27200
  for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
26610
27201
  const directory = JSON.parse(`"${match[1]}"`);
26611
27202
  if (path16.isAbsolute(directory) && namesProject(directory)) {
@@ -26615,7 +27206,7 @@ async function locateProject(project, activity, env = process.env) {
26615
27206
  } catch {
26616
27207
  }
26617
27208
  try {
26618
- const config4 = await readFile5(path16.join(phrenStoreRoot(env), project, "phren.project.yaml"), "utf8");
27209
+ const config4 = await readFile6(path16.join(phrenStoreRoot(env), project, "phren.project.yaml"), "utf8");
26619
27210
  const match = /^sourcePath:\s*(.+)$/m.exec(config4);
26620
27211
  if (match) await offer(match[1].trim().replace(/^['"]|['"]$/g, ""), "phren");
26621
27212
  } catch {
@@ -26792,7 +27383,7 @@ import { execFile } from "node:child_process";
26792
27383
  import { promisify } from "node:util";
26793
27384
  import { request } from "node:http";
26794
27385
  import { userInfo as userInfo2 } from "node:os";
26795
- import { readFile as readFile6, realpath, stat as stat4 } from "node:fs/promises";
27386
+ import { readFile as readFile7, realpath, stat as stat4 } from "node:fs/promises";
26796
27387
  import path17 from "node:path";
26797
27388
  function remainingGitTime(budget) {
26798
27389
  const remaining = budget.deadline - performance.now();
@@ -26999,7 +27590,7 @@ async function headFile(cwd) {
26999
27590
  const info = await stat4(dotGit).catch(() => void 0);
27000
27591
  if (info?.isDirectory()) return path17.join(dotGit, "HEAD");
27001
27592
  if (info?.isFile()) {
27002
- const match = /^gitdir:\s*(.+)$/m.exec(await readFile6(dotGit, "utf8").catch(() => ""));
27593
+ const match = /^gitdir:\s*(.+)$/m.exec(await readFile7(dotGit, "utf8").catch(() => ""));
27003
27594
  return match ? path17.join(path17.resolve(directory, match[1].trim()), "HEAD") : void 0;
27004
27595
  }
27005
27596
  const parent = path17.dirname(directory);
@@ -27011,7 +27602,7 @@ async function headFile(cwd) {
27011
27602
  async function headState(cwd) {
27012
27603
  const file4 = await headFile(cwd);
27013
27604
  if (!file4) return void 0;
27014
- const text5 = await readFile6(file4, "utf8").catch(() => void 0);
27605
+ const text5 = await readFile7(file4, "utf8").catch(() => void 0);
27015
27606
  return text5 === void 0 ? void 0 : `${file4}
27016
27607
  ${text5}`;
27017
27608
  }
@@ -27213,7 +27804,7 @@ var init_projects = __esm({
27213
27804
 
27214
27805
  // src/bridge/changes.ts
27215
27806
  import { execFile as execFile2 } from "node:child_process";
27216
- import { appendFile, copyFile, mkdir as mkdir5, mkdtemp, readdir as readdir2, readFile as readFile7, realpath as realpath2, rm as rm2, stat as stat5, unlink as unlink2, utimes } from "node:fs/promises";
27807
+ import { appendFile, copyFile, mkdir as mkdir5, mkdtemp, readdir as readdir2, readFile as readFile8, realpath as realpath2, rm as rm2, stat as stat5, unlink as unlink2, utimes } from "node:fs/promises";
27217
27808
  import path18 from "node:path";
27218
27809
  import { promisify as promisify2 } from "node:util";
27219
27810
  function capturesChanges(tool, input2) {
@@ -27585,7 +28176,7 @@ var init_changes = __esm({
27585
28176
  entry2.loaded ??= (async () => {
27586
28177
  const file4 = this.file(conversation);
27587
28178
  const size = (await stat5(file4).catch(() => void 0))?.size ?? 0;
27588
- const text5 = size <= 16777216 ? await readFile7(file4, "utf8").catch(() => "") : "";
28179
+ const text5 = size <= 16777216 ? await readFile8(file4, "utf8").catch(() => "") : "";
27589
28180
  for (const line of text5.split("\n")) {
27590
28181
  if (!line) continue;
27591
28182
  try {
@@ -27636,7 +28227,7 @@ var init_changes = __esm({
27636
28227
 
27637
28228
  // src/bridge/opencode-approvals.ts
27638
28229
  import { lstatSync, readFileSync as readFileSync9 } from "node:fs";
27639
- import { lstat as lstat2, opendir, readFile as readFile8 } from "node:fs/promises";
28230
+ import { lstat as lstat2, opendir, readFile as readFile9 } from "node:fs/promises";
27640
28231
  import path19 from "node:path";
27641
28232
  function opencodeApprovalFile(session, kind, store = phrenStoreRoot()) {
27642
28233
  if (!opencodeSession.test(session)) return void 0;
@@ -27673,7 +28264,7 @@ async function readOpencodeRequest(session, store) {
27673
28264
  try {
27674
28265
  const info = await lstat2(file4);
27675
28266
  if (!info.isFile() || info.size > 65536) return void 0;
27676
- return validRequest(object2(JSON.parse(await readFile8(file4, "utf8"))), session);
28267
+ return validRequest(object2(JSON.parse(await readFile9(file4, "utf8"))), session);
27677
28268
  } catch {
27678
28269
  return void 0;
27679
28270
  }
@@ -27691,7 +28282,7 @@ var init_opencode_approvals = __esm({
27691
28282
  // src/bridge/fanouts.ts
27692
28283
  import { execFile as execFile3 } from "node:child_process";
27693
28284
  import { createHash as createHash5 } from "node:crypto";
27694
- import { lstat as lstat3, mkdir as mkdir6, open as open4, readdir as readdir3, readFile as readFile9, realpath as realpath3, rename as rename3, rm as rm3, stat as stat6, writeFile as writeFile2 } from "node:fs/promises";
28285
+ import { lstat as lstat3, mkdir as mkdir6, open as open4, readdir as readdir3, readFile as readFile10, realpath as realpath3, rename as rename3, rm as rm3, stat as stat6, writeFile as writeFile2 } from "node:fs/promises";
27695
28286
  import { homedir as homedir5 } from "node:os";
27696
28287
  import path20 from "node:path";
27697
28288
  import { promisify as promisify3 } from "node:util";
@@ -27772,7 +28363,7 @@ async function readBlocked(jobRoot) {
27772
28363
  const file4 = await regularContainedFile(jobRoot, path20.join(jobRoot, "blocked.json"), MAX_BLOCKED_BYTES);
27773
28364
  if (file4) {
27774
28365
  try {
27775
- return blockedSchema.parse(JSON.parse(await readFile9(file4, "utf8")));
28366
+ return blockedSchema.parse(JSON.parse(await readFile10(file4, "utf8")));
27776
28367
  } catch {
27777
28368
  }
27778
28369
  }
@@ -27819,7 +28410,7 @@ async function fanoutChildren(parentProvider, parentSession, env = process.env,
27819
28410
  const manifestFile = await regularContainedFile(root, path20.join(directory, "manifest.json"), MAX_MANIFEST_BYTES);
27820
28411
  if (!manifestFile) continue;
27821
28412
  try {
27822
- const manifest = manifestSchema.parse(JSON.parse(await readFile9(manifestFile, "utf8")));
28413
+ const manifest = manifestSchema.parse(JSON.parse(await readFile10(manifestFile, "utf8")));
27823
28414
  if (manifest.id !== name || manifest.parent?.provider !== parentProvider || manifest.parent.session !== parentSession || manifest.parent.computer !== void 0 && parentComputer !== void 0 && manifest.parent.computer !== parentComputer) continue;
27824
28415
  const jobRoot = await realpath3(directory);
27825
28416
  if (!jobRoot.startsWith(root + path20.sep)) continue;
@@ -27863,7 +28454,7 @@ async function fanoutWorktrees(env = process.env) {
27863
28454
  const manifestFile = await regularContainedFile(root, path20.join(root, name, "manifest.json"), MAX_MANIFEST_BYTES);
27864
28455
  if (!manifestFile) continue;
27865
28456
  try {
27866
- const manifest = manifestSchema.parse(JSON.parse(await readFile9(manifestFile, "utf8")));
28457
+ const manifest = manifestSchema.parse(JSON.parse(await readFile10(manifestFile, "utf8")));
27867
28458
  if (manifest.id !== name) continue;
27868
28459
  jobs.push({ worktree: manifest.worktree, label: manifest.taskLabel, provider: manifest.provider, state: manifest.status });
27869
28460
  } catch {
@@ -27882,7 +28473,7 @@ async function blockedFanouts(env = process.env) {
27882
28473
  const manifestFile = await regularContainedFile(root, path20.join(jobRoot, "manifest.json"), MAX_MANIFEST_BYTES);
27883
28474
  if (!manifestFile) continue;
27884
28475
  try {
27885
- const manifest = manifestSchema.parse(JSON.parse(await readFile9(manifestFile, "utf8")));
28476
+ const manifest = manifestSchema.parse(JSON.parse(await readFile10(manifestFile, "utf8")));
27886
28477
  if (manifest.id !== name) continue;
27887
28478
  const value2 = await readBlocked(jobRoot);
27888
28479
  if (!value2) continue;
@@ -27908,7 +28499,7 @@ async function fanoutAsking(job, session, env = process.env) {
27908
28499
  const file4 = await regularContainedFile(root, path20.join(jobRoot, "manifest.json"), MAX_MANIFEST_BYTES);
27909
28500
  if (!file4) return void 0;
27910
28501
  try {
27911
- const manifest = manifestSchema.parse(JSON.parse(await readFile9(file4, "utf8")));
28502
+ const manifest = manifestSchema.parse(JSON.parse(await readFile10(file4, "utf8")));
27912
28503
  if (manifest.id !== job || manifest.provider !== "opencode" || manifest.session !== session || manifest.status !== "running" || !manifest.parent) return void 0;
27913
28504
  return { id: manifest.id, label: manifest.taskLabel, worktree: manifest.worktree, parent: manifest.parent };
27914
28505
  } catch {
@@ -27919,7 +28510,7 @@ async function jobManifest(root, directory) {
27919
28510
  const manifestFile = await regularContainedFile(root, path20.join(directory, "manifest.json"), MAX_MANIFEST_BYTES);
27920
28511
  if (!manifestFile) return void 0;
27921
28512
  try {
27922
- return manifestSchema.parse(JSON.parse(await readFile9(manifestFile, "utf8")));
28513
+ return manifestSchema.parse(JSON.parse(await readFile10(manifestFile, "utf8")));
27923
28514
  } catch {
27924
28515
  return void 0;
27925
28516
  }
@@ -27932,7 +28523,7 @@ async function archivedFinishedAt(directory) {
27932
28523
  const manifestFile = await lstat3(path20.join(directory, "manifest.json")).catch(() => void 0);
27933
28524
  if (manifestFile?.isFile() && !manifestFile.isSymbolicLink() && manifestFile.size <= MAX_MANIFEST_BYTES) {
27934
28525
  try {
27935
- const value2 = JSON.parse(await readFile9(path20.join(directory, "manifest.json"), "utf8"));
28526
+ const value2 = JSON.parse(await readFile10(path20.join(directory, "manifest.json"), "utf8"));
27936
28527
  const finished2 = typeof value2.finishedAt === "string" ? Date.parse(value2.finishedAt) : NaN;
27937
28528
  if (Number.isFinite(finished2)) return finished2;
27938
28529
  } catch {
@@ -28339,7 +28930,7 @@ var init_fanouts = __esm({
28339
28930
  });
28340
28931
 
28341
28932
  // src/bridge/transcript-claude.ts
28342
- import { readdir as readdir4, readFile as readFile10, realpath as realpath4, stat as stat7 } from "node:fs/promises";
28933
+ import { readdir as readdir4, readFile as readFile11, realpath as realpath4, stat as stat7 } from "node:fs/promises";
28343
28934
  import { createReadStream } from "node:fs";
28344
28935
  import { createInterface } from "node:readline";
28345
28936
  import { createHash as createHash6 } from "node:crypto";
@@ -28374,7 +28965,7 @@ async function claudeChildModel(file4) {
28374
28965
  return model;
28375
28966
  }
28376
28967
  async function claudeChildCheckout(file4) {
28377
- const meta3 = await readFile10(file4.slice(0, -".jsonl".length) + ".meta.json", "utf8").then((v2) => object2(JSON.parse(v2))).catch(() => ({}));
28968
+ const meta3 = await readFile11(file4.slice(0, -".jsonl".length) + ".meta.json", "utf8").then((v2) => object2(JSON.parse(v2))).catch(() => ({}));
28378
28969
  let cwd = typeof meta3.worktreePath === "string" && path21.isAbsolute(meta3.worktreePath) ? meta3.worktreePath : void 0;
28379
28970
  let branch = typeof meta3.worktreeBranch === "string" && meta3.worktreeBranch ? meta3.worktreeBranch.slice(0, 200) : void 0;
28380
28971
  if (!cwd) {
@@ -28543,7 +29134,7 @@ async function claudeChildRelations(file4, session, signature, rows2) {
28543
29134
  if (await claudeSkillFinished(childFile).catch(() => false)) launch2.state = "completed";
28544
29135
  else live = true;
28545
29136
  }
28546
- const meta3 = await readFile10(childFile.slice(0, -".jsonl".length) + ".meta.json", "utf8").then((v2) => object2(JSON.parse(v2))).catch(() => ({}));
29137
+ const meta3 = await readFile11(childFile.slice(0, -".jsonl".length) + ".meta.json", "utf8").then((v2) => object2(JSON.parse(v2))).catch(() => ({}));
28547
29138
  const model = await claudeChildModel(childFile).catch(() => void 0) ?? (typeof meta3.model === "string" && meta3.model ? meta3.model.slice(0, 200) : void 0);
28548
29139
  const checkout = await claudeChildCheckout(childFile).catch(() => ({}));
28549
29140
  relations.push({
@@ -28590,7 +29181,7 @@ async function claudeChildNames(root, entries2) {
28590
29181
  const names = /* @__PURE__ */ new Map();
28591
29182
  for (const entry2 of entries2) {
28592
29183
  if (!/^agent-[A-Za-z0-9._-]{1,128}\.meta\.json$/.test(entry2)) continue;
28593
- const meta3 = await readFile10(path21.join(root, entry2), "utf8").then((v2) => object2(JSON.parse(v2))).catch(() => ({}));
29184
+ const meta3 = await readFile11(path21.join(root, entry2), "utf8").then((v2) => object2(JSON.parse(v2))).catch(() => ({}));
28594
29185
  if (typeof meta3.name === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(meta3.name)) names.set(meta3.name, entry2.slice(0, -".meta.json".length) + ".jsonl");
28595
29186
  }
28596
29187
  return names;
@@ -28602,7 +29193,7 @@ async function claudeWorkflowAgents(root, session, workflow) {
28602
29193
  const info = await stat7(journal).catch(() => void 0);
28603
29194
  if (!info?.isFile() || info.size > 16 * 1024 * 1024) return [];
28604
29195
  const agents = /* @__PURE__ */ new Map();
28605
- for (const line of (await readFile10(journal, "utf8")).split("\n")) {
29196
+ for (const line of (await readFile11(journal, "utf8")).split("\n")) {
28606
29197
  try {
28607
29198
  const row = object2(JSON.parse(line)), id2 = String(row.agentId ?? "");
28608
29199
  if (!/^[A-Za-z0-9._-]{1,128}$/.test(id2)) continue;
@@ -28614,7 +29205,7 @@ async function claudeWorkflowAgents(root, session, workflow) {
28614
29205
  for (const [agentId, done] of agents) {
28615
29206
  const childFile = await realpath4(path21.join(directory, `agent-${agentId}.jsonl`)).catch(() => void 0);
28616
29207
  if (!childFile || !childFile.startsWith(directory + path21.sep) || !await claudeChildBelongsTo(childFile, session, agentId)) continue;
28617
- const meta3 = await readFile10(childFile.slice(0, -".jsonl".length) + ".meta.json", "utf8").then((v2) => object2(JSON.parse(v2))).catch(() => ({}));
29208
+ const meta3 = await readFile11(childFile.slice(0, -".jsonl".length) + ".meta.json", "utf8").then((v2) => object2(JSON.parse(v2))).catch(() => ({}));
28618
29209
  const model = await claudeChildModel(childFile).catch(() => void 0);
28619
29210
  const checkout = await claudeChildCheckout(childFile).catch(() => ({}));
28620
29211
  relations.push({
@@ -29060,7 +29651,7 @@ async function findCodeModeCall(rows2, line, callId) {
29060
29651
  }
29061
29652
  return void 0;
29062
29653
  }
29063
- function commandText(value2) {
29654
+ function commandText2(value2) {
29064
29655
  if (typeof value2 === "string") return value2;
29065
29656
  const parts = Array.isArray(value2) ? value2.filter((part) => typeof part === "string") : [];
29066
29657
  if (parts.length === 3 && ["-lc", "-c"].includes(parts[1]) && /(^|\/)(ba|z|da|fi|k)?sh$/.test(parts[0])) return parts[2];
@@ -29114,7 +29705,7 @@ function itemCall(raw, item) {
29114
29705
  const tail2 = text5.slice(-OUTPUT_TAIL2);
29115
29706
  const output2 = typeof item.exit_code === "number" ? JSON.stringify({ output: tail2, exit_code: item.exit_code }) : `${tail2}${tail2 && !tail2.endsWith("\n") ? "\n" : ""}[${status}]`;
29116
29707
  return row(
29117
- { type: "function_call", name: "exec_command", arguments: JSON.stringify({ cmd: commandText(item.command).slice(0, COMMAND), ...workdir ? { workdir } : {} }) },
29708
+ { type: "function_call", name: "exec_command", arguments: JSON.stringify({ cmd: commandText2(item.command).slice(0, COMMAND), ...workdir ? { workdir } : {} }) },
29118
29709
  { type: "function_call_output", output: output2 }
29119
29710
  );
29120
29711
  }
@@ -29897,7 +30488,7 @@ var init_harness_status = __esm({
29897
30488
  });
29898
30489
 
29899
30490
  // src/bridge/turn-records.ts
29900
- import { lstat as lstat5, readFile as readFile11 } from "node:fs/promises";
30491
+ import { lstat as lstat5, readFile as readFile12 } from "node:fs/promises";
29901
30492
  import path24 from "node:path";
29902
30493
  function truncateUtf8(value2, limit = TURN_REPLY_LIMIT) {
29903
30494
  const bytes = Buffer.from(value2);
@@ -29914,8 +30505,10 @@ function nextTurn(previous, event) {
29914
30505
  record4.seq++;
29915
30506
  record4.at = at2;
29916
30507
  if (event.dispatch && briefId.safeParse(event.dispatch).success) record4.dispatch ??= event.dispatch;
29917
- if (event.event === "SessionStart") record4.startedAt ??= at2;
29918
- else if (event.event === "UserPromptSubmit") record4.prompt = { seq: record4.seq, at: at2 };
30508
+ if (event.event === "SessionStart") {
30509
+ record4.startedAt ??= at2;
30510
+ if ((event.start === "resume" || event.start === "clear") && record4.stop?.background !== void 0) delete record4.stop.background;
30511
+ } else if (event.event === "UserPromptSubmit") record4.prompt = { seq: record4.seq, at: at2 };
29919
30512
  else {
29920
30513
  const reply = event.reply?.trim() ? truncateUtf8(event.reply.trim()) : void 0;
29921
30514
  record4.stop = {
@@ -29948,7 +30541,7 @@ async function readRecord(file4) {
29948
30541
  try {
29949
30542
  const info = await lstat5(file4);
29950
30543
  if (!info.isFile() || info.size > MAX_RECORD_BYTES) return void 0;
29951
- const parsed = turnRecordSchema.safeParse(JSON.parse(await readFile11(file4, "utf8")));
30544
+ const parsed = turnRecordSchema.safeParse(JSON.parse(await readFile12(file4, "utf8")));
29952
30545
  return parsed.success ? parsed.data : void 0;
29953
30546
  } catch {
29954
30547
  return void 0;
@@ -30033,6 +30626,15 @@ function recordedBackground(record4, finishedTasks, now = Date.now()) {
30033
30626
  if (phase.phase !== "ended" || !(now - Date.parse(phase.at) < BACKGROUND_STALE_MS)) return void 0;
30034
30627
  return backgroundLeft(phase.background, phase.at, finishedTasks) || void 0;
30035
30628
  }
30629
+ async function takesPrompt(server, pane, session, guards = {}, now = Date.now()) {
30630
+ const status = String(pane.agent_status);
30631
+ if (status === "idle" || status === "done") return true;
30632
+ if (status !== "working" || pane.agent !== "claude") return false;
30633
+ if (!recordedBackground(await paneRecord(server, pane, session), [], now) || guards.held?.()) return false;
30634
+ if (!guards.screen) return true;
30635
+ const screen = await guards.screen().catch(() => void 0);
30636
+ return screen !== void 0 && !screenDialog("claude", screen);
30637
+ }
30036
30638
  function awaitedShells(record4, final, now = Date.now()) {
30037
30639
  const phase = record4 ? turnPhase(record4) : void 0;
30038
30640
  if (phase?.phase === "ended") {
@@ -30109,6 +30711,7 @@ var init_session_activity = __esm({
30109
30711
  "src/bridge/session-activity.ts"() {
30110
30712
  "use strict";
30111
30713
  init_launch_brief();
30714
+ init_pane_status();
30112
30715
  init_protocol();
30113
30716
  init_turn_records();
30114
30717
  BACKGROUND_STALE_MS = 2 * 60 * 60 * 1e3;
@@ -30118,7 +30721,7 @@ var init_session_activity = __esm({
30118
30721
  });
30119
30722
 
30120
30723
  // src/bridge/tab-activity.ts
30121
- import { readFile as readFile12 } from "node:fs/promises";
30724
+ import { readFile as readFile13 } from "node:fs/promises";
30122
30725
  import path25 from "node:path";
30123
30726
  import { createHash as createHash8 } from "node:crypto";
30124
30727
  var digest, tabActivityKey, TabActivityStore;
@@ -30175,7 +30778,7 @@ var init_tab_activity = __esm({
30175
30778
  }
30176
30779
  async load() {
30177
30780
  if (!this.loaded) {
30178
- const saved = await readFile12(this.file, "utf8").then(JSON.parse).catch(() => ({}));
30781
+ const saved = await readFile13(this.file, "utf8").then(JSON.parse).catch(() => ({}));
30179
30782
  for (const [key4, value2] of Object.entries(object2(object2(saved).entries))) {
30180
30783
  const stamp2 = object2(value2);
30181
30784
  if (typeof stamp2.signature === "string" && typeof stamp2.lastChangedAt === "string" && Number.isFinite(Date.parse(stamp2.lastChangedAt))) {
@@ -34146,7 +34749,7 @@ var init_codex_binary = __esm({
34146
34749
 
34147
34750
  // src/bridge/codex-app-server.ts
34148
34751
  import { spawn as spawn2 } from "node:child_process";
34149
- import { mkdir as mkdir7, open as open8, readFile as readFile13, rm as rm4, stat as stat11 } from "node:fs/promises";
34752
+ import { mkdir as mkdir7, open as open8, readFile as readFile14, rm as rm4, stat as stat11 } from "node:fs/promises";
34150
34753
  import path28 from "node:path";
34151
34754
  async function spawnAppServer(options) {
34152
34755
  const env = { ...options.replaceEnv ? {} : process.env, ...options.env ?? {}, ...options.codexHome ? { CODEX_HOME: options.codexHome } : {} };
@@ -34180,7 +34783,7 @@ async function spawnAppServer(options) {
34180
34783
  stderr = (stderr + chunk.toString("utf8")).slice(-2e3);
34181
34784
  });
34182
34785
  const why = async () => {
34183
- const text5 = options.logFile ? (await readFile13(options.logFile, "utf8").catch(() => "")).slice(-2e3) : stderr;
34786
+ const text5 = options.logFile ? (await readFile14(options.logFile, "utf8").catch(() => "")).slice(-2e3) : stderr;
34184
34787
  return text5.trim() ? `: ${text5.trim().split("\n").slice(-3).join(" | ")}` : "";
34185
34788
  };
34186
34789
  const deadline = Date.now() + STARTUP_TIMEOUT_MS;
@@ -34484,7 +35087,7 @@ var init_codex_app_server = __esm({
34484
35087
  // src/bridge/codex-servers.ts
34485
35088
  import { randomBytes } from "node:crypto";
34486
35089
  import { readFileSync as readFileSync10 } from "node:fs";
34487
- import { mkdir as mkdir8, mkdtemp as mkdtemp2, readdir as readdir7, readFile as readFile14, rm as rm5 } from "node:fs/promises";
35090
+ import { mkdir as mkdir8, mkdtemp as mkdtemp2, readdir as readdir7, readFile as readFile15, rm as rm5 } from "node:fs/promises";
34488
35091
  import { tmpdir as tmpdir2 } from "node:os";
34489
35092
  import path29 from "node:path";
34490
35093
  function serviceCgroup(pid = "self") {
@@ -34517,7 +35120,7 @@ function codexServersRoot() {
34517
35120
  }
34518
35121
  async function readEntry(serverId) {
34519
35122
  try {
34520
- const parsed = entrySchema.safeParse(JSON.parse(await readFile14(path29.join(codexServersRoot(), serverId, "server.json"), "utf8")));
35123
+ const parsed = entrySchema.safeParse(JSON.parse(await readFile15(path29.join(codexServersRoot(), serverId, "server.json"), "utf8")));
34521
35124
  return parsed.success && parsed.data.id === serverId ? parsed.data : void 0;
34522
35125
  } catch {
34523
35126
  return void 0;
@@ -35094,636 +35697,45 @@ var init_codex_servers = __esm({
35094
35697
  const offClose = client.onClose?.(socketClosed);
35095
35698
  live.off = () => {
35096
35699
  off2();
35097
- offClose?.();
35098
- };
35099
- }
35100
- /** A server that ended on its own mid-turn: the returns loop reports the turn failed. */
35101
- markLost(entry2) {
35102
- if (!entry2.activeTurn || !entry2.threadId) return;
35103
- logger.warn("codex-servers", `The Codex server for ${entry2.server} ${entry2.pane} ended during turn ${entry2.activeTurn}`);
35104
- this.lost.set(paneKey(entry2.server, entry2.pane), {
35105
- threadId: entry2.threadId,
35106
- turn: entry2.activeTurn,
35107
- ...entry2.dispatchId ? { dispatchId: entry2.dispatchId } : {},
35108
- at: (/* @__PURE__ */ new Date()).toISOString()
35109
- });
35110
- }
35111
- async drop(live) {
35112
- live.off?.();
35113
- live.client?.close();
35114
- live.client = void 0;
35115
- this.live.delete(live.entry.id);
35116
- await this.forget(live.entry.id);
35117
- }
35118
- async forget(serverId) {
35119
- await rm5(path29.join(codexServersRoot(), codexServerId.parse(serverId)), { recursive: true, force: true }).catch(() => void 0);
35120
- }
35121
- /** One server's registry writes run in order, each with the entry as it is
35122
- * then, so an earlier write that finishes late never lands over a newer one. */
35123
- save(entry2) {
35124
- const file4 = path29.join(codexServersRoot(), entry2.id, "server.json");
35125
- const next = (this.saving.get(entry2.id) ?? Promise.resolve()).catch(() => void 0).then(() => atomic(file4, entrySchema.parse(entry2)));
35126
- this.saving.set(entry2.id, next);
35127
- void next.catch(() => void 0).finally(() => {
35128
- if (this.saving.get(entry2.id) === next) this.saving.delete(entry2.id);
35129
- });
35130
- return next;
35131
- }
35132
- };
35133
- paneKey = (server, pane) => `${server}
35134
- ${pane}`;
35135
- codexServers = new CodexServers();
35136
- }
35137
- });
35138
-
35139
- // src/terminal-text.ts
35140
- function stripTerminal(text5) {
35141
- return text5.replace(TERMINAL_CONTROL, "");
35142
- }
35143
- var TERMINAL_CONTROL;
35144
- var init_terminal_text = __esm({
35145
- "src/terminal-text.ts"() {
35146
- "use strict";
35147
- TERMINAL_CONTROL = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\r/g;
35148
- }
35149
- });
35150
-
35151
- // src/bridge/claude-question-dialog.ts
35152
- function claudeQuestionDialog(text5) {
35153
- const lines = text5.split(/\r?\n/);
35154
- let bar = -1;
35155
- for (let index2 = lines.length - 1; index2 >= 0; index2--) if (TAB_BAR.test(lines[index2]) && /[☐☒]/.test(lines[index2])) {
35156
- bar = index2;
35157
- break;
35158
- }
35159
- if (bar < 0) return void 0;
35160
- const tabs = [...lines[bar].matchAll(/[☐☒]\s+([^☐☒✔→]+?)(?=\s{2,}|\s*[☐☒✔→]|\s*$)/g)].map((match) => match[1].trim());
35161
- const body2 = lines.slice(bar + 1);
35162
- const content = body2.map((line) => line.replace(GUTTER, "$1").trim()).filter((line) => line && !/^─+$/.test(line));
35163
- if (content[0] === "Review your answers") {
35164
- if (!body2.some((line) => /^\s*❯?\s*1\.\s+Submit answers\s*$/.test(line))) return void 0;
35165
- const answers = [];
35166
- for (const line of content.slice(1)) {
35167
- if (/^Ready to submit/.test(line)) break;
35168
- const question2 = /^●\s+(.+)$/.exec(line), answer2 = /^→\s+(.+)$/.exec(line), last = answers[answers.length - 1];
35169
- if (question2) answers.push({ question: question2[1], answer: "" });
35170
- else if (answer2 && last) last.answer = answer2[1];
35171
- else if (last) {
35172
- if (last.answer) last.answer += " " + line;
35173
- else last.question += " " + line;
35174
- }
35175
- }
35176
- return { kind: "review", tabs, answers };
35177
- }
35178
- if (!content.some((line) => /Esc to cancel/.test(line))) return void 0;
35179
- const first = body2.findIndex((line) => ROW.test(line));
35180
- if (first < 0) return void 0;
35181
- const title2 = normalize(body2.slice(0, first).map((line) => line.replace(GUTTER, "$1")).filter((line) => line.trim()).join(" "));
35182
- const rows2 = [];
35183
- let cursor, chat = false;
35184
- for (const line of body2.slice(first)) {
35185
- const next = NEXT.exec(line);
35186
- if (next) {
35187
- if (next[1]) cursor = "next";
35188
- continue;
35189
- }
35190
- const match = ROW.exec(line);
35191
- if (!match) continue;
35192
- const number4 = Number(match[2]);
35193
- if (match[1]) cursor = number4;
35194
- if (/^Chat about this$/.test(match[4])) {
35195
- chat = true;
35196
- continue;
35197
- }
35198
- const answered = !match[3] && / ✔$/.test(match[4]);
35199
- rows2.push({
35200
- number: number4,
35201
- label: answered ? match[4].slice(0, -2).trim() : match[4],
35202
- answered,
35203
- cursor: !!match[1],
35204
- ...match[3] ? { checked: match[3] === "\u2714" } : {}
35205
- });
35206
- }
35207
- if (!title2 || !chat || rows2.length < 2) return void 0;
35208
- const other = rows2.pop();
35209
- return { kind: "question", tabs, title: title2, multiSelect: rows2.some((row) => row.checked !== void 0), options: rows2, other, ...cursor !== void 0 ? { cursor } : {} };
35210
- }
35211
- async function answerClaudeQuestionDialog(io, questions, answers, options = {}) {
35212
- const from = options.from ?? 0, submit = options.submit ?? true;
35213
- let sent = false;
35214
- const changed = (message) => refusal(message, sent);
35215
- const realKeys = io.keys.bind(io);
35216
- io = { ...io, keys: async (keys2) => {
35217
- sent = true;
35218
- await realKeys(keys2);
35219
- } };
35220
- const sleep5 = io.sleep ?? ((ms2) => new Promise((resolve17) => setTimeout(resolve17, ms2)));
35221
- const matches = (screen, index2) => screen?.kind === "question" && sameTitle(screen.title, questions[index2].question);
35222
- const settle2 = async (check2, ms2 = 2e3) => {
35223
- for (let waited = 0; ; waited += 120) {
35224
- const value2 = check2(claudeQuestionDialog(await io.read()));
35225
- if (value2 !== void 0 || waited >= ms2) return value2;
35226
- await sleep5(120);
35227
- }
35228
- };
35229
- const ANSWERED_MS = 8e3;
35230
- const initial = await settle2((screen) => screen);
35231
- if (!initial) throw changed("The terminal is not showing Claude's question.");
35232
- if (initial.tabs.length !== questions.length) throw changed("The terminal is asking a different set of questions.");
35233
- const reach = async (index2) => {
35234
- const screen = await settle2((value2) => value2);
35235
- if (screen?.kind === "question" && sameTitle(screen.title, questions[index2].question)) return screen;
35236
- const at2 = screen?.kind === "review" ? questions.length : screen?.kind === "question" ? questions.findIndex((question2) => sameTitle(screen.title, question2.question)) : -1;
35237
- if (at2 < 0) throw changed("The terminal is showing a different question.");
35238
- if (screen?.kind === "question" && screen.other && screen.cursor === screen.other.number) await io.keys(["up"]);
35239
- await io.keys(Array(Math.abs(index2 - at2)).fill(index2 > at2 ? "right" : "left"));
35240
- const moved = await settle2((value2) => matches(value2, index2) ? value2 : void 0);
35241
- if (!moved) throw changed("Could not move the terminal to the question being answered.");
35242
- return moved;
35243
- };
35244
- const leaves = (index2) => (value2) => value2 === void 0 ? "gone" : !matches(value2, index2) ? "moved" : void 0;
35245
- for (const [offset, answer2] of answers.entries()) {
35246
- const index2 = from + offset, question2 = questions[index2];
35247
- if (!question2) throw new BridgeError(400, "The answer names a question that was not asked.");
35248
- const typed = answer2.text?.trim() ?? "";
35249
- let screen = await reach(index2);
35250
- if (screen.multiSelect !== !!question2.multiSelect || screen.options.length !== question2.options.length || screen.options.some((row, position) => !sameLabel(row.label, question2.options[position].label))) {
35251
- throw changed("The terminal's options differ from the question being answered.");
35252
- }
35253
- if (!screen.multiSelect) {
35254
- if (typed) {
35255
- const other = screen.other;
35256
- await io.keys([String(other.number)]);
35257
- const focused = await settle2((value2) => matches(value2, index2) && value2.cursor === other.number ? value2 : void 0);
35258
- if (!focused) throw changed("Could not open the typed answer.");
35259
- await io.keys(typedKeys(typed));
35260
- const shown = await settle2((value2) => matches(value2, index2) && value2.other && normalize(value2.other.label).startsWith(normalize(typed).slice(0, 20)) ? value2 : void 0);
35261
- if (!shown) throw changed("The typed answer did not appear in the terminal.");
35262
- await io.keys(["enter"]);
35263
- } else {
35264
- await io.keys([String(screen.options[answer2.options[0]].number)]);
35700
+ offClose?.();
35701
+ };
35265
35702
  }
35266
- if (!await settle2(leaves(index2), ANSWERED_MS)) throw changed("The terminal did not take the answer.");
35267
- continue;
35268
- }
35269
- const rows2 = [...screen.options, ...screen.other ? [screen.other] : []];
35270
- for (const [position, row] of rows2.entries()) {
35271
- const wanted = position < screen.options.length ? answer2.options.includes(position) : !!row.checked && !!typed;
35272
- if (wanted === !!row.checked) continue;
35273
- const box = (value2) => matches(value2, index2) ? !!(position < value2.options.length ? value2.options[position] : value2.other)?.checked : void 0;
35274
- for (let attempt = 0; attempt < 2 && box(screen) !== wanted; attempt++) {
35275
- await io.keys([String(row.number)]);
35276
- screen = await settle2((value2) => box(value2) === wanted ? value2 : void 0, 1e3) ?? screen;
35703
+ /** A server that ended on its own mid-turn: the returns loop reports the turn failed. */
35704
+ markLost(entry2) {
35705
+ if (!entry2.activeTurn || !entry2.threadId) return;
35706
+ logger.warn("codex-servers", `The Codex server for ${entry2.server} ${entry2.pane} ended during turn ${entry2.activeTurn}`);
35707
+ this.lost.set(paneKey(entry2.server, entry2.pane), {
35708
+ threadId: entry2.threadId,
35709
+ turn: entry2.activeTurn,
35710
+ ...entry2.dispatchId ? { dispatchId: entry2.dispatchId } : {},
35711
+ at: (/* @__PURE__ */ new Date()).toISOString()
35712
+ });
35713
+ }
35714
+ async drop(live) {
35715
+ live.off?.();
35716
+ live.client?.close();
35717
+ live.client = void 0;
35718
+ this.live.delete(live.entry.id);
35719
+ await this.forget(live.entry.id);
35720
+ }
35721
+ async forget(serverId) {
35722
+ await rm5(path29.join(codexServersRoot(), codexServerId.parse(serverId)), { recursive: true, force: true }).catch(() => void 0);
35723
+ }
35724
+ /** One server's registry writes run in order, each with the entry as it is
35725
+ * then, so an earlier write that finishes late never lands over a newer one. */
35726
+ save(entry2) {
35727
+ const file4 = path29.join(codexServersRoot(), entry2.id, "server.json");
35728
+ const next = (this.saving.get(entry2.id) ?? Promise.resolve()).catch(() => void 0).then(() => atomic(file4, entrySchema.parse(entry2)));
35729
+ this.saving.set(entry2.id, next);
35730
+ void next.catch(() => void 0).finally(() => {
35731
+ if (this.saving.get(entry2.id) === next) this.saving.delete(entry2.id);
35732
+ });
35733
+ return next;
35277
35734
  }
35278
- if (box(screen) !== wanted) throw changed("The terminal's checkboxes did not match the answer.");
35279
- }
35280
- if (typed) {
35281
- const other = screen.other, cursor = typeof screen.cursor === "number" ? screen.cursor : 1;
35282
- if (cursor !== other.number) await io.keys(Array(Math.abs(other.number - cursor)).fill(other.number > cursor ? "down" : "up"));
35283
- if (!await settle2((value2) => matches(value2, index2) && value2.cursor === other.number ? value2 : void 0)) throw changed("Could not reach the typed answer row.");
35284
- await io.keys(typedKeys(typed));
35285
- const shown = await settle2((value2) => matches(value2, index2) && value2.other?.checked && normalize(value2.other.label).startsWith(normalize(typed).slice(0, 20)) ? value2 : void 0);
35286
- if (!shown) throw changed("The typed answer did not appear in the terminal.");
35287
- await io.keys(["tab"]);
35288
- if (!await settle2((value2) => matches(value2, index2) && value2.cursor === "next" ? value2 : void 0)) throw changed("Could not reach the question's Next row.");
35289
- await io.keys(["enter"]);
35290
- } else {
35291
- await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
35292
- }
35293
- if (!await settle2(leaves(index2), ANSWERED_MS)) throw changed("The terminal did not move past the question.");
35294
- }
35295
- if (!submit) return;
35296
- const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0, ANSWERED_MS);
35297
- if (review === "gone") return;
35298
- if (!review) throw changed("The terminal did not reach the review of the answers.");
35299
- if (review.answers.length !== questions.length || review.answers.some((row, position) => !sameTitle(normalize(row.question), questions[position].question) || !row.answer)) {
35300
- throw changed("Not every question has an answer in the terminal.");
35301
- }
35302
- await io.keys(["1"]);
35303
- if (await settle2((value2) => value2 === void 0 ? "gone" : void 0, ANSWERED_MS) !== "gone") throw changed("The terminal did not submit the answers.");
35304
- }
35305
- var TAB_BAR, ROW, NEXT, normalize, sameTitle, sameLabel, GUTTER, refusal, typedKeys;
35306
- var init_claude_question_dialog = __esm({
35307
- "src/bridge/claude-question-dialog.ts"() {
35308
- "use strict";
35309
- init_protocol();
35310
- TAB_BAR = /^\s*(?:←\s+)?((?:[☐☒]\s+\S[^☐☒✔→]*?\s*)+)(?:✔\s+Submit\s*)?(?:→\s*)?$/;
35311
- ROW = /^\s*(❯)?\s*(\d)\.\s+(?:\[([ ✔])\]\s+)?(.*?)\s*$/;
35312
- NEXT = /^\s*(❯)?\s+(?:Next|Submit)\s*$/;
35313
- normalize = (text5) => text5.replace(/\s+/g, " ").trim();
35314
- sameTitle = (shown, asked) => {
35315
- const want = normalize(asked);
35316
- if (shown === want) return true;
35317
- return shown.endsWith("\u2026") && shown.length > 200 && want.startsWith(shown.slice(0, -1).trimEnd());
35318
- };
35319
- sameLabel = (shown, asked) => {
35320
- const want = normalize(asked);
35321
- return shown === want || shown.length >= 30 && want.startsWith(shown);
35322
- };
35323
- GUTTER = /^(\s*)│(?: |$)/;
35324
- refusal = (message, sent) => sent ? new BridgeError(409, `${message} Some keys were already sent, so check the terminal before answering again, or cancel the question.`, { code: "question-unconfirmed" }) : new BridgeError(409, `${message} Nothing was sent; check the question and answer again, or cancel it.`, { code: "question-not-shown" });
35325
- typedKeys = (text5) => [...text5].map((character) => character === " " ? "space" : character);
35326
- }
35327
- });
35328
-
35329
- // src/bridge/terminal-choice.ts
35330
- function choiceKey(value2) {
35331
- if (typeof value2 !== "string") return void 0;
35332
- const text5 = value2.trim().toLowerCase();
35333
- if (!text5) return void 0;
35334
- if (text5 === "esc" || text5 === "escape") return "Escape";
35335
- if (text5 === "enter" || text5 === "return") return "Enter";
35336
- if (text5 === "up" || text5 === "down" || text5 === "tab") return text5[0].toUpperCase() + text5.slice(1);
35337
- return choiceKeys.has(text5) ? text5 : void 0;
35338
- }
35339
- function commandText2(value2) {
35340
- if (typeof value2 === "string" && value2.trim()) return value2.trim();
35341
- if (Array.isArray(value2)) {
35342
- const parts = value2.filter((part) => typeof part === "string" && !!part.trim());
35343
- if (parts.length) return parts.join(" ");
35344
- }
35345
- return void 0;
35346
- }
35347
- function optionLabel(value2) {
35348
- if (typeof value2 === "string") return value2.trim() || void 0;
35349
- const fields2 = object2(value2);
35350
- for (const key4 of ["label", "name", "title", "text", "value"]) {
35351
- if (typeof fields2[key4] === "string" && fields2[key4].trim()) return fields2[key4].trim();
35352
- }
35353
- return void 0;
35354
- }
35355
- function labeledOption(label2, key4) {
35356
- let resolved = choiceKey(key4);
35357
- const trailing = /^(.+?)\s*\(([A-Za-z0-9]+)\)\s*$/.exec(label2);
35358
- if (!resolved && trailing) resolved = choiceKey(trailing[2]);
35359
- return resolved ? { label: label2, key: resolved } : void 0;
35360
- }
35361
- function structuredOptions(value2) {
35362
- if (!Array.isArray(value2)) return [];
35363
- return value2.flatMap((item) => {
35364
- const label2 = optionLabel(item);
35365
- if (!label2) return [];
35366
- const fields2 = object2(item);
35367
- const key4 = ["key", "shortcut", "hotkey", "accelerator", "value"].map((name) => choiceKey(fields2[name])).find(Boolean);
35368
- const option = labeledOption(label2, key4);
35369
- return option ? [{ ...option, ...typeof fields2.description === "string" && fields2.description.trim() ? { description: fields2.description.trim().slice(0, 4e3) } : {} }] : [];
35370
- });
35371
- }
35372
- function numberedOptions(text5) {
35373
- return text5.split(/\r?\n/).flatMap((line) => {
35374
- const match = /^\s*([>❯›▸▶»•*])?\s*(\d+)[.)]\s+(.+?)\s*$/.exec(line);
35375
- if (!match) return [];
35376
- const columns = /^(.+?)\s{2,}(.+)$/.exec(match[3].trim());
35377
- const label2 = columns?.[1] ?? match[3].trim();
35378
- const description = columns?.[2].trim();
35379
- const trailing = /^(.+?)\s*\(([A-Za-z0-9]+)\)\s*$/.exec(label2);
35380
- const descriptionKey = description ? /^(.+?)\s*\(([A-Za-z0-9]+)\)\s*$/.exec(description) : null;
35381
- const labelKey = trailing ? choiceKey(trailing[2]) : void 0;
35382
- const endKey = descriptionKey ? choiceKey(descriptionKey[2]) : void 0;
35383
- const key4 = labelKey ?? endKey ?? choiceKey(match[2]);
35384
- return key4 ? [{
35385
- label: labelKey && trailing ? trailing[1].trim() : label2,
35386
- key: key4,
35387
- highlighted: !!match[1],
35388
- hasKey: !!(labelKey ?? endKey),
35389
- ...description ? { description: endKey && descriptionKey ? descriptionKey[1].trim() : description } : {}
35390
- }] : [];
35391
- });
35392
- }
35393
- function unframed(text5) {
35394
- let lines = text5.split(/\r?\n/);
35395
- const filled = lines.filter((line) => line.trim());
35396
- if (filled.length && filled.filter((line) => /┃\s*$/.test(line)).length * 2 > filled.length) {
35397
- lines = lines.map((line) => line.replace(/\s*┃\s*$/, ""));
35398
- }
35399
- if (!lines.some((line) => framed.test(line))) return lines.join("\n");
35400
- return lines.flatMap((line) => {
35401
- if (!framed.test(line)) return [border.test(line) ? "" : line];
35402
- let inner = line, match;
35403
- while (match = framed.exec(inner)) inner = match[1];
35404
- return border.test(inner) ? [] : [inner];
35405
- }).join("\n");
35406
- }
35407
- function visibleTerminalChoice(text5) {
35408
- text5 = unframed(text5);
35409
- const parsed = numberedOptions(text5);
35410
- const highlights = parsed.flatMap((option, index2) => option.highlighted ? [index2] : []);
35411
- const highlightedIndex = highlights.length === 1 ? highlights[0] : void 0;
35412
- if (parsed.some((option) => !option.hasKey) && highlightedIndex === void 0) return void 0;
35413
- const options = parsed.map(({ highlighted: _highlighted, ...option }) => option);
35414
- if (options.length < 2 || new Set(options.map((option) => option.key)).size !== options.length) return void 0;
35415
- const lines = text5.split(/\r?\n/);
35416
- const firstOption = lines.findIndex((line) => /^\s*[>❯›▸▶»•*]?\s*\d+[.)]\s+/.test(line));
35417
- const above = firstOption < 0 ? lines.slice(0, 1) : lines.slice(0, firstOption);
35418
- while (above.length && !above[above.length - 1].trim()) above.pop();
35419
- let start = above.length;
35420
- while (start > 0 && above[start - 1].trim()) start -= 1;
35421
- const menuStart = above.findIndex((line, index2) => index2 >= above.length - QUESTION_LINES && /^\s*(?:select|choose) (?:model|reasoning (?:level|effort))\b/i.test(line));
35422
- const question2 = above.slice(menuStart >= 0 ? menuStart : Math.max(start, above.length - QUESTION_LINES));
35423
- const title2 = question2.map((line) => line.trim()).filter((line) => line && !/^press enter\b/i.test(line)).join("\n").trim();
35424
- if (!title2) return void 0;
35425
- return {
35426
- title: title2.slice(0, 4e3),
35427
- options: options.slice(0, 12),
35428
- ...highlightedIndex !== void 0 ? { highlightedIndex } : {}
35429
- };
35430
- }
35431
- function opencodePermissionDialog(ansi) {
35432
- const raw = ansi.split(/\r?\n/);
35433
- const plain2 = raw.map((line) => stripTerminal(line).replace(/\r/g, ""));
35434
- const content = (line) => line.replace(/^\s*[┃│]?/, "");
35435
- let header2 = -1;
35436
- plain2.forEach((line, index2) => {
35437
- if (/^\s*△\s*Permission required\s*$/.test(content(line))) header2 = index2;
35438
- });
35439
- if (header2 < 0) return void 0;
35440
- const row = plain2.findIndex((line, index2) => index2 > header2 && OPENCODE_OPTIONS.every((label2) => line.includes(label2)));
35441
- if (row < 0 || row - header2 > 24) return void 0;
35442
- const body2 = plain2.slice(header2 + 1, row).map(content).filter((line) => line.trim() && !/^\s{24,}/.test(line)).map((line) => line.trim());
35443
- const [asks, ...rest] = body2;
35444
- const title2 = (asks?.replace(/^[←→]\s*/, "") || "Permission required").slice(0, 4e3);
35445
- const patterns = rest.indexOf("Patterns");
35446
- const details = patterns < 0 ? rest : [...rest.slice(0, patterns), ...rest.slice(patterns + 1).map((line) => line.replace(/^-\s+/, ""))];
35447
- const detail = details.join("\n").slice(0, 4e3);
35448
- const backgrounds = OPENCODE_OPTIONS.map((label2) => {
35449
- const at2 = raw[row].indexOf(label2);
35450
- if (at2 < 0) return void 0;
35451
- const before = [...raw[row].slice(0, at2).matchAll(/\x1b\[[0-9;]*48;2;(\d+;\d+;\d+)[0-9;]*m/g)];
35452
- return before.at(-1)?.[1];
35453
- });
35454
- const unique = backgrounds.flatMap((background, index2) => background !== void 0 && backgrounds.filter((other) => other === background).length === 1 ? [index2] : []);
35455
- const selected = unique.length === 1 && backgrounds.every((background) => background !== void 0) ? unique[0] : void 0;
35456
- return { choice: {
35457
- title: title2,
35458
- ...detail ? { body: detail } : {},
35459
- options: [{ label: "Allow once", key: "1", hasKey: false }, { label: "Reject", key: "Escape", hasKey: true }],
35460
- ...selected === 0 ? { highlightedIndex: 0 } : {}
35461
- }, ...selected !== void 0 ? { selected } : {} };
35462
- }
35463
- function passwordLine(text5) {
35464
- if (text5.includes("[sudo] password for")) return true;
35465
- const last = text5.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).pop() ?? "";
35466
- return /password[^\n]*:\s*$/i.test(last);
35467
- }
35468
- function numberedDialog(text5) {
35469
- text5 = unframed(text5);
35470
- const row = /^\s*[>❯›▸▶»•*]?\s*(\d+)\.\s+(.+?)\s*$/;
35471
- const lines = text5.split(/\r?\n/);
35472
- const first = lines.findIndex((line) => row.test(line));
35473
- if (first < 0) return void 0;
35474
- const title2 = lines.slice(0, first).map((line) => line.trim()).filter(Boolean).pop();
35475
- if (!title2) return void 0;
35476
- const options = [];
35477
- for (const line of lines.slice(first)) {
35478
- const match = row.exec(line);
35479
- if (!match) continue;
35480
- const label2 = match[2].split(" \xB7 ")[0].trim();
35481
- if (label2) options.push({ label: label2, key: match[1] });
35482
- }
35483
- if (options.length < 2) return void 0;
35484
- if (lines.some((line) => line.includes("Esc to cancel"))) options.push({ label: "Cancel", key: "Escape" });
35485
- return { title: title2.slice(0, 4e3), options: options.slice(0, 12) };
35486
- }
35487
- function terminalChoice(input2) {
35488
- const fields2 = object2(input2), command = commandText2(fields2.command ?? fields2.cmd);
35489
- let options = [fields2.options, fields2.choices, fields2.actions, fields2.answers].map(structuredOptions).find((list) => list.length >= 2) ?? [];
35490
- if (options.length < 2) {
35491
- const text5 = [fields2.question, fields2.description, fields2.justification, fields2.prompt, fields2.message, fields2.text, fields2.content, fields2.display].filter((value2) => typeof value2 === "string").join("\n");
35492
- const parsed = numberedOptions(text5);
35493
- if (parsed.length >= 2) options = parsed.map(({ highlighted: _highlighted, hasKey: _hasKey, ...option }) => option);
35494
- }
35495
- if (options.length < 2) return void 0;
35496
- const title2 = [fields2.question, fields2.description, fields2.justification, fields2.prompt].find((value2) => typeof value2 === "string" && !!value2.trim() && value2.trim() !== command);
35497
- if (!title2 && !command) return void 0;
35498
- return { ...title2 ? { title: String(title2).slice(0, 4e3) } : {}, ...command ? { body: command.slice(0, 4e3) } : {}, options: options.slice(0, 12) };
35499
- }
35500
- function permissionTitle(tool, input2) {
35501
- const fields2 = object2(input2);
35502
- const sentence = [fields2.question, fields2.prompt, fields2.description, fields2.justification, fields2.message].find((value2) => typeof value2 === "string" && !!value2.trim() && !/^[{[]/.test(value2.trim()));
35503
- if (sentence) return sentence.trim().slice(0, 4e3);
35504
- const mcp = /^mcp__([^_]+)__(.+)$/.exec(tool);
35505
- const server = mcp?.[1] ?? fields2.server;
35506
- const name = mcp?.[2] ?? fields2.tool;
35507
- if (typeof server === "string" && typeof name === "string") return `Allow the ${server} MCP server to run tool ${name}?`;
35508
- return tool && tool !== "action" ? `Allow ${tool}?` : void 0;
35509
- }
35510
- function samePermission(choice, title2, tool, input2) {
35511
- const text5 = choice.title?.toLowerCase() ?? "";
35512
- if (title2 && text5.includes(title2.toLowerCase())) return true;
35513
- const command = commandText2(object2(input2).command ?? object2(input2).cmd);
35514
- if (command && text5.includes(command.toLowerCase())) return true;
35515
- const name = tool.split("__").pop();
35516
- return !!name && name !== "action" && text5.includes(name.toLowerCase());
35517
- }
35518
- function permissionPrompt(tool, input2, terminalText = "") {
35519
- const title2 = permissionTitle(tool, input2);
35520
- const dialog = visibleTerminalChoice(terminalText);
35521
- const matched = dialog && samePermission(dialog, title2, tool, input2) ? dialog : void 0;
35522
- const sentence = matched?.title?.split("\n").find((line) => /\?\s*$/.test(line) && !/^[{[]/.test(line.trim()));
35523
- const choice = matched ? { ...matched, title: sentence ?? title2 } : terminalChoice(input2);
35524
- return {
35525
- title: choice?.title ?? title2,
35526
- details: JSON.stringify(input2 ?? {}, null, 2).slice(0, 32768),
35527
- ...choice ? { choice } : {},
35528
- terminalOnly: !choice
35529
- };
35530
- }
35531
- function terminalQuestions(input2) {
35532
- const questions = objects(object2(input2).questions).flatMap((raw) => {
35533
- const question2 = typeof raw.question === "string" ? raw.question.trim() : "";
35534
- if (!question2 || question2.length > 4e3) return [];
35535
- const options = objects(raw.options).flatMap((option) => {
35536
- const label2 = typeof option.label === "string" ? option.label.trim() : "";
35537
- if (!label2 || label2.length > 2e3) return [];
35538
- return [{
35539
- label: label2,
35540
- ...typeof option.description === "string" && option.description ? { description: option.description.slice(0, 4e3) } : {},
35541
- ...typeof option.preview === "string" && option.preview ? { preview: option.preview.slice(0, 4e3) } : {}
35542
- }];
35543
- });
35544
- if (!options.length || options.length > 12) return [];
35545
- return [{
35546
- question: question2,
35547
- ...typeof raw.header === "string" && raw.header ? { header: raw.header.slice(0, 200) } : {},
35548
- ...raw.multiSelect === true ? { multiSelect: true } : {},
35549
- options
35550
- }];
35551
- });
35552
- return questions.length >= 1 && questions.length <= 8 ? questions : void 0;
35553
- }
35554
- function questionChoice(questions, index2) {
35555
- const question2 = questions[index2];
35556
- if (!question2) return void 0;
35557
- const options = question2.options.map((option, position) => ({ label: option.label, key: String(position + 1) }));
35558
- if (question2.multiSelect) options.push({ label: "Done", key: "Enter" });
35559
- return { title: question2.question, options: options.slice(0, 12) };
35560
- }
35561
- function canonical(value2) {
35562
- if (Array.isArray(value2)) return "[" + value2.map(canonical).join(",") + "]";
35563
- if (value2 !== null && typeof value2 === "object") return "{" + Object.keys(value2).sort().map((k2) => JSON.stringify(k2) + ":" + canonical(value2[k2])).join(",") + "}";
35564
- return JSON.stringify(value2) ?? "null";
35565
- }
35566
- function answeredQuestionInput(tool, input2, updatedInput) {
35567
- if (tool !== "AskUserQuestion") throw new BridgeError(400, "Only a question can be answered with input.");
35568
- if (updatedInput === null || typeof updatedInput !== "object" || Array.isArray(updatedInput)) throw new BridgeError(400, "The answer is not an object.");
35569
- const raw = JSON.stringify(updatedInput);
35570
- if (Buffer.byteLength(raw) > 32768) throw new BridgeError(400, "The answer is too large.");
35571
- const parsed = questionAnswers.safeParse(updatedInput);
35572
- if (!parsed.success) throw new BridgeError(400, "The answer must add an answers object.");
35573
- const { answers, response, ...rest } = parsed.data;
35574
- if (canonical(rest) !== canonical(object2(input2))) throw new BridgeError(400, "The answer must keep the original questions.");
35575
- const asked = new Set(objects(object2(input2).questions).map((q2) => q2.question).filter((q2) => typeof q2 === "string"));
35576
- if (Object.keys(answers).some((q2) => !asked.has(q2))) throw new BridgeError(400, "The answer names a question that was not asked.");
35577
- return { ...object2(input2), answers, ...response === void 0 ? {} : { response } };
35578
- }
35579
- var choiceKeys, QUESTION_LINES, BAR, framed, border, OPENCODE_OPTIONS, questionAnswers;
35580
- var init_terminal_choice = __esm({
35581
- "src/bridge/terminal-choice.ts"() {
35582
- "use strict";
35583
- init_zod();
35584
- init_protocol();
35585
- init_terminal_text();
35586
- choiceKeys = /* @__PURE__ */ new Set(["Escape", "Enter", "Up", "Down", "Tab", "y", "n", "p", "1", "2", "3", "4", "5", "6", "7", "8", "9"]);
35587
- QUESTION_LINES = 12;
35588
- BAR = "\u2502\u2503\u2551";
35589
- framed = new RegExp(`^\\s*[${BAR}] ?(.*?)\\s*[${BAR}]\\s*$`);
35590
- border = /^[\s╭╮╰╯┌┐└┘├┤─━═│┃║]*$/;
35591
- OPENCODE_OPTIONS = ["Allow once", "Allow always", "Reject"];
35592
- questionAnswers = external_exports.looseObject({
35593
- answers: external_exports.record(external_exports.string().min(1).max(4e3), external_exports.union([external_exports.string().max(4e3), external_exports.array(external_exports.string().max(4e3)).min(1).max(24)])).refine((a) => Object.keys(a).length > 0),
35594
- response: external_exports.string().max(4e3).optional()
35595
- });
35596
- }
35597
- });
35598
-
35599
- // src/bridge/pane-status.ts
35600
- import { readFile as readFile15 } from "node:fs/promises";
35601
- function eventStatus(event) {
35602
- return typeof event === "string" && Object.hasOwn(EVENT_STATUS, event) ? EVENT_STATUS[event] : void 0;
35603
- }
35604
- function notePaneStatus(server, pane, terminal2, status, at2 = Date.now()) {
35605
- const id2 = key(server, pane), current2 = entries.get(id2);
35606
- if (current2 && current2.terminal === terminal2 && current2.status === status) {
35607
- current2.at = at2;
35608
- return { status, seq: current2.seq };
35609
- }
35610
- entries.delete(id2);
35611
- while (entries.size >= 512) entries.delete(entries.keys().next().value);
35612
- const entry2 = { terminal: terminal2, status, seq: ++sequence, at: at2 };
35613
- entries.set(id2, entry2);
35614
- return { status, seq: entry2.seq };
35615
- }
35616
- function settleBlockedPane(server, pane, minimumMs = 3e3) {
35617
- const id2 = key(server, pane), current2 = entries.get(id2), dialog = dialogs.get(id2);
35618
- if (current2?.status === "blocked" && Date.now() - current2.at >= minimumMs) notePaneStatus(server, pane, current2.terminal, "working");
35619
- if (dialog?.shown && Date.now() - dialog.shown.at >= minimumMs) {
35620
- dialog.shown = void 0;
35621
- dialog.cleared = ++sequence;
35622
- dialog.readAt = Date.now();
35623
- }
35624
- }
35625
- async function paneStatus(server, pane, terminal2) {
35626
- const current2 = entries.get(key(server, pane));
35627
- if (current2 && current2.terminal === terminal2) return { status: current2.status, seq: current2.seq };
35628
- if (current2) return void 0;
35629
- try {
35630
- const value2 = object2(JSON.parse(await readFile15(bindingPath(server, pane), "utf8")));
35631
- const status = eventStatus(value2.event);
35632
- if (value2.terminal !== terminal2 || !status) return void 0;
35633
- const at2 = Date.parse(String(value2.at));
35634
- return notePaneStatus(server, pane, terminal2, status, Number.isFinite(at2) ? at2 : Date.now());
35635
- } catch {
35636
- return void 0;
35637
- }
35638
- }
35639
- function claudeTeachAutoModeDialog(screen) {
35640
- return /Teach auto mode about your environment/i.test(stripTerminal(screen));
35641
- }
35642
- function screenDialog(agent, screen) {
35643
- const text5 = stripTerminal(screen);
35644
- if (agent === "opencode") return !!opencodePermissionDialog(screen);
35645
- if (agent === "codex" || agent === "copilot") return !!visibleTerminalChoice(text5);
35646
- if (agent === "claude" && (claudeQuestionDialog(text5) || claudeTeachAutoModeDialog(text5))) return true;
35647
- return /Esc to cancel/i.test(text5) && !!numberedDialog(text5);
35648
- }
35649
- async function dialogStatus(server, pane, terminal2, agent, base, read) {
35650
- const id2 = key(server, pane);
35651
- if (base?.status !== "working") {
35652
- dialogs.delete(id2);
35653
- return base;
35654
- }
35655
- let entry2 = dialogs.get(id2);
35656
- if (!entry2 || entry2.terminal !== terminal2) {
35657
- entry2 = { terminal: terminal2, readAt: 0 };
35658
- dialogs.delete(id2);
35659
- while (dialogs.size >= 512) dialogs.delete(dialogs.keys().next().value);
35660
- dialogs.set(id2, entry2);
35661
- }
35662
- const now = Date.now();
35663
- if (now - entry2.readAt >= DIALOG_READ_MS) {
35664
- entry2.readAt = now;
35665
- const shown = await read().then((screen) => screenDialog(agent, screen), () => void 0);
35666
- if (shown === true && !entry2.shown) entry2.shown = { at: now, seq: ++sequence };
35667
- else if (shown === false && entry2.shown) {
35668
- entry2.shown = void 0;
35669
- entry2.cleared = ++sequence;
35670
- }
35671
- }
35672
- if (entry2.shown) return { status: "blocked", seq: entry2.shown.seq };
35673
- return { status: base.status, seq: Math.max(base.seq, entry2.cleared ?? 0) };
35674
- }
35675
- function codexStartupStatus(screen) {
35676
- const text5 = stripTerminal(screen);
35677
- if (visibleTerminalChoice(text5)) return "blocked";
35678
- if (/\besc to interrupt\b/i.test(text5)) return "working";
35679
- const lines = text5.split(/\r?\n/).map((line) => line.trimEnd()).filter((line) => line.trim());
35680
- let composer = lines.length - 1;
35681
- while (composer >= 0 && !/^\u203a(?:\s|$)/.test(lines[composer])) composer -= 1;
35682
- return composer >= 0 && composer >= lines.length - 3 && lines.length - composer > 1 ? "idle" : void 0;
35683
- }
35684
- async function startupStatus(server, pane, terminal2, agent, read) {
35685
- if (agent !== "codex") return void 0;
35686
- const id2 = key(server, pane);
35687
- let entry2 = startups.get(id2);
35688
- if (!entry2 || entry2.terminal !== terminal2) {
35689
- entry2 = { terminal: terminal2, readAt: 0 };
35690
- startups.delete(id2);
35691
- while (startups.size >= 512) startups.delete(startups.keys().next().value);
35692
- startups.set(id2, entry2);
35693
- }
35694
- const now = Date.now();
35695
- if (now - entry2.readAt >= DIALOG_READ_MS) {
35696
- entry2.readAt = now;
35697
- const seen = await read().then(codexStartupStatus, () => entry2.status?.status);
35698
- if (seen !== entry2.status?.status) entry2.status = seen ? { status: seen, seq: ++sequence } : void 0;
35699
- }
35700
- return entry2.status;
35701
- }
35702
- var DIALOG_READ_MS, EVENT_STATUS, entries, sequence, key, dialogs, startups;
35703
- var init_pane_status = __esm({
35704
- "src/bridge/pane-status.ts"() {
35705
- "use strict";
35706
- init_terminal_text();
35707
- init_agent_hook_stores();
35708
- init_claude_question_dialog();
35709
- init_limits();
35710
- init_protocol();
35711
- init_terminal_choice();
35712
- DIALOG_READ_MS = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3e3);
35713
- EVENT_STATUS = {
35714
- SessionStart: "idle",
35715
- UserPromptSubmit: "working",
35716
- PreToolUse: "working",
35717
- PostToolUse: "working",
35718
- PreCompact: "working",
35719
- Stop: "idle",
35720
- PermissionRequest: "blocked"
35721
35735
  };
35722
- entries = /* @__PURE__ */ new Map();
35723
- sequence = 0;
35724
- key = (server, pane) => `${server}\0${pane}`;
35725
- dialogs = /* @__PURE__ */ new Map();
35726
- startups = /* @__PURE__ */ new Map();
35736
+ paneKey = (server, pane) => `${server}
35737
+ ${pane}`;
35738
+ codexServers = new CodexServers();
35727
35739
  }
35728
35740
  });
35729
35741
 
@@ -37103,7 +37115,7 @@ var init_package_metadata = __esm({
37103
37115
  __dirname = path35.dirname(fileURLToPath2(import.meta.url));
37104
37116
  ROOT = path35.join(__dirname, "..");
37105
37117
  PACKAGE_JSON_PATH = path35.join(ROOT, "package.json");
37106
- BUNDLED_VERSION = true ? "0.3.55" : "0.0.0";
37118
+ BUNDLED_VERSION = true ? "0.3.56" : "0.0.0";
37107
37119
  PACKAGE_JSON = readPackageJson();
37108
37120
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
37109
37121
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -41663,6 +41675,7 @@ var init_dispatch_returns = __esm({
41663
41675
  isLocal;
41664
41676
  snapshot;
41665
41677
  identity;
41678
+ takesPrompt;
41666
41679
  deliver;
41667
41680
  localArrival;
41668
41681
  now;
@@ -41688,6 +41701,7 @@ var init_dispatch_returns = __esm({
41688
41701
  this.isLocal = options.isLocal ?? ((computer) => isLocalComputer(computer));
41689
41702
  this.snapshot = options.snapshot ?? ((server) => sharedSnapshot(server, SNAPSHOT_AGE_MS));
41690
41703
  this.identity = options.identity ?? ((server, pane) => paneIdentity(server, pane));
41704
+ this.takesPrompt = options.takesPrompt ?? ((target2, pane) => takesPrompt(target2.server, pane, target2.session));
41691
41705
  this.deliver = options.deliver ?? ((target2, text5, deliveryId) => handOff({ target: target2, text: text5 }, { deliveryId, bypassConductor: true }));
41692
41706
  this.localArrival = options.localArrival ?? briefArrival;
41693
41707
  this.now = options.now ?? Date.now;
@@ -41922,13 +41936,17 @@ var init_dispatch_returns = __esm({
41922
41936
  } else {
41923
41937
  const pane = findPane(await this.snapshot(origin.server).catch(() => ({})), { ...origin, source: origin.agent });
41924
41938
  if (!pane || pane.terminal_id !== origin.terminal) continue;
41925
- if (!["idle", "done"].includes(String(pane.agent_status))) {
41939
+ if (!["idle", "done", "working"].includes(String(pane.agent_status))) {
41926
41940
  busy2 = true;
41927
41941
  continue;
41928
41942
  }
41929
41943
  const session = await this.identity(origin.server, pane).catch(() => void 0);
41930
41944
  const target2 = targetSchema.safeParse({ server: origin.server, workspace: origin.workspace, tab: origin.tab, pane: origin.pane, source: origin.agent, session });
41931
41945
  if (!target2.success) continue;
41946
+ if (!await this.takesPrompt(target2.data, pane).catch(() => false)) {
41947
+ busy2 = true;
41948
+ continue;
41949
+ }
41932
41950
  this.lastNotice.set(key4, this.now());
41933
41951
  const sent = await this.deliver(target2.data, noticeLine(receipts), noticeDeliveryId(receipts)).catch(() => ({ delivered: false }));
41934
41952
  if (!sent.delivered) continue;
@@ -58607,8 +58625,30 @@ var init_hand_off_queue = __esm({
58607
58625
  row.error = "The Hook restarted before delivery was confirmed.";
58608
58626
  await this.save(row);
58609
58627
  }
58628
+ await this.follow(row);
58610
58629
  return row;
58611
58630
  }
58631
+ /** An uncertain row takes the outcome its typed message came to: delivered once the agent's
58632
+ * UserPromptSubmit came, failed (with why) once the Hook knows the agent will not take it. A
58633
+ * failed row still turns delivered when the agent takes the message late. */
58634
+ async follow(row) {
58635
+ if (row.state !== "uncertain" && row.state !== "failed" || !this.options.delivery) return;
58636
+ const known2 = this.options.delivery(row.target, row.deliveryId);
58637
+ if (known2.state === "delivered") {
58638
+ row.state = "delivered";
58639
+ delete row.error;
58640
+ await this.save(row);
58641
+ } else if (known2.state === "failed" && row.state === "uncertain") {
58642
+ row.state = "failed";
58643
+ row.error = (known2.reason ?? "The agent did not take the message.").slice(0, 500);
58644
+ await this.save(row);
58645
+ }
58646
+ }
58647
+ /** Uncertain only while the agent may still take it: its typed message is held, not yet settled, and
58648
+ * in a pane whose hooks will settle it or typed only moments ago. Past that the sender hears "uncertain". */
58649
+ stillHeld(row) {
58650
+ return row.state === "uncertain" && !!this.options.held?.(row.target, row.deliveryId);
58651
+ }
58612
58652
  async rows() {
58613
58653
  const names = await readdir15(this.root).catch((error62) => {
58614
58654
  if (error62.code === "ENOENT") return [];
@@ -58713,7 +58753,8 @@ var init_hand_off_queue = __esm({
58713
58753
  await this.save(row);
58714
58754
  return;
58715
58755
  }
58716
- if (!["idle", "done"].includes(String(pane.agent_status))) return;
58756
+ if (!(this.options.ready ? await this.options.ready(row.target, pane).catch(() => false) : ["idle", "done"].includes(String(pane.agent_status)))) return;
58757
+ if (this.options.inFlight?.(row.target)) return;
58717
58758
  let typed = false;
58718
58759
  try {
58719
58760
  const result = await this.options.send(row.target, row.text, row.deliveryId, async () => {
@@ -58752,7 +58793,7 @@ var init_hand_off_queue = __esm({
58752
58793
  attempted.add(key4);
58753
58794
  await this.attempt(row);
58754
58795
  }
58755
- for (const row of rows2) if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state)) {
58796
+ for (const row of rows2) if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state) && !this.stillHeld(row)) {
58756
58797
  if (row.originComputer) {
58757
58798
  remote2.push(row);
58758
58799
  continue;
@@ -60297,6 +60338,7 @@ function matchingOffsets(buffer, start, record4) {
60297
60338
  for (let index2 = lines.length - 1; index2 >= 0; index2--) {
60298
60339
  const line = lines[index2];
60299
60340
  offset -= Buffer.byteLength(line) + (index2 < lines.length - 1 ? 1 : 0);
60341
+ if (!line.includes('"user') && !line.includes("queue-operation")) continue;
60300
60342
  let row;
60301
60343
  try {
60302
60344
  row = object2(JSON.parse(line));
@@ -60304,8 +60346,8 @@ function matchingOffsets(buffer, start, record4) {
60304
60346
  continue;
60305
60347
  }
60306
60348
  const stamp2 = Date.parse(String(row.timestamp ?? ""));
60307
- if (Number.isFinite(stamp2) && stamp2 < record4.at - 5e3) break;
60308
- if (userTexts(row).some((text5) => promptHash(text5) === record4.hash)) entries2.push({ offset, hook: row.type === "user" });
60349
+ if (Number.isFinite(stamp2) && stamp2 < record4.at - 5e3) continue;
60350
+ if (userTexts(row).some((text5) => promptHash(text5) === record4.hash)) entries2.push({ offset, hook: row.type === "user", ...Number.isFinite(stamp2) ? { at: stamp2 } : {} });
60309
60351
  }
60310
60352
  return entries2;
60311
60353
  }
@@ -60332,7 +60374,7 @@ function userTexts(row) {
60332
60374
  if (payload.type === "message" && payload.role === "user") blocks(payload.content);
60333
60375
  return texts;
60334
60376
  }
60335
- var DELIVERY_RETENTION_MS, DELIVERY_GIVE_UP_MS, MAX_RECORDS, LANDED_CHECK_MS, ENTRY_SLACK_MS, PICTURE_PATH_LINE, promptHash, recordSchema2, PromptDeliveries;
60377
+ var DELIVERY_RETENTION_MS, DELIVERY_GIVE_UP_MS, MAX_RECORDS, LANDED_CHECK_MS, ENTRY_SLACK_MS, HOOK_ROW_MS, IN_FLIGHT_MS, PICTURE_PATH_LINE, promptHash, recordSchema2, PromptDeliveries;
60336
60378
  var init_prompt_deliveries = __esm({
60337
60379
  "src/bridge/prompt-deliveries.ts"() {
60338
60380
  "use strict";
@@ -60344,6 +60386,8 @@ var init_prompt_deliveries = __esm({
60344
60386
  MAX_RECORDS = 512;
60345
60387
  LANDED_CHECK_MS = 3e3;
60346
60388
  ENTRY_SLACK_MS = 5e3;
60389
+ HOOK_ROW_MS = 3e4;
60390
+ IN_FLIGHT_MS = 45e3;
60347
60391
  PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
60348
60392
  promptHash = (text5) => createHash33("sha256").update(promptKey(text5)).digest("hex");
60349
60393
  recordSchema2 = external_exports.object({
@@ -60360,7 +60404,9 @@ var init_prompt_deliveries = __esm({
60360
60404
  settledAt: external_exports.number().optional(),
60361
60405
  stoppedAt: external_exports.number().optional(),
60362
60406
  /** The transcript entry (byte offset) that settled it, so no other message claims the same one. */
60363
- entry: external_exports.number().optional()
60407
+ entry: external_exports.number().optional(),
60408
+ /** Whether that entry is a user row (one its agent's UserPromptSubmit fired for), not a mid-turn queue removal. */
60409
+ entryHook: external_exports.boolean().optional()
60364
60410
  }).strict();
60365
60411
  PromptDeliveries = class _PromptDeliveries {
60366
60412
  constructor(file4, now = Date.now, landed = transcriptEntries) {
@@ -60385,6 +60431,8 @@ var init_prompt_deliveries = __esm({
60385
60431
  writing = Promise.resolve();
60386
60432
  /** Panes (server, pane, agent) that sent a UserPromptSubmit or Stop since the Hook started. */
60387
60433
  hookPanes = /* @__PURE__ */ new Set();
60434
+ /** When each pane (server, pane, agent) last sent a Stop since the Hook started. */
60435
+ lastStop = /* @__PURE__ */ new Map();
60388
60436
  paneKey(target2) {
60389
60437
  return [target2.server, target2.pane, target2.source].join("|");
60390
60438
  }
@@ -60468,6 +60516,19 @@ var init_prompt_deliveries = __esm({
60468
60516
  pending(target2, text5) {
60469
60517
  return !!this.open(target2, text5);
60470
60518
  }
60519
+ /** Whether `record` still holds its pane: open, and either young or in a pane whose hooks will settle it. */
60520
+ inFlight(record4) {
60521
+ return _PromptDeliveries.open(record4) && (this.now() - record4.at < IN_FLIGHT_MS || this.hookPanes.has(this.paneKey(record4)));
60522
+ }
60523
+ /** Whether any message typed into `target`'s pane is still waiting to be taken or refused. */
60524
+ holding(target2) {
60525
+ return this.records.some((record4) => this.samePane(record4, target2) && this.inFlight(record4));
60526
+ }
60527
+ /** Whether phone message `id` may still be taken: held by the agent, and in flight as `holding` counts it. */
60528
+ held(id2, target2) {
60529
+ const record4 = this.find(id2, target2);
60530
+ return !!record4 && this.inFlight(record4);
60531
+ }
60471
60532
  /** Wait again for a message `expect` reported pending, after a second Enter. */
60472
60533
  awaitLate(target2, text5, waitMs = 2500) {
60473
60534
  const record4 = this.open(target2, text5);
@@ -60568,8 +60629,9 @@ var init_prompt_deliveries = __esm({
60568
60629
  async submitted(target2, prompt) {
60569
60630
  const hash2 = promptHash(prompt);
60570
60631
  this.hookPanes.add(this.paneKey(target2));
60632
+ const stop = this.lastStop.get(this.paneKey(target2)) ?? -Infinity;
60571
60633
  const pick3 = () => {
60572
- const open30 = this.records.filter((record5) => record5.hash === hash2 && this.samePane(record5, target2) && record5.state !== "delivered");
60634
+ const open30 = this.records.filter((record5) => record5.hash === hash2 && this.samePane(record5, target2) && record5.state !== "delivered" && (record5.state !== "failed" || (record5.settledAt ?? record5.at) >= stop));
60573
60635
  return open30.find((entry3) => entry3.session === target2.session) ?? open30[0];
60574
60636
  };
60575
60637
  let record4 = pick3();
@@ -60584,26 +60646,27 @@ var init_prompt_deliveries = __esm({
60584
60646
  }
60585
60647
  record4 = pick3();
60586
60648
  if (!record4) return;
60587
- const claimed = new Set(this.records.filter((other) => other.hash === hash2 && this.samePane(other, target2) && other.session === target2.session && other.entry !== void 0).map((other) => other.entry));
60588
- if (!rows2 && !claimed.size) {
60649
+ const claimed = new Set(this.records.filter((other) => other.hash === hash2 && this.samePane(other, target2) && other.session === target2.session && other.entry !== void 0 && other.entryHook !== false).map((other) => other.entry));
60650
+ const free = rows2?.filter((row) => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
60651
+ if (!free && !claimed.size) {
60589
60652
  this.settle(record4, void 0, target2.session);
60590
60653
  this.save();
60591
60654
  return;
60592
60655
  }
60593
- if (!rows2?.length) {
60594
- record4.hookClaim = true;
60595
- record4.session = target2.session;
60656
+ if (!free) {
60657
+ if (!rows2?.length) {
60658
+ record4.hookClaim = true;
60659
+ record4.session = target2.session;
60660
+ }
60596
60661
  return;
60597
60662
  }
60598
- const free = rows2.filter((row) => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
60599
- if (!free) return;
60600
60663
  entry2 = free.offset;
60601
60664
  }
60602
- this.settle(record4, entry2, target2.session);
60665
+ this.settle(record4, entry2, target2.session, entry2 !== void 0 ? true : void 0);
60603
60666
  this.save();
60604
60667
  }
60605
60668
  /** Marks `record` delivered, with the transcript entry that settled it when known. */
60606
- settle(record4, entry2, session) {
60669
+ settle(record4, entry2, session, hook) {
60607
60670
  record4.state = "delivered";
60608
60671
  record4.settledAt = this.now();
60609
60672
  delete record4.reason;
@@ -60611,6 +60674,7 @@ var init_prompt_deliveries = __esm({
60611
60674
  delete record4.seenRow;
60612
60675
  if (session) record4.session = session;
60613
60676
  if (entry2 !== void 0) record4.entry = entry2;
60677
+ if (hook !== void 0) record4.entryHook = hook;
60614
60678
  this.release(record4, "delivered");
60615
60679
  }
60616
60680
  /** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
@@ -60628,10 +60692,22 @@ var init_prompt_deliveries = __esm({
60628
60692
  const key4 = [record4.hash, record4.server, record4.pane, record4.session, working].join("|");
60629
60693
  let free = pass.get(key4);
60630
60694
  if (!free) {
60631
- const found = (await this.landed(record4).catch(() => [])).sort((a, b) => a.offset - b.offset);
60695
+ const hooked = this.records.filter((other) => same2(other) && other.state === "delivered" && other.entry === void 0).sort((a, b) => (a.settledAt ?? a.at) - (b.settledAt ?? b.at));
60696
+ const from = Math.min(record4.at, ...hooked.map((other) => other.at));
60697
+ const found = (await this.landed({ ...record4, at: from }).catch(() => [])).sort((a, b) => a.offset - b.offset);
60632
60698
  const used = new Set(this.records.filter((other) => same2(other) && other.entry !== void 0).map((other) => other.entry));
60633
- let hooked = this.records.filter((other) => same2(other) && other.state === "delivered" && other.entry === void 0 && (other.settledAt ?? 0) >= record4.at - ENTRY_SLACK_MS).length;
60634
- const unclaimed = found.filter((entry3) => !used.has(entry3.offset)).filter((entry3) => !(entry3.hook && hooked-- > 0));
60699
+ let claimedRows = false;
60700
+ for (const other of hooked) {
60701
+ if (other.entry !== void 0) continue;
60702
+ const row = found.find((entry3) => entry3.hook && !used.has(entry3.offset) && (entry3.at === void 0 || entry3.at >= other.at - ENTRY_SLACK_MS && entry3.at <= (other.settledAt ?? other.at) + HOOK_ROW_MS));
60703
+ if (!row) continue;
60704
+ other.entry = row.offset;
60705
+ other.entryHook = true;
60706
+ used.add(row.offset);
60707
+ claimedRows = true;
60708
+ }
60709
+ if (claimedRows) this.save();
60710
+ const unclaimed = found.filter((entry3) => !used.has(entry3.offset) && (entry3.at === void 0 || entry3.at >= record4.at - ENTRY_SLACK_MS));
60635
60711
  if (working) {
60636
60712
  const row = unclaimed.find((entry3) => entry3.hook);
60637
60713
  const hookless = !this.hookPanes.has(this.paneKey(record4));
@@ -60645,12 +60721,14 @@ var init_prompt_deliveries = __esm({
60645
60721
  pass.set(key4, free);
60646
60722
  if (entry2 === void 0) return false;
60647
60723
  record4.entry = entry2.offset;
60724
+ record4.entryHook = entry2.hook;
60648
60725
  return true;
60649
60726
  }
60650
60727
  /** A turn in `target`'s pane ended: the agent now takes held input or never will. */
60651
60728
  stopped(target2) {
60652
60729
  const at2 = this.now();
60653
60730
  this.hookPanes.add(this.paneKey(target2));
60731
+ this.lastStop.set(this.paneKey(target2), at2);
60654
60732
  let marked = false;
60655
60733
  for (const record4 of this.records) if (this.samePane(record4, target2) && (record4.state === "typed" || record4.state === "queued") && record4.at < at2) {
60656
60734
  record4.stoppedAt = at2;
@@ -61445,6 +61523,7 @@ async function forwardHook(source, target2, event, value2, left3) {
61445
61523
  toolUseId: value2.tool_use_id,
61446
61524
  cwd: value2.cwd,
61447
61525
  ...event === "UserPromptSubmit" && typeof value2.prompt === "string" ? { prompt: value2.prompt.slice(0, 65536) } : {},
61526
+ ...event === "SessionStart" && typeof value2.source === "string" ? { startSource: value2.source.slice(0, 32) } : {},
61448
61527
  ...event === "Stop" ? stopFacts(value2) : {}
61449
61528
  });
61450
61529
  await new Promise((resolve17) => {
@@ -62031,6 +62110,7 @@ var init_agent_hooks = __esm({
62031
62110
  source: target2.source,
62032
62111
  session: target2.session,
62033
62112
  ...dispatch2 ? { dispatch: dispatch2 } : {},
62113
+ ...body2.event === "SessionStart" && typeof body2.startSource === "string" ? { start: body2.startSource } : {},
62034
62114
  ...typeof body2.background === "number" ? { background: body2.background } : {},
62035
62115
  ...typeof body2.reply === "string" ? { reply: body2.reply } : {},
62036
62116
  ...body2.event === "Stop" && typeof body2.cwd === "string" ? { cwd: body2.cwd } : {}
@@ -64661,6 +64741,12 @@ function claudeQuestionAnswer(data) {
64661
64741
  });
64662
64742
  return { questions: body2.questions.map((q2) => ({ question: q2.question, multiSelect: q2.multiSelect, options: q2.options.map((label2) => ({ label: label2 })) })), answers };
64663
64743
  }
64744
+ function promptGuards(agentHooks, target2) {
64745
+ return {
64746
+ held: () => !!(agentHooks.approval(target2) || agentHooks.terminalPrompt(target2) || agentHooks.servedQuestion(target2)),
64747
+ screen: () => terminalProvider().readScreen(target2.server, target2.pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2e3 })
64748
+ };
64749
+ }
64664
64750
  async function resubmitIfIdle(agentHooks, target2, text5) {
64665
64751
  const status = async () => {
64666
64752
  try {
@@ -64669,7 +64755,7 @@ async function resubmitIfIdle(agentHooks, target2, text5) {
64669
64755
  return "unknown";
64670
64756
  }
64671
64757
  };
64672
- if (await status() === "working") return "pending";
64758
+ if (await status() === "working") return await agentHooks.deliveries.awaitLate(target2, text5);
64673
64759
  const late = agentHooks.deliveries.awaitLate(target2, text5);
64674
64760
  await terminalProvider().sendKeys(target2.server, target2.pane, ["enter"]);
64675
64761
  const outcome = await late;
@@ -64863,7 +64949,7 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
64863
64949
  }
64864
64950
  if (url2.pathname === "/v1/prompt") {
64865
64951
  const status = String(pane.agent_status);
64866
- if (data.hookQueued === true && !["idle", "done"].includes(status)) throw new BridgeError(409, "The worker is busy; the hand-off remains queued.", { code: "hand-off-busy" });
64952
+ if (data.hookQueued === true && !await takesPrompt(target2.server, pane, target2.session, promptGuards(agentHooks, target2))) throw new BridgeError(409, "The worker is busy; the hand-off remains queued.", { code: "hand-off-busy" });
64867
64953
  if (status === "unknown" || ["blocked", "waiting"].includes(status) && (agentHooks.approval(target2) || agentHooks.terminalPrompt(target2) || agentHooks.servedQuestion(target2))) {
64868
64954
  throw new BridgeError(409, "This agent needs input in the terminal first.");
64869
64955
  }
@@ -64914,11 +65000,13 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
64914
65000
  deliveryId,
64915
65001
  typeof pane.terminal_id === "string" ? pane.terminal_id : void 0
64916
65002
  );
64917
- await typing();
65003
+ let typed = false;
64918
65004
  try {
65005
+ await typing();
65006
+ typed = true;
64919
65007
  await terminalProvider().prompt(target2.server, target2.pane, text5);
64920
65008
  } catch (error62) {
64921
- if (agentNotReady(error62)) refused2.abort();
65009
+ if (!typed || agentNotReady(error62) || herdrRefused(error62)) refused2.abort();
64922
65010
  throw error62;
64923
65011
  }
64924
65012
  return expected;
@@ -65110,7 +65198,7 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
65110
65198
  }
65111
65199
  return result;
65112
65200
  }
65113
- var ANSWER_KEYS, HERDR_KEYS, questionText, claudeQuestionBody, secretText, promptOnce;
65201
+ var ANSWER_KEYS, HERDR_KEYS, questionText, claudeQuestionBody, secretText, herdrRefused, promptOnce;
65114
65202
  var init_server_pane_routes = __esm({
65115
65203
  "src/bridge/server-pane-routes.ts"() {
65116
65204
  "use strict";
@@ -65129,6 +65217,7 @@ var init_server_pane_routes = __esm({
65129
65217
  init_model_switch();
65130
65218
  init_permission_mode();
65131
65219
  init_session_servers();
65220
+ init_session_activity();
65132
65221
  init_projects();
65133
65222
  init_protocol();
65134
65223
  init_transcripts();
@@ -65150,6 +65239,7 @@ var init_server_pane_routes = __esm({
65150
65239
  })).min(1).max(8)
65151
65240
  });
65152
65241
  secretText = external_exports.string().min(1).max(256).refine((t) => !/[\x00-\x1f\x7f]/.test(t));
65242
+ herdrRefused = (error62) => error62 instanceof BridgeError && error62.status === 409 && typeof error62.details?.herdrCode === "string";
65153
65243
  promptOnce = new PromptOnce();
65154
65244
  }
65155
65245
  });
@@ -79214,6 +79304,7 @@ async function serve(version2, options = {}) {
79214
79304
  const agentHooks = new AgentHooks(void 0, modules, path151.join(bridgeRoot(), "deliveries.json"));
79215
79305
  let succession;
79216
79306
  const returns = dispatches ? new DispatchReturns({
79307
+ takesPrompt: (target2, pane) => takesPrompt(target2.server, pane, target2.session, promptGuards(agentHooks, target2)),
79217
79308
  localComputer: { id: computerID2, name: hostname13() },
79218
79309
  forward: (origin, text5, deliveryId) => succession?.forward(origin, text5, deliveryId) ?? Promise.resolve(void 0),
79219
79310
  // Continue on another signed-in account when a Claude worker stops at its usage limit: opt-in, `phren config account-failover on`.
@@ -79269,7 +79360,11 @@ async function serve(version2, options = {}) {
79269
79360
  return pane && session ? { session, terminal: pane.terminal_id } : void 0;
79270
79361
  },
79271
79362
  notify: (target2, text5, deliveryId, computer) => handOff({ computer, target: target2, text: text5, deliveryId }, { notifySender: false, bypassConductor: true }),
79272
- send: sendPrompt
79363
+ send: sendPrompt,
79364
+ delivery: (target2, deliveryId) => agentHooks.deliveries.status(deliveryId, target2),
79365
+ inFlight: (target2) => agentHooks.deliveries.holding(target2),
79366
+ held: (target2, deliveryId) => agentHooks.deliveries.held(deliveryId, target2),
79367
+ ready: (target2, pane) => takesPrompt(target2.server, pane, target2.session, promptGuards(agentHooks, target2))
79273
79368
  }) : void 0;
79274
79369
  succession = dispatches ? new ConductorSuccessionService({
79275
79370
  root,
@@ -79643,6 +79738,7 @@ var init_server = __esm({
79643
79738
  init_harnesses();
79644
79739
  init_pane_accounts();
79645
79740
  init_turn_records();
79741
+ init_session_activity();
79646
79742
  init_launch_brief();
79647
79743
  init_conductor_role();
79648
79744
  init_terminal();
@@ -80072,7 +80168,7 @@ async function main() {
80072
80168
  return askpass2(args[1]);
80073
80169
  }
80074
80170
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
80075
- return runBridge2(args, "0.3.55");
80171
+ return runBridge2(args, "0.3.56");
80076
80172
  }
80077
80173
  main().then((code) => {
80078
80174
  process.exitCode = code;