@phren/cli 0.3.16 → 0.3.17

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 (41) hide show
  1. package/dist/bridge/agent-hooks.d.ts +10 -0
  2. package/dist/bridge/agent-hooks.js +49 -10
  3. package/dist/bridge/claude-suggestion.d.ts +8 -0
  4. package/dist/bridge/claude-suggestion.js +71 -0
  5. package/dist/bridge/dispatch-returns.d.ts +6 -3
  6. package/dist/bridge/dispatch-returns.js +29 -17
  7. package/dist/bridge/job-registry.d.ts +144 -0
  8. package/dist/bridge/job-registry.js +247 -0
  9. package/dist/bridge/opencode-permissions.d.ts +17 -0
  10. package/dist/bridge/opencode-permissions.js +96 -0
  11. package/dist/bridge/protocol.d.ts +4 -0
  12. package/dist/bridge/protocol.js +3 -0
  13. package/dist/bridge/resources.d.ts +38 -5
  14. package/dist/bridge/resources.js +110 -19
  15. package/dist/bridge/server-launch.js +8 -0
  16. package/dist/bridge/server-routes.d.ts +1 -1
  17. package/dist/bridge/server-routes.js +8 -6
  18. package/dist/bridge/server-stream.js +11 -2
  19. package/dist/bridge/session-activity.d.ts +13 -0
  20. package/dist/bridge/session-activity.js +27 -2
  21. package/dist/bridge/settings-switch.d.ts +12 -2
  22. package/dist/bridge/settings-switch.js +13 -6
  23. package/dist/bridge/speech.d.ts +6 -4
  24. package/dist/bridge/speech.js +6 -4
  25. package/dist/bridge/terminal-tmux.d.ts +4 -2
  26. package/dist/bridge/terminal-tmux.js +13 -7
  27. package/dist/bridge/transcript-claude.d.ts +9 -1
  28. package/dist/bridge/transcript-claude.js +50 -1
  29. package/dist/bridge/transcript-codex.js +23 -3
  30. package/dist/bridge/transcripts.d.ts +5 -1
  31. package/dist/bridge/transcripts.js +13 -3
  32. package/dist/bridge-hook.mjs +1044 -528
  33. package/dist/computers/command.js +2 -1
  34. package/dist/fanout/opencode-serve.js +3 -2
  35. package/dist/hooks.d.ts +3 -0
  36. package/dist/hooks.js +41 -6
  37. package/dist/init/setup.js +6 -3
  38. package/dist/modules/registry.js +1 -1
  39. package/dist/tools/dispatch.js +3 -2
  40. package/package.json +1 -1
  41. package/plugins/opencode/phren-transcript.js +4 -4
@@ -268,10 +268,10 @@ function mergeDefs(...defs) {
268
268
  function cloneDef(schema) {
269
269
  return mergeDefs(schema._zod.def);
270
270
  }
271
- function getElementAtPath(obj, path112) {
272
- if (!path112)
271
+ function getElementAtPath(obj, path114) {
272
+ if (!path114)
273
273
  return obj;
274
- return path112.reduce((acc, key3) => acc?.[key3], obj);
274
+ return path114.reduce((acc, key3) => acc?.[key3], obj);
275
275
  }
276
276
  function promiseAllObject(promisesObj) {
277
277
  const keys = Object.keys(promisesObj);
@@ -530,11 +530,11 @@ function explicitlyAborted(x, startIndex = 0) {
530
530
  }
531
531
  return false;
532
532
  }
533
- function prefixIssues(path112, issues) {
533
+ function prefixIssues(path114, issues) {
534
534
  return issues.map((iss) => {
535
535
  var _a3;
536
536
  (_a3 = iss).path ?? (_a3.path = []);
537
- iss.path.unshift(path112);
537
+ iss.path.unshift(path114);
538
538
  return iss;
539
539
  });
540
540
  }
@@ -1055,16 +1055,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
1055
1055
  }
1056
1056
  function formatError(error62, mapper = (issue2) => issue2.message) {
1057
1057
  const fieldErrors = { _errors: [] };
1058
- const processError = (error63, path112 = []) => {
1058
+ const processError = (error63, path114 = []) => {
1059
1059
  for (const issue2 of error63.issues) {
1060
1060
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1061
- issue2.errors.map((issues) => processError({ issues }, [...path112, ...issue2.path]));
1061
+ issue2.errors.map((issues) => processError({ issues }, [...path114, ...issue2.path]));
1062
1062
  } else if (issue2.code === "invalid_key") {
1063
- processError({ issues: issue2.issues }, [...path112, ...issue2.path]);
1063
+ processError({ issues: issue2.issues }, [...path114, ...issue2.path]);
1064
1064
  } else if (issue2.code === "invalid_element") {
1065
- processError({ issues: issue2.issues }, [...path112, ...issue2.path]);
1065
+ processError({ issues: issue2.issues }, [...path114, ...issue2.path]);
1066
1066
  } else {
1067
- const fullpath = [...path112, ...issue2.path];
1067
+ const fullpath = [...path114, ...issue2.path];
1068
1068
  if (fullpath.length === 0) {
1069
1069
  fieldErrors._errors.push(mapper(issue2));
1070
1070
  } else {
@@ -1103,17 +1103,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
1103
1103
  }
1104
1104
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
1105
1105
  const result = { errors: [] };
1106
- const processError = (error63, path112 = []) => {
1106
+ const processError = (error63, path114 = []) => {
1107
1107
  var _a3;
1108
1108
  for (const issue2 of error63.issues) {
1109
1109
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1110
- issue2.errors.map((issues) => processError({ issues }, [...path112, ...issue2.path]));
1110
+ issue2.errors.map((issues) => processError({ issues }, [...path114, ...issue2.path]));
1111
1111
  } else if (issue2.code === "invalid_key") {
1112
- processError({ issues: issue2.issues }, [...path112, ...issue2.path]);
1112
+ processError({ issues: issue2.issues }, [...path114, ...issue2.path]);
1113
1113
  } else if (issue2.code === "invalid_element") {
1114
- processError({ issues: issue2.issues }, [...path112, ...issue2.path]);
1114
+ processError({ issues: issue2.issues }, [...path114, ...issue2.path]);
1115
1115
  } else {
1116
- const fullpath = [...path112, ...issue2.path];
1116
+ const fullpath = [...path114, ...issue2.path];
1117
1117
  if (fullpath.length === 0) {
1118
1118
  result.errors.push(mapper(issue2));
1119
1119
  continue;
@@ -1152,8 +1152,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
1152
1152
  }
1153
1153
  function toDotPath(_path) {
1154
1154
  const segs = [];
1155
- const path112 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1156
- for (const seg of path112) {
1155
+ const path114 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1156
+ for (const seg of path114) {
1157
1157
  if (typeof seg === "number")
1158
1158
  segs.push(`[${seg}]`);
1159
1159
  else if (typeof seg === "symbol")
@@ -19149,13 +19149,13 @@ function resolveRef(ref, ctx) {
19149
19149
  if (!ref.startsWith("#")) {
19150
19150
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
19151
19151
  }
19152
- const path112 = ref.slice(1).split("/").filter(Boolean);
19153
- if (path112.length === 0) {
19152
+ const path114 = ref.slice(1).split("/").filter(Boolean);
19153
+ if (path114.length === 0) {
19154
19154
  return ctx.rootSchema;
19155
19155
  }
19156
19156
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
19157
- if (path112[0] === defsKey) {
19158
- const key3 = path112[1] === void 0 ? void 0 : decodeJSONPointerSegment(path112[1]);
19157
+ if (path114[0] === defsKey) {
19158
+ const key3 = path114[1] === void 0 ? void 0 : decodeJSONPointerSegment(path114[1]);
19159
19159
  if (!key3 || !ctx.defs[key3]) {
19160
19160
  throw new Error(`Reference not found: ${ref}`);
19161
19161
  }
@@ -20506,7 +20506,7 @@ async function atomicInPrivateDir(file3, value2, mode) {
20506
20506
  function targetFromURL(url2) {
20507
20507
  return targetSchema.parse(Object.fromEntries(["server", "workspace", "tab", "pane", "source", "session"].map((k) => [k, url2.searchParams.get(k)])));
20508
20508
  }
20509
- var PROTOCOL, MAX_FRAME, id, serverName, computerName, provider, sessionId, targetSchema, startingTargetSchema, BridgeError, ERROR_CODE, requestID, launchEfforts, PERMISSION_MODES;
20509
+ var PROTOCOL, MAX_FRAME, id, serverName, computerName, provider, sessionId, targetSchema, startingTargetSchema, approvalDecisions, BridgeError, ERROR_CODE, requestID, launchEfforts, PERMISSION_MODES;
20510
20510
  var init_protocol = __esm({
20511
20511
  "src/bridge/protocol.ts"() {
20512
20512
  "use strict";
@@ -20534,6 +20534,7 @@ var init_protocol = __esm({
20534
20534
  starting: external_exports.literal(true),
20535
20535
  startingToken: external_exports.string().regex(/^[a-f0-9]{64}$/)
20536
20536
  });
20537
+ approvalDecisions = ["approve", "deny", "allow-project", "allow-everywhere"];
20537
20538
  BridgeError = class extends Error {
20538
20539
  constructor(status, message, details) {
20539
20540
  super(message);
@@ -22769,7 +22770,7 @@ function writeNode(state, level, node2, parent, ctx) {
22769
22770
  else {
22770
22771
  const layout = scalarLayout(state, node2, parent, level, iskey, !block);
22771
22772
  detectAllowedStyles(layout);
22772
- for (const rule of state.scalarStyleRules) rule(layout);
22773
+ for (const rule2 of state.scalarStyleRules) rule2(layout);
22773
22774
  body2 = renderScalar(layout);
22774
22775
  state.openEnded = (layout.style === SCALAR_STYLE.LITERAL_BLOCK || layout.style === SCALAR_STYLE.FOLDED_BLOCK) && (node2.value === "\n" || node2.value.endsWith("\n\n"));
22775
22776
  shouldPrintTag = node2.tagged || body2 === "" && layout.flowOnly && parent?.kind === "sequence" && !hasAnchor || layout.style !== SCALAR_STYLE.PLAIN && node2.tag !== state.defaultScalarTagName;
@@ -25348,7 +25349,7 @@ var init_package_metadata = __esm({
25348
25349
  __dirname = path15.dirname(fileURLToPath2(import.meta.url));
25349
25350
  ROOT = path15.join(__dirname, "..");
25350
25351
  PACKAGE_JSON_PATH = path15.join(ROOT, "package.json");
25351
- BUNDLED_VERSION = true ? "0.3.16" : "0.0.0";
25352
+ BUNDLED_VERSION = true ? "0.3.17" : "0.0.0";
25352
25353
  PACKAGE_JSON = readPackageJson();
25353
25354
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
25354
25355
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -25633,30 +25634,30 @@ var init_claude_accounts = __esm({
25633
25634
 
25634
25635
  // src/bridge/pane-accounts.ts
25635
25636
  import path24 from "node:path";
25636
- function entry(paneKey3, terminal2) {
25637
- let current2 = known.get(paneKey3);
25637
+ function entry(paneKey4, terminal2) {
25638
+ let current2 = known.get(paneKey4);
25638
25639
  if (current2 && terminal2 && current2.terminal && current2.terminal !== terminal2) {
25639
- known.delete(paneKey3);
25640
+ known.delete(paneKey4);
25640
25641
  current2 = void 0;
25641
25642
  }
25642
25643
  if (!current2) {
25643
25644
  while (known.size >= MAX_PANES) known.delete(known.keys().next().value);
25644
25645
  current2 = {};
25645
- known.set(paneKey3, current2);
25646
+ known.set(paneKey4, current2);
25646
25647
  }
25647
25648
  if (terminal2) current2.terminal = terminal2;
25648
25649
  return current2;
25649
25650
  }
25650
- function recordPaneAccount(paneKey3, accountId, terminal2) {
25651
- entry(paneKey3, terminal2).launched = accountId;
25651
+ function recordPaneAccount(paneKey4, accountId, terminal2) {
25652
+ entry(paneKey4, terminal2).launched = accountId;
25652
25653
  }
25653
- function notePaneTranscript(paneKey3, file3, terminal2) {
25654
+ function notePaneTranscript(paneKey4, file3, terminal2) {
25654
25655
  if (typeof file3 !== "string" || !path24.isAbsolute(file3) || file3.length > 4096) return;
25655
25656
  const home = claudeHomeOfPath(file3);
25656
- if (home) entry(paneKey3, terminal2).fromFile = home.id;
25657
+ if (home) entry(paneKey4, terminal2).fromFile = home.id;
25657
25658
  }
25658
- function paneAccount(paneKey3, terminal2) {
25659
- const current2 = known.get(paneKey3);
25659
+ function paneAccount(paneKey4, terminal2) {
25660
+ const current2 = known.get(paneKey4);
25660
25661
  if (!current2 || terminal2 && current2.terminal && current2.terminal !== terminal2) return void 0;
25661
25662
  const id2 = current2.fromFile ?? current2.launched;
25662
25663
  const home = id2 ? claudeHome(id2) : void 0;
@@ -27896,6 +27897,16 @@ async function claudeChildBelongsTo(file3, parent, agentId) {
27896
27897
  return false;
27897
27898
  }
27898
27899
  }
27900
+ function queuePromptKey(raw) {
27901
+ if (raw.type !== "user" || raw.isSidechain === true) return void 0;
27902
+ const content = object2(raw.message).content;
27903
+ const text4 = unwrapPastedContent(typeof content === "string" ? content : objects(content).filter((block) => block.type === "text").map((block) => String(block.text ?? "")).join("\n"));
27904
+ if (!text4.trim() || text4.trimStart().startsWith("<")) return void 0;
27905
+ return createHash8("sha256").update(text4).digest("hex");
27906
+ }
27907
+ function scheduledPromptTurn(raw) {
27908
+ return raw.turnOrigin === "scheduled" || typeof raw.scheduledTaskId === "string" || object2(raw.origin).kind === "auto-continuation";
27909
+ }
27899
27910
  function taskNotification(content) {
27900
27911
  const envelope = /<task-notification>([\s\S]*?)<\/task-notification>/.exec(content)?.[1];
27901
27912
  if (!envelope) return;
@@ -27963,11 +27974,22 @@ function phrenHookContext(raw, includeSidechain = false) {
27963
27974
  content: content.length > HOOK_CONTEXT_LIMIT ? content.slice(0, HOOK_CONTEXT_LIMIT) + "\n\u2026" : content
27964
27975
  };
27965
27976
  }
27966
- function visibleClaudeEvent(raw, includeSidechain = false) {
27977
+ function visibleClaudeEvent(raw, includeSidechain = false, queue3) {
27967
27978
  if (raw.type === "phren/fanout-message" && typeof raw.text === "string") {
27968
27979
  return { type: "user", timestamp: raw.timestamp, message: { role: "user", content: raw.text.slice(0, 65536) } };
27969
27980
  }
27970
27981
  if (raw.type === "queue-operation" && typeof raw.content === "string") raw = { ...raw, content: unwrapPastedContent(raw.content) };
27982
+ if (raw.type === "queue-operation" && raw.operation === "dequeue") {
27983
+ const key3 = queue3?.key, scheduled = queue3?.scheduled;
27984
+ if (queue3) {
27985
+ queue3.key = void 0;
27986
+ queue3.scheduled = void 0;
27987
+ }
27988
+ return { type: "phren_queue_consumed", ...key3 ? { key: key3 } : {}, ...key3 && scheduled ? { scheduled: true } : {}, timestamp: raw.timestamp };
27989
+ }
27990
+ if (raw.type === "queue-operation" && raw.operation === "popAll" && typeof raw.content === "string") {
27991
+ return { type: "phren_queue_returned", key: createHash8("sha256").update(raw.content).digest("hex"), timestamp: raw.timestamp };
27992
+ }
27971
27993
  if (raw.type === "queue-operation" && raw.operation === "remove" && typeof raw.content === "string") {
27972
27994
  return { type: "phren_queue_consumed", key: createHash8("sha256").update(raw.content).digest("hex"), timestamp: raw.timestamp };
27973
27995
  }
@@ -28013,6 +28035,13 @@ function visibleClaudeEvent(raw, includeSidechain = false) {
28013
28035
  if (raw.type === "permission-mode" && typeof raw.permissionMode === "string" && /^[A-Za-z]{1,30}$/.test(raw.permissionMode)) {
28014
28036
  return { type: "permission-mode", permissionMode: raw.permissionMode, ...typeof raw.timestamp === "string" ? { timestamp: raw.timestamp } : {} };
28015
28037
  }
28038
+ if (queue3 && raw.type === "user") {
28039
+ const key3 = queuePromptKey(raw);
28040
+ if (key3 !== void 0) {
28041
+ queue3.key = key3;
28042
+ queue3.scheduled = scheduledPromptTurn(raw);
28043
+ }
28044
+ }
28016
28045
  if (raw.isMeta || raw.isSidechain && !includeSidechain || !["user", "assistant", "system"].includes(String(raw.type))) return void 0;
28017
28046
  raw = Object.fromEntries(Object.entries(raw).filter(([key3]) => CLAUDE_KEYS.has(key3)));
28018
28047
  const message = unwrapUserText(object2(raw.message));
@@ -28092,7 +28121,7 @@ var init_codex_question_reply = __esm({
28092
28121
 
28093
28122
  // src/bridge/transcript-codex.ts
28094
28123
  import { createReadStream as createReadStream2 } from "node:fs";
28095
- import { stat as stat7 } from "node:fs/promises";
28124
+ import { open as open6, stat as stat7 } from "node:fs/promises";
28096
28125
  function addChildRelation(line, found) {
28097
28126
  if (!line.includes("SubAgentActivity")) return;
28098
28127
  try {
@@ -28111,10 +28140,24 @@ function addChildRelation(line, found) {
28111
28140
  } catch {
28112
28141
  }
28113
28142
  }
28143
+ async function readAt(file3, position, length) {
28144
+ const handle = await open6(file3, "r");
28145
+ try {
28146
+ const buffer = Buffer.alloc(length);
28147
+ const { bytesRead } = await handle.read(buffer, 0, length, position);
28148
+ return buffer.subarray(0, bytesRead);
28149
+ } finally {
28150
+ await handle.close();
28151
+ }
28152
+ }
28153
+ async function sameBytes(file3, position, expected) {
28154
+ if (position < 0) return false;
28155
+ return (await readAt(file3, position, expected.length).catch(() => Buffer.alloc(0))).equals(expected);
28156
+ }
28114
28157
  async function directChildAgents(file3) {
28115
28158
  const metadata = await stat7(file3), cached3 = childRelationCache.get(file3);
28116
28159
  if (cached3 && cached3.dev === metadata.dev && cached3.ino === metadata.ino && cached3.fileSize === metadata.size && cached3.mtimeMs === metadata.mtimeMs) return [...cached3.relations.values()];
28117
- const append = cached3 && cached3.dev === metadata.dev && cached3.ino === metadata.ino && metadata.size > cached3.fileSize;
28160
+ const append = cached3 && cached3.dev === metadata.dev && cached3.ino === metadata.ino && metadata.size > cached3.fileSize && await sameBytes(file3, cached3.completeOffset - cached3.tail.length, cached3.tail);
28118
28161
  const start = append ? cached3.completeOffset : 0;
28119
28162
  const found = append ? new Map(cached3.relations) : /* @__PURE__ */ new Map();
28120
28163
  let pending = Buffer.alloc(0), completeOffset = start;
@@ -28128,12 +28171,14 @@ async function directChildAgents(file3) {
28128
28171
  pending = pending.subarray(newline + 1);
28129
28172
  }
28130
28173
  }
28174
+ const tail2 = completeOffset > 0 ? await readAt(file3, Math.max(0, completeOffset - TAIL_CHECK), Math.min(TAIL_CHECK, completeOffset)) : Buffer.alloc(0);
28131
28175
  const entry2 = {
28132
28176
  dev: metadata.dev,
28133
28177
  ino: metadata.ino,
28134
28178
  fileSize: metadata.size,
28135
28179
  completeOffset,
28136
28180
  mtimeMs: metadata.mtimeMs,
28181
+ tail: tail2,
28137
28182
  relations: found
28138
28183
  };
28139
28184
  childRelationCache.set(file3, entry2);
@@ -28369,9 +28414,9 @@ function resolveString(expression, source) {
28369
28414
  const declaration = new RegExp(`\\b(?:const|let|var)\\s+${identifier}\\s*=\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`)`).exec(source);
28370
28415
  return declaration ? unescapeJs(declaration[1].slice(1, -1)) : void 0;
28371
28416
  }
28372
- function callArguments(source, open24) {
28417
+ function callArguments(source, open25) {
28373
28418
  let depth = 0, quote5 = "";
28374
- for (let index2 = open24; index2 < source.length; index2++) {
28419
+ for (let index2 = open25; index2 < source.length; index2++) {
28375
28420
  const character = source[index2];
28376
28421
  if (quote5) {
28377
28422
  if (character === "\\") index2++;
@@ -28384,7 +28429,7 @@ function callArguments(source, open24) {
28384
28429
  }
28385
28430
  if (character === "(" || character === "{" || character === "[") depth++;
28386
28431
  else if (character === ")" || character === "}" || character === "]") {
28387
- if (--depth === 0) return source.slice(open24 + 1, index2);
28432
+ if (--depth === 0) return source.slice(open25 + 1, index2);
28388
28433
  }
28389
28434
  }
28390
28435
  return void 0;
@@ -28483,7 +28528,7 @@ function rewriteProjectedOutput(entries2, base) {
28483
28528
  entry2.raw = { ...renameProjectedChanges(entry2.raw, base), payload: { ...payload, call_id: `${base}:1` } };
28484
28529
  }
28485
28530
  }
28486
- var childRelationCache, OUTPUT_TAIL2, MCP_OUTPUT, PATCH_FILE, COMMAND, WRAPPED_TOOL, VIEW_IMAGE, ITEM_TOOLS, CODE_TOOL_CALL, JS_ESCAPES, projectedCodeCalls;
28531
+ var childRelationCache, TAIL_CHECK, OUTPUT_TAIL2, MCP_OUTPUT, PATCH_FILE, COMMAND, WRAPPED_TOOL, VIEW_IMAGE, ITEM_TOOLS, CODE_TOOL_CALL, JS_ESCAPES, projectedCodeCalls;
28487
28532
  var init_transcript_codex = __esm({
28488
28533
  "src/bridge/transcript-codex.ts"() {
28489
28534
  "use strict";
@@ -28492,6 +28537,7 @@ var init_transcript_codex = __esm({
28492
28537
  init_transcript_claude();
28493
28538
  init_codex_question_reply();
28494
28539
  childRelationCache = /* @__PURE__ */ new Map();
28540
+ TAIL_CHECK = 256;
28495
28541
  OUTPUT_TAIL2 = 4e3;
28496
28542
  MCP_OUTPUT = 65536;
28497
28543
  PATCH_FILE = 2e5;
@@ -28619,6 +28665,11 @@ function childAgent(tree, id2) {
28619
28665
  if (nested) return nested;
28620
28666
  }
28621
28667
  }
28668
+ function runningChildAgents(tree) {
28669
+ return tree.flatMap(function visit3(child) {
28670
+ return [child, ...child.children.flatMap(visit3)];
28671
+ }).filter((child) => child.state === "running");
28672
+ }
28622
28673
  function imageReferences(content, toolResults = false) {
28623
28674
  if (!Array.isArray(content)) return content;
28624
28675
  return content.map((value2) => {
@@ -28737,10 +28788,10 @@ async function transcriptPath(source, session, account) {
28737
28788
  async function refreshTranscript(file3, source, session) {
28738
28789
  if (source === "codex" && file3.startsWith(materializedRoot() + path32.sep)) await materializeCodexThread(session);
28739
28790
  }
28740
- function visibleEvent(raw, source, includeSidechain = false, cwd) {
28791
+ function visibleEvent(raw, source, includeSidechain = false, cwd, queue3) {
28741
28792
  if (source === "phren" || source === "opencode") return visibleOpencodeEvent(raw, source, cwd);
28742
28793
  if (source === "codex") return visibleCodexEvent(raw);
28743
- if (source === "claude") return visibleClaudeEvent(raw, includeSidechain);
28794
+ if (source === "claude") return visibleClaudeEvent(raw, includeSidechain, queue3);
28744
28795
  return visibleCopilotEvent(raw);
28745
28796
  }
28746
28797
  async function historicalImage(file3, line, block, source, inner) {
@@ -28841,11 +28892,12 @@ var init_transcripts = __esm({
28841
28892
  const entryBudget = opening ? 60 : 200;
28842
28893
  const byteBudget = opening ? 1048576 : 4194304;
28843
28894
  let bytes = 0, cursor = end, held;
28895
+ const queue3 = {};
28844
28896
  for await (const row of index2.rows(handle, end, lower, signal)) {
28845
28897
  signal?.throwIfAborted();
28846
28898
  let rows = [];
28847
28899
  try {
28848
- let raw = row.bytes && visibleEvent(object2(JSON.parse(row.bytes.toString())), this.source, this.includeSidechain, this.cwd);
28900
+ let raw = row.bytes && visibleEvent(object2(JSON.parse(row.bytes.toString())), this.source, this.includeSidechain, this.cwd, queue3);
28849
28901
  if (raw && this.includeSidechain && raw.isSidechain === true) {
28850
28902
  const { isSidechain: _sidechain, ...own2 } = raw;
28851
28903
  raw = own2;
@@ -28905,14 +28957,14 @@ var init_transcripts = __esm({
28905
28957
  });
28906
28958
 
28907
28959
  // src/bridge/harness-status.ts
28908
- import { open as open6, stat as stat8 } from "node:fs/promises";
28960
+ import { open as open7, stat as stat8 } from "node:fs/promises";
28909
28961
  import { homedir as homedir8 } from "node:os";
28910
28962
  import path33 from "node:path";
28911
28963
  async function opencodeProcessStatus(pids, root = phrenStoreRoot()) {
28912
28964
  const folder = path33.join(root, ".runtime", "sessions");
28913
28965
  let current2, latest = -Infinity;
28914
28966
  for (const pid of pids.slice(0, 16)) {
28915
- const file3 = await open6(path33.join(folder, `opencode-status-${pid}.json`), "r").catch(() => void 0);
28967
+ const file3 = await open7(path33.join(folder, `opencode-status-${pid}.json`), "r").catch(() => void 0);
28916
28968
  if (!file3) continue;
28917
28969
  try {
28918
28970
  if ((await file3.stat()).size > 4096) continue;
@@ -28933,7 +28985,7 @@ async function opencodeTurnStamps(pids, root = phrenStoreRoot()) {
28933
28985
  const folder = path33.join(root, ".runtime", "sessions");
28934
28986
  let current2, latest = -Infinity;
28935
28987
  for (const pid of pids.slice(0, 16)) {
28936
- const file3 = await open6(path33.join(folder, `opencode-status-${pid}.json`), "r").catch(() => void 0);
28988
+ const file3 = await open7(path33.join(folder, `opencode-status-${pid}.json`), "r").catch(() => void 0);
28937
28989
  if (!file3) continue;
28938
28990
  try {
28939
28991
  if ((await file3.stat()).size > 4096) continue;
@@ -29015,7 +29067,7 @@ async function copilotProcessStatus(pids, home = process.env.COPILOT_HOME || pat
29015
29067
  if (!info?.isFile()) return void 0;
29016
29068
  const cached3 = copilotCache.get(file3);
29017
29069
  if (cached3 && cached3.size === info.size && cached3.mtime === info.mtimeMs) return cached3.status;
29018
- const handle = await open6(file3, "r");
29070
+ const handle = await open7(file3, "r");
29019
29071
  let text4;
29020
29072
  try {
29021
29073
  const length = Math.min(info.size, TAIL_BYTES);
@@ -29185,11 +29237,24 @@ function recordedBackground(record2, finishedTasks, now = Date.now()) {
29185
29237
  if (phase.phase !== "ended" || !(now - Date.parse(phase.at) < BACKGROUND_STALE_MS)) return void 0;
29186
29238
  return backgroundLeft(phase.background, phase.at, finishedTasks) || void 0;
29187
29239
  }
29240
+ function awaitedShells(record2, final, now = Date.now()) {
29241
+ const phase = record2 ? turnPhase(record2) : void 0;
29242
+ if (phase?.phase === "ended") {
29243
+ if (!(now - Date.parse(phase.at) < BACKGROUND_STALE_MS)) return void 0;
29244
+ const recorded = backgroundLeft(phase.background, phase.at, final?.finishedTasks);
29245
+ const shells = phase.background !== void 0 ? recorded : final?.awaited ?? 0;
29246
+ return shells && final?.awaited ? Math.min(shells, final.awaited) : void 0;
29247
+ }
29248
+ return final?.completed ? final.awaited || void 0 : void 0;
29249
+ }
29250
+ function liveWork(record2, final, runningChildren = 0, now = Date.now()) {
29251
+ const total = (awaitedShells(record2, final, now) ?? 0) + runningChildren;
29252
+ return total || void 0;
29253
+ }
29188
29254
  async function liveBackground(record2, readFinal, now = Date.now()) {
29189
29255
  if (!record2 || record2.source !== "claude" || !recordedBackground(record2, [], now)) return void 0;
29190
29256
  const final = await readFinal("claude", record2.session).catch(() => void 0);
29191
- const left = recordedBackground(record2, final?.finishedTasks, now);
29192
- return left && final?.awaited ? Math.min(left, final.awaited) : void 0;
29257
+ return awaitedShells(record2, final, now);
29193
29258
  }
29194
29259
  function markBackground(tab, count2) {
29195
29260
  if (!count2 || count2 < 1) return;
@@ -29337,7 +29402,7 @@ var init_tab_activity = __esm({
29337
29402
 
29338
29403
  // src/bridge/codex-daemon.ts
29339
29404
  import { execFile as execFile4 } from "node:child_process";
29340
- import { open as open7, readdir as readdir7, realpath as realpath5, stat as stat9 } from "node:fs/promises";
29405
+ import { open as open8, readdir as readdir7, realpath as realpath5, stat as stat9 } from "node:fs/promises";
29341
29406
  import path36 from "node:path";
29342
29407
  import { promisify as promisify4 } from "node:util";
29343
29408
  function parseElapsed(text4) {
@@ -29382,7 +29447,7 @@ async function underCodexDaemon(env = process.env, pid = process.pid) {
29382
29447
  return false;
29383
29448
  }
29384
29449
  async function rolloutMeta(file3) {
29385
- const handle = await open7(file3, "r").catch(() => void 0);
29450
+ const handle = await open8(file3, "r").catch(() => void 0);
29386
29451
  if (!handle) return void 0;
29387
29452
  let text4;
29388
29453
  try {
@@ -29456,8 +29521,8 @@ async function sameDirectory(a, b) {
29456
29521
  return path36.resolve(a) === path36.resolve(b) || await real(a) === await real(b);
29457
29522
  }
29458
29523
  function assignDaemonConversation(here, self, claimed, rivals, now = Date.now()) {
29459
- const open24 = here.filter((r) => !claimed.has(r.id) && r.startedAt <= now + 6e4);
29460
- const after = (from) => open24.filter((r) => r.startedAt >= from - START_SLACK_MS);
29524
+ const open25 = here.filter((r) => !claimed.has(r.id) && r.startedAt <= now + 6e4);
29525
+ const after = (from) => open25.filter((r) => r.startedAt >= from - START_SLACK_MS);
29461
29526
  if (!rivals.length) {
29462
29527
  const pool = after(self.start);
29463
29528
  const held = pool.filter((r) => r.held);
@@ -32679,7 +32744,7 @@ var require_stream = __commonJS({
32679
32744
  };
32680
32745
  duplex._final = function(callback) {
32681
32746
  if (ws.readyState === ws.CONNECTING) {
32682
- ws.once("open", function open24() {
32747
+ ws.once("open", function open25() {
32683
32748
  duplex._final(callback);
32684
32749
  });
32685
32750
  return;
@@ -32700,7 +32765,7 @@ var require_stream = __commonJS({
32700
32765
  };
32701
32766
  duplex._write = function(chunk, encoding, callback) {
32702
32767
  if (ws.readyState === ws.CONNECTING) {
32703
- ws.once("open", function open24() {
32768
+ ws.once("open", function open25() {
32704
32769
  duplex._write(chunk, encoding, callback);
32705
32770
  });
32706
32771
  return;
@@ -33178,14 +33243,14 @@ var init_wrapper = __esm({
33178
33243
 
33179
33244
  // src/bridge/codex-app-server.ts
33180
33245
  import { spawn as spawn3 } from "node:child_process";
33181
- import { mkdir as mkdir9, open as open8, readFile as readFile14, rm as rm4, stat as stat10 } from "node:fs/promises";
33246
+ import { mkdir as mkdir9, open as open9, readFile as readFile14, rm as rm4, stat as stat10 } from "node:fs/promises";
33182
33247
  import path37 from "node:path";
33183
33248
  async function spawnAppServer(options) {
33184
33249
  const env = { ...options.replaceEnv ? {} : process.env, ...options.env ?? {}, ...options.codexHome ? { CODEX_HOME: options.codexHome } : {} };
33185
33250
  const codexBin = options.codexBin ?? codexExecutable(env);
33186
33251
  await mkdir9(path37.dirname(options.socketPath), { recursive: true, mode: 448 });
33187
33252
  await rm4(options.socketPath, { force: true });
33188
- const log2 = options.logFile ? await open8(options.logFile, "a", 384) : void 0;
33253
+ const log2 = options.logFile ? await open9(options.logFile, "a", 384) : void 0;
33189
33254
  let child;
33190
33255
  const command = [codexBin, "app-server", ...(options.config ?? []).flatMap((value2) => ["-c", value2]), "--listen", `unix://${options.socketPath}`];
33191
33256
  const [file3, ...args] = options.scope ? ["systemd-run", "--user", "--scope", "--quiet", "--collect", `--unit=${options.scope}`, "--", ...command] : command;
@@ -34870,14 +34935,14 @@ async function tmuxSocketsIn(folder) {
34870
34935
  const names = (await readdir9(folder).catch(() => [])).slice(0, 256);
34871
34936
  const found = [];
34872
34937
  for (const name of names) {
34873
- if (found.length >= 32) break;
34874
34938
  if (!tmuxServerName(name)) continue;
34875
34939
  const info = await lstat8(path39.join(folder, name)).catch(() => void 0);
34876
34940
  if (!info?.isSocket() || uid !== void 0 && info.uid !== uid) continue;
34877
- found.push(name);
34941
+ found.push({ name, at: info.mtimeMs });
34878
34942
  if (folder !== primary && !socketPaths.has(name) && !existsSync15(path39.join(primary ?? folder, name))) socketPaths.set(name, path39.join(folder, name));
34879
34943
  }
34880
- return found;
34944
+ found.sort((a, b) => b.at - a.at);
34945
+ return found.slice(0, 32).map((entry2) => entry2.name);
34881
34946
  }
34882
34947
  function setTmuxDeps(replacement) {
34883
34948
  const previous = deps;
@@ -35492,7 +35557,7 @@ import { createHmac, randomBytes as randomBytes2 } from "node:crypto";
35492
35557
  import { execFile as execFile6 } from "node:child_process";
35493
35558
  import { connect } from "node:net";
35494
35559
  import { homedir as homedir9 } from "node:os";
35495
- import { open as open9, readdir as readdir10, readlink, realpath as realpath6, stat as stat11 } from "node:fs/promises";
35560
+ import { open as open10, readdir as readdir10, readlink, realpath as realpath6, stat as stat11 } from "node:fs/promises";
35496
35561
  import path40 from "node:path";
35497
35562
  import { promisify as promisify5 } from "node:util";
35498
35563
  function herdrRoot() {
@@ -35734,7 +35799,7 @@ async function copilotForegroundSession(pids, home = copilotHome()) {
35734
35799
  const logs = names.filter((name) => pids.some((pid) => name.startsWith("process-") && name.endsWith(`-${pid}.log`)));
35735
35800
  let current2, latest = -1;
35736
35801
  for (const name of logs) {
35737
- const file3 = await open9(path40.join(folder, name), "r").catch(() => void 0);
35802
+ const file3 = await open10(path40.join(folder, name), "r").catch(() => void 0);
35738
35803
  if (!file3) continue;
35739
35804
  try {
35740
35805
  const { size } = await file3.stat(), length = Math.min(size, 262144);
@@ -35756,7 +35821,7 @@ async function opencodePidSession(pids, root = phrenStoreRoot()) {
35756
35821
  const folder = path40.join(root, ".runtime", "sessions");
35757
35822
  let current2, latest = -Infinity;
35758
35823
  for (const pid of pids) {
35759
- const file3 = await open9(path40.join(folder, `opencode-pid-${pid}.json`), "r").catch(() => void 0);
35824
+ const file3 = await open10(path40.join(folder, `opencode-pid-${pid}.json`), "r").catch(() => void 0);
35760
35825
  if (!file3) continue;
35761
35826
  try {
35762
35827
  const { size } = await file3.stat();
@@ -35801,8 +35866,8 @@ async function identityFromProcesses(server, pane, pids) {
35801
35866
  });
35802
35867
  if (new Set(candidates).size === 1) {
35803
35868
  if (pane.agent === "claude") {
35804
- const open24 = files.find((file3) => file3.endsWith(`/${candidates[0]}.jsonl`));
35805
- if (open24) notePaneTranscript(paneAccountKey(server, pane.pane_id), open24, String(pane.terminal_id ?? ""));
35869
+ const open25 = files.find((file3) => file3.endsWith(`/${candidates[0]}.jsonl`));
35870
+ if (open25) notePaneTranscript(paneAccountKey(server, pane.pane_id), open25, String(pane.terminal_id ?? ""));
35806
35871
  }
35807
35872
  return { sessionId: candidates[0], noTranscriptLogs: false };
35808
35873
  }
@@ -36759,7 +36824,7 @@ var init_types = __esm({
36759
36824
  });
36760
36825
 
36761
36826
  // src/fanout/adapters/codex.ts
36762
- import * as path79 from "node:path";
36827
+ import * as path80 from "node:path";
36763
36828
  var codex;
36764
36829
  var init_codex = __esm({
36765
36830
  "src/fanout/adapters/codex.ts"() {
@@ -36773,7 +36838,7 @@ var init_codex = __esm({
36773
36838
  "--json",
36774
36839
  ...!o.resume ? ["--sandbox", o.review ? "read-only" : "workspace-write", "-C", o.worktree] : [],
36775
36840
  "-o",
36776
- path79.join(o.job, "final.txt"),
36841
+ path80.join(o.job, "final.txt"),
36777
36842
  ...o.model ? ["-m", o.model] : [],
36778
36843
  ...o.extra ?? [],
36779
36844
  ...o.resume ? [o.resume] : [],
@@ -36786,7 +36851,7 @@ var init_codex = __esm({
36786
36851
 
36787
36852
  // src/fanout/opencode-serve.ts
36788
36853
  import * as fs24 from "node:fs";
36789
- import * as path80 from "node:path";
36854
+ import * as path81 from "node:path";
36790
36855
  function approvalWindow() {
36791
36856
  const value2 = Number(process.env.PHREN_FANOUT_APPROVAL_MS);
36792
36857
  return Number.isFinite(value2) && value2 >= 100 && value2 <= 24 * 36e5 ? Math.floor(value2) : 36e5;
@@ -36843,7 +36908,7 @@ async function driveOpencode(child, o) {
36843
36908
  const decision = await relay(o, session, asked, stop.signal);
36844
36909
  if (decision === "stopped") return;
36845
36910
  line("phren/permission", { permission: asked.permission, patterns: asked.patterns, decision });
36846
- await call("POST", `/permission/${encodeURIComponent(asked.id)}/reply`, decision === "approve" ? { reply: "once" } : { reply: "reject", message: decision === "deny" ? DENIED_FEEDBACK : UNANSWERED_FEEDBACK });
36911
+ await call("POST", `/permission/${encodeURIComponent(asked.id)}/reply`, decision === "approve" ? { reply: "once" } : decision === "always" ? { reply: "always" } : { reply: "reject", message: decision === "deny" ? DENIED_FEEDBACK : UNANSWERED_FEEDBACK });
36847
36912
  };
36848
36913
  const reader = events.body.getReader(), decoder = new TextDecoder();
36849
36914
  let pending = "";
@@ -36913,8 +36978,8 @@ ${message}` : message;
36913
36978
  return error62 ? 1 : 0;
36914
36979
  }
36915
36980
  async function relay(o, session, asked, signal) {
36916
- const directory = path80.join(o.store, ".runtime", "approvals");
36917
- const request9 = path80.join(directory, `opencode-${session}.request.json`), answer = path80.join(directory, `opencode-${session}.answer.json`);
36981
+ const directory = path81.join(o.store, ".runtime", "approvals");
36982
+ const request9 = path81.join(directory, `opencode-${session}.request.json`), answer = path81.join(directory, `opencode-${session}.answer.json`);
36918
36983
  fs24.mkdirSync(directory, { recursive: true, mode: 448 });
36919
36984
  fs24.rmSync(answer, { force: true });
36920
36985
  const created = Date.now(), deadline = created + approvalWindow(), pattern = asked.patterns.join(", ");
@@ -36934,7 +36999,7 @@ async function relay(o, session, asked, signal) {
36934
36999
  if (signal.aborted) return "stopped";
36935
37000
  try {
36936
37001
  const value2 = JSON.parse(fs24.readFileSync(answer, "utf8"));
36937
- if (value2.id === asked.id && (value2.decision === "approve" || value2.decision === "deny")) return value2.decision;
37002
+ if (value2.id === asked.id && (value2.decision === "approve" || value2.decision === "deny" || value2.decision === "always")) return value2.decision;
36938
37003
  } catch {
36939
37004
  }
36940
37005
  }
@@ -37053,15 +37118,15 @@ __export(launcher_exports, {
37053
37118
  import { spawn as spawn11, execFileSync as execFileSync4 } from "node:child_process";
37054
37119
  import { randomBytes as randomBytes5 } from "node:crypto";
37055
37120
  import * as fs25 from "node:fs";
37056
- import * as path81 from "node:path";
37121
+ import * as path82 from "node:path";
37057
37122
  function jobsRoot(store) {
37058
- return path81.join(store, ".runtime", "agent-fanouts");
37123
+ return path82.join(store, ".runtime", "agent-fanouts");
37059
37124
  }
37060
37125
  function readJob(store, id2) {
37061
37126
  if (!/^[a-z0-9][a-z0-9._-]{0,127}$/i.test(id2)) throw new Error("Invalid job id.");
37062
- const root = fs25.realpathSync(jobsRoot(store)), job = path81.join(root, id2);
37127
+ const root = fs25.realpathSync(jobsRoot(store)), job = path82.join(root, id2);
37063
37128
  if (!fs25.lstatSync(job).isDirectory() || fs25.realpathSync(job) !== job) throw new Error("Invalid job directory.");
37064
- const file3 = path81.join(job, "manifest.json"), info = fs25.lstatSync(file3);
37129
+ const file3 = path82.join(job, "manifest.json"), info = fs25.lstatSync(file3);
37065
37130
  if (!info.isFile() || info.isSymbolicLink() || info.size > 65536) throw new Error("Invalid job manifest.");
37066
37131
  const result = manifestSchema.parse(JSON.parse(fs25.readFileSync(file3, "utf8")));
37067
37132
  if (result.id !== id2) throw new Error("Job id does not match its manifest.");
@@ -37079,7 +37144,7 @@ function listJobs(store) {
37079
37144
  }
37080
37145
  function swiftBuildCount() {
37081
37146
  const output2 = execFileSync4("ps", ["-axo", "comm="], { encoding: "utf8", timeout: 5e3 });
37082
- return output2.split("\n").filter((line) => path81.basename(line.trim()) === "xcodebuild").length;
37147
+ return output2.split("\n").filter((line) => path82.basename(line.trim()) === "xcodebuild").length;
37083
37148
  }
37084
37149
  function nearestAgent(pid = process.ppid) {
37085
37150
  if (process.platform === "win32") return void 0;
@@ -37092,7 +37157,7 @@ function nearestAgent(pid = process.ppid) {
37092
37157
  }
37093
37158
  const match = /^(\d+)\s+(.+)$/.exec(row);
37094
37159
  if (!match) return void 0;
37095
- const name = path81.basename(match[2].trim());
37160
+ const name = path82.basename(match[2].trim());
37096
37161
  if (name === "claude") return "claude";
37097
37162
  if (name === "codex" || name.startsWith("codex-")) return "codex";
37098
37163
  pid = Number(match[1]);
@@ -37100,15 +37165,15 @@ function nearestAgent(pid = process.ppid) {
37100
37165
  return void 0;
37101
37166
  }
37102
37167
  function writeManifest2(job, manifest) {
37103
- atomicWriteText(path81.join(job, "manifest.json"), JSON.stringify(manifestSchema.parse(manifest)) + "\n");
37104
- fs25.chmodSync(path81.join(job, "manifest.json"), 384);
37168
+ atomicWriteText(path82.join(job, "manifest.json"), JSON.stringify(manifestSchema.parse(manifest)) + "\n");
37169
+ fs25.chmodSync(path82.join(job, "manifest.json"), 384);
37105
37170
  }
37106
37171
  function createJob(options, env = process.env, nearest = nearestAgent) {
37107
37172
  if (!options.label.trim() || options.label.length > 200) throw new Error("Choose a label of 1 to 200 characters.");
37108
37173
  const worktree = fs25.realpathSync(options.worktree);
37109
37174
  if (!fs25.statSync(worktree).isDirectory()) throw new Error("Choose a worktree directory.");
37110
37175
  const id2 = `${options.provider}-${randomBytes5(12).toString("hex")}`;
37111
- const root = jobsRoot(options.store), job = path81.join(root, id2);
37176
+ const root = jobsRoot(options.store), job = path82.join(root, id2);
37112
37177
  fs25.mkdirSync(job, { recursive: true, mode: 448 });
37113
37178
  fs25.chmodSync(root, 448);
37114
37179
  const claudeParent = uuid3(env.CLAUDE_CODE_SESSION_ID);
@@ -37132,14 +37197,14 @@ function createJob(options, env = process.env, nearest = nearestAgent) {
37132
37197
  ...options.resume ? { resumes: options.resume } : {},
37133
37198
  ...codexParent ? { parent: { provider: "codex", session: codexParent } } : claudeParent ? { parent: { provider: "claude", session: claudeParent } } : {}
37134
37199
  };
37135
- for (const [file3, content] of Object.entries({ "prompt.txt": options.prompt, "events.jsonl": "", "stderr.log": "" })) fs25.writeFileSync(path81.join(job, file3), content, { mode: 384 });
37200
+ for (const [file3, content] of Object.entries({ "prompt.txt": options.prompt, "events.jsonl": "", "stderr.log": "" })) fs25.writeFileSync(path82.join(job, file3), content, { mode: 384 });
37136
37201
  writeManifest2(job, manifest);
37137
37202
  return { job, manifest };
37138
37203
  }
37139
37204
  async function launch(options, reservation = createJob(options)) {
37140
37205
  const { job, manifest } = reservation, adapter = adapters[options.provider];
37141
37206
  console.log(job);
37142
- const out = fs25.openSync(path81.join(job, manifest.eventLog), "a"), err = fs25.openSync(path81.join(job, "stderr.log"), "a");
37207
+ const out = fs25.openSync(path82.join(job, manifest.eventLog), "a"), err = fs25.openSync(path82.join(job, "stderr.log"), "a");
37143
37208
  const password = randomBytes5(24).toString("hex");
37144
37209
  const child = spawn11("nice", ["-n", "15", adapter.command, ...adapter.argv({ ...options, job })], {
37145
37210
  cwd: manifest.worktree,
@@ -37209,8 +37274,8 @@ async function launch(options, reservation = createJob(options)) {
37209
37274
  const timer = setInterval(() => {
37210
37275
  const reason2 = watchdog.reason();
37211
37276
  if (!reason2) return;
37212
- fs25.writeFileSync(path81.join(job, "looped.txt"), reason2 + "\n", { mode: 384 });
37213
- atomicWriteText(path81.join(job, "blocked.json"), JSON.stringify({ type: "tool_loop", pattern: "", message: reason2, at: (/* @__PURE__ */ new Date()).toISOString() }));
37277
+ fs25.writeFileSync(path82.join(job, "looped.txt"), reason2 + "\n", { mode: 384 });
37278
+ atomicWriteText(path82.join(job, "blocked.json"), JSON.stringify({ type: "tool_loop", pattern: "", message: reason2, at: (/* @__PURE__ */ new Date()).toISOString() }));
37214
37279
  kill();
37215
37280
  }, 3e4);
37216
37281
  let exitCode;
@@ -37231,11 +37296,11 @@ async function launch(options, reservation = createJob(options)) {
37231
37296
  for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.off(signal, cancel);
37232
37297
  fs25.closeSync(out);
37233
37298
  fs25.closeSync(err);
37234
- const blockedFile = path81.join(job, "blocked.json"), refusal = refused ?? stderrRefusal(stderr);
37299
+ const blockedFile = path82.join(job, "blocked.json"), refusal = refused ?? stderrRefusal(stderr);
37235
37300
  if (refusal && !fs25.existsSync(blockedFile)) atomicWriteText(blockedFile, JSON.stringify({ ...refusal, at: (/* @__PURE__ */ new Date()).toISOString() }));
37236
37301
  const blocked = fs25.existsSync(blockedFile);
37237
37302
  if (blocked) console.error(`blocked: ${fs25.readFileSync(blockedFile, "utf8").slice(0, 4e3)}`);
37238
- fs25.writeFileSync(path81.join(job, "exit.txt"), `${exitCode}
37303
+ fs25.writeFileSync(path82.join(job, "exit.txt"), `${exitCode}
37239
37304
  `, { mode: 384 });
37240
37305
  writeManifest2(job, {
37241
37306
  ...manifest,
@@ -37262,7 +37327,7 @@ var init_launcher = __esm({
37262
37327
  });
37263
37328
 
37264
37329
  // src/bridge/command.ts
37265
- import { readFile as readFile52 } from "node:fs/promises";
37330
+ import { readFile as readFile53 } from "node:fs/promises";
37266
37331
 
37267
37332
  // src/bridge/owner-inbox.ts
37268
37333
  init_zod();
@@ -37377,7 +37442,7 @@ import * as fs17 from "node:fs";
37377
37442
  import * as path16 from "node:path";
37378
37443
  var core = (names) => names.map((name) => ({ name, profiles: ["core", "full"] }));
37379
37444
  var full = (names) => names.map((name) => ({ name, profiles: ["full"] }));
37380
- var routes = (method, paths) => paths.map((path112) => ({ method, path: path112 }));
37445
+ var routes = (method, paths) => paths.map((path114) => ({ method, path: path114 }));
37381
37446
  var BUILTIN_MODULES = [
37382
37447
  {
37383
37448
  schemaVersion: 1,
@@ -37647,7 +37712,8 @@ var BUILTIN_MODULES = [
37647
37712
  "/v1/subagents/archive-finished",
37648
37713
  "/v1/canary",
37649
37714
  "/v1/speech",
37650
- "/v1/sudo/answer"
37715
+ "/v1/sudo/answer",
37716
+ "/v1/jobs/cleanup"
37651
37717
  ]),
37652
37718
  ...routes("WS", ["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe"])
37653
37719
  ],
@@ -38792,7 +38858,7 @@ async function captureClaudeUsage(original) {
38792
38858
  // src/bridge/install.ts
38793
38859
  init_home_paths();
38794
38860
  init_claude_accounts();
38795
- import { access, chmod as chmod2, copyFile as copyFile2, mkdir as mkdir13, open as open11, readFile as readFile23, rename as rename4, symlink as symlink2, unlink as unlink4, lstat as lstat11, writeFile as writeFile3 } from "node:fs/promises";
38861
+ import { access, chmod as chmod2, copyFile as copyFile2, mkdir as mkdir13, open as open12, readFile as readFile23, rename as rename4, symlink as symlink2, unlink as unlink4, lstat as lstat11, writeFile as writeFile3 } from "node:fs/promises";
38796
38862
  import { homedir as homedir12 } from "node:os";
38797
38863
 
38798
38864
  // src/bridge/claude-account-setup.ts
@@ -39400,7 +39466,7 @@ import { execFile as execFile8 } from "node:child_process";
39400
39466
  import { randomUUID as randomUUID8 } from "node:crypto";
39401
39467
  import { EventEmitter } from "node:events";
39402
39468
  import { existsSync as existsSync17 } from "node:fs";
39403
- import { open as open10, readdir as readdir11, readFile as readFile19, readlink as readlink2, unlink as unlink3 } from "node:fs/promises";
39469
+ import { open as open11, readdir as readdir11, readFile as readFile19, readlink as readlink2, unlink as unlink3 } from "node:fs/promises";
39404
39470
  import { request as request3 } from "node:http";
39405
39471
  import path45 from "node:path";
39406
39472
  import { promisify as promisify7 } from "node:util";
@@ -39556,7 +39622,7 @@ async function processStart(pid) {
39556
39622
  async function writeToAsker(pid, start, password) {
39557
39623
  if (await processStart(pid) !== start) return { status: 410, error: "askpass went away." };
39558
39624
  try {
39559
- const out = await open10(`/proc/${pid}/fd/1`, "w");
39625
+ const out = await open11(`/proc/${pid}/fd/1`, "w");
39560
39626
  try {
39561
39627
  await out.write(`${password}
39562
39628
  `);
@@ -39635,10 +39701,10 @@ var SudoBroker = class {
39635
39701
  this.watchers++;
39636
39702
  const handler = () => listener(this.list());
39637
39703
  this.events.on("change", handler);
39638
- let open24 = true;
39704
+ let open25 = true;
39639
39705
  return () => {
39640
- if (!open24) return;
39641
- open24 = false;
39706
+ if (!open25) return;
39707
+ open25 = false;
39642
39708
  this.watchers--;
39643
39709
  this.events.off("change", handler);
39644
39710
  };
@@ -40460,7 +40526,7 @@ async function install(version3, noService = false, force = false) {
40460
40526
  await mkdir13(versions, { recursive: true, mode: 448 });
40461
40527
  await chmod2(root, 448);
40462
40528
  const serviceLog = path50.join(root, "service.log");
40463
- const log2 = await open11(serviceLog, "a", 384);
40529
+ const log2 = await open12(serviceLog, "a", 384);
40464
40530
  try {
40465
40531
  await log2.chmod(384);
40466
40532
  } finally {
@@ -40668,7 +40734,7 @@ function opencodePluginNeedsWrite(existing, source) {
40668
40734
  return existing.startsWith(OPENCODE_PLUGIN_MARKER);
40669
40735
  }
40670
40736
  async function opencodePluginSource() {
40671
- if (true) return '// Installed by Phren Hook and replaced on every update. Copy it under another name to customize.\nimport { execFileSync } from "node:child_process";\nimport { lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";\nimport { homedir } from "node:os";\nimport path from "node:path";\n\nconst PHREN_STORE = "__PHREN_STORE__";\nconst FLUSH_MS = 250;\nconst MAX_TOOL_OUTPUT = 200_000;\n// OpenCode\'s read tool returns a picture as an inline data URL on the tool\n// part (`state.attachments`). The Hook serves images up to 8 MiB; the session\n// budget bounds what every flush rewrites.\nconst MAX_IMAGE_DATA = 4_000_000;\nconst MAX_SESSION_IMAGE_DATA = 24_000_000;\nconst IMAGE_DATA_URL = /^data:(image\\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;\nconst STOP_REASONS = { stop: "end_turn", "tool-calls": "tool_use", length: "max_tokens" };\nconst OPENCODE_SESSION = /^ses_[0-9A-Za-z]{1,64}$/;\nconst APPROVAL_POLL_MS = 200;\nconst APPROVAL_DEADLINE_MS = 50_000;\n// An ask relayed from its event blocks nothing: the TUI keeps its own prompt,\n// so the phone\'s card can wait as long as the ask does.\nconst RELAYED_DEADLINE_MS = 30 * 60_000;\n\nfunction storeRoot() {\n if (PHREN_STORE && !PHREN_STORE.startsWith("__")) return PHREN_STORE;\n const configured = process.env.PHREN_PATH?.trim();\n if (!configured) return path.join(homedir(), ".phren");\n const expanded = configured === "~" ? homedir() : configured.startsWith("~/") ? path.join(homedir(), configured.slice(2)) : configured;\n return path.resolve(expanded);\n}\n\nfunction text(value) {\n return typeof value === "string" ? value : "";\n}\n\nfunction approvalDirectory() {\n return path.join(storeRoot(), ".runtime", "approvals");\n}\n\nfunction fanoutDirectory() {\n const configured = process.env.PHREN_FANOUT_DIR?.trim();\n if (configured) return path.resolve(configured);\n return path.join(storeRoot(), ".runtime", "agent-fanouts", text(process.env.PHREN_FANOUT_JOB));\n}\n\nfunction fanoutPatterns(input) {\n const value = input?.pattern;\n if (Array.isArray(value)) return value.filter(entry => typeof entry === "string" && entry);\n return typeof value === "string" && value ? [value] : [];\n}\n\n/** The worktree\'s grandparent is the scratch root the fan-out launcher owns:\n * external reads and writes are allowed only inside it. */\nfunction underScratchRoot(value) {\n const scratch = path.dirname(path.dirname(path.resolve(process.cwd())));\n if (scratch === path.parse(scratch).root) return false;\n const resolved = path.resolve(scratch, value);\n return resolved === scratch || resolved.startsWith(scratch + path.sep);\n}\n\nfunction under(parent, value) {\n if (!parent || parent === path.parse(parent).root) return false;\n const root = path.resolve(parent), resolved = path.resolve(root, value);\n return resolved === root || resolved.startsWith(root + path.sep);\n}\n\n/** Beyond the scratch root, a worker legitimately reads its own machine: the\n * node_modules its worktree links into the main checkout, the store it was\n * briefed from, the toolchains a build shells out to, and the temporary\n * directories those builds write. Everything outside this set is refused. */\nfunction fanoutReadable(value) {\n if (underScratchRoot(value)) return true;\n const home = process.env.HOME || "";\n const roots = [home, storeRoot(), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders",\n "/Applications/Xcode.app", "/Library/Developer"];\n return roots.some(root => under(root, value));\n}\n\n/** A headless fan-out worker may edit, run commands and fetch, and continue\n * when OpenCode\'s own loop detector asks (the launcher\'s watchdog stops a real\n * loop and says why, which is a clearer failure than a refused permission).\n * Anything else is refused outright. */\nfunction fanoutAllowed(input) {\n const kind = text(input?.type);\n if (kind === "edit" || kind === "bash" || kind === "webfetch" || kind === "doom_loop") return true;\n if (kind !== "external_directory") return false;\n const patterns = fanoutPatterns(input);\n return patterns.length > 0 && patterns.every(fanoutReadable);\n}\n\nfunction writeBlocked(input) {\n try {\n const directory = fanoutDirectory();\n mkdirSync(directory, { recursive: true });\n writeJsonAtomic(path.join(directory, "blocked.json"), {\n type: text(input?.type) || "action",\n pattern: fanoutPatterns(input).join(", "),\n message: permissionMessage(input),\n at: new Date().toISOString(),\n });\n } catch {}\n}\n\nfunction approvalPaths(sessionID) {\n const base = path.join(approvalDirectory(), `opencode-${sessionID}`);\n return { request: `${base}.request.json`, answer: `${base}.answer.json` };\n}\n\nfunction writeJsonAtomic(file, value) {\n const staging = `${file}.${process.pid}.tmp`;\n writeFileSync(staging, JSON.stringify(value), { mode: 0o600 });\n renameSync(staging, file);\n}\n\nfunction removeFile(file) {\n try { unlinkSync(file); } catch {}\n}\n\nfunction sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/** Started by Phren Hook with a port of its own (`opencode --port N`, with\n * PHREN_OPENCODE_PORT=N and a server password in its environment): the Hook\n * lists and answers this process\'s permission asks over its HTTP API, so no\n * request file is written for them. The port must be on this process\'s own\n * command line, so an OpenCode started by hand in the same shell keeps the\n * file path. Plugins run in a worker whose `process.argv` is the worker\'s,\n * so the command line comes from `ps`, once. */\nlet served;\nfunction servedByHook() {\n if (served !== undefined) return served;\n const port = text(process.env.PHREN_OPENCODE_PORT);\n served = false;\n if (!/^\\d{1,5}$/.test(port) || !text(process.env.OPENCODE_SERVER_PASSWORD)) return served;\n try {\n const command = execFileSync("ps", ["-ww", "-o", "command=", "-p", String(process.pid)], { encoding: "utf8", timeout: 2_000 });\n served = new RegExp(`(?:^|\\\\s)--port(?:\\\\s+|=)${port}(?:\\\\s|$)`).test(command.trim());\n } catch {}\n return served;\n}\n\nfunction setStatus(output, status) {\n if (output && typeof output === "object") output.status = status;\n}\n\nfunction permissionMessage(input) {\n const type = text(input?.type) || "action";\n const pattern = Array.isArray(input?.pattern)\n ? input.pattern.filter(value => typeof value === "string").join(", ")\n : text(input?.pattern);\n const metadata = input?.metadata && typeof input.metadata === "object" ? input.metadata : {};\n const detail = [pattern, text(metadata.command), text(metadata.description), text(metadata.path), text(metadata.url)].find(value => value);\n return (detail ? `${type}: ${detail}` : `opencode asks to use ${type}.`).slice(0, 2000);\n}\n\nfunction toolOutput(state) {\n if (!state || typeof state !== "object") return "";\n const output = state.output ?? state.metadata?.output ?? state.result ?? "";\n const value = typeof output === "string" ? output : JSON.stringify(output ?? "");\n return value.length > MAX_TOOL_OUTPUT ? value.slice(0, MAX_TOOL_OUTPUT) : value;\n}\n\nfunction blocksFor(message) {\n const blocks = [];\n for (const id of message.partOrder) {\n const part = message.parts.get(id);\n if (!part || typeof part !== "object") continue;\n if (part.type === "text" && typeof part.text === "string" && part.text.length) {\n blocks.push({ type: "text", text: part.text });\n } else if (part.type === "tool" && typeof part.callID === "string") {\n blocks.push({ type: "tool_use", id: part.callID, name: text(part.tool) || "tool", input: part.state?.input ?? {} });\n }\n }\n return blocks;\n}\n\n/** A tool\'s picture attachments as Anthropic-shaped image blocks, the form the\n * Hook\'s image route and the phone already read from Claude Code. Only inline\n * data URLs are carried; an image over the caps becomes a text marker. */\nfunction toolImages(state, budget) {\n const blocks = [];\n for (const attachment of Array.isArray(state?.attachments) ? state.attachments : []) {\n if (attachment?.type !== "file" || typeof attachment.url !== "string") continue;\n const match = IMAGE_DATA_URL.exec(attachment.url);\n if (!match) continue;\n const data = match[2];\n if (data.length > MAX_IMAGE_DATA || data.length > budget.remaining) {\n blocks.push({ type: "text", text: "[Image not included: too large to show on the phone]" });\n continue;\n }\n budget.remaining -= data.length;\n blocks.push({ type: "image", source: { type: "base64", media_type: match[1], data } });\n }\n return blocks;\n}\n\nfunction toolResults(message, budget) {\n const results = [];\n for (const id of message.partOrder) {\n const part = message.parts.get(id);\n if (!part || part.type !== "tool" || typeof part.callID !== "string") continue;\n const status = part.state?.status;\n if (status !== "completed" && status !== "error") continue;\n const output = toolOutput(part.state), images = toolImages(part.state, budget);\n const content = images.length ? [{ type: "text", text: output }, ...images] : output;\n results.push({ type: "tool_result", tool_use_id: part.callID, content, is_error: status === "error" });\n }\n return results;\n}\n\nfunction linesFor(session) {\n const messages = session.order\n .map(id => session.messages.get(id))\n .filter(Boolean)\n .sort((a, b) => (a.info?.time?.created ?? 0) - (b.info?.time?.created ?? 0) || String(a.info?.id).localeCompare(String(b.info?.id)));\n const lines = [];\n const budget = { remaining: MAX_SESSION_IMAGE_DATA };\n let seq = 0;\n const emit = (type, data, created) => {\n lines.push(JSON.stringify({ seq: seq++, time: new Date(created || Date.now()).toISOString(), type, data }));\n };\n for (const message of messages) {\n const info = message.info ?? {};\n if (info.role === "user") {\n const blocks = blocksFor(message);\n if (blocks.length) emit("user/message", { source: "user", message: { role: "user", content: blocks } }, info.time?.created);\n } else if (info.role === "assistant") {\n const complete = Boolean(info.time?.completed || info.finish);\n const blocks = blocksFor(message).filter(block => complete || block.type !== "text");\n const data = { stop_reason: STOP_REASONS[info.finish] || info.finish || "end_turn", message: { role: "assistant", content: blocks } };\n if (info.tokens && (typeof info.tokens.input === "number" || typeof info.tokens.output === "number")) {\n data.usage = { input_tokens: info.tokens.input ?? 0, output_tokens: info.tokens.output ?? 0 };\n }\n if (blocks.length) emit("assistant/message", data, info.time?.created);\n const results = toolResults(message, budget);\n if (results.length) emit("tool/results", { message: { role: "user", content: results } }, info.time?.updated ?? info.time?.created);\n }\n }\n return lines;\n}\n\n/** Which conversation this OpenCode process is showing, by PID: the Hook\n * reads it to bind a pane when Herdr reports no session for it. */\nconst pidBindingFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-pid-${process.pid}.json`);\nfunction writePidBinding(sessionID) {\n mkdirSync(path.dirname(pidBindingFile()), { recursive: true });\n writeJsonAtomic(pidBindingFile(), { session: sessionID, at: new Date().toISOString() });\n}\n\n/** What this OpenCode process is doing, by PID: "working", "idle" or\n * "blocked" (a permission waits for an answer). The Hook reads it for a pane\n * whose terminal does not watch its agents (tmux); Herdr has its own. */\nconst statusFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-status-${process.pid}.json`);\n\nexport const PhrenTranscriptPlugin = async input => {\n // The process\'s own API, bound to its in-process server (no port needed).\n const client = input?.client;\n const sessions = new Map();\n // Subagent sessions run inside the same process; the pane shows their parent.\n const children = new Set();\n let boundSession;\n // A reused PID must not inherit an old process\'s conversation or state.\n try { removeFile(pidBindingFile()); removeFile(statusFile()); } catch {}\n let recordedStatus;\n // Permission asks still open, by id: while any is, the process is blocked.\n const asking = new Set();\n // The session\'s last turn: when it went busy, and when it went idle after\n // that. Dispatch returns read these as the turn\'s start and Stop.\n let turn = {};\n const recordStatus = (status, sessionID) => {\n // A fan-out worker runs headless, in no pane.\n if (process.env.PHREN_FANOUT_JOB) return;\n const next = asking.size && status === "working" ? "blocked" : status;\n if (next === recordedStatus) return;\n try {\n const at = new Date().toISOString();\n if (sessionID && turn.session !== sessionID) turn = { session: sessionID };\n if (next !== "idle" && (recordedStatus === undefined || recordedStatus === "idle")) { turn.busyAt = at; delete turn.idleAt; }\n else if (next === "idle" && turn.busyAt) turn.idleAt = at;\n mkdirSync(path.dirname(statusFile()), { recursive: true });\n writeJsonAtomic(statusFile(), { status: next, ...(sessionID ? { session: sessionID } : {}), at,\n ...(turn.session === sessionID && turn.busyAt ? { busyAt: turn.busyAt } : {}), ...(turn.session === sessionID && turn.idleAt ? { idleAt: turn.idleAt } : {}) });\n recordedStatus = next;\n } catch {}\n };\n const permissionId = properties => text(properties?.permissionID) || text(properties?.requestID) || text(properties?.id);\n const timers = new Map();\n const written = new Map();\n const pendingApprovals = new Set();\n // Asks the permission.ask hook took (OpenCode before 1.18), and asks relayed\n // from their event, by id; `done` once the terminal answered one.\n const hookAsks = new Set();\n const relayed = new Map();\n\n /** OpenCode 1.18 never calls the permission.ask hook: its TUI draws the ask\n * from the `permission.asked` event. For an OpenCode started by hand the ask\n * goes to the phone through the same request file, and the phone\'s answer\n * is replied through this process\'s own API. Whichever answers first wins;\n * an answer in the terminal (`permission.replied`) withdraws the card. */\n const relayAsk = async ask => {\n const id = text(ask?.id), sessionID = text(ask?.sessionID);\n if (process.env.PHREN_FANOUT_JOB || !id || hookAsks.has(id) || relayed.has(id) || !OPENCODE_SESSION.test(sessionID)\n || typeof client?.postSessionIdPermissionsPermissionId !== "function" || servedByHook() || pendingApprovals.has(sessionID)) return;\n const shown = { type: text(ask.permission) || text(ask.type), pattern: Array.isArray(ask.patterns) ? ask.patterns : ask.pattern,\n metadata: ask.metadata, title: ask.title };\n const state = { done: false };\n relayed.set(id, state); pendingApprovals.add(sessionID);\n const { request, answer } = approvalPaths(sessionID);\n try {\n mkdirSync(approvalDirectory(), { recursive: true });\n removeFile(answer);\n const created = Date.now();\n writeJsonAtomic(request, { id, sessionID, type: shown.type || "action",\n title: text(shown.title) || `Allow ${shown.type || "action"}?`, message: permissionMessage(shown),\n createdAt: new Date(created).toISOString(), expiresAt: new Date(created + RELAYED_DEADLINE_MS).toISOString() });\n let decision;\n while (!state.done && Date.now() < created + RELAYED_DEADLINE_MS) {\n await sleep(APPROVAL_POLL_MS);\n try {\n const info = lstatSync(answer);\n if (!info.isFile() || info.size > 65_536) continue;\n const value = JSON.parse(readFileSync(answer, "utf8"));\n if (value && value.id === id && (value.decision === "approve" || value.decision === "deny")) { decision = value.decision; break; }\n } catch {}\n }\n if (decision && !state.done) {\n await client.postSessionIdPermissionsPermissionId({ path: { id: sessionID, permissionID: id },\n body: { response: decision === "approve" ? "once" : "reject" } });\n }\n } catch {} finally {\n removeFile(answer); removeFile(request);\n pendingApprovals.delete(sessionID); relayed.delete(id);\n }\n };\n\n const sessionState = sessionID => {\n let state = sessions.get(sessionID);\n if (!state) { state = { messages: new Map(), order: [], idle: false }; sessions.set(sessionID, state); }\n return state;\n };\n\n const messageState = (sessionID, messageID) => {\n const state = sessionState(sessionID);\n let message = state.messages.get(messageID);\n if (!message) { message = { info: { id: messageID }, parts: new Map(), partOrder: [] }; state.messages.set(messageID, message); state.order.push(messageID); }\n return message;\n };\n\n const flush = sessionID => {\n const state = sessions.get(sessionID);\n if (!state) return;\n const body = linesFor(state);\n const content = body.length ? body.join("\\n") + "\\n" : "";\n const directory = path.join(storeRoot(), ".runtime", "sessions");\n mkdirSync(directory, { recursive: true });\n const file = path.join(directory, `opencode-${sessionID}.events.jsonl`);\n const messages = state.order.map(id => state.messages.get(id));\n const latest = messages.at(-1), info = latest?.info;\n const user = messages.findLast(message => message.info?.role === "user");\n const preview = !state.idle && info?.role === "assistant" && !info.time?.completed && !info.finish\n ? blocksFor(latest).filter(block => block.type === "text").map(block => block.text).join("\\n").slice(0, 32_768) : "";\n if (preview && user?.info.time?.created) writeJsonAtomic(file + ".preview.json", {\n turnStartedAt: new Date(user.info.time.created).toISOString(), text: preview,\n });\n else removeFile(file + ".preview.json");\n if (written.get(sessionID) === content) return;\n const staging = `${file}.${process.pid}.tmp`;\n writeFileSync(staging, content, { mode: 0o600 });\n renameSync(staging, file);\n written.set(sessionID, content);\n };\n\n const schedule = sessionID => {\n if (!sessionID || timers.has(sessionID)) return;\n timers.set(sessionID, setTimeout(() => {\n timers.delete(sessionID);\n try { flush(sessionID); } catch {}\n }, FLUSH_MS));\n };\n\n const rememberInfo = (sessionID, info) => {\n if (!info || typeof info.id !== "string") return;\n const message = messageState(sessionID, info.id);\n message.info = { ...message.info, ...info };\n if (info.role === "user") sessionState(sessionID).idle = false;\n schedule(sessionID);\n };\n\n const rememberPart = (sessionID, messageID, part) => {\n if (!part || typeof part.id !== "string" || typeof messageID !== "string") return;\n const message = messageState(sessionID, messageID);\n if (!message.parts.has(part.id)) message.partOrder.push(part.id);\n message.parts.set(part.id, part);\n schedule(sessionID);\n };\n\n return {\n "chat.message": async (input, output) => {\n if (!OPENCODE_SESSION.test(text(input?.sessionID)) || !output?.message) return;\n if (!process.env.PHREN_FANOUT_JOB && !children.has(input.sessionID) && boundSession !== input.sessionID) {\n try { writePidBinding(input.sessionID); boundSession = input.sessionID; } catch {}\n }\n rememberInfo(input.sessionID, output.message);\n for (const part of output.parts ?? []) rememberPart(input.sessionID, output.message.id, part);\n if (!children.has(input.sessionID)) recordStatus("working", input.sessionID);\n },\n "permission.ask": async (input, output) => {\n // A fan-out worker runs headless in its own worktree with nobody watching\n // the phone\'s approval queue, so edits, commands and fetches inside that\n // worktree are granted here and anything else is refused outright rather\n // than waiting 50 seconds for an answer that never comes.\n if (process.env.PHREN_FANOUT_JOB) {\n if (fanoutAllowed(input)) { setStatus(output, "allow"); return; }\n // A worker the launcher drives through `opencode serve` relays the\n // ask to the phone and resumes on the owner\'s answer.\n if (process.env.PHREN_FANOUT_APPROVALS === "1") { setStatus(output, "ask"); return; }\n setStatus(output, "deny");\n // A denied permission aborts the turn; record what was refused so the\n // Hook can report the worker as blocked rather than finished.\n writeBlocked(input);\n return;\n }\n let request, answer, pendingSession, decision;\n // The ask blocks the process until it is answered: here from the\n // phone, or in the terminal (permission.replied below).\n const askId = text(input?.id);\n if (askId) { hookAsks.add(askId); asking.add(askId); recordStatus("blocked", text(input?.sessionID)); }\n try {\n const sessionID = text(input?.sessionID), id = text(input?.id);\n if (!OPENCODE_SESSION.test(sessionID) || !id || servedByHook()) { setStatus(output, "ask"); return; }\n // A second request for this session belongs in the terminal until\n // the existing phone request has finished.\n if (pendingApprovals.has(sessionID)) { setStatus(output, "ask"); return; }\n pendingApprovals.add(sessionID);\n pendingSession = sessionID;\n const paths = approvalPaths(sessionID);\n request = paths.request; answer = paths.answer;\n mkdirSync(approvalDirectory(), { recursive: true });\n removeFile(answer);\n const created = Date.now();\n writeJsonAtomic(request, { id, sessionID, type: text(input.type) || "action",\n title: text(input.title) || `Allow ${text(input.type) || "action"}?`, message: permissionMessage(input),\n createdAt: new Date(created).toISOString(), expiresAt: new Date(created + APPROVAL_DEADLINE_MS).toISOString() });\n const deadline = created + APPROVAL_DEADLINE_MS;\n while (Date.now() < deadline) {\n await sleep(APPROVAL_POLL_MS);\n try {\n const info = lstatSync(answer);\n if (!info.isFile() || info.size > 65_536) continue;\n const value = JSON.parse(readFileSync(answer, "utf8"));\n if (value && value.id === id) { decision = value.decision; break; }\n } catch {}\n }\n setStatus(output, decision === "approve" ? "allow" : decision === "deny" ? "deny" : "ask");\n } catch {\n setStatus(output, "ask");\n } finally {\n if (answer) removeFile(answer);\n if (request) removeFile(request);\n if (pendingSession) pendingApprovals.delete(pendingSession);\n // Answered from the phone: back to work. Otherwise the terminal asks.\n if (askId && (decision === "approve" || decision === "deny")) { asking.delete(askId); recordStatus("working", pendingSession); }\n if (askId) hookAsks.delete(askId);\n }\n },\n event: async ({ event }) => {\n const properties = event?.properties ?? {};\n if ((event?.type === "session.created" || event?.type === "session.updated") && properties.info?.parentID\n && OPENCODE_SESSION.test(text(properties.info.id))) children.add(properties.info.id);\n const sessionID = typeof properties.sessionID === "string" ? properties.sessionID : properties.info?.sessionID ?? properties.part?.sessionID;\n // Permission events name the ask (permission.updated / permission.asked)\n // and its answer, which may come from the terminal.\n if (event?.type === "permission.updated" || event?.type === "permission.asked") {\n const id = permissionId(properties);\n if (id) { asking.add(id); recordStatus("blocked", text(sessionID)); }\n if (event.type === "permission.asked") void relayAsk(properties).catch(() => {});\n } else if (event?.type === "permission.replied") {\n const id = permissionId(properties);\n if (id) asking.delete(id); else asking.clear();\n const relay = id && relayed.get(id);\n if (relay) relay.done = true;\n recordStatus("working", text(sessionID));\n }\n if (!OPENCODE_SESSION.test(text(sessionID))) return;\n if (event.type === "message.updated") rememberInfo(sessionID, properties.info);\n else if (event.type === "message.part.updated") rememberPart(sessionID, properties.part?.messageID, properties.part);\n else if (event.type === "message.part.delta" && properties.field === "text" && typeof properties.delta === "string") {\n const message = messageState(sessionID, properties.messageID);\n const part = message.parts.get(properties.partID);\n if (part?.type === "text") rememberPart(sessionID, properties.messageID, { ...part, text: text(part.text) + properties.delta });\n }\n else if (event.type === "message.removed") {\n const state = sessions.get(sessionID);\n if (state && typeof properties.messageID === "string") {\n state.messages.delete(properties.messageID);\n state.order = state.order.filter(id => id !== properties.messageID);\n schedule(sessionID);\n }\n } else if (event.type === "session.idle" || event.type === "session.error") {\n sessionState(sessionID).idle = true;\n flush(sessionID);\n if (!children.has(sessionID)) { asking.clear(); recordStatus("idle", sessionID); }\n } else if (event.type === "session.status") {\n if (properties.status?.type === "busy") sessionState(sessionID).idle = false;\n // A subagent\'s session runs inside its parent\'s turn.\n if (!children.has(sessionID) && ["busy", "retry", "idle"].includes(properties.status?.type)) {\n if (properties.status.type === "idle") asking.clear();\n recordStatus(properties.status.type === "idle" ? "idle" : "working", sessionID);\n }\n }\n },\n };\n};\n';
40737
+ if (true) return '// Installed by Phren Hook and replaced on every update. Copy it under another name to customize.\nimport { execFileSync } from "node:child_process";\nimport { lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";\nimport { homedir } from "node:os";\nimport path from "node:path";\n\nconst PHREN_STORE = "__PHREN_STORE__";\nconst FLUSH_MS = 250;\nconst MAX_TOOL_OUTPUT = 200_000;\n// OpenCode\'s read tool returns a picture as an inline data URL on the tool\n// part (`state.attachments`). The Hook serves images up to 8 MiB; the session\n// budget bounds what every flush rewrites.\nconst MAX_IMAGE_DATA = 4_000_000;\nconst MAX_SESSION_IMAGE_DATA = 24_000_000;\nconst IMAGE_DATA_URL = /^data:(image\\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;\nconst STOP_REASONS = { stop: "end_turn", "tool-calls": "tool_use", length: "max_tokens" };\nconst OPENCODE_SESSION = /^ses_[0-9A-Za-z]{1,64}$/;\nconst APPROVAL_POLL_MS = 200;\nconst APPROVAL_DEADLINE_MS = 50_000;\n// An ask relayed from its event blocks nothing: the TUI keeps its own prompt,\n// so the phone\'s card can wait as long as the ask does.\nconst RELAYED_DEADLINE_MS = 30 * 60_000;\n\nfunction storeRoot() {\n if (PHREN_STORE && !PHREN_STORE.startsWith("__")) return PHREN_STORE;\n const configured = process.env.PHREN_PATH?.trim();\n if (!configured) return path.join(homedir(), ".phren");\n const expanded = configured === "~" ? homedir() : configured.startsWith("~/") ? path.join(homedir(), configured.slice(2)) : configured;\n return path.resolve(expanded);\n}\n\nfunction text(value) {\n return typeof value === "string" ? value : "";\n}\n\nfunction approvalDirectory() {\n return path.join(storeRoot(), ".runtime", "approvals");\n}\n\nfunction fanoutDirectory() {\n const configured = process.env.PHREN_FANOUT_DIR?.trim();\n if (configured) return path.resolve(configured);\n return path.join(storeRoot(), ".runtime", "agent-fanouts", text(process.env.PHREN_FANOUT_JOB));\n}\n\nfunction fanoutPatterns(input) {\n const value = input?.pattern;\n if (Array.isArray(value)) return value.filter(entry => typeof entry === "string" && entry);\n return typeof value === "string" && value ? [value] : [];\n}\n\n/** The worktree\'s grandparent is the scratch root the fan-out launcher owns:\n * external reads and writes are allowed only inside it. */\nfunction underScratchRoot(value) {\n const scratch = path.dirname(path.dirname(path.resolve(process.cwd())));\n if (scratch === path.parse(scratch).root) return false;\n const resolved = path.resolve(scratch, value);\n return resolved === scratch || resolved.startsWith(scratch + path.sep);\n}\n\nfunction under(parent, value) {\n if (!parent || parent === path.parse(parent).root) return false;\n const root = path.resolve(parent), resolved = path.resolve(root, value);\n return resolved === root || resolved.startsWith(root + path.sep);\n}\n\n/** Beyond the scratch root, a worker legitimately reads its own machine: the\n * node_modules its worktree links into the main checkout, the store it was\n * briefed from, the toolchains a build shells out to, and the temporary\n * directories those builds write. Everything outside this set is refused. */\nfunction fanoutReadable(value) {\n if (underScratchRoot(value)) return true;\n const home = process.env.HOME || "";\n const roots = [home, storeRoot(), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders",\n "/Applications/Xcode.app", "/Library/Developer"];\n return roots.some(root => under(root, value));\n}\n\n/** A headless fan-out worker may edit, run commands and fetch, and continue\n * when OpenCode\'s own loop detector asks (the launcher\'s watchdog stops a real\n * loop and says why, which is a clearer failure than a refused permission).\n * Anything else is refused outright. */\nfunction fanoutAllowed(input) {\n const kind = text(input?.type);\n if (kind === "edit" || kind === "bash" || kind === "webfetch" || kind === "doom_loop") return true;\n if (kind !== "external_directory") return false;\n const patterns = fanoutPatterns(input);\n return patterns.length > 0 && patterns.every(fanoutReadable);\n}\n\nfunction writeBlocked(input) {\n try {\n const directory = fanoutDirectory();\n mkdirSync(directory, { recursive: true });\n writeJsonAtomic(path.join(directory, "blocked.json"), {\n type: text(input?.type) || "action",\n pattern: fanoutPatterns(input).join(", "),\n message: permissionMessage(input),\n at: new Date().toISOString(),\n });\n } catch {}\n}\n\nfunction approvalPaths(sessionID) {\n const base = path.join(approvalDirectory(), `opencode-${sessionID}`);\n return { request: `${base}.request.json`, answer: `${base}.answer.json` };\n}\n\nfunction writeJsonAtomic(file, value) {\n const staging = `${file}.${process.pid}.tmp`;\n writeFileSync(staging, JSON.stringify(value), { mode: 0o600 });\n renameSync(staging, file);\n}\n\nfunction removeFile(file) {\n try { unlinkSync(file); } catch {}\n}\n\nfunction sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/** Started by Phren Hook with a port of its own (`opencode --port N`, with\n * PHREN_OPENCODE_PORT=N and a server password in its environment): the Hook\n * lists and answers this process\'s permission asks over its HTTP API, so no\n * request file is written for them. The port must be on this process\'s own\n * command line, so an OpenCode started by hand in the same shell keeps the\n * file path. Plugins run in a worker whose `process.argv` is the worker\'s,\n * so the command line comes from `ps`, once. */\nlet served;\nfunction servedByHook() {\n if (served !== undefined) return served;\n const port = text(process.env.PHREN_OPENCODE_PORT);\n served = false;\n if (!/^\\d{1,5}$/.test(port) || !text(process.env.OPENCODE_SERVER_PASSWORD)) return served;\n try {\n const command = execFileSync("ps", ["-ww", "-o", "command=", "-p", String(process.pid)], { encoding: "utf8", timeout: 2_000 });\n served = new RegExp(`(?:^|\\\\s)--port(?:\\\\s+|=)${port}(?:\\\\s|$)`).test(command.trim());\n } catch {}\n return served;\n}\n\nfunction setStatus(output, status) {\n if (output && typeof output === "object") output.status = status;\n}\n\nfunction permissionMessage(input) {\n const type = text(input?.type) || "action";\n const pattern = Array.isArray(input?.pattern)\n ? input.pattern.filter(value => typeof value === "string").join(", ")\n : text(input?.pattern);\n const metadata = input?.metadata && typeof input.metadata === "object" ? input.metadata : {};\n const detail = [pattern, text(metadata.command), text(metadata.description), text(metadata.path), text(metadata.url)].find(value => value);\n return (detail ? `${type}: ${detail}` : `opencode asks to use ${type}.`).slice(0, 2000);\n}\n\nfunction toolOutput(state) {\n if (!state || typeof state !== "object") return "";\n const output = state.output ?? state.metadata?.output ?? state.result ?? "";\n const value = typeof output === "string" ? output : JSON.stringify(output ?? "");\n return value.length > MAX_TOOL_OUTPUT ? value.slice(0, MAX_TOOL_OUTPUT) : value;\n}\n\nfunction blocksFor(message) {\n const blocks = [];\n for (const id of message.partOrder) {\n const part = message.parts.get(id);\n if (!part || typeof part !== "object") continue;\n if (part.type === "text" && typeof part.text === "string" && part.text.length) {\n blocks.push({ type: "text", text: part.text });\n } else if (part.type === "tool" && typeof part.callID === "string") {\n blocks.push({ type: "tool_use", id: part.callID, name: text(part.tool) || "tool", input: part.state?.input ?? {} });\n }\n }\n return blocks;\n}\n\n/** A tool\'s picture attachments as Anthropic-shaped image blocks, the form the\n * Hook\'s image route and the phone already read from Claude Code. Only inline\n * data URLs are carried; an image over the caps becomes a text marker. */\nfunction toolImages(state, budget) {\n const blocks = [];\n for (const attachment of Array.isArray(state?.attachments) ? state.attachments : []) {\n if (attachment?.type !== "file" || typeof attachment.url !== "string") continue;\n const match = IMAGE_DATA_URL.exec(attachment.url);\n if (!match) continue;\n const data = match[2];\n if (data.length > MAX_IMAGE_DATA || data.length > budget.remaining) {\n blocks.push({ type: "text", text: "[Image not included: too large to show on the phone]" });\n continue;\n }\n budget.remaining -= data.length;\n blocks.push({ type: "image", source: { type: "base64", media_type: match[1], data } });\n }\n return blocks;\n}\n\nfunction toolResults(message, budget) {\n const results = [];\n for (const id of message.partOrder) {\n const part = message.parts.get(id);\n if (!part || part.type !== "tool" || typeof part.callID !== "string") continue;\n const status = part.state?.status;\n if (status !== "completed" && status !== "error") continue;\n const output = toolOutput(part.state), images = toolImages(part.state, budget);\n const content = images.length ? [{ type: "text", text: output }, ...images] : output;\n results.push({ type: "tool_result", tool_use_id: part.callID, content, is_error: status === "error" });\n }\n return results;\n}\n\nfunction linesFor(session) {\n const messages = session.order\n .map(id => session.messages.get(id))\n .filter(Boolean)\n .sort((a, b) => (a.info?.time?.created ?? 0) - (b.info?.time?.created ?? 0) || String(a.info?.id).localeCompare(String(b.info?.id)));\n const lines = [];\n const budget = { remaining: MAX_SESSION_IMAGE_DATA };\n let seq = 0;\n const emit = (type, data, created) => {\n lines.push(JSON.stringify({ seq: seq++, time: new Date(created || Date.now()).toISOString(), type, data }));\n };\n for (const message of messages) {\n const info = message.info ?? {};\n if (info.role === "user") {\n const blocks = blocksFor(message);\n if (blocks.length) emit("user/message", { source: "user", message: { role: "user", content: blocks } }, info.time?.created);\n } else if (info.role === "assistant") {\n const complete = Boolean(info.time?.completed || info.finish);\n const blocks = blocksFor(message).filter(block => complete || block.type !== "text");\n const data = { stop_reason: STOP_REASONS[info.finish] || info.finish || "end_turn", message: { role: "assistant", content: blocks } };\n if (info.tokens && (typeof info.tokens.input === "number" || typeof info.tokens.output === "number")) {\n data.usage = { input_tokens: info.tokens.input ?? 0, output_tokens: info.tokens.output ?? 0 };\n }\n if (blocks.length) emit("assistant/message", data, info.time?.created);\n const results = toolResults(message, budget);\n if (results.length) emit("tool/results", { message: { role: "user", content: results } }, info.time?.updated ?? info.time?.created);\n }\n }\n return lines;\n}\n\n/** Which conversation this OpenCode process is showing, by PID: the Hook\n * reads it to bind a pane when Herdr reports no session for it. */\nconst pidBindingFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-pid-${process.pid}.json`);\nfunction writePidBinding(sessionID) {\n mkdirSync(path.dirname(pidBindingFile()), { recursive: true });\n writeJsonAtomic(pidBindingFile(), { session: sessionID, at: new Date().toISOString() });\n}\n\n/** What this OpenCode process is doing, by PID: "working", "idle" or\n * "blocked" (a permission waits for an answer). The Hook reads it for a pane\n * whose terminal does not watch its agents (tmux); Herdr has its own. */\nconst statusFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-status-${process.pid}.json`);\n\nexport const PhrenTranscriptPlugin = async input => {\n // The process\'s own API, bound to its in-process server (no port needed).\n const client = input?.client;\n const sessions = new Map();\n // Subagent sessions run inside the same process; the pane shows their parent.\n const children = new Set();\n let boundSession;\n // A reused PID must not inherit an old process\'s conversation or state.\n try { removeFile(pidBindingFile()); removeFile(statusFile()); } catch {}\n let recordedStatus;\n // Permission asks still open, by id: while any is, the process is blocked.\n const asking = new Set();\n // The session\'s last turn: when it went busy, and when it went idle after\n // that. Dispatch returns read these as the turn\'s start and Stop.\n let turn = {};\n const recordStatus = (status, sessionID) => {\n // A fan-out worker runs headless, in no pane.\n if (process.env.PHREN_FANOUT_JOB) return;\n const next = asking.size && status === "working" ? "blocked" : status;\n if (next === recordedStatus) return;\n try {\n const at = new Date().toISOString();\n if (sessionID && turn.session !== sessionID) turn = { session: sessionID };\n if (next !== "idle" && (recordedStatus === undefined || recordedStatus === "idle")) { turn.busyAt = at; delete turn.idleAt; }\n else if (next === "idle" && turn.busyAt) turn.idleAt = at;\n mkdirSync(path.dirname(statusFile()), { recursive: true });\n writeJsonAtomic(statusFile(), { status: next, ...(sessionID ? { session: sessionID } : {}), at,\n ...(turn.session === sessionID && turn.busyAt ? { busyAt: turn.busyAt } : {}), ...(turn.session === sessionID && turn.idleAt ? { idleAt: turn.idleAt } : {}) });\n recordedStatus = next;\n } catch {}\n };\n const permissionId = properties => text(properties?.permissionID) || text(properties?.requestID) || text(properties?.id);\n const timers = new Map();\n const written = new Map();\n const pendingApprovals = new Set();\n // Asks the permission.ask hook took (OpenCode before 1.18), and asks relayed\n // from their event, by id; `done` once the terminal answered one.\n const hookAsks = new Set();\n const relayed = new Map();\n\n /** OpenCode 1.18 never calls the permission.ask hook: its TUI draws the ask\n * from the `permission.asked` event. For an OpenCode started by hand the ask\n * goes to the phone through the same request file, and the phone\'s answer\n * is replied through this process\'s own API. Whichever answers first wins;\n * an answer in the terminal (`permission.replied`) withdraws the card. */\n const relayAsk = async ask => {\n const id = text(ask?.id), sessionID = text(ask?.sessionID);\n if (process.env.PHREN_FANOUT_JOB || !id || hookAsks.has(id) || relayed.has(id) || !OPENCODE_SESSION.test(sessionID)\n || typeof client?.postSessionIdPermissionsPermissionId !== "function" || servedByHook() || pendingApprovals.has(sessionID)) return;\n const shown = { type: text(ask.permission) || text(ask.type), pattern: Array.isArray(ask.patterns) ? ask.patterns : ask.pattern,\n metadata: ask.metadata, title: ask.title };\n const state = { done: false };\n relayed.set(id, state); pendingApprovals.add(sessionID);\n const { request, answer } = approvalPaths(sessionID);\n try {\n mkdirSync(approvalDirectory(), { recursive: true });\n removeFile(answer);\n const created = Date.now();\n writeJsonAtomic(request, { id, sessionID, type: shown.type || "action",\n title: text(shown.title) || `Allow ${shown.type || "action"}?`, message: permissionMessage(shown),\n createdAt: new Date(created).toISOString(), expiresAt: new Date(created + RELAYED_DEADLINE_MS).toISOString() });\n let decision;\n while (!state.done && Date.now() < created + RELAYED_DEADLINE_MS) {\n await sleep(APPROVAL_POLL_MS);\n try {\n const info = lstatSync(answer);\n if (!info.isFile() || info.size > 65_536) continue;\n const value = JSON.parse(readFileSync(answer, "utf8"));\n if (value && value.id === id && (value.decision === "approve" || value.decision === "deny" || value.decision === "always")) { decision = value.decision; break; }\n } catch {}\n }\n if (decision && !state.done) {\n await client.postSessionIdPermissionsPermissionId({ path: { id: sessionID, permissionID: id },\n body: { response: decision === "approve" ? "once" : decision === "always" ? "always" : "reject" } });\n }\n } catch {} finally {\n removeFile(answer); removeFile(request);\n pendingApprovals.delete(sessionID); relayed.delete(id);\n }\n };\n\n const sessionState = sessionID => {\n let state = sessions.get(sessionID);\n if (!state) { state = { messages: new Map(), order: [], idle: false }; sessions.set(sessionID, state); }\n return state;\n };\n\n const messageState = (sessionID, messageID) => {\n const state = sessionState(sessionID);\n let message = state.messages.get(messageID);\n if (!message) { message = { info: { id: messageID }, parts: new Map(), partOrder: [] }; state.messages.set(messageID, message); state.order.push(messageID); }\n return message;\n };\n\n const flush = sessionID => {\n const state = sessions.get(sessionID);\n if (!state) return;\n const body = linesFor(state);\n const content = body.length ? body.join("\\n") + "\\n" : "";\n const directory = path.join(storeRoot(), ".runtime", "sessions");\n mkdirSync(directory, { recursive: true });\n const file = path.join(directory, `opencode-${sessionID}.events.jsonl`);\n const messages = state.order.map(id => state.messages.get(id));\n const latest = messages.at(-1), info = latest?.info;\n const user = messages.findLast(message => message.info?.role === "user");\n const preview = !state.idle && info?.role === "assistant" && !info.time?.completed && !info.finish\n ? blocksFor(latest).filter(block => block.type === "text").map(block => block.text).join("\\n").slice(0, 32_768) : "";\n if (preview && user?.info.time?.created) writeJsonAtomic(file + ".preview.json", {\n turnStartedAt: new Date(user.info.time.created).toISOString(), text: preview,\n });\n else removeFile(file + ".preview.json");\n if (written.get(sessionID) === content) return;\n const staging = `${file}.${process.pid}.tmp`;\n writeFileSync(staging, content, { mode: 0o600 });\n renameSync(staging, file);\n written.set(sessionID, content);\n };\n\n const schedule = sessionID => {\n if (!sessionID || timers.has(sessionID)) return;\n timers.set(sessionID, setTimeout(() => {\n timers.delete(sessionID);\n try { flush(sessionID); } catch {}\n }, FLUSH_MS));\n };\n\n const rememberInfo = (sessionID, info) => {\n if (!info || typeof info.id !== "string") return;\n const message = messageState(sessionID, info.id);\n message.info = { ...message.info, ...info };\n if (info.role === "user") sessionState(sessionID).idle = false;\n schedule(sessionID);\n };\n\n const rememberPart = (sessionID, messageID, part) => {\n if (!part || typeof part.id !== "string" || typeof messageID !== "string") return;\n const message = messageState(sessionID, messageID);\n if (!message.parts.has(part.id)) message.partOrder.push(part.id);\n message.parts.set(part.id, part);\n schedule(sessionID);\n };\n\n return {\n "chat.message": async (input, output) => {\n if (!OPENCODE_SESSION.test(text(input?.sessionID)) || !output?.message) return;\n if (!process.env.PHREN_FANOUT_JOB && !children.has(input.sessionID) && boundSession !== input.sessionID) {\n try { writePidBinding(input.sessionID); boundSession = input.sessionID; } catch {}\n }\n rememberInfo(input.sessionID, output.message);\n for (const part of output.parts ?? []) rememberPart(input.sessionID, output.message.id, part);\n if (!children.has(input.sessionID)) recordStatus("working", input.sessionID);\n },\n "permission.ask": async (input, output) => {\n // A fan-out worker runs headless in its own worktree with nobody watching\n // the phone\'s approval queue, so edits, commands and fetches inside that\n // worktree are granted here and anything else is refused outright rather\n // than waiting 50 seconds for an answer that never comes.\n if (process.env.PHREN_FANOUT_JOB) {\n if (fanoutAllowed(input)) { setStatus(output, "allow"); return; }\n // A worker the launcher drives through `opencode serve` relays the\n // ask to the phone and resumes on the owner\'s answer.\n if (process.env.PHREN_FANOUT_APPROVALS === "1") { setStatus(output, "ask"); return; }\n setStatus(output, "deny");\n // A denied permission aborts the turn; record what was refused so the\n // Hook can report the worker as blocked rather than finished.\n writeBlocked(input);\n return;\n }\n let request, answer, pendingSession, decision;\n // The ask blocks the process until it is answered: here from the\n // phone, or in the terminal (permission.replied below).\n const askId = text(input?.id);\n if (askId) { hookAsks.add(askId); asking.add(askId); recordStatus("blocked", text(input?.sessionID)); }\n try {\n const sessionID = text(input?.sessionID), id = text(input?.id);\n if (!OPENCODE_SESSION.test(sessionID) || !id || servedByHook()) { setStatus(output, "ask"); return; }\n // A second request for this session belongs in the terminal until\n // the existing phone request has finished.\n if (pendingApprovals.has(sessionID)) { setStatus(output, "ask"); return; }\n pendingApprovals.add(sessionID);\n pendingSession = sessionID;\n const paths = approvalPaths(sessionID);\n request = paths.request; answer = paths.answer;\n mkdirSync(approvalDirectory(), { recursive: true });\n removeFile(answer);\n const created = Date.now();\n writeJsonAtomic(request, { id, sessionID, type: text(input.type) || "action",\n title: text(input.title) || `Allow ${text(input.type) || "action"}?`, message: permissionMessage(input),\n createdAt: new Date(created).toISOString(), expiresAt: new Date(created + APPROVAL_DEADLINE_MS).toISOString() });\n const deadline = created + APPROVAL_DEADLINE_MS;\n while (Date.now() < deadline) {\n await sleep(APPROVAL_POLL_MS);\n try {\n const info = lstatSync(answer);\n if (!info.isFile() || info.size > 65_536) continue;\n const value = JSON.parse(readFileSync(answer, "utf8"));\n if (value && value.id === id) { decision = value.decision; break; }\n } catch {}\n }\n setStatus(output, decision === "approve" || decision === "always" ? "allow" : decision === "deny" ? "deny" : "ask");\n } catch {\n setStatus(output, "ask");\n } finally {\n if (answer) removeFile(answer);\n if (request) removeFile(request);\n if (pendingSession) pendingApprovals.delete(pendingSession);\n // Answered from the phone: back to work. Otherwise the terminal asks.\n if (askId && (decision === "approve" || decision === "deny" || decision === "always")) { asking.delete(askId); recordStatus("working", pendingSession); }\n if (askId) hookAsks.delete(askId);\n }\n },\n event: async ({ event }) => {\n const properties = event?.properties ?? {};\n if ((event?.type === "session.created" || event?.type === "session.updated") && properties.info?.parentID\n && OPENCODE_SESSION.test(text(properties.info.id))) children.add(properties.info.id);\n const sessionID = typeof properties.sessionID === "string" ? properties.sessionID : properties.info?.sessionID ?? properties.part?.sessionID;\n // Permission events name the ask (permission.updated / permission.asked)\n // and its answer, which may come from the terminal.\n if (event?.type === "permission.updated" || event?.type === "permission.asked") {\n const id = permissionId(properties);\n if (id) { asking.add(id); recordStatus("blocked", text(sessionID)); }\n if (event.type === "permission.asked") void relayAsk(properties).catch(() => {});\n } else if (event?.type === "permission.replied") {\n const id = permissionId(properties);\n if (id) asking.delete(id); else asking.clear();\n const relay = id && relayed.get(id);\n if (relay) relay.done = true;\n recordStatus("working", text(sessionID));\n }\n if (!OPENCODE_SESSION.test(text(sessionID))) return;\n if (event.type === "message.updated") rememberInfo(sessionID, properties.info);\n else if (event.type === "message.part.updated") rememberPart(sessionID, properties.part?.messageID, properties.part);\n else if (event.type === "message.part.delta" && properties.field === "text" && typeof properties.delta === "string") {\n const message = messageState(sessionID, properties.messageID);\n const part = message.parts.get(properties.partID);\n if (part?.type === "text") rememberPart(sessionID, properties.messageID, { ...part, text: text(part.text) + properties.delta });\n }\n else if (event.type === "message.removed") {\n const state = sessions.get(sessionID);\n if (state && typeof properties.messageID === "string") {\n state.messages.delete(properties.messageID);\n state.order = state.order.filter(id => id !== properties.messageID);\n schedule(sessionID);\n }\n } else if (event.type === "session.idle" || event.type === "session.error") {\n sessionState(sessionID).idle = true;\n flush(sessionID);\n if (!children.has(sessionID)) { asking.clear(); recordStatus("idle", sessionID); }\n } else if (event.type === "session.status") {\n if (properties.status?.type === "busy") sessionState(sessionID).idle = false;\n // A subagent\'s session runs inside its parent\'s turn.\n if (!children.has(sessionID) && ["busy", "retry", "idle"].includes(properties.status?.type)) {\n if (properties.status.type === "idle") asking.clear();\n recordStatus(properties.status.type === "idle" ? "idle" : "working", sessionID);\n }\n }\n },\n };\n};\n';
40672
40738
  const here = path50.dirname(fileURLToPath4(import.meta.url));
40673
40739
  for (const candidate of [
40674
40740
  path50.join(here, "..", "..", "plugins", "opencode", "phren-transcript.js"),
@@ -40910,10 +40976,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
40910
40976
  for (const value2 of values.slice(0, 128)) {
40911
40977
  if (state.count >= 128) break;
40912
40978
  const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
40913
- const path112 = publicLabel(raw.path);
40979
+ const path114 = publicLabel(raw.path);
40914
40980
  const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
40915
40981
  const routed = destination(raw, fallbackComputer, fallbackTarget);
40916
- if (!id2.success || !source.success || !path112 || !callId || !routed) continue;
40982
+ if (!id2.success || !source.success || !path114 || !callId || !routed) continue;
40917
40983
  const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
40918
40984
  const nestedSession = sessionId.safeParse(raw.session);
40919
40985
  const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
@@ -40926,7 +40992,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
40926
40992
  projected.push({
40927
40993
  id: publicID(parent, routed.computer.id, receipt.id, descendant),
40928
40994
  provider: source.data,
40929
- path: path112,
40995
+ path: path114,
40930
40996
  callId,
40931
40997
  state: raw.failed === true ? "failed" : childState,
40932
40998
  ...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
@@ -41970,7 +42036,7 @@ init_shared();
41970
42036
 
41971
42037
  // src/bridge/schedule-watch.ts
41972
42038
  init_herdr();
41973
- import { open as open12, stat as stat15 } from "node:fs/promises";
42039
+ import { open as open13, stat as stat15 } from "node:fs/promises";
41974
42040
 
41975
42041
  // src/bridge/pane-text.ts
41976
42042
  init_herdr();
@@ -42150,7 +42216,7 @@ async function readFinalTurn(source, sessionId2) {
42150
42216
  if (!sessionId2) return void 0;
42151
42217
  const file3 = await transcriptPath(source, sessionId2).catch(() => void 0);
42152
42218
  if (!file3) return void 0;
42153
- const handle = await open12(file3, "r").catch(() => void 0);
42219
+ const handle = await open13(file3, "r").catch(() => void 0);
42154
42220
  if (!handle) return void 0;
42155
42221
  try {
42156
42222
  const { size } = await handle.stat();
@@ -42637,8 +42703,8 @@ var Scheduler = class {
42637
42703
  const resume = this.launch.resume;
42638
42704
  if (this.recovered || !resume) return;
42639
42705
  this.recovered = true;
42640
- const open24 = (await readScheduleRuns(this.runsFile)).filter((run2) => runningStatuses.has(run2.status) && !this.own.has(run2.id));
42641
- for (const run2 of open24) {
42706
+ const open25 = (await readScheduleRuns(this.runsFile)).filter((run2) => runningStatuses.has(run2.status) && !this.own.has(run2.id));
42707
+ for (const run2 of open25) {
42642
42708
  this.own.add(run2.id);
42643
42709
  let schedule;
42644
42710
  try {
@@ -43927,13 +43993,13 @@ async function setIntegrator(input2) {
43927
43993
  init_transcripts();
43928
43994
  init_terminal();
43929
43995
  import { createHash as createHash16 } from "node:crypto";
43930
- import { open as open13 } from "node:fs/promises";
43996
+ import { open as open14 } from "node:fs/promises";
43931
43997
  function stallThreshold() {
43932
43998
  const value2 = Number(process.env.PHREN_STALL_MS ?? 3e5);
43933
43999
  return Number.isFinite(value2) && value2 >= 0 ? value2 : 3e5;
43934
44000
  }
43935
44001
  async function transcriptStamp(target) {
43936
- const file3 = await open13(await targetTranscriptPath(target), "r");
44002
+ const file3 = await open14(await targetTranscriptPath(target), "r");
43937
44003
  try {
43938
44004
  const info = await file3.stat(), start = Math.max(0, info.size - 8192), buffer = Buffer.alloc(info.size - start);
43939
44005
  await file3.read(buffer, 0, buffer.length, start);
@@ -44199,7 +44265,9 @@ async function listLiveSessions(options = {}) {
44199
44265
 
44200
44266
  // src/bridge/dispatch-returns.ts
44201
44267
  init_protocol();
44268
+ init_session_activity();
44202
44269
  init_terminal();
44270
+ init_transcripts();
44203
44271
  init_turn_records();
44204
44272
  init_turn_records();
44205
44273
  var REPLY_LIMIT = TURN_REPLY_LIMIT;
@@ -44222,6 +44290,7 @@ var defaultReaders = {
44222
44290
  identity: (server, pane) => paneIdentity(server, pane),
44223
44291
  finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(void 0),
44224
44292
  turn: paneTurn,
44293
+ children: (source, session) => childAgentTree(source, session).then(runningChildAgents).then((children) => children.length),
44225
44294
  stall: (target, pane) => sessionStalls.observe(target, pane),
44226
44295
  lost: (server, pane, session) => codexServers.lostTurn(server, pane, session)
44227
44296
  };
@@ -44244,22 +44313,26 @@ async function fromTurn(record2, session, status, source, readers) {
44244
44313
  if (phase.phase === "unprompted") return { state: "idle", ...base, completed: false };
44245
44314
  const idle = status === "idle" || status === "done";
44246
44315
  if (phase.phase === "working" && !idle) return { state: "working", ...base };
44247
- const final = await readers.finalTurn(source, session).catch(() => void 0);
44316
+ const now = (readers.now ?? Date.now)();
44317
+ const [final, children] = await Promise.all([
44318
+ readers.finalTurn(source, session).catch(() => void 0),
44319
+ readers.children ? readers.children(source, session).catch(() => 0) : Promise.resolve(0)
44320
+ ]);
44248
44321
  if (phase.phase === "working") {
44249
44322
  if (final?.interrupted) return { state: "done", ...base, completed: true, interrupted: true };
44250
- if (!final?.completed || final.background) return { state: "working", ...base };
44323
+ if (!final?.completed) return { state: "working", ...base };
44324
+ const live2 = liveWork(record2, final, children, now);
44325
+ if (live2) return { state: "working", ...base, background: live2 };
44251
44326
  return { state: "done", ...base, completed: true, ...final.error ? { error: final.error } : {}, ...replyFields(final.lastAssistant) };
44252
44327
  }
44253
- const background = phase.background !== void 0 ? backgroundLeft(phase.background, phase.at, final?.finishedTasks) || void 0 : final?.completed ? final.background : void 0;
44254
- const now = (readers.now ?? Date.now)();
44255
- if (background && now - Date.parse(phase.at) < BACKGROUND_WAIT_MS) return { state: "working", ...base, background };
44328
+ const live = liveWork(record2, final, children, now);
44329
+ if (live) return { state: "working", ...base, background: live };
44256
44330
  return {
44257
44331
  state: "done",
44258
44332
  ...base,
44259
44333
  completed: true,
44260
44334
  endedAt: phase.at,
44261
44335
  stopSeq: record2.stop?.seq,
44262
- ...background ? { background } : {},
44263
44336
  ...final?.completed && final.error ? { error: final.error } : {},
44264
44337
  ...phase.reply ? replyFields(phase.reply, phase.truncated) : replyFields(final?.lastAssistant)
44265
44338
  };
@@ -44308,8 +44381,10 @@ async function workerStates2(input2, readers = defaultReaders) {
44308
44381
  return { state, ...session ? { session } : {}, ...full2.success && state === "working" ? await readers.stall?.(full2.data, pane) : {} };
44309
44382
  }
44310
44383
  const turn = await readers.finalTurn(target.source, session).catch(() => void 0);
44311
- if (turn?.completed && turn.background) {
44312
- return { state: "working", session, completed: true, background: turn.background, ...turn.error ? { error: turn.error } : {}, ...replyFields(turn.lastAssistant) };
44384
+ const children = readers.children ? await readers.children(target.source, session).catch(() => 0) : 0;
44385
+ const live = turn?.completed ? liveWork(void 0, turn, children, (readers.now ?? Date.now)()) : void 0;
44386
+ if (live) {
44387
+ return { state: "working", session, completed: true, background: live, ...turn?.error ? { error: turn.error } : {}, ...replyFields(turn?.lastAssistant) };
44313
44388
  }
44314
44389
  return {
44315
44390
  state,
@@ -44641,11 +44716,11 @@ var DispatchReturns = class {
44641
44716
  async poll() {
44642
44717
  await this.confirmArrivals(await this.peers().catch(() => []));
44643
44718
  const now = this.now();
44644
- const open24 = (await dispatchStatus()).filter((receipt) => (receipt.state === "accepted" || receipt.state === "uncertain") && receipt.target && !receipt.closedAt && receipt.worker?.state !== "gone" && now - Date.parse(receipt.createdAt) < WATCH_MS);
44645
- if (!open24.length) return;
44719
+ const open25 = (await dispatchStatus()).filter((receipt) => (receipt.state === "accepted" || receipt.state === "uncertain") && receipt.target && !receipt.closedAt && receipt.worker?.state !== "gone" && now - Date.parse(receipt.createdAt) < WATCH_MS);
44720
+ if (!open25.length) return;
44646
44721
  const peers = await this.peers().catch(() => []);
44647
44722
  const byComputer = /* @__PURE__ */ new Map();
44648
- for (const receipt of open24) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
44723
+ for (const receipt of open25) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
44649
44724
  await Promise.all([...byComputer].map(async ([computer, receipts]) => {
44650
44725
  const peer = peers.find((candidate) => candidate.name === computer);
44651
44726
  const local = !peer && this.isLocal(computer);
@@ -44885,7 +44960,7 @@ async function closeFinishedWorker(input2, queue3) {
44885
44960
  init_zod();
44886
44961
  init_protocol();
44887
44962
  import { createHash as createHash20, randomUUID as randomUUID15 } from "node:crypto";
44888
- import { lstat as lstat21, open as open14, readFile as readFile35, readdir as readdir13, unlink as unlink5 } from "node:fs/promises";
44963
+ import { lstat as lstat21, open as open15, readFile as readFile35, readdir as readdir13, unlink as unlink5 } from "node:fs/promises";
44889
44964
  import path67 from "node:path";
44890
44965
  init_terminal();
44891
44966
  var queuedHandOffSchema = external_exports.object({
@@ -44934,7 +45009,7 @@ var HandOffQueue = class {
44934
45009
  const file3 = this.file(row.deliveryId);
44935
45010
  await atomicInPrivateDir(file3, rowSchema.parse(row));
44936
45011
  if (process.platform !== "win32") for (const target of [file3, this.root]) {
44937
- const handle = await open14(target, "r");
45012
+ const handle = await open15(target, "r");
44938
45013
  try {
44939
45014
  await handle.sync();
44940
45015
  } finally {
@@ -45117,7 +45192,7 @@ var HandOffQueue = class {
45117
45192
 
45118
45193
  // src/bridge/server-pane-routes.ts
45119
45194
  init_zod();
45120
- import path78 from "node:path";
45195
+ import path79 from "node:path";
45121
45196
  import { setTimeout as sleep4 } from "node:timers/promises";
45122
45197
 
45123
45198
  // src/bridge/git.ts
@@ -45862,20 +45937,20 @@ init_protocol();
45862
45937
  init_herdr();
45863
45938
  init_codex_daemon();
45864
45939
  import { request as request6, createServer as createServer2 } from "node:http";
45865
- import { mkdir as mkdir19, readFile as readFile38, chmod as chmod4, unlink as unlink6, lstat as lstat23 } from "node:fs/promises";
45940
+ import { mkdir as mkdir20, readFile as readFile39, chmod as chmod4, unlink as unlink7, lstat as lstat24 } from "node:fs/promises";
45866
45941
  import { watch } from "node:fs";
45867
- import path75 from "node:path";
45868
- import { createHash as createHash23, randomUUID as randomUUID16 } from "node:crypto";
45942
+ import path76 from "node:path";
45943
+ import { createHash as createHash23, randomUUID as randomUUID17 } from "node:crypto";
45869
45944
  import { hostname as hostname10 } from "node:os";
45870
45945
 
45871
45946
  // src/bridge/codex-review-mode.ts
45872
- import { open as open15 } from "node:fs/promises";
45947
+ import { open as open16 } from "node:fs/promises";
45873
45948
  import path70 from "node:path";
45874
45949
  var SCAN_LIMIT = 64 * 1048576;
45875
45950
  var CHUNK = 1048576;
45876
45951
  async function codexAutoReview(transcriptPath2) {
45877
45952
  if (typeof transcriptPath2 !== "string" || !path70.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path70.basename(transcriptPath2))) return false;
45878
- const file3 = await open15(transcriptPath2, "r").catch(() => void 0);
45953
+ const file3 = await open16(transcriptPath2, "r").catch(() => void 0);
45879
45954
  if (!file3) return false;
45880
45955
  try {
45881
45956
  const size = (await file3.stat()).size;
@@ -46381,6 +46456,80 @@ init_limits();
46381
46456
  init_claude_question_dialog();
46382
46457
  init_terminal_choice();
46383
46458
  init_opencode_approvals();
46459
+
46460
+ // src/bridge/opencode-permissions.ts
46461
+ init_locks();
46462
+ init_home_paths();
46463
+ init_protocol();
46464
+ import { randomUUID as randomUUID16 } from "node:crypto";
46465
+ import { lstat as lstat23, mkdir as mkdir19, readFile as readFile38, rename as rename6, unlink as unlink6, writeFile as writeFile6 } from "node:fs/promises";
46466
+ import path73 from "node:path";
46467
+ function opencodeConfigPath(env = process.env, home = homeDir(env)) {
46468
+ return path73.join(env.XDG_CONFIG_HOME || path73.join(home, ".config"), "opencode", "opencode.json");
46469
+ }
46470
+ function opencodeToolName(value2) {
46471
+ if (typeof value2 !== "string") return void 0;
46472
+ const name = value2.trim().slice(0, 100);
46473
+ return /^[A-Za-z0-9_*-]+$/.test(name) ? name : void 0;
46474
+ }
46475
+ async function readConfig2(file3) {
46476
+ let text4;
46477
+ try {
46478
+ text4 = await readFile38(file3, "utf8");
46479
+ } catch (error62) {
46480
+ if (error62.code === "ENOENT") return {};
46481
+ throw new BridgeError(409, "Could not read ~/.config/opencode/opencode.json.");
46482
+ }
46483
+ let parsed;
46484
+ try {
46485
+ parsed = JSON.parse(text4);
46486
+ } catch {
46487
+ throw new BridgeError(409, "~/.config/opencode/opencode.json is not valid JSON.");
46488
+ }
46489
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new BridgeError(409, "~/.config/opencode/opencode.json is not a JSON object.");
46490
+ return parsed;
46491
+ }
46492
+ function withAllowedTool(config3, tool) {
46493
+ const permission = config3.permission;
46494
+ if (permission === void 0) return { ...config3, permission: { [tool]: "allow" } };
46495
+ if (typeof permission === "string") return { ...config3, permission: { "*": permission, [tool]: "allow" } };
46496
+ if (!permission || typeof permission !== "object" || Array.isArray(permission)) {
46497
+ throw new BridgeError(409, "The opencode permission block is not a JSON object.");
46498
+ }
46499
+ const block = { ...permission };
46500
+ const existing = block[tool];
46501
+ if (existing && typeof existing === "object" && !Array.isArray(existing)) {
46502
+ const merged = { "*": "allow", ...existing };
46503
+ merged["*"] = "allow";
46504
+ block[tool] = merged;
46505
+ } else block[tool] = "allow";
46506
+ return { ...config3, permission: block };
46507
+ }
46508
+ async function allowOpencodeToolEverywhere(tool, file3 = opencodeConfigPath()) {
46509
+ const name = opencodeToolName(tool);
46510
+ if (!name) throw new BridgeError(400, "OpenCode did not name a tool this can allow.");
46511
+ const release = tryFileLock(file3);
46512
+ if (!release) throw new BridgeError(409, "~/.config/opencode/opencode.json is being updated. Try again.");
46513
+ try {
46514
+ const config3 = withAllowedTool(await readConfig2(file3), name);
46515
+ const mode = (await lstat23(file3).catch(() => void 0))?.mode;
46516
+ await mkdir19(path73.dirname(file3), { recursive: true, mode: 448 });
46517
+ const temporary = `${file3}.${randomUUID16()}.tmp`;
46518
+ await writeFile6(temporary, `${JSON.stringify(config3, null, 2)}
46519
+ `, { mode: mode === void 0 ? 384 : mode & 511, flag: "wx" });
46520
+ try {
46521
+ await rename6(temporary, file3);
46522
+ } finally {
46523
+ await unlink6(temporary).catch(() => {
46524
+ });
46525
+ }
46526
+ return name;
46527
+ } finally {
46528
+ release();
46529
+ }
46530
+ }
46531
+
46532
+ // src/bridge/agent-hooks.ts
46384
46533
  init_agent_hook_stores();
46385
46534
  init_pane_accounts();
46386
46535
  init_pane_status();
@@ -46392,7 +46541,7 @@ init_codex_servers();
46392
46541
  // src/bridge/opencode-panes.ts
46393
46542
  init_limits();
46394
46543
  import { execFile as execFile14 } from "node:child_process";
46395
- import path74 from "node:path";
46544
+ import path75 from "node:path";
46396
46545
  import { promisify as promisify13 } from "node:util";
46397
46546
 
46398
46547
  // src/bridge/opencode-pane-server.ts
@@ -46400,7 +46549,7 @@ init_phren_paths();
46400
46549
  import * as crypto6 from "node:crypto";
46401
46550
  import * as fs23 from "node:fs";
46402
46551
  import * as net from "node:net";
46403
- import * as path73 from "node:path";
46552
+ import * as path74 from "node:path";
46404
46553
  var MAX_PASSWORD = 200;
46405
46554
  var REQUEST_TIMEOUT_MS = 1e4;
46406
46555
  var PROMPT_POLL_MS = 200;
@@ -46425,7 +46574,7 @@ function alive(pid) {
46425
46574
  }
46426
46575
  }
46427
46576
  function paneServerFile(dir, server, pane) {
46428
- return path73.join(dir, `${encodeURIComponent(`${server}/${pane}`)}.json`);
46577
+ return path74.join(dir, `${encodeURIComponent(`${server}/${pane}`)}.json`);
46429
46578
  }
46430
46579
  function registerPaneServer(dir, entry2) {
46431
46580
  if (!validEntry(entry2)) throw new Error("Invalid OpenCode pane server entry.");
@@ -46463,7 +46612,7 @@ function listPaneServers(dir) {
46463
46612
  const entries2 = [];
46464
46613
  for (const name of names.slice(0, 1024)) {
46465
46614
  if (!name.endsWith(".json")) continue;
46466
- const file3 = path73.join(dir, name);
46615
+ const file3 = path74.join(dir, name);
46467
46616
  let parsed;
46468
46617
  try {
46469
46618
  const info = fs23.lstatSync(file3);
@@ -46669,7 +46818,7 @@ var READY_MS = 2e4;
46669
46818
  var PID_MS = intervalFromEnv("PHREN_OPENCODE_PID_MS", 2e3);
46670
46819
  var BRIEF_CONFIRM_MS = 1e4;
46671
46820
  function paneServersDir() {
46672
- return path74.join(bridgeRoot(), "opencode-panes");
46821
+ return path75.join(bridgeRoot(), "opencode-panes");
46673
46822
  }
46674
46823
  function servedPane(server, pane) {
46675
46824
  return readPaneServer(paneServersDir(), server, pane);
@@ -46938,6 +47087,18 @@ function conductorCall(tool, input2) {
46938
47087
  const computer = typeof fields2.computer === "string" ? fields2.computer : void 0;
46939
47088
  return { action, ...project ? { project } : {}, ...computer ? { computer } : {} };
46940
47089
  }
47090
+ var OPENCODE_APPROVAL_OPTIONS = [
47091
+ { label: "Allow once", decision: "approve" },
47092
+ { label: "Allow for this project", decision: "allow-project" },
47093
+ { label: "Allow everywhere", decision: "allow-everywhere" },
47094
+ { label: "Deny", decision: "deny" }
47095
+ ];
47096
+ function opencodePermissionReply(decision) {
47097
+ if (decision === "approve") return "once";
47098
+ if (decision === "deny") return "reject";
47099
+ if (decision === "allow-project" || decision === "allow-everywhere") return "always";
47100
+ return void 0;
47101
+ }
46941
47102
  var TRACK_MS = 6e5;
46942
47103
  function promptKey(text4) {
46943
47104
  return unwrapPastedContent(text4).split("\n").filter((line) => !PICTURE_PATH_LINE.test(line)).join("\n").replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
@@ -47042,7 +47203,7 @@ var AgentHooks = class {
47042
47203
  /** sudo -A requests from askpass, answered from the phone (sudo.ts). */
47043
47204
  sudo;
47044
47205
  approvalsDirectory() {
47045
- return path75.join(phrenStoreRoot(), ".runtime", "approvals");
47206
+ return path76.join(phrenStoreRoot(), ".runtime", "approvals");
47046
47207
  }
47047
47208
  scheduleOpencodeSweep() {
47048
47209
  if (this.closed || this.opencodeDebounce) return;
@@ -47095,17 +47256,17 @@ var AgentHooks = class {
47095
47256
  ) : void 0;
47096
47257
  const cwd = asking?.worktree ?? (pane ? await trustedDirectory(pane).catch(() => void 0) : void 0);
47097
47258
  const summary = approvalSummary({ tool: String(request9.type ?? ""), input: request9, message: typeof request9.message === "string" ? request9.message : void 0, cwd });
47098
- const fanout = asking ? { session: match[1], actionId: asking.parent.provider === "opencode" ? randomUUID16().replaceAll("-", "") : randomUUID16() } : void 0;
47259
+ const fanout = asking ? { session: match[1], actionId: asking.parent.provider === "opencode" ? randomUUID17().replaceAll("-", "") : randomUUID17() } : void 0;
47099
47260
  this.opencode.set(id2, { ...target ? { target } : {}, request: request9, requestLine: summary.request, expiresAt, ...fanout ? { fanout } : {} });
47100
47261
  if (!this.push.available) continue;
47101
- const binding = randomUUID16();
47262
+ const binding = randomUUID17();
47102
47263
  this.pushBindings.add(binding, { action: id2, expiresAt });
47103
47264
  void this.push.notify({
47104
47265
  binding,
47105
47266
  provider: "opencode",
47106
47267
  question: false,
47107
47268
  expiresAt: String(request9.expiresAt),
47108
- ...cwd ? { project: path75.basename(cwd) } : {},
47269
+ ...cwd ? { project: path76.basename(cwd) } : {},
47109
47270
  computer: this.computerName,
47110
47271
  ...summary
47111
47272
  }).then((delivered) => {
@@ -47173,14 +47334,14 @@ var AgentHooks = class {
47173
47334
  const summary = approvalSummary({ tool: type, input: request9, message, cwd: entry2.directory });
47174
47335
  this.opencode.set(ask.id, { ...target ? { target } : {}, request: request9, requestLine: summary.request, expiresAt, served: where });
47175
47336
  if (!this.push.available) continue;
47176
- const binding = randomUUID16();
47337
+ const binding = randomUUID17();
47177
47338
  this.pushBindings.add(binding, { action: ask.id, expiresAt });
47178
47339
  void this.push.notify({
47179
47340
  binding,
47180
47341
  provider: "opencode",
47181
47342
  question: false,
47182
47343
  expiresAt: String(request9.expiresAt),
47183
- project: path75.basename(entry2.directory),
47344
+ project: path76.basename(entry2.directory),
47184
47345
  computer: this.computerName,
47185
47346
  ...summary
47186
47347
  }).then((delivered) => {
@@ -47243,11 +47404,13 @@ var AgentHooks = class {
47243
47404
  }
47244
47405
  /** Answers a served pane's permission ask over its own API. */
47245
47406
  async answerServed(id2, held, decision) {
47246
- if (!["approve", "deny"].includes(String(decision))) throw new BridgeError(400, "The approval answer is not valid.");
47407
+ const reply = opencodePermissionReply(decision);
47408
+ if (!reply) throw new BridgeError(400, "The approval answer is not valid.");
47247
47409
  const served = held.served;
47248
47410
  const client = this.servedClient(served.server, served.pane);
47411
+ if (decision === "allow-everywhere") await allowOpencodeToolEverywhere(held.request.type);
47249
47412
  try {
47250
- await client.replyPermission(id2, decision === "approve" ? "once" : "reject");
47413
+ await client.replyPermission(id2, reply);
47251
47414
  } catch {
47252
47415
  throw new BridgeError(409, "This approval is no longer pending.");
47253
47416
  }
@@ -47307,15 +47470,15 @@ var AgentHooks = class {
47307
47470
  /** A session's exact pane. A recorded binding carries the full target; when
47308
47471
  * there is none, Herdr's explicit session identity names the pane. */
47309
47472
  async resolveTarget(source, session) {
47310
- const root = path75.join(bridgeRoot(), "bindings");
47473
+ const root = path76.join(bridgeRoot(), "bindings");
47311
47474
  for await (const folder of directoryNames(root, 64)) {
47312
- for await (const name of directoryNames(path75.join(root, folder), 1024)) {
47475
+ for await (const name of directoryNames(path76.join(root, folder), 1024)) {
47313
47476
  if (!name.endsWith(".json")) continue;
47314
47477
  let value2;
47315
47478
  try {
47316
- const file3 = path75.join(root, folder, name), info = await lstat23(file3);
47479
+ const file3 = path76.join(root, folder, name), info = await lstat24(file3);
47317
47480
  if (!info.isFile() || info.size > 65536) continue;
47318
- value2 = object2(JSON.parse(await readFile38(file3, "utf8")));
47481
+ value2 = object2(JSON.parse(await readFile39(file3, "utf8")));
47319
47482
  } catch {
47320
47483
  continue;
47321
47484
  }
@@ -47847,12 +48010,13 @@ var AgentHooks = class {
47847
48010
  title: worker.request.title,
47848
48011
  message: worker.request.message,
47849
48012
  request: worker.requestLine,
47850
- expiresAt: worker.request.expiresAt
48013
+ expiresAt: worker.request.expiresAt,
48014
+ options: OPENCODE_APPROVAL_OPTIONS
47851
48015
  } : void 0;
47852
48016
  }
47853
48017
  opencodeApproval(target) {
47854
48018
  const held = [...this.opencode.values()].find((value2) => !value2.fanout && JSON.stringify(value2.target) === JSON.stringify(target));
47855
- if (held) return { actionId: held.request.id, toolName: held.request.type, title: held.request.title, message: held.request.message, request: held.requestLine, expiresAt: held.request.expiresAt };
48019
+ if (held) return { actionId: held.request.id, toolName: held.request.type, title: held.request.title, message: held.request.message, request: held.requestLine, expiresAt: held.request.expiresAt, options: OPENCODE_APPROVAL_OPTIONS };
47856
48020
  const request9 = opencodeRequest(target.session);
47857
48021
  return request9 ? {
47858
48022
  actionId: request9.id,
@@ -47860,7 +48024,8 @@ var AgentHooks = class {
47860
48024
  title: request9.title,
47861
48025
  message: request9.message,
47862
48026
  request: approvalSummary({ tool: String(request9.type ?? ""), input: request9, message: typeof request9.message === "string" ? request9.message : void 0 }).request,
47863
- expiresAt: request9.expiresAt
48027
+ expiresAt: request9.expiresAt,
48028
+ options: OPENCODE_APPROVAL_OPTIONS
47864
48029
  } : void 0;
47865
48030
  }
47866
48031
  /** Live fan-out worker asks shown on this parent conversation, oldest first. */
@@ -47902,10 +48067,12 @@ var AgentHooks = class {
47902
48067
  }
47903
48068
  /** Hands the owner's answer to the fan-out launcher waiting on the worker's session. */
47904
48069
  async answerFanout(id2, held, decision) {
47905
- if (!["approve", "deny"].includes(String(decision))) throw new BridgeError(400, "The approval answer is not valid.");
48070
+ const reply = opencodePermissionReply(decision);
48071
+ if (!reply) throw new BridgeError(400, "The approval answer is not valid.");
47906
48072
  const file3 = held.fanout && opencodeApprovalFile(held.fanout.session, "answer");
47907
48073
  if (!held.fanout || !file3 || opencodeRequest(held.fanout.session)?.id !== id2) throw new BridgeError(409, "This approval is no longer pending.");
47908
- await atomicInPrivateDir(file3, JSON.stringify({ id: id2, decision }));
48074
+ if (decision === "allow-everywhere") await allowOpencodeToolEverywhere(held.request.type);
48075
+ await atomicInPrivateDir(file3, JSON.stringify({ id: id2, decision: decision === "approve" || decision === "deny" ? decision : "always" }));
47909
48076
  this.opencode.delete(id2);
47910
48077
  this.pushBindings.dropAction(id2);
47911
48078
  }
@@ -47934,12 +48101,15 @@ var AgentHooks = class {
47934
48101
  return;
47935
48102
  }
47936
48103
  if (target.source === "opencode") {
47937
- if (!["approve", "deny"].includes(String(decision))) throw new BridgeError(400, "The approval answer is not valid.");
48104
+ const reply = opencodePermissionReply(decision);
48105
+ if (!reply) throw new BridgeError(400, "The approval answer is not valid.");
47938
48106
  const file3 = opencodeApprovalFile(target.session, "answer");
47939
48107
  if (!file3) throw new BridgeError(400, "Invalid conversation identity.");
47940
48108
  await validateTarget(target);
47941
- if (opencodeRequest(target.session)?.id !== id2) throw new BridgeError(409, "This approval is no longer pending.");
47942
- await atomicInPrivateDir(file3, JSON.stringify({ id: id2, decision }));
48109
+ const request9 = opencodeRequest(target.session);
48110
+ if (request9?.id !== id2) throw new BridgeError(409, "This approval is no longer pending.");
48111
+ if (decision === "allow-everywhere") await allowOpencodeToolEverywhere(request9.type);
48112
+ await atomicInPrivateDir(file3, JSON.stringify({ id: id2, decision: decision === "approve" || decision === "deny" ? decision : "always" }));
47943
48113
  this.opencode.delete(id2);
47944
48114
  this.pushBindings.dropAction(id2);
47945
48115
  return;
@@ -48084,7 +48254,7 @@ var AgentHooks = class {
48084
48254
  if (this.dialogPushes.get(key3)?.title === title2) continue;
48085
48255
  this.dropDialogPush(key3);
48086
48256
  if (this.adoptReleasedHold(key3, target, entry2.choice, title2)) continue;
48087
- const action = `dialog-${randomUUID16()}`, binding = randomUUID16(), expiresAt = Date.now() + DIALOG_PUSH_MS;
48257
+ const action = `dialog-${randomUUID17()}`, binding = randomUUID17(), expiresAt = Date.now() + DIALOG_PUSH_MS;
48088
48258
  this.dialogPushes.set(key3, { action, title: title2 });
48089
48259
  this.dialogActions.set(action, { target, choice: entry2.choice, expiresAt });
48090
48260
  this.pushBindings.add(binding, { action, expiresAt });
@@ -48095,7 +48265,7 @@ var AgentHooks = class {
48095
48265
  provider: target.source,
48096
48266
  question: entry2.tool === "AskUserQuestion",
48097
48267
  expiresAt: new Date(expiresAt).toISOString(),
48098
- ...cwd ? { project: path75.basename(cwd) } : {},
48268
+ ...cwd ? { project: path76.basename(cwd) } : {},
48099
48269
  computer: this.computerName,
48100
48270
  ...summary
48101
48271
  }).then((delivered) => {
@@ -48179,7 +48349,7 @@ ${target.source}`) ?? 0) > Date.now();
48179
48349
  else {
48180
48350
  this.dropForwardedDialog(key3);
48181
48351
  while (this.forwardedDialogs.size >= 64) this.dropForwardedDialog(this.forwardedDialogs.keys().next().value);
48182
- action = `dialog-${randomUUID16()}`;
48352
+ action = `dialog-${randomUUID17()}`;
48183
48353
  this.forwardedDialogs.set(key3, { action, title: title2, body: entry2.choice.body });
48184
48354
  this.dialogActions.set(action, { target, choice: entry2.choice, expiresAt: Date.now() + DIALOG_PUSH_MS });
48185
48355
  }
@@ -48201,7 +48371,7 @@ ${target.source}`) ?? 0) > Date.now();
48201
48371
  * dispatch path. */
48202
48372
  pushForwarded(summary, answer) {
48203
48373
  if (!this.push.available || this.closed) return;
48204
- const action = `forward-${randomUUID16()}`, binding = randomUUID16(), expiresAt = Date.now() + DIALOG_PUSH_MS;
48374
+ const action = `forward-${randomUUID17()}`, binding = randomUUID17(), expiresAt = Date.now() + DIALOG_PUSH_MS;
48205
48375
  while (this.forwardedPushes.size >= 64) {
48206
48376
  const oldest = this.forwardedPushes.keys().next().value;
48207
48377
  this.forwardedPushes.delete(oldest);
@@ -48287,7 +48457,7 @@ ${target.source}`) ?? 0) > Date.now();
48287
48457
  known2.appServer.answer = answer;
48288
48458
  return;
48289
48459
  }
48290
- const action = randomUUID16();
48460
+ const action = randomUUID17();
48291
48461
  const held = { requestId: request9.requestId, answer };
48292
48462
  const reply = { destroyed: false, end(body2) {
48293
48463
  if (reply.destroyed) return;
@@ -48301,7 +48471,7 @@ ${target.source}`) ?? 0) > Date.now();
48301
48471
  })()).hookSpecificOutput).decision).behavior;
48302
48472
  if (behavior === "allow" || behavior === "deny") held.answer(appServerDecision(request9, behavior === "allow"));
48303
48473
  } };
48304
- const cwd = typeof request9.params.cwd === "string" && path75.isAbsolute(request9.params.cwd) ? request9.params.cwd : void 0;
48474
+ const cwd = typeof request9.params.cwd === "string" && path76.isAbsolute(request9.params.cwd) ? request9.params.cwd : void 0;
48305
48475
  const summary = approvalSummary({ tool: shown.tool, input: shown.input, cwd });
48306
48476
  const expiresAt = Date.now() + DIALOG_PUSH_MS;
48307
48477
  this.pending.set(action, {
@@ -48316,14 +48486,14 @@ ${target.source}`) ?? 0) > Date.now();
48316
48486
  });
48317
48487
  while (this.pending.size > 64) this.pending.delete(this.pending.keys().next().value);
48318
48488
  if (!this.push.available) return;
48319
- const binding = randomUUID16();
48489
+ const binding = randomUUID17();
48320
48490
  this.pushBindings.add(binding, { action, expiresAt });
48321
48491
  void this.push.notify({
48322
48492
  binding,
48323
48493
  provider: "codex",
48324
48494
  question: false,
48325
48495
  expiresAt: new Date(expiresAt).toISOString(),
48326
- ...cwd ? { project: path75.basename(cwd) } : {},
48496
+ ...cwd ? { project: path76.basename(cwd) } : {},
48327
48497
  computer: this.computerName,
48328
48498
  ...summary
48329
48499
  }).then((delivered) => {
@@ -48343,10 +48513,10 @@ ${target.source}`) ?? 0) > Date.now();
48343
48513
  }
48344
48514
  async start() {
48345
48515
  await this.push.start();
48346
- const previous = await lstat23(localSocket()).catch(() => void 0);
48516
+ const previous = await lstat24(localSocket()).catch(() => void 0);
48347
48517
  if (previous) {
48348
48518
  if (!previous.isSocket() || previous.uid !== process.getuid?.()) throw new Error("Unexpected agent callback socket.");
48349
- await unlink6(localSocket());
48519
+ await unlink7(localSocket());
48350
48520
  }
48351
48521
  this.server = createServer2(async (req, res) => {
48352
48522
  res.setHeader("Content-Type", "application/json");
@@ -48373,7 +48543,7 @@ ${target.source}`) ?? 0) > Date.now();
48373
48543
  const daemon = body2.daemon === true;
48374
48544
  if (daemon) {
48375
48545
  if (target.source !== "codex") throw new Error("Invalid callback");
48376
- const placed = await paneForCodexSession(target.server, target.session, typeof body2.cwd === "string" && path75.isAbsolute(body2.cwd) ? body2.cwd : void 0);
48546
+ const placed = await paneForCodexSession(target.server, target.session, typeof body2.cwd === "string" && path76.isAbsolute(body2.cwd) ? body2.cwd : void 0);
48377
48547
  if (!placed) {
48378
48548
  res.end("{}");
48379
48549
  return;
@@ -48422,7 +48592,7 @@ ${target.source}`) ?? 0) > Date.now();
48422
48592
  if (body2.event === "SessionStart" || body2.event === "Stop") await this.recordTurn(target, pane, body2, dispatch2);
48423
48593
  if ((this.modules?.has("git") ?? true) && ["PreToolUse", "PostToolUse"].includes(String(body2.event)) && capturesChanges(String(body2.tool), input2)) {
48424
48594
  const conversation = `${target.source}:${target.session}`, id2 = String(body2.toolUseId || "").slice(0, 200);
48425
- if (body2.event === "PreToolUse") await this.changes.before(conversation, id2, typeof body2.cwd === "string" && path75.isAbsolute(body2.cwd) ? body2.cwd : await trustedDirectory(pane), command ?? "", input2);
48595
+ if (body2.event === "PreToolUse") await this.changes.before(conversation, id2, typeof body2.cwd === "string" && path76.isAbsolute(body2.cwd) ? body2.cwd : await trustedDirectory(pane), command ?? "", input2);
48426
48596
  else await this.changes.after(conversation, id2);
48427
48597
  res.end("{}");
48428
48598
  return;
@@ -48459,11 +48629,11 @@ ${target.source}`) ?? 0) > Date.now();
48459
48629
  res.end("{}");
48460
48630
  return;
48461
48631
  }
48462
- const action = randomUUID16();
48632
+ const action = randomUUID17();
48463
48633
  this.dialogReads.delete(JSON.stringify(target));
48464
48634
  const conductor = body2.event === "PermissionRequest" ? conductorCall(String(body2.tool || "action"), body2.input) : void 0;
48465
48635
  const locallyWatched = this.watching.has(JSON.stringify(target)) || this.overview.has(target.server) || this.dispatchLeased(target);
48466
- const cwd = typeof body2.cwd === "string" && path75.isAbsolute(body2.cwd) ? body2.cwd : await trustedDirectory(pane).catch(() => void 0);
48636
+ const cwd = typeof body2.cwd === "string" && path76.isAbsolute(body2.cwd) ? body2.cwd : await trustedDirectory(pane).catch(() => void 0);
48467
48637
  let released = false;
48468
48638
  const timer = setTimeout(() => {
48469
48639
  released = true;
@@ -48496,7 +48666,7 @@ ${target.source}`) ?? 0) > Date.now();
48496
48666
  if (!released) this.dropPushBindings(action);
48497
48667
  });
48498
48668
  if (this.push.available) {
48499
- const binding = randomUUID16(), pushExpiresAt = Date.now() + DIALOG_PUSH_MS;
48669
+ const binding = randomUUID17(), pushExpiresAt = Date.now() + DIALOG_PUSH_MS;
48500
48670
  this.pushBindings.add(binding, { action, expiresAt: pushExpiresAt });
48501
48671
  this.pushedHolds.set(action, pushExpiresAt);
48502
48672
  void this.push.notify({
@@ -48504,7 +48674,7 @@ ${target.source}`) ?? 0) > Date.now();
48504
48674
  provider: target.source,
48505
48675
  question: body2.tool === "AskUserQuestion",
48506
48676
  expiresAt: new Date(pushExpiresAt).toISOString(),
48507
- ...cwd ? { project: path75.basename(cwd) } : {},
48677
+ ...cwd ? { project: path76.basename(cwd) } : {},
48508
48678
  computer: this.computerName,
48509
48679
  ...summary
48510
48680
  }).catch(() => false).then((delivered) => {
@@ -48531,7 +48701,7 @@ ${target.source}`) ?? 0) > Date.now();
48531
48701
  this.server.listen(localSocket(), () => resolve11());
48532
48702
  });
48533
48703
  await chmod4(localSocket(), 384);
48534
- await mkdir19(this.approvalsDirectory(), { recursive: true, mode: 448 }).catch(() => {
48704
+ await mkdir20(this.approvalsDirectory(), { recursive: true, mode: 448 }).catch(() => {
48535
48705
  });
48536
48706
  try {
48537
48707
  this.opencodeWatcher = watch(this.approvalsDirectory(), { persistent: false }, () => this.scheduleOpencodeSweep());
@@ -48675,9 +48845,9 @@ init_protocol();
48675
48845
  init_claude_accounts();
48676
48846
  init_codex_binary();
48677
48847
  import { spawn as spawn10 } from "node:child_process";
48678
- import { readdir as readdir15, readFile as readFile39, stat as stat20 } from "node:fs/promises";
48848
+ import { readdir as readdir15, readFile as readFile40, stat as stat20 } from "node:fs/promises";
48679
48849
  import { homedir as homedir17 } from "node:os";
48680
- import path76 from "node:path";
48850
+ import path77 from "node:path";
48681
48851
  function readCodexModels(executable2 = codexExecutable()) {
48682
48852
  return new Promise((resolve11) => {
48683
48853
  const child = spawn10(executable2, ["app-server"], { cwd: homedir17(), stdio: ["pipe", "pipe", "ignore"] });
@@ -48756,12 +48926,12 @@ var CLAUDE_MENU = [
48756
48926
  { id: "claude-fable-5-1[1m]", name: "Fable 5.1 (1M context)", description: "Fable 5.1 with a 1M context window." }
48757
48927
  ];
48758
48928
  async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
48759
- const directory = path76.join(configDir, "cache", "model-catalog");
48929
+ const directory = path77.join(configDir, "cache", "model-catalog");
48760
48930
  let newest2;
48761
48931
  try {
48762
48932
  for (const name of await readdir15(directory)) {
48763
48933
  if (!name.endsWith("-cc.json")) continue;
48764
- const file3 = path76.join(directory, name), at = (await stat20(file3)).mtimeMs;
48934
+ const file3 = path77.join(directory, name), at = (await stat20(file3)).mtimeMs;
48765
48935
  if (!newest2 || at > newest2.at) newest2 = { file: file3, at };
48766
48936
  }
48767
48937
  } catch {
@@ -48770,7 +48940,7 @@ async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
48770
48940
  if (!newest2) return [];
48771
48941
  let parsed;
48772
48942
  try {
48773
- parsed = JSON.parse(await readFile39(newest2.file, "utf8"));
48943
+ parsed = JSON.parse(await readFile40(newest2.file, "utf8"));
48774
48944
  } catch {
48775
48945
  return [];
48776
48946
  }
@@ -48842,7 +49012,7 @@ async function readClaudeModels(configDir, installed) {
48842
49012
  const live = await readClaudeCatalog(configDir, version3).catch(() => []);
48843
49013
  return live.length ? live : CLAUDE_MENU.map((model) => ({ ...model }));
48844
49014
  }
48845
- async function readOpenCodeModels(executable2 = "opencode", configDir = path76.join(homedir17(), ".config/opencode")) {
49015
+ async function readOpenCodeModels(executable2 = "opencode", configDir = path77.join(homedir17(), ".config/opencode")) {
48846
49016
  const listed2 = await new Promise((resolve11) => {
48847
49017
  const child = spawn10(executable2, ["models"], { cwd: homedir17(), stdio: ["ignore", "pipe", "ignore"] });
48848
49018
  let out = "", done = false;
@@ -48869,7 +49039,7 @@ async function readOpenCodeModels(executable2 = "opencode", configDir = path76.j
48869
49039
  let configured;
48870
49040
  for (const file3 of ["opencode.json", "opencode.jsonc"]) {
48871
49041
  try {
48872
- const text4 = await readFile39(path76.join(configDir, file3), "utf8");
49042
+ const text4 = await readFile40(path77.join(configDir, file3), "utf8");
48873
49043
  const model = /"model"\s*:\s*"([^"]+)"/.exec(text4)?.[1];
48874
49044
  if (model) {
48875
49045
  configured = model.slice(0, 200);
@@ -48927,7 +49097,7 @@ init_protocol();
48927
49097
  // src/bridge/side-questions.ts
48928
49098
  init_herdr();
48929
49099
  init_terminal();
48930
- import { randomUUID as randomUUID17 } from "node:crypto";
49100
+ import { randomUUID as randomUUID18 } from "node:crypto";
48931
49101
  init_protocol();
48932
49102
  var MAX_QUESTION = 4e3;
48933
49103
  var MAX_ANSWER = 65536;
@@ -49024,7 +49194,7 @@ var SideQuestions = class {
49024
49194
  if (!question2) throw new BridgeError(422, "Side questions are for Claude Code: /btw followed by the question.");
49025
49195
  if (question2.length > MAX_QUESTION) throw new BridgeError(413, "The side question is too long.");
49026
49196
  this.assertAvailable(target);
49027
- const key3 = this.paneKey(target), id2 = randomUUID17();
49197
+ const key3 = this.paneKey(target), id2 = randomUUID18();
49028
49198
  this.open.set(key3, id2);
49029
49199
  try {
49030
49200
  if (sidePanel(await this.read(target))) throw new BridgeError(409, "The terminal already shows a side question. Close it there first.");
@@ -49357,7 +49527,7 @@ init_protocol();
49357
49527
  init_herdr();
49358
49528
  init_terminal();
49359
49529
  import { execFile as execFile15 } from "node:child_process";
49360
- import { open as open16, stat as stat21 } from "node:fs/promises";
49530
+ import { open as open17, stat as stat21 } from "node:fs/promises";
49361
49531
  import { promisify as promisify14 } from "node:util";
49362
49532
  init_transcripts();
49363
49533
  var exec14 = promisify14(execFile15);
@@ -49418,7 +49588,7 @@ async function transcriptHolders(file3) {
49418
49588
  }
49419
49589
  async function transcriptTail(file3) {
49420
49590
  const size = (await stat21(file3)).size;
49421
- const handle = await open16(file3, "r");
49591
+ const handle = await open17(file3, "r");
49422
49592
  try {
49423
49593
  const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
49424
49594
  const buffer = Buffer.alloc(length);
@@ -49459,9 +49629,9 @@ init_transcripts();
49459
49629
 
49460
49630
  // src/bridge/uploads.ts
49461
49631
  init_protocol();
49462
- import { mkdir as mkdir20, readdir as readdir16, lstat as lstat24, realpath as realpath13, readFile as readFile40, stat as stat22, unlink as unlink7, writeFile as writeFile6 } from "node:fs/promises";
49463
- import path77 from "node:path";
49464
- import { randomUUID as randomUUID18 } from "node:crypto";
49632
+ import { mkdir as mkdir21, readdir as readdir16, lstat as lstat25, realpath as realpath13, readFile as readFile41, stat as stat22, unlink as unlink8, writeFile as writeFile7 } from "node:fs/promises";
49633
+ import path78 from "node:path";
49634
+ import { randomUUID as randomUUID19 } from "node:crypto";
49465
49635
  function imageBytes(bytes) {
49466
49636
  return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255])) || /^GIF8[79]a/.test(bytes.subarray(0, 6).toString()) || bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP";
49467
49637
  }
@@ -49473,61 +49643,61 @@ async function saveUpload(session, name, bytes) {
49473
49643
  let saved = "";
49474
49644
  const task = uploadQueue.catch(() => {
49475
49645
  }).then(async () => {
49476
- const root = path77.join(bridgeRoot(), "uploads");
49477
- await mkdir20(root, { recursive: true, mode: 448 });
49646
+ const root = path78.join(bridgeRoot(), "uploads");
49647
+ await mkdir21(root, { recursive: true, mode: 448 });
49478
49648
  let used = 0;
49479
49649
  const directories = await readdir16(root, { withFileTypes: true });
49480
49650
  for (const dir of directories) {
49481
49651
  if (!dir.isDirectory()) continue;
49482
- const folder2 = path77.join(root, dir.name);
49652
+ const folder2 = path78.join(root, dir.name);
49483
49653
  for (const entry2 of await readdir16(folder2, { withFileTypes: true })) {
49484
49654
  if (!entry2.isFile()) continue;
49485
- const file3 = path77.join(folder2, entry2.name), metadata = await lstat24(file3);
49486
- if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink7(file3);
49655
+ const file3 = path78.join(folder2, entry2.name), metadata = await lstat25(file3);
49656
+ if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink8(file3);
49487
49657
  else used += metadata.size;
49488
49658
  }
49489
49659
  }
49490
49660
  if (used + bytes.length > 268435456) throw new BridgeError(413, "Phren's image storage is full. Remove older uploads on the computer.");
49491
- const folder = path77.join(root, session);
49492
- await mkdir20(folder, { recursive: true, mode: 448 });
49493
- saved = path77.join(folder, `${randomUUID18()}-${name}`);
49494
- await writeFile6(saved, bytes, { flag: "wx", mode: 384 });
49661
+ const folder = path78.join(root, session);
49662
+ await mkdir21(folder, { recursive: true, mode: 448 });
49663
+ saved = path78.join(folder, `${randomUUID19()}-${name}`);
49664
+ await writeFile7(saved, bytes, { flag: "wx", mode: 384 });
49495
49665
  });
49496
49666
  uploadQueue = task;
49497
49667
  await task;
49498
49668
  return saved;
49499
49669
  }
49500
49670
  async function listUploads(session) {
49501
- const folder = path77.join(bridgeRoot(), "uploads", session);
49671
+ const folder = path78.join(bridgeRoot(), "uploads", session);
49502
49672
  const entries2 = await readdir16(folder, { withFileTypes: true }).catch(() => []);
49503
49673
  const files = [];
49504
49674
  for (const entry2 of entries2) {
49505
49675
  if (!entry2.isFile()) continue;
49506
- const file3 = path77.join(folder, entry2.name), metadata = await stat22(file3);
49676
+ const file3 = path78.join(folder, entry2.name), metadata = await stat22(file3);
49507
49677
  files.push({ name: entry2.name.replace(/^[0-9a-f-]{36}-/, ""), path: file3, size: metadata.size, modified: metadata.mtime.toISOString() });
49508
49678
  }
49509
49679
  return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
49510
49680
  }
49511
49681
  async function uploadImage(requested) {
49512
49682
  const missing = new BridgeError(404, "This image is not one of the phone's uploads.");
49513
- if (!requested || requested.length > 4096 || !path77.isAbsolute(requested)) throw missing;
49514
- const root = await realpath13(path77.join(bridgeRoot(), "uploads")).catch(() => void 0);
49683
+ if (!requested || requested.length > 4096 || !path78.isAbsolute(requested)) throw missing;
49684
+ const root = await realpath13(path78.join(bridgeRoot(), "uploads")).catch(() => void 0);
49515
49685
  const file3 = await realpath13(requested).catch(() => void 0);
49516
- if (!root || !file3 || !file3.startsWith(root + path77.sep)) throw missing;
49686
+ if (!root || !file3 || !file3.startsWith(root + path78.sep)) throw missing;
49517
49687
  const metadata = await stat22(file3);
49518
49688
  if (!metadata.isFile()) throw missing;
49519
49689
  if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
49520
- const bytes = await readFile40(file3);
49690
+ const bytes = await readFile41(file3);
49521
49691
  if (bytes.length > 8388608) throw new BridgeError(413, "This image is too large.");
49522
49692
  if (!imageBytes(bytes)) throw missing;
49523
49693
  return bytes;
49524
49694
  }
49525
49695
  async function sessionUpload(session, requested) {
49526
49696
  const refused = new BridgeError(400, "An attachment is not one of this conversation's uploads. Attach it again.");
49527
- if (!requested || requested.length > 4096 || !path77.isAbsolute(requested)) throw refused;
49528
- const folder = await realpath13(path77.join(bridgeRoot(), "uploads", session)).catch(() => void 0);
49697
+ if (!requested || requested.length > 4096 || !path78.isAbsolute(requested)) throw refused;
49698
+ const folder = await realpath13(path78.join(bridgeRoot(), "uploads", session)).catch(() => void 0);
49529
49699
  const file3 = await realpath13(requested).catch(() => void 0);
49530
- if (!folder || !file3 || !file3.startsWith(folder + path77.sep)) throw refused;
49700
+ if (!folder || !file3 || !file3.startsWith(folder + path78.sep)) throw refused;
49531
49701
  if (!(await stat22(file3)).isFile()) throw refused;
49532
49702
  return file3;
49533
49703
  }
@@ -49588,7 +49758,7 @@ function herdrWorktreeWorkers(s) {
49588
49758
  const workers = [];
49589
49759
  for (const pane of objects(s.panes)) {
49590
49760
  const cwd = pane.foreground_cwd || pane.cwd;
49591
- if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path78.isAbsolute(cwd)) continue;
49761
+ if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path79.isAbsolute(cwd)) continue;
49592
49762
  const name = paneAgentName(s, pane);
49593
49763
  workers.push({
49594
49764
  cwd,
@@ -49990,9 +50160,9 @@ init_fanouts();
49990
50160
  init_protocol();
49991
50161
  init_transcripts();
49992
50162
  init_metrics();
49993
- import { randomUUID as randomUUID19 } from "node:crypto";
49994
- import { appendFile as appendFile2, lstat as lstat25, mkdir as mkdir21, readdir as readdir17, readFile as readFile41, realpath as realpath14, rename as rename6, rm as rm10, writeFile as writeFile7 } from "node:fs/promises";
49995
- import path82 from "node:path";
50163
+ import { randomUUID as randomUUID20 } from "node:crypto";
50164
+ import { appendFile as appendFile2, lstat as lstat26, mkdir as mkdir22, readdir as readdir17, readFile as readFile42, realpath as realpath14, rename as rename7, rm as rm10, writeFile as writeFile8 } from "node:fs/promises";
50165
+ import path83 from "node:path";
49996
50166
  var fanoutMessageSchema = external_exports.object({
49997
50167
  target: targetSchema,
49998
50168
  child: external_exports.string().regex(/^[a-f0-9]{32}$/),
@@ -50031,12 +50201,12 @@ var FanoutMessages = class {
50031
50201
  if (!root) return [];
50032
50202
  const jobs = [];
50033
50203
  for (const name of (await readdir17(root)).slice(0, 1024)) {
50034
- const directory = path82.join(root, name);
50204
+ const directory = path83.join(root, name);
50035
50205
  try {
50036
- if (!(await lstat25(directory)).isDirectory() || await realpath14(directory) !== directory) continue;
50037
- const file3 = path82.join(directory, "manifest.json"), info = await lstat25(file3);
50206
+ if (!(await lstat26(directory)).isDirectory() || await realpath14(directory) !== directory) continue;
50207
+ const file3 = path83.join(directory, "manifest.json"), info = await lstat26(file3);
50038
50208
  if (!info.isFile() || info.isSymbolicLink() || info.size > 65536) continue;
50039
- const manifest = manifestSchema.parse(JSON.parse(await readFile41(file3, "utf8")));
50209
+ const manifest = manifestSchema.parse(JSON.parse(await readFile42(file3, "utf8")));
50040
50210
  if (manifest.id === name) jobs.push({ directory, manifest });
50041
50211
  } catch {
50042
50212
  }
@@ -50058,10 +50228,10 @@ var FanoutMessages = class {
50058
50228
  const data = fanoutMessageSchema.parse(input2);
50059
50229
  const job = await this.selected(data.target, data.child);
50060
50230
  const directory = await this.messageDirectory(job);
50061
- const message = { id: randomUUID19(), text: data.text, status: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString() };
50231
+ const message = { id: randomUUID20(), text: data.text, status: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString() };
50062
50232
  const pending = (await this.records(job)).filter((row) => row.message.status === "queued");
50063
50233
  if (pending.length >= 32) throw new BridgeError(429, "This worker already has 32 queued messages.");
50064
- const file3 = path82.join(directory, `${message.createdAt.replace(/[:.]/g, "-")}-${message.id}.queued.json`);
50234
+ const file3 = path83.join(directory, `${message.createdAt.replace(/[:.]/g, "-")}-${message.id}.queued.json`);
50065
50235
  await atomic(file3, JSON.stringify(message));
50066
50236
  await this.drain(job);
50067
50237
  const fresh = (await this.records(job)).find((row) => row.message.id === message.id)?.message;
@@ -50082,14 +50252,14 @@ var FanoutMessages = class {
50082
50252
  return { messages: (await this.records(job)).map((row) => row.message) };
50083
50253
  }
50084
50254
  async messageDirectory(job) {
50085
- const directory = path82.join(job.directory, "messages");
50086
- await mkdir21(directory, { recursive: true, mode: 448 });
50255
+ const directory = path83.join(job.directory, "messages");
50256
+ await mkdir22(directory, { recursive: true, mode: 448 });
50087
50257
  if (await realpath14(directory) !== directory) throw new BridgeError(400, "Invalid worker message directory.");
50088
50258
  return directory;
50089
50259
  }
50090
50260
  async records(job) {
50091
- const directory = path82.join(job.directory, "messages");
50092
- const info = await lstat25(directory).catch(() => void 0);
50261
+ const directory = path83.join(job.directory, "messages");
50262
+ const info = await lstat26(directory).catch(() => void 0);
50093
50263
  if (!info) return [];
50094
50264
  if (!info.isDirectory() || info.isSymbolicLink() || await realpath14(directory) !== directory) {
50095
50265
  throw new BridgeError(400, "Invalid worker message directory.");
@@ -50097,10 +50267,10 @@ var FanoutMessages = class {
50097
50267
  const rows = [];
50098
50268
  for (const name of (await readdir17(directory)).sort().slice(-512)) {
50099
50269
  if (!/^[0-9TZ-]+-[a-f0-9-]+\.(queued|sent)\.json$/.test(name)) continue;
50100
- const file3 = path82.join(directory, name), info2 = await lstat25(file3);
50270
+ const file3 = path83.join(directory, name), info2 = await lstat26(file3);
50101
50271
  if (!info2.isFile() || info2.isSymbolicLink() || info2.size > 262144) continue;
50102
50272
  try {
50103
- rows.push({ file: file3, message: receiptSchema2.parse(JSON.parse(await readFile41(file3, "utf8"))) });
50273
+ rows.push({ file: file3, message: receiptSchema2.parse(JSON.parse(await readFile42(file3, "utf8"))) });
50104
50274
  } catch {
50105
50275
  }
50106
50276
  }
@@ -50120,9 +50290,9 @@ var FanoutMessages = class {
50120
50290
  }
50121
50291
  }
50122
50292
  async drain(job) {
50123
- const lock = path82.join(job.directory, "message-lock");
50293
+ const lock = path83.join(job.directory, "message-lock");
50124
50294
  try {
50125
- await mkdir21(lock, { mode: 448 });
50295
+ await mkdir22(lock, { mode: 448 });
50126
50296
  } catch {
50127
50297
  return;
50128
50298
  }
@@ -50136,27 +50306,27 @@ var FanoutMessages = class {
50136
50306
  const next = (await this.records(fresh)).find((row) => row.message.status === "queued");
50137
50307
  if (!next) return;
50138
50308
  pending = next;
50139
- if (!(await lstat25(fresh.manifest.worktree)).isDirectory()) throw new BridgeError(409, "The worker's original worktree is unavailable.");
50309
+ if (!(await lstat26(fresh.manifest.worktree)).isDirectory()) throw new BridgeError(409, "The worker's original worktree is unavailable.");
50140
50310
  for (const name of [fresh.manifest.eventLog, "events.jsonl", "stderr.log", "final.txt", "exit.txt", "blocked.json", "prompt.txt"]) {
50141
- const info = await lstat25(path82.join(fresh.directory, name)).catch(() => void 0);
50311
+ const info = await lstat26(path83.join(fresh.directory, name)).catch(() => void 0);
50142
50312
  if (info && (!info.isFile() || info.isSymbolicLink())) throw new BridgeError(400, "Invalid worker output file.");
50143
50313
  }
50144
- const round = path82.join(fresh.directory, "rounds");
50145
- await mkdir21(round, { recursive: true, mode: 448 });
50314
+ const round = path83.join(fresh.directory, "rounds");
50315
+ await mkdir22(round, { recursive: true, mode: 448 });
50146
50316
  if (await realpath14(round) !== round) throw new BridgeError(400, "Invalid worker round directory.");
50147
- const roundDir = path82.join(round, next.message.id);
50148
- await mkdir21(roundDir, { mode: 448 });
50149
- await writeFile7(path82.join(roundDir, "prompt.txt"), next.message.text, { mode: 384 });
50317
+ const roundDir = path83.join(round, next.message.id);
50318
+ await mkdir22(roundDir, { mode: 448 });
50319
+ await writeFile8(path83.join(roundDir, "prompt.txt"), next.message.text, { mode: 384 });
50150
50320
  for (const name of ["stderr.log", "final.txt", "exit.txt", "blocked.json", "prompt.txt"]) {
50151
- await rename6(path82.join(fresh.directory, name), path82.join(roundDir, `previous-${name}`)).catch((error62) => {
50321
+ await rename7(path83.join(fresh.directory, name), path83.join(roundDir, `previous-${name}`)).catch((error62) => {
50152
50322
  if (error62.code !== "ENOENT") throw error62;
50153
50323
  });
50154
50324
  }
50155
- await writeFile7(path82.join(fresh.directory, "prompt.txt"), next.message.text, { mode: 384 });
50325
+ await writeFile8(path83.join(fresh.directory, "prompt.txt"), next.message.text, { mode: 384 });
50156
50326
  const sentFile = next.file.replace(/\.queued\.json$/, ".sent.json");
50157
50327
  const message = { ...next.message, status: "running" };
50158
50328
  await atomic(next.file, JSON.stringify(message));
50159
- await rename6(next.file, sentFile);
50329
+ await rename7(next.file, sentFile);
50160
50330
  pending = { file: sentFile, message };
50161
50331
  const now = (/* @__PURE__ */ new Date()).toISOString();
50162
50332
  const manifest = {
@@ -50168,9 +50338,9 @@ var FanoutMessages = class {
50168
50338
  finishedAt: void 0,
50169
50339
  exitCode: void 0
50170
50340
  };
50171
- await atomic(path82.join(fresh.directory, "manifest.json"), JSON.stringify(manifest));
50341
+ await atomic(path83.join(fresh.directory, "manifest.json"), JSON.stringify(manifest));
50172
50342
  started = manifest;
50173
- await appendFile2(path82.join(fresh.directory, manifest.eventLog), JSON.stringify({
50343
+ await appendFile2(path83.join(fresh.directory, manifest.eventLog), JSON.stringify({
50174
50344
  type: "phren/fanout-message",
50175
50345
  timestamp: now,
50176
50346
  id: message.id,
@@ -50194,7 +50364,7 @@ var FanoutMessages = class {
50194
50364
  await atomic(sentFile, JSON.stringify({ ...message, status: code === 0 ? "completed" : "failed" }));
50195
50365
  }).catch(async () => {
50196
50366
  await atomic(sentFile, JSON.stringify({ ...message, status: "failed" }));
50197
- await atomic(path82.join(fresh.directory, "manifest.json"), JSON.stringify({ ...manifest, status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString() }));
50367
+ await atomic(path83.join(fresh.directory, "manifest.json"), JSON.stringify({ ...manifest, status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString() }));
50198
50368
  }).finally(async () => {
50199
50369
  await rm10(lock, { recursive: true, force: true });
50200
50370
  }).catch(() => {
@@ -50202,8 +50372,8 @@ var FanoutMessages = class {
50202
50372
  } catch (error62) {
50203
50373
  if (!pending) throw error62;
50204
50374
  await atomic(pending.file, JSON.stringify({ ...pending.message, status: "failed" }));
50205
- if (pending.file.endsWith(".queued.json")) await rename6(pending.file, pending.file.replace(/\.queued\.json$/, ".sent.json"));
50206
- if (started) await atomic(path82.join(job.directory, "manifest.json"), JSON.stringify({
50375
+ if (pending.file.endsWith(".queued.json")) await rename7(pending.file, pending.file.replace(/\.queued\.json$/, ".sent.json"));
50376
+ if (started) await atomic(path83.join(job.directory, "manifest.json"), JSON.stringify({
50207
50377
  ...started,
50208
50378
  status: "failed",
50209
50379
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -50216,12 +50386,12 @@ var FanoutMessages = class {
50216
50386
 
50217
50387
  // src/bridge/server.ts
50218
50388
  init_wrapper();
50219
- import { randomUUID as randomUUID25 } from "node:crypto";
50220
- import { chmod as chmod6, lstat as lstat30, mkdir as mkdir29, readFile as readFile50, rm as rm15, unlink as unlink9, writeFile as writeFile11 } from "node:fs/promises";
50221
- import { readFileSync as readFileSync36 } from "node:fs";
50389
+ import { randomUUID as randomUUID26 } from "node:crypto";
50390
+ import { chmod as chmod6, lstat as lstat31, mkdir as mkdir30, readFile as readFile51, rm as rm15, unlink as unlink10, writeFile as writeFile12 } from "node:fs/promises";
50391
+ import { readFileSync as readFileSync37 } from "node:fs";
50222
50392
  import { createServer as createServer3 } from "node:http";
50223
50393
  import { cpus as cpus2, hostname as hostname12, loadavg as loadavg2 } from "node:os";
50224
- import path110 from "node:path";
50394
+ import path112 from "node:path";
50225
50395
 
50226
50396
  // src/bridge/speech-transcribe.ts
50227
50397
  init_wrapper();
@@ -50336,8 +50506,8 @@ function relayTranscription(client, query, options = {}) {
50336
50506
 
50337
50507
  // src/bridge/activity.ts
50338
50508
  init_protocol();
50339
- import { appendFile as appendFile3, mkdir as mkdir22, readFile as readFile42, rename as rename7, stat as stat23 } from "node:fs/promises";
50340
- import path83 from "node:path";
50509
+ import { appendFile as appendFile3, mkdir as mkdir23, readFile as readFile43, rename as rename8, stat as stat23 } from "node:fs/promises";
50510
+ import path84 from "node:path";
50341
50511
  var ActivityJournal = class {
50342
50512
  pending = Promise.resolve();
50343
50513
  previous = /* @__PURE__ */ new Map();
@@ -50364,16 +50534,16 @@ var ActivityJournal = class {
50364
50534
  });
50365
50535
  }
50366
50536
  if (!changes.length) return;
50367
- const root = bridgeRoot(), file3 = path83.join(root, "activity.jsonl");
50368
- await mkdir22(root, { recursive: true, mode: 448 });
50369
- if ((await stat23(file3).catch(() => null))?.size && (await stat23(file3)).size > 2097152) await rename7(file3, file3 + ".previous");
50537
+ const root = bridgeRoot(), file3 = path84.join(root, "activity.jsonl");
50538
+ await mkdir23(root, { recursive: true, mode: 448 });
50539
+ if ((await stat23(file3).catch(() => null))?.size && (await stat23(file3)).size > 2097152) await rename8(file3, file3 + ".previous");
50370
50540
  await appendFile3(file3, changes.map((row) => JSON.stringify(row)).join("\n") + "\n", { mode: 384 });
50371
50541
  if (this.previous.size > 4096) this.previous.clear();
50372
50542
  });
50373
50543
  return this.pending;
50374
50544
  }
50375
50545
  async recent() {
50376
- const text4 = await readFile42(path83.join(bridgeRoot(), "activity.jsonl"), "utf8").catch(() => "");
50546
+ const text4 = await readFile43(path84.join(bridgeRoot(), "activity.jsonl"), "utf8").catch(() => "");
50377
50547
  return text4.trim().split("\n").slice(-500).flatMap((line) => {
50378
50548
  try {
50379
50549
  return [JSON.parse(line)];
@@ -50392,7 +50562,7 @@ init_changes();
50392
50562
  init_store_registry();
50393
50563
  import { rm as rm11 } from "node:fs/promises";
50394
50564
  import * as fs27 from "node:fs";
50395
- import * as path85 from "node:path";
50565
+ import * as path86 from "node:path";
50396
50566
  init_zod();
50397
50567
  init_shared();
50398
50568
 
@@ -50400,7 +50570,7 @@ init_shared();
50400
50570
  import { execFileSync as execFileSync5 } from "node:child_process";
50401
50571
  import * as fs26 from "node:fs";
50402
50572
  import { homedir as homedir18 } from "node:os";
50403
- import * as path84 from "node:path";
50573
+ import * as path85 from "node:path";
50404
50574
  import { fileURLToPath as fileURLToPath5, pathToFileURL } from "node:url";
50405
50575
  var CODE_PACKAGE_HINT = "phren code needs @phren/code: run phren modules enable code";
50406
50576
  var loaded;
@@ -50409,13 +50579,13 @@ function loadedFrom() {
50409
50579
  return resolvedFrom;
50410
50580
  }
50411
50581
  function bridgeRoot2() {
50412
- return process.env.PHREN_BRIDGE_HOME || path84.join(homedir18(), ".local/share/phren/bridge");
50582
+ return process.env.PHREN_BRIDGE_HOME || path85.join(homedir18(), ".local/share/phren/bridge");
50413
50583
  }
50414
- var EXTRA_PATH = [path84.join(homedir18(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
50584
+ var EXTRA_PATH = [path85.join(homedir18(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
50415
50585
  function npmPath() {
50416
- const entries2 = (process.env.PATH ?? "").split(path84.delimiter).filter(Boolean);
50586
+ const entries2 = (process.env.PATH ?? "").split(path85.delimiter).filter(Boolean);
50417
50587
  for (const entry2 of EXTRA_PATH) if (!entries2.includes(entry2) && fs26.existsSync(entry2)) entries2.push(entry2);
50418
- return entries2.join(path84.delimiter);
50588
+ return entries2.join(path85.delimiter);
50419
50589
  }
50420
50590
  function npm(args, options) {
50421
50591
  const env = { ...process.env, PATH: npmPath() };
@@ -50423,11 +50593,11 @@ function npm(args, options) {
50423
50593
  return String(execFileSync5("npm.cmd", args.map((arg) => `"${arg}"`), { ...options, env, shell: true }) ?? "");
50424
50594
  }
50425
50595
  function packageEntry(directory) {
50426
- const manifest = JSON.parse(fs26.readFileSync(path84.join(directory, "package.json"), "utf8"));
50596
+ const manifest = JSON.parse(fs26.readFileSync(path85.join(directory, "package.json"), "utf8"));
50427
50597
  const exported = typeof manifest.exports === "object" && manifest.exports !== null && "." in manifest.exports ? manifest.exports["."] : manifest.exports;
50428
50598
  const nested = typeof exported === "object" && exported !== null ? exported.default ?? exported.import : exported;
50429
50599
  for (const candidate of [nested, manifest.module, manifest.main, "index.js", "index.mjs"]) {
50430
- if (typeof candidate === "string") return path84.join(directory, candidate);
50600
+ if (typeof candidate === "string") return path85.join(directory, candidate);
50431
50601
  }
50432
50602
  throw new Error(`@phren/code has no entry point in ${directory}.`);
50433
50603
  }
@@ -50437,7 +50607,7 @@ async function importDirectory(directory) {
50437
50607
  function globalPackageDirectory() {
50438
50608
  try {
50439
50609
  const root = npm(["root", "-g"], { encoding: "utf8", timeout: 1e4 }).trim();
50440
- return root ? path84.join(root, "@phren", "code") : void 0;
50610
+ return root ? path85.join(root, "@phren", "code") : void 0;
50441
50611
  } catch {
50442
50612
  return void 0;
50443
50613
  }
@@ -50446,13 +50616,13 @@ async function loadCodePackage(store) {
50446
50616
  if (loaded) return loaded;
50447
50617
  const candidates = [];
50448
50618
  if (process.env.PHREN_CODE_PACKAGE) candidates.push(process.env.PHREN_CODE_PACKAGE);
50449
- candidates.push(path84.join(bridgeRoot2(), "node_modules", "@phren", "code"));
50619
+ candidates.push(path85.join(bridgeRoot2(), "node_modules", "@phren", "code"));
50450
50620
  const root = store || process.env.PHREN_PATH;
50451
- if (root) candidates.push(path84.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
50621
+ if (root) candidates.push(path85.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
50452
50622
  const workspace = workspaceCodeDirectory();
50453
50623
  if (workspace && builtEntryExists(workspace)) candidates.push(workspace);
50454
50624
  for (const directory of candidates) {
50455
- if (!fs26.existsSync(path84.join(directory, "package.json"))) continue;
50625
+ if (!fs26.existsSync(path85.join(directory, "package.json"))) continue;
50456
50626
  try {
50457
50627
  loaded = await importDirectory(directory);
50458
50628
  resolvedFrom = directory;
@@ -50468,7 +50638,7 @@ async function loadCodePackage(store) {
50468
50638
  if (error62.code !== "ERR_MODULE_NOT_FOUND") throw error62;
50469
50639
  }
50470
50640
  const global = globalPackageDirectory();
50471
- if (global && fs26.existsSync(path84.join(global, "package.json"))) {
50641
+ if (global && fs26.existsSync(path85.join(global, "package.json"))) {
50472
50642
  try {
50473
50643
  loaded = await importDirectory(global);
50474
50644
  resolvedFrom = global;
@@ -50479,11 +50649,11 @@ async function loadCodePackage(store) {
50479
50649
  return void 0;
50480
50650
  }
50481
50651
  function workspaceCodeDirectory() {
50482
- let directory = path84.dirname(fileURLToPath5(import.meta.url));
50652
+ let directory = path85.dirname(fileURLToPath5(import.meta.url));
50483
50653
  for (let depth = 0; depth < 8; depth++) {
50484
- const candidate = path84.join(directory, "packages", "code");
50485
- if (fs26.existsSync(path84.join(candidate, "package.json"))) return candidate;
50486
- const parent = path84.dirname(directory);
50654
+ const candidate = path85.join(directory, "packages", "code");
50655
+ if (fs26.existsSync(path85.join(candidate, "package.json"))) return candidate;
50656
+ const parent = path85.dirname(directory);
50487
50657
  if (parent === directory) break;
50488
50658
  directory = parent;
50489
50659
  }
@@ -50498,7 +50668,7 @@ function builtEntryExists(directory) {
50498
50668
  }
50499
50669
  function codePackageHint(store) {
50500
50670
  const root = store || process.env.PHREN_PATH;
50501
- const linked = root && path84.join(root, ".runtime", "packages", "node_modules", "@phren", "code");
50671
+ const linked = root && path85.join(root, ".runtime", "packages", "node_modules", "@phren", "code");
50502
50672
  const workspace = workspaceCodeDirectory();
50503
50673
  let workspaceLink;
50504
50674
  try {
@@ -50506,7 +50676,7 @@ function codePackageHint(store) {
50506
50676
  } catch {
50507
50677
  }
50508
50678
  for (const directory of [workspace, workspaceLink]) {
50509
- if (!directory || !fs26.existsSync(path84.join(directory, "package.json")) || builtEntryExists(directory)) continue;
50679
+ if (!directory || !fs26.existsSync(path85.join(directory, "package.json")) || builtEntryExists(directory)) continue;
50510
50680
  return `${CODE_PACKAGE_HINT}. @phren/code at ${directory} has no built entry. From the source checkout root run: pnpm --filter @phren/code build`;
50511
50681
  }
50512
50682
  return `${CODE_PACKAGE_HINT}. For a source checkout, from its root run pnpm --filter @phren/code build, then node packages/cli/dist/index.js modules enable code and restart the Hook.`;
@@ -50542,7 +50712,7 @@ var projectSchema = external_exports.string().min(1).max(100).refine((value2) =>
50542
50712
  var querySchema = external_exports.string().max(500);
50543
50713
  var symbolSchema = external_exports.string().min(1).max(4600);
50544
50714
  var pathSchema = external_exports.string().min(1).max(4096).refine((value2) => !value2.includes("\0") && !value2.split("/").includes(".."), "Choose a valid file path.");
50545
- var relativePathSchema = pathSchema.refine((value2) => !path85.isAbsolute(value2) && !path85.win32.isAbsolute(value2) && !value2.includes("\\") && !value2.split("/").some((part) => part === "." || part === ""));
50715
+ var relativePathSchema = pathSchema.refine((value2) => !path86.isAbsolute(value2) && !path86.win32.isAbsolute(value2) && !value2.includes("\\") && !value2.split("/").some((part) => part === "." || part === ""));
50546
50716
  var optionalPath = (value2) => value2 ? relativePathSchema.parse(value2) : void 0;
50547
50717
  var offsetSchema = external_exports.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
50548
50718
  var kindSchema = external_exports.enum(KIND_VALUES);
@@ -50630,9 +50800,9 @@ var CodeRoutes = class {
50630
50800
  };
50631
50801
  const midnight = new Date(now);
50632
50802
  midnight.setHours(0, 0, 0, 0);
50633
- const dir = path85.join(bridgeRoot(), "changes");
50803
+ const dir = path86.join(bridgeRoot(), "changes");
50634
50804
  const logs = fs27.existsSync(dir) ? fs27.readdirSync(dir).filter((name) => name.endsWith(".jsonl")) : [];
50635
- const today = logs.map((name) => ({ file: path85.join(dir, name), at: fs27.statSync(path85.join(dir, name)).mtimeMs })).filter((entry2) => entry2.at >= midnight.getTime()).sort((a, b) => b.at - a.at);
50805
+ const today = logs.map((name) => ({ file: path86.join(dir, name), at: fs27.statSync(path86.join(dir, name)).mtimeMs })).filter((entry2) => entry2.at >= midnight.getTime()).sort((a, b) => b.at - a.at);
50636
50806
  for (const log2 of today) {
50637
50807
  for (const line of fs27.readFileSync(log2.file, "utf8").split("\n")) {
50638
50808
  if (!line.trim()) continue;
@@ -50693,7 +50863,7 @@ var CodeRoutes = class {
50693
50863
  for (const file3 of untracked) {
50694
50864
  let count2 = 0;
50695
50865
  try {
50696
- count2 = fs27.readFileSync(path85.join(root, file3), "utf8").split("\n").length;
50866
+ count2 = fs27.readFileSync(path86.join(root, file3), "utf8").split("\n").length;
50697
50867
  } catch {
50698
50868
  continue;
50699
50869
  }
@@ -50723,7 +50893,7 @@ var CodeRoutes = class {
50723
50893
  const project = projectSchema.parse(projectValue ?? "");
50724
50894
  const { codeDatabasePath } = await requireCodePackage(this.store);
50725
50895
  const file3 = codeDatabasePath(this.store, project);
50726
- await Promise.all([file3, `${file3}-journal`, `${file3}-wal`, `${file3}-shm`].map((path112) => rm11(path112, { force: true })));
50896
+ await Promise.all([file3, `${file3}-journal`, `${file3}-wal`, `${file3}-shm`].map((path114) => rm11(path114, { force: true })));
50727
50897
  return { project, disabled: true };
50728
50898
  }
50729
50899
  async reindex(projectValue) {
@@ -50757,7 +50927,7 @@ var CodeRoutes = class {
50757
50927
  } catch {
50758
50928
  throw new BridgeError(400, "Choose valid paths.");
50759
50929
  }
50760
- const paths = external_exports.array(pathSchema.refine((value2) => !path85.isAbsolute(value2) && !path85.win32.isAbsolute(value2) && !value2.split(/[\\/]/).includes(".."))).min(1).max(200).parse(raw);
50930
+ const paths = external_exports.array(pathSchema.refine((value2) => !path86.isAbsolute(value2) && !path86.win32.isAbsolute(value2) && !value2.split(/[\\/]/).includes(".."))).min(1).max(200).parse(raw);
50761
50931
  const result = await (await requireCodePackage(this.store)).outlineSummary(this.store, project, [...new Set(paths)]);
50762
50932
  if (!result.available) throw noIndex(project);
50763
50933
  return { project, entries: result.value };
@@ -50832,7 +51002,7 @@ var CodeReindexer = class {
50832
51002
  const { codeDatabasePath, resolveRepoRoot } = await requireCodePackage(this.store);
50833
51003
  const result = [];
50834
51004
  for (const directory of getProjectDirs(this.store)) {
50835
- const project = path85.basename(directory);
51005
+ const project = path86.basename(directory);
50836
51006
  if (!fs27.existsSync(codeDatabasePath(this.store, project))) continue;
50837
51007
  try {
50838
51008
  result.push({ project, root: fs27.realpathSync(resolveRepoRoot(this.store, project)) });
@@ -50874,13 +51044,13 @@ var CodeReindexer = class {
50874
51044
  };
50875
51045
  function readHead(root) {
50876
51046
  try {
50877
- const dotGit = path85.join(root, ".git");
51047
+ const dotGit = path86.join(root, ".git");
50878
51048
  const gitDirectory2 = fs27.statSync(dotGit).isDirectory() ? dotGit : (() => {
50879
51049
  const match = /^gitdir:\s*(.+)$/m.exec(fs27.readFileSync(dotGit, "utf8"));
50880
- return match ? path85.resolve(root, match[1]) : void 0;
51050
+ return match ? path86.resolve(root, match[1]) : void 0;
50881
51051
  })();
50882
51052
  if (!gitDirectory2) return void 0;
50883
- return fs27.readFileSync(path85.join(gitDirectory2, "HEAD"), "utf8").trim();
51053
+ return fs27.readFileSync(path86.join(gitDirectory2, "HEAD"), "utf8").trim();
50884
51054
  } catch {
50885
51055
  return void 0;
50886
51056
  }
@@ -50890,7 +51060,7 @@ function readHead(root) {
50890
51060
  init_herdr();
50891
51061
  init_protocol();
50892
51062
  init_transcripts();
50893
- import { open as open17 } from "node:fs/promises";
51063
+ import { open as open18 } from "node:fs/promises";
50894
51064
  import { constants as constants3 } from "node:fs";
50895
51065
  var MAX_TAIL_BYTES = 262144;
50896
51066
  var MAX_SESSIONS = 32;
@@ -50923,7 +51093,7 @@ function codexContext(tail2, startsAtBeginning) {
50923
51093
  var ContextUsageReader = class {
50924
51094
  cache = /* @__PURE__ */ new Map();
50925
51095
  async read(file3, session) {
50926
- const handle = await open17(file3, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
51096
+ const handle = await open18(file3, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
50927
51097
  try {
50928
51098
  const metadata = await handle.stat();
50929
51099
  if (!metadata.isFile()) return void 0;
@@ -51029,8 +51199,8 @@ init_transcript_index();
51029
51199
  init_codex_question_reply();
51030
51200
  import { execFile as execFile16 } from "node:child_process";
51031
51201
  import { createHash as createHash24 } from "node:crypto";
51032
- import { mkdir as mkdir23, open as open18, stat as stat24, readFile as readFile43, writeFile as writeFile8 } from "node:fs/promises";
51033
- import path86 from "node:path";
51202
+ import { mkdir as mkdir24, open as open19, stat as stat24, readFile as readFile44, writeFile as writeFile9 } from "node:fs/promises";
51203
+ import path87 from "node:path";
51034
51204
  import { promisify as promisify15 } from "node:util";
51035
51205
  var exec15 = promisify15(execFile16);
51036
51206
  var text3 = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
@@ -51257,7 +51427,7 @@ var CodexQuestions = class {
51257
51427
  }
51258
51428
  return Promise.all((pending ?? []).map(async (p) => {
51259
51429
  const key3 = createHash24("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
51260
- const submitted = await readFile43(path86.join(bridgeRoot(), "question-replies", key3), "utf8").then((value2) => value2 === "submitted").catch(() => false);
51430
+ const submitted = await readFile44(path87.join(bridgeRoot(), "question-replies", key3), "utf8").then((value2) => value2 === "submitted").catch(() => false);
51261
51431
  return { toolUseId: p.id, isAsync: true, submitted, questions: asPrompt(p.questions) };
51262
51432
  })).then((prompts) => prompts.filter((p) => !p.submitted));
51263
51433
  }
@@ -51290,11 +51460,11 @@ var CodexQuestions = class {
51290
51460
  ] : [];
51291
51461
  const pane = await validateTarget(target);
51292
51462
  if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
51293
- const directory = path86.join(bridgeRoot(), "question-replies");
51294
- await mkdir23(directory, { recursive: true, mode: 448 });
51463
+ const directory = path87.join(bridgeRoot(), "question-replies");
51464
+ await mkdir24(directory, { recursive: true, mode: 448 });
51295
51465
  const key3 = createHash24("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
51296
- const receiptPath = path86.join(directory, key3);
51297
- const receipt = await open18(receiptPath, "wx", 384).catch((error62) => {
51466
+ const receiptPath = path87.join(directory, key3);
51467
+ const receipt = await open19(receiptPath, "wx", 384).catch((error62) => {
51298
51468
  if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
51299
51469
  throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
51300
51470
  });
@@ -51302,7 +51472,7 @@ var CodexQuestions = class {
51302
51472
  try {
51303
51473
  if (entry2) await this.served.steer(entry2, reply, extra);
51304
51474
  else await exec15(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8e3, maxBuffer: 65536 });
51305
- await writeFile8(receiptPath, "submitted", { mode: 384 });
51475
+ await writeFile9(receiptPath, "submitted", { mode: 384 });
51306
51476
  } catch {
51307
51477
  throw new BridgeError(409, "Codex did not confirm the answer. Check the conversation; Phren has not retried it.");
51308
51478
  }
@@ -51318,7 +51488,50 @@ init_transcripts();
51318
51488
 
51319
51489
  // src/bridge/settings-switch.ts
51320
51490
  init_zod();
51321
- import { open as open19, stat as stat25 } from "node:fs/promises";
51491
+ import { open as open20, stat as stat25 } from "node:fs/promises";
51492
+
51493
+ // src/bridge/claude-suggestion.ts
51494
+ init_terminal_text();
51495
+ var MAX_SUGGESTION = 500;
51496
+ var rule = (line) => /^[─━═]{3,}/.test(line.trim());
51497
+ var PLACEHOLDERS = [/^Try ".*"$/, /^Press (?:up|Enter) to /, /^Message @.*…$/];
51498
+ function claudeSuggestion(screen) {
51499
+ const lines = screen.split("\n").map((line) => line.replace(/\r$/, ""));
51500
+ for (let index2 = lines.length - 2; index2 > 0; index2--) {
51501
+ const plain2 = stripTerminal(lines[index2]);
51502
+ if (!/^\s*❯/.test(plain2)) continue;
51503
+ if (!rule(stripTerminal(lines[index2 - 1])) || !rule(stripTerminal(lines[index2 + 1]))) return void 0;
51504
+ const text4 = dimText(lines[index2]);
51505
+ if (!text4 || text4.endsWith("\u2026") || text4.length > MAX_SUGGESTION || PLACEHOLDERS.some((pattern) => pattern.test(text4))) return void 0;
51506
+ return text4;
51507
+ }
51508
+ return void 0;
51509
+ }
51510
+ function dimText(line) {
51511
+ let dim = false, prompt = false, text4 = "";
51512
+ for (const token of line.match(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|[^\x1b]/gu) ?? []) {
51513
+ if (token.startsWith("\x1B")) {
51514
+ if (!token.startsWith("\x1B[") || !token.endsWith("m")) continue;
51515
+ const codes = (token.slice(2, -1) || "0").split(/[;:]/).map(Number);
51516
+ for (let i = 0; i < codes.length; i++) {
51517
+ const code = codes[i];
51518
+ if (code === 38 || code === 48 || code === 58) {
51519
+ i += codes[i + 1] === 5 ? 2 : codes[i + 1] === 2 ? 4 : 0;
51520
+ continue;
51521
+ }
51522
+ if (code === 0 || code === 22) dim = false;
51523
+ else if (code === 2) dim = true;
51524
+ }
51525
+ } else if (!prompt) {
51526
+ if (token === "\u276F") prompt = true;
51527
+ } else if (!token.trim()) text4 += " ";
51528
+ else if (!dim) return "";
51529
+ else text4 += token;
51530
+ }
51531
+ return text4.replace(/\s+/g, " ").trim();
51532
+ }
51533
+
51534
+ // src/bridge/settings-switch.ts
51322
51535
  init_codex_servers();
51323
51536
  init_herdr();
51324
51537
  init_limits();
@@ -51375,16 +51588,22 @@ var ClaudeSettingsReader = class {
51375
51588
  this.cache.set(key3, entry2);
51376
51589
  if (Date.now() - entry2.at >= this.every) {
51377
51590
  entry2.at = Date.now();
51378
- entry2.mode = await this.hooks.paneLines(target).then(claudeFooterMode, () => entry2.mode);
51591
+ const screen = await this.hooks.paneAnsi(target).catch(() => void 0);
51592
+ if (screen !== void 0) entry2.mode = claudeFooterMode(screen);
51593
+ entry2.suggestion = screen === void 0 ? void 0 : claudeSuggestion(screen);
51379
51594
  if (entry2.mode === "bypassPermissions") entry2.bypass = true;
51380
51595
  while (this.cache.size > 64) this.cache.delete(this.cache.keys().next().value);
51381
51596
  }
51382
51597
  const phone = entry2.mode ? CLAUDE_MODES[entry2.mode] : void 0;
51383
- return { bypass: entry2.bypass, ...phone ? { state: phone === "plan" ? { plan: true } : { permissionMode: phone, plan: false } } : {} };
51598
+ return {
51599
+ bypass: entry2.bypass,
51600
+ ...phone ? { state: phone === "plan" ? { plan: true } : { permissionMode: phone, plan: false } } : {},
51601
+ ...entry2.suggestion ? { suggestion: { text: entry2.suggestion, readAt: entry2.at } } : {}
51602
+ };
51384
51603
  }
51385
51604
  };
51386
51605
  async function commandOutput2(file3, from) {
51387
- const handle = await open19(file3, "r");
51606
+ const handle = await open20(file3, "r");
51388
51607
  try {
51389
51608
  const { size } = await handle.stat(), length = Math.min(Math.max(size - from, 0), 1048576), buffer = Buffer.alloc(length);
51390
51609
  await handle.read(buffer, 0, length, from);
@@ -51414,14 +51633,15 @@ var SettingsSwitcher = class {
51414
51633
  wait;
51415
51634
  active = /* @__PURE__ */ new Set();
51416
51635
  reader;
51417
- /** A Claude pane's footer-read settings and capabilities for the stream. */
51636
+ /** A Claude pane's footer-read settings and capabilities for the stream,
51637
+ * with the suggested next prompt its input box shows. */
51418
51638
  async streamSettings(target, terminal2, codexServed) {
51419
51639
  if (target.source !== "claude") {
51420
51640
  const settings = settingsCapabilities(target.source, codexServed);
51421
51641
  return settings ? { settings } : {};
51422
51642
  }
51423
- const { state, bypass } = await this.reader.read(target, terminal2);
51424
- return { settings: settingsCapabilities("claude", false, bypass), ...state ? { settingsState: state } : {} };
51643
+ const { state, bypass, suggestion } = await this.reader.read(target, terminal2);
51644
+ return { settings: settingsCapabilities("claude", false, bypass), ...state ? { settingsState: state } : {}, ...suggestion ? { suggestion } : {} };
51425
51645
  }
51426
51646
  key(target) {
51427
51647
  return `${target.server}:${target.pane}`;
@@ -51550,13 +51770,208 @@ var SettingsSwitcher = class {
51550
51770
  // src/bridge/resources.ts
51551
51771
  init_home_paths();
51552
51772
  init_herdr();
51553
- init_limits();
51554
- init_protocol();
51555
51773
  import { execFile as execFile17 } from "node:child_process";
51556
- import { readdir as readdir18, readFile as readFile44, statfs } from "node:fs/promises";
51774
+ import { readdir as readdir18, readFile as readFile45, statfs } from "node:fs/promises";
51557
51775
  import { cpus, loadavg, totalmem, uptime } from "node:os";
51558
- import path87 from "node:path";
51776
+ import path89 from "node:path";
51559
51777
  import { promisify as promisify16 } from "node:util";
51778
+
51779
+ // src/bridge/job-registry.ts
51780
+ init_zod();
51781
+ init_protocol();
51782
+ import { readFileSync as readFileSync29 } from "node:fs";
51783
+ import path88 from "node:path";
51784
+ var paneSchema = external_exports.object({
51785
+ server: external_exports.string().min(1).max(200),
51786
+ workspace: external_exports.string().max(200).optional(),
51787
+ pane: external_exports.string().min(1).max(200),
51788
+ agent: external_exports.string().max(60).optional(),
51789
+ label: external_exports.string().max(200).optional()
51790
+ }).strict();
51791
+ var jobSchema = external_exports.object({
51792
+ /** The worker's process group, once the process table has shown it. */
51793
+ pgid: external_exports.number().int().positive().optional(),
51794
+ /** When the group's leader started (epoch ms), recorded with the pgid, so a
51795
+ * group id the system later reuses for another program is never signalled. */
51796
+ leaderStartedAt: external_exports.number().int().nonnegative().optional(),
51797
+ pane: paneSchema.optional(),
51798
+ session: external_exports.string().min(1).max(200).optional(),
51799
+ agent: external_exports.string().max(60).optional(),
51800
+ label: external_exports.string().max(200).optional(),
51801
+ /** The Harness/executable the Hook started, for display and a reuse check. */
51802
+ command: external_exports.string().min(1).max(500),
51803
+ /** Epoch ms. */
51804
+ startedAt: external_exports.number().int().nonnegative()
51805
+ }).strict();
51806
+ var stateSchema2 = external_exports.object({ version: external_exports.literal(1), jobs: external_exports.array(jobSchema).max(1024) }).strict();
51807
+ var paneKey3 = (pane) => `${pane.server}\0${pane.pane}`;
51808
+ function jobKey(job) {
51809
+ if (job.pane) return `pane:${paneKey3(job.pane)}`;
51810
+ if (job.session) return `session:${job.session}`;
51811
+ if (job.pgid !== void 0) return `pgid:${job.pgid}`;
51812
+ return `command:${job.command}`;
51813
+ }
51814
+ function jobPgids(jobs) {
51815
+ const byPgid = /* @__PURE__ */ new Map();
51816
+ for (const job of jobs) if (job.pgid !== void 0 && !byPgid.has(job.pgid)) byPgid.set(job.pgid, job);
51817
+ return byPgid;
51818
+ }
51819
+ function resolveJobGroups(jobs, rows, owners) {
51820
+ const byPane = /* @__PURE__ */ new Map();
51821
+ for (const row of rows) {
51822
+ const pane = owners.get(row.pid);
51823
+ if (pane && row.pgid > 1 && !byPane.has(paneKey3(pane))) byPane.set(paneKey3(pane), row.pgid);
51824
+ }
51825
+ const leaders = new Map(rows.filter((row) => row.pid === row.pgid && row.startedAt !== void 0).map((row) => [row.pid, Math.round(row.startedAt)]));
51826
+ return jobs.map((job) => {
51827
+ if (job.pgid !== void 0 || !job.pane) return job;
51828
+ const pgid = byPane.get(paneKey3(job.pane));
51829
+ if (pgid === void 0) return job;
51830
+ const leaderStartedAt = leaders.get(pgid);
51831
+ return { ...job, pgid, ...leaderStartedAt !== void 0 ? { leaderStartedAt } : {} };
51832
+ });
51833
+ }
51834
+ var CLEANUP_LEASE_MS = 5 * 6e4;
51835
+ var LEADER_START_TOLERANCE_MS = 3e3;
51836
+ var CLEANUP_RETAIN_MS = 24 * 60 * 6e4;
51837
+ function commandMatches(job, row) {
51838
+ return path88.basename(row.command) === path88.basename(job.command) || row.args.includes(job.command);
51839
+ }
51840
+ function planCleanup(jobs, rows, live, options = {}) {
51841
+ const now = options.now ?? Date.now(), leaseMs = options.leaseMs ?? CLEANUP_LEASE_MS, retainMs = options.retainMs ?? CLEANUP_RETAIN_MS;
51842
+ const self = options.selfPid ?? process.pid;
51843
+ const panesKnown = options.panesKnown ?? true;
51844
+ const byPgid = /* @__PURE__ */ new Map();
51845
+ for (const row of rows) {
51846
+ const list = byPgid.get(row.pgid);
51847
+ if (list) list.push(row);
51848
+ else byPgid.set(row.pgid, [row]);
51849
+ }
51850
+ const ownGroup = rows.find((row) => row.pid === self)?.pgid;
51851
+ const kill = [], keep = [], forget = [];
51852
+ for (const job of jobs) {
51853
+ const kept = (reason2) => keep.push({ job, reason: reason2 });
51854
+ if (!panesKnown) {
51855
+ kept("unknown");
51856
+ continue;
51857
+ }
51858
+ if (job.pgid === void 0) {
51859
+ if (job.pane && !live.has(paneKey3(job.pane)) && now - job.startedAt > leaseMs) forget.push(job);
51860
+ else kept("unresolved");
51861
+ continue;
51862
+ }
51863
+ if (job.pgid <= 1 || job.pgid === ownGroup) {
51864
+ kept("reserved");
51865
+ continue;
51866
+ }
51867
+ if (!job.pane) {
51868
+ kept("no-pane");
51869
+ continue;
51870
+ }
51871
+ if (!options.servers?.has(job.pane.server)) {
51872
+ kept("server-unknown");
51873
+ continue;
51874
+ }
51875
+ if (live.has(paneKey3(job.pane))) {
51876
+ kept("pane-alive");
51877
+ continue;
51878
+ }
51879
+ const group = byPgid.get(job.pgid);
51880
+ if (!group || group.length === 0) {
51881
+ forget.push(job);
51882
+ continue;
51883
+ }
51884
+ if (group.some((row) => row.pid === self)) {
51885
+ kept("self");
51886
+ continue;
51887
+ }
51888
+ if (now - job.startedAt < leaseMs) {
51889
+ kept("lease");
51890
+ continue;
51891
+ }
51892
+ if (!group.some((row) => commandMatches(job, row))) {
51893
+ if (now - job.startedAt > retainMs) forget.push(job);
51894
+ else kept("reused");
51895
+ continue;
51896
+ }
51897
+ const leader = group.find((row) => row.pid === job.pgid);
51898
+ if (leader && (job.leaderStartedAt === void 0 || leader.startedAt === void 0 || Math.abs(leader.startedAt - job.leaderStartedAt) > LEADER_START_TOLERANCE_MS)) {
51899
+ if (now - job.startedAt > retainMs) forget.push(job);
51900
+ else kept("leader-unverified");
51901
+ continue;
51902
+ }
51903
+ kill.push(job);
51904
+ }
51905
+ return { kill, keep, forget };
51906
+ }
51907
+ var defaultFile = () => path88.join(bridgeRoot(), "jobs.json");
51908
+ var JobRegistry = class {
51909
+ constructor(file3 = defaultFile(), now = Date.now) {
51910
+ this.file = file3;
51911
+ this.now = now;
51912
+ }
51913
+ file;
51914
+ now;
51915
+ async list() {
51916
+ try {
51917
+ const parsed = stateSchema2.safeParse(JSON.parse(readFileSync29(this.file, "utf8")));
51918
+ return parsed.success ? parsed.data.jobs : [];
51919
+ } catch {
51920
+ return [];
51921
+ }
51922
+ }
51923
+ async replace(jobs) {
51924
+ await atomicInPrivateDir(this.file, JSON.stringify({ version: 1, jobs }, null, 2) + "\n");
51925
+ }
51926
+ /** Record (or refresh) one worker's job, keyed by its pane. */
51927
+ async register(job) {
51928
+ const entry2 = { ...job, startedAt: job.startedAt ?? this.now() };
51929
+ const key3 = jobKey(entry2);
51930
+ const jobs = await this.list();
51931
+ await this.replace([...jobs.filter((existing) => jobKey(existing) !== key3), entry2].slice(-1024));
51932
+ return entry2;
51933
+ }
51934
+ /** Resolve process groups against the current table and persist any change. */
51935
+ async reconcile(rows, owners) {
51936
+ const jobs = await this.list();
51937
+ const resolved = resolveJobGroups(jobs, rows, owners);
51938
+ if (JSON.stringify(resolved) !== JSON.stringify(jobs)) await this.replace(resolved);
51939
+ return resolved;
51940
+ }
51941
+ /**
51942
+ * End every registered process group that is safe to end (`planCleanup`) and
51943
+ * drop the records that are gone. `live` is the set of pane keys the caller
51944
+ * still sees; a caller whose snapshot failed passes `panesKnown: false`, and
51945
+ * nothing is ended.
51946
+ */
51947
+ async cleanup(rows, live, options = {}) {
51948
+ const jobs = options.owners ? await this.reconcile(rows, options.owners) : await this.list();
51949
+ const plan = planCleanup(jobs, rows, live, { ...options, ...options.now === void 0 ? { now: this.now() } : {} });
51950
+ const signal = options.kill ?? ((pgid, value2) => {
51951
+ process.kill(-pgid, value2);
51952
+ });
51953
+ const killed = [];
51954
+ for (const job of plan.kill) {
51955
+ try {
51956
+ signal(job.pgid, "SIGTERM");
51957
+ killed.push(job.pgid);
51958
+ } catch {
51959
+ }
51960
+ }
51961
+ const done = new Set([...plan.forget, ...plan.kill].map(jobKey));
51962
+ const remaining = jobs.filter((job) => !done.has(jobKey(job)));
51963
+ if (remaining.length !== jobs.length) await this.replace(remaining);
51964
+ return {
51965
+ killed,
51966
+ kept: plan.keep.map(({ job, reason: reason2 }) => ({ ...job.pgid !== void 0 ? { pgid: job.pgid } : {}, reason: reason2 })),
51967
+ forgotten: plan.forget.flatMap((job) => job.pgid !== void 0 ? [job.pgid] : [])
51968
+ };
51969
+ }
51970
+ };
51971
+
51972
+ // src/bridge/resources.ts
51973
+ init_limits();
51974
+ init_protocol();
51560
51975
  var exec16 = promisify16(execFile17);
51561
51976
  var RESOURCES_MAX_AGE_MS = intervalFromEnv("PHREN_RESOURCES_MAX_AGE_MS", 1e4, 1e3, 6e4);
51562
51977
  var LOW_DISK_BYTES = 10 * 1024 ** 3;
@@ -51569,15 +51984,27 @@ function parsePs(stats, args) {
51569
51984
  }
51570
51985
  const rows = [];
51571
51986
  for (const line of stats.split("\n")) {
51572
- const match = /^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
51987
+ const six = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
51988
+ const five = six ? void 0 : /^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
51989
+ const match = six ?? five;
51573
51990
  if (!match) continue;
51574
51991
  const pid = Number(match[1]);
51575
- rows.push({ pid, ppid: Number(match[2]), cpu: Number(match[3]), rssKB: Number(match[4]), command: match[5].trim(), args: argv.get(pid) ?? match[5].trim() });
51992
+ const pgid = six ? Number(match[3]) : 0;
51993
+ const command = (six ? match[6] : match[5]).trim();
51994
+ rows.push({
51995
+ pid,
51996
+ ppid: Number(match[2]),
51997
+ pgid,
51998
+ cpu: Number(six ? match[4] : match[3]),
51999
+ rssKB: Number(six ? match[5] : match[4]),
52000
+ command,
52001
+ args: argv.get(pid) ?? command
52002
+ });
51576
52003
  }
51577
52004
  return rows;
51578
52005
  }
51579
52006
  function heavyKind(row) {
51580
- const base = path87.basename(row.command);
52007
+ const base = path89.basename(row.command);
51581
52008
  const args = row.args;
51582
52009
  if (base === "launchd_sim") {
51583
52010
  return { kind: "simulator", name: /XCTestDevices|Clone \d+ of /.test(args) ? "Simulator test clone" : "Simulator" };
@@ -51597,7 +52024,7 @@ function heavyKind(row) {
51597
52024
  if (base === "claude" || /(?:^|\/)claude\/versions\/\d+\.\d+\.\d+$/.test(row.command)) return { kind: "claude", name: "Claude Code" };
51598
52025
  return void 0;
51599
52026
  }
51600
- function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), limit = 12) {
52027
+ function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), jobs = [], limit = 12) {
51601
52028
  const byPid = new Map(rows.map((row) => [row.pid, row]));
51602
52029
  const kinds = /* @__PURE__ */ new Map();
51603
52030
  for (const row of rows) {
@@ -51606,11 +52033,12 @@ function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), limit = 12) {
51606
52033
  }
51607
52034
  for (const row of rows) {
51608
52035
  const parent = byPid.get(row.ppid);
51609
- if (kinds.get(row.pid)?.kind === "codex" && parent && path87.basename(parent.command) === "node" && kinds.get(parent.pid)?.kind === "codex") {
52036
+ if (kinds.get(row.pid)?.kind === "codex" && parent && path89.basename(parent.command) === "node" && kinds.get(parent.pid)?.kind === "codex") {
51610
52037
  kinds.set(parent.pid, kinds.get(row.pid));
51611
52038
  kinds.delete(row.pid);
51612
52039
  }
51613
52040
  }
52041
+ const jobsByPgid = jobPgids(jobs);
51614
52042
  const totals = /* @__PURE__ */ new Map();
51615
52043
  const busy = /* @__PURE__ */ new Map();
51616
52044
  const claim2 = (row) => {
@@ -51624,20 +52052,30 @@ function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), limit = 12) {
51624
52052
  for (let at = row, hops = 0; at && hops < 64; at = byPid.get(at.ppid), hops++) {
51625
52053
  const pane = owners.get(at.pid);
51626
52054
  if (pane) return pane;
52055
+ const job = jobsByPgid.get(at.pgid);
52056
+ if (job?.pane) return job.pane;
51627
52057
  if (at.ppid === at.pid || at.ppid <= 1) break;
51628
52058
  }
51629
- return void 0;
52059
+ return jobsByPgid.get(row.pgid)?.pane;
51630
52060
  };
52061
+ const trackedRoots = /* @__PURE__ */ new Set();
51631
52062
  for (const row of rows) {
51632
52063
  const root = claim2(row);
52064
+ if (root !== void 0 && jobsByPgid.has(row.pgid)) trackedRoots.add(root);
52065
+ }
52066
+ for (const row of rows) {
52067
+ const root = claim2(row);
52068
+ const tracked = jobsByPgid.has(row.pgid) || root !== void 0 && trackedRoots.has(root);
51633
52069
  if (root === void 0) {
51634
- const name = path87.basename(row.command).slice(0, 60);
51635
- const group = busy.get(name);
51636
- if (!group) busy.set(name, { kind: "busy", name, pid: row.pid, processes: 1, cpuPercent: row.cpu, memoryBytes: row.rssKB * 1024, top: row.cpu, row });
52070
+ const name = path89.basename(row.command).slice(0, 60);
52071
+ const key3 = tracked ? `job:${row.pgid}\0${name}` : name;
52072
+ const group = busy.get(key3);
52073
+ if (!group) busy.set(key3, { kind: "busy", name, pid: row.pid, processes: 1, cpuPercent: row.cpu, memoryBytes: row.rssKB * 1024, top: row.cpu, row, ...tracked ? { tracked: true } : {} });
51637
52074
  else {
51638
52075
  group.processes++;
51639
52076
  group.cpuPercent += row.cpu;
51640
52077
  group.memoryBytes += row.rssKB * 1024;
52078
+ if (tracked) group.tracked = true;
51641
52079
  if (row.cpu > group.top) {
51642
52080
  group.top = row.cpu;
51643
52081
  group.pid = row.pid;
@@ -51650,19 +52088,30 @@ function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), limit = 12) {
51650
52088
  if (!total) {
51651
52089
  const { kind, name } = kinds.get(root);
51652
52090
  const pane = owner(byPid.get(root));
51653
- total = { kind, name, pid: root, processes: 0, cpuPercent: 0, memoryBytes: 0, ...pane ? { pane } : {} };
52091
+ total = {
52092
+ kind,
52093
+ name,
52094
+ pid: root,
52095
+ processes: 0,
52096
+ cpuPercent: 0,
52097
+ memoryBytes: 0,
52098
+ ...tracked ? { tracked: true } : {},
52099
+ ...pane ? { pane } : {},
52100
+ ...pane?.agent ? { agent: pane.agent } : {}
52101
+ };
51654
52102
  totals.set(root, total);
51655
52103
  }
51656
52104
  total.processes++;
51657
52105
  total.cpuPercent += row.cpu;
51658
52106
  total.memoryBytes += row.rssKB * 1024;
52107
+ if (tracked) total.tracked = true;
51659
52108
  }
51660
52109
  for (const { top: _top, row, ...group } of busy.values()) {
51661
- if (group.cpuPercent < 50) continue;
52110
+ if (group.cpuPercent < 50 && !group.tracked) continue;
51662
52111
  const pane = owner(row);
51663
- totals.set(group.pid, { ...group, ...pane ? { pane } : {} });
52112
+ totals.set(group.pid, { ...group, ...pane ? { pane } : {}, ...pane?.agent ? { agent: pane.agent } : {} });
51664
52113
  }
51665
- return [...totals.values()].filter((item) => item.kind === "busy" || item.cpuPercent >= 10 || item.memoryBytes >= 200 * 1024 ** 2).map((item) => ({
52114
+ return [...totals.values()].filter((item) => item.kind === "busy" || item.cpuPercent >= 10 || item.memoryBytes >= 200 * 1024 ** 2 || item.tracked).map((item) => ({
51666
52115
  ...item,
51667
52116
  cpuPercent: Math.round(item.cpuPercent * 10) / 10,
51668
52117
  resourceReason: item.cpuPercent >= 10 ? "cpu" : item.memoryBytes >= 200 * 1024 ** 2 ? "memory" : "tracked"
@@ -51737,7 +52186,7 @@ async function linuxBattery() {
51737
52186
  const names = await readdir18(root).catch(() => []);
51738
52187
  const battery = names.find((name) => /^BAT/.test(name));
51739
52188
  if (!battery) return void 0;
51740
- const read = (name, field) => readFile44(path87.join(root, name, field), "utf8").then((text4) => text4.trim()).catch(() => "");
52189
+ const read = (name, field) => readFile45(path89.join(root, name, field), "utf8").then((text4) => text4.trim()).catch(() => "");
51741
52190
  const [capacity2, status] = await Promise.all([read(battery, "capacity"), read(battery, "status")]);
51742
52191
  const online = await Promise.all(names.filter((name) => !/^BAT/.test(name)).map((name) => read(name, "online")));
51743
52192
  const percent = Number(capacity2);
@@ -51745,8 +52194,37 @@ async function linuxBattery() {
51745
52194
  return { percent, charging: status === "Charging" || status === "Full", onAC: online.includes("1") };
51746
52195
  }
51747
52196
  async function processTable4() {
51748
- const [stats, args] = await Promise.all([run("/bin/ps", ["-axo", "pid=,ppid=,pcpu=,rss=,comm="]), run("/bin/ps", ["-axo", "pid=,args="])]);
51749
- return parsePs(stats, args);
52197
+ const [stats, args, elapsed] = await Promise.all([
52198
+ run("/bin/ps", ["-axo", "pid=,ppid=,pgid=,pcpu=,rss=,comm="]),
52199
+ run("/bin/ps", ["-axo", "pid=,args="]),
52200
+ run("/bin/ps", ["-axo", "pid=,etime="]).catch(() => "")
52201
+ ]);
52202
+ return withStartTimes(parsePs(stats, args), elapsed, Date.now());
52203
+ }
52204
+ function parseEtime(value2) {
52205
+ const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(value2.trim());
52206
+ if (!match) return void 0;
52207
+ return Number(match[1] ?? 0) * 86400 + Number(match[2] ?? 0) * 3600 + Number(match[3]) * 60 + Number(match[4]);
52208
+ }
52209
+ function withStartTimes(rows, elapsed, now) {
52210
+ const started = /* @__PURE__ */ new Map();
52211
+ for (const line of elapsed.split("\n")) {
52212
+ const match = /^\s*(\d+)\s+(\S+)\s*$/.exec(line);
52213
+ const seconds = match ? parseEtime(match[2]) : void 0;
52214
+ if (match && seconds !== void 0) started.set(Number(match[1]), now - seconds * 1e3);
52215
+ }
52216
+ return rows.map((row) => started.has(row.pid) ? { ...row, startedAt: started.get(row.pid) } : row);
52217
+ }
52218
+ async function livePanes() {
52219
+ const panes2 = /* @__PURE__ */ new Set(), servers2 = /* @__PURE__ */ new Set();
52220
+ for (const server of await recentServers()) {
52221
+ const name = String(server.session);
52222
+ const s = await sharedSnapshot(name, RESOURCES_MAX_AGE_MS).catch(() => void 0);
52223
+ if (!s) return void 0;
52224
+ servers2.add(name);
52225
+ for (const pane of objects(s.panes)) panes2.add(paneKey3({ server: name, pane: String(pane.pane_id) }));
52226
+ }
52227
+ return { panes: panes2, servers: servers2 };
51750
52228
  }
51751
52229
  async function paneOwners() {
51752
52230
  const owners = /* @__PURE__ */ new Map();
@@ -51776,14 +52254,17 @@ async function collectResources(deps2) {
51776
52254
  const [one, five, fifteen] = loadavg();
51777
52255
  const cores = cpus().length || 1;
51778
52256
  const platform = deps2.platform;
51779
- const [memory, disk, battery, rows] = await Promise.all([
51780
- platform === "darwin" ? darwinMemory() : platform === "linux" ? readFile44("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() })) : Promise.resolve({ totalBytes: totalmem() }),
52257
+ const registry2 = deps2.jobs ?? new JobRegistry();
52258
+ const [memory, disk, battery, rows, registered] = await Promise.all([
52259
+ platform === "darwin" ? darwinMemory() : platform === "linux" ? readFile45("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() })) : Promise.resolve({ totalBytes: totalmem() }),
51781
52260
  statfs(deps2.home()).then((info) => ({ path: "~", totalBytes: info.blocks * info.bsize, freeBytes: info.bavail * info.bsize })).catch(() => void 0),
51782
52261
  platform === "darwin" ? run("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => void 0) : platform === "linux" ? linuxBattery() : Promise.resolve(void 0),
51783
- deps2.processes().catch(() => [])
52262
+ deps2.processes().catch(() => []),
52263
+ registry2.list().catch(() => [])
51784
52264
  ]);
51785
- const preliminary = heavyProcesses(rows);
51786
- const owners = preliminary.length ? await deps2.owners().catch(() => /* @__PURE__ */ new Map()) : /* @__PURE__ */ new Map();
52265
+ const preliminary = heavyProcesses(rows, /* @__PURE__ */ new Map(), registered);
52266
+ const owners = preliminary.length || registered.length ? await deps2.owners().catch(() => /* @__PURE__ */ new Map()) : /* @__PURE__ */ new Map();
52267
+ const jobs = owners.size ? await registry2.reconcile(rows, owners).catch(() => registered) : registered;
51787
52268
  const round = (n) => Math.round(n * 100) / 100;
51788
52269
  const value2 = {
51789
52270
  collectedAt: new Date(deps2.now()).toISOString(),
@@ -51793,19 +52274,21 @@ async function collectResources(deps2) {
51793
52274
  memory,
51794
52275
  ...disk ? { disk } : {},
51795
52276
  ...battery ? { battery } : {},
51796
- heavy: owners.size ? heavyProcesses(rows, owners) : preliminary
52277
+ heavy: owners.size || jobs.length ? heavyProcesses(rows, owners, jobs) : preliminary
51797
52278
  };
51798
52279
  return { ...value2, ...assess(value2) };
51799
52280
  }
51800
52281
  var ResourceMonitor = class {
51801
52282
  constructor(deps2 = {}, maxAgeMs = RESOURCES_MAX_AGE_MS) {
51802
52283
  this.maxAgeMs = maxAgeMs;
51803
- this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable4, owners: paneOwners, ...deps2 };
52284
+ this.registry = deps2.jobs ?? new JobRegistry();
52285
+ this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable4, owners: paneOwners, panes: livePanes, ...deps2, jobs: this.registry };
51804
52286
  }
51805
52287
  maxAgeMs;
51806
52288
  cached;
51807
52289
  pending;
51808
52290
  deps;
52291
+ registry;
51809
52292
  async read() {
51810
52293
  if (this.cached && this.deps.now() - this.cached.at < this.maxAgeMs) return this.cached.value;
51811
52294
  this.pending ??= collectResources(this.deps).then((value2) => {
@@ -51816,13 +52299,31 @@ var ResourceMonitor = class {
51816
52299
  });
51817
52300
  return this.pending;
51818
52301
  }
52302
+ /**
52303
+ * End only the registered process groups whose owning pane is gone. The
52304
+ * registry (job-registry.ts) does the safety checks; a failed pane read ends
52305
+ * nothing. Never the Hook's own service, never an owner's session, never an
52306
+ * unregistered process.
52307
+ */
52308
+ async cleanupJobs() {
52309
+ const rows = await this.deps.processes().catch(() => []);
52310
+ const owners = await this.deps.owners().catch(() => /* @__PURE__ */ new Map());
52311
+ const live = await this.deps.panes().catch(() => void 0);
52312
+ const report = await this.registry.cleanup(
52313
+ rows,
52314
+ live?.panes ?? /* @__PURE__ */ new Set(),
52315
+ { owners, panesKnown: live !== void 0, ...live ? { servers: live.servers } : {} }
52316
+ );
52317
+ this.cached = void 0;
52318
+ return report;
52319
+ }
51819
52320
  };
51820
52321
 
51821
52322
  // src/bridge/canary.ts
51822
52323
  init_phren_paths();
51823
- import { lstat as lstat26, mkdtemp as mkdtemp5, realpath as realpath15, rm as rm12 } from "node:fs/promises";
52324
+ import { lstat as lstat27, mkdtemp as mkdtemp5, realpath as realpath15, rm as rm12 } from "node:fs/promises";
51824
52325
  import { hostname as hostname11, tmpdir as tmpdir2 } from "node:os";
51825
- import path88 from "node:path";
52326
+ import path90 from "node:path";
51826
52327
  init_herdr();
51827
52328
  init_terminal();
51828
52329
  init_terminal_tmux();
@@ -51864,7 +52365,7 @@ async function closeCanaryWorkspaces(server, before, created) {
51864
52365
  }
51865
52366
  async function conductorStep(options, server) {
51866
52367
  const before = new Set(objects((await snapshot(server)).workspaces).map((workspace) => String(workspace.workspace_id)));
51867
- const folder = await realpath15(await mkdtemp5(path88.join(tmpdir2(), "phren-canary-")));
52368
+ const folder = await realpath15(await mkdtemp5(path90.join(tmpdir2(), "phren-canary-")));
51868
52369
  let created, failure2, detail;
51869
52370
  try {
51870
52371
  const launched = await options.launch(server, { role: "conductor", kind: "claude", label: CANARY_LABEL, cwd: folder, timeoutMs: 45e3 });
@@ -51885,12 +52386,12 @@ async function scheduleStep(options) {
51885
52386
  let count2 = 0;
51886
52387
  const broken = [];
51887
52388
  for (const directory of getProjectDirs(options.store)) {
51888
- const present2 = await lstat26(path88.join(directory, "schedules.yaml")).catch(() => void 0);
52389
+ const present2 = await lstat27(path90.join(directory, "schedules.yaml")).catch(() => void 0);
51889
52390
  if (!present2) continue;
51890
52391
  try {
51891
52392
  count2 += (await readScheduleDocument(directory)).schedules.length;
51892
52393
  } catch (error62) {
51893
- broken.push(`${path88.basename(directory)}: ${reason(error62)}`);
52394
+ broken.push(`${path90.basename(directory)}: ${reason(error62)}`);
51894
52395
  }
51895
52396
  }
51896
52397
  const tick = options.scheduler.lastTickAt;
@@ -51960,7 +52461,7 @@ function runCanary(options) {
51960
52461
  }
51961
52462
  async function dailyCanaryEnabled(root = bridgeRoot()) {
51962
52463
  if (process.env.PHREN_CANARY_DAILY === "1") return true;
51963
- return !!(await lstat26(path88.join(root, "canary-daily")).catch(() => void 0))?.isFile();
52464
+ return !!(await lstat27(path90.join(root, "canary-daily")).catch(() => void 0))?.isFile();
51964
52465
  }
51965
52466
  async function dailyCanaryDue(root = bridgeRoot(), now = Date.now()) {
51966
52467
  if (running || !await dailyCanaryEnabled(root)) return false;
@@ -51998,11 +52499,11 @@ async function ownerInboxView(inbox, input2, localOnly = false) {
51998
52499
 
51999
52500
  // src/bridge/server-routes.ts
52000
52501
  init_zod();
52001
- import path108 from "node:path";
52502
+ import path110 from "node:path";
52002
52503
 
52003
52504
  // src/bridge/code-note.ts
52004
52505
  init_zod();
52005
- import * as path94 from "node:path";
52506
+ import * as path96 from "node:path";
52006
52507
 
52007
52508
  // src/content/validate.ts
52008
52509
  init_utils_helpers();
@@ -52016,7 +52517,7 @@ init_store_routing();
52016
52517
  init_locks();
52017
52518
  init_data_utils();
52018
52519
  import * as fs29 from "fs";
52019
- import * as path90 from "path";
52520
+ import * as path92 from "path";
52020
52521
  import * as crypto8 from "crypto";
52021
52522
 
52022
52523
  // src/project-topics.ts
@@ -52028,7 +52529,7 @@ init_data_utils();
52028
52529
  init_filenames();
52029
52530
  import * as crypto7 from "crypto";
52030
52531
  import * as fs28 from "fs";
52031
- import * as path89 from "path";
52532
+ import * as path91 from "path";
52032
52533
  var TOPIC_CONFIG_FILENAME = "topic-config.json";
52033
52534
  var SOFTWARE_TOPICS = [
52034
52535
  {
@@ -52566,7 +53067,7 @@ function topicDocHeader(project, topic) {
52566
53067
  }
52567
53068
  function appendArchivedEntriesToTopicDoc(filePath, project, topic, entries2) {
52568
53069
  if (entries2.length === 0) return;
52569
- fs28.mkdirSync(path89.dirname(filePath), { recursive: true });
53070
+ fs28.mkdirSync(path91.dirname(filePath), { recursive: true });
52570
53071
  withFileLock(filePath, () => {
52571
53072
  let existing = "";
52572
53073
  if (fs28.existsSync(filePath)) existing = fs28.readFileSync(filePath, "utf8");
@@ -52685,7 +53186,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
52685
53186
  if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
52686
53187
  const resolvedDir = storeAwareProjectPath(phrenPath, project);
52687
53188
  if (!resolvedDir || !fs29.existsSync(resolvedDir)) return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
52688
- const learningsPath = path90.join(resolvedDir, FINDINGS_FILENAME);
53189
+ const learningsPath = path92.join(resolvedDir, FINDINGS_FILENAME);
52689
53190
  if (!fs29.existsSync(learningsPath)) return phrenOk(0);
52690
53191
  const STALE_LOCK_MS = 6e5;
52691
53192
  const lockFile = runtimeFile(phrenPath, `consolidation-${project}.lock`);
@@ -52721,7 +53222,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
52721
53222
  const entries2 = parseActiveEntries(content);
52722
53223
  if (entries2.length <= keepCount) return phrenOk(0);
52723
53224
  const toArchive = entries2.slice(0, entries2.length - keepCount);
52724
- const referenceDir = path90.join(resolvedDir, "reference");
53225
+ const referenceDir = path92.join(resolvedDir, "reference");
52725
53226
  const { topics } = readProjectTopics(phrenPath, project);
52726
53227
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
52727
53228
  const archivedSet = buildArchivedBulletSet(referenceDir);
@@ -53291,7 +53792,7 @@ var DEFAULT_DECAY = {
53291
53792
  var DEFAULT_UNDATED_CONFIDENCE = DEFAULT_DECAY.d120;
53292
53793
 
53293
53794
  // src/content/dedup.ts
53294
- import * as path91 from "path";
53795
+ import * as path93 from "path";
53295
53796
  init_shared();
53296
53797
  init_utils();
53297
53798
  init_store_routing();
@@ -53415,7 +53916,7 @@ function resolveCoref(text4, context) {
53415
53916
  result = result.replace(/\bthe project\b/gi, context.project);
53416
53917
  }
53417
53918
  if (context.file) {
53418
- const basename12 = path91.basename(context.file);
53919
+ const basename12 = path93.basename(context.file);
53419
53920
  result = result.replace(/\b(this file|the file)\b/gi, basename12);
53420
53921
  }
53421
53922
  if (context.project && /\b(it|this|that|they|them)\b/i.test(result)) {
@@ -53432,7 +53933,7 @@ init_shared();
53432
53933
  init_shared();
53433
53934
  init_governance();
53434
53935
  import * as fs31 from "fs";
53435
- import * as path93 from "path";
53936
+ import * as path95 from "path";
53436
53937
  import * as crypto9 from "crypto";
53437
53938
 
53438
53939
  // src/finding-graph-id.ts
@@ -53467,7 +53968,7 @@ init_store_routing();
53467
53968
  // src/finding/context.ts
53468
53969
  init_utils();
53469
53970
  import * as fs30 from "fs";
53470
- import * as path92 from "path";
53971
+ import * as path94 from "path";
53471
53972
 
53472
53973
  // src/session/utils.ts
53473
53974
  init_utils();
@@ -53549,14 +54050,14 @@ function resolveFindingTaskReference(phrenPath, project, match) {
53549
54050
  const projectDir = safeProjectPath(phrenPath, project);
53550
54051
  if (!projectDir) return { error: `Invalid project name: "${project}".` };
53551
54052
  const taskPath = resolveTaskFilePath(phrenPath, project);
53552
- const items = parseTaskItems(taskPath ?? path92.join(projectDir, "tasks.md"));
54053
+ const items = parseTaskItems(taskPath ?? path94.join(projectDir, "tasks.md"));
53553
54054
  return resolveTaskItemMatch(items, match);
53554
54055
  }
53555
54056
  function resolveAutoFindingTaskItem(phrenPath, project) {
53556
54057
  const projectDir = safeProjectPath(phrenPath, project);
53557
54058
  if (!projectDir) return void 0;
53558
54059
  const taskPath = resolveTaskFilePath(phrenPath, project);
53559
- const active = parseTaskItems(taskPath ?? path92.join(projectDir, "tasks.md")).filter(
54060
+ const active = parseTaskItems(taskPath ?? path94.join(projectDir, "tasks.md")).filter(
53560
54061
  (item) => item.section === "Active" && item.stableId
53561
54062
  );
53562
54063
  if (active.length === 1) return active[0].stableId;
@@ -53596,7 +54097,7 @@ function buildFindingCitation(citationInput, nowIso, inferredRepo, headCommit) {
53596
54097
  function resolveInferredCitationRepo(citationInput) {
53597
54098
  if (citationInput?.repo) return citationInput.repo;
53598
54099
  if (citationInput?.file) {
53599
- const fileDir = path93.dirname(citationInput.file);
54100
+ const fileDir = path95.dirname(citationInput.file);
53600
54101
  return getRepoRoot(fileDir);
53601
54102
  }
53602
54103
  return void 0;
@@ -53731,7 +54232,7 @@ function addFindingToFile(phrenPath, project, learning, citationInput, opts) {
53731
54232
  if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
53732
54233
  const resolvedDir = storeAwareProjectPath(phrenPath, project);
53733
54234
  if (!resolvedDir) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
53734
- const learningsPath = path93.join(resolvedDir, FINDINGS_FILENAME);
54235
+ const learningsPath = path95.join(resolvedDir, FINDINGS_FILENAME);
53735
54236
  const nowIso = (opts?.now ?? /* @__PURE__ */ new Date()).toISOString();
53736
54237
  const today = nowIso.slice(0, 10);
53737
54238
  const resolvedCitationInputResult = resolveFindingCitationInput(phrenPath, project, citationInput);
@@ -53913,7 +54414,7 @@ var codeNoteSchema = external_exports.object({
53913
54414
  // phone's spelling, accepted until 0.3.1.
53914
54415
  name: external_exports.string().min(1).max(4600).optional(),
53915
54416
  symbol: external_exports.string().min(1).max(4600).optional(),
53916
- file: external_exports.string().min(1).max(4096).refine((file3) => !path94.isAbsolute(file3) && !file3.includes("\0") && !file3.split(/[\\/]/).includes("..")),
54417
+ file: external_exports.string().min(1).max(4096).refine((file3) => !path96.isAbsolute(file3) && !file3.includes("\0") && !file3.split(/[\\/]/).includes("..")),
53917
54418
  line: external_exports.number().int().positive(),
53918
54419
  text: external_exports.string().trim().min(1).max(4500).refine((text4) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text4)),
53919
54420
  target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(["codex", "claude", "opencode"]) }).strict()]).optional()
@@ -53967,26 +54468,26 @@ init_transcripts();
53967
54468
  import { execFile as execFile18 } from "node:child_process";
53968
54469
  import { promisify as promisify17 } from "node:util";
53969
54470
  import { realpathSync as realpathSync5 } from "node:fs";
53970
- import { readdir as readdir19, readFile as readFile45, stat as stat26, mkdir as mkdir24 } from "node:fs/promises";
54471
+ import { readdir as readdir19, readFile as readFile46, stat as stat26, mkdir as mkdir25 } from "node:fs/promises";
53971
54472
  import { homedir as homedir19 } from "node:os";
53972
- import path99 from "node:path";
54473
+ import path101 from "node:path";
53973
54474
 
53974
54475
  // src/core/project.ts
53975
54476
  init_shared();
53976
- import * as path97 from "path";
54477
+ import * as path99 from "path";
53977
54478
 
53978
54479
  // src/core/project-registry.ts
53979
54480
  init_phren_paths();
53980
54481
  import * as fs33 from "fs";
53981
- import * as path96 from "path";
54482
+ import * as path98 from "path";
53982
54483
 
53983
54484
  // src/git-worktree.ts
53984
54485
  import * as fs32 from "fs";
53985
- import * as path95 from "path";
54486
+ import * as path97 from "path";
53986
54487
  var WORKTREE_CONTAINER_NAMES = /* @__PURE__ */ new Set(["worktrees", ".worktrees"]);
53987
- var LINKED_WORKTREE_SEGMENT = `${path95.sep}.git${path95.sep}worktrees${path95.sep}`;
54488
+ var LINKED_WORKTREE_SEGMENT = `${path97.sep}.git${path97.sep}worktrees${path97.sep}`;
53988
54489
  function resolveWorktreeParent(dir) {
53989
- const resolved = path95.resolve(dir);
54490
+ const resolved = path97.resolve(dir);
53990
54491
  const agentParent = parentFromAgentWorktreePath(resolved);
53991
54492
  if (agentParent) return { repoRoot: agentParent, reason: "agent-worktree-dir" };
53992
54493
  const linkedParent = parentFromLinkedWorktree(resolved);
@@ -53994,23 +54495,23 @@ function resolveWorktreeParent(dir) {
53994
54495
  return null;
53995
54496
  }
53996
54497
  function parentFromAgentWorktreePath(resolved) {
53997
- const segments = resolved.split(path95.sep);
54498
+ const segments = resolved.split(path97.sep);
53998
54499
  for (let i = 1; i < segments.length; i++) {
53999
54500
  if (!WORKTREE_CONTAINER_NAMES.has(segments[i])) continue;
54000
54501
  let j = i - 1;
54001
54502
  if (!segments[j]?.startsWith(".")) continue;
54002
54503
  while (j >= 1 && segments[j].startsWith(".")) j--;
54003
54504
  if (j < 1) continue;
54004
- return segments.slice(0, j + 1).join(path95.sep) || path95.sep;
54505
+ return segments.slice(0, j + 1).join(path97.sep) || path97.sep;
54005
54506
  }
54006
54507
  return null;
54007
54508
  }
54008
54509
  function parentFromLinkedWorktree(resolved) {
54009
54510
  let current2 = resolved;
54010
54511
  while (true) {
54011
- const parent = repoRootFromGitFile(path95.join(current2, ".git"));
54512
+ const parent = repoRootFromGitFile(path97.join(current2, ".git"));
54012
54513
  if (parent) return parent;
54013
- const next = path95.dirname(current2);
54514
+ const next = path97.dirname(current2);
54014
54515
  if (next === current2) return null;
54015
54516
  current2 = next;
54016
54517
  }
@@ -54025,7 +54526,7 @@ function repoRootFromGitFile(gitPath) {
54025
54526
  }
54026
54527
  const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
54027
54528
  if (!match) return null;
54028
- const gitDir = path95.resolve(path95.dirname(gitPath), match[1].replace(/[/\\]/g, path95.sep));
54529
+ const gitDir = path97.resolve(path97.dirname(gitPath), match[1].replace(/[/\\]/g, path97.sep));
54029
54530
  const idx = gitDir.indexOf(LINKED_WORKTREE_SEGMENT);
54030
54531
  if (idx === -1) return null;
54031
54532
  return gitDir.slice(0, idx);
@@ -54238,7 +54739,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
54238
54739
  return topics;
54239
54740
  }
54240
54741
  function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
54241
- const resolvedRoot = path96.resolve(repoRoot);
54742
+ const resolvedRoot = path98.resolve(repoRoot);
54242
54743
  if (!fs33.existsSync(resolvedRoot)) return null;
54243
54744
  const signal = {
54244
54745
  domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
@@ -54249,7 +54750,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
54249
54750
  usefulSignals: 0
54250
54751
  };
54251
54752
  const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
54252
- const packageJsonPath = path96.join(resolvedRoot, "package.json");
54753
+ const packageJsonPath = path98.join(resolvedRoot, "package.json");
54253
54754
  if (fs33.existsSync(packageJsonPath)) {
54254
54755
  signal.usefulSignals++;
54255
54756
  addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
@@ -54279,33 +54780,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
54279
54780
  debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
54280
54781
  }
54281
54782
  }
54282
- const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs33.existsSync(path96.join(resolvedRoot, fileName)));
54783
+ const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs33.existsSync(path98.join(resolvedRoot, fileName)));
54283
54784
  for (const configName of topLevelConfigs) {
54284
54785
  signal.usefulSignals++;
54285
54786
  const configScore = DOMAIN_CONFIG_HINTS[configName];
54286
54787
  if (configScore) addDomainScores(signal.domainScores, configScore);
54287
54788
  }
54288
54789
  const readmeCandidates = [
54289
- path96.join(resolvedRoot, "README.md"),
54290
- path96.join(resolvedRoot, "readme.md")
54790
+ path98.join(resolvedRoot, "README.md"),
54791
+ path98.join(resolvedRoot, "readme.md")
54291
54792
  ];
54292
54793
  for (const readmePath of readmeCandidates) {
54293
54794
  if (!fs33.existsSync(readmePath)) continue;
54294
54795
  const content = maybeReadUtf8(readmePath);
54295
54796
  if (!content) continue;
54296
54797
  signal.usefulSignals++;
54297
- signal.referenceHints.push(path96.relative(resolvedRoot, readmePath));
54798
+ signal.referenceHints.push(path98.relative(resolvedRoot, readmePath));
54298
54799
  addTermCount(signal.terms, content, 2);
54299
54800
  signal.docsText += ` ${content.toLowerCase()}`;
54300
54801
  break;
54301
54802
  }
54302
- const docsDir = path96.join(resolvedRoot, "docs");
54803
+ const docsDir = path98.join(resolvedRoot, "docs");
54303
54804
  if (fs33.existsSync(docsDir) && fs33.statSync(docsDir).isDirectory()) {
54304
54805
  signal.referenceHints.push("docs/");
54305
54806
  for (const entry2 of fs33.readdirSync(docsDir, { withFileTypes: true })) {
54306
54807
  if (!entry2.isFile()) continue;
54307
54808
  if (!/\.(md|txt|rst)$/i.test(entry2.name)) continue;
54308
- const docsContent = maybeReadUtf8(path96.join(docsDir, entry2.name));
54809
+ const docsContent = maybeReadUtf8(path98.join(docsDir, entry2.name));
54309
54810
  if (!docsContent) continue;
54310
54811
  signal.usefulSignals++;
54311
54812
  addTermCount(signal.terms, docsContent, 1);
@@ -54313,7 +54814,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
54313
54814
  }
54314
54815
  }
54315
54816
  for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
54316
- const fullPath = path96.join(resolvedRoot, folderName);
54817
+ const fullPath = path98.join(resolvedRoot, folderName);
54317
54818
  if (fs33.existsSync(fullPath)) {
54318
54819
  signal.referenceHints.push(`${folderName}/`);
54319
54820
  }
@@ -54324,14 +54825,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
54324
54825
  if (scannedFiles >= maxFiles) return;
54325
54826
  for (const entry2 of fs33.readdirSync(dir, { withFileTypes: true })) {
54326
54827
  if (scannedFiles >= maxFiles) return;
54327
- const fullPath = path96.join(dir, entry2.name);
54828
+ const fullPath = path98.join(dir, entry2.name);
54328
54829
  if (entry2.isDirectory()) {
54329
54830
  if (skipDirs.has(entry2.name)) continue;
54330
54831
  walk(fullPath);
54331
54832
  continue;
54332
54833
  }
54333
54834
  scannedFiles++;
54334
- const ext = path96.extname(entry2.name).toLowerCase();
54835
+ const ext = path98.extname(entry2.name).toLowerCase();
54335
54836
  if (!ext) continue;
54336
54837
  const extScore = EXTENSION_DOMAIN_HINTS[ext];
54337
54838
  if (extScore) {
@@ -54505,7 +55006,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
54505
55006
  return null;
54506
55007
  }
54507
55008
  };
54508
- const resolvedSource = path96.resolve(sourceRoot);
55009
+ const resolvedSource = path98.resolve(sourceRoot);
54509
55010
  for (const project of candidates) {
54510
55011
  if (sourceOf(project) === resolvedSource) return project;
54511
55012
  }
@@ -54519,7 +55020,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
54519
55020
  function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
54520
55021
  const profile = typeof opts === "string" ? opts : opts.profile;
54521
55022
  const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
54522
- const resolvedPath = path96.resolve(projectPath);
55023
+ const resolvedPath = path98.resolve(projectPath);
54523
55024
  if (!fs33.existsSync(resolvedPath)) {
54524
55025
  throw new Error(`Path does not exist: ${resolvedPath}`);
54525
55026
  }
@@ -54530,17 +55031,17 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
54530
55031
  if (worktreeRepoRoot) {
54531
55032
  debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
54532
55033
  }
54533
- const sourceRoot = isProjectLocal ? path96.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
55034
+ const sourceRoot = isProjectLocal ? path98.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
54534
55035
  if (isProjectLocal) {
54535
- const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path96.sep);
55036
+ const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path98.sep);
54536
55037
  if (!matchesWorkspace) {
54537
55038
  throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
54538
55039
  }
54539
55040
  }
54540
55041
  let claudeMdPath = null;
54541
55042
  const candidates = [
54542
- path96.join(sourceRoot, "AGENTS.md"),
54543
- path96.join(sourceRoot, ".claude", "CLAUDE.md")
55043
+ path98.join(sourceRoot, "AGENTS.md"),
55044
+ path98.join(sourceRoot, ".claude", "CLAUDE.md")
54544
55045
  ];
54545
55046
  for (const c of candidates) {
54546
55047
  if (fs33.existsSync(c)) {
@@ -54560,12 +55061,12 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
54560
55061
  `Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
54561
55062
  );
54562
55063
  }
54563
- const projDir = path96.join(phrenPath, projectName2);
55064
+ const projDir = path98.join(phrenPath, projectName2);
54564
55065
  fs33.mkdirSync(projDir, { recursive: true });
54565
55066
  const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
54566
55067
  const existingConfig = readProjectConfig(phrenPath, projectName2);
54567
55068
  const ownership = typeof opts === "string" ? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath) : opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath);
54568
- const claudePath = path96.join(projDir, "AGENTS.md");
55069
+ const claudePath = path98.join(projDir, "AGENTS.md");
54569
55070
  if (ownership !== "repo-managed") {
54570
55071
  if (claudeContent) {
54571
55072
  if (!fs33.existsSync(claudePath)) {
@@ -54600,7 +55101,7 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
54600
55101
  }
54601
55102
  }
54602
55103
  const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
54603
- const summaryPath = path96.join(projDir, "summary.md");
55104
+ const summaryPath = path98.join(projDir, "summary.md");
54604
55105
  if (!fs33.existsSync(summaryPath)) {
54605
55106
  atomicWriteText(
54606
55107
  summaryPath,
@@ -54613,18 +55114,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
54613
55114
  `
54614
55115
  );
54615
55116
  }
54616
- if (!fs33.existsSync(path96.join(projDir, FINDINGS_FILENAME))) {
55117
+ if (!fs33.existsSync(path98.join(projDir, FINDINGS_FILENAME))) {
54617
55118
  atomicWriteText(
54618
- path96.join(projDir, FINDINGS_FILENAME),
55119
+ path98.join(projDir, FINDINGS_FILENAME),
54619
55120
  `# ${projectName2} FINDINGS
54620
55121
 
54621
55122
  <!-- Bootstrapped from ${sourceRoot} -->
54622
55123
  `
54623
55124
  );
54624
55125
  }
54625
- if (moduleEnabled(phrenPath, "tasks") && !fs33.existsSync(path96.join(projDir, TASKS_FILENAME))) {
55126
+ if (moduleEnabled(phrenPath, "tasks") && !fs33.existsSync(path98.join(projDir, TASKS_FILENAME))) {
54626
55127
  atomicWriteText(
54627
- path96.join(projDir, TASKS_FILENAME),
55128
+ path98.join(projDir, TASKS_FILENAME),
54628
55129
  `# ${projectName2} tasks
54629
55130
 
54630
55131
  ## Active
@@ -54635,11 +55136,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
54635
55136
  `
54636
55137
  );
54637
55138
  }
54638
- if (!fs33.existsSync(path96.join(projDir, "topic-config.json"))) {
55139
+ if (!fs33.existsSync(path98.join(projDir, "topic-config.json"))) {
54639
55140
  const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
54640
55141
  const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
54641
55142
  atomicWriteText(
54642
- path96.join(projDir, "topic-config.json"),
55143
+ path98.join(projDir, "topic-config.json"),
54643
55144
  JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
54644
55145
  );
54645
55146
  }
@@ -54671,10 +55172,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
54671
55172
  if (!activeProfile.ok) return activeProfile;
54672
55173
  const writePhrenPath = options.writeToPath ?? phrenPath;
54673
55174
  const manifest = readRootManifest(phrenPath);
54674
- const resolvedPath = path97.resolve(targetPath);
55175
+ const resolvedPath = path99.resolve(targetPath);
54675
55176
  if (manifest?.installMode === "project-local") {
54676
- const workspaceRoot = path97.resolve(manifest.workspaceRoot || "");
54677
- const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path97.sep);
55177
+ const workspaceRoot = path99.resolve(manifest.workspaceRoot || "");
55178
+ const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path99.sep);
54678
55179
  if (!matchesWorkspace) {
54679
55180
  return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
54680
55181
  }
@@ -54692,9 +55193,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
54692
55193
  ownership: added.ownership,
54693
55194
  files: {
54694
55195
  claude: added.claudePath,
54695
- summary: path97.join(writePhrenPath, added.project, "summary.md"),
54696
- findings: path97.join(writePhrenPath, added.project, FINDINGS_FILENAME),
54697
- task: path97.join(writePhrenPath, added.project, TASKS_FILENAME)
55196
+ summary: path99.join(writePhrenPath, added.project, "summary.md"),
55197
+ findings: path99.join(writePhrenPath, added.project, FINDINGS_FILENAME),
55198
+ task: path99.join(writePhrenPath, added.project, TASKS_FILENAME)
54698
55199
  }
54699
55200
  });
54700
55201
  }
@@ -54720,7 +55221,7 @@ import { execFileSync as execFileSync6, spawnSync as spawnSync2 } from "child_pr
54720
55221
  import * as crypto10 from "crypto";
54721
55222
  import * as fs34 from "fs";
54722
55223
  import * as os3 from "os";
54723
- import * as path98 from "path";
55224
+ import * as path100 from "path";
54724
55225
 
54725
55226
  // src/content/summarize.ts
54726
55227
  init_phren_dotenv();
@@ -54881,7 +55382,7 @@ function mergeTasksByBid(base, ours, theirs) {
54881
55382
  // src/sync/conflict-resolve.ts
54882
55383
  function conflictStrategy(relFile) {
54883
55384
  const file3 = relFile.replace(/\\/g, "/");
54884
- const name = path98.posix.basename(file3).toLowerCase();
55385
+ const name = path100.posix.basename(file3).toLowerCase();
54885
55386
  if (isTaskFileName(name)) return "tasks";
54886
55387
  if (name === "findings.md") return "findings";
54887
55388
  if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file3)) return "archive";
@@ -54916,9 +55417,9 @@ function splitBlock(content, start, end) {
54916
55417
  function mergeText(base, ours, theirs) {
54917
55418
  if (ours === theirs || ours === base) return theirs;
54918
55419
  if (theirs === base) return ours;
54919
- const dir = fs34.mkdtempSync(path98.join(os3.tmpdir(), "phren-merge-"));
55420
+ const dir = fs34.mkdtempSync(path100.join(os3.tmpdir(), "phren-merge-"));
54920
55421
  try {
54921
- const [o, b, t] = ["ours", "base", "theirs"].map((name) => path98.join(dir, name));
55422
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path100.join(dir, name));
54922
55423
  fs34.writeFileSync(o, ours);
54923
55424
  fs34.writeFileSync(b, base);
54924
55425
  fs34.writeFileSync(t, theirs);
@@ -54931,9 +55432,9 @@ function mergeText(base, ours, theirs) {
54931
55432
  function unionText(base, ours, theirs) {
54932
55433
  const clean2 = mergeText(base, ours, theirs);
54933
55434
  if (clean2 !== null) return clean2;
54934
- const dir = fs34.mkdtempSync(path98.join(os3.tmpdir(), "phren-merge-"));
55435
+ const dir = fs34.mkdtempSync(path100.join(os3.tmpdir(), "phren-merge-"));
54935
55436
  try {
54936
- const [o, b, t] = ["ours", "base", "theirs"].map((name) => path98.join(dir, name));
55437
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path100.join(dir, name));
54937
55438
  fs34.writeFileSync(o, ours);
54938
55439
  fs34.writeFileSync(b, base);
54939
55440
  fs34.writeFileSync(t, theirs);
@@ -54993,7 +55494,7 @@ function resolveStoreConflicts(cwd) {
54993
55494
  const base = stage(cwd, 1, relFile) ?? "";
54994
55495
  const ours = stage(cwd, 2, relFile);
54995
55496
  const theirs = stage(cwd, 3, relFile);
54996
- const fullPath = path98.join(cwd, relFile);
55497
+ const fullPath = path100.join(cwd, relFile);
54997
55498
  if (ours === null && theirs === null) {
54998
55499
  unresolved.push(relFile);
54999
55500
  continue;
@@ -55004,7 +55505,7 @@ function resolveStoreConflicts(cwd) {
55004
55505
  continue;
55005
55506
  }
55006
55507
  const tmp = `${fullPath}.tmp-${crypto10.randomUUID()}`;
55007
- fs34.mkdirSync(path98.dirname(fullPath), { recursive: true });
55508
+ fs34.mkdirSync(path100.dirname(fullPath), { recursive: true });
55008
55509
  fs34.writeFileSync(tmp, merged);
55009
55510
  fs34.renameSync(tmp, fullPath);
55010
55511
  git4(cwd, ["add", "--", relFile]);
@@ -55284,7 +55785,7 @@ function repoName(url2) {
55284
55785
  }
55285
55786
  async function isRepository(directory) {
55286
55787
  try {
55287
- await stat26(path99.join(directory, ".git"));
55788
+ await stat26(path101.join(directory, ".git"));
55288
55789
  return true;
55289
55790
  } catch {
55290
55791
  return false;
@@ -55304,7 +55805,7 @@ async function registeredSources(env) {
55304
55805
  const source = readProjectConfig(store, project).sourcePath;
55305
55806
  if (typeof source === "string" && source) {
55306
55807
  try {
55307
- paths.add(realpathSync5.native(path99.resolve(source)));
55808
+ paths.add(realpathSync5.native(path101.resolve(source)));
55308
55809
  } catch {
55309
55810
  }
55310
55811
  }
@@ -55316,7 +55817,7 @@ async function candidateRepos(activity, env = process.env) {
55316
55817
  const found = [];
55317
55818
  const seen = /* @__PURE__ */ new Set();
55318
55819
  const offer = async (directory, source, lastSeen) => {
55319
- let dir = path99.resolve(directory);
55820
+ let dir = path101.resolve(directory);
55320
55821
  try {
55321
55822
  if (!(await stat26(dir)).isDirectory()) return;
55322
55823
  dir = realpathSync5.native(dir);
@@ -55331,7 +55832,7 @@ async function candidateRepos(activity, env = process.env) {
55331
55832
  const toplevel = async (directory) => {
55332
55833
  let existing = directory;
55333
55834
  while (!await stat26(existing).catch(() => void 0)) {
55334
- const parent = path99.dirname(existing);
55835
+ const parent = path101.dirname(existing);
55335
55836
  if (parent === existing) return void 0;
55336
55837
  existing = parent;
55337
55838
  }
@@ -55344,25 +55845,25 @@ async function candidateRepos(activity, env = process.env) {
55344
55845
  };
55345
55846
  for (const event of [...activity].reverse()) {
55346
55847
  const directory = typeof event.directory === "string" ? event.directory : void 0;
55347
- if (!directory || !path99.isAbsolute(directory)) continue;
55848
+ if (!directory || !path101.isAbsolute(directory)) continue;
55348
55849
  const root = await toplevel(directory);
55349
55850
  if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
55350
55851
  }
55351
55852
  try {
55352
- const session = JSON.parse(await readFile45(path99.join(herdrRoot(), "session.json"), "utf8"));
55853
+ const session = JSON.parse(await readFile46(path101.join(herdrRoot(), "session.json"), "utf8"));
55353
55854
  for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
55354
55855
  const directory = JSON.parse(`"${match[1]}"`);
55355
- if (!path99.isAbsolute(directory)) continue;
55856
+ if (!path101.isAbsolute(directory)) continue;
55356
55857
  const root = await toplevel(directory);
55357
55858
  if (root) await offer(root, "herdr");
55358
55859
  }
55359
55860
  } catch {
55360
55861
  }
55361
55862
  const home = homedir19();
55362
- for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path99.join(home, r))]) {
55863
+ for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path101.join(home, r))]) {
55363
55864
  let children = [];
55364
55865
  try {
55365
- children = (await readdir19(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path99.join(root, e.name));
55866
+ children = (await readdir19(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path101.join(root, e.name));
55366
55867
  } catch {
55367
55868
  continue;
55368
55869
  }
@@ -55372,14 +55873,14 @@ async function candidateRepos(activity, env = process.env) {
55372
55873
  }
55373
55874
  async function cloneRoot(env) {
55374
55875
  const home = homedir19();
55375
- for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path99.join(home, r))]) {
55876
+ for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path101.join(home, r))]) {
55376
55877
  try {
55377
55878
  if ((await stat26(root)).isDirectory()) return root;
55378
55879
  } catch {
55379
55880
  }
55380
55881
  }
55381
- const fallback2 = path99.join(home, "Projects");
55382
- await mkdir24(fallback2, { recursive: true });
55882
+ const fallback2 = path101.join(home, "Projects");
55883
+ await mkdir25(fallback2, { recursive: true });
55383
55884
  return fallback2;
55384
55885
  }
55385
55886
  async function publishStore(store, project) {
@@ -55400,7 +55901,7 @@ async function publishStore(store, project) {
55400
55901
  async function enrollProject(input2, env = process.env) {
55401
55902
  const store = phrenStoreRoot(env);
55402
55903
  try {
55403
- if (!(await stat26(path99.join(store, ".config"))).isDirectory()) throw new Error();
55904
+ if (!(await stat26(path101.join(store, ".config"))).isDirectory()) throw new Error();
55404
55905
  } catch {
55405
55906
  throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
55406
55907
  }
@@ -55411,7 +55912,7 @@ async function enrollProject(input2, env = process.env) {
55411
55912
  if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
55412
55913
  const name = repoName(url2);
55413
55914
  if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
55414
- directory = path99.join(await cloneRoot(env), name);
55915
+ directory = path101.join(await cloneRoot(env), name);
55415
55916
  try {
55416
55917
  await stat26(directory);
55417
55918
  throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
@@ -55428,7 +55929,7 @@ async function enrollProject(input2, env = process.env) {
55428
55929
  cloned = true;
55429
55930
  } else if (typeof input2.directory === "string" && input2.directory) {
55430
55931
  const raw = input2.directory;
55431
- if (raw.length > 4096 || raw.includes("\0") || !path99.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
55932
+ if (raw.length > 4096 || raw.includes("\0") || !path101.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
55432
55933
  try {
55433
55934
  directory = realpathSync5.native(raw);
55434
55935
  if (!(await stat26(directory)).isDirectory()) throw new Error();
@@ -55444,33 +55945,33 @@ async function enrollProject(input2, env = process.env) {
55444
55945
  // src/bridge/files.ts
55445
55946
  init_protocol();
55446
55947
  import { constants as constants4 } from "node:fs";
55447
- import { lstat as lstat27, open as open20, readdir as readdir20, realpath as realpath16 } from "node:fs/promises";
55448
- import path100 from "node:path";
55948
+ import { lstat as lstat28, open as open21, readdir as readdir20, realpath as realpath16 } from "node:fs/promises";
55949
+ import path102 from "node:path";
55449
55950
  var MAX_BYTES = 2097152;
55450
55951
  async function browseFiles(root, relative3) {
55451
- if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path100.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
55952
+ if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path102.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
55452
55953
  throw new BridgeError(400, "Invalid repository path.");
55453
55954
  }
55454
55955
  const base = await realpath16(root);
55455
55956
  let file3 = base;
55456
55957
  for (const part of relative3.split("/").filter((part2) => part2 && part2 !== ".")) {
55457
- file3 = path100.join(file3, part);
55458
- if ((await lstat27(file3)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
55958
+ file3 = path102.join(file3, part);
55959
+ if ((await lstat28(file3)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
55459
55960
  }
55460
55961
  const resolved = await realpath16(file3);
55461
- if (resolved !== base && !resolved.startsWith(base + path100.sep)) throw new BridgeError(403, "The path is outside this repository.");
55462
- const metadata = await lstat27(resolved);
55962
+ if (resolved !== base && !resolved.startsWith(base + path102.sep)) throw new BridgeError(403, "The path is outside this repository.");
55963
+ const metadata = await lstat28(resolved);
55463
55964
  if (metadata.isDirectory()) {
55464
55965
  const entries2 = (await readdir20(resolved, { withFileTypes: true })).filter((entry2) => entry2.name !== ".git" && (entry2.isDirectory() || entry2.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
55465
55966
  return {
55466
55967
  path: relative3,
55467
55968
  kind: "directory",
55468
55969
  truncated: entries2.length > 500,
55469
- entries: entries2.slice(0, 500).map((entry2) => ({ name: entry2.name, path: path100.posix.join(relative3, entry2.name), kind: entry2.isDirectory() ? "directory" : "file" }))
55970
+ entries: entries2.slice(0, 500).map((entry2) => ({ name: entry2.name, path: path102.posix.join(relative3, entry2.name), kind: entry2.isDirectory() ? "directory" : "file" }))
55470
55971
  };
55471
55972
  }
55472
55973
  if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
55473
- const handle = await open20(resolved, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
55974
+ const handle = await open21(resolved, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
55474
55975
  try {
55475
55976
  const current2 = await handle.stat();
55476
55977
  if (!current2.isFile() || current2.ino !== metadata.ino || current2.dev !== metadata.dev) throw new BridgeError(409, "The file changed. Refresh and try again.");
@@ -55492,8 +55993,8 @@ async function browseFiles(root, relative3) {
55492
55993
  // src/bridge/file-range.ts
55493
55994
  init_protocol();
55494
55995
  import { constants as constants5 } from "node:fs";
55495
- import { lstat as lstat28, open as open21, realpath as realpath17 } from "node:fs/promises";
55496
- import path101 from "node:path";
55996
+ import { lstat as lstat29, open as open22, realpath as realpath17 } from "node:fs/promises";
55997
+ import path103 from "node:path";
55497
55998
  var MAX_FILE_RANGE = 4 * 1024 * 1024;
55498
55999
  var types = {
55499
56000
  mp4: "video/mp4",
@@ -55530,7 +56031,7 @@ var types = {
55530
56031
  xml: "text/xml"
55531
56032
  };
55532
56033
  function fileContentType(file3) {
55533
- const ext = path101.extname(file3).slice(1).toLowerCase();
56034
+ const ext = path103.extname(file3).slice(1).toLowerCase();
55534
56035
  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");
55535
56036
  }
55536
56037
  function version2(stat29) {
@@ -55548,18 +56049,18 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
55548
56049
  }
55549
56050
  try {
55550
56051
  const base = await realpath17(root);
55551
- const relative3 = path101.isAbsolute(requested) ? path101.relative(base, requested) : requested;
55552
- if (relative3 === ".." || relative3.startsWith(`..${path101.sep}`) || path101.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
56052
+ const relative3 = path103.isAbsolute(requested) ? path103.relative(base, requested) : requested;
56053
+ if (relative3 === ".." || relative3.startsWith(`..${path103.sep}`) || path103.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
55553
56054
  let file3 = base;
55554
- for (const part of relative3.split(path101.sep).filter((part2) => part2 && part2 !== ".")) {
55555
- file3 = path101.join(file3, part);
55556
- if ((await lstat28(file3)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
56055
+ for (const part of relative3.split(path103.sep).filter((part2) => part2 && part2 !== ".")) {
56056
+ file3 = path103.join(file3, part);
56057
+ if ((await lstat29(file3)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
55557
56058
  }
55558
56059
  const resolved = await realpath17(file3);
55559
- if (!resolved.startsWith(base + path101.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
55560
- const metadata = await lstat28(resolved);
56060
+ if (!resolved.startsWith(base + path103.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
56061
+ const metadata = await lstat29(resolved);
55561
56062
  if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be opened.");
55562
- const handle = await open21(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
56063
+ const handle = await open22(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
55563
56064
  try {
55564
56065
  const current2 = await handle.stat();
55565
56066
  if (!current2.isFile() || version2(current2) !== version2(metadata) || await realpath17(file3) !== resolved) {
@@ -55600,8 +56101,8 @@ init_zod();
55600
56101
  init_protocol();
55601
56102
  import { execFile as execFile19 } from "node:child_process";
55602
56103
  import { createHash as createHash26 } from "node:crypto";
55603
- import { lstat as lstat29, mkdir as mkdir25, readFile as readFile46, realpath as realpath18, rename as rename8, rm as rm13, writeFile as writeFile9 } from "node:fs/promises";
55604
- import path102 from "node:path";
56104
+ import { lstat as lstat30, mkdir as mkdir26, readFile as readFile47, realpath as realpath18, rename as rename9, rm as rm13, writeFile as writeFile10 } from "node:fs/promises";
56105
+ import path104 from "node:path";
55605
56106
  import { promisify as promisify18 } from "node:util";
55606
56107
  var exec18 = promisify18(execFile19);
55607
56108
  var SHA = /^[0-9a-f]{40}$/;
@@ -55629,14 +56130,14 @@ function blobSha(content) {
55629
56130
  return createHash26("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
55630
56131
  }
55631
56132
  async function isRepository2(store) {
55632
- return await lstat29(path102.join(store, ".git")).catch(() => void 0) !== void 0;
56133
+ return await lstat30(path104.join(store, ".git")).catch(() => void 0) !== void 0;
55633
56134
  }
55634
- function storeHead(store, indexFile = path102.join(bridgeRoot(), "store-snapshot.index")) {
56135
+ function storeHead(store, indexFile = path104.join(bridgeRoot(), "store-snapshot.index")) {
55635
56136
  return serialized2(async () => {
55636
56137
  if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
55637
- await mkdir25(path102.dirname(indexFile), { recursive: true, mode: 448 });
56138
+ await mkdir26(path104.dirname(indexFile), { recursive: true, mode: 448 });
55638
56139
  const env = { GIT_INDEX_FILE: indexFile };
55639
- if (!await lstat29(indexFile).catch(() => void 0)) {
56140
+ if (!await lstat30(indexFile).catch(() => void 0)) {
55640
56141
  const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
55641
56142
  await git5(store, head.trim() ? ["read-tree", "HEAD"] : ["read-tree", "--empty"], env);
55642
56143
  }
@@ -55661,27 +56162,27 @@ async function storeBlob(store, sha) {
55661
56162
  return { sha, encoding: "base64", content: stdout.toString("base64") };
55662
56163
  }
55663
56164
  async function storeFile(store, relative3) {
55664
- const normalized = path102.posix.normalize(relative3);
55665
- if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path102.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
56165
+ const normalized = path104.posix.normalize(relative3);
56166
+ if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path104.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
55666
56167
  throw new BridgeError(400, "Invalid store path.");
55667
56168
  }
55668
56169
  const root = await realpath18(store);
55669
- let parent = path102.dirname(path102.join(root, normalized));
56170
+ let parent = path104.dirname(path104.join(root, normalized));
55670
56171
  for (; ; ) {
55671
56172
  const real2 = await realpath18(parent).catch(() => void 0);
55672
56173
  if (real2) {
55673
- if (real2 !== root && !real2.startsWith(root + path102.sep)) throw new BridgeError(400, "Invalid store path.");
56174
+ if (real2 !== root && !real2.startsWith(root + path104.sep)) throw new BridgeError(400, "Invalid store path.");
55674
56175
  break;
55675
56176
  }
55676
- parent = path102.dirname(parent);
56177
+ parent = path104.dirname(parent);
55677
56178
  }
55678
- const file3 = path102.join(root, normalized);
55679
- const info = await lstat29(file3).catch(() => void 0);
56179
+ const file3 = path104.join(root, normalized);
56180
+ const info = await lstat30(file3).catch(() => void 0);
55680
56181
  if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
55681
56182
  return file3;
55682
56183
  }
55683
56184
  async function currentSha(file3) {
55684
- const content = await readFile46(file3).catch((error62) => {
56185
+ const content = await readFile47(file3).catch((error62) => {
55685
56186
  if (error62.code === "ENOENT") return null;
55686
56187
  throw error62;
55687
56188
  });
@@ -55696,10 +56197,10 @@ function putStoreFile(store, data) {
55696
56197
  return serialized2(async () => {
55697
56198
  const file3 = await storeFile(store, input2.path);
55698
56199
  if (await currentSha(file3) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
55699
- await mkdir25(path102.dirname(file3), { recursive: true });
56200
+ await mkdir26(path104.dirname(file3), { recursive: true });
55700
56201
  const temporary = `${file3}.phren-${process.pid}-${Date.now()}`;
55701
- await writeFile9(temporary, content, { flag: "wx" });
55702
- await rename8(temporary, file3);
56202
+ await writeFile10(temporary, content, { flag: "wx" });
56203
+ await rename9(temporary, file3);
55703
56204
  return { content: { sha: blobSha(content), path: input2.path }, commit: { sha: blobSha(content) } };
55704
56205
  });
55705
56206
  }
@@ -55730,10 +56231,10 @@ init_protocol();
55730
56231
  // src/bridge/simulators.ts
55731
56232
  init_protocol();
55732
56233
  import { execFile as execFile20 } from "node:child_process";
55733
- import { chmod as chmod5, mkdir as mkdir26, readFile as readFile47, rename as rename9, stat as stat27, unlink as unlink8, writeFile as writeFile10 } from "node:fs/promises";
56234
+ import { chmod as chmod5, mkdir as mkdir27, readFile as readFile48, rename as rename10, stat as stat27, unlink as unlink9, writeFile as writeFile11 } from "node:fs/promises";
55734
56235
  import { tmpdir as tmpdir4 } from "node:os";
55735
- import path103 from "node:path";
55736
- import { createHash as createHash27, randomUUID as randomUUID24 } from "node:crypto";
56236
+ import path105 from "node:path";
56237
+ import { createHash as createHash27, randomUUID as randomUUID25 } from "node:crypto";
55737
56238
  import { promisify as promisify19 } from "node:util";
55738
56239
  var exec19 = promisify19(execFile20);
55739
56240
  var UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
@@ -55760,15 +56261,15 @@ async function bootedSimulators() {
55760
56261
  async function simulatorScreenshot(udid) {
55761
56262
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
55762
56263
  if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
55763
- const file3 = path103.join(tmpdir4(), `phren-sim-${randomUUID24()}.png`);
56264
+ const file3 = path105.join(tmpdir4(), `phren-sim-${randomUUID25()}.png`);
55764
56265
  try {
55765
56266
  await exec19("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file3], { timeout: 15e3 });
55766
- return await readFile47(file3);
56267
+ return await readFile48(file3);
55767
56268
  } catch (error62) {
55768
56269
  if (error62 instanceof BridgeError) throw error62;
55769
56270
  throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
55770
56271
  } finally {
55771
- await unlink8(file3).catch(() => void 0);
56272
+ await unlink9(file3).catch(() => void 0);
55772
56273
  }
55773
56274
  }
55774
56275
  var building;
@@ -55779,27 +56280,27 @@ function helper() {
55779
56280
  return building;
55780
56281
  }
55781
56282
  async function buildHelper() {
55782
- const dir = path103.join(bridgeRoot(), "native");
55783
- const binary = path103.join(dir, "simtap");
55784
- const code = true ? '// Touches and keys for the iOS Simulator, without AppleScript: the window\n// is found through the Accessibility API and events are posted with CGEvent,\n// so one Accessibility grant for this helper is all macOS asks for.\n// Built on demand by Phren Hook with swiftc; see simulators.ts.\nimport ApplicationServices\nimport Cocoa\n\nfunc fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }\n\nlet args = CommandLine.arguments\nguard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise") }\nlet prefix = args[1], command = args[2]\n\nguard AXIsProcessTrusted() else { fail(3, "accessibility") }\nguard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }\nlet element = AXUIElementCreateApplication(app.processIdentifier)\nvar windowsRef: CFTypeRef?\nAXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)\nlet windows = (windowsRef as? [AXUIElement]) ?? []\nvar target: AXUIElement?\nfor window in windows {\n var titleRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)\n if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }\n}\nguard let window = target else { fail(5, "no window for \\(prefix)") }\n\nfunc frame(_ window: AXUIElement) -> CGRect {\n var posRef: CFTypeRef?, sizeRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)\n AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)\n var pos = CGPoint.zero, size = CGSize.zero\n if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }\n if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }\n return CGRect(origin: pos, size: size)\n}\nfunc raise() {\n app.activate(options: [])\n AXUIElementPerformAction(window, kAXRaiseAction as CFString)\n usleep(120_000)\n}\nfunc post(_ event: CGEvent?) {\n guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }\n event?.postToPid(app.processIdentifier)\n usleep(40_000)\n}\n\nswitch command {\ncase "raise": raise()\ncase "tap":\n guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }\n raise()\n let f = frame(window)\n // The device screen fills the window below its title bar.\n let titleBar: CGFloat = 28\n let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))\n post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))\ncase "key":\n guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }\n raise()\n var flags: CGEventFlags = []\n if args.contains("cmd") { flags.insert(.maskCommand) }\n if args.contains("shift") { flags.insert(.maskShift) }\n let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)\n down?.flags = flags; up?.flags = flags\n post(down); post(up)\ncase "type":\n guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }\n let submit = args.count == 5 && args[4] == "submit"\n guard args[3].unicodeScalars.allSatisfy({ scalar in\n (scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)\n }) else { fail(2, "invalid type controls; newline needs submit") }\n raise()\n for scalar in args[3].unicodeScalars {\n var chars = Array(String(scalar).utf16)\n let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)\n down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n post(down); post(up)\n }\ndefault: fail(2, "unknown command \\(command)")\n}\n' : await readFile47(new URL("./native/simtap.swift", import.meta.url), "utf8");
56283
+ const dir = path105.join(bridgeRoot(), "native");
56284
+ const binary = path105.join(dir, "simtap");
56285
+ const code = true ? '// Touches and keys for the iOS Simulator, without AppleScript: the window\n// is found through the Accessibility API and events are posted with CGEvent,\n// so one Accessibility grant for this helper is all macOS asks for.\n// Built on demand by Phren Hook with swiftc; see simulators.ts.\nimport ApplicationServices\nimport Cocoa\n\nfunc fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }\n\nlet args = CommandLine.arguments\nguard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise") }\nlet prefix = args[1], command = args[2]\n\nguard AXIsProcessTrusted() else { fail(3, "accessibility") }\nguard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }\nlet element = AXUIElementCreateApplication(app.processIdentifier)\nvar windowsRef: CFTypeRef?\nAXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)\nlet windows = (windowsRef as? [AXUIElement]) ?? []\nvar target: AXUIElement?\nfor window in windows {\n var titleRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)\n if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }\n}\nguard let window = target else { fail(5, "no window for \\(prefix)") }\n\nfunc frame(_ window: AXUIElement) -> CGRect {\n var posRef: CFTypeRef?, sizeRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)\n AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)\n var pos = CGPoint.zero, size = CGSize.zero\n if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }\n if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }\n return CGRect(origin: pos, size: size)\n}\nfunc raise() {\n app.activate(options: [])\n AXUIElementPerformAction(window, kAXRaiseAction as CFString)\n usleep(120_000)\n}\nfunc post(_ event: CGEvent?) {\n guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }\n event?.postToPid(app.processIdentifier)\n usleep(40_000)\n}\n\nswitch command {\ncase "raise": raise()\ncase "tap":\n guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }\n raise()\n let f = frame(window)\n // The device screen fills the window below its title bar.\n let titleBar: CGFloat = 28\n let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))\n post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))\ncase "key":\n guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }\n raise()\n var flags: CGEventFlags = []\n if args.contains("cmd") { flags.insert(.maskCommand) }\n if args.contains("shift") { flags.insert(.maskShift) }\n let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)\n down?.flags = flags; up?.flags = flags\n post(down); post(up)\ncase "type":\n guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }\n let submit = args.count == 5 && args[4] == "submit"\n guard args[3].unicodeScalars.allSatisfy({ scalar in\n (scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)\n }) else { fail(2, "invalid type controls; newline needs submit") }\n raise()\n for scalar in args[3].unicodeScalars {\n var chars = Array(String(scalar).utf16)\n let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)\n down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n post(down); post(up)\n }\ndefault: fail(2, "unknown command \\(command)")\n}\n' : await readFile48(new URL("./native/simtap.swift", import.meta.url), "utf8");
55785
56286
  const digest2 = createHash27("sha256").update(code).digest("hex");
55786
- const saved = await readFile47(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
56287
+ const saved = await readFile48(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
55787
56288
  if (await stat27(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
55788
- await mkdir26(dir, { recursive: true, mode: 448 });
55789
- const temporary = path103.join(dir, `simtap.${randomUUID24()}`), source = temporary + ".swift";
56289
+ await mkdir27(dir, { recursive: true, mode: 448 });
56290
+ const temporary = path105.join(dir, `simtap.${randomUUID25()}`), source = temporary + ".swift";
55790
56291
  const sidecar = temporary + ".sha256";
55791
56292
  try {
55792
- await writeFile10(source, code, { mode: 384, flag: "wx" });
56293
+ await writeFile11(source, code, { mode: 384, flag: "wx" });
55793
56294
  await exec19("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
55794
56295
  throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
55795
56296
  });
55796
56297
  await chmod5(temporary, 448);
55797
- const binarySha = createHash27("sha256").update(await readFile47(temporary)).digest("hex");
55798
- await writeFile10(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
55799
- await rename9(temporary, binary);
55800
- await rename9(sidecar, binary + ".sha256");
56298
+ const binarySha = createHash27("sha256").update(await readFile48(temporary)).digest("hex");
56299
+ await writeFile11(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
56300
+ await rename10(temporary, binary);
56301
+ await rename10(sidecar, binary + ".sha256");
55801
56302
  } finally {
55802
- await Promise.all([source, temporary, sidecar].map((file3) => unlink8(file3).catch(() => void 0)));
56303
+ await Promise.all([source, temporary, sidecar].map((file3) => unlink9(file3).catch(() => void 0)));
55803
56304
  }
55804
56305
  return binary;
55805
56306
  }
@@ -55812,8 +56313,8 @@ function simtap(name, ...args) {
55812
56313
  }
55813
56314
  async function executeSimtap(name, ...args) {
55814
56315
  const binary = await helper();
55815
- const saved = await readFile47(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
55816
- const binarySha = createHash27("sha256").update(await readFile47(binary)).digest("hex");
56316
+ const saved = await readFile48(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
56317
+ const binarySha = createHash27("sha256").update(await readFile48(binary)).digest("hex");
55817
56318
  if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
55818
56319
  try {
55819
56320
  await exec19(binary, [name, ...args], { timeout: 6e4 });
@@ -55899,7 +56400,7 @@ init_transcripts();
55899
56400
  init_transcript_index();
55900
56401
  init_transcripts();
55901
56402
  import { homedir as homedir20, tmpdir as tmpdir5 } from "node:os";
55902
- import path104 from "node:path";
56403
+ import path106 from "node:path";
55903
56404
  init_protocol();
55904
56405
  var cache = /* @__PURE__ */ new Map();
55905
56406
  var modelCache = /* @__PURE__ */ new Map();
@@ -56037,7 +56538,7 @@ function describe3(tool, args) {
56037
56538
  return "";
56038
56539
  };
56039
56540
  const firstLine = (v) => v.split(/\r?\n/).map((l) => l.trim()).find((l) => l) ?? "";
56040
- const base = (v) => path104.basename(v.split(" \xB7 ")[0].trim()) || "file";
56541
+ const base = (v) => path106.basename(v.split(" \xB7 ")[0].trim()) || "file";
56041
56542
  const name = tool.toLowerCase();
56042
56543
  let value2;
56043
56544
  if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
@@ -56076,8 +56577,8 @@ init_home_paths();
56076
56577
  init_terminal_text();
56077
56578
  init_codex_servers();
56078
56579
  init_herdr();
56079
- import { open as open22 } from "node:fs/promises";
56080
- import path105 from "node:path";
56580
+ import { open as open23 } from "node:fs/promises";
56581
+ import path107 from "node:path";
56081
56582
  init_protocol();
56082
56583
  init_terminal();
56083
56584
  init_terminal_choice();
@@ -56108,7 +56609,7 @@ function lastIndexedName(text4, thread) {
56108
56609
  return void 0;
56109
56610
  }
56110
56611
  async function tail(file3) {
56111
- const handle = await open22(file3, "r").catch(() => void 0);
56612
+ const handle = await open23(file3, "r").catch(() => void 0);
56112
56613
  if (!handle) return void 0;
56113
56614
  try {
56114
56615
  const { size } = await handle.stat();
@@ -56138,7 +56639,7 @@ var defaultRenameDeps = {
56138
56639
  return text4 === void 0 ? void 0 : lastCustomTitle(text4);
56139
56640
  },
56140
56641
  async codexIndexTitle(thread) {
56141
- const text4 = await tail(path105.join(codexHome(), "session_index.jsonl"));
56642
+ const text4 = await tail(path107.join(codexHome(), "session_index.jsonl"));
56142
56643
  return text4 === void 0 ? void 0 : lastIndexedName(text4, thread);
56143
56644
  },
56144
56645
  sleep: (ms) => new Promise((resolve11) => setTimeout(resolve11, ms)),
@@ -56224,8 +56725,8 @@ async function renameSession(server, data, deps2 = defaultRenameDeps) {
56224
56725
  }
56225
56726
 
56226
56727
  // src/bridge/server-launch.ts
56227
- import { mkdir as mkdir28, readFile as readFile48 } from "node:fs/promises";
56228
- import path107 from "node:path";
56728
+ import { mkdir as mkdir29, readFile as readFile49 } from "node:fs/promises";
56729
+ import path109 from "node:path";
56229
56730
  init_zod();
56230
56731
  init_home_paths();
56231
56732
  init_herdr();
@@ -56238,8 +56739,8 @@ init_zod();
56238
56739
  init_utils_helpers();
56239
56740
  init_metrics();
56240
56741
  import { execFile as execFile21 } from "node:child_process";
56241
- import { mkdir as mkdir27, realpath as realpath19, rm as rm14, stat as stat28 } from "node:fs/promises";
56242
- import path106 from "node:path";
56742
+ import { mkdir as mkdir28, realpath as realpath19, rm as rm14, stat as stat28 } from "node:fs/promises";
56743
+ import path108 from "node:path";
56243
56744
  import { promisify as promisify20 } from "node:util";
56244
56745
  init_protocol();
56245
56746
  var exec20 = promisify20(execFile21);
@@ -56268,11 +56769,11 @@ async function createLaunchWorktree(cwd, request9) {
56268
56769
  if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
56269
56770
  throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
56270
56771
  }
56271
- const worktree = path106.join(root, ".claude", "worktrees", worktreeFolderName(branch));
56772
+ const worktree = path108.join(root, ".claude", "worktrees", worktreeFolderName(branch));
56272
56773
  if (await stat28(worktree).then(() => true, () => false)) {
56273
56774
  throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
56274
56775
  }
56275
- await mkdir27(path106.dirname(worktree), { recursive: true });
56776
+ await mkdir28(path108.dirname(worktree), { recursive: true });
56276
56777
  try {
56277
56778
  await git6(root, "worktree", "add", "-b", branch, worktree, head);
56278
56779
  } catch (error62) {
@@ -56280,8 +56781,8 @@ async function createLaunchWorktree(cwd, request9) {
56280
56781
  throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
56281
56782
  }
56282
56783
  const abs = await realpath19(worktree);
56283
- const inside = path106.relative(root, await realpath19(cwd));
56284
- const start = inside && !inside.startsWith("..") ? path106.join(abs, inside) : abs;
56784
+ const inside = path108.relative(root, await realpath19(cwd));
56785
+ const start = inside && !inside.startsWith("..") ? path108.join(abs, inside) : abs;
56285
56786
  const startDir = await stat28(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
56286
56787
  return {
56287
56788
  cwd: startDir,
@@ -56309,12 +56810,12 @@ async function conductorBrief() {
56309
56810
  let source;
56310
56811
  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\nLinuxbox 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 and Codex only).\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: Linuxbox 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';
56311
56812
  else {
56312
- const here = path107.dirname(fileURLToPath(import.meta.url));
56813
+ const here = path109.dirname(fileURLToPath(import.meta.url));
56313
56814
  for (const candidate of [
56314
- path107.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
56315
- path107.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
56815
+ path109.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
56816
+ path109.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
56316
56817
  ]) {
56317
- source = await readFile48(candidate, "utf8").catch(() => void 0);
56818
+ source = await readFile49(candidate, "utf8").catch(() => void 0);
56318
56819
  if (source !== void 0) break;
56319
56820
  }
56320
56821
  }
@@ -56332,15 +56833,15 @@ function effortArgs(kind, effort) {
56332
56833
  }
56333
56834
  async function prepareConductor(kind, effort, model) {
56334
56835
  const brief = await conductorBrief();
56335
- const briefDirectory2 = path107.join(bridgeRoot(), "conductor");
56336
- await mkdir28(briefDirectory2, { recursive: true, mode: 448 });
56337
- const briefFile = path107.join(briefDirectory2, "brief.md");
56338
- if (await readFile48(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
56836
+ const briefDirectory2 = path109.join(bridgeRoot(), "conductor");
56837
+ await mkdir29(briefDirectory2, { recursive: true, mode: 448 });
56838
+ const briefFile = path109.join(briefDirectory2, "brief.md");
56839
+ if (await readFile49(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
56339
56840
  if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
56340
56841
  if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
56341
56842
  if (kind === "opencode") {
56342
- const directory = path107.join(process.env.XDG_CONFIG_HOME || path107.join(homeDir(), ".config"), "opencode", "agents");
56343
- const file3 = path107.join(directory, "conductor.md");
56843
+ const directory = path109.join(process.env.XDG_CONFIG_HOME || path109.join(homeDir(), ".config"), "opencode", "agents");
56844
+ const file3 = path109.join(directory, "conductor.md");
56344
56845
  const definition = `---
56345
56846
  description: Coordinate the owner's work across agent sessions.
56346
56847
  mode: primary
@@ -56348,8 +56849,8 @@ mode: primary
56348
56849
 
56349
56850
  ${brief}
56350
56851
  `;
56351
- await mkdir28(directory, { recursive: true, mode: 448 });
56352
- if (await readFile48(file3, "utf8").catch(() => void 0) !== definition) await atomic(file3, definition, 420);
56852
+ await mkdir29(directory, { recursive: true, mode: 448 });
56853
+ if (await readFile49(file3, "utf8").catch(() => void 0) !== definition) await atomic(file3, definition, 420);
56353
56854
  return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
56354
56855
  }
56355
56856
  throw new BridgeError(400, "The selected harness cannot run as a conductor.");
@@ -56444,7 +56945,7 @@ async function requireAvailable(kind, account) {
56444
56945
  }
56445
56946
  async function launchSession(server, data, options = {}) {
56446
56947
  const role = external_exports.enum(["agent", "conductor"]).default("agent").parse(data.role);
56447
- const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path107.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
56948
+ const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path109.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
56448
56949
  const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
56449
56950
  if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
56450
56951
  const label2 = plainText(200).parse(data.label);
@@ -56587,6 +57088,15 @@ async function launchSession(server, data, options = {}) {
56587
57088
  );
56588
57089
  const chat = !sessionId2 && pane && pane.agent === kind ? await paneChatState(server, pane).catch(() => ({})) : {};
56589
57090
  const target = sessionId2 ? { ...binding, session: sessionId2 } : chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : void 0;
57091
+ if (brief && role === "agent") {
57092
+ await new JobRegistry().register({
57093
+ pane: { server, pane: created.paneId, ...created.workspaceId ? { workspace: created.workspaceId } : {}, agent: kind, label: label2 },
57094
+ ...sessionId2 ? { session: sessionId2 } : {},
57095
+ agent: kind,
57096
+ label: label2,
57097
+ command: kind
57098
+ }).catch(() => void 0);
57099
+ }
56590
57100
  return {
56591
57101
  ok: true,
56592
57102
  ...created,
@@ -56617,7 +57127,7 @@ async function workspaceAction(server, operation, data) {
56617
57127
  if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
56618
57128
  if (pane && !objects(s.panes).some((p) => p.pane_id === pane && (!tab || p.tab_id === tab) && (!workspace || p.workspace_id === workspace))) throw new BridgeError(409, "The pane changed.");
56619
57129
  const label2 = data.label === void 0 ? void 0 : external_exports.string().min(1).max(200).refine((t) => !/[\x00-\x1f\x7f]/.test(t)).parse(data.label);
56620
- const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path107.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
57130
+ const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path109.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
56621
57131
  if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
56622
57132
  else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
56623
57133
  else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
@@ -56717,11 +57227,12 @@ init_zod();
56717
57227
  init_protocol();
56718
57228
  import { once } from "node:events";
56719
57229
  var SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
56720
- var SPEECH_FORMATS = ["pcm_44100", "mp3_44100_192", "pcm_24000"];
57230
+ var SPEECH_FORMATS = ["pcm_44100", "mp3_44100_192", "mp3_44100_128", "pcm_24000"];
56721
57231
  var BASE_FORMAT = "pcm_24000";
56722
57232
  var SPEECH_FORMAT_INFO = {
56723
57233
  pcm_44100: { audio: "pcm_s16le;rate=44100;channels=1", sampleRate: 44100, contentType: "application/octet-stream" },
56724
57234
  mp3_44100_192: { audio: "mp3;rate=44100;bitrate=192000;channels=1", sampleRate: 44100, contentType: "audio/mpeg" },
57235
+ mp3_44100_128: { audio: "mp3;rate=44100;bitrate=128000;channels=1", sampleRate: 44100, contentType: "audio/mpeg" },
56725
57236
  pcm_24000: { audio: SPEECH_AUDIO, sampleRate: 24e3, contentType: "application/octet-stream" }
56726
57237
  };
56727
57238
  var SPEECH_SLOW_MS = 1500;
@@ -56953,9 +57464,7 @@ async function childActivity(source, session) {
56953
57464
  const key3 = `${source}\0${session}`, now = Date.now(), cached3 = childActivityCache.get(key3);
56954
57465
  if (cached3 && now - cached3.at < CHILD_ACTIVITY_CACHE_MS) return cached3.result;
56955
57466
  const result = childAgentTree(source, session).then((tree) => {
56956
- const running2 = tree.flatMap(function visit3(child) {
56957
- return [child, ...child.children.flatMap(visit3)];
56958
- }).filter((child) => child.state === "running");
57467
+ const running2 = runningChildAgents(tree);
56959
57468
  return { runningChildren: running2.length, childProviders: [...new Set(running2.map((child) => child.provider))].sort() };
56960
57469
  }).catch(() => ({ runningChildren: 0, childProviders: [] }));
56961
57470
  childActivityCache.set(key3, { at: now, result });
@@ -57307,7 +57816,7 @@ function createRouteHandler(ctx) {
57307
57816
  case "/v1/files/range": {
57308
57817
  let root;
57309
57818
  if (url2.searchParams.get("scope") === "uploads") {
57310
- root = path108.join(bridgeRoot(), "uploads");
57819
+ root = path110.join(bridgeRoot(), "uploads");
57311
57820
  } else if (url2.searchParams.has("session")) {
57312
57821
  const target = targetFromURL(url2), pane = await validateTarget(target);
57313
57822
  const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
@@ -57531,6 +58040,8 @@ function createRouteHandler(ctx) {
57531
58040
  } : void 0);
57532
58041
  } else if (url2.pathname === "/v1/sessions/rename") {
57533
58042
  result = await renameSession(selectedServer(url2), data);
58043
+ } else if (url2.pathname === "/v1/jobs/cleanup") {
58044
+ result = { ok: true, ...await ctx.resources.cleanupJobs() };
57534
58045
  } else if (url2.pathname === "/v1/schedules") {
57535
58046
  result = await scheduler.statuses();
57536
58047
  } else if (url2.pathname === "/v1/schedules/run") {
@@ -57569,7 +58080,7 @@ function createRouteHandler(ctx) {
57569
58080
  } else if (url2.pathname === "/v1/dispatch/returns") {
57570
58081
  result = { returns: await ctx.returns.take() };
57571
58082
  } else if (url2.pathname === "/v1/dispatch/approve") {
57572
- const body2 = external_exports.object({ id: external_exports.string().uuid(), decision: external_exports.enum(["approve", "deny"]), actionId: external_exports.string().min(1).max(200), origin: originPaneSchema.optional() }).strict().parse(data);
58083
+ const body2 = external_exports.object({ id: external_exports.string().uuid(), decision: external_exports.enum(approvalDecisions), actionId: external_exports.string().min(1).max(200), origin: originPaneSchema.optional() }).strict().parse(data);
57573
58084
  await ctx.returns.answerApproval(body2.id, body2.decision, body2.actionId, body2.origin);
57574
58085
  result = { ok: true };
57575
58086
  } else if (url2.pathname === "/v1/conductor/grants") {
@@ -57674,7 +58185,7 @@ init_protocol();
57674
58185
  // src/bridge/transcript-preview.ts
57675
58186
  init_codex_threads();
57676
58187
  import { constants as constants6 } from "node:fs";
57677
- import { open as open23 } from "node:fs/promises";
58188
+ import { open as open24 } from "node:fs/promises";
57678
58189
  init_protocol();
57679
58190
  init_transcript_index();
57680
58191
  init_terminal_text();
@@ -57904,7 +58415,7 @@ async function readDeltaPreview(target, file3, rollout) {
57904
58415
  if (target.source === "codex") return await codexThreadPreview(target.session) ?? (file3 && rollout ? await rollout.read(file3).catch(() => null) : null);
57905
58416
  if (target.source !== "opencode" || !file3) return null;
57906
58417
  try {
57907
- const handle = await open23(file3 + ".preview.json", constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
58418
+ const handle = await open24(file3 + ".preview.json", constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
57908
58419
  let bytes;
57909
58420
  try {
57910
58421
  const stat29 = await handle.stat();
@@ -58015,7 +58526,7 @@ var TranscriptPreviewStream = class {
58015
58526
  }
58016
58527
  }
58017
58528
  async update(status, file3, now) {
58018
- const readAt = now ?? Date.now();
58529
+ const readAt2 = now ?? Date.now();
58019
58530
  let next = null;
58020
58531
  if (status === "working") {
58021
58532
  this.wasWorking = true;
@@ -58026,8 +58537,8 @@ var TranscriptPreviewStream = class {
58026
58537
  if (text4 && [...this.codexCompleted].some((completed2) => completed2.startsWith(text4))) next = null;
58027
58538
  }
58028
58539
  } else if (this.target.source === "claude" && this.startedAt && !this.ended) {
58029
- if (readAt - this.lastRead < PREVIEW_INTERVAL_MS) return void 0;
58030
- this.lastRead = readAt;
58540
+ if (readAt2 - this.lastRead < PREVIEW_INTERVAL_MS) return void 0;
58541
+ this.lastRead = readAt2;
58031
58542
  const pane = await this.pane();
58032
58543
  const text4 = this.landed ? "" : claudePanePreview(
58033
58544
  pane,
@@ -58041,8 +58552,8 @@ var TranscriptPreviewStream = class {
58041
58552
  }
58042
58553
  if (text4) next = { turnStartedAt: this.startedAt, text: text4 };
58043
58554
  } else if (this.target.source === "copilot" && this.startedAt && !this.ended) {
58044
- if (readAt - this.lastRead < PREVIEW_INTERVAL_MS) return void 0;
58045
- this.lastRead = readAt;
58555
+ if (readAt2 - this.lastRead < PREVIEW_INTERVAL_MS) return void 0;
58556
+ this.lastRead = readAt2;
58046
58557
  const thinking = copilotThinking(await this.pane());
58047
58558
  if (thinking) {
58048
58559
  this.activity = thinking;
@@ -58114,6 +58625,7 @@ function transcriptStreams(ctx) {
58114
58625
  let busy = false, ready = false, first = true;
58115
58626
  let awaitingTranscript = false, lastTranscriptLookup = 0;
58116
58627
  let initialPane;
58628
+ let busyAt = 0;
58117
58629
  const pending = [];
58118
58630
  const stop = () => {
58119
58631
  abort.abort();
@@ -58182,7 +58694,10 @@ function transcriptStreams(ctx) {
58182
58694
  choice: { title: queued.title, options: queued.options }
58183
58695
  } : void 0).catch(() => void 0) : void 0);
58184
58696
  const codexServed = target.source === "codex" && !!codexServers.forTarget(target);
58185
- const { settings, settingsState } = settingsSwitcher ? await settingsSwitcher.streamSettings(target, pane.terminal_id, codexServed) : { settings: settingsCapabilities(target.source, codexServed), settingsState: void 0 };
58697
+ const { settings, settingsState, suggestion } = settingsSwitcher ? await settingsSwitcher.streamSettings(target, pane.terminal_id, codexServed) : { settings: settingsCapabilities(target.source, codexServed), settingsState: void 0, suggestion: void 0 };
58698
+ const between = ["idle", "done"].includes(String(pane.agent_status)) && !pendingApproval && !servedQuestion;
58699
+ if (!between) busyAt = Date.now();
58700
+ const nextPrompt = between && suggestion && suggestion.readAt > busyAt ? suggestion.text : void 0;
58186
58701
  const historyHealth = target.source === "codex" ? await threadHealth(target.session, pane.agent_status) : { stalled: false };
58187
58702
  send(client, { agentStatus: {
58188
58703
  source: target.source,
@@ -58193,6 +58708,7 @@ function transcriptStreams(ctx) {
58193
58708
  terminalPrompt,
58194
58709
  ...waiting && agentHooks.passwordPrompt(target) ? { passwordPrompt: true } : {},
58195
58710
  compacting: agentHooks.compacting(target),
58711
+ ...nextPrompt ? { suggestion: nextPrompt } : {},
58196
58712
  ...historyHealth.stalled ? { historyStalled: true, historyStalledSince: historyHealth.since } : {},
58197
58713
  modules: info.modules,
58198
58714
  store: info.store,
@@ -58384,12 +58900,12 @@ init_codex_servers();
58384
58900
  init_home_paths();
58385
58901
  init_logger();
58386
58902
  init_protocol();
58387
- import { readFile as readFile49 } from "node:fs/promises";
58388
- import path109 from "node:path";
58903
+ import { readFile as readFile50 } from "node:fs/promises";
58904
+ import path111 from "node:path";
58389
58905
  var REFRESH_AFTER_MS = 6 * 864e5;
58390
- async function lastCodexRefresh(file3 = path109.join(codexHome(), "auth.json")) {
58906
+ async function lastCodexRefresh(file3 = path111.join(codexHome(), "auth.json")) {
58391
58907
  try {
58392
- const auth = object2(JSON.parse(await readFile49(file3, "utf8")));
58908
+ const auth = object2(JSON.parse(await readFile50(file3, "utf8")));
58393
58909
  if (!object2(auth.tokens).refresh_token) return void 0;
58394
58910
  const at = Date.parse(String(auth.last_refresh ?? ""));
58395
58911
  return Number.isFinite(at) ? at : 0;
@@ -58440,15 +58956,15 @@ async function serve(version3, options = {}) {
58440
58956
  if (!modules.has("hook")) throw new BridgeError(404, disabledHint("hook"));
58441
58957
  const activeCapabilities = capabilitiesForModules(modules);
58442
58958
  const root = bridgeRoot();
58443
- await mkdir29(root, { recursive: true, mode: 448 });
58959
+ await mkdir30(root, { recursive: true, mode: 448 });
58444
58960
  await chmod6(root, 448);
58445
58961
  let computerID2;
58446
- const identityFile = path110.join(root, "computer-id");
58962
+ const identityFile = path112.join(root, "computer-id");
58447
58963
  try {
58448
- computerID2 = (await readFile50(identityFile, "utf8")).trim();
58964
+ computerID2 = (await readFile51(identityFile, "utf8")).trim();
58449
58965
  } catch {
58450
- computerID2 = randomUUID25();
58451
- await writeFile11(identityFile, computerID2, { flag: "wx", mode: 384 });
58966
+ computerID2 = randomUUID26();
58967
+ await writeFile12(identityFile, computerID2, { flag: "wx", mode: 384 });
58452
58968
  }
58453
58969
  const launches = new LaunchLimiter();
58454
58970
  const dispatches = modules.has("conductor") ? new DispatchService({
@@ -58562,7 +59078,7 @@ async function serve(version3, options = {}) {
58562
59078
  if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
58563
59079
  function gatewayTiming() {
58564
59080
  try {
58565
- const parsed = JSON.parse(readFileSync36(path110.join(root, "gateway.json"), "utf8"));
59081
+ const parsed = JSON.parse(readFileSync37(path112.join(root, "gateway.json"), "utf8"));
58566
59082
  if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
58567
59083
  } catch {
58568
59084
  }
@@ -58591,7 +59107,7 @@ async function serve(version3, options = {}) {
58591
59107
  launch: (server, data) => launches.run(() => launchSession(server, data, { canary: true })),
58592
59108
  scheduler
58593
59109
  });
58594
- const old = await lstat30(socketPath()).catch(() => null);
59110
+ const old = await lstat31(socketPath()).catch(() => null);
58595
59111
  if (old) {
58596
59112
  if (!old.isSocket() || process.getuid && old.uid !== process.getuid()) throw new Error("Refusing to replace an unexpected hook socket.");
58597
59113
  const { connect: connect4 } = await import("node:net");
@@ -58604,11 +59120,11 @@ async function serve(version3, options = {}) {
58604
59120
  s.on("error", () => resolve11(false));
58605
59121
  });
58606
59122
  if (live) throw new Error("Phren Hook is already running.");
58607
- await unlink9(socketPath());
59123
+ await unlink10(socketPath());
58608
59124
  }
58609
59125
  const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
58610
59126
  };
58611
- if (modules.has("git")) await rm15(path110.join(root, "changes-scratch"), { recursive: true, force: true });
59127
+ if (modules.has("git")) await rm15(path112.join(root, "changes-scratch"), { recursive: true, force: true });
58612
59128
  const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
58613
59129
  const { stream } = streams;
58614
59130
  const overview = overviewStream({
@@ -58777,7 +59293,7 @@ async function serve(version3, options = {}) {
58777
59293
  process.once("SIGTERM", stop);
58778
59294
  process.once("SIGINT", stop);
58779
59295
  });
58780
- await unlink9(socketPath()).catch(() => {
59296
+ await unlink10(socketPath()).catch(() => {
58781
59297
  });
58782
59298
  }
58783
59299
 
@@ -58789,9 +59305,9 @@ init_protocol();
58789
59305
  init_profile_store();
58790
59306
  init_phren_paths();
58791
59307
  import { execFile as execFile22 } from "node:child_process";
58792
- import { readFile as readFile51 } from "node:fs/promises";
59308
+ import { readFile as readFile52 } from "node:fs/promises";
58793
59309
  import { homedir as homedir21, hostname as hostname13, userInfo as userInfo5 } from "node:os";
58794
- import path111 from "node:path";
59310
+ import path113 from "node:path";
58795
59311
  import { promisify as promisify21 } from "node:util";
58796
59312
  init_protocol();
58797
59313
  var exec21 = promisify21(execFile22);
@@ -58838,11 +59354,11 @@ async function probe2(host) {
58838
59354
  return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
58839
59355
  }
58840
59356
  async function discoverComputers(options = {}) {
58841
- const config3 = options.sshConfig ?? await readFile51(path111.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
59357
+ const config3 = options.sshConfig ?? await readFile52(path113.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
58842
59358
  const store = options.store !== void 0 ? options.store : findPhrenPath();
58843
59359
  const machines = store ? listMachines(store) : void 0;
58844
59360
  const { peers } = await optionalHookPeers();
58845
- const own2 = (await readFile51(path111.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
59361
+ const own2 = (await readFile52(path113.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
58846
59362
  const known2 = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
58847
59363
  const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known2.has(computerLabel(host))).slice(0, 32);
58848
59364
  const [found, peerIds] = await Promise.all([
@@ -58864,7 +59380,7 @@ function slugName(value2) {
58864
59380
  async function linkComputer(host, options = {}) {
58865
59381
  const remote = await probe2(host);
58866
59382
  if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
58867
- const own2 = (await readFile51(path111.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
59383
+ const own2 = (await readFile52(path113.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
58868
59384
  if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
58869
59385
  const name = computerName.parse(options.name ?? slugName(host));
58870
59386
  const as = computerName.parse(options.as ?? slugName(hostname13()));
@@ -58872,7 +59388,7 @@ async function linkComputer(host, options = {}) {
58872
59388
  if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
58873
59389
  const resolved = Object.fromEntries((await exec21("ssh", ["-G", "--", host], { timeout: 5e3 })).stdout.split("\n").map((line) => line.split(" ")).filter((parts) => parts.length >= 2).map(([key3, ...rest]) => [key3, rest.join(" ")]));
58874
59390
  const remoteHostKey = publicComputerKey((await ssh(host, "cat /etc/ssh/ssh_host_ed25519_key.pub")).trim().split(/\s+/).slice(0, 2).join(" "));
58875
- const localHostKey = publicComputerKey((await readFile51("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
59391
+ const localHostKey = publicComputerKey((await readFile52("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
58876
59392
  const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
58877
59393
  await ssh(host, `f=$(mktemp) && cat > "$f" && ${REMOTE_PATH} phren bridge enroll-computer ${as} --accept "$f"; s=$?; rm -f "$f"; exit $s`, await enrollComputer(as));
58878
59394
  await acceptComputer(name, remoteLine);
@@ -58908,7 +59424,7 @@ async function runBridge(args, version3) {
58908
59424
  case "enroll-computer": {
58909
59425
  if (args.length === 2) console.log(await enrollComputer(args[1]));
58910
59426
  else if (args.length === 4 && args[2] === "--accept") {
58911
- await acceptComputer(args[1], await readFile52(args[3], "utf8"));
59427
+ await acceptComputer(args[1], await readFile53(args[3], "utf8"));
58912
59428
  console.log(`Enrolled ${args[1]} for Phren Hook.`);
58913
59429
  } else throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
58914
59430
  break;
@@ -59036,7 +59552,7 @@ async function runBridge(args, version3) {
59036
59552
  break;
59037
59553
  }
59038
59554
  const readModels = async (source) => {
59039
- const rows = JSON.parse(await readFile52(fixture, "utf8"));
59555
+ const rows = JSON.parse(await readFile53(fixture, "utf8"));
59040
59556
  return Array.isArray(rows[source]) ? rows[source] : [];
59041
59557
  };
59042
59558
  const emptyUsage = (source) => ({ source, windows: [] });
@@ -59144,7 +59660,7 @@ async function readSecret(prompt) {
59144
59660
  // src/bridge/hook-main.ts
59145
59661
  init_utils_helpers();
59146
59662
  Object.assign(process.env, nonInteractiveGitEnv());
59147
- runBridge(process.argv.slice(2), "0.3.16").then((code) => {
59663
+ runBridge(process.argv.slice(2), "0.3.17").then((code) => {
59148
59664
  process.exitCode = code;
59149
59665
  }).catch((error62) => {
59150
59666
  console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");