@phren/cli 0.3.55 → 0.3.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/bridge/agent-hook-callback.js +1 -0
  2. package/dist/bridge/agent-hooks.js +1 -0
  3. package/dist/bridge/claude-suggestion.d.ts +9 -0
  4. package/dist/bridge/claude-suggestion.js +30 -4
  5. package/dist/bridge/dispatch-command.js +3 -3
  6. package/dist/bridge/dispatch-returns.d.ts +4 -0
  7. package/dist/bridge/dispatch-returns.js +10 -3
  8. package/dist/bridge/hand-off-queue.d.ts +21 -0
  9. package/dist/bridge/hand-off-queue.js +31 -2
  10. package/dist/bridge/hand-off.d.ts +1 -0
  11. package/dist/bridge/hand-off.js +5 -1
  12. package/dist/bridge/pair.d.ts +22 -0
  13. package/dist/bridge/pair.js +74 -1
  14. package/dist/bridge/prompt-deliveries.d.ts +21 -0
  15. package/dist/bridge/prompt-deliveries.js +140 -24
  16. package/dist/bridge/server-launch.d.ts +4 -0
  17. package/dist/bridge/server-launch.js +4 -1
  18. package/dist/bridge/server-pane-routes.d.ts +16 -0
  19. package/dist/bridge/server-pane-routes.js +132 -4
  20. package/dist/bridge/server-routes.d.ts +1 -0
  21. package/dist/bridge/server-routes.js +1 -1
  22. package/dist/bridge/server.js +9 -2
  23. package/dist/bridge/session-activity.d.ts +28 -0
  24. package/dist/bridge/session-activity.js +30 -0
  25. package/dist/bridge/session-move.d.ts +25 -0
  26. package/dist/bridge/session-move.js +128 -9
  27. package/dist/bridge/speech-transcribe.js +28 -3
  28. package/dist/bridge/terminal-herdr.js +28 -8
  29. package/dist/bridge/turn-records.d.ts +2 -0
  30. package/dist/bridge/turn-records.js +6 -1
  31. package/dist/bridge-hook.mjs +1900 -1524
  32. package/dist/cli-registry.js +2 -2
  33. package/dist/modules/registry.js +1 -1
  34. package/dist/tools/dispatch.js +3 -2
  35. package/package.json +1 -1
  36. package/starter/global/skills/conductor/SKILL.md +7 -0
@@ -24110,18 +24110,18 @@ async function setAccountLabel(id2, label2) {
24110
24110
  }
24111
24111
  function oauthIdentity(configFile) {
24112
24112
  try {
24113
- const stat32 = statSync2(configFile);
24114
- if (!stat32.isFile() || stat32.size > 16777216) return {};
24113
+ const stat33 = statSync2(configFile);
24114
+ if (!stat33.isFile() || stat33.size > 16777216) return {};
24115
24115
  const cached3 = identityCache.get(configFile);
24116
- if (cached3 && cached3.mtimeMs === stat32.mtimeMs && cached3.size === stat32.size) return cached3;
24116
+ if (cached3 && cached3.mtimeMs === stat33.mtimeMs && cached3.size === stat33.size) return cached3;
24117
24117
  const config4 = JSON.parse(readFileSync2(configFile, "utf8"));
24118
24118
  const account2 = config4.oauthAccount && typeof config4.oauthAccount === "object" ? config4.oauthAccount : {};
24119
24119
  const id2 = (value3) => typeof value3 === "string" && /^[A-Za-z0-9-]{1,64}$/.test(value3) ? value3 : void 0;
24120
24120
  const email3 = typeof account2.emailAddress === "string" && /^[^\s@]{1,64}@[^\s@]{1,190}$/.test(account2.emailAddress) ? account2.emailAddress : void 0;
24121
24121
  const fetched = typeof account2.profileFetchedAt === "number" ? subscriptionDate(Math.floor(account2.profileFetchedAt / 1e3)) : void 0;
24122
24122
  const value2 = {
24123
- mtimeMs: stat32.mtimeMs,
24124
- size: stat32.size,
24123
+ mtimeMs: stat33.mtimeMs,
24124
+ size: stat33.size,
24125
24125
  uuid: id2(account2.accountUuid),
24126
24126
  email: email3,
24127
24127
  organization: id2(account2.organizationUuid),
@@ -24327,8 +24327,8 @@ ${Date.now()}`, { flag: "wx" });
24327
24327
  } catch (err) {
24328
24328
  logger.debug("acquireFileLock", `lockWrite: ${errorMessage(err)}`);
24329
24329
  try {
24330
- const stat32 = fs3.statSync(lockPath);
24331
- if (Date.now() - stat32.mtimeMs > staleThreshold) {
24330
+ const stat33 = fs3.statSync(lockPath);
24331
+ if (Date.now() - stat33.mtimeMs > staleThreshold) {
24332
24332
  let ownerAlive = false;
24333
24333
  try {
24334
24334
  const content = fs3.readFileSync(lockPath, "utf-8");
@@ -25737,8 +25737,8 @@ function collectNativeMemoryFiles() {
25737
25737
  }
25738
25738
  function pushFileToken(parts, filePath) {
25739
25739
  try {
25740
- const stat32 = fs7.statSync(filePath);
25741
- if (stat32.isFile()) parts.push(`${filePath}:${stat32.mtimeMs}:${stat32.size}`);
25740
+ const stat33 = fs7.statSync(filePath);
25741
+ if (stat33.isFile()) parts.push(`${filePath}:${stat33.mtimeMs}:${stat33.size}`);
25742
25742
  } catch {
25743
25743
  parts.push(`${filePath}:missing`);
25744
25744
  }
@@ -25754,8 +25754,8 @@ function pushDirTokens(parts, dirPath) {
25754
25754
  pushDirTokens(parts, fullPath);
25755
25755
  continue;
25756
25756
  }
25757
- const stat32 = fs7.statSync(fullPath);
25758
- parts.push(`${fullPath}:${stat32.mtimeMs}:${stat32.size}`);
25757
+ const stat33 = fs7.statSync(fullPath);
25758
+ parts.push(`${fullPath}:${stat33.mtimeMs}:${stat33.size}`);
25759
25759
  }
25760
25760
  }
25761
25761
  function computePhrenLiveStateToken(phrenPath) {
@@ -25845,8 +25845,8 @@ function appendAuditLog(phrenPath, event, details) {
25845
25845
  fs8.mkdirSync(path13.dirname(logPath), { recursive: true });
25846
25846
  withFileLock(logPath, () => {
25847
25847
  fs8.appendFileSync(logPath, line);
25848
- const stat32 = fs8.statSync(logPath);
25849
- if (stat32.size > 1e6) {
25848
+ const stat33 = fs8.statSync(logPath);
25849
+ if (stat33.size > 1e6) {
25850
25850
  const content = fs8.readFileSync(logPath, "utf8");
25851
25851
  const lines = content.split("\n");
25852
25852
  fs8.writeFileSync(logPath, lines.slice(-MAX_LOG_LINES).join("\n") + "\n");
@@ -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;
@@ -35091,639 +35694,48 @@ var init_codex_servers = __esm({
35091
35694
  const socketClosed = () => {
35092
35695
  if (live.client === client) live.client = void 0;
35093
35696
  };
35094
- const offClose = client.onClose?.(socketClosed);
35095
- live.off = () => {
35096
- 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)]);
35697
+ const offClose = client.onClose?.(socketClosed);
35698
+ live.off = () => {
35699
+ off2();
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
 
@@ -35737,9 +35749,14 @@ function phrenCommandLine(args) {
35737
35749
  `herdr pane release-agent "$HERDR_PANE_ID" --source ${PHREN_REPORT_SOURCE} --agent phren >/dev/null 2>&1`
35738
35750
  ].join("; ");
35739
35751
  }
35740
- async function reportedPhren(server, pane) {
35752
+ async function typableAgent(server, pane, forPrompt) {
35741
35753
  const info = object2((await rpc(server, "pane.get", { pane_id: pane }).catch(() => ({}))).pane);
35742
- return info.agent === "phren";
35754
+ if (info.agent === "phren") return true;
35755
+ if (typeof info.agent !== "string" || !info.agent) return false;
35756
+ if (forPrompt && !["idle", "working", "done"].includes(String(info.agent_status))) return false;
35757
+ const processes = object2((await rpc(server, "pane.process_info", { pane_id: pane }).catch(() => ({}))).process_info);
35758
+ if (!Number.isSafeInteger(processes.foreground_process_group_id) || processes.foreground_process_group_id === processes.shell_pid) return false;
35759
+ return objects(processes.foreground_processes).some((p) => typeof p.cmdline === "string" && agentFromCommand(p.cmdline) === info.agent);
35743
35760
  }
35744
35761
  function unnamedAgent(error62) {
35745
35762
  return error62 instanceof BridgeError && error62.details?.herdrCode === "agent_not_ready" && /not an active named agent/.test(error62.message);
@@ -35820,7 +35837,7 @@ var init_terminal_herdr = __esm({
35820
35837
  try {
35821
35838
  await rpc(server, "agent.send_keys", { target: pane, keys: keys2 });
35822
35839
  } catch (error62) {
35823
- if (!unnamedAgent(error62) || !await reportedPhren(server, pane)) throw error62;
35840
+ if (!unnamedAgent(error62) || !await typableAgent(server, pane, false)) throw error62;
35824
35841
  await rpc(server, "pane.send_keys", { pane_id: pane, keys: keys2 });
35825
35842
  }
35826
35843
  },
@@ -35840,7 +35857,7 @@ var init_terminal_herdr = __esm({
35840
35857
  if (signal) await rpc(server, "agent.prompt", { target: pane, text: text5 }, signal);
35841
35858
  else await rpc(server, "agent.prompt", { target: pane, text: text5 });
35842
35859
  } catch (error62) {
35843
- if (!unnamedAgent(error62) || !await reportedPhren(server, pane)) throw error62;
35860
+ if (!unnamedAgent(error62) || !await typableAgent(server, pane, true)) throw error62;
35844
35861
  await rpc(server, "pane.send_text", { pane_id: pane, text: `\x1B[200~${text5}\x1B[201~` }, signal);
35845
35862
  await new Promise((resolve17) => setTimeout(resolve17, 150));
35846
35863
  await rpc(server, "pane.send_keys", { pane_id: pane, keys: ["Enter"] }, signal);
@@ -37039,9 +37056,9 @@ import * as path34 from "node:path";
37039
37056
  function gitDirectory(store) {
37040
37057
  const dotGit = path34.join(store, ".git");
37041
37058
  try {
37042
- const stat32 = fs15.statSync(dotGit);
37043
- if (stat32.isDirectory()) return dotGit;
37044
- if (!stat32.isFile()) return void 0;
37059
+ const stat33 = fs15.statSync(dotGit);
37060
+ if (stat33.isDirectory()) return dotGit;
37061
+ if (!stat33.isFile()) return void 0;
37045
37062
  const match = /^gitdir:\s*(.+)\s*$/i.exec(fs15.readFileSync(dotGit, "utf8"));
37046
37063
  if (!match) return void 0;
37047
37064
  return path34.resolve(store, match[1]);
@@ -37103,7 +37120,7 @@ var init_package_metadata = __esm({
37103
37120
  __dirname = path35.dirname(fileURLToPath2(import.meta.url));
37104
37121
  ROOT = path35.join(__dirname, "..");
37105
37122
  PACKAGE_JSON_PATH = path35.join(ROOT, "package.json");
37106
- BUNDLED_VERSION = true ? "0.3.55" : "0.0.0";
37123
+ BUNDLED_VERSION = true ? "0.3.57" : "0.0.0";
37107
37124
  PACKAGE_JSON = readPackageJson();
37108
37125
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
37109
37126
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -37521,6 +37538,7 @@ var init_registry = __esm({
37521
37538
  "moveNewChat",
37522
37539
  "moveConductor",
37523
37540
  "moveToComputer",
37541
+ "moveResume",
37524
37542
  "claudeAccountAdd",
37525
37543
  "workerRelocation"
37526
37544
  ],
@@ -37988,8 +38006,8 @@ function recordLookupEvents(phrenPath, events) {
37988
38006
  return;
37989
38007
  }
37990
38008
  try {
37991
- const stat32 = fs20.statSync(logPath);
37992
- if (stat32.size > ROTATE_BYTES) {
38009
+ const stat33 = fs20.statSync(logPath);
38010
+ if (stat33.size > ROTATE_BYTES) {
37993
38011
  const content = fs20.readFileSync(logPath, "utf8");
37994
38012
  const kept = content.split("\n").filter(Boolean).slice(-MAX_LOG_LINES2);
37995
38013
  fs20.writeFileSync(logPath, kept.join("\n") + "\n");
@@ -38286,8 +38304,8 @@ function appendHookErrorLog(phrenPath, event, message) {
38286
38304
  withFileLock(logPath, () => {
38287
38305
  fs21.appendFileSync(logPath, line);
38288
38306
  try {
38289
- const stat32 = fs21.statSync(logPath);
38290
- if (stat32.size > 2e5) {
38307
+ const stat33 = fs21.statSync(logPath);
38308
+ if (stat33.size > 2e5) {
38291
38309
  const content = fs21.readFileSync(logPath, "utf-8");
38292
38310
  const lines = content.split("\n").filter(Boolean);
38293
38311
  atomicWriteText(logPath, lines.slice(-HOOK_ERROR_LOG_MAX_LINES).join("\n") + "\n");
@@ -40853,7 +40871,13 @@ async function moveSession(input2, options = {}) {
40853
40871
  const target2 = data.target ?? (data.session ? (await targetFromOverview(request10, data.session, peer?.server)).target : await paneTarget(request10, data.pane, peer?.server));
40854
40872
  if (peer && target2.server !== peer.server) throw new BridgeError(400, "The target belongs to a different Herdr server on that computer.");
40855
40873
  const to = { harness: data.harness, ...data.account ? { account: data.account } : {}, ...data.model ? { model: data.model } : {}, ...data.effort ? { effort: data.effort } : {} };
40856
- move = object2((await request10("/v1/sessions/move", { target: target2, to: moveToSchema.parse(to), ...options.agent ? { origin: "agent" } : {}, ...data.id ? { id: data.id } : {} })).move);
40874
+ move = object2((await request10("/v1/sessions/move", {
40875
+ target: target2,
40876
+ to: moveToSchema.parse(to),
40877
+ ...options.agent ? { origin: "agent" } : {},
40878
+ ...data.id ? { id: data.id } : {},
40879
+ ...data.resume ? { continuation: "resume" } : {}
40880
+ })).move);
40857
40881
  if (data.wait !== false && typeof move.id === "string") {
40858
40882
  const until = Date.now() + (options.waitMs ?? MOVE_WAIT_MS);
40859
40883
  while (!settled3(move) && Date.now() < until) {
@@ -41017,12 +41041,14 @@ var init_hand_off = __esm({
41017
41041
  account: moveToSchema.shape.account,
41018
41042
  model: moveToSchema.shape.model,
41019
41043
  effort: moveToSchema.shape.effort,
41044
+ resume: external_exports.boolean().optional().describe("Switch a Claude conversation to another Claude account on this computer without a hand-off: the old agent exits, its transcript is copied into that account's home and the same conversation resumes there, so an account at its usage limit can still switch. Needs harness claude and account."),
41020
41045
  id: external_exports.string().uuid().optional().describe("Move id: keep it on a retry, or pass it with status:true to read where the move is."),
41021
41046
  status: external_exports.boolean().optional().describe("Read the move's state without starting one; requires id."),
41022
41047
  wait: external_exports.boolean().optional().describe("Wait (up to five minutes) until the move finished or failed. Defaults to true.")
41023
41048
  }).strict().superRefine((value2, context3) => {
41024
41049
  if (!value2.status && [value2.target, value2.session, value2.pane].filter((item) => item !== void 0).length !== 1) context3.addIssue({ code: "custom", message: "Provide exactly one of target, session or pane." });
41025
41050
  if (value2.status && !value2.id) context3.addIssue({ code: "custom", message: "A status query requires id." });
41051
+ if (value2.resume && (value2.harness !== "claude" || !value2.account || value2.computer)) context3.addIssue({ code: "custom", message: "resume switches a Claude conversation on its own computer to another account: harness claude, an account, and no computer." });
41026
41052
  });
41027
41053
  MOVE_WAIT_MS = 5 * 6e4;
41028
41054
  CLAUDE_USAGE_ROUTE = "/v1/usage?sources=claude&accounts=all";
@@ -41663,6 +41689,7 @@ var init_dispatch_returns = __esm({
41663
41689
  isLocal;
41664
41690
  snapshot;
41665
41691
  identity;
41692
+ takesPrompt;
41666
41693
  deliver;
41667
41694
  localArrival;
41668
41695
  now;
@@ -41688,6 +41715,7 @@ var init_dispatch_returns = __esm({
41688
41715
  this.isLocal = options.isLocal ?? ((computer) => isLocalComputer(computer));
41689
41716
  this.snapshot = options.snapshot ?? ((server) => sharedSnapshot(server, SNAPSHOT_AGE_MS));
41690
41717
  this.identity = options.identity ?? ((server, pane) => paneIdentity(server, pane));
41718
+ this.takesPrompt = options.takesPrompt ?? ((target2, pane) => takesPrompt(target2.server, pane, target2.session));
41691
41719
  this.deliver = options.deliver ?? ((target2, text5, deliveryId) => handOff({ target: target2, text: text5 }, { deliveryId, bypassConductor: true }));
41692
41720
  this.localArrival = options.localArrival ?? briefArrival;
41693
41721
  this.now = options.now ?? Date.now;
@@ -41922,13 +41950,17 @@ var init_dispatch_returns = __esm({
41922
41950
  } else {
41923
41951
  const pane = findPane(await this.snapshot(origin.server).catch(() => ({})), { ...origin, source: origin.agent });
41924
41952
  if (!pane || pane.terminal_id !== origin.terminal) continue;
41925
- if (!["idle", "done"].includes(String(pane.agent_status))) {
41953
+ if (!["idle", "done", "working"].includes(String(pane.agent_status))) {
41926
41954
  busy2 = true;
41927
41955
  continue;
41928
41956
  }
41929
41957
  const session = await this.identity(origin.server, pane).catch(() => void 0);
41930
41958
  const target2 = targetSchema.safeParse({ server: origin.server, workspace: origin.workspace, tab: origin.tab, pane: origin.pane, source: origin.agent, session });
41931
41959
  if (!target2.success) continue;
41960
+ if (!await this.takesPrompt(target2.data, pane).catch(() => false)) {
41961
+ busy2 = true;
41962
+ continue;
41963
+ }
41932
41964
  this.lastNotice.set(key4, this.now());
41933
41965
  const sent = await this.deliver(target2.data, noticeLine(receipts), noticeDeliveryId(receipts)).catch(() => ({ delivered: false }));
41934
41966
  if (!sent.delivered) continue;
@@ -43708,8 +43740,8 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
43708
43740
  } catch (e) {
43709
43741
  if (e.code === "EEXIST") {
43710
43742
  try {
43711
- const stat32 = fs27.statSync(lockFile);
43712
- if (Date.now() - stat32.mtimeMs < STALE_LOCK_MS) {
43743
+ const stat33 = fs27.statSync(lockFile);
43744
+ if (Date.now() - stat33.mtimeMs < STALE_LOCK_MS) {
43713
43745
  return phrenErr("Consolidation already running", PhrenError.LOCK_TIMEOUT);
43714
43746
  }
43715
43747
  tryUnlink(lockFile);
@@ -48038,8 +48070,8 @@ import * as path73 from "path";
48038
48070
  function gitDir(store) {
48039
48071
  const dotGit = path73.join(store, ".git");
48040
48072
  try {
48041
- const stat32 = fs40.statSync(dotGit);
48042
- if (stat32.isDirectory()) return dotGit;
48073
+ const stat33 = fs40.statSync(dotGit);
48074
+ if (stat33.isDirectory()) return dotGit;
48043
48075
  const match = /^gitdir:\s*(.+)\s*$/i.exec(fs40.readFileSync(dotGit, "utf8"));
48044
48076
  return match ? path73.resolve(store, match[1]) : void 0;
48045
48077
  } catch {
@@ -48847,8 +48879,8 @@ async function removeClaudeCredit(home, id2) {
48847
48879
  }
48848
48880
  function readLedger(file4) {
48849
48881
  try {
48850
- const stat32 = statSync20(file4);
48851
- if (!stat32.isFile() || stat32.size > 1048576) return {};
48882
+ const stat33 = statSync20(file4);
48883
+ if (!stat33.isFile() || stat33.size > 1048576) return {};
48852
48884
  const sessions = object2(object2(JSON.parse(readFileSync41(file4, "utf8"))).sessions);
48853
48885
  return Object.fromEntries(Object.entries(sessions).flatMap(([id2, raw]) => {
48854
48886
  const item = object2(raw);
@@ -48876,8 +48908,8 @@ function homeSessionCosts(home) {
48876
48908
  const sessions = readLedger(costLedgerFile(home));
48877
48909
  let projects = {};
48878
48910
  try {
48879
- const stat32 = statSync20(home.configFile);
48880
- if (stat32.isFile() && stat32.size <= 16777216) projects = object2(object2(JSON.parse(readFileSync41(home.configFile, "utf8"))).projects);
48911
+ const stat33 = statSync20(home.configFile);
48912
+ if (stat33.isFile() && stat33.size <= 16777216) projects = object2(object2(JSON.parse(readFileSync41(home.configFile, "utf8"))).projects);
48881
48913
  } catch {
48882
48914
  }
48883
48915
  const wanted = /* @__PURE__ */ new Map();
@@ -48908,8 +48940,8 @@ function transcriptTimes(root, wanted) {
48908
48940
  for (const id2 of wanted) {
48909
48941
  if (found.has(id2)) continue;
48910
48942
  try {
48911
- const stat32 = statSync20(path78.join(root, folder, `${id2}.jsonl`));
48912
- const time3 = stat32.birthtimeMs > 0 ? stat32.birthtimeMs : stat32.mtimeMs;
48943
+ const stat33 = statSync20(path78.join(root, folder, `${id2}.jsonl`));
48944
+ const time3 = stat33.birthtimeMs > 0 ? stat33.birthtimeMs : stat33.mtimeMs;
48913
48945
  found.set(id2, new Date(time3).toISOString());
48914
48946
  } catch {
48915
48947
  }
@@ -49039,8 +49071,8 @@ async function readCodexSubscription(file4 = path79.join(codexHome(), "auth.json
49039
49071
  try {
49040
49072
  const handle = await open11(file4, "r");
49041
49073
  try {
49042
- const stat32 = await handle.stat();
49043
- if (!stat32.isFile() || stat32.size > 131072) return void 0;
49074
+ const stat33 = await handle.stat();
49075
+ if (!stat33.isFile() || stat33.size > 131072) return void 0;
49044
49076
  return codexSubscription(object2(object2(JSON.parse(await handle.readFile("utf8"))).tokens).id_token, now);
49045
49077
  } finally {
49046
49078
  await handle.close();
@@ -49080,8 +49112,8 @@ async function readOpenRouterKey() {
49080
49112
  try {
49081
49113
  const handle = await open11(openCodeAuthFile(), "r");
49082
49114
  try {
49083
- const stat32 = await handle.stat();
49084
- if (!stat32.isFile() || stat32.size > 65536) return void 0;
49115
+ const stat33 = await handle.stat();
49116
+ if (!stat33.isFile() || stat33.size > 65536) return void 0;
49085
49117
  const key4 = object2(object2(JSON.parse(await handle.readFile("utf8"))).openrouter).key;
49086
49118
  return typeof key4 === "string" && key4.length >= 16 && key4.length <= 4096 && !/[\x00-\x1f\x7f]/.test(key4) ? key4 : void 0;
49087
49119
  } finally {
@@ -49797,8 +49829,8 @@ var init_usage = __esm({
49797
49829
  try {
49798
49830
  const handle = await open11(claudeFile(home), "r");
49799
49831
  try {
49800
- const stat32 = await handle.stat();
49801
- if (!stat32.isFile() || stat32.size > 16384) throw new Error("Invalid usage snapshot");
49832
+ const stat33 = await handle.stat();
49833
+ if (!stat33.isFile() || stat33.size > 16384) throw new Error("Invalid usage snapshot");
49802
49834
  const saved = object2(JSON.parse(await handle.readFile("utf8")));
49803
49835
  const date5 = new Date(String(saved.updatedAt));
49804
49836
  if (!Number.isFinite(date5.getTime()) || date5.getTime() > this.now() + 6e4) throw new Error("Invalid usage timestamp");
@@ -49811,8 +49843,8 @@ var init_usage = __esm({
49811
49843
  try {
49812
49844
  const handle = await open11(home.configFile, "r");
49813
49845
  try {
49814
- const stat32 = await handle.stat();
49815
- if (!stat32.isFile() || stat32.size > 16777216) throw new Error("Invalid Claude config");
49846
+ const stat33 = await handle.stat();
49847
+ if (!stat33.isFile() || stat33.size > 16777216) throw new Error("Invalid Claude config");
49816
49848
  const scoped = claudeScopedWindows(JSON.parse(await handle.readFile("utf8")), new Date(this.now())).filter((entry2) => !claude2.windows.some((existing) => existing.id === entry2.id));
49817
49849
  if (scoped.length) claude2 = { ...claude2, windows: [...claude2.windows, ...scoped], message: void 0 };
49818
49850
  } finally {
@@ -53122,6 +53154,7 @@ __export(session_move_exports, {
53122
53154
  SessionMover: () => SessionMover,
53123
53155
  continuePrompt: () => continuePrompt,
53124
53156
  conversationEntries: () => conversationEntries,
53157
+ copyClaudeConversation: () => copyClaudeConversation,
53125
53158
  extractHandoff: () => extractHandoff,
53126
53159
  fallbackHandoff: () => fallbackHandoff,
53127
53160
  handoffDocument: () => handoffDocument,
@@ -53144,7 +53177,7 @@ __export(session_move_exports, {
53144
53177
  });
53145
53178
  import { execFile as execFile17 } from "node:child_process";
53146
53179
  import { randomUUID as randomUUID19 } from "node:crypto";
53147
- import { lstat as lstat22, mkdir as mkdir21, open as open13, readFile as readFile36, readdir as readdir11, realpath as realpath11, rm as rm10 } from "node:fs/promises";
53180
+ import { copyFile as copyFile3, cp, lstat as lstat22, mkdir as mkdir21, open as open13, readFile as readFile36, readdir as readdir11, realpath as realpath11, rename as rename6, rm as rm10, stat as stat18 } from "node:fs/promises";
53148
53181
  import path91 from "node:path";
53149
53182
  import { promisify as promisify15 } from "node:util";
53150
53183
  function movesRoot() {
@@ -53411,6 +53444,48 @@ async function transcriptTail(file4, bytes = 512 * 1024) {
53411
53444
  await handle.close();
53412
53445
  }
53413
53446
  }
53447
+ async function copyClaudeConversation(file4, to, env = process.env, check2 = false) {
53448
+ const real2 = async (dir) => realpath11(dir).catch(() => path91.resolve(dir));
53449
+ const inside = (child, parent) => child.startsWith(parent + path91.sep);
53450
+ const source = await real2(file4);
53451
+ const homes = await Promise.all(claudeHomes(env).map(async (home) => ({ home, dir: await real2(home.dir), projects: await real2(path91.join(home.dir, "projects")) })));
53452
+ const longest = (list) => list.sort((a, b) => b.projects.length - a.projects.length)[0];
53453
+ const match = longest(homes.filter((item) => inside(source, item.projects))) ?? longest(homes.filter((item) => inside(source, item.dir)));
53454
+ if (!match) throw new BridgeError(409, "The conversation's transcript is not in a Claude home on this computer.");
53455
+ const from = match.home;
53456
+ if (from.dir === to.dir) throw new BridgeError(400, "The conversation already belongs to that account.");
53457
+ const projects = match.projects;
53458
+ const relative5 = path91.relative(projects, source);
53459
+ if (!relative5 || !inside(source, projects) || !relative5.endsWith(".jsonl")) {
53460
+ throw new BridgeError(409, "The conversation's transcript is not under its Claude home's projects folder.");
53461
+ }
53462
+ const targetProjects = path91.join(to.dir, "projects");
53463
+ const destination2 = path91.join(targetProjects, relative5);
53464
+ const targetRoot = await real2(targetProjects);
53465
+ let existing = path91.dirname(destination2);
53466
+ while (!await lstat22(existing).catch(() => void 0) && existing !== path91.dirname(existing) && existing !== to.dir) existing = path91.dirname(existing);
53467
+ const resolved = await real2(existing);
53468
+ if (resolved !== targetRoot && !inside(resolved, targetRoot) && resolved !== await real2(to.dir)) {
53469
+ throw new BridgeError(409, "The other account's projects folder points outside its Claude home.");
53470
+ }
53471
+ if (check2) return destination2;
53472
+ await mkdir21(path91.dirname(destination2), { recursive: true, mode: 448 });
53473
+ const temporary = `${destination2}.${randomUUID19()}.tmp`;
53474
+ try {
53475
+ await copyFile3(source, temporary);
53476
+ await rename6(temporary, destination2);
53477
+ } catch (error62) {
53478
+ await rm10(temporary, { force: true }).catch(() => void 0);
53479
+ throw error62;
53480
+ }
53481
+ const folder = source.slice(0, -".jsonl".length);
53482
+ if ((await stat18(folder).catch(() => void 0))?.isDirectory()) {
53483
+ const folderTo = destination2.slice(0, -".jsonl".length);
53484
+ if ((await lstat22(folderTo).catch(() => void 0))?.isSymbolicLink()) await rm10(folderTo, { force: true });
53485
+ await cp(folder, folderTo, { recursive: true, force: true, verbatimSymlinks: true });
53486
+ }
53487
+ return destination2;
53488
+ }
53414
53489
  var run2, moveRequestSchema, MOVE_STATES, timestamp4, moveRecordSchema, EXIT_COMMANDS, HARNESS_NAMES, MOVE_KEEP_MS, MAX_MOVES, MAX_RECORD_BYTES2, PROMPT_LIMIT2, recordFile, handoffPath, landedMoves, writes3, markers, placeOf, briefText, DEFAULT_HANDOFF_MS, SessionMover;
53415
53490
  var init_session_move = __esm({
53416
53491
  "src/bridge/session-move.ts"() {
@@ -53436,6 +53511,11 @@ var init_session_move = __esm({
53436
53511
  target: targetSchema,
53437
53512
  to: moveToSchema,
53438
53513
  mode: external_exports.enum(["replace", "new-chat"]).default("replace"),
53514
+ /** `resume` switches a Claude conversation to another account on this
53515
+ * computer without a hand-off: the transcript is copied into the target
53516
+ * account's home and the same conversation resumes there (`claude --resume`),
53517
+ * so an account at its usage limit can still switch. */
53518
+ continuation: external_exports.enum(["handoff", "resume"]).default("handoff"),
53439
53519
  /** Kept on a retry: the same id returns the move already under way. */
53440
53520
  id: external_exports.string().uuid().optional(),
53441
53521
  /** How long the agent gets to write its hand-off before Phren builds one. */
@@ -53455,6 +53535,7 @@ var init_session_move = __esm({
53455
53535
  accountChoice: external_exports.string().max(400).optional(),
53456
53536
  project: projectName.optional(),
53457
53537
  mode: external_exports.enum(["replace", "new-chat"]).optional(),
53538
+ continuation: external_exports.literal("resume").optional(),
53458
53539
  modeForced: external_exports.literal("conductor").optional(),
53459
53540
  handedOffTo: external_exports.object({ computer: external_exports.string().optional(), target: external_exports.union([targetSchema, startingTargetSchema]) }).strict().optional(),
53460
53541
  handedOffFrom: external_exports.object({ target: targetSchema, title: external_exports.string().max(200) }).strict().optional(),
@@ -53561,6 +53642,17 @@ var init_session_move = __esm({
53561
53642
  const account2 = target2.source === "claude" ? this.deps.paneAccount?.(target2.server, pane) ?? DEFAULT_ACCOUNT : void 0;
53562
53643
  const sameHarness = to.harness === target2.source && (to.harness !== "claude" || (to.account ?? account2) === account2);
53563
53644
  if (!peer && sameHarness && !to.model && !to.effort) throw new BridgeError(400, "The session already runs there. Choose another harness, account, model or effort.");
53645
+ if (data.continuation === "resume") {
53646
+ if (peer) throw new BridgeError(400, "Switching account keeps the conversation on this computer; continue on another computer with a hand-off.");
53647
+ if (target2.source !== "claude" || to.harness !== "claude") throw new BridgeError(400, "Only a Claude conversation can switch account.");
53648
+ if (!target2.session) throw new BridgeError(409, "The conversation has no session id yet, so it cannot resume under another account.");
53649
+ if (data.mode === "new-chat") throw new BridgeError(400, "Switching account continues the same conversation; it cannot keep the old chat running.");
53650
+ if (conductor) throw new BridgeError(409, "Switching the conductor's account is not supported yet; use Continue in\u2026 for the conductor.");
53651
+ if (!to.account || to.account === account2) throw new BridgeError(400, "Choose another Claude account to switch to.");
53652
+ if (!claudeHome(to.account)) throw new BridgeError(409, `No Claude account "${to.account}" on this computer.`, { code: "account_unavailable" });
53653
+ if (!this.deps.copyConversation) throw new BridgeError(503, "This Hook cannot switch accounts.");
53654
+ await this.deps.copyConversation(target2, claudeHome(to.account), true);
53655
+ }
53564
53656
  const inventory = peer ? void 0 : await this.deps.inventory().catch(() => void 0);
53565
53657
  if (inventory) {
53566
53658
  const availability2 = hasUsable(inventory, to.harness, to.harness === "claude" ? to.account : void 0);
@@ -53606,13 +53698,15 @@ var init_session_move = __esm({
53606
53698
  const workerDispatch = peer && dispatch2 ? await (await Promise.resolve().then(() => (init_worker_relocation(), worker_relocation_exports))).preflightWorkerRelocation(dispatch2, target2) : void 0;
53607
53699
  const label2 = [pane.label, pane.title, pane.terminal_title_stripped, pane.agent_name].find((value2) => typeof value2 === "string" && value2.trim() && !/^\d+$/.test(value2));
53608
53700
  const at2 = new Date(this.now).toISOString();
53701
+ const resume = data.continuation === "resume";
53609
53702
  const record4 = {
53610
53703
  id: data.id ?? randomUUID19(),
53611
- state: "handing-off",
53704
+ state: resume ? "exiting" : "handing-off",
53612
53705
  createdAt: at2,
53613
53706
  updatedAt: at2,
53614
53707
  ...project ? { project } : {},
53615
53708
  mode: conductor || peer ? "new-chat" : data.mode,
53709
+ ...resume ? { continuation: "resume" } : {},
53616
53710
  ...conductor ? { modeForced: "conductor" } : {},
53617
53711
  from: { target: target2, ...account2 ? { account: account2 } : {}, ...label2 ? { label: label2.slice(0, 200) } : {} },
53618
53712
  to,
@@ -53630,7 +53724,7 @@ var init_session_move = __esm({
53630
53724
  }
53631
53725
  await saveMove(record4);
53632
53726
  const key4 = `${target2.server}\0${target2.pane}`;
53633
- const work = this.run(record4, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS, conductor, peer, project).finally(() => this.running.delete(key4));
53727
+ const work = (resume ? this.switchAccount(record4) : this.run(record4, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS, conductor, peer, project)).finally(() => this.running.delete(key4));
53634
53728
  this.running.set(key4, work);
53635
53729
  return record4;
53636
53730
  }
@@ -53969,6 +54063,32 @@ ${safeDocument}`));
53969
54063
  ...record4.from.label ? { label: record4.from.label } : {}
53970
54064
  });
53971
54065
  }
54066
+ /** The same conversation under another Claude account: the old agent exits,
54067
+ * its transcript (now final) is copied into the target home, and Claude
54068
+ * resumes it there. Nothing is asked of the old agent, so its quota does not matter. */
54069
+ async switchAccount(record4) {
54070
+ const from = record4.from.target;
54071
+ let copied = false;
54072
+ try {
54073
+ const exit = await this.exit(record4);
54074
+ await this.update(record4, { exit });
54075
+ await this.checkPromotion(record4);
54076
+ const home = claudeHome(record4.to.account);
54077
+ if (!home) throw new BridgeError(409, `No Claude account "${record4.to.account}" on this computer.`);
54078
+ await this.deps.copyConversation(from, home);
54079
+ copied = true;
54080
+ await this.update(record4, { state: "launching" });
54081
+ const launched = await this.relaunch(record4, { resume: from.session });
54082
+ await this.update(record4, { state: "moved", movedAt: new Date(this.now).toISOString(), ...launched });
54083
+ logger.info("move", `Switched Claude in pane ${from.pane} from account ${record4.from.account ?? DEFAULT_ACCOUNT} to ${record4.to.account} (${launched.placement}).`);
54084
+ } catch (error62) {
54085
+ const message = (error62 instanceof Error ? error62.message : String(error62)).replace(/[\x00-\x1f\x7f]+/g, " ");
54086
+ const resumeHome = claudeHome(copied ? record4.to.account : record4.from.account);
54087
+ const hint = record4.exit !== void 0 ? ` The old agent has exited; resume it with \`claude --resume ${from.session}\`${resumeHome && !resumeHome.isDefault ? ` under CLAUDE_CONFIG_DIR=${resumeHome.dir}` : ""}.` : "";
54088
+ await this.update(record4, { state: "failed", error: `${message}${hint}`.slice(0, 500) }).catch(() => void 0);
54089
+ logger.warn("move", `Switching the account of pane ${from.pane} failed: ${message}`);
54090
+ }
54091
+ }
53972
54092
  /** Ends the old agent with its own exit command; an interrupt, then a kill, only when it hangs. */
53973
54093
  async exit(record4) {
53974
54094
  const from = record4.from.target;
@@ -54014,7 +54134,8 @@ ${safeDocument}`));
54014
54134
  throw new BridgeError(409, "The old agent did not exit, even when killed; nothing was started.");
54015
54135
  }
54016
54136
  /** Starts the target in the old pane when its shell has what the target needs, else in a new tab beside it. */
54017
- async relaunch(record4, prompt) {
54137
+ async relaunch(record4, start) {
54138
+ const prompt = typeof start === "string" ? start : void 0;
54018
54139
  const from = record4.from.target;
54019
54140
  const s = await this.deps.snapshot(from.server);
54020
54141
  const pane = findPane(s, placeOf(from));
@@ -54029,12 +54150,16 @@ ${safeDocument}`));
54029
54150
  ...record4.to.model ? { model: record4.to.model } : {},
54030
54151
  ...record4.to.effort ? { effort: record4.to.effort } : {},
54031
54152
  ...account2 ? { account: account2 } : {},
54032
- brief: { id: record4.id, text: prompt },
54153
+ ...prompt === void 0 ? {} : { brief: { id: record4.id, text: prompt } },
54033
54154
  ...samePane4 ? {} : { workspaceId: from.workspace }
54034
54155
  };
54035
54156
  const into = samePane4 ? { workspaceId: from.workspace, tabId: from.tab, paneId: from.pane } : void 0;
54036
54157
  await this.checkPromotion(record4);
54037
- const launched = await this.deps.launch(from.server, data, { ...into ? { into } : {}, ...record4.dispatch && record4.modeForced !== "conductor" ? { dispatchId: record4.dispatch } : {} });
54158
+ const launched = await this.deps.launch(from.server, data, {
54159
+ ...into ? { into } : {},
54160
+ ...record4.dispatch && record4.modeForced !== "conductor" ? { dispatchId: record4.dispatch } : {},
54161
+ ...prompt === void 0 ? { resumeClaude: start.resume } : {}
54162
+ });
54038
54163
  const paneTarget2 = targetSchema.omit({ session: true }).parse({
54039
54164
  server: from.server,
54040
54165
  workspace: launched.workspaceId,
@@ -54048,7 +54173,7 @@ ${safeDocument}`));
54048
54173
  placement: samePane4 ? "same-pane" : "adjacent-pane",
54049
54174
  ...launchedTarget.success ? { target: launchedTarget.data } : {}
54050
54175
  });
54051
- if (launched.briefLaunched === false) {
54176
+ if (prompt !== void 0 && launched.briefLaunched === false) {
54052
54177
  try {
54053
54178
  const typedTo = targetSchema.safeParse(launched.target);
54054
54179
  if (typedTo.success) {
@@ -54131,7 +54256,7 @@ import { createHmac as createHmac2, randomBytes as randomBytes5 } from "node:cry
54131
54256
  import { execFile as execFile18 } from "node:child_process";
54132
54257
  import { connect as connect2 } from "node:net";
54133
54258
  import { homedir as homedir14 } from "node:os";
54134
- import { open as open14, readdir as readdir12, readlink, realpath as realpath12, stat as stat18 } from "node:fs/promises";
54259
+ import { open as open14, readdir as readdir12, readlink, realpath as realpath12, stat as stat19 } from "node:fs/promises";
54135
54260
  import path92 from "node:path";
54136
54261
  import { promisify as promisify16 } from "node:util";
54137
54262
  function herdrRoot() {
@@ -54169,7 +54294,7 @@ function noteOptionalReadFailure(what, key4, error62) {
54169
54294
  async function rpc(server, method, params = {}, signal, timeoutMs = 1e4) {
54170
54295
  const socket = herdrSocket(server);
54171
54296
  countHerdr(method);
54172
- const metadata = await stat18(socket).catch((error62) => {
54297
+ const metadata = await stat19(socket).catch((error62) => {
54173
54298
  throw herdrSocketError(error62);
54174
54299
  });
54175
54300
  if (!metadata.isSocket() || process.getuid && metadata.uid !== process.getuid()) throw new BridgeError(503, "The Herdr socket is unavailable.", { code: "herdr-permission" });
@@ -54404,7 +54529,7 @@ async function opencodePidSession(pids, root = phrenStoreRoot()) {
54404
54529
  const session = typeof value2.session === "string" && /^ses_[0-9A-Za-z]{1,64}$/.test(value2.session) ? value2.session : void 0;
54405
54530
  const at2 = Date.parse(String(value2.at));
54406
54531
  if (!session || !(at2 > latest)) continue;
54407
- if (!await stat18(path92.join(folder, `opencode-${session}.events.jsonl`)).catch(() => void 0)) continue;
54532
+ if (!await stat19(path92.join(folder, `opencode-${session}.events.jsonl`)).catch(() => void 0)) continue;
54408
54533
  current2 = session;
54409
54534
  latest = at2;
54410
54535
  } catch {
@@ -54422,7 +54547,7 @@ async function identityFromProcesses(server, pane, pids) {
54422
54547
  }
54423
54548
  if (pane.agent === "copilot") {
54424
54549
  const current2 = await copilotForegroundSession(pids).catch(() => void 0);
54425
- if (current2) return await stat18(path92.join(copilotHome2(), "session-state", current2, "events.jsonl")).then(() => ({ sessionId: current2, noTranscriptLogs: false }), () => ({ noTranscriptLogs: true }));
54550
+ if (current2) return await stat19(path92.join(copilotHome2(), "session-state", current2, "events.jsonl")).then(() => ({ sessionId: current2, noTranscriptLogs: false }), () => ({ noTranscriptLogs: true }));
54426
54551
  const reported = object2(pane.agent_session);
54427
54552
  if (reported.kind === "id" && reported.agent === "copilot" && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) return { sessionId: reported.value, noTranscriptLogs: false };
54428
54553
  }
@@ -54811,7 +54936,7 @@ async function readProcess(pid) {
54811
54936
  try {
54812
54937
  if (process.platform === "linux") {
54813
54938
  const base = `/proc/${pid}`;
54814
- const [status, stat32, cmdline, env] = await Promise.all([
54939
+ const [status, stat33, cmdline, env] = await Promise.all([
54815
54940
  readFile37(`${base}/status`, "utf8"),
54816
54941
  readFile37(`${base}/stat`, "utf8"),
54817
54942
  readFile37(`${base}/cmdline`, "utf8"),
@@ -54821,7 +54946,7 @@ async function readProcess(pid) {
54821
54946
  const euid = /^Uid:\s+\d+\s+(\d+)/m.exec(status)?.[1];
54822
54947
  const name = /^Name:\s+(.+)$/m.exec(status)?.[1];
54823
54948
  const start = (value2) => value2.slice(value2.lastIndexOf(")") + 2).trim().split(/\s+/)[19];
54824
- const started2 = start(stat32);
54949
+ const started2 = start(stat33);
54825
54950
  if (!ppid || !euid || !name || !started2 || !/^\d+$/.test(started2)) return void 0;
54826
54951
  if (start(await readFile37(`${base}/stat`, "utf8")) !== started2) return void 0;
54827
54952
  const argv2 = cmdline.split("\0").filter(Boolean);
@@ -54907,8 +55032,8 @@ async function connectionHolders(pid, hookFd) {
54907
55032
  }
54908
55033
  }
54909
55034
  async function processStart(pid) {
54910
- const stat32 = await readFile37(`/proc/${pid}/stat`, "utf8").catch(() => void 0);
54911
- return stat32?.slice(stat32.lastIndexOf(")") + 2).split(" ")[19];
55035
+ const stat33 = await readFile37(`/proc/${pid}/stat`, "utf8").catch(() => void 0);
55036
+ return stat33?.slice(stat33.lastIndexOf(")") + 2).split(" ")[19];
54912
55037
  }
54913
55038
  function deliveryFrom(value2) {
54914
55039
  const item = object2(value2);
@@ -56086,7 +56211,7 @@ var init_git_host_http = __esm({
56086
56211
  // src/bridge/git-host-auth.ts
56087
56212
  import { createHash as createHash27 } from "node:crypto";
56088
56213
  import { execFile as execFile20 } from "node:child_process";
56089
- import { mkdir as mkdir22, readFile as readFile39, stat as stat19 } from "node:fs/promises";
56214
+ import { mkdir as mkdir22, readFile as readFile39, stat as stat20 } from "node:fs/promises";
56090
56215
  import path95 from "node:path";
56091
56216
  import { promisify as promisify18 } from "node:util";
56092
56217
  function gitHostsFile() {
@@ -56101,7 +56226,7 @@ function normalDomain(domain2) {
56101
56226
  async function readStore(file4 = gitHostsFile()) {
56102
56227
  let info;
56103
56228
  try {
56104
- info = await stat19(file4);
56229
+ info = await stat20(file4);
56105
56230
  } catch {
56106
56231
  return null;
56107
56232
  }
@@ -58607,8 +58732,30 @@ var init_hand_off_queue = __esm({
58607
58732
  row.error = "The Hook restarted before delivery was confirmed.";
58608
58733
  await this.save(row);
58609
58734
  }
58735
+ await this.follow(row);
58610
58736
  return row;
58611
58737
  }
58738
+ /** An uncertain row takes the outcome its typed message came to: delivered once the agent's
58739
+ * UserPromptSubmit came, failed (with why) once the Hook knows the agent will not take it. A
58740
+ * failed row still turns delivered when the agent takes the message late. */
58741
+ async follow(row) {
58742
+ if (row.state !== "uncertain" && row.state !== "failed" || !this.options.delivery) return;
58743
+ const known2 = this.options.delivery(row.target, row.deliveryId);
58744
+ if (known2.state === "delivered") {
58745
+ row.state = "delivered";
58746
+ delete row.error;
58747
+ await this.save(row);
58748
+ } else if (known2.state === "failed" && row.state === "uncertain") {
58749
+ row.state = "failed";
58750
+ row.error = (known2.reason ?? "The agent did not take the message.").slice(0, 500);
58751
+ await this.save(row);
58752
+ }
58753
+ }
58754
+ /** Uncertain only while the agent may still take it: its typed message is held, not yet settled, and
58755
+ * in a pane whose hooks will settle it or typed only moments ago. Past that the sender hears "uncertain". */
58756
+ stillHeld(row) {
58757
+ return row.state === "uncertain" && !!this.options.held?.(row.target, row.deliveryId);
58758
+ }
58612
58759
  async rows() {
58613
58760
  const names = await readdir15(this.root).catch((error62) => {
58614
58761
  if (error62.code === "ENOENT") return [];
@@ -58619,251 +58766,846 @@ var init_hand_off_queue = __esm({
58619
58766
  const row = await this.read(name.slice(0, -5));
58620
58767
  if (row) rows2.push(row);
58621
58768
  }
58622
- return rows2.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.deliveryId.localeCompare(b.deliveryId));
58769
+ return rows2.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.deliveryId.localeCompare(b.deliveryId));
58770
+ }
58771
+ /** Drops settled rows past retention, then the oldest settled rows over the
58772
+ * cap (those still owing their sender a notice last). Returns what is kept. */
58773
+ async prune(rows2) {
58774
+ this.lastPrune = this.now();
58775
+ const now = this.now(), drop = /* @__PURE__ */ new Set();
58776
+ for (const row of rows2) if (settled2(row) && now - Date.parse(row.updatedAt) > HAND_OFF_RETENTION_MS) drop.add(row.deliveryId);
58777
+ let excess = rows2.length - drop.size - HAND_OFF_MAX_ROWS;
58778
+ if (excess > 0) {
58779
+ const owesNotice = (row) => row.origin && !row.notified ? 1 : 0;
58780
+ const candidates = rows2.filter((row) => settled2(row) && !drop.has(row.deliveryId)).sort((a, b) => owesNotice(a) - owesNotice(b) || a.updatedAt.localeCompare(b.updatedAt) || a.deliveryId.localeCompare(b.deliveryId));
58781
+ for (const row of candidates) {
58782
+ if (excess-- <= 0) break;
58783
+ drop.add(row.deliveryId);
58784
+ }
58785
+ }
58786
+ for (const id2 of drop) await unlink5(this.file(id2)).catch((error62) => {
58787
+ if (error62.code !== "ENOENT") throw error62;
58788
+ });
58789
+ return drop.size ? rows2.filter((row) => !drop.has(row.deliveryId)) : rows2;
58790
+ }
58791
+ reply(row) {
58792
+ return {
58793
+ ok: row.state === "delivered" || row.state === "queued",
58794
+ delivered: row.state === "delivered",
58795
+ queued: row.state === "queued",
58796
+ deliveryId: row.deliveryId,
58797
+ state: row.state,
58798
+ target: row.target,
58799
+ ...row.state === "uncertain" ? { deliveryUncertain: true } : {},
58800
+ ...row.error ? { error: row.error } : {}
58801
+ };
58802
+ }
58803
+ enqueue(input2) {
58804
+ return this.serial(async () => {
58805
+ const data = queuedHandOffSchema.parse(input2), id2 = data.deliveryId ?? randomUUID23().replaceAll("-", "");
58806
+ const prior = await this.read(id2);
58807
+ if (prior) {
58808
+ if (!samePane3(prior.target, data.target) || prior.text !== data.text) throw new BridgeError(409, "This message id was already used for a different message.");
58809
+ return { ...this.reply(prior), replayed: true };
58810
+ }
58811
+ const row = { ...data, deliveryId: id2 };
58812
+ const pane = await this.validate(row);
58813
+ if (typeof pane.terminal_id !== "string") throw new BridgeError(409, "This agent has no terminal binding.");
58814
+ const at2 = new Date(this.now()).toISOString();
58815
+ Object.assign(row, { terminal: pane.terminal_id, state: "queued", createdAt: at2, updatedAt: at2 });
58816
+ await this.save(row);
58817
+ const ahead = (await this.prune(await this.rows())).some((other) => other.deliveryId !== id2 && samePane3(other.target, row.target) && other.state === "queued");
58818
+ if (!ahead) await this.attempt(row, pane);
58819
+ return this.reply(row);
58820
+ });
58821
+ }
58822
+ status(id2, target2) {
58823
+ return this.serial(async () => {
58824
+ const row = await this.read(id2);
58825
+ if (!row || !samePane3(row.target, target2)) throw new BridgeError(404, "No hand-off with this id and target.");
58826
+ return this.reply(row);
58827
+ });
58828
+ }
58829
+ /** Validates the row's target. When the pane's conversation was replaced
58830
+ * in the same terminal (a Codex thread change, a Claude /clear), the row
58831
+ * follows it: a queued message is for the pane, not for a conversation
58832
+ * that is no longer there. Saved by the caller's next state change. */
58833
+ async validate(row) {
58834
+ try {
58835
+ return await this.options.validate(row.target);
58836
+ } catch (error62) {
58837
+ if (!(error62 instanceof BridgeError) || error62.status !== 409 || !this.options.current) throw error62;
58838
+ const now = await this.options.current(row.target).catch(() => void 0);
58839
+ if (!now || now.session === row.target.session || row.terminal && now.terminal !== row.terminal) throw error62;
58840
+ row.target = { ...row.target, session: now.session };
58841
+ return await this.options.validate(row.target);
58842
+ }
58843
+ }
58844
+ async attempt(row, pane) {
58845
+ const session = row.target.session;
58846
+ try {
58847
+ pane ??= await this.validate(row);
58848
+ if (row.target.session !== session) await this.save(row);
58849
+ } catch (error62) {
58850
+ if (error62 instanceof BridgeError && [404, 409].includes(error62.status)) {
58851
+ row.state = "failed";
58852
+ row.error = error62.message.slice(0, 500);
58853
+ await this.save(row);
58854
+ }
58855
+ return;
58856
+ }
58857
+ if (pane.terminal_id !== row.terminal) {
58858
+ row.state = "failed";
58859
+ row.error = "The worker's terminal changed before delivery.";
58860
+ await this.save(row);
58861
+ return;
58862
+ }
58863
+ if (!(this.options.ready ? await this.options.ready(row.target, pane).catch(() => false) : ["idle", "done"].includes(String(pane.agent_status)))) return;
58864
+ if (this.options.inFlight?.(row.target)) return;
58865
+ let typed = false;
58866
+ try {
58867
+ const result = await this.options.send(row.target, row.text, row.deliveryId, async () => {
58868
+ row.state = "attempting";
58869
+ await this.save(row);
58870
+ typed = true;
58871
+ });
58872
+ row.state = result.delivered === true && result.deliveryUncertain !== true && result.unsubmitted !== true ? "delivered" : "uncertain";
58873
+ } catch (error62) {
58874
+ if (agentNotReady(error62) || error62 instanceof BridgeError && error62.details?.code === "hand-off-busy") row.state = "queued";
58875
+ else if (!typed) {
58876
+ if (!(error62 instanceof BridgeError) || ![404, 409, 422].includes(error62.status)) return;
58877
+ row.state = "failed";
58878
+ } else row.state = "uncertain";
58879
+ row.error = (error62 instanceof Error ? error62.message : "Delivery failed.").slice(0, 500);
58880
+ }
58881
+ if (row.state === "delivered") delete row.error;
58882
+ await this.save(row);
58883
+ }
58884
+ /** Coalesced: the Hook calls this every 5 s whether or not the last tick
58885
+ * finished, and queuing each behind the lock would hold every enqueue and
58886
+ * status behind a backlog that grows faster than a slow tick drains it. */
58887
+ tick() {
58888
+ return this.ticking ??= this.sweep().finally(() => {
58889
+ this.ticking = void 0;
58890
+ });
58891
+ }
58892
+ async sweep() {
58893
+ const remote = await this.serial(async () => {
58894
+ let rows2 = await this.rows();
58895
+ if (this.now() - this.lastPrune >= DAY3) rows2 = await this.prune(rows2);
58896
+ const attempted = /* @__PURE__ */ new Set(), remote2 = [];
58897
+ for (const row of rows2) if (row.state === "queued") {
58898
+ const key4 = JSON.stringify({ ...row.target, session: void 0 });
58899
+ if (attempted.has(key4)) continue;
58900
+ attempted.add(key4);
58901
+ await this.attempt(row);
58902
+ }
58903
+ for (const row of rows2) if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state) && !this.stillHeld(row)) {
58904
+ if (row.originComputer) {
58905
+ remote2.push(row);
58906
+ continue;
58907
+ }
58908
+ const forwarded = await this.options.forward?.(row.origin, `Hand-off ${row.deliveryId}: ${row.state}.`, this.noticeId(row)).catch(() => ({ delivered: false }));
58909
+ if (forwarded) {
58910
+ if (forwarded.delivered) {
58911
+ row.notified = true;
58912
+ await this.save(row);
58913
+ }
58914
+ continue;
58915
+ }
58916
+ const id2 = this.noticeId(row);
58917
+ if (!await this.read(id2)) {
58918
+ const pane = await this.options.validate(row.origin).catch(() => void 0);
58919
+ if (!pane || typeof pane.terminal_id !== "string") continue;
58920
+ const at2 = new Date(this.now()).toISOString();
58921
+ await this.save({
58922
+ deliveryId: id2,
58923
+ target: row.origin,
58924
+ text: `Hand-off ${row.deliveryId}: ${row.state}.`,
58925
+ terminal: pane.terminal_id,
58926
+ state: "queued",
58927
+ createdAt: at2,
58928
+ updatedAt: at2
58929
+ });
58930
+ }
58931
+ row.notified = true;
58932
+ await this.save(row);
58933
+ }
58934
+ return remote2;
58935
+ });
58936
+ await Promise.all(remote.map(async (row) => {
58937
+ const result = await this.options.notify?.(row.origin, `Hand-off ${row.deliveryId}: ${row.state}.`, this.noticeId(row), row.originComputer).catch(() => void 0);
58938
+ if (!result || !result.queued && !result.delivered && !result.deliveryUncertain) return;
58939
+ await this.serial(async () => {
58940
+ const current2 = await this.read(row.deliveryId);
58941
+ if (current2 && !current2.notified) {
58942
+ current2.notified = true;
58943
+ await this.save(current2);
58944
+ }
58945
+ });
58946
+ }));
58947
+ }
58948
+ noticeId(row) {
58949
+ return `handoff-notice-${createHash30("sha256").update(row.deliveryId).digest("hex").slice(0, 40)}`;
58950
+ }
58951
+ /** Hold enqueues and delivery while the Hook validates and closes a worker.
58952
+ * A new hand-off cannot be accepted between the pending check and closure. */
58953
+ whenNoPending(target2, close) {
58954
+ return this.serial(async () => {
58955
+ if ((await this.rows()).some((row) => samePane3(row.target, target2) && ["queued", "attempting", "uncertain"].includes(row.state))) return { ok: true, closed: false };
58956
+ return close();
58957
+ });
58958
+ }
58959
+ hasPending(target2) {
58960
+ return this.serial(async () => (await this.rows()).some((row) => samePane3(row.target, target2) && ["queued", "attempting", "uncertain"].includes(row.state)));
58961
+ }
58962
+ };
58963
+ }
58964
+ });
58965
+
58966
+ // src/bridge/git-write-policy.ts
58967
+ function clientIdentity(headers) {
58968
+ const clean5 = (value2) => (Array.isArray(value2) ? value2.join(", ") : value2 ?? "").replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 200);
58969
+ const client = clean5(headers["x-phren-client"]);
58970
+ const version2 = clean5(headers["x-phren-app-version"] || headers["x-phren-client-version"]);
58971
+ const agent = clean5(headers["user-agent"]);
58972
+ return [client, version2, agent].filter(Boolean).join(" / ") || "unknown client";
58973
+ }
58974
+ var EXPECTED_REPOSITORY_REQUIRED, WRITE_ROUTES, isGitWriteRoute, GitWriteDiagnostics;
58975
+ var init_git_write_policy = __esm({
58976
+ "src/bridge/git-write-policy.ts"() {
58977
+ "use strict";
58978
+ EXPECTED_REPOSITORY_REQUIRED = false;
58979
+ WRITE_ROUTES = new Set(["stage", "unstage", "discard", "commit", "push", "pr", "pr/merge", "host-token", "checkout", "fetch", "pull", "apply"].map((action) => `/v1/git/${action}`));
58980
+ isGitWriteRoute = (route2) => WRITE_ROUTES.has(route2);
58981
+ GitWriteDiagnostics = class {
58982
+ clients = /* @__PURE__ */ new Map();
58983
+ record(route2, headers) {
58984
+ let client = clientIdentity(headers);
58985
+ if (!this.clients.has(client) && this.clients.size >= 128) client = "other clients";
58986
+ let entry2 = this.clients.get(client);
58987
+ if (!entry2) {
58988
+ entry2 = { count: 0, routes: /* @__PURE__ */ new Set() };
58989
+ this.clients.set(client, entry2);
58990
+ }
58991
+ entry2.count++;
58992
+ if (!entry2.routes.has(route2)) {
58993
+ entry2.routes.add(route2);
58994
+ console.warn(`[phren-hook] ${route2}: git write without expectedRepository from ${client}; update the app before the compatibility window ends.`);
58995
+ }
58996
+ }
58997
+ snapshot() {
58998
+ return [...this.clients].map(([client, entry2]) => ({
58999
+ client,
59000
+ count: entry2.count,
59001
+ warning: `${entry2.count} git writes without expectedRepository from ${client}`
59002
+ }));
59003
+ }
59004
+ };
59005
+ }
59006
+ });
59007
+
59008
+ // src/bridge/prompt-deliveries.ts
59009
+ import { createHash as createHash31 } from "node:crypto";
59010
+ import { readFileSync as readFileSync45 } from "node:fs";
59011
+ import { open as open18 } from "node:fs/promises";
59012
+ function promptKey(text5) {
59013
+ return unwrapPastedContent(text5).split("\n").filter((line) => !PICTURE_PATH_LINE.test(line)).join("\n").replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
59014
+ }
59015
+ function matchingOffsets(buffer, start, record4) {
59016
+ const entries2 = [];
59017
+ const lines = buffer.toString("utf8").split("\n");
59018
+ let offset = start + buffer.length;
59019
+ for (let index2 = lines.length - 1; index2 >= 0; index2--) {
59020
+ const line = lines[index2];
59021
+ offset -= Buffer.byteLength(line) + (index2 < lines.length - 1 ? 1 : 0);
59022
+ if (!line.includes('"user') && !line.includes("queue-operation")) continue;
59023
+ let row;
59024
+ try {
59025
+ row = object2(JSON.parse(line));
59026
+ } catch {
59027
+ continue;
59028
+ }
59029
+ const stamp2 = Date.parse(String(row.timestamp ?? ""));
59030
+ if (Number.isFinite(stamp2) && stamp2 < record4.at - 5e3) continue;
59031
+ if (userTexts(row).some((text5) => promptHash(text5) === record4.hash)) entries2.push({ offset, hook: row.type === "user", ...Number.isFinite(stamp2) ? { at: stamp2 } : {} });
59032
+ }
59033
+ return entries2;
59034
+ }
59035
+ async function transcriptEntries(record4) {
59036
+ const file4 = await open18(await transcriptPath(record4.source, record4.session), "r");
59037
+ try {
59038
+ const size = (await file4.stat()).size, start = Math.max(0, size - 524288), buffer = Buffer.alloc(size - start);
59039
+ await file4.read(buffer, 0, buffer.length, start);
59040
+ return matchingOffsets(buffer, start, record4);
59041
+ } finally {
59042
+ await file4.close();
59043
+ }
59044
+ }
59045
+ function userTexts(row) {
59046
+ const texts = [];
59047
+ const blocks = (content) => {
59048
+ if (typeof content === "string") texts.push(content);
59049
+ else for (const block of objects(content)) if (typeof block.text === "string") texts.push(block.text);
59050
+ };
59051
+ if (row.type === "user" && !row.isMeta) blocks(object2(row.message).content);
59052
+ if (row.type === "queue-operation" && row.operation === "remove" && typeof row.content === "string" && (row.reason === "absorbed_mid_turn" || row.reason === "delivered_to_agent")) texts.push(row.content);
59053
+ const payload = object2(row.payload);
59054
+ if (payload.type === "user_message" && typeof payload.message === "string") texts.push(payload.message);
59055
+ if (payload.type === "message" && payload.role === "user") blocks(payload.content);
59056
+ return texts;
59057
+ }
59058
+ var TURN_ENDED_WITHOUT_IT, 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, JOINED_MAX_LINES, JOINED_MAX_OPEN, JOINED_MAX_CHARS, recordSchema2, PromptDeliveries;
59059
+ var init_prompt_deliveries = __esm({
59060
+ "src/bridge/prompt-deliveries.ts"() {
59061
+ "use strict";
59062
+ init_zod();
59063
+ init_protocol();
59064
+ init_transcripts();
59065
+ TURN_ENDED_WITHOUT_IT = "The agent finished its turn without taking the message.";
59066
+ DELIVERY_RETENTION_MS = 24 * 36e5;
59067
+ DELIVERY_GIVE_UP_MS = 3e4;
59068
+ MAX_RECORDS = 512;
59069
+ LANDED_CHECK_MS = 3e3;
59070
+ ENTRY_SLACK_MS = 5e3;
59071
+ HOOK_ROW_MS = 3e4;
59072
+ IN_FLIGHT_MS = 45e3;
59073
+ PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
59074
+ promptHash = (text5) => createHash31("sha256").update(promptKey(text5)).digest("hex");
59075
+ JOINED_MAX_LINES = 64;
59076
+ JOINED_MAX_OPEN = 32;
59077
+ JOINED_MAX_CHARS = 1048576;
59078
+ recordSchema2 = external_exports.object({
59079
+ id: external_exports.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional(),
59080
+ hash: external_exports.string().regex(/^[0-9a-f]{64}$/),
59081
+ server: external_exports.string().min(1).max(200),
59082
+ pane: external_exports.string().min(1).max(200),
59083
+ source: provider,
59084
+ session: external_exports.string().min(1).max(200),
59085
+ terminal: external_exports.string().max(200).optional(),
59086
+ state: external_exports.enum(["typed", "queued", "delivered", "failed"]),
59087
+ reason: external_exports.string().max(500).optional(),
59088
+ at: external_exports.number(),
59089
+ settledAt: external_exports.number().optional(),
59090
+ stoppedAt: external_exports.number().optional(),
59091
+ /** The transcript entry (byte offset) that settled it, so no other message claims the same one. */
59092
+ entry: external_exports.number().optional(),
59093
+ /** Whether that entry is a user row (one its agent's UserPromptSubmit fired for), not a mid-turn queue removal. */
59094
+ entryHook: external_exports.boolean().optional(),
59095
+ /** From a joined prompt (`settleJoined`): "part", a message settled inside it, claims no row of its own (the turn's
59096
+ * row carries other words); "turn", the joined words themselves, no message of anyone's, claims that row. */
59097
+ joined: external_exports.enum(["part", "turn"]).optional()
59098
+ }).strict();
59099
+ PromptDeliveries = class _PromptDeliveries {
59100
+ constructor(file4, now = Date.now, landed = transcriptEntries) {
59101
+ this.file = file4;
59102
+ this.now = now;
59103
+ this.landed = landed;
59104
+ if (!file4) return;
59105
+ try {
59106
+ for (const row of objects(object2(JSON.parse(readFileSync45(file4, "utf8"))).records)) {
59107
+ const parsed = recordSchema2.safeParse(row);
59108
+ if (parsed.success) this.records.push({ ...parsed.data, state: parsed.data.state === "typed" ? "queued" : parsed.data.state });
59109
+ }
59110
+ } catch {
59111
+ }
59112
+ this.prune();
59113
+ }
59114
+ file;
59115
+ now;
59116
+ landed;
59117
+ records = [];
59118
+ waiters = /* @__PURE__ */ new Map();
59119
+ writing = Promise.resolve();
59120
+ /** Panes (server, pane, agent) that sent a UserPromptSubmit or Stop since the Hook started. */
59121
+ hookPanes = /* @__PURE__ */ new Set();
59122
+ /** When each pane (server, pane, agent) last sent a Stop since the Hook started. */
59123
+ lastStop = /* @__PURE__ */ new Map();
59124
+ paneKey(target2) {
59125
+ return [target2.server, target2.pane, target2.source].join("|");
59126
+ }
59127
+ static open(record4) {
59128
+ return record4.state === "typed" || record4.state === "queued";
59129
+ }
59130
+ /** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
59131
+ static claimable(record4) {
59132
+ return _PromptDeliveries.open(record4) || record4.state === "failed" && !!record4.hookClaim;
59133
+ }
59134
+ samePane(record4, target2) {
59135
+ return record4.server === target2.server && record4.pane === target2.pane && record4.source === target2.source;
59136
+ }
59137
+ byId(id2) {
59138
+ return this.records.find((record4) => record4.id === id2);
59139
+ }
59140
+ prune() {
59141
+ const cutoff = this.now() - DELIVERY_RETENTION_MS;
59142
+ this.records = this.records.filter((record4) => record4.at >= cutoff || this.waiters.has(record4));
59143
+ while (this.records.length > MAX_RECORDS) this.records.shift();
59144
+ }
59145
+ save() {
59146
+ if (!this.file) return;
59147
+ const rows2 = this.records.filter((record4) => record4.id || record4.entry !== void 0 || record4.joined === "turn").map(({ idleSince: _2, checkedAt: __, hookClaim: ___, seenRow: ____, ...row }) => row);
59148
+ const file4 = this.file;
59149
+ this.writing = this.writing.then(() => atomicInPrivateDir(file4, { records: rows2 })).catch(() => void 0);
59150
+ }
59151
+ /** Settled writes, for tests and an orderly shutdown. */
59152
+ flush() {
59153
+ return this.writing;
59154
+ }
59155
+ /** Register a message about to be typed into `target`'s pane. Settles
59156
+ * "delivered" once a conversation in that pane submits the words, or
59157
+ * "pending" after `waitMs`; the record outlives the wait. A retry of a
59158
+ * failed id replaces its record. Aborting (the terminal refused before
59159
+ * writing) drops it. */
59160
+ expect(target2, text5, waitMs, signal, id2, terminal2) {
59161
+ if (!promptKey(text5) || signal?.aborted) return Promise.resolve("pending");
59162
+ this.prune();
59163
+ if (id2) this.records = this.records.filter((record5) => record5.id !== id2);
59164
+ const record4 = {
59165
+ ...id2 ? { id: id2 } : {},
59166
+ hash: promptHash(text5),
59167
+ server: target2.server,
59168
+ pane: target2.pane,
59169
+ source: target2.source,
59170
+ session: target2.session,
59171
+ ...typeof terminal2 === "string" ? { terminal: terminal2 } : {},
59172
+ state: "typed",
59173
+ at: this.now()
59174
+ };
59175
+ this.records.push(record4);
59176
+ this.save();
59177
+ return new Promise((resolve17) => {
59178
+ const timer = setTimeout(() => this.release(record4, "pending"), waitMs);
59179
+ timer.unref?.();
59180
+ this.waiters.set(record4, { resolve: resolve17, timer });
59181
+ signal?.addEventListener("abort", () => {
59182
+ this.release(record4, "pending");
59183
+ if (record4.state === "typed") {
59184
+ this.records = this.records.filter((entry2) => entry2 !== record4);
59185
+ this.save();
59186
+ }
59187
+ }, { once: true });
59188
+ });
59189
+ }
59190
+ release(record4, outcome) {
59191
+ const waiter = this.waiters.get(record4);
59192
+ if (!waiter) return;
59193
+ clearTimeout(waiter.timer);
59194
+ waiter.resolve?.(outcome);
59195
+ waiter.resolve = void 0;
59196
+ if (outcome !== "pending") waiter.late?.(outcome);
59197
+ if (outcome !== "pending" || !waiter.late) this.waiters.delete(record4);
59198
+ }
59199
+ open(target2, text5) {
59200
+ const hash2 = promptHash(text5);
59201
+ return this.records.find((record4) => record4.hash === hash2 && this.samePane(record4, target2) && (record4.state === "typed" || record4.state === "queued"));
59202
+ }
59203
+ /** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
59204
+ pending(target2, text5) {
59205
+ return !!this.open(target2, text5);
59206
+ }
59207
+ /** Whether `record` still holds its pane: open, and either young or in a pane whose hooks will settle it. */
59208
+ inFlight(record4) {
59209
+ return _PromptDeliveries.open(record4) && (this.now() - record4.at < IN_FLIGHT_MS || this.hookPanes.has(this.paneKey(record4)));
59210
+ }
59211
+ /** Whether any message typed into `target`'s pane is still waiting to be taken or refused. */
59212
+ holding(target2) {
59213
+ return this.records.some((record4) => this.samePane(record4, target2) && this.inFlight(record4));
59214
+ }
59215
+ /** Whether phone message `id` may still be taken: held by the agent, and in flight as `holding` counts it. */
59216
+ held(id2, target2) {
59217
+ const record4 = this.find(id2, target2);
59218
+ return !!record4 && this.inFlight(record4);
59219
+ }
59220
+ /** Wait again for a message `expect` reported pending, after a second Enter. */
59221
+ awaitLate(target2, text5, waitMs = 2500) {
59222
+ const record4 = this.open(target2, text5);
59223
+ if (!record4) return Promise.resolve("pending");
59224
+ return new Promise((resolve17) => {
59225
+ const waiter = this.waiters.get(record4) ?? {};
59226
+ const timer = setTimeout(() => {
59227
+ waiter.late = void 0;
59228
+ if (!waiter.resolve) this.waiters.delete(record4);
59229
+ resolve17("pending");
59230
+ }, waitMs);
59231
+ timer.unref?.();
59232
+ waiter.late = (outcome) => {
59233
+ clearTimeout(timer);
59234
+ waiter.late = void 0;
59235
+ resolve17(outcome);
59236
+ };
59237
+ this.waiters.set(record4, waiter);
59238
+ });
59239
+ }
59240
+ find(id2, target2) {
59241
+ const record4 = this.byId(id2);
59242
+ return record4 && this.samePane(record4, target2) && this.now() - record4.at <= DELIVERY_RETENTION_MS ? record4 : void 0;
59243
+ }
59244
+ /** The Hook answered `id` as typed and held by the agent. */
59245
+ queue(id2, target2) {
59246
+ const record4 = this.find(id2, target2);
59247
+ if (record4?.state === "typed") {
59248
+ record4.state = "queued";
59249
+ this.save();
59250
+ }
58623
59251
  }
58624
- /** Drops settled rows past retention, then the oldest settled rows over the
58625
- * cap (those still owing their sender a notice last). Returns what is kept. */
58626
- async prune(rows2) {
58627
- this.lastPrune = this.now();
58628
- const now = this.now(), drop = /* @__PURE__ */ new Set();
58629
- for (const row of rows2) if (settled2(row) && now - Date.parse(row.updatedAt) > HAND_OFF_RETENTION_MS) drop.add(row.deliveryId);
58630
- let excess = rows2.length - drop.size - HAND_OFF_MAX_ROWS;
58631
- if (excess > 0) {
58632
- const owesNotice = (row) => row.origin && !row.notified ? 1 : 0;
58633
- const candidates = rows2.filter((row) => settled2(row) && !drop.has(row.deliveryId)).sort((a, b) => owesNotice(a) - owesNotice(b) || a.updatedAt.localeCompare(b.updatedAt) || a.deliveryId.localeCompare(b.deliveryId));
58634
- for (const row of candidates) {
58635
- if (excess-- <= 0) break;
58636
- drop.add(row.deliveryId);
58637
- }
58638
- }
58639
- for (const id2 of drop) await unlink5(this.file(id2)).catch((error62) => {
58640
- if (error62.code !== "ENOENT") throw error62;
59252
+ /** Delivered without a hook: an app-server turn or a served OpenCode prompt. */
59253
+ delivered(id2, target2, text5) {
59254
+ if (!id2) return;
59255
+ this.records = this.records.filter((record4) => record4.id !== id2);
59256
+ this.records.push({
59257
+ id: id2,
59258
+ hash: promptHash(text5),
59259
+ server: target2.server,
59260
+ pane: target2.pane,
59261
+ source: target2.source,
59262
+ session: target2.session,
59263
+ state: "delivered",
59264
+ at: this.now(),
59265
+ settledAt: this.now()
58641
59266
  });
58642
- return drop.size ? rows2.filter((row) => !drop.has(row.deliveryId)) : rows2;
59267
+ this.save();
58643
59268
  }
58644
- reply(row) {
58645
- return {
58646
- ok: row.state === "delivered" || row.state === "queued",
58647
- delivered: row.state === "delivered",
58648
- queued: row.state === "queued",
58649
- deliveryId: row.deliveryId,
58650
- state: row.state,
58651
- target: row.target,
58652
- ...row.state === "uncertain" ? { deliveryUncertain: true } : {},
58653
- ...row.error ? { error: row.error } : {}
58654
- };
59269
+ /** The message did not reach the agent, and why. It stays matchable, so a
59270
+ * late submission still turns it delivered. */
59271
+ fail(id2, target2, reason2) {
59272
+ const record4 = id2 ? this.find(id2, target2) : void 0;
59273
+ if (!record4 || record4.state === "delivered") return;
59274
+ record4.state = "failed";
59275
+ record4.reason = reason2.slice(0, 500);
59276
+ record4.settledAt = this.now();
59277
+ this.save();
58655
59278
  }
58656
- enqueue(input2) {
58657
- return this.serial(async () => {
58658
- const data = queuedHandOffSchema.parse(input2), id2 = data.deliveryId ?? randomUUID23().replaceAll("-", "");
58659
- const prior = await this.read(id2);
58660
- if (prior) {
58661
- if (!samePane3(prior.target, data.target) || prior.text !== data.text) throw new BridgeError(409, "This message id was already used for a different message.");
58662
- return { ...this.reply(prior), replayed: true };
58663
- }
58664
- const row = { ...data, deliveryId: id2 };
58665
- const pane = await this.validate(row);
58666
- if (typeof pane.terminal_id !== "string") throw new BridgeError(409, "This agent has no terminal binding.");
58667
- const at2 = new Date(this.now()).toISOString();
58668
- Object.assign(row, { terminal: pane.terminal_id, state: "queued", createdAt: at2, updatedAt: at2 });
58669
- await this.save(row);
58670
- const ahead = (await this.prune(await this.rows())).some((other) => other.deliveryId !== id2 && samePane3(other.target, row.target) && other.state === "queued");
58671
- if (!ahead) await this.attempt(row, pane);
58672
- return this.reply(row);
58673
- });
59279
+ /** The pane's Codex server moved to another thread (/new, /resume):
59280
+ * input still pending on the old one stays there, out of the pane's view.
59281
+ * Fails loudly; a late UserPromptSubmit from the old thread still settles it. */
59282
+ threadChanged(previous) {
59283
+ let changed = false;
59284
+ for (const record4 of this.records) if ((record4.state === "typed" || record4.state === "queued") && this.samePane(record4, previous) && record4.session === previous.session) {
59285
+ record4.state = "failed";
59286
+ record4.settledAt = this.now();
59287
+ changed = true;
59288
+ record4.reason = "The pane moved to another Codex conversation before the agent took the message.";
59289
+ }
59290
+ if (changed) this.save();
59291
+ }
59292
+ /** False when `id` names another message: other words or another pane. */
59293
+ sameMessage(id2, target2, text5) {
59294
+ const record4 = this.byId(id2);
59295
+ return !record4 || this.samePane(record4, target2) && record4.hash === promptHash(text5);
58674
59296
  }
59297
+ /** What became of phone message `id` in `target`'s pane. `unknown` while the
59298
+ * Hook has not answered it, for another pane, or past retention. */
58675
59299
  status(id2, target2) {
58676
- return this.serial(async () => {
58677
- const row = await this.read(id2);
58678
- if (!row || !samePane3(row.target, target2)) throw new BridgeError(404, "No hand-off with this id and target.");
58679
- return this.reply(row);
58680
- });
59300
+ const record4 = this.find(id2, target2);
59301
+ if (!record4 || record4.state === "typed") return { state: "unknown" };
59302
+ return { state: record4.state, ...record4.reason && record4.state === "failed" ? { reason: record4.reason } : {}, session: record4.session };
58681
59303
  }
58682
- /** Validates the row's target. When the pane's conversation was replaced
58683
- * in the same terminal (a Codex thread change, a Claude /clear), the row
58684
- * follows it: a queued message is for the pane, not for a conversation
58685
- * that is no longer there. Saved by the caller's next state change. */
58686
- async validate(row) {
58687
- try {
58688
- return await this.options.validate(row.target);
58689
- } catch (error62) {
58690
- if (!(error62 instanceof BridgeError) || error62.status !== 409 || !this.options.current) throw error62;
58691
- const now = await this.options.current(row.target).catch(() => void 0);
58692
- if (!now || now.session === row.target.session || row.terminal && now.terminal !== row.terminal) throw error62;
58693
- row.target = { ...row.target, session: now.session };
58694
- return await this.options.validate(row.target);
59304
+ /** Every known phone message in `target`'s pane, for its conversation's stream. */
59305
+ forPane(target2) {
59306
+ return this.records.filter((record4) => record4.id && this.samePane(record4, target2)).map((record4) => ({ deliveryId: record4.id, ...this.status(record4.id, target2) })).filter((item) => item.state !== "unknown");
59307
+ }
59308
+ /** Conversation `target` just submitted `prompt`. Its own record wins, then
59309
+ * the oldest open one in the same pane: the agent kept the text across a
59310
+ * conversation change, and the conversation now in the pane is where it
59311
+ * went. A prompt nothing matches was typed locally. Never refused.
59312
+ * For Claude the transcript is consulted first and the submission claims
59313
+ * the earliest unclaimed user row with these words, through the same
59314
+ * `settle` and the same table of claimed entries the idle check uses: a
59315
+ * callback for a row already claimed (the idle check settled it, the hook
59316
+ * came late) settles nothing more. */
59317
+ async submitted(target2, prompt) {
59318
+ const hash2 = promptHash(prompt);
59319
+ this.hookPanes.add(this.paneKey(target2));
59320
+ const stop = this.lastStop.get(this.paneKey(target2)) ?? -Infinity;
59321
+ const pick3 = () => {
59322
+ const open30 = this.records.filter((record5) => record5.hash === hash2 && this.samePane(record5, target2) && record5.state !== "delivered" && (record5.state !== "failed" || (record5.settledAt ?? record5.at) >= stop));
59323
+ return open30.find((entry3) => entry3.session === target2.session) ?? open30[0];
59324
+ };
59325
+ let record4 = pick3();
59326
+ if (!record4) {
59327
+ if (!this.records.some((other) => other.hash === hash2 && this.samePane(other, target2) && other.joined === void 0) && this.settleJoined(target2, prompt)) this.save();
59328
+ return;
59329
+ }
59330
+ let entry2;
59331
+ if (target2.source === "claude") {
59332
+ let rows2;
59333
+ try {
59334
+ rows2 = (await this.landed({ source: target2.source, session: target2.session, hash: hash2, at: record4.at })).filter((row) => row.hook);
59335
+ } catch {
59336
+ rows2 = void 0;
59337
+ }
59338
+ record4 = pick3();
59339
+ if (!record4) return;
59340
+ 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));
59341
+ const free = rows2?.filter((row) => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
59342
+ if (!free && !claimed.size) {
59343
+ this.settle(record4, void 0, target2.session);
59344
+ this.save();
59345
+ return;
59346
+ }
59347
+ if (!free) {
59348
+ if (!rows2?.length) {
59349
+ record4.hookClaim = true;
59350
+ record4.session = target2.session;
59351
+ }
59352
+ return;
59353
+ }
59354
+ entry2 = free.offset;
58695
59355
  }
59356
+ this.settle(record4, entry2, target2.session, entry2 !== void 0 ? true : void 0);
59357
+ this.save();
58696
59358
  }
58697
- async attempt(row, pane) {
58698
- const session = row.target.session;
58699
- try {
58700
- pane ??= await this.validate(row);
58701
- if (row.target.session !== session) await this.save(row);
58702
- } catch (error62) {
58703
- if (error62 instanceof BridgeError && [404, 409].includes(error62.status)) {
58704
- row.state = "failed";
58705
- row.error = error62.message.slice(0, 500);
58706
- await this.save(row);
59359
+ /** Claude submits the messages it held while busy as one turn, joined by newlines, so no single message's
59360
+ * hash matches the prompt. Each open message in the pane whose words are a run of whole lines of it settles,
59361
+ * the longest run first at each line and the oldest of identical messages first, so "yes" never settles
59362
+ * inside "yes, but later". Only hashes of the line runs are compared, never stored. Only messages still held
59363
+ * (typed or queued) are matched: a failed one could take the lines of messages that are held, and a late
59364
+ * take of a failed message stays its own hook's to report. */
59365
+ settleJoined(target2, prompt) {
59366
+ const candidates = this.records.filter((record4) => this.samePane(record4, target2) && _PromptDeliveries.open(record4)).sort((a, b) => a.at - b.at).slice(0, JOINED_MAX_OPEN);
59367
+ if (!candidates.length) return false;
59368
+ const lines = unwrapPastedContent(prompt).split("\n").filter((line) => !PICTURE_PATH_LINE.test(line));
59369
+ if (lines.length < 2 || lines.length > JOINED_MAX_LINES) return false;
59370
+ const matched = [];
59371
+ let budget = JOINED_MAX_CHARS;
59372
+ for (let start = 0; start < lines.length; ) {
59373
+ let next = start + 1;
59374
+ for (let end = lines.length; end > start; end--) {
59375
+ const run4 = lines.slice(start, end).join("\n");
59376
+ if ((budget -= run4.length) < 0) break;
59377
+ if (!promptKey(run4)) continue;
59378
+ const hash2 = promptHash(run4), same2 = candidates.filter((record5) => record5.hash === hash2 && !matched.includes(record5));
59379
+ const record4 = same2.find((entry2) => entry2.session === target2.session) ?? same2[0];
59380
+ if (record4) {
59381
+ matched.push(record4);
59382
+ next = end;
59383
+ break;
59384
+ }
58707
59385
  }
58708
- return;
59386
+ start = next;
58709
59387
  }
58710
- if (pane.terminal_id !== row.terminal) {
58711
- row.state = "failed";
58712
- row.error = "The worker's terminal changed before delivery.";
58713
- await this.save(row);
58714
- return;
59388
+ if (!matched.length) return false;
59389
+ for (const record4 of matched) {
59390
+ record4.joined = "part";
59391
+ this.settle(record4, void 0, target2.session);
58715
59392
  }
58716
- if (!["idle", "done"].includes(String(pane.agent_status))) return;
58717
- let typed = false;
58718
- try {
58719
- const result = await this.options.send(row.target, row.text, row.deliveryId, async () => {
58720
- row.state = "attempting";
58721
- await this.save(row);
58722
- typed = true;
58723
- });
58724
- row.state = result.delivered === true && result.deliveryUncertain !== true && result.unsubmitted !== true ? "delivered" : "uncertain";
58725
- } catch (error62) {
58726
- if (agentNotReady(error62) || error62 instanceof BridgeError && error62.details?.code === "hand-off-busy") row.state = "queued";
58727
- else if (!typed) {
58728
- if (!(error62 instanceof BridgeError) || ![404, 409, 422].includes(error62.status)) return;
58729
- row.state = "failed";
58730
- } else row.state = "uncertain";
58731
- row.error = (error62 instanceof Error ? error62.message : "Delivery failed.").slice(0, 500);
59393
+ this.records.push({
59394
+ hash: promptHash(prompt),
59395
+ server: target2.server,
59396
+ pane: target2.pane,
59397
+ source: target2.source,
59398
+ session: target2.session,
59399
+ state: "delivered",
59400
+ at: this.now(),
59401
+ settledAt: this.now(),
59402
+ joined: "turn"
59403
+ });
59404
+ return true;
59405
+ }
59406
+ /** Marks `record` delivered, with the transcript entry that settled it when known. */
59407
+ settle(record4, entry2, session, hook) {
59408
+ record4.state = "delivered";
59409
+ record4.settledAt = this.now();
59410
+ delete record4.reason;
59411
+ delete record4.hookClaim;
59412
+ delete record4.seenRow;
59413
+ if (session) record4.session = session;
59414
+ if (entry2 !== void 0) record4.entry = entry2;
59415
+ if (hook !== void 0) record4.entryHook = hook;
59416
+ this.release(record4, "delivered");
59417
+ }
59418
+ /** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
59419
+ * An entry settles one message: the table of records' `entry` offsets (per conversation) is the only
59420
+ * state, so neither this path nor the hook's can settle two messages with one turn. A user row is a
59421
+ * turn start whose UserPromptSubmit hook settles the message itself, so while the agent works only a
59422
+ * mid-turn queue removal (no hook fires for it) settles from the transcript; once the agent is idle
59423
+ * (`working` false) a user row settles too, for a hook that never came. Of several identical open
59424
+ * messages the oldest take the entries. `pass` carries the entries still unclaimed within one observe. */
59425
+ async taken(record4, pass, working = false) {
59426
+ if (record4.source !== "claude") return (await this.landed(record4).catch(() => [])).length > 0;
59427
+ const same2 = (other) => other.hash === record4.hash && other.server === record4.server && other.pane === record4.pane && other.session === record4.session;
59428
+ const open30 = this.records.filter((other) => same2(other) && _PromptDeliveries.claimable(other)).sort((a, b) => a.at - b.at);
59429
+ if (open30[0] !== record4) return false;
59430
+ const key4 = [record4.hash, record4.server, record4.pane, record4.session, working].join("|");
59431
+ let free = pass.get(key4);
59432
+ if (!free) {
59433
+ const hooked = this.records.filter((other) => same2(other) && other.state === "delivered" && other.entry === void 0 && other.joined !== "part").sort((a, b) => (a.settledAt ?? a.at) - (b.settledAt ?? b.at));
59434
+ const from = Math.min(record4.at, ...hooked.map((other) => other.at));
59435
+ const found = (await this.landed({ ...record4, at: from }).catch(() => [])).sort((a, b) => a.offset - b.offset);
59436
+ const used = new Set(this.records.filter((other) => same2(other) && other.entry !== void 0).map((other) => other.entry));
59437
+ let claimedRows = false;
59438
+ for (const other of hooked) {
59439
+ if (other.entry !== void 0) continue;
59440
+ 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));
59441
+ if (!row) continue;
59442
+ other.entry = row.offset;
59443
+ other.entryHook = true;
59444
+ used.add(row.offset);
59445
+ claimedRows = true;
59446
+ }
59447
+ if (claimedRows) this.save();
59448
+ const unclaimed = found.filter((entry3) => !used.has(entry3.offset) && (entry3.at === void 0 || entry3.at >= record4.at - ENTRY_SLACK_MS));
59449
+ if (working) {
59450
+ const row = unclaimed.find((entry3) => entry3.hook);
59451
+ const hookless = !this.hookPanes.has(this.paneKey(record4));
59452
+ const own2 = row && (record4.hookClaim || hookless && record4.seenRow === row.offset);
59453
+ if (row && hookless && !own2) record4.seenRow = row.offset;
59454
+ free = unclaimed.filter((entry3) => !entry3.hook || own2 && entry3 === row);
59455
+ } else free = unclaimed;
58732
59456
  }
58733
- if (row.state === "delivered") delete row.error;
58734
- await this.save(row);
59457
+ if (!_PromptDeliveries.claimable(record4)) return false;
59458
+ const entry2 = free.shift();
59459
+ pass.set(key4, free);
59460
+ if (entry2 === void 0) return false;
59461
+ record4.entry = entry2.offset;
59462
+ record4.entryHook = entry2.hook;
59463
+ return true;
58735
59464
  }
58736
- /** Coalesced: the Hook calls this every 5 s whether or not the last tick
58737
- * finished, and queuing each behind the lock would hold every enqueue and
58738
- * status behind a backlog that grows faster than a slow tick drains it. */
58739
- tick() {
58740
- return this.ticking ??= this.sweep().finally(() => {
58741
- this.ticking = void 0;
58742
- });
59465
+ /** A turn in `target`'s pane ended: the agent now takes held input or never will. */
59466
+ stopped(target2) {
59467
+ const at2 = this.now();
59468
+ this.hookPanes.add(this.paneKey(target2));
59469
+ this.lastStop.set(this.paneKey(target2), at2);
59470
+ let marked = false;
59471
+ for (const record4 of this.records) if (this.samePane(record4, target2) && (record4.state === "typed" || record4.state === "queued") && record4.at < at2) {
59472
+ record4.stoppedAt = at2;
59473
+ marked = true;
59474
+ }
59475
+ if (marked) this.save();
58743
59476
  }
58744
- async sweep() {
58745
- const remote = await this.serial(async () => {
58746
- let rows2 = await this.rows();
58747
- if (this.now() - this.lastPrune >= DAY3) rows2 = await this.prune(rows2);
58748
- const attempted = /* @__PURE__ */ new Set(), remote2 = [];
58749
- for (const row of rows2) if (row.state === "queued") {
58750
- const key4 = JSON.stringify({ ...row.target, session: void 0 });
58751
- if (attempted.has(key4)) continue;
58752
- attempted.add(key4);
58753
- await this.attempt(row);
59477
+ /** Called on the Hook's activity tick with a server's panes. A message
59478
+ * still held fails loudly when its pane closed, its agent restarted, or the
59479
+ * agent ended a turn and stayed idle without taking it (unless its
59480
+ * transcript shows it after all). */
59481
+ async observe(server, panes2) {
59482
+ const now = this.now();
59483
+ let changed = false;
59484
+ const pass = /* @__PURE__ */ new Map();
59485
+ for (const record4 of this.records) {
59486
+ if (record4.server !== server) continue;
59487
+ if (record4.state === "failed" && record4.hookClaim) {
59488
+ if (record4.source === "claude" && (record4.checkedAt === void 0 || now - record4.checkedAt >= LANDED_CHECK_MS)) {
59489
+ record4.checkedAt = now;
59490
+ if (await this.taken(record4, pass, true)) {
59491
+ this.settle(record4);
59492
+ changed = true;
59493
+ }
59494
+ }
59495
+ continue;
58754
59496
  }
58755
- for (const row of rows2) if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state)) {
58756
- if (row.originComputer) {
58757
- remote2.push(row);
59497
+ if (record4.state !== "typed" && record4.state !== "queued") continue;
59498
+ const pane = panes2.find((entry2) => entry2.pane_id === record4.pane);
59499
+ if (!pane || record4.terminal && pane.terminal_id !== record4.terminal || pane.agent && pane.agent !== record4.source) {
59500
+ if (await this.taken(record4, pass)) {
59501
+ this.settle(record4);
59502
+ changed = true;
58758
59503
  continue;
58759
59504
  }
58760
- const forwarded = await this.options.forward?.(row.origin, `Hand-off ${row.deliveryId}: ${row.state}.`, this.noticeId(row)).catch(() => ({ delivered: false }));
58761
- if (forwarded) {
58762
- if (forwarded.delivered) {
58763
- row.notified = true;
58764
- await this.save(row);
59505
+ if (!_PromptDeliveries.open(record4)) continue;
59506
+ record4.state = "failed";
59507
+ record4.settledAt = now;
59508
+ changed = true;
59509
+ record4.reason = pane ? "The agent in this pane restarted before it took the message." : "The agent's pane closed before it took the message.";
59510
+ continue;
59511
+ }
59512
+ if (!["idle", "done"].includes(String(pane.agent_status))) {
59513
+ record4.idleSince = void 0;
59514
+ if (record4.source === "claude" && (record4.checkedAt === void 0 || now - record4.checkedAt >= LANDED_CHECK_MS)) {
59515
+ record4.checkedAt = now;
59516
+ if (await this.taken(record4, pass, true)) {
59517
+ this.settle(record4);
59518
+ changed = true;
58765
59519
  }
58766
- continue;
58767
- }
58768
- const id2 = this.noticeId(row);
58769
- if (!await this.read(id2)) {
58770
- const pane = await this.options.validate(row.origin).catch(() => void 0);
58771
- if (!pane || typeof pane.terminal_id !== "string") continue;
58772
- const at2 = new Date(this.now()).toISOString();
58773
- await this.save({
58774
- deliveryId: id2,
58775
- target: row.origin,
58776
- text: `Hand-off ${row.deliveryId}: ${row.state}.`,
58777
- terminal: pane.terminal_id,
58778
- state: "queued",
58779
- createdAt: at2,
58780
- updatedAt: at2
58781
- });
58782
59520
  }
58783
- row.notified = true;
58784
- await this.save(row);
59521
+ continue;
58785
59522
  }
58786
- return remote2;
58787
- });
58788
- await Promise.all(remote.map(async (row) => {
58789
- const result = await this.options.notify?.(row.origin, `Hand-off ${row.deliveryId}: ${row.state}.`, this.noticeId(row), row.originComputer).catch(() => void 0);
58790
- if (!result || !result.queued && !result.delivered && !result.deliveryUncertain) return;
58791
- await this.serial(async () => {
58792
- const current2 = await this.read(row.deliveryId);
58793
- if (current2 && !current2.notified) {
58794
- current2.notified = true;
58795
- await this.save(current2);
58796
- }
58797
- });
58798
- }));
58799
- }
58800
- noticeId(row) {
58801
- return `handoff-notice-${createHash30("sha256").update(row.deliveryId).digest("hex").slice(0, 40)}`;
58802
- }
58803
- /** Hold enqueues and delivery while the Hook validates and closes a worker.
58804
- * A new hand-off cannot be accepted between the pending check and closure. */
58805
- whenNoPending(target2, close) {
58806
- return this.serial(async () => {
58807
- if ((await this.rows()).some((row) => samePane3(row.target, target2) && ["queued", "attempting", "uncertain"].includes(row.state))) return { ok: true, closed: false };
58808
- return close();
58809
- });
58810
- }
58811
- hasPending(target2) {
58812
- return this.serial(async () => (await this.rows()).some((row) => samePane3(row.target, target2) && ["queued", "attempting", "uncertain"].includes(row.state)));
59523
+ record4.idleSince ??= now;
59524
+ if (record4.stoppedAt === void 0 || now - Math.max(record4.idleSince, record4.stoppedAt) < DELIVERY_GIVE_UP_MS) continue;
59525
+ if (await this.taken(record4, pass)) {
59526
+ this.settle(record4);
59527
+ changed = true;
59528
+ continue;
59529
+ }
59530
+ if (!_PromptDeliveries.open(record4)) continue;
59531
+ record4.state = "failed";
59532
+ record4.settledAt = now;
59533
+ changed = true;
59534
+ record4.reason = TURN_ENDED_WITHOUT_IT;
59535
+ }
59536
+ if (changed) this.save();
58813
59537
  }
58814
59538
  };
58815
59539
  }
58816
59540
  });
58817
59541
 
58818
- // src/bridge/git-write-policy.ts
58819
- function clientIdentity(headers) {
58820
- const clean5 = (value2) => (Array.isArray(value2) ? value2.join(", ") : value2 ?? "").replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 200);
58821
- const client = clean5(headers["x-phren-client"]);
58822
- const version2 = clean5(headers["x-phren-app-version"] || headers["x-phren-client-version"]);
58823
- const agent = clean5(headers["user-agent"]);
58824
- return [client, version2, agent].filter(Boolean).join(" / ") || "unknown client";
59542
+ // src/bridge/claude-suggestion.ts
59543
+ function claudeSuggestion(screen) {
59544
+ const text5 = liveInputDimText(screen);
59545
+ if (!text5 || text5.endsWith("\u2026") || text5.length > MAX_SUGGESTION || PLACEHOLDERS.some((pattern) => pattern.test(text5))) return void 0;
59546
+ return text5;
58825
59547
  }
58826
- var EXPECTED_REPOSITORY_REQUIRED, WRITE_ROUTES, isGitWriteRoute, GitWriteDiagnostics;
58827
- var init_git_write_policy = __esm({
58828
- "src/bridge/git-write-policy.ts"() {
58829
- "use strict";
58830
- EXPECTED_REPOSITORY_REQUIRED = false;
58831
- WRITE_ROUTES = new Set(["stage", "unstage", "discard", "commit", "push", "pr", "pr/merge", "host-token", "checkout", "fetch", "pull", "apply"].map((action) => `/v1/git/${action}`));
58832
- isGitWriteRoute = (route2) => WRITE_ROUTES.has(route2);
58833
- GitWriteDiagnostics = class {
58834
- clients = /* @__PURE__ */ new Map();
58835
- record(route2, headers) {
58836
- let client = clientIdentity(headers);
58837
- if (!this.clients.has(client) && this.clients.size >= 128) client = "other clients";
58838
- let entry2 = this.clients.get(client);
58839
- if (!entry2) {
58840
- entry2 = { count: 0, routes: /* @__PURE__ */ new Set() };
58841
- this.clients.set(client, entry2);
58842
- }
58843
- entry2.count++;
58844
- if (!entry2.routes.has(route2)) {
58845
- entry2.routes.add(route2);
58846
- console.warn(`[phren-hook] ${route2}: git write without expectedRepository from ${client}; update the app before the compatibility window ends.`);
59548
+ function claudeSuggestionShown(screen) {
59549
+ const text5 = liveInputDimText(screen);
59550
+ if (!text5 || text5.length > MAX_SUGGESTION || PLACEHOLDERS.some((pattern) => pattern.test(text5)) || SUBAGENT_VIEW.test(text5)) return void 0;
59551
+ return text5;
59552
+ }
59553
+ function claudeSubagentView(screen) {
59554
+ const text5 = liveInputDimText(screen);
59555
+ return !!text5 && SUBAGENT_VIEW.test(text5);
59556
+ }
59557
+ function liveInputDimText(screen) {
59558
+ const lines = screen.split("\n").map((line) => line.replace(/\r$/, ""));
59559
+ for (let index2 = lines.length - 2; index2 > 0; index2--) {
59560
+ const plain2 = stripTerminal(lines[index2]);
59561
+ if (!/^\s*❯/.test(plain2)) continue;
59562
+ if (!rule(stripTerminal(lines[index2 - 1])) || !rule(stripTerminal(lines[index2 + 1]))) return void 0;
59563
+ return dimText(lines[index2]);
59564
+ }
59565
+ return void 0;
59566
+ }
59567
+ function dimText(line) {
59568
+ let dim = false, prompt = false, text5 = "";
59569
+ for (const token of line.match(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|[^\x1b]/gu) ?? []) {
59570
+ if (token.startsWith("\x1B")) {
59571
+ if (!token.startsWith("\x1B[") || !token.endsWith("m")) continue;
59572
+ const codes = (token.slice(2, -1) || "0").split(/[;:]/).map(Number);
59573
+ for (let i = 0; i < codes.length; i++) {
59574
+ const code = codes[i];
59575
+ if (code === 38 || code === 48 || code === 58) {
59576
+ i += codes[i + 1] === 5 ? 2 : codes[i + 1] === 2 ? 4 : 0;
59577
+ continue;
58847
59578
  }
59579
+ if (code === 0 || code === 22) dim = false;
59580
+ else if (code === 2) dim = true;
58848
59581
  }
58849
- snapshot() {
58850
- return [...this.clients].map(([client, entry2]) => ({
58851
- client,
58852
- count: entry2.count,
58853
- warning: `${entry2.count} git writes without expectedRepository from ${client}`
58854
- }));
58855
- }
58856
- };
59582
+ } else if (!prompt) {
59583
+ if (token === "\u276F") prompt = true;
59584
+ } else if (!token.trim()) text5 += " ";
59585
+ else if (!dim) return "";
59586
+ else text5 += token;
59587
+ }
59588
+ return text5.replace(/\s+/g, " ").trim();
59589
+ }
59590
+ var MAX_SUGGESTION, rule, PLACEHOLDERS, SUBAGENT_VIEW;
59591
+ var init_claude_suggestion = __esm({
59592
+ "src/bridge/claude-suggestion.ts"() {
59593
+ "use strict";
59594
+ init_terminal_text();
59595
+ MAX_SUGGESTION = 500;
59596
+ rule = (line) => /^[─━═]{3,}/.test(line.trim());
59597
+ PLACEHOLDERS = [/^Try ".*"$/, /^Press (?:up|Enter) to /, /^Message @.*…$/];
59598
+ SUBAGENT_VIEW = /^Message @[\w.-]{1,20}…?…$/;
58857
59599
  }
58858
59600
  });
58859
59601
 
58860
59602
  // src/bridge/git-worktrees.ts
58861
- import { createHash as createHash31 } from "node:crypto";
58862
- import { realpath as realpath14, stat as stat20 } from "node:fs/promises";
59603
+ import { createHash as createHash32 } from "node:crypto";
59604
+ import { realpath as realpath14, stat as stat21 } from "node:fs/promises";
58863
59605
  import { homedir as homedir16 } from "node:os";
58864
59606
  import path101 from "node:path";
58865
59607
  function worktreeId(abs) {
58866
- return createHash31("sha256").update(`worktree\0${abs}`).digest("hex").slice(0, 32);
59608
+ return createHash32("sha256").update(`worktree\0${abs}`).digest("hex").slice(0, 32);
58867
59609
  }
58868
59610
  async function listed3(root) {
58869
59611
  const output2 = await git(root, "worktree", "list", "--porcelain", "-z");
@@ -58888,7 +59630,7 @@ async function listed3(root) {
58888
59630
  for (const [index2, block] of blocks.entries()) {
58889
59631
  if (block.bare !== void 0 || block.prunable !== void 0) continue;
58890
59632
  const abs = await realpath14(block.worktree).catch(() => void 0);
58891
- if (!abs || !(await stat20(abs).catch(() => void 0))?.isDirectory()) continue;
59633
+ if (!abs || !(await stat21(abs).catch(() => void 0))?.isDirectory()) continue;
58892
59634
  if (index2 === 0) main2 = abs;
58893
59635
  const branch = block.branch?.startsWith("refs/heads/") ? block.branch.slice("refs/heads/".length) : null;
58894
59636
  worktrees.push({ abs, head: block.HEAD ?? "", branch, locked: block.locked !== void 0 });
@@ -59268,7 +60010,7 @@ var init_git_review = __esm({
59268
60010
  // src/bridge/approval-rules.ts
59269
60011
  import { execFile as execFile22 } from "node:child_process";
59270
60012
  import { promisify as promisify20 } from "node:util";
59271
- import { createHash as createHash32, createPublicKey, verify } from "node:crypto";
60013
+ import { createHash as createHash33, createPublicKey, verify } from "node:crypto";
59272
60014
  import { lstat as lstat27, mkdir as mkdir24, readFile as readFile43, realpath as realpath15 } from "node:fs/promises";
59273
60015
  import { hostname as hostname8 } from "node:os";
59274
60016
  import path103 from "node:path";
@@ -59296,7 +60038,7 @@ function verified(envelope, keys2) {
59296
60038
  const key4 = createPublicKey({ key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), raw]), format: "der", type: "spki" });
59297
60039
  if (!verify(null, payload, key4, signature)) throw forbidden();
59298
60040
  const operation = operationSchema2.parse(JSON.parse(payload.toString("utf8")));
59299
- return { operation, owner: createHash32("sha256").update(raw).digest("hex") };
60041
+ return { operation, owner: createHash33("sha256").update(raw).digest("hex") };
59300
60042
  }
59301
60043
  async function privateJSON(file4, fallback2, max = 2097152) {
59302
60044
  const info = await lstat27(file4).catch((error62) => {
@@ -59346,7 +60088,7 @@ async function locked(root, work) {
59346
60088
  }
59347
60089
  async function listApprovalRules(root = bridgeRoot(), pairedKey) {
59348
60090
  try {
59349
- const pairedOwner = pairedKey ? createHash32("sha256").update(Buffer.from(pairedKey, "base64")).digest("hex") : void 0;
60091
+ const pairedOwner = pairedKey ? createHash33("sha256").update(Buffer.from(pairedKey, "base64")).digest("hex") : void 0;
59350
60092
  return [...(await readPolicy(root)).rules.values()].map((rule2) => ({
59351
60093
  ...rule2,
59352
60094
  signerFingerprint: "SHA256:" + Buffer.from(rule2.owner, "hex").toString("base64").replace(/=+$/, ""),
@@ -59468,7 +60210,7 @@ import { readFile as readFile44 } from "node:fs/promises";
59468
60210
  import path104 from "node:path";
59469
60211
  async function conductorBrief() {
59470
60212
  let source;
59471
- if (true) source = '---\nname: conductor\ndescription: Coordinate independent Phren tasks across every project in the store and every enrolled computer, supervise their local agent fanout, and integrate verified returns in a concise dispatcher voice.\n---\n\n# Conductor\n\nYou are the owner\'s dispatcher for the whole store, not one project. You start\nin the phren store itself; that folder is not a project and not your work.\n\nFirst, before trusting your tools, check which phren you are running:\n`phren --version` and `command -v phren`. If the version is older than the one\nthe store or the owner expects, or the path is not the install you expect (a\nstale global package, an old checkout), tell the owner in one line and say\nwhich tools may be missing or behave differently.\n\nThen read the relevant projects\' summaries and Phren tasks\n(`get_project_summary`, `get_tasks`) before selecting work.\n\nYour tools, use these instead of exploring the CLI or the Hook\'s files:\n\n- `live_sessions` (CLI `phren dispatch sessions`): every live agent on this\n computer and each enrolled one, with project, harness, status, `idleFor`\n (seconds since it last changed) and the target `hand_off` takes. Start here\n when asked what is running. Computers it could not reach are listed; say so\n rather than guessing. Computers in `notLinked` are registered in the store\n but have no Hook link here: say they were not checked, never that nothing is\n running there.\n- `hand_off`: send a prompt to one of those sessions.\n- `account_usage` (CLI `phren dispatch usage`): every computer\'s agent usage\n merged by account (each Claude login, Codex, OpenCode Go and the rest): percent\n left on each window, when it resets, whether the numbers are fresh, and the\n computers where it is signed in. In core use\n `phren_admin(action: "account_usage")`.\n- `hand_off`: send a prompt to one of those sessions. A busy session queues it\n durably in its Hook. Keep its `deliveryId`; `queued` means waiting, `delivered`\n means confirmed. Check with `hand_off(target|session, computer?, deliveryId,\n status:true)` and no text. Never resend with a new id because it is busy.\n- `dispatch`: start a new worker on a computer (or `anywhere`).\n- `dispatch_returns` (CLI `phren dispatch returns`): what your workers sent\n back since you last asked: done with the final reply, needs-you with the\n question, stalled with an unchanged screen and transcript, failed with the error (a usage limit), blocked, or gone. Reading them marks them read. In core use\n `phren_admin(action: "dispatch_returns")`.\n- `dispatch_report`: workers record `prs`, an array of `{url, repo, branch,\n tests, notes?}`, on their own Hook before ending the turn. The done return\n carries that evidence, and the Hook queues it to the configured integrator.\n In core use `phren_admin(action: "dispatch_report", prs)`.\n- `owner_inbox` (CLI `phren owner-inbox`): list what waits on the owner across\n linked computers, add a title with optional project, or resolve an id with\n optional resolution. In core use `phren_admin(action: "owner_inbox", ...)`.\n Use an item\'s `inboxComputer` as `computer` when resolving a remote item;\n omit it for `local`. Say which computers were unreachable.\n- `phren dispatch status`: receipts of what you dispatched.\n- `get_tasks`, `get_project_summary`, `search_knowledge`: the store\'s memory.\n\nKeep engineering detail in worker briefs, Phren tasks and findings, and review\nartifacts, not in the owner\'s chat.\n\n## Voice and pace\n\nThe owner talks to you from the phone, often in talk mode, where your replies\nare read aloud in their voice. Sound like a good dispatcher: short, quick and\nconversational.\n\n- Lead with the outcome in one sentence. Keep the whole reply to one to four\n short sentences unless the owner asks for detail.\n- No tables, file paths, SHAs, PR numbers or run IDs in a reply unless the\n owner asks for them. Record them in Phren tasks and findings instead.\n- One short line per dispatch or return: who, what, result. A routine watcher\n or monitor event where nothing changed gets silence or a single line.\n- When the owner gives you a task, dispatch an engineer for it right away and\n say so in one line. That is the owner\'s standing rule; do not ask first.\n- Ask at most one question at a time, and name the options.\n- Delegate reading and analysis to workers instead of running long\n investigations yourself, so your own turns stay fast.\n- A message that begins with `[voice]` was spoken in talk mode, and your reply\n will be read aloud. Answer in one or two spoken sentences with no markdown,\n lists, symbols or code, written to sound natural read aloud: "back in about\n twenty minutes", not "ETA ~20m".\n\n```text\nDevbox has the parser checks on Codex, back around two twenty.\nDesk finished the navigation checks: tests passed, not merged yet.\n```\n\nIf a result or return time is unknown, say so. Surface a worker\'s question in\nthe same short voice, with the worker\'s own choices.\n\n## Dispatching\n\nPick five to ten independent tasks when that many are available and capacity\npermits. Do not manufacture tasks to fill the batch. Separate dependencies and\nfile ownership; give each remote lead a base revision, acceptance checks, local\nfanout limit, report time and integration instructions. Every brief repeats the\nowner\'s repository constraints, including any prohibition on commits, pushes,\nbranches or particular tests. Dispatch never expands the owner\'s authorization.\nA worker that needs root runs `sudo -A <command>`: its launch sets\n`SUDO_ASKPASS`, and the owner approves the exact command and types the\npassword on the phone. Plain `sudo` fails without a terminal.\n\nYou are the one conductor for this computer and every computer linked with\nit; a second conductor in the group is refused at launch. Conductors on\ncomputers that are not linked share only the store, so claim a task before you\ndispatch it: `claim_task` (in core, `manage_task` with `action: "claim"`).\nSkip tasks marked `[claimed: <computer>]` by another computer. A claim that\ncomes back not claimed, with `heldBy`, means another conductor got there first:\nmove on. Completing a task clears its claim; release one you will not do. Start\nworkers with `dispatch` or `hand_off`, never as tabs in your own Herdr\nworkspace. When a computer shows up in `notLinked`, tell the owner that\n`phren bridge link <host>` can link it; never link a computer yourself.\n\nPrefer Codex. Use OpenCode Go when its account and harness are connected. Use\nOpenRouter only when the owner explicitly requests it; an unavailable account\ndoes not authorize another paid provider. Name an explicit model when instructed,\notherwise use and report the remote configured default. Each remote lead owns\nits local checkouts, fanout and provider rate limits. Where installed, local\nworkers use the fanout wrapper\'s `scripts/run.sh --provider codex|opencode\n--label --worktree [--model] [--mode]` contract and parent-bound manifests.\nTell every lead the same: a worker started any other way (its own `opencode\nrun` or `codex exec`, a launch script, nohup) has no manifest, so the phone and\nyou cannot see, resume or review it. Workers that exist only as processes do\nnot count as dispatched.\n\nCheck `account_usage` before you dispatch, once per batch. The one hard rule:\nnever dispatch to an account that is `exhausted` (a window at 100%, or\nrefusing requests), until its `availableIn` passes. Low quota is information,\nnot a reason to steer away: `nearLimit` (under 20% left) is still usable, and\nthe owner often wants quota used up before it resets, so an account with quota\nleft that resets soon is a good pick; use it before it resets. For Claude, pass\nthe `account` id the row\'s `computers` list gives for the computer you pick. A\n`stale` row\'s numbers may be out of date, and a window marked `reset` has\nrolled over with no new number yet: say so rather than quoting them. Name the\nchoice in the dispatch line, such as "Desk has the parser checks on Codex,\nusing its last 15% before the week resets tomorrow." When every account is\nexhausted, tell the owner before dispatching. The owner\'s explicit choice of\nharness or account always wins. Usage on `unreachable` and `notLinked`\ncomputers is unknown, not zero.\n\nPrefer handing work to a session that already owns the project and is idle or\ndoing related work; call `hand_off` in full or `phren_admin(action: "hand_off",\ncomputer?, target|session, text)` in core. Otherwise dispatch a new worker.\nWrite one short line either way. Call `dispatch` in full or\n`phren_admin(action: "dispatch", computer, project, harness, model?, effort?, permissionMode?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>] [--effort <effort>]\n[--permission-mode supervised|auto-edits|auto|full-access]`. `permissionMode` sets how the\nworker starts (Claude, Codex and Copilot; not OpenCode). `harness` is codex,\nclaude, opencode or copilot.\nFor release work (merge, publish, deploy, app-store, github-admin), read the\nowner\'s release authority policy first with `authority` in full or\n`phren_admin(action: "authority", project)` in core (CLI: `phren authority show\n<project>`), quote its `line` in the brief, and list the actions in\n`releaseActions`. An ask-first action is refused until the owner confirms it:\nask them, and never confirm or change the policy yourself. The policy only\nrestricts; when a worker\'s own harness still refuses release work, only the\nowner\'s own harness settings can allow it.\n`anywhere` chooses the connected computer with the fewest working agents, and\nskips one whose account for that harness is exhausted. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\nConfigure the integrator once with `phren conductor integrator --session <id>\n[--computer <name>]`; list with `phren conductor integrator`, clear with\n`--clear`. A dispatch can override it with `integrator: {computer?, target}`.\nThe integrator\'s full target is bound to that conversation. Workers report\nstructured PR evidence with `dispatch_report(prs)` in full or\n`phren_admin(action:"dispatch_report", prs)` in core before finishing; they do not\nneed direct messaging or a GitHub comment to reach it. Inspect `prs` and\n`integratorDelivery` in receipts and verify the evidence before integration.\n\nFinished worker panes close after their done return is read. Use\n`closeOnFinish:false` (`--keep-open` in the CLI) for a worker you will reuse.\nThe Hook rechecks its ended turn and skips a pane with new work, background\ntasks, queued messages or uncertain delivery. Intentional closes do not return\n`gone`. Reading returns can close panes, so record any follow-up first.\n\nKeep one owner inbox item for each decision or action that waits on the owner.\nNeeds-you returns and blocked prompts appear automatically, even if their\nreturns were read. Add other actions such as restarting the router with\n`owner_inbox(operation:"add", title, project?, id?)` in full or\n`phren_admin(action:"owner_inbox", operation:"add", title, project?, id?)` in\ncore; keep the id on retries.\nResolve an item only once the owner decided or completed the action. Resolution\ndoes not send an answer, approve a prompt, or mark a task complete. Send an\nowner\'s answer separately with queued `hand_off`. A source that stopped waiting\nis retained as `live:false` until resolved; a resolved source stays resolved.\n\n`accepted` on a receipt is prompt acceptance, not worker completion. Returns\narrive on their own: the Hook follows every worker you dispatch, and when you\nare idle it types one line into this session, such as `Return: Devbox parser\nchecks done, tests passed (dispatch <id>). Call dispatch_returns.` When you see\none, call `dispatch_returns` and report each return in one short line. You may\nalso call it whenever you want the current state; do not poll it in a loop, and\ndo not read remote transcripts by hand to learn whether a worker finished. Tell\nthe owner a return time as an expectation, not a promise.\n\nA return with an `approval` is a permission request a worker is waiting on.\nAnswer it with `dispatch_approve` when it is plainly what the brief asked for;\ndeny when unsure and ask the owner. Standing grants already answer `dispatch`\nand `hand_off` requests they cover.\n\nFor a `needs-you` return, surface the worker\'s question in the owner\'s chat\nwith its choices as the worker wrote them; do not rewrite or answer it for the\nowner unless the owner already decided. Send the answer back with `hand_off`\nto the row\'s `target`. A `blocked` worker waits on terminal input, such as a\npermission prompt: say so and point the owner to the phone or the terminal. A\n`gone` worker\'s pane closed or was taken over: say so, and decide with the\nowner before giving its work to another agent. A `done` reply is the worker\'s\nown account; check its evidence before saying tests passed or work merged.\n\nA `stalled` return or `live_sessions` row with `stalled:true` means both the\nscreen and transcript have stopped changing while working. Check it and report\nwhat is known; do not launch a duplicate or interrupt it just because of the flag.\n\nAn uncertain delivery is never retried automatically. Inspect its known target\nor status before deciding with the owner whether a replacement is needed. Keep\nunavailable workers visible instead of giving their work to another agent\nwhile the original may still be running.\n\nIntegrate returned changes in dependency order within the owner\'s allowed\nworkflow. Run a cleanup pass across the combined result and the affected checks.\nRequire evidence before saying tests passed or merged. Ship only within existing\nauthorization; if publication is not authorized, return the reviewable result.\nUpdate Phren tasks when verified complete and save durable decisions. A worker\'s\nfinished turn alone does not complete the owner\'s task.\n';
60213
+ if (true) source = "---\nname: conductor\ndescription: Coordinate independent Phren tasks across every project in the store and every enrolled computer, supervise their local agent fanout, and integrate verified returns in a concise dispatcher voice.\n---\n\n# Conductor\n\nYou are the owner's dispatcher for the whole store, not one project. You start\nin the phren store itself; that folder is not a project and not your work.\n\nFirst, before trusting your tools, check which phren you are running:\n`phren --version` and `command -v phren`. If the version is older than the one\nthe store or the owner expects, or the path is not the install you expect (a\nstale global package, an old checkout), tell the owner in one line and say\nwhich tools may be missing or behave differently.\n\nThen read the relevant projects' summaries and Phren tasks\n(`get_project_summary`, `get_tasks`) before selecting work.\n\nYour tools, use these instead of exploring the CLI or the Hook's files:\n\n- `live_sessions` (CLI `phren dispatch sessions`): every live agent on this\n computer and each enrolled one, with project, harness, status, `idleFor`\n (seconds since it last changed) and the target `hand_off` takes. Start here\n when asked what is running. Computers it could not reach are listed; say so\n rather than guessing. Computers in `notLinked` are registered in the store\n but have no Hook link here: say they were not checked, never that nothing is\n running there.\n- `hand_off`: send a prompt to one of those sessions.\n- `account_usage` (CLI `phren dispatch usage`): every computer's agent usage\n merged by account (each Claude login, Codex, OpenCode Go and the rest): percent\n left on each window, when it resets, whether the numbers are fresh, and the\n computers where it is signed in. In core use\n `phren_admin(action: \"account_usage\")`.\n- `hand_off`: send a prompt to one of those sessions. A busy session queues it\n durably in its Hook. Keep its `deliveryId`; `queued` means waiting, `delivered`\n means confirmed. Check with `hand_off(target|session, computer?, deliveryId,\n status:true)` and no text. Never resend with a new id because it is busy.\n- `dispatch`: start a new worker on a computer (or `anywhere`).\n- `dispatch_returns` (CLI `phren dispatch returns`): what your workers sent\n back since you last asked: done with the final reply, needs-you with the\n question, stalled with an unchanged screen and transcript, failed with the error (a usage limit), blocked, or gone. Reading them marks them read. In core use\n `phren_admin(action: \"dispatch_returns\")`.\n- `dispatch_report`: workers record `prs`, an array of `{url, repo, branch,\n tests, notes?}`, on their own Hook before ending the turn. The done return\n carries that evidence, and the Hook queues it to the configured integrator.\n In core use `phren_admin(action: \"dispatch_report\", prs)`.\n- `owner_inbox` (CLI `phren owner-inbox`): list what waits on the owner across\n linked computers, add a title with optional project, or resolve an id with\n optional resolution. In core use `phren_admin(action: \"owner_inbox\", ...)`.\n Use an item's `inboxComputer` as `computer` when resolving a remote item;\n omit it for `local`. Say which computers were unreachable.\n- `phren dispatch status`: receipts of what you dispatched.\n- `get_tasks`, `get_project_summary`, `search_knowledge`: the store's memory.\n\nKeep engineering detail in worker briefs, Phren tasks and findings, and review\nartifacts, not in the owner's chat.\n\n## Voice and pace\n\nThe owner talks to you from the phone, often in talk mode, where your replies\nare read aloud in their voice. Sound like a good dispatcher: short, quick and\nconversational.\n\n- Lead with the outcome in one sentence. Keep the whole reply to one to four\n short sentences unless the owner asks for detail.\n- No tables, file paths, SHAs, PR numbers or run IDs in a reply unless the\n owner asks for them. Record them in Phren tasks and findings instead.\n- One short line per dispatch or return: who, what, result. A routine watcher\n or monitor event where nothing changed gets silence or a single line.\n- When the owner gives you a task, dispatch an engineer for it right away and\n say so in one line. That is the owner's standing rule; do not ask first.\n- Ask at most one question at a time, and name the options.\n- Delegate reading and analysis to workers instead of running long\n investigations yourself, so your own turns stay fast.\n- A message that begins with `[voice]` was spoken in talk mode, and your reply\n will be read aloud. Answer in one or two spoken sentences with no markdown,\n lists, symbols or code, written to sound natural read aloud: \"back in about\n twenty minutes\", not \"ETA ~20m\".\n\n```text\nDevbox has the parser checks on Codex, back around two twenty.\nDesk finished the navigation checks: tests passed, not merged yet.\n```\n\nIf a result or return time is unknown, say so. Surface a worker's question in\nthe same short voice, with the worker's own choices.\n\n## Dispatching\n\nPick five to ten independent tasks when that many are available and capacity\npermits. Do not manufacture tasks to fill the batch. Separate dependencies and\nfile ownership; give each remote lead a base revision, acceptance checks, local\nfanout limit, report time and integration instructions. Every brief repeats the\nowner's repository constraints, including any prohibition on commits, pushes,\nbranches or particular tests. Dispatch never expands the owner's authorization.\nA worker that needs root runs `sudo -A <command>`: its launch sets\n`SUDO_ASKPASS`, and the owner approves the exact command and types the\npassword on the phone. Plain `sudo` fails without a terminal.\n\nYou are the one conductor for this computer and every computer linked with\nit; a second conductor in the group is refused at launch. Conductors on\ncomputers that are not linked share only the store, so claim a task before you\ndispatch it: `claim_task` (in core, `manage_task` with `action: \"claim\"`).\nSkip tasks marked `[claimed: <computer>]` by another computer. A claim that\ncomes back not claimed, with `heldBy`, means another conductor got there first:\nmove on. Completing a task clears its claim; release one you will not do. Start\nworkers with `dispatch` or `hand_off`, never as tabs in your own Herdr\nworkspace. When a computer shows up in `notLinked`, tell the owner that\n`phren bridge link <host>` can link it; never link a computer yourself.\n\nPrefer Codex. Use OpenCode Go when its account and harness are connected. Use\nOpenRouter only when the owner explicitly requests it; an unavailable account\ndoes not authorize another paid provider. Name an explicit model when instructed,\notherwise use and report the remote configured default. Each remote lead owns\nits local checkouts, fanout and provider rate limits. Where installed, local\nworkers use the fanout wrapper's `scripts/run.sh --provider codex|opencode\n--label --worktree [--model] [--mode]` contract and parent-bound manifests.\nTell every lead the same: a worker started any other way (its own `opencode\nrun` or `codex exec`, a launch script, nohup) has no manifest, so the phone and\nyou cannot see, resume or review it. Workers that exist only as processes do\nnot count as dispatched.\n\nCheck `account_usage` before you dispatch, once per batch. The one hard rule:\nnever dispatch to an account that is `exhausted` (a window at 100%, or\nrefusing requests), until its `availableIn` passes. Low quota is information,\nnot a reason to steer away: `nearLimit` (under 20% left) is still usable, and\nthe owner often wants quota used up before it resets, so an account with quota\nleft that resets soon is a good pick; use it before it resets. For Claude, pass\nthe `account` id the row's `computers` list gives for the computer you pick. A\n`stale` row's numbers may be out of date, and a window marked `reset` has\nrolled over with no new number yet: say so rather than quoting them. Name the\nchoice in the dispatch line, such as \"Desk has the parser checks on Codex,\nusing its last 15% before the week resets tomorrow.\" When every account is\nexhausted, tell the owner before dispatching. The owner's explicit choice of\nharness or account always wins. Usage on `unreachable` and `notLinked`\ncomputers is unknown, not zero.\n\nPrefer handing work to a session that already owns the project and is idle or\ndoing related work; call `hand_off` in full or `phren_admin(action: \"hand_off\",\ncomputer?, target|session, text)` in core. Otherwise dispatch a new worker.\nWrite one short line either way. Call `dispatch` in full or\n`phren_admin(action: \"dispatch\", computer, project, harness, model?, effort?, permissionMode?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>] [--effort <effort>]\n[--permission-mode supervised|auto-edits|auto|full-access]`. `permissionMode` sets how the\nworker starts (Claude, Codex and Copilot; not OpenCode). `harness` is codex,\nclaude, opencode or copilot.\nFor release work (merge, publish, deploy, app-store, github-admin), read the\nowner's release authority policy first with `authority` in full or\n`phren_admin(action: \"authority\", project)` in core (CLI: `phren authority show\n<project>`), quote its `line` in the brief, and list the actions in\n`releaseActions`. An ask-first action is refused until the owner confirms it:\nask them, and never confirm or change the policy yourself. The policy only\nrestricts; when a worker's own harness still refuses release work, only the\nowner's own harness settings can allow it.\n`anywhere` chooses the connected computer with the fewest working agents, and\nskips one whose account for that harness is exhausted. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\nConfigure the integrator once with `phren conductor integrator --session <id>\n[--computer <name>]`; list with `phren conductor integrator`, clear with\n`--clear`. A dispatch can override it with `integrator: {computer?, target}`.\nThe integrator's full target is bound to that conversation. Workers report\nstructured PR evidence with `dispatch_report(prs)` in full or\n`phren_admin(action:\"dispatch_report\", prs)` in core before finishing; they do not\nneed direct messaging or a GitHub comment to reach it. Inspect `prs` and\n`integratorDelivery` in receipts and verify the evidence before integration.\n\nFinished worker panes close after their done return is read. Use\n`closeOnFinish:false` (`--keep-open` in the CLI) for a worker you will reuse.\nThe Hook rechecks its ended turn and skips a pane with new work, background\ntasks, queued messages or uncertain delivery. Intentional closes do not return\n`gone`. Reading returns can close panes, so record any follow-up first.\n\nKeep one owner inbox item for each decision or action that waits on the owner.\nNeeds-you returns and blocked prompts appear automatically, even if their\nreturns were read. Add other actions such as restarting the router with\n`owner_inbox(operation:\"add\", title, project?, id?)` in full or\n`phren_admin(action:\"owner_inbox\", operation:\"add\", title, project?, id?)` in\ncore; keep the id on retries.\nResolve an item only once the owner decided or completed the action. Resolution\ndoes not send an answer, approve a prompt, or mark a task complete. Send an\nowner's answer separately with queued `hand_off`. A source that stopped waiting\nis retained as `live:false` until resolved; a resolved source stays resolved.\n\n`accepted` on a receipt is prompt acceptance, not worker completion. Returns\narrive on their own: the Hook follows every worker you dispatch, and when you\nare idle it types one line into this session, such as `Return: Devbox parser\nchecks done, tests passed (dispatch <id>). Call dispatch_returns.` When you see\none, call `dispatch_returns` and report each return in one short line. You may\nalso call it whenever you want the current state; do not poll it in a loop, and\ndo not read remote transcripts by hand to learn whether a worker finished. Tell\nthe owner a return time as an expectation, not a promise.\n\nA return with an `approval` is a permission request a worker is waiting on.\nAnswer it with `dispatch_approve` when it is plainly what the brief asked for;\ndeny when unsure and ask the owner. Standing grants already answer `dispatch`\nand `hand_off` requests they cover.\n\nFor a `needs-you` return, surface the worker's question in the owner's chat\nwith its choices as the worker wrote them; do not rewrite or answer it for the\nowner unless the owner already decided. Send the answer back with `hand_off`\nto the row's `target`. A `blocked` worker waits on terminal input, such as a\npermission prompt: say so and point the owner to the phone or the terminal. A\n`gone` worker's pane closed or was taken over: say so, and decide with the\nowner before giving its work to another agent. A `done` reply is the worker's\nown account; check its evidence before saying tests passed or work merged.\n\nA `stalled` return or `live_sessions` row with `stalled:true` means both the\nscreen and transcript have stopped changing while working. Check it and report\nwhat is known; do not launch a duplicate or interrupt it just because of the flag.\n\nNever submit, clear or relay text you read in a Claude pane's input box as the\nowner's words. After a turn Claude draws its own guess at the owner's next\nmessage there, dim; a plain screen read shows it as if typed, and Enter does not\nsend it. The Hook keeps a delivery record for each phone message, so an owner\nmessage never needs rescuing from a pane. Ask the owner instead. The Hook\nrefuses a hand-off that repeats a pane's suggestion (`prompt-suggestion`).\n\nAn uncertain delivery is never retried automatically. Inspect its known target\nor status before deciding with the owner whether a replacement is needed. Keep\nunavailable workers visible instead of giving their work to another agent\nwhile the original may still be running.\n\nIntegrate returned changes in dependency order within the owner's allowed\nworkflow. Run a cleanup pass across the combined result and the affected checks.\nRequire evidence before saying tests passed or merged. Ship only within existing\nauthorization; if publication is not authorized, return the reviewable result.\nUpdate Phren tasks when verified complete and save durable decisions. A worker's\nfinished turn alone does not complete the owner's task.\n";
59472
60214
  else {
59473
60215
  const here = path104.dirname(fileURLToPath(import.meta.url));
59474
60216
  for (const candidate of [
@@ -59510,7 +60252,7 @@ var init_conductor_context = __esm({
59510
60252
 
59511
60253
  // src/bridge/push.ts
59512
60254
  import { createCipheriv, createHmac as createHmac4, createPrivateKey, randomBytes as randomBytes7, sign } from "node:crypto";
59513
- import { readFile as readFile45, stat as stat21 } from "node:fs/promises";
60255
+ import { readFile as readFile45, stat as stat22 } from "node:fs/promises";
59514
60256
  import { connect as connect3 } from "node:http2";
59515
60257
  import path105 from "node:path";
59516
60258
  function scheduleCollapseId(kind, runId) {
@@ -59579,7 +60321,7 @@ function schedulePushPayload(value2) {
59579
60321
  }
59580
60322
  async function secureJSON(file4, schema) {
59581
60323
  try {
59582
- const metadata = await stat21(file4);
60324
+ const metadata = await stat22(file4);
59583
60325
  if ((metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
59584
60326
  return schema.parse(JSON.parse(await readFile45(file4, "utf8")));
59585
60327
  } catch {
@@ -59588,7 +60330,7 @@ async function secureJSON(file4, schema) {
59588
60330
  }
59589
60331
  async function secureFile(file4) {
59590
60332
  try {
59591
- const metadata = await stat21(file4);
60333
+ const metadata = await stat22(file4);
59592
60334
  if (!metadata.isFile() || (metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
59593
60335
  return await readFile45(file4, "utf8");
59594
60336
  } catch {
@@ -60201,14 +60943,15 @@ var init_pair = __esm({
60201
60943
  publicKey: external_exports.string().max(512),
60202
60944
  proof: external_exports.string().max(128),
60203
60945
  device: external_exports.enum(["ios", "android"]).default("ios"),
60204
- name: external_exports.string().max(80).optional()
60946
+ name: external_exports.string().max(80).optional(),
60947
+ typed: external_exports.boolean().optional()
60205
60948
  });
60206
60949
  }
60207
60950
  });
60208
60951
 
60209
60952
  // src/bridge/opencode-permissions.ts
60210
60953
  import { randomUUID as randomUUID24 } from "node:crypto";
60211
- import { lstat as lstat28, mkdir as mkdir25, readFile as readFile46, rename as rename6, unlink as unlink6, writeFile as writeFile7 } from "node:fs/promises";
60954
+ import { lstat as lstat28, mkdir as mkdir25, readFile as readFile46, rename as rename7, unlink as unlink6, writeFile as writeFile7 } from "node:fs/promises";
60212
60955
  import path106 from "node:path";
60213
60956
  function opencodeConfigPath(env = process.env, home = homeDir(env)) {
60214
60957
  return path106.join(env.XDG_CONFIG_HOME || path106.join(home, ".config"), "opencode", "opencode.json");
@@ -60242,484 +60985,44 @@ function withAllowedTool(config4, tool) {
60242
60985
  if (!permission || typeof permission !== "object" || Array.isArray(permission)) {
60243
60986
  throw new BridgeError(409, "The opencode permission block is not a JSON object.");
60244
60987
  }
60245
- const block = { ...permission };
60246
- const existing = block[tool];
60247
- if (existing && typeof existing === "object" && !Array.isArray(existing)) {
60248
- const merged = { "*": "allow", ...existing };
60249
- merged["*"] = "allow";
60250
- block[tool] = merged;
60251
- } else block[tool] = "allow";
60252
- return { ...config4, permission: block };
60253
- }
60254
- async function allowOpencodeToolEverywhere(tool, file4 = opencodeConfigPath()) {
60255
- const name = opencodeToolName(tool);
60256
- if (!name) throw new BridgeError(400, "OpenCode did not name a tool this can allow.");
60257
- const release = tryFileLock(file4);
60258
- if (!release) throw new BridgeError(409, "~/.config/opencode/opencode.json is being updated. Try again.");
60259
- try {
60260
- const config4 = withAllowedTool(await readConfig2(file4), name);
60261
- const mode = (await lstat28(file4).catch(() => void 0))?.mode;
60262
- await mkdir25(path106.dirname(file4), { recursive: true, mode: 448 });
60263
- const temporary = `${file4}.${randomUUID24()}.tmp`;
60264
- await writeFile7(temporary, `${JSON.stringify(config4, null, 2)}
60265
- `, { mode: mode === void 0 ? 384 : mode & 511, flag: "wx" });
60266
- try {
60267
- await rename6(temporary, file4);
60268
- } finally {
60269
- await unlink6(temporary).catch(() => {
60270
- });
60271
- }
60272
- return name;
60273
- } finally {
60274
- release();
60275
- }
60276
- }
60277
- var init_opencode_permissions = __esm({
60278
- "src/bridge/opencode-permissions.ts"() {
60279
- "use strict";
60280
- init_locks();
60281
- init_home_paths();
60282
- init_protocol();
60283
- }
60284
- });
60285
-
60286
- // src/bridge/prompt-deliveries.ts
60287
- import { createHash as createHash33 } from "node:crypto";
60288
- import { readFileSync as readFileSync45 } from "node:fs";
60289
- import { open as open18 } from "node:fs/promises";
60290
- function promptKey(text5) {
60291
- return unwrapPastedContent(text5).split("\n").filter((line) => !PICTURE_PATH_LINE.test(line)).join("\n").replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
60292
- }
60293
- function matchingOffsets(buffer, start, record4) {
60294
- const entries2 = [];
60295
- const lines = buffer.toString("utf8").split("\n");
60296
- let offset = start + buffer.length;
60297
- for (let index2 = lines.length - 1; index2 >= 0; index2--) {
60298
- const line = lines[index2];
60299
- offset -= Buffer.byteLength(line) + (index2 < lines.length - 1 ? 1 : 0);
60300
- let row;
60301
- try {
60302
- row = object2(JSON.parse(line));
60303
- } catch {
60304
- continue;
60305
- }
60306
- 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" });
60309
- }
60310
- return entries2;
60988
+ const block = { ...permission };
60989
+ const existing = block[tool];
60990
+ if (existing && typeof existing === "object" && !Array.isArray(existing)) {
60991
+ const merged = { "*": "allow", ...existing };
60992
+ merged["*"] = "allow";
60993
+ block[tool] = merged;
60994
+ } else block[tool] = "allow";
60995
+ return { ...config4, permission: block };
60311
60996
  }
60312
- async function transcriptEntries(record4) {
60313
- const file4 = await open18(await transcriptPath(record4.source, record4.session), "r");
60997
+ async function allowOpencodeToolEverywhere(tool, file4 = opencodeConfigPath()) {
60998
+ const name = opencodeToolName(tool);
60999
+ if (!name) throw new BridgeError(400, "OpenCode did not name a tool this can allow.");
61000
+ const release = tryFileLock(file4);
61001
+ if (!release) throw new BridgeError(409, "~/.config/opencode/opencode.json is being updated. Try again.");
60314
61002
  try {
60315
- const size = (await file4.stat()).size, start = Math.max(0, size - 524288), buffer = Buffer.alloc(size - start);
60316
- await file4.read(buffer, 0, buffer.length, start);
60317
- return matchingOffsets(buffer, start, record4);
61003
+ const config4 = withAllowedTool(await readConfig2(file4), name);
61004
+ const mode = (await lstat28(file4).catch(() => void 0))?.mode;
61005
+ await mkdir25(path106.dirname(file4), { recursive: true, mode: 448 });
61006
+ const temporary = `${file4}.${randomUUID24()}.tmp`;
61007
+ await writeFile7(temporary, `${JSON.stringify(config4, null, 2)}
61008
+ `, { mode: mode === void 0 ? 384 : mode & 511, flag: "wx" });
61009
+ try {
61010
+ await rename7(temporary, file4);
61011
+ } finally {
61012
+ await unlink6(temporary).catch(() => {
61013
+ });
61014
+ }
61015
+ return name;
60318
61016
  } finally {
60319
- await file4.close();
61017
+ release();
60320
61018
  }
60321
61019
  }
60322
- function userTexts(row) {
60323
- const texts = [];
60324
- const blocks = (content) => {
60325
- if (typeof content === "string") texts.push(content);
60326
- else for (const block of objects(content)) if (typeof block.text === "string") texts.push(block.text);
60327
- };
60328
- if (row.type === "user" && !row.isMeta) blocks(object2(row.message).content);
60329
- if (row.type === "queue-operation" && row.operation === "remove" && typeof row.content === "string" && (row.reason === "absorbed_mid_turn" || row.reason === "delivered_to_agent")) texts.push(row.content);
60330
- const payload = object2(row.payload);
60331
- if (payload.type === "user_message" && typeof payload.message === "string") texts.push(payload.message);
60332
- if (payload.type === "message" && payload.role === "user") blocks(payload.content);
60333
- return texts;
60334
- }
60335
- var DELIVERY_RETENTION_MS, DELIVERY_GIVE_UP_MS, MAX_RECORDS, LANDED_CHECK_MS, ENTRY_SLACK_MS, PICTURE_PATH_LINE, promptHash, recordSchema2, PromptDeliveries;
60336
- var init_prompt_deliveries = __esm({
60337
- "src/bridge/prompt-deliveries.ts"() {
61020
+ var init_opencode_permissions = __esm({
61021
+ "src/bridge/opencode-permissions.ts"() {
60338
61022
  "use strict";
60339
- init_zod();
61023
+ init_locks();
61024
+ init_home_paths();
60340
61025
  init_protocol();
60341
- init_transcripts();
60342
- DELIVERY_RETENTION_MS = 24 * 36e5;
60343
- DELIVERY_GIVE_UP_MS = 3e4;
60344
- MAX_RECORDS = 512;
60345
- LANDED_CHECK_MS = 3e3;
60346
- ENTRY_SLACK_MS = 5e3;
60347
- PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
60348
- promptHash = (text5) => createHash33("sha256").update(promptKey(text5)).digest("hex");
60349
- recordSchema2 = external_exports.object({
60350
- id: external_exports.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional(),
60351
- hash: external_exports.string().regex(/^[0-9a-f]{64}$/),
60352
- server: external_exports.string().min(1).max(200),
60353
- pane: external_exports.string().min(1).max(200),
60354
- source: provider,
60355
- session: external_exports.string().min(1).max(200),
60356
- terminal: external_exports.string().max(200).optional(),
60357
- state: external_exports.enum(["typed", "queued", "delivered", "failed"]),
60358
- reason: external_exports.string().max(500).optional(),
60359
- at: external_exports.number(),
60360
- settledAt: external_exports.number().optional(),
60361
- stoppedAt: external_exports.number().optional(),
60362
- /** The transcript entry (byte offset) that settled it, so no other message claims the same one. */
60363
- entry: external_exports.number().optional()
60364
- }).strict();
60365
- PromptDeliveries = class _PromptDeliveries {
60366
- constructor(file4, now = Date.now, landed = transcriptEntries) {
60367
- this.file = file4;
60368
- this.now = now;
60369
- this.landed = landed;
60370
- if (!file4) return;
60371
- try {
60372
- for (const row of objects(object2(JSON.parse(readFileSync45(file4, "utf8"))).records)) {
60373
- const parsed = recordSchema2.safeParse(row);
60374
- if (parsed.success) this.records.push({ ...parsed.data, state: parsed.data.state === "typed" ? "queued" : parsed.data.state });
60375
- }
60376
- } catch {
60377
- }
60378
- this.prune();
60379
- }
60380
- file;
60381
- now;
60382
- landed;
60383
- records = [];
60384
- waiters = /* @__PURE__ */ new Map();
60385
- writing = Promise.resolve();
60386
- /** Panes (server, pane, agent) that sent a UserPromptSubmit or Stop since the Hook started. */
60387
- hookPanes = /* @__PURE__ */ new Set();
60388
- paneKey(target2) {
60389
- return [target2.server, target2.pane, target2.source].join("|");
60390
- }
60391
- static open(record4) {
60392
- return record4.state === "typed" || record4.state === "queued";
60393
- }
60394
- /** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
60395
- static claimable(record4) {
60396
- return _PromptDeliveries.open(record4) || record4.state === "failed" && !!record4.hookClaim;
60397
- }
60398
- samePane(record4, target2) {
60399
- return record4.server === target2.server && record4.pane === target2.pane && record4.source === target2.source;
60400
- }
60401
- byId(id2) {
60402
- return this.records.find((record4) => record4.id === id2);
60403
- }
60404
- prune() {
60405
- const cutoff = this.now() - DELIVERY_RETENTION_MS;
60406
- this.records = this.records.filter((record4) => record4.at >= cutoff || this.waiters.has(record4));
60407
- while (this.records.length > MAX_RECORDS) this.records.shift();
60408
- }
60409
- save() {
60410
- if (!this.file) return;
60411
- const rows2 = this.records.filter((record4) => record4.id || record4.entry !== void 0).map(({ idleSince: _2, checkedAt: __, hookClaim: ___, seenRow: ____, ...row }) => row);
60412
- const file4 = this.file;
60413
- this.writing = this.writing.then(() => atomicInPrivateDir(file4, { records: rows2 })).catch(() => void 0);
60414
- }
60415
- /** Settled writes, for tests and an orderly shutdown. */
60416
- flush() {
60417
- return this.writing;
60418
- }
60419
- /** Register a message about to be typed into `target`'s pane. Settles
60420
- * "delivered" once a conversation in that pane submits the words, or
60421
- * "pending" after `waitMs`; the record outlives the wait. A retry of a
60422
- * failed id replaces its record. Aborting (the terminal refused before
60423
- * writing) drops it. */
60424
- expect(target2, text5, waitMs, signal, id2, terminal2) {
60425
- if (!promptKey(text5) || signal?.aborted) return Promise.resolve("pending");
60426
- this.prune();
60427
- if (id2) this.records = this.records.filter((record5) => record5.id !== id2);
60428
- const record4 = {
60429
- ...id2 ? { id: id2 } : {},
60430
- hash: promptHash(text5),
60431
- server: target2.server,
60432
- pane: target2.pane,
60433
- source: target2.source,
60434
- session: target2.session,
60435
- ...typeof terminal2 === "string" ? { terminal: terminal2 } : {},
60436
- state: "typed",
60437
- at: this.now()
60438
- };
60439
- this.records.push(record4);
60440
- this.save();
60441
- return new Promise((resolve17) => {
60442
- const timer = setTimeout(() => this.release(record4, "pending"), waitMs);
60443
- timer.unref?.();
60444
- this.waiters.set(record4, { resolve: resolve17, timer });
60445
- signal?.addEventListener("abort", () => {
60446
- this.release(record4, "pending");
60447
- if (record4.state === "typed") {
60448
- this.records = this.records.filter((entry2) => entry2 !== record4);
60449
- this.save();
60450
- }
60451
- }, { once: true });
60452
- });
60453
- }
60454
- release(record4, outcome) {
60455
- const waiter = this.waiters.get(record4);
60456
- if (!waiter) return;
60457
- clearTimeout(waiter.timer);
60458
- waiter.resolve?.(outcome);
60459
- waiter.resolve = void 0;
60460
- if (outcome !== "pending") waiter.late?.(outcome);
60461
- if (outcome !== "pending" || !waiter.late) this.waiters.delete(record4);
60462
- }
60463
- open(target2, text5) {
60464
- const hash2 = promptHash(text5);
60465
- return this.records.find((record4) => record4.hash === hash2 && this.samePane(record4, target2) && (record4.state === "typed" || record4.state === "queued"));
60466
- }
60467
- /** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
60468
- pending(target2, text5) {
60469
- return !!this.open(target2, text5);
60470
- }
60471
- /** Wait again for a message `expect` reported pending, after a second Enter. */
60472
- awaitLate(target2, text5, waitMs = 2500) {
60473
- const record4 = this.open(target2, text5);
60474
- if (!record4) return Promise.resolve("pending");
60475
- return new Promise((resolve17) => {
60476
- const waiter = this.waiters.get(record4) ?? {};
60477
- const timer = setTimeout(() => {
60478
- waiter.late = void 0;
60479
- if (!waiter.resolve) this.waiters.delete(record4);
60480
- resolve17("pending");
60481
- }, waitMs);
60482
- timer.unref?.();
60483
- waiter.late = (outcome) => {
60484
- clearTimeout(timer);
60485
- waiter.late = void 0;
60486
- resolve17(outcome);
60487
- };
60488
- this.waiters.set(record4, waiter);
60489
- });
60490
- }
60491
- find(id2, target2) {
60492
- const record4 = this.byId(id2);
60493
- return record4 && this.samePane(record4, target2) && this.now() - record4.at <= DELIVERY_RETENTION_MS ? record4 : void 0;
60494
- }
60495
- /** The Hook answered `id` as typed and held by the agent. */
60496
- queue(id2, target2) {
60497
- const record4 = this.find(id2, target2);
60498
- if (record4?.state === "typed") {
60499
- record4.state = "queued";
60500
- this.save();
60501
- }
60502
- }
60503
- /** Delivered without a hook: an app-server turn or a served OpenCode prompt. */
60504
- delivered(id2, target2, text5) {
60505
- if (!id2) return;
60506
- this.records = this.records.filter((record4) => record4.id !== id2);
60507
- this.records.push({
60508
- id: id2,
60509
- hash: promptHash(text5),
60510
- server: target2.server,
60511
- pane: target2.pane,
60512
- source: target2.source,
60513
- session: target2.session,
60514
- state: "delivered",
60515
- at: this.now(),
60516
- settledAt: this.now()
60517
- });
60518
- this.save();
60519
- }
60520
- /** The message did not reach the agent, and why. It stays matchable, so a
60521
- * late submission still turns it delivered. */
60522
- fail(id2, target2, reason2) {
60523
- const record4 = id2 ? this.find(id2, target2) : void 0;
60524
- if (!record4 || record4.state === "delivered") return;
60525
- record4.state = "failed";
60526
- record4.reason = reason2.slice(0, 500);
60527
- record4.settledAt = this.now();
60528
- this.save();
60529
- }
60530
- /** The pane's Codex server moved to another thread (/new, /resume):
60531
- * input still pending on the old one stays there, out of the pane's view.
60532
- * Fails loudly; a late UserPromptSubmit from the old thread still settles it. */
60533
- threadChanged(previous) {
60534
- let changed = false;
60535
- for (const record4 of this.records) if ((record4.state === "typed" || record4.state === "queued") && this.samePane(record4, previous) && record4.session === previous.session) {
60536
- record4.state = "failed";
60537
- record4.settledAt = this.now();
60538
- changed = true;
60539
- record4.reason = "The pane moved to another Codex conversation before the agent took the message.";
60540
- }
60541
- if (changed) this.save();
60542
- }
60543
- /** False when `id` names another message: other words or another pane. */
60544
- sameMessage(id2, target2, text5) {
60545
- const record4 = this.byId(id2);
60546
- return !record4 || this.samePane(record4, target2) && record4.hash === promptHash(text5);
60547
- }
60548
- /** What became of phone message `id` in `target`'s pane. `unknown` while the
60549
- * Hook has not answered it, for another pane, or past retention. */
60550
- status(id2, target2) {
60551
- const record4 = this.find(id2, target2);
60552
- if (!record4 || record4.state === "typed") return { state: "unknown" };
60553
- return { state: record4.state, ...record4.reason && record4.state === "failed" ? { reason: record4.reason } : {}, session: record4.session };
60554
- }
60555
- /** Every known phone message in `target`'s pane, for its conversation's stream. */
60556
- forPane(target2) {
60557
- return this.records.filter((record4) => record4.id && this.samePane(record4, target2)).map((record4) => ({ deliveryId: record4.id, ...this.status(record4.id, target2) })).filter((item) => item.state !== "unknown");
60558
- }
60559
- /** Conversation `target` just submitted `prompt`. Its own record wins, then
60560
- * the oldest open one in the same pane: the agent kept the text across a
60561
- * conversation change, and the conversation now in the pane is where it
60562
- * went. A prompt nothing matches was typed locally. Never refused.
60563
- * For Claude the transcript is consulted first and the submission claims
60564
- * the earliest unclaimed user row with these words, through the same
60565
- * `settle` and the same table of claimed entries the idle check uses: a
60566
- * callback for a row already claimed (the idle check settled it, the hook
60567
- * came late) settles nothing more. */
60568
- async submitted(target2, prompt) {
60569
- const hash2 = promptHash(prompt);
60570
- this.hookPanes.add(this.paneKey(target2));
60571
- const pick3 = () => {
60572
- const open30 = this.records.filter((record5) => record5.hash === hash2 && this.samePane(record5, target2) && record5.state !== "delivered");
60573
- return open30.find((entry3) => entry3.session === target2.session) ?? open30[0];
60574
- };
60575
- let record4 = pick3();
60576
- if (!record4) return;
60577
- let entry2;
60578
- if (target2.source === "claude") {
60579
- let rows2;
60580
- try {
60581
- rows2 = (await this.landed({ source: target2.source, session: target2.session, hash: hash2, at: record4.at })).filter((row) => row.hook);
60582
- } catch {
60583
- rows2 = void 0;
60584
- }
60585
- record4 = pick3();
60586
- 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) {
60589
- this.settle(record4, void 0, target2.session);
60590
- this.save();
60591
- return;
60592
- }
60593
- if (!rows2?.length) {
60594
- record4.hookClaim = true;
60595
- record4.session = target2.session;
60596
- return;
60597
- }
60598
- const free = rows2.filter((row) => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
60599
- if (!free) return;
60600
- entry2 = free.offset;
60601
- }
60602
- this.settle(record4, entry2, target2.session);
60603
- this.save();
60604
- }
60605
- /** Marks `record` delivered, with the transcript entry that settled it when known. */
60606
- settle(record4, entry2, session) {
60607
- record4.state = "delivered";
60608
- record4.settledAt = this.now();
60609
- delete record4.reason;
60610
- delete record4.hookClaim;
60611
- delete record4.seenRow;
60612
- if (session) record4.session = session;
60613
- if (entry2 !== void 0) record4.entry = entry2;
60614
- this.release(record4, "delivered");
60615
- }
60616
- /** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
60617
- * An entry settles one message: the table of records' `entry` offsets (per conversation) is the only
60618
- * state, so neither this path nor the hook's can settle two messages with one turn. A user row is a
60619
- * turn start whose UserPromptSubmit hook settles the message itself, so while the agent works only a
60620
- * mid-turn queue removal (no hook fires for it) settles from the transcript; once the agent is idle
60621
- * (`working` false) a user row settles too, for a hook that never came. Of several identical open
60622
- * messages the oldest take the entries. `pass` carries the entries still unclaimed within one observe. */
60623
- async taken(record4, pass, working = false) {
60624
- if (record4.source !== "claude") return (await this.landed(record4).catch(() => [])).length > 0;
60625
- const same2 = (other) => other.hash === record4.hash && other.server === record4.server && other.pane === record4.pane && other.session === record4.session;
60626
- const open30 = this.records.filter((other) => same2(other) && _PromptDeliveries.claimable(other)).sort((a, b) => a.at - b.at);
60627
- if (open30[0] !== record4) return false;
60628
- const key4 = [record4.hash, record4.server, record4.pane, record4.session, working].join("|");
60629
- let free = pass.get(key4);
60630
- if (!free) {
60631
- const found = (await this.landed(record4).catch(() => [])).sort((a, b) => a.offset - b.offset);
60632
- 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));
60635
- if (working) {
60636
- const row = unclaimed.find((entry3) => entry3.hook);
60637
- const hookless = !this.hookPanes.has(this.paneKey(record4));
60638
- const own2 = row && (record4.hookClaim || hookless && record4.seenRow === row.offset);
60639
- if (row && hookless && !own2) record4.seenRow = row.offset;
60640
- free = unclaimed.filter((entry3) => !entry3.hook || own2 && entry3 === row);
60641
- } else free = unclaimed;
60642
- }
60643
- if (!_PromptDeliveries.claimable(record4)) return false;
60644
- const entry2 = free.shift();
60645
- pass.set(key4, free);
60646
- if (entry2 === void 0) return false;
60647
- record4.entry = entry2.offset;
60648
- return true;
60649
- }
60650
- /** A turn in `target`'s pane ended: the agent now takes held input or never will. */
60651
- stopped(target2) {
60652
- const at2 = this.now();
60653
- this.hookPanes.add(this.paneKey(target2));
60654
- let marked = false;
60655
- for (const record4 of this.records) if (this.samePane(record4, target2) && (record4.state === "typed" || record4.state === "queued") && record4.at < at2) {
60656
- record4.stoppedAt = at2;
60657
- marked = true;
60658
- }
60659
- if (marked) this.save();
60660
- }
60661
- /** Called on the Hook's activity tick with a server's panes. A message
60662
- * still held fails loudly when its pane closed, its agent restarted, or the
60663
- * agent ended a turn and stayed idle without taking it (unless its
60664
- * transcript shows it after all). */
60665
- async observe(server, panes2) {
60666
- const now = this.now();
60667
- let changed = false;
60668
- const pass = /* @__PURE__ */ new Map();
60669
- for (const record4 of this.records) {
60670
- if (record4.server !== server) continue;
60671
- if (record4.state === "failed" && record4.hookClaim) {
60672
- if (record4.source === "claude" && (record4.checkedAt === void 0 || now - record4.checkedAt >= LANDED_CHECK_MS)) {
60673
- record4.checkedAt = now;
60674
- if (await this.taken(record4, pass, true)) {
60675
- this.settle(record4);
60676
- changed = true;
60677
- }
60678
- }
60679
- continue;
60680
- }
60681
- if (record4.state !== "typed" && record4.state !== "queued") continue;
60682
- const pane = panes2.find((entry2) => entry2.pane_id === record4.pane);
60683
- if (!pane || record4.terminal && pane.terminal_id !== record4.terminal || pane.agent && pane.agent !== record4.source) {
60684
- if (await this.taken(record4, pass)) {
60685
- this.settle(record4);
60686
- changed = true;
60687
- continue;
60688
- }
60689
- if (!_PromptDeliveries.open(record4)) continue;
60690
- record4.state = "failed";
60691
- record4.settledAt = now;
60692
- changed = true;
60693
- record4.reason = pane ? "The agent in this pane restarted before it took the message." : "The agent's pane closed before it took the message.";
60694
- continue;
60695
- }
60696
- if (!["idle", "done"].includes(String(pane.agent_status))) {
60697
- record4.idleSince = void 0;
60698
- if (record4.source === "claude" && (record4.checkedAt === void 0 || now - record4.checkedAt >= LANDED_CHECK_MS)) {
60699
- record4.checkedAt = now;
60700
- if (await this.taken(record4, pass, true)) {
60701
- this.settle(record4);
60702
- changed = true;
60703
- }
60704
- }
60705
- continue;
60706
- }
60707
- record4.idleSince ??= now;
60708
- if (record4.stoppedAt === void 0 || now - Math.max(record4.idleSince, record4.stoppedAt) < DELIVERY_GIVE_UP_MS) continue;
60709
- if (await this.taken(record4, pass)) {
60710
- this.settle(record4);
60711
- changed = true;
60712
- continue;
60713
- }
60714
- if (!_PromptDeliveries.open(record4)) continue;
60715
- record4.state = "failed";
60716
- record4.settledAt = now;
60717
- changed = true;
60718
- record4.reason = "The agent finished its turn without taking the message.";
60719
- }
60720
- if (changed) this.save();
60721
- }
60722
- };
60723
61026
  }
60724
61027
  });
60725
61028
 
@@ -61445,6 +61748,7 @@ async function forwardHook(source, target2, event, value2, left3) {
61445
61748
  toolUseId: value2.tool_use_id,
61446
61749
  cwd: value2.cwd,
61447
61750
  ...event === "UserPromptSubmit" && typeof value2.prompt === "string" ? { prompt: value2.prompt.slice(0, 65536) } : {},
61751
+ ...event === "SessionStart" && typeof value2.source === "string" ? { startSource: value2.source.slice(0, 32) } : {},
61448
61752
  ...event === "Stop" ? stopFacts(value2) : {}
61449
61753
  });
61450
61754
  await new Promise((resolve17) => {
@@ -62031,6 +62335,7 @@ var init_agent_hooks = __esm({
62031
62335
  source: target2.source,
62032
62336
  session: target2.session,
62033
62337
  ...dispatch2 ? { dispatch: dispatch2 } : {},
62338
+ ...body2.event === "SessionStart" && typeof body2.startSource === "string" ? { start: body2.startSource } : {},
62034
62339
  ...typeof body2.background === "number" ? { background: body2.background } : {},
62035
62340
  ...typeof body2.reply === "string" ? { reply: body2.reply } : {},
62036
62341
  ...body2.event === "Stop" && typeof body2.cwd === "string" ? { cwd: body2.cwd } : {}
@@ -63212,7 +63517,7 @@ ${await conductorBrief()}` : context3 } : {}));
63212
63517
 
63213
63518
  // src/bridge/models.ts
63214
63519
  import { spawn as spawn11 } from "node:child_process";
63215
- import { readdir as readdir16, readFile as readFile48, stat as stat22 } from "node:fs/promises";
63520
+ import { readdir as readdir16, readFile as readFile48, stat as stat23 } from "node:fs/promises";
63216
63521
  import { homedir as homedir18 } from "node:os";
63217
63522
  import path112 from "node:path";
63218
63523
  function readCodexModels(executable2 = codexExecutable()) {
@@ -63291,7 +63596,7 @@ async function readClaudeCatalog(configDir2 = claudeConfigDir(), installed) {
63291
63596
  try {
63292
63597
  for (const name of await readdir16(directory)) {
63293
63598
  if (!name.endsWith("-cc.json")) continue;
63294
- const file4 = path112.join(directory, name), at2 = (await stat22(file4)).mtimeMs;
63599
+ const file4 = path112.join(directory, name), at2 = (await stat23(file4)).mtimeMs;
63295
63600
  if (!newest2 || at2 > newest2.at) newest2 = { file: file4, at: at2 };
63296
63601
  }
63297
63602
  } catch {
@@ -64082,7 +64387,7 @@ var init_permission_mode = __esm({
64082
64387
 
64083
64388
  // src/bridge/session-servers.ts
64084
64389
  import { execFile as execFile25 } from "node:child_process";
64085
- import { open as open21, stat as stat23 } from "node:fs/promises";
64390
+ import { open as open21, stat as stat24 } from "node:fs/promises";
64086
64391
  import { promisify as promisify23 } from "node:util";
64087
64392
  function mentionedPorts(text5) {
64088
64393
  const ports = /* @__PURE__ */ new Set();
@@ -64137,7 +64442,7 @@ async function transcriptHolders(file4) {
64137
64442
  return stdout.split("\n").map(Number).filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid);
64138
64443
  }
64139
64444
  async function transcriptTail2(file4) {
64140
- const size = (await stat23(file4)).size;
64445
+ const size = (await stat24(file4)).size;
64141
64446
  const handle = await open21(file4, "r");
64142
64447
  try {
64143
64448
  const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
@@ -64190,7 +64495,7 @@ var init_session_servers = __esm({
64190
64495
  });
64191
64496
 
64192
64497
  // src/bridge/uploads.ts
64193
- import { mkdir as mkdir27, readdir as readdir17, lstat as lstat30, realpath as realpath16, readFile as readFile49, stat as stat24, unlink as unlink8, writeFile as writeFile8 } from "node:fs/promises";
64498
+ import { mkdir as mkdir27, readdir as readdir17, lstat as lstat30, realpath as realpath16, readFile as readFile49, stat as stat25, unlink as unlink8, writeFile as writeFile8 } from "node:fs/promises";
64194
64499
  import path113 from "node:path";
64195
64500
  import { randomUUID as randomUUID27 } from "node:crypto";
64196
64501
  function imageBytes(bytes) {
@@ -64232,7 +64537,7 @@ async function listUploads(session) {
64232
64537
  const files = [];
64233
64538
  for (const entry2 of entries2) {
64234
64539
  if (!entry2.isFile()) continue;
64235
- const file4 = path113.join(folder, entry2.name), metadata = await stat24(file4);
64540
+ const file4 = path113.join(folder, entry2.name), metadata = await stat25(file4);
64236
64541
  files.push({ name: entry2.name.replace(/^[0-9a-f-]{36}-/, ""), path: file4, size: metadata.size, modified: metadata.mtime.toISOString() });
64237
64542
  }
64238
64543
  return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
@@ -64252,7 +64557,7 @@ async function uploadImage(requested) {
64252
64557
  const root = await realpath16(path113.join(bridgeRoot(), "uploads")).catch(() => void 0);
64253
64558
  const file4 = await realpath16(requested).catch(() => void 0);
64254
64559
  if (!root || !file4 || !file4.startsWith(root + path113.sep)) throw missing;
64255
- const metadata = await stat24(file4);
64560
+ const metadata = await stat25(file4);
64256
64561
  if (!metadata.isFile()) throw missing;
64257
64562
  if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
64258
64563
  const bytes = await readFile49(file4);
@@ -64266,7 +64571,7 @@ async function sessionUpload(session, requested) {
64266
64571
  const folder = await realpath16(path113.join(bridgeRoot(), "uploads", session)).catch(() => void 0);
64267
64572
  const file4 = await realpath16(requested).catch(() => void 0);
64268
64573
  if (!folder || !file4 || !file4.startsWith(folder + path113.sep)) throw refused2;
64269
- if (!(await stat24(file4)).isFile()) throw refused2;
64574
+ if (!(await stat25(file4)).isFile()) throw refused2;
64270
64575
  return file4;
64271
64576
  }
64272
64577
  var IMAGE_NAME, uploadQueue;
@@ -64287,8 +64592,8 @@ function fileContentType(file4) {
64287
64592
  const ext = path114.extname(file4).slice(1).toLowerCase();
64288
64593
  return types[ext] ?? (/^(ts|tsx|js|jsx|swift|py|rs|go|rb|sh|bash|zsh|c|h|cpp|hpp|cs|java|kt|html|css|scss|sql|toml|ini)$/.test(ext) ? "text/plain" : "application/octet-stream");
64289
64594
  }
64290
- function fileVersion(stat32) {
64291
- return `${stat32.dev}:${stat32.ino}:${stat32.size}:${stat32.mtimeMs}:${stat32.ctimeMs}`;
64595
+ function fileVersion(stat33) {
64596
+ return `${stat33.dev}:${stat33.ino}:${stat33.size}:${stat33.mtimeMs}:${stat33.ctimeMs}`;
64292
64597
  }
64293
64598
  function rangeInteger(value2, fallback2) {
64294
64599
  if (value2 === null) return fallback2;
@@ -64394,7 +64699,7 @@ var init_file_range = __esm({
64394
64699
  // src/bridge/file-write.ts
64395
64700
  import { randomBytes as randomBytes9 } from "node:crypto";
64396
64701
  import { constants as constants4 } from "node:fs";
64397
- import { lstat as lstat32, open as open23, realpath as realpath18, rename as rename7, rm as rm12 } from "node:fs/promises";
64702
+ import { lstat as lstat32, open as open23, realpath as realpath18, rename as rename8, rm as rm12 } from "node:fs/promises";
64398
64703
  import path115 from "node:path";
64399
64704
  async function serialized3(key4, work) {
64400
64705
  const previous = fileLocks.get(key4) ?? Promise.resolve();
@@ -64468,7 +64773,7 @@ async function writeRepoFileNow(root, requested, content, expectedVersion) {
64468
64773
  if (!current2 || current2.isSymbolicLink() || fileVersion(current2) !== expectedVersion) {
64469
64774
  throw new BridgeError(409, "The file changed since you opened it.", { code: "file-changed" });
64470
64775
  }
64471
- await rename7(temporary, file4);
64776
+ await rename8(temporary, file4);
64472
64777
  } finally {
64473
64778
  await rm12(temporary, { force: true });
64474
64779
  }
@@ -64661,6 +64966,25 @@ function claudeQuestionAnswer(data) {
64661
64966
  });
64662
64967
  return { questions: body2.questions.map((q2) => ({ question: q2.question, multiSelect: q2.multiSelect, options: q2.options.map((label2) => ({ label: label2 })) })), answers };
64663
64968
  }
64969
+ function promptGuards(agentHooks, target2) {
64970
+ return {
64971
+ held: () => !!(agentHooks.approval(target2) || agentHooks.terminalPrompt(target2) || agentHooks.servedQuestion(target2)),
64972
+ screen: () => terminalProvider().readScreen(target2.server, target2.pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2e3 })
64973
+ };
64974
+ }
64975
+ async function relaysSuggestion(target2, text5) {
64976
+ let screen = "";
64977
+ try {
64978
+ screen = await terminalProvider().readScreen(target2.server, target2.pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2e3 });
64979
+ } catch {
64980
+ return false;
64981
+ }
64982
+ const shown = claudeSuggestionShown(screen);
64983
+ const plain2 = (value2) => value2.replace(/\s+/g, " ").trim().replace(/^\[voice\]\s*/i, "");
64984
+ if (shown === void 0) return false;
64985
+ const words = plain2(text5), cut = shown.endsWith("\u2026") ? plain2(shown.slice(0, -1)) : void 0;
64986
+ return words === plain2(shown) || cut !== void 0 && (words === cut || words === `${cut}\u2026` || words === `${cut} \u2026`);
64987
+ }
64664
64988
  async function resubmitIfIdle(agentHooks, target2, text5) {
64665
64989
  const status = async () => {
64666
64990
  try {
@@ -64669,13 +64993,72 @@ async function resubmitIfIdle(agentHooks, target2, text5) {
64669
64993
  return "unknown";
64670
64994
  }
64671
64995
  };
64672
- if (await status() === "working") return "pending";
64996
+ if (await status() === "working") return await agentHooks.deliveries.awaitLate(target2, text5);
64673
64997
  const late = agentHooks.deliveries.awaitLate(target2, text5);
64674
64998
  await terminalProvider().sendKeys(target2.server, target2.pane, ["enter"]);
64675
64999
  const outcome = await late;
64676
65000
  if (outcome !== "pending") return outcome;
64677
65001
  return await status() === "working" ? "pending" : "unsubmitted";
64678
65002
  }
65003
+ async function leaveClaudeSubagentView(agentHooks, target2, waitMs = 250) {
65004
+ if (target2.source !== "claude") return false;
65005
+ const shows = async () => {
65006
+ let screen;
65007
+ try {
65008
+ screen = await agentHooks.paneAnsi?.(target2);
65009
+ } catch {
65010
+ screen = void 0;
65011
+ }
65012
+ return screen !== void 0 && claudeSubagentView(screen);
65013
+ };
65014
+ if (!await shows()) return false;
65015
+ process.stderr.write(`phren hook: ${target2.server}:${target2.pane} shows a subagent view; Escape back to the conversation before typing
65016
+ `);
65017
+ await terminalProvider().sendKeys(target2.server, target2.pane, ["esc"]);
65018
+ await sleep4(waitMs);
65019
+ if (!await shows()) return true;
65020
+ process.stderr.write(`phren hook: ${target2.server}:${target2.pane} still shows a subagent view after Escape; not pressing it again
65021
+ `);
65022
+ return false;
65023
+ }
65024
+ function retryAfterSubagentView(agentHooks, target2, terminal2, text5, id2, intervalMs = 2e3, limitMs = 6e5, escapeWaitMs = 250) {
65025
+ const started = Date.now();
65026
+ const look = async () => {
65027
+ if (Date.now() - started > limitMs) return;
65028
+ const status = agentHooks.deliveries.status(id2, target2);
65029
+ if (status.state !== "failed") {
65030
+ if (status.state !== "delivered") schedule();
65031
+ return;
65032
+ }
65033
+ if (status.reason !== TURN_ENDED_WITHOUT_IT) return;
65034
+ let pane;
65035
+ try {
65036
+ pane = await validateTarget(target2, true, true);
65037
+ } catch (error62) {
65038
+ if (error62 instanceof BridgeError && error62.status === 409) return;
65039
+ schedule();
65040
+ return;
65041
+ }
65042
+ if (!pane || pane.terminal_id !== terminal2) return;
65043
+ if (!["idle", "done"].includes(String(pane.agent_status))) {
65044
+ schedule();
65045
+ return;
65046
+ }
65047
+ if (!await leaveClaudeSubagentView(agentHooks, target2, escapeWaitMs)) return;
65048
+ const now = agentHooks.deliveries.status(id2, target2);
65049
+ if (now.state !== "failed" || now.reason !== TURN_ENDED_WITHOUT_IT) return;
65050
+ process.stderr.write(`phren hook: retrying phone message ${id2} in the conversation after leaving the subagent view
65051
+ `);
65052
+ const expected = agentHooks.deliveries.expect(target2, text5, 1500, void 0, id2, typeof terminal2 === "string" ? terminal2 : void 0);
65053
+ await terminalProvider().prompt(target2.server, target2.pane, text5);
65054
+ if (await expected === "pending") await resubmitIfIdle(agentHooks, target2, text5);
65055
+ };
65056
+ const schedule = () => {
65057
+ const timer = setTimeout(() => void look().catch(() => void 0), intervalMs);
65058
+ timer.unref?.();
65059
+ };
65060
+ schedule();
65061
+ }
64679
65062
  function followQueuedDelivery(agentHooks, target2, terminal2, text5, intervalMs = 2e3) {
64680
65063
  const started = Date.now();
64681
65064
  let finishedLooks = 0;
@@ -64863,7 +65246,10 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
64863
65246
  }
64864
65247
  if (url2.pathname === "/v1/prompt") {
64865
65248
  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" });
65249
+ 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" });
65250
+ if (data.hookQueued === true && target2.source === "claude" && typeof data.text === "string" && await relaysSuggestion(target2, data.text)) {
65251
+ throw new BridgeError(409, "That text is Claude's own suggested next prompt, drawn dim in the agent's empty input box. The owner did not send it, so it was not typed.", { code: "prompt-suggestion" });
65252
+ }
64867
65253
  if (status === "unknown" || ["blocked", "waiting"].includes(status) && (agentHooks.approval(target2) || agentHooks.terminalPrompt(target2) || agentHooks.servedQuestion(target2))) {
64868
65254
  throw new BridgeError(409, "This agent needs input in the terminal first.");
64869
65255
  }
@@ -64914,11 +65300,14 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
64914
65300
  deliveryId,
64915
65301
  typeof pane.terminal_id === "string" ? pane.terminal_id : void 0
64916
65302
  );
64917
- await typing();
65303
+ let typed = false;
64918
65304
  try {
65305
+ await typing();
65306
+ typed = true;
65307
+ await leaveClaudeSubagentView(agentHooks, target2);
64919
65308
  await terminalProvider().prompt(target2.server, target2.pane, text5);
64920
65309
  } catch (error62) {
64921
- if (agentNotReady(error62)) refused2.abort();
65310
+ if (!typed || agentNotReady(error62) || herdrRefused(error62)) refused2.abort();
64922
65311
  throw error62;
64923
65312
  }
64924
65313
  return expected;
@@ -64935,6 +65324,7 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
64935
65324
  if (!busy2) outcome = await resubmitIfIdle(agentHooks, target2, text5);
64936
65325
  else followQueuedDelivery(agentHooks, target2, pane.terminal_id, text5);
64937
65326
  }
65327
+ if (deliveryId && target2.source === "claude" && outcome !== "delivered") retryAfterSubagentView(agentHooks, target2, pane.terminal_id, text5, deliveryId);
64938
65328
  if (/^\/[a-z][a-z0-9_-]*$/i.test(text5.trim())) agentHooks.menuOpened(target2, text5.trim());
64939
65329
  if (outcome === "delivered") result = { ok: true, delivered: true, state: "delivered" };
64940
65330
  else if (outcome === "unsubmitted") {
@@ -65110,12 +65500,14 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
65110
65500
  }
65111
65501
  return result;
65112
65502
  }
65113
- var ANSWER_KEYS, HERDR_KEYS, questionText, claudeQuestionBody, secretText, promptOnce;
65503
+ var ANSWER_KEYS, HERDR_KEYS, questionText, claudeQuestionBody, secretText, herdrRefused, promptOnce;
65114
65504
  var init_server_pane_routes = __esm({
65115
65505
  "src/bridge/server-pane-routes.ts"() {
65116
65506
  "use strict";
65117
65507
  init_git_write_policy();
65118
65508
  init_zod();
65509
+ init_prompt_deliveries();
65510
+ init_claude_suggestion();
65119
65511
  init_git();
65120
65512
  init_fanouts();
65121
65513
  init_git_worktrees();
@@ -65129,6 +65521,7 @@ var init_server_pane_routes = __esm({
65129
65521
  init_model_switch();
65130
65522
  init_permission_mode();
65131
65523
  init_session_servers();
65524
+ init_session_activity();
65132
65525
  init_projects();
65133
65526
  init_protocol();
65134
65527
  init_transcripts();
@@ -65139,6 +65532,7 @@ var init_server_pane_routes = __esm({
65139
65532
  init_prompt_once();
65140
65533
  init_prompt_startup();
65141
65534
  init_opencode_panes();
65535
+ init_claude_suggestion();
65142
65536
  ANSWER_KEYS = ["Escape", "Enter", "Up", "Down", "Tab", "AltUp", "y", "n", "p", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
65143
65537
  HERDR_KEYS = { Escape: "esc", Enter: "enter", Up: "up", Down: "down", Tab: "tab", AltUp: "alt+Up" };
65144
65538
  questionText = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
@@ -65150,6 +65544,7 @@ var init_server_pane_routes = __esm({
65150
65544
  })).min(1).max(8)
65151
65545
  });
65152
65546
  secretText = external_exports.string().min(1).max(256).refine((t) => !/[\x00-\x1f\x7f]/.test(t));
65547
+ herdrRefused = (error62) => error62 instanceof BridgeError && error62.status === 409 && typeof error62.details?.herdrCode === "string";
65153
65548
  promptOnce = new PromptOnce();
65154
65549
  }
65155
65550
  });
@@ -65669,7 +66064,7 @@ var init_launcher = __esm({
65669
66064
 
65670
66065
  // src/bridge/fanout-messages.ts
65671
66066
  import { randomUUID as randomUUID28 } from "node:crypto";
65672
- import { appendFile as appendFile2, lstat as lstat33, mkdir as mkdir28, readdir as readdir18, readFile as readFile50, realpath as realpath19, rename as rename8, rm as rm13, writeFile as writeFile9 } from "node:fs/promises";
66067
+ import { appendFile as appendFile2, lstat as lstat33, mkdir as mkdir28, readdir as readdir18, readFile as readFile50, realpath as realpath19, rename as rename9, rm as rm13, writeFile as writeFile9 } from "node:fs/promises";
65673
66068
  import path120 from "node:path";
65674
66069
  var fanoutMessageSchema, receiptSchema2, FanoutMessages;
65675
66070
  var init_fanout_messages = __esm({
@@ -65835,7 +66230,7 @@ var init_fanout_messages = __esm({
65835
66230
  await mkdir28(roundDir, { mode: 448 });
65836
66231
  await writeFile9(path120.join(roundDir, "prompt.txt"), next.message.text, { mode: 384 });
65837
66232
  for (const name of ["stderr.log", "final.txt", "exit.txt", "blocked.json", "prompt.txt"]) {
65838
- await rename8(path120.join(fresh2.directory, name), path120.join(roundDir, `previous-${name}`)).catch((error62) => {
66233
+ await rename9(path120.join(fresh2.directory, name), path120.join(roundDir, `previous-${name}`)).catch((error62) => {
65839
66234
  if (error62.code !== "ENOENT") throw error62;
65840
66235
  });
65841
66236
  }
@@ -65843,7 +66238,7 @@ var init_fanout_messages = __esm({
65843
66238
  const sentFile = next.file.replace(/\.queued\.json$/, ".sent.json");
65844
66239
  const message = { ...next.message, status: "running" };
65845
66240
  await atomic(next.file, JSON.stringify(message));
65846
- await rename8(next.file, sentFile);
66241
+ await rename9(next.file, sentFile);
65847
66242
  pending3 = { file: sentFile, message };
65848
66243
  const now = (/* @__PURE__ */ new Date()).toISOString();
65849
66244
  const manifest = {
@@ -65889,7 +66284,7 @@ var init_fanout_messages = __esm({
65889
66284
  } catch (error62) {
65890
66285
  if (!pending3) throw error62;
65891
66286
  await atomic(pending3.file, JSON.stringify({ ...pending3.message, status: "failed" }));
65892
- if (pending3.file.endsWith(".queued.json")) await rename8(pending3.file, pending3.file.replace(/\.queued\.json$/, ".sent.json"));
66287
+ if (pending3.file.endsWith(".queued.json")) await rename9(pending3.file, pending3.file.replace(/\.queued\.json$/, ".sent.json"));
65893
66288
  if (started) await atomic(path120.join(job.directory, "manifest.json"), JSON.stringify({
65894
66289
  ...started,
65895
66290
  status: "failed",
@@ -66567,17 +66962,31 @@ function failRelay(client) {
66567
66962
  }
66568
66963
  function relayTranscription(client, query, options = {}) {
66569
66964
  const connect5 = options.connect ?? ((url2, key4) => new import_websocket.default(url2, { headers: { "xi-api-key": key4 } }));
66965
+ let receive;
66966
+ let early = [], earlyBytes = 0, hungUp = false;
66967
+ client.on("message", (data, isBinary) => {
66968
+ if (receive) {
66969
+ receive(data, isBinary);
66970
+ return;
66971
+ }
66972
+ if (early && (earlyBytes += data.length) <= MAX_PENDING_BYTES) early.push([data, isBinary]);
66973
+ });
66974
+ client.on("close", () => {
66975
+ hungUp = true;
66976
+ });
66570
66977
  return (async () => {
66571
66978
  const key4 = await (options.key ?? readSpeechKey)();
66572
66979
  const tell = (frame) => {
66573
66980
  if (client.readyState === OPEN3) client.send(JSON.stringify(frame));
66574
66981
  };
66982
+ if (hungUp) return;
66575
66983
  if (!key4) {
66576
66984
  tell({ type: "error", code: "transcribe-unconfigured", error: "This computer has no ElevenLabs key." });
66577
66985
  client.close(1008, "No ElevenLabs key");
66578
66986
  return;
66579
66987
  }
66580
66988
  const origin = options.origin ?? (await resolveSpeechRegion()).origin;
66989
+ if (hungUp) return;
66581
66990
  const upstream = connect5(transcribeURL(query, origin), key4);
66582
66991
  let pending3 = [], pendingBytes = 0, closed = false;
66583
66992
  const finish = (code = 1e3, reason2 = "") => {
@@ -66604,10 +67013,11 @@ function relayTranscription(client, query, options = {}) {
66604
67013
  commit,
66605
67014
  sample_rate: TRANSCRIBE_RATE
66606
67015
  });
66607
- client.on("message", (data, isBinary) => {
67016
+ receive = (data, isBinary) => {
66608
67017
  if (closed) return;
66609
67018
  if (!isBinary) {
66610
67019
  if (upstream.readyState === OPEN3) upstream.send(chunk(Buffer.alloc(0), true));
67020
+ else pending3.push(null);
66611
67021
  return;
66612
67022
  }
66613
67023
  if (upstream.readyState === OPEN3) {
@@ -66621,11 +67031,13 @@ function relayTranscription(client, query, options = {}) {
66621
67031
  return;
66622
67032
  }
66623
67033
  pending3.push(data);
66624
- });
67034
+ };
67035
+ for (const [data, isBinary] of early ?? []) receive(data, isBinary);
67036
+ early = void 0;
66625
67037
  client.on("close", () => finish());
66626
67038
  client.on("error", () => finish());
66627
67039
  upstream.on("open", () => {
66628
- for (const audio of pending3) upstream.send(chunk(audio));
67040
+ for (const audio of pending3) upstream.send(audio ? chunk(audio) : chunk(Buffer.alloc(0), true));
66629
67041
  pending3 = [];
66630
67042
  pendingBytes = 0;
66631
67043
  if (!closed) tell({ type: "ready" });
@@ -66684,7 +67096,7 @@ var init_speech_transcribe = __esm({
66684
67096
  });
66685
67097
 
66686
67098
  // src/bridge/activity.ts
66687
- import { appendFile as appendFile3, mkdir as mkdir29, readFile as readFile51, rename as rename9, stat as stat25 } from "node:fs/promises";
67099
+ import { appendFile as appendFile3, mkdir as mkdir29, readFile as readFile51, rename as rename10, stat as stat26 } from "node:fs/promises";
66688
67100
  import path121 from "node:path";
66689
67101
  var ActivityJournal;
66690
67102
  var init_activity2 = __esm({
@@ -66719,7 +67131,7 @@ var init_activity2 = __esm({
66719
67131
  if (!changes.length) return;
66720
67132
  const root = bridgeRoot(), file4 = path121.join(root, "activity.jsonl");
66721
67133
  await mkdir29(root, { recursive: true, mode: 448 });
66722
- if ((await stat25(file4).catch(() => null))?.size && (await stat25(file4)).size > 2097152) await rename9(file4, file4 + ".previous");
67134
+ if ((await stat26(file4).catch(() => null))?.size && (await stat26(file4)).size > 2097152) await rename10(file4, file4 + ".previous");
66723
67135
  await appendFile3(file4, changes.map((row) => JSON.stringify(row)).join("\n") + "\n", { mode: 384 });
66724
67136
  if (this.previous.size > 4096) this.previous.clear();
66725
67137
  });
@@ -67321,10 +67733,10 @@ var init_context2 = __esm({
67321
67733
  const metadata = await handle.stat();
67322
67734
  if (!metadata.isFile()) return void 0;
67323
67735
  const key4 = `codex:${session}:${file4}`;
67324
- const stat32 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
67736
+ const stat33 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
67325
67737
  const cached3 = this.cache.get(key4);
67326
67738
  this.cache.delete(key4);
67327
- if (cached3?.stat === stat32) {
67739
+ if (cached3?.stat === stat33) {
67328
67740
  this.cache.set(key4, cached3);
67329
67741
  return cached3.percent;
67330
67742
  }
@@ -67335,7 +67747,7 @@ var init_context2 = __esm({
67335
67747
  const after = await handle.stat();
67336
67748
  if (after.size !== metadata.size || after.mtimeMs !== metadata.mtimeMs || after.ctimeMs !== metadata.ctimeMs) return void 0;
67337
67749
  const percent = codexContext(tail2, start === 0);
67338
- this.cache.set(key4, { stat: stat32, percent });
67750
+ this.cache.set(key4, { stat: stat33, percent });
67339
67751
  while (this.cache.size > MAX_SESSIONS2) this.cache.delete(this.cache.keys().next().value);
67340
67752
  return percent;
67341
67753
  } finally {
@@ -67412,7 +67824,7 @@ var init_context2 = __esm({
67412
67824
  // src/bridge/questions.ts
67413
67825
  import { execFile as execFile26 } from "node:child_process";
67414
67826
  import { createHash as createHash34 } from "node:crypto";
67415
- import { mkdir as mkdir30, open as open25, stat as stat26, readFile as readFile52, writeFile as writeFile10 } from "node:fs/promises";
67827
+ import { mkdir as mkdir30, open as open25, stat as stat27, readFile as readFile52, writeFile as writeFile10 } from "node:fs/promises";
67416
67828
  import path124 from "node:path";
67417
67829
  import { promisify as promisify24 } from "node:util";
67418
67830
  function asyncQuestion(raw, id2) {
@@ -67643,7 +68055,7 @@ ${attachedFiles(paths)}` : answer2;
67643
68055
  const cached3 = this.snapshots.get(target2.session);
67644
68056
  let pending3 = cached3?.pending;
67645
68057
  if (!cached3 || Date.now() - cached3.at > 1e3) {
67646
- const metadata = await stat26(file4), stamp2 = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
68058
+ const metadata = await stat27(file4), stamp2 = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
67647
68059
  pending3 = cached3?.stamp === stamp2 ? cached3.pending : await pendingAsyncQuestions(file4).catch((error62) => {
67648
68060
  if (this.failedSnapshots.size >= 64) this.failedSnapshots.delete(this.failedSnapshots.keys().next().value);
67649
68061
  this.failedSnapshots.set(target2.session, Date.now());
@@ -67709,55 +68121,8 @@ ${attachedFiles(paths)}` : answer2;
67709
68121
  }
67710
68122
  });
67711
68123
 
67712
- // src/bridge/claude-suggestion.ts
67713
- function claudeSuggestion(screen) {
67714
- const lines = screen.split("\n").map((line) => line.replace(/\r$/, ""));
67715
- for (let index2 = lines.length - 2; index2 > 0; index2--) {
67716
- const plain2 = stripTerminal(lines[index2]);
67717
- if (!/^\s*❯/.test(plain2)) continue;
67718
- if (!rule(stripTerminal(lines[index2 - 1])) || !rule(stripTerminal(lines[index2 + 1]))) return void 0;
67719
- const text5 = dimText(lines[index2]);
67720
- if (!text5 || text5.endsWith("\u2026") || text5.length > MAX_SUGGESTION || PLACEHOLDERS.some((pattern) => pattern.test(text5))) return void 0;
67721
- return text5;
67722
- }
67723
- return void 0;
67724
- }
67725
- function dimText(line) {
67726
- let dim = false, prompt = false, text5 = "";
67727
- for (const token of line.match(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|[^\x1b]/gu) ?? []) {
67728
- if (token.startsWith("\x1B")) {
67729
- if (!token.startsWith("\x1B[") || !token.endsWith("m")) continue;
67730
- const codes = (token.slice(2, -1) || "0").split(/[;:]/).map(Number);
67731
- for (let i = 0; i < codes.length; i++) {
67732
- const code = codes[i];
67733
- if (code === 38 || code === 48 || code === 58) {
67734
- i += codes[i + 1] === 5 ? 2 : codes[i + 1] === 2 ? 4 : 0;
67735
- continue;
67736
- }
67737
- if (code === 0 || code === 22) dim = false;
67738
- else if (code === 2) dim = true;
67739
- }
67740
- } else if (!prompt) {
67741
- if (token === "\u276F") prompt = true;
67742
- } else if (!token.trim()) text5 += " ";
67743
- else if (!dim) return "";
67744
- else text5 += token;
67745
- }
67746
- return text5.replace(/\s+/g, " ").trim();
67747
- }
67748
- var MAX_SUGGESTION, rule, PLACEHOLDERS;
67749
- var init_claude_suggestion = __esm({
67750
- "src/bridge/claude-suggestion.ts"() {
67751
- "use strict";
67752
- init_terminal_text();
67753
- MAX_SUGGESTION = 500;
67754
- rule = (line) => /^[─━═]{3,}/.test(line.trim());
67755
- PLACEHOLDERS = [/^Try ".*"$/, /^Press (?:up|Enter) to /, /^Message @.*…$/];
67756
- }
67757
- });
67758
-
67759
68124
  // src/bridge/settings-switch.ts
67760
- import { open as open26, stat as stat27 } from "node:fs/promises";
68125
+ import { open as open26, stat as stat28 } from "node:fs/promises";
67761
68126
  function codexModeFlags(mode) {
67762
68127
  const { approvalPolicy, approvalsReviewer, sandboxPolicy } = CODEX_MODES[mode];
67763
68128
  const sandbox = { readOnly: "read-only", workspaceWrite: "workspace-write", dangerFullAccess: "danger-full-access" }[String(sandboxPolicy?.type)];
@@ -67854,7 +68219,7 @@ var init_settings_switch = __esm({
67854
68219
  };
67855
68220
  }
67856
68221
  };
67857
- fileSize = async (file4) => file4 ? (await stat27(file4).catch(() => void 0))?.size ?? 0 : 0;
68222
+ fileSize = async (file4) => file4 ? (await stat28(file4).catch(() => void 0))?.size ?? 0 : 0;
67858
68223
  SettingsSwitcher = class {
67859
68224
  constructor(hooks, wait = STEP_WAIT_MS2) {
67860
68225
  this.hooks = hooks;
@@ -68815,7 +69180,7 @@ var init_account_add = __esm({
68815
69180
 
68816
69181
  // src/bridge/launch-worktree.ts
68817
69182
  import { execFile as execFile28 } from "node:child_process";
68818
- import { mkdir as mkdir31, realpath as realpath21, rm as rm16, stat as stat28 } from "node:fs/promises";
69183
+ import { mkdir as mkdir31, realpath as realpath21, rm as rm16, stat as stat29 } from "node:fs/promises";
68819
69184
  import path129 from "node:path";
68820
69185
  import { promisify as promisify26 } from "node:util";
68821
69186
  async function git7(cwd, ...args) {
@@ -68842,7 +69207,7 @@ async function createLaunchWorktree(cwd, request10) {
68842
69207
  throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
68843
69208
  }
68844
69209
  const worktree = path129.join(root, ".claude", "worktrees", worktreeFolderName(branch));
68845
- if (await stat28(worktree).then(() => true, () => false)) {
69210
+ if (await stat29(worktree).then(() => true, () => false)) {
68846
69211
  throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
68847
69212
  }
68848
69213
  await mkdir31(path129.dirname(worktree), { recursive: true });
@@ -68855,7 +69220,7 @@ async function createLaunchWorktree(cwd, request10) {
68855
69220
  const abs = await realpath21(worktree);
68856
69221
  const inside = path129.relative(root, await realpath21(cwd));
68857
69222
  const start = inside && !inside.startsWith("..") ? path129.join(abs, inside) : abs;
68858
- const startDir = await stat28(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
69223
+ const startDir = await stat29(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
68859
69224
  return {
68860
69225
  cwd: startDir,
68861
69226
  path: abs,
@@ -69142,6 +69507,8 @@ async function startSession(server, data, options) {
69142
69507
  if (role === "conductor" && kind === "copilot") throw new BridgeError(400, "Copilot cannot run as a conductor.");
69143
69508
  if (role === "conductor" && data.mode === "chat") throw new BridgeError(400, "A conductor needs agent mode with tools.");
69144
69509
  const phrenArgs = await phrenLaunchArgs(kind, data);
69510
+ const resumeClaude = options.resumeClaude === void 0 ? void 0 : external_exports.string().uuid("resumeClaude must be a Claude session id.").parse(options.resumeClaude);
69511
+ if (resumeClaude && (kind !== "claude" || role !== "agent" || data.brief != null)) throw new BridgeError(400, "Only a Claude worker without a brief resumes a conversation.");
69145
69512
  const brief = data.brief === void 0 || data.brief === null ? void 0 : launchBriefSchema.parse(data.brief);
69146
69513
  if (brief && role === "conductor") throw new BridgeError(400, "A conductor starts with its own brief.");
69147
69514
  const baseName = herdrAgentName(data.name === void 0 ? label2 : plainText(200).parse(data.name));
@@ -69167,6 +69534,7 @@ async function startSession(server, data, options) {
69167
69534
  ...model && kind === "phren" ? phrenModelArgs(model) : model && modelFlag[kind] ? [modelFlag[kind], model] : [],
69168
69535
  ...data.effort === void 0 ? [] : effortArgs(kind, effort),
69169
69536
  ...permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : [],
69537
+ ...resumeClaude ? ["--resume", resumeClaude] : [],
69170
69538
  ...permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : [],
69171
69539
  ...permissionMode && kind === "copilot" ? copilotModeFlags(permissionMode) : []
69172
69540
  ];
@@ -69407,7 +69775,7 @@ var init_server_launch = __esm({
69407
69775
 
69408
69776
  // src/bridge/task-routes.ts
69409
69777
  import * as path131 from "node:path";
69410
- import { realpath as realpath23, stat as stat29 } from "node:fs/promises";
69778
+ import { realpath as realpath23, stat as stat30 } from "node:fs/promises";
69411
69779
  function owner(base, id2, write) {
69412
69780
  const matches = taskStores(base).filter((s) => s.taskStoreId === id2 && s.available !== false);
69413
69781
  if (matches.length !== 1) throw new BridgeError(404, "Task store is unavailable or ambiguous.");
@@ -69510,7 +69878,7 @@ async function launchTaskRoute(base, server, input2) {
69510
69878
  const store = writableTaskProject(base, data.storeId, data.project);
69511
69879
  const configured = getProjectSourcePath(store.path, data.project);
69512
69880
  const cwd = configured ? await realpath23(configured).catch(() => void 0) : void 0;
69513
- if (!cwd || !(await stat29(cwd)).isDirectory()) throw new BridgeError(409, "This task project has no configured checkout on this computer.");
69881
+ if (!cwd || !(await stat30(cwd)).isDirectory()) throw new BridgeError(409, "This task project has no configured checkout on this computer.");
69514
69882
  const currentStore = writableTaskProject(base, data.storeId, data.project);
69515
69883
  if (path131.resolve(currentStore.path) !== path131.resolve(store.path)) throw new BridgeError(409, "Task store changed; refresh before starting.");
69516
69884
  const reserved = reserveTaskLaunch(store.path, data.project, data.stableId, data.expectedRevision, getMachineName(), base);
@@ -69762,8 +70130,8 @@ function addTermCount(terms, rawText, weight = 1) {
69762
70130
  }
69763
70131
  function maybeReadUtf8(filePath, maxBytes = 256e3) {
69764
70132
  try {
69765
- const stat32 = fs49.statSync(filePath);
69766
- if (!stat32.isFile() || stat32.size > maxBytes) return "";
70133
+ const stat33 = fs49.statSync(filePath);
70134
+ if (!stat33.isFile() || stat33.size > maxBytes) return "";
69767
70135
  return fs49.readFileSync(filePath, "utf8");
69768
70136
  } catch {
69769
70137
  return "";
@@ -70518,7 +70886,7 @@ var init_session_git = __esm({
70518
70886
  import { execFile as execFile29 } from "node:child_process";
70519
70887
  import { promisify as promisify27 } from "node:util";
70520
70888
  import { realpathSync as realpathSync6 } from "node:fs";
70521
- import { readdir as readdir20, readFile as readFile55, stat as stat30, mkdir as mkdir33 } from "node:fs/promises";
70889
+ import { readdir as readdir20, readFile as readFile55, stat as stat31, mkdir as mkdir33 } from "node:fs/promises";
70522
70890
  import { homedir as homedir20 } from "node:os";
70523
70891
  import path136 from "node:path";
70524
70892
  function repoName(url2) {
@@ -70527,7 +70895,7 @@ function repoName(url2) {
70527
70895
  }
70528
70896
  async function isRepository2(directory) {
70529
70897
  try {
70530
- await stat30(path136.join(directory, ".git"));
70898
+ await stat31(path136.join(directory, ".git"));
70531
70899
  return true;
70532
70900
  } catch {
70533
70901
  return false;
@@ -70561,7 +70929,7 @@ async function candidateRepos(activity, env = process.env) {
70561
70929
  const offer = async (directory, source, lastSeen) => {
70562
70930
  let dir = path136.resolve(directory);
70563
70931
  try {
70564
- if (!(await stat30(dir)).isDirectory()) return;
70932
+ if (!(await stat31(dir)).isDirectory()) return;
70565
70933
  dir = realpathSync6.native(dir);
70566
70934
  } catch {
70567
70935
  return;
@@ -70573,7 +70941,7 @@ async function candidateRepos(activity, env = process.env) {
70573
70941
  };
70574
70942
  const toplevel = async (directory) => {
70575
70943
  let existing = directory;
70576
- while (!await stat30(existing).catch(() => void 0)) {
70944
+ while (!await stat31(existing).catch(() => void 0)) {
70577
70945
  const parent = path136.dirname(existing);
70578
70946
  if (parent === existing) return void 0;
70579
70947
  existing = parent;
@@ -70631,7 +70999,7 @@ async function cloneRoot(env) {
70631
70999
  const home = homedir20();
70632
71000
  for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path136.join(home, r))]) {
70633
71001
  try {
70634
- if ((await stat30(root)).isDirectory()) return root;
71002
+ if ((await stat31(root)).isDirectory()) return root;
70635
71003
  } catch {
70636
71004
  }
70637
71005
  }
@@ -70661,7 +71029,7 @@ async function enrollProject(input2, env = process.env) {
70661
71029
  const baseStore = phrenStoreRoot(env);
70662
71030
  const store = await resolveCodeStore(baseStore, input2.store, true);
70663
71031
  try {
70664
- if (!(await stat30(path136.join(baseStore, ".config"))).isDirectory()) throw new Error();
71032
+ if (!(await stat31(path136.join(baseStore, ".config"))).isDirectory()) throw new Error();
70665
71033
  } catch {
70666
71034
  throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
70667
71035
  }
@@ -70674,7 +71042,7 @@ async function enrollProject(input2, env = process.env) {
70674
71042
  if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
70675
71043
  directory = path136.join(await cloneRoot(env), name);
70676
71044
  try {
70677
- await stat30(directory);
71045
+ await stat31(directory);
70678
71046
  throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
70679
71047
  } catch (error62) {
70680
71048
  if (error62 instanceof BridgeError) throw error62;
@@ -70692,7 +71060,7 @@ async function enrollProject(input2, env = process.env) {
70692
71060
  if (raw.length > 4096 || raw.includes("\0") || !path136.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
70693
71061
  try {
70694
71062
  directory = realpathSync6.native(raw);
70695
- if (!(await stat30(directory)).isDirectory()) throw new Error();
71063
+ if (!(await stat31(directory)).isDirectory()) throw new Error();
70696
71064
  } catch {
70697
71065
  throw new BridgeError(404, "That folder is not on this computer.");
70698
71066
  }
@@ -76192,7 +76560,7 @@ var init_project_git = __esm({
76192
76560
 
76193
76561
  // src/bridge/simulators.ts
76194
76562
  import { execFile as execFile30 } from "node:child_process";
76195
- import { chmod as chmod5, mkdir as mkdir34, readFile as readFile56, rename as rename10, stat as stat31, unlink as unlink9, writeFile as writeFile11 } from "node:fs/promises";
76563
+ import { chmod as chmod5, mkdir as mkdir34, readFile as readFile56, rename as rename11, stat as stat32, unlink as unlink9, writeFile as writeFile11 } from "node:fs/promises";
76196
76564
  import { tmpdir as tmpdir7 } from "node:os";
76197
76565
  import path144 from "node:path";
76198
76566
  import { createHash as createHash35, randomUUID as randomUUID31 } from "node:crypto";
@@ -76334,7 +76702,7 @@ default: fail(2, "unknown command \\(command)")
76334
76702
  ` : await readFile56(new URL("./native/simtap.swift", import.meta.url), "utf8");
76335
76703
  const digest2 = createHash35("sha256").update(code).digest("hex");
76336
76704
  const saved = await readFile56(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
76337
- if (await stat31(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
76705
+ if (await stat32(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
76338
76706
  await mkdir34(dir, { recursive: true, mode: 448 });
76339
76707
  const temporary = path144.join(dir, `simtap.${randomUUID31()}`), source = temporary + ".swift";
76340
76708
  const sidecar = temporary + ".sha256";
@@ -76346,8 +76714,8 @@ default: fail(2, "unknown command \\(command)")
76346
76714
  await chmod5(temporary, 448);
76347
76715
  const binarySha = createHash35("sha256").update(await readFile56(temporary)).digest("hex");
76348
76716
  await writeFile11(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
76349
- await rename10(temporary, binary);
76350
- await rename10(sidecar, binary + ".sha256");
76717
+ await rename11(temporary, binary);
76718
+ await rename11(sidecar, binary + ".sha256");
76351
76719
  } finally {
76352
76720
  await Promise.all([source, temporary, sidecar].map((file4) => unlink9(file4).catch(() => void 0)));
76353
76721
  }
@@ -78259,6 +78627,7 @@ var init_server_routes = __esm({
78259
78627
  moveConductor: true,
78260
78628
  moveToComputer: true,
78261
78629
  moveConductorToComputer: true,
78630
+ moveResume: true,
78262
78631
  claudeAccountAdd: true,
78263
78632
  workerRelocation: 1,
78264
78633
  projectMemory: true,
@@ -78454,8 +78823,8 @@ async function readDeltaPreview(target2, file4, rollout) {
78454
78823
  const handle = await open29(file4 + ".preview.json", constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK);
78455
78824
  let bytes;
78456
78825
  try {
78457
- const stat32 = await handle.stat();
78458
- if (!stat32.isFile() || stat32.size > MAX_PREVIEW_BYTES) return null;
78826
+ const stat33 = await handle.stat();
78827
+ if (!stat33.isFile() || stat33.size > MAX_PREVIEW_BYTES) return null;
78459
78828
  const buffer = Buffer.alloc(MAX_PREVIEW_BYTES + 1);
78460
78829
  const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
78461
78830
  if (bytesRead > MAX_PREVIEW_BYTES) return null;
@@ -79214,6 +79583,7 @@ async function serve(version2, options = {}) {
79214
79583
  const agentHooks = new AgentHooks(void 0, modules, path151.join(bridgeRoot(), "deliveries.json"));
79215
79584
  let succession;
79216
79585
  const returns = dispatches ? new DispatchReturns({
79586
+ takesPrompt: (target2, pane) => takesPrompt(target2.server, pane, target2.session, promptGuards(agentHooks, target2)),
79217
79587
  localComputer: { id: computerID2, name: hostname13() },
79218
79588
  forward: (origin, text5, deliveryId) => succession?.forward(origin, text5, deliveryId) ?? Promise.resolve(void 0),
79219
79589
  // Continue on another signed-in account when a Claude worker stops at its usage limit: opt-in, `phren config account-failover on`.
@@ -79269,7 +79639,11 @@ async function serve(version2, options = {}) {
79269
79639
  return pane && session ? { session, terminal: pane.terminal_id } : void 0;
79270
79640
  },
79271
79641
  notify: (target2, text5, deliveryId, computer) => handOff({ computer, target: target2, text: text5, deliveryId }, { notifySender: false, bypassConductor: true }),
79272
- send: sendPrompt
79642
+ send: sendPrompt,
79643
+ delivery: (target2, deliveryId) => agentHooks.deliveries.status(deliveryId, target2),
79644
+ inFlight: (target2) => agentHooks.deliveries.holding(target2),
79645
+ held: (target2, deliveryId) => agentHooks.deliveries.held(deliveryId, target2),
79646
+ ready: (target2, pane) => takesPrompt(target2.server, pane, target2.session, promptGuards(agentHooks, target2))
79273
79647
  }) : void 0;
79274
79648
  succession = dispatches ? new ConductorSuccessionService({
79275
79649
  root,
@@ -79291,6 +79665,7 @@ async function serve(version2, options = {}) {
79291
79665
  launch: (server, data, options2) => launches.run(() => launchSession(server, data, { trustFolder: true, ...options2 })),
79292
79666
  inventory: () => launchCheckOff() ? Promise.resolve(void 0) : harnessInventoryWithin(2500),
79293
79667
  transcript: async (target2) => transcriptTail(await targetTranscriptPath(target2)),
79668
+ copyConversation: async (target2, home, check2) => copyClaudeConversation(await targetTranscriptPath(target2), home, process.env, check2),
79294
79669
  paneAccount: (server, pane) => paneAccount(paneAccountKey(server, pane.pane_id), typeof pane.terminal_id === "string" ? pane.terminal_id : void 0)?.id,
79295
79670
  paneDispatch: async (server, pane) => {
79296
79671
  const dispatch2 = (await readTurn(server, String(pane.pane_id)))?.dispatch;
@@ -79643,6 +80018,7 @@ var init_server = __esm({
79643
80018
  init_harnesses();
79644
80019
  init_pane_accounts();
79645
80020
  init_turn_records();
80021
+ init_session_activity();
79646
80022
  init_launch_brief();
79647
80023
  init_conductor_role();
79648
80024
  init_terminal();
@@ -80072,7 +80448,7 @@ async function main() {
80072
80448
  return askpass2(args[1]);
80073
80449
  }
80074
80450
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
80075
- return runBridge2(args, "0.3.55");
80451
+ return runBridge2(args, "0.3.57");
80076
80452
  }
80077
80453
  main().then((code) => {
80078
80454
  process.exitCode = code;