@phren/cli 0.3.16 → 0.3.18

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 (46) 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/permission-mode.d.ts +48 -0
  12. package/dist/bridge/permission-mode.js +144 -0
  13. package/dist/bridge/protocol.d.ts +4 -0
  14. package/dist/bridge/protocol.js +3 -0
  15. package/dist/bridge/resources.d.ts +38 -5
  16. package/dist/bridge/resources.js +110 -19
  17. package/dist/bridge/server-launch.js +8 -0
  18. package/dist/bridge/server-pane-routes.d.ts +2 -0
  19. package/dist/bridge/server-pane-routes.js +12 -2
  20. package/dist/bridge/server-routes.d.ts +3 -1
  21. package/dist/bridge/server-routes.js +8 -6
  22. package/dist/bridge/server-stream.js +14 -2
  23. package/dist/bridge/server.js +4 -2
  24. package/dist/bridge/session-activity.d.ts +13 -0
  25. package/dist/bridge/session-activity.js +27 -2
  26. package/dist/bridge/settings-switch.d.ts +19 -7
  27. package/dist/bridge/settings-switch.js +21 -29
  28. package/dist/bridge/speech.d.ts +6 -4
  29. package/dist/bridge/speech.js +6 -4
  30. package/dist/bridge/terminal-tmux.d.ts +4 -2
  31. package/dist/bridge/terminal-tmux.js +13 -7
  32. package/dist/bridge/transcript-claude.d.ts +9 -1
  33. package/dist/bridge/transcript-claude.js +50 -1
  34. package/dist/bridge/transcript-codex.js +23 -3
  35. package/dist/bridge/transcripts.d.ts +5 -1
  36. package/dist/bridge/transcripts.js +13 -3
  37. package/dist/bridge-hook.mjs +1169 -546
  38. package/dist/computers/command.js +2 -1
  39. package/dist/fanout/opencode-serve.js +3 -2
  40. package/dist/hooks.d.ts +3 -0
  41. package/dist/hooks.js +41 -6
  42. package/dist/init/setup.js +6 -3
  43. package/dist/modules/registry.js +2 -2
  44. package/dist/tools/dispatch.js +3 -2
  45. package/package.json +1 -1
  46. 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.18" : "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,
@@ -37637,6 +37702,7 @@ var BUILTIN_MODULES = [
37637
37702
  "/v1/prompt/status",
37638
37703
  "/v1/model",
37639
37704
  "/v1/settings",
37705
+ "/v1/agents/permission-mode",
37640
37706
  "/v1/side-question/dismiss",
37641
37707
  "/v1/keys",
37642
37708
  "/v1/secret",
@@ -37647,7 +37713,8 @@ var BUILTIN_MODULES = [
37647
37713
  "/v1/subagents/archive-finished",
37648
37714
  "/v1/canary",
37649
37715
  "/v1/speech",
37650
- "/v1/sudo/answer"
37716
+ "/v1/sudo/answer",
37717
+ "/v1/jobs/cleanup"
37651
37718
  ]),
37652
37719
  ...routes("WS", ["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe"])
37653
37720
  ],
@@ -38792,7 +38859,7 @@ async function captureClaudeUsage(original) {
38792
38859
  // src/bridge/install.ts
38793
38860
  init_home_paths();
38794
38861
  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";
38862
+ 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
38863
  import { homedir as homedir12 } from "node:os";
38797
38864
 
38798
38865
  // src/bridge/claude-account-setup.ts
@@ -39400,7 +39467,7 @@ import { execFile as execFile8 } from "node:child_process";
39400
39467
  import { randomUUID as randomUUID8 } from "node:crypto";
39401
39468
  import { EventEmitter } from "node:events";
39402
39469
  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";
39470
+ import { open as open11, readdir as readdir11, readFile as readFile19, readlink as readlink2, unlink as unlink3 } from "node:fs/promises";
39404
39471
  import { request as request3 } from "node:http";
39405
39472
  import path45 from "node:path";
39406
39473
  import { promisify as promisify7 } from "node:util";
@@ -39556,7 +39623,7 @@ async function processStart(pid) {
39556
39623
  async function writeToAsker(pid, start, password) {
39557
39624
  if (await processStart(pid) !== start) return { status: 410, error: "askpass went away." };
39558
39625
  try {
39559
- const out = await open10(`/proc/${pid}/fd/1`, "w");
39626
+ const out = await open11(`/proc/${pid}/fd/1`, "w");
39560
39627
  try {
39561
39628
  await out.write(`${password}
39562
39629
  `);
@@ -39635,10 +39702,10 @@ var SudoBroker = class {
39635
39702
  this.watchers++;
39636
39703
  const handler = () => listener(this.list());
39637
39704
  this.events.on("change", handler);
39638
- let open24 = true;
39705
+ let open25 = true;
39639
39706
  return () => {
39640
- if (!open24) return;
39641
- open24 = false;
39707
+ if (!open25) return;
39708
+ open25 = false;
39642
39709
  this.watchers--;
39643
39710
  this.events.off("change", handler);
39644
39711
  };
@@ -40460,7 +40527,7 @@ async function install(version3, noService = false, force = false) {
40460
40527
  await mkdir13(versions, { recursive: true, mode: 448 });
40461
40528
  await chmod2(root, 448);
40462
40529
  const serviceLog = path50.join(root, "service.log");
40463
- const log2 = await open11(serviceLog, "a", 384);
40530
+ const log2 = await open12(serviceLog, "a", 384);
40464
40531
  try {
40465
40532
  await log2.chmod(384);
40466
40533
  } finally {
@@ -40668,7 +40735,7 @@ function opencodePluginNeedsWrite(existing, source) {
40668
40735
  return existing.startsWith(OPENCODE_PLUGIN_MARKER);
40669
40736
  }
40670
40737
  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';
40738
+ 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
40739
  const here = path50.dirname(fileURLToPath4(import.meta.url));
40673
40740
  for (const candidate of [
40674
40741
  path50.join(here, "..", "..", "plugins", "opencode", "phren-transcript.js"),
@@ -40910,10 +40977,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
40910
40977
  for (const value2 of values.slice(0, 128)) {
40911
40978
  if (state.count >= 128) break;
40912
40979
  const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
40913
- const path112 = publicLabel(raw.path);
40980
+ const path114 = publicLabel(raw.path);
40914
40981
  const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
40915
40982
  const routed = destination(raw, fallbackComputer, fallbackTarget);
40916
- if (!id2.success || !source.success || !path112 || !callId || !routed) continue;
40983
+ if (!id2.success || !source.success || !path114 || !callId || !routed) continue;
40917
40984
  const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
40918
40985
  const nestedSession = sessionId.safeParse(raw.session);
40919
40986
  const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
@@ -40926,7 +40993,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
40926
40993
  projected.push({
40927
40994
  id: publicID(parent, routed.computer.id, receipt.id, descendant),
40928
40995
  provider: source.data,
40929
- path: path112,
40996
+ path: path114,
40930
40997
  callId,
40931
40998
  state: raw.failed === true ? "failed" : childState,
40932
40999
  ...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
@@ -41970,7 +42037,7 @@ init_shared();
41970
42037
 
41971
42038
  // src/bridge/schedule-watch.ts
41972
42039
  init_herdr();
41973
- import { open as open12, stat as stat15 } from "node:fs/promises";
42040
+ import { open as open13, stat as stat15 } from "node:fs/promises";
41974
42041
 
41975
42042
  // src/bridge/pane-text.ts
41976
42043
  init_herdr();
@@ -42150,7 +42217,7 @@ async function readFinalTurn(source, sessionId2) {
42150
42217
  if (!sessionId2) return void 0;
42151
42218
  const file3 = await transcriptPath(source, sessionId2).catch(() => void 0);
42152
42219
  if (!file3) return void 0;
42153
- const handle = await open12(file3, "r").catch(() => void 0);
42220
+ const handle = await open13(file3, "r").catch(() => void 0);
42154
42221
  if (!handle) return void 0;
42155
42222
  try {
42156
42223
  const { size } = await handle.stat();
@@ -42637,8 +42704,8 @@ var Scheduler = class {
42637
42704
  const resume = this.launch.resume;
42638
42705
  if (this.recovered || !resume) return;
42639
42706
  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) {
42707
+ const open25 = (await readScheduleRuns(this.runsFile)).filter((run2) => runningStatuses.has(run2.status) && !this.own.has(run2.id));
42708
+ for (const run2 of open25) {
42642
42709
  this.own.add(run2.id);
42643
42710
  let schedule;
42644
42711
  try {
@@ -43927,13 +43994,13 @@ async function setIntegrator(input2) {
43927
43994
  init_transcripts();
43928
43995
  init_terminal();
43929
43996
  import { createHash as createHash16 } from "node:crypto";
43930
- import { open as open13 } from "node:fs/promises";
43997
+ import { open as open14 } from "node:fs/promises";
43931
43998
  function stallThreshold() {
43932
43999
  const value2 = Number(process.env.PHREN_STALL_MS ?? 3e5);
43933
44000
  return Number.isFinite(value2) && value2 >= 0 ? value2 : 3e5;
43934
44001
  }
43935
44002
  async function transcriptStamp(target) {
43936
- const file3 = await open13(await targetTranscriptPath(target), "r");
44003
+ const file3 = await open14(await targetTranscriptPath(target), "r");
43937
44004
  try {
43938
44005
  const info = await file3.stat(), start = Math.max(0, info.size - 8192), buffer = Buffer.alloc(info.size - start);
43939
44006
  await file3.read(buffer, 0, buffer.length, start);
@@ -44199,7 +44266,9 @@ async function listLiveSessions(options = {}) {
44199
44266
 
44200
44267
  // src/bridge/dispatch-returns.ts
44201
44268
  init_protocol();
44269
+ init_session_activity();
44202
44270
  init_terminal();
44271
+ init_transcripts();
44203
44272
  init_turn_records();
44204
44273
  init_turn_records();
44205
44274
  var REPLY_LIMIT = TURN_REPLY_LIMIT;
@@ -44222,6 +44291,7 @@ var defaultReaders = {
44222
44291
  identity: (server, pane) => paneIdentity(server, pane),
44223
44292
  finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(void 0),
44224
44293
  turn: paneTurn,
44294
+ children: (source, session) => childAgentTree(source, session).then(runningChildAgents).then((children) => children.length),
44225
44295
  stall: (target, pane) => sessionStalls.observe(target, pane),
44226
44296
  lost: (server, pane, session) => codexServers.lostTurn(server, pane, session)
44227
44297
  };
@@ -44244,22 +44314,26 @@ async function fromTurn(record2, session, status, source, readers) {
44244
44314
  if (phase.phase === "unprompted") return { state: "idle", ...base, completed: false };
44245
44315
  const idle = status === "idle" || status === "done";
44246
44316
  if (phase.phase === "working" && !idle) return { state: "working", ...base };
44247
- const final = await readers.finalTurn(source, session).catch(() => void 0);
44317
+ const now = (readers.now ?? Date.now)();
44318
+ const [final, children] = await Promise.all([
44319
+ readers.finalTurn(source, session).catch(() => void 0),
44320
+ readers.children ? readers.children(source, session).catch(() => 0) : Promise.resolve(0)
44321
+ ]);
44248
44322
  if (phase.phase === "working") {
44249
44323
  if (final?.interrupted) return { state: "done", ...base, completed: true, interrupted: true };
44250
- if (!final?.completed || final.background) return { state: "working", ...base };
44324
+ if (!final?.completed) return { state: "working", ...base };
44325
+ const live2 = liveWork(record2, final, children, now);
44326
+ if (live2) return { state: "working", ...base, background: live2 };
44251
44327
  return { state: "done", ...base, completed: true, ...final.error ? { error: final.error } : {}, ...replyFields(final.lastAssistant) };
44252
44328
  }
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 };
44329
+ const live = liveWork(record2, final, children, now);
44330
+ if (live) return { state: "working", ...base, background: live };
44256
44331
  return {
44257
44332
  state: "done",
44258
44333
  ...base,
44259
44334
  completed: true,
44260
44335
  endedAt: phase.at,
44261
44336
  stopSeq: record2.stop?.seq,
44262
- ...background ? { background } : {},
44263
44337
  ...final?.completed && final.error ? { error: final.error } : {},
44264
44338
  ...phase.reply ? replyFields(phase.reply, phase.truncated) : replyFields(final?.lastAssistant)
44265
44339
  };
@@ -44308,8 +44382,10 @@ async function workerStates2(input2, readers = defaultReaders) {
44308
44382
  return { state, ...session ? { session } : {}, ...full2.success && state === "working" ? await readers.stall?.(full2.data, pane) : {} };
44309
44383
  }
44310
44384
  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) };
44385
+ const children = readers.children ? await readers.children(target.source, session).catch(() => 0) : 0;
44386
+ const live = turn?.completed ? liveWork(void 0, turn, children, (readers.now ?? Date.now)()) : void 0;
44387
+ if (live) {
44388
+ return { state: "working", session, completed: true, background: live, ...turn?.error ? { error: turn.error } : {}, ...replyFields(turn?.lastAssistant) };
44313
44389
  }
44314
44390
  return {
44315
44391
  state,
@@ -44641,11 +44717,11 @@ var DispatchReturns = class {
44641
44717
  async poll() {
44642
44718
  await this.confirmArrivals(await this.peers().catch(() => []));
44643
44719
  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;
44720
+ 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);
44721
+ if (!open25.length) return;
44646
44722
  const peers = await this.peers().catch(() => []);
44647
44723
  const byComputer = /* @__PURE__ */ new Map();
44648
- for (const receipt of open24) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
44724
+ for (const receipt of open25) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
44649
44725
  await Promise.all([...byComputer].map(async ([computer, receipts]) => {
44650
44726
  const peer = peers.find((candidate) => candidate.name === computer);
44651
44727
  const local = !peer && this.isLocal(computer);
@@ -44885,7 +44961,7 @@ async function closeFinishedWorker(input2, queue3) {
44885
44961
  init_zod();
44886
44962
  init_protocol();
44887
44963
  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";
44964
+ import { lstat as lstat21, open as open15, readFile as readFile35, readdir as readdir13, unlink as unlink5 } from "node:fs/promises";
44889
44965
  import path67 from "node:path";
44890
44966
  init_terminal();
44891
44967
  var queuedHandOffSchema = external_exports.object({
@@ -44934,7 +45010,7 @@ var HandOffQueue = class {
44934
45010
  const file3 = this.file(row.deliveryId);
44935
45011
  await atomicInPrivateDir(file3, rowSchema.parse(row));
44936
45012
  if (process.platform !== "win32") for (const target of [file3, this.root]) {
44937
- const handle = await open14(target, "r");
45013
+ const handle = await open15(target, "r");
44938
45014
  try {
44939
45015
  await handle.sync();
44940
45016
  } finally {
@@ -45117,7 +45193,7 @@ var HandOffQueue = class {
45117
45193
 
45118
45194
  // src/bridge/server-pane-routes.ts
45119
45195
  init_zod();
45120
- import path78 from "node:path";
45196
+ import path79 from "node:path";
45121
45197
  import { setTimeout as sleep4 } from "node:timers/promises";
45122
45198
 
45123
45199
  // src/bridge/git.ts
@@ -45862,20 +45938,20 @@ init_protocol();
45862
45938
  init_herdr();
45863
45939
  init_codex_daemon();
45864
45940
  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";
45941
+ import { mkdir as mkdir20, readFile as readFile39, chmod as chmod4, unlink as unlink7, lstat as lstat24 } from "node:fs/promises";
45866
45942
  import { watch } from "node:fs";
45867
- import path75 from "node:path";
45868
- import { createHash as createHash23, randomUUID as randomUUID16 } from "node:crypto";
45943
+ import path76 from "node:path";
45944
+ import { createHash as createHash23, randomUUID as randomUUID17 } from "node:crypto";
45869
45945
  import { hostname as hostname10 } from "node:os";
45870
45946
 
45871
45947
  // src/bridge/codex-review-mode.ts
45872
- import { open as open15 } from "node:fs/promises";
45948
+ import { open as open16 } from "node:fs/promises";
45873
45949
  import path70 from "node:path";
45874
45950
  var SCAN_LIMIT = 64 * 1048576;
45875
45951
  var CHUNK = 1048576;
45876
45952
  async function codexAutoReview(transcriptPath2) {
45877
45953
  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);
45954
+ const file3 = await open16(transcriptPath2, "r").catch(() => void 0);
45879
45955
  if (!file3) return false;
45880
45956
  try {
45881
45957
  const size = (await file3.stat()).size;
@@ -46381,6 +46457,80 @@ init_limits();
46381
46457
  init_claude_question_dialog();
46382
46458
  init_terminal_choice();
46383
46459
  init_opencode_approvals();
46460
+
46461
+ // src/bridge/opencode-permissions.ts
46462
+ init_locks();
46463
+ init_home_paths();
46464
+ init_protocol();
46465
+ import { randomUUID as randomUUID16 } from "node:crypto";
46466
+ import { lstat as lstat23, mkdir as mkdir19, readFile as readFile38, rename as rename6, unlink as unlink6, writeFile as writeFile6 } from "node:fs/promises";
46467
+ import path73 from "node:path";
46468
+ function opencodeConfigPath(env = process.env, home = homeDir(env)) {
46469
+ return path73.join(env.XDG_CONFIG_HOME || path73.join(home, ".config"), "opencode", "opencode.json");
46470
+ }
46471
+ function opencodeToolName(value2) {
46472
+ if (typeof value2 !== "string") return void 0;
46473
+ const name = value2.trim().slice(0, 100);
46474
+ return /^[A-Za-z0-9_*-]+$/.test(name) ? name : void 0;
46475
+ }
46476
+ async function readConfig2(file3) {
46477
+ let text4;
46478
+ try {
46479
+ text4 = await readFile38(file3, "utf8");
46480
+ } catch (error62) {
46481
+ if (error62.code === "ENOENT") return {};
46482
+ throw new BridgeError(409, "Could not read ~/.config/opencode/opencode.json.");
46483
+ }
46484
+ let parsed;
46485
+ try {
46486
+ parsed = JSON.parse(text4);
46487
+ } catch {
46488
+ throw new BridgeError(409, "~/.config/opencode/opencode.json is not valid JSON.");
46489
+ }
46490
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new BridgeError(409, "~/.config/opencode/opencode.json is not a JSON object.");
46491
+ return parsed;
46492
+ }
46493
+ function withAllowedTool(config3, tool) {
46494
+ const permission = config3.permission;
46495
+ if (permission === void 0) return { ...config3, permission: { [tool]: "allow" } };
46496
+ if (typeof permission === "string") return { ...config3, permission: { "*": permission, [tool]: "allow" } };
46497
+ if (!permission || typeof permission !== "object" || Array.isArray(permission)) {
46498
+ throw new BridgeError(409, "The opencode permission block is not a JSON object.");
46499
+ }
46500
+ const block = { ...permission };
46501
+ const existing = block[tool];
46502
+ if (existing && typeof existing === "object" && !Array.isArray(existing)) {
46503
+ const merged = { "*": "allow", ...existing };
46504
+ merged["*"] = "allow";
46505
+ block[tool] = merged;
46506
+ } else block[tool] = "allow";
46507
+ return { ...config3, permission: block };
46508
+ }
46509
+ async function allowOpencodeToolEverywhere(tool, file3 = opencodeConfigPath()) {
46510
+ const name = opencodeToolName(tool);
46511
+ if (!name) throw new BridgeError(400, "OpenCode did not name a tool this can allow.");
46512
+ const release = tryFileLock(file3);
46513
+ if (!release) throw new BridgeError(409, "~/.config/opencode/opencode.json is being updated. Try again.");
46514
+ try {
46515
+ const config3 = withAllowedTool(await readConfig2(file3), name);
46516
+ const mode = (await lstat23(file3).catch(() => void 0))?.mode;
46517
+ await mkdir19(path73.dirname(file3), { recursive: true, mode: 448 });
46518
+ const temporary = `${file3}.${randomUUID16()}.tmp`;
46519
+ await writeFile6(temporary, `${JSON.stringify(config3, null, 2)}
46520
+ `, { mode: mode === void 0 ? 384 : mode & 511, flag: "wx" });
46521
+ try {
46522
+ await rename6(temporary, file3);
46523
+ } finally {
46524
+ await unlink6(temporary).catch(() => {
46525
+ });
46526
+ }
46527
+ return name;
46528
+ } finally {
46529
+ release();
46530
+ }
46531
+ }
46532
+
46533
+ // src/bridge/agent-hooks.ts
46384
46534
  init_agent_hook_stores();
46385
46535
  init_pane_accounts();
46386
46536
  init_pane_status();
@@ -46392,7 +46542,7 @@ init_codex_servers();
46392
46542
  // src/bridge/opencode-panes.ts
46393
46543
  init_limits();
46394
46544
  import { execFile as execFile14 } from "node:child_process";
46395
- import path74 from "node:path";
46545
+ import path75 from "node:path";
46396
46546
  import { promisify as promisify13 } from "node:util";
46397
46547
 
46398
46548
  // src/bridge/opencode-pane-server.ts
@@ -46400,7 +46550,7 @@ init_phren_paths();
46400
46550
  import * as crypto6 from "node:crypto";
46401
46551
  import * as fs23 from "node:fs";
46402
46552
  import * as net from "node:net";
46403
- import * as path73 from "node:path";
46553
+ import * as path74 from "node:path";
46404
46554
  var MAX_PASSWORD = 200;
46405
46555
  var REQUEST_TIMEOUT_MS = 1e4;
46406
46556
  var PROMPT_POLL_MS = 200;
@@ -46425,7 +46575,7 @@ function alive(pid) {
46425
46575
  }
46426
46576
  }
46427
46577
  function paneServerFile(dir, server, pane) {
46428
- return path73.join(dir, `${encodeURIComponent(`${server}/${pane}`)}.json`);
46578
+ return path74.join(dir, `${encodeURIComponent(`${server}/${pane}`)}.json`);
46429
46579
  }
46430
46580
  function registerPaneServer(dir, entry2) {
46431
46581
  if (!validEntry(entry2)) throw new Error("Invalid OpenCode pane server entry.");
@@ -46463,7 +46613,7 @@ function listPaneServers(dir) {
46463
46613
  const entries2 = [];
46464
46614
  for (const name of names.slice(0, 1024)) {
46465
46615
  if (!name.endsWith(".json")) continue;
46466
- const file3 = path73.join(dir, name);
46616
+ const file3 = path74.join(dir, name);
46467
46617
  let parsed;
46468
46618
  try {
46469
46619
  const info = fs23.lstatSync(file3);
@@ -46669,7 +46819,7 @@ var READY_MS = 2e4;
46669
46819
  var PID_MS = intervalFromEnv("PHREN_OPENCODE_PID_MS", 2e3);
46670
46820
  var BRIEF_CONFIRM_MS = 1e4;
46671
46821
  function paneServersDir() {
46672
- return path74.join(bridgeRoot(), "opencode-panes");
46822
+ return path75.join(bridgeRoot(), "opencode-panes");
46673
46823
  }
46674
46824
  function servedPane(server, pane) {
46675
46825
  return readPaneServer(paneServersDir(), server, pane);
@@ -46938,6 +47088,18 @@ function conductorCall(tool, input2) {
46938
47088
  const computer = typeof fields2.computer === "string" ? fields2.computer : void 0;
46939
47089
  return { action, ...project ? { project } : {}, ...computer ? { computer } : {} };
46940
47090
  }
47091
+ var OPENCODE_APPROVAL_OPTIONS = [
47092
+ { label: "Allow once", decision: "approve" },
47093
+ { label: "Allow for this project", decision: "allow-project" },
47094
+ { label: "Allow everywhere", decision: "allow-everywhere" },
47095
+ { label: "Deny", decision: "deny" }
47096
+ ];
47097
+ function opencodePermissionReply(decision) {
47098
+ if (decision === "approve") return "once";
47099
+ if (decision === "deny") return "reject";
47100
+ if (decision === "allow-project" || decision === "allow-everywhere") return "always";
47101
+ return void 0;
47102
+ }
46941
47103
  var TRACK_MS = 6e5;
46942
47104
  function promptKey(text4) {
46943
47105
  return unwrapPastedContent(text4).split("\n").filter((line) => !PICTURE_PATH_LINE.test(line)).join("\n").replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
@@ -47042,7 +47204,7 @@ var AgentHooks = class {
47042
47204
  /** sudo -A requests from askpass, answered from the phone (sudo.ts). */
47043
47205
  sudo;
47044
47206
  approvalsDirectory() {
47045
- return path75.join(phrenStoreRoot(), ".runtime", "approvals");
47207
+ return path76.join(phrenStoreRoot(), ".runtime", "approvals");
47046
47208
  }
47047
47209
  scheduleOpencodeSweep() {
47048
47210
  if (this.closed || this.opencodeDebounce) return;
@@ -47095,17 +47257,17 @@ var AgentHooks = class {
47095
47257
  ) : void 0;
47096
47258
  const cwd = asking?.worktree ?? (pane ? await trustedDirectory(pane).catch(() => void 0) : void 0);
47097
47259
  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;
47260
+ const fanout = asking ? { session: match[1], actionId: asking.parent.provider === "opencode" ? randomUUID17().replaceAll("-", "") : randomUUID17() } : void 0;
47099
47261
  this.opencode.set(id2, { ...target ? { target } : {}, request: request9, requestLine: summary.request, expiresAt, ...fanout ? { fanout } : {} });
47100
47262
  if (!this.push.available) continue;
47101
- const binding = randomUUID16();
47263
+ const binding = randomUUID17();
47102
47264
  this.pushBindings.add(binding, { action: id2, expiresAt });
47103
47265
  void this.push.notify({
47104
47266
  binding,
47105
47267
  provider: "opencode",
47106
47268
  question: false,
47107
47269
  expiresAt: String(request9.expiresAt),
47108
- ...cwd ? { project: path75.basename(cwd) } : {},
47270
+ ...cwd ? { project: path76.basename(cwd) } : {},
47109
47271
  computer: this.computerName,
47110
47272
  ...summary
47111
47273
  }).then((delivered) => {
@@ -47173,14 +47335,14 @@ var AgentHooks = class {
47173
47335
  const summary = approvalSummary({ tool: type, input: request9, message, cwd: entry2.directory });
47174
47336
  this.opencode.set(ask.id, { ...target ? { target } : {}, request: request9, requestLine: summary.request, expiresAt, served: where });
47175
47337
  if (!this.push.available) continue;
47176
- const binding = randomUUID16();
47338
+ const binding = randomUUID17();
47177
47339
  this.pushBindings.add(binding, { action: ask.id, expiresAt });
47178
47340
  void this.push.notify({
47179
47341
  binding,
47180
47342
  provider: "opencode",
47181
47343
  question: false,
47182
47344
  expiresAt: String(request9.expiresAt),
47183
- project: path75.basename(entry2.directory),
47345
+ project: path76.basename(entry2.directory),
47184
47346
  computer: this.computerName,
47185
47347
  ...summary
47186
47348
  }).then((delivered) => {
@@ -47243,11 +47405,13 @@ var AgentHooks = class {
47243
47405
  }
47244
47406
  /** Answers a served pane's permission ask over its own API. */
47245
47407
  async answerServed(id2, held, decision) {
47246
- if (!["approve", "deny"].includes(String(decision))) throw new BridgeError(400, "The approval answer is not valid.");
47408
+ const reply = opencodePermissionReply(decision);
47409
+ if (!reply) throw new BridgeError(400, "The approval answer is not valid.");
47247
47410
  const served = held.served;
47248
47411
  const client = this.servedClient(served.server, served.pane);
47412
+ if (decision === "allow-everywhere") await allowOpencodeToolEverywhere(held.request.type);
47249
47413
  try {
47250
- await client.replyPermission(id2, decision === "approve" ? "once" : "reject");
47414
+ await client.replyPermission(id2, reply);
47251
47415
  } catch {
47252
47416
  throw new BridgeError(409, "This approval is no longer pending.");
47253
47417
  }
@@ -47307,15 +47471,15 @@ var AgentHooks = class {
47307
47471
  /** A session's exact pane. A recorded binding carries the full target; when
47308
47472
  * there is none, Herdr's explicit session identity names the pane. */
47309
47473
  async resolveTarget(source, session) {
47310
- const root = path75.join(bridgeRoot(), "bindings");
47474
+ const root = path76.join(bridgeRoot(), "bindings");
47311
47475
  for await (const folder of directoryNames(root, 64)) {
47312
- for await (const name of directoryNames(path75.join(root, folder), 1024)) {
47476
+ for await (const name of directoryNames(path76.join(root, folder), 1024)) {
47313
47477
  if (!name.endsWith(".json")) continue;
47314
47478
  let value2;
47315
47479
  try {
47316
- const file3 = path75.join(root, folder, name), info = await lstat23(file3);
47480
+ const file3 = path76.join(root, folder, name), info = await lstat24(file3);
47317
47481
  if (!info.isFile() || info.size > 65536) continue;
47318
- value2 = object2(JSON.parse(await readFile38(file3, "utf8")));
47482
+ value2 = object2(JSON.parse(await readFile39(file3, "utf8")));
47319
47483
  } catch {
47320
47484
  continue;
47321
47485
  }
@@ -47847,12 +48011,13 @@ var AgentHooks = class {
47847
48011
  title: worker.request.title,
47848
48012
  message: worker.request.message,
47849
48013
  request: worker.requestLine,
47850
- expiresAt: worker.request.expiresAt
48014
+ expiresAt: worker.request.expiresAt,
48015
+ options: OPENCODE_APPROVAL_OPTIONS
47851
48016
  } : void 0;
47852
48017
  }
47853
48018
  opencodeApproval(target) {
47854
48019
  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 };
48020
+ 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
48021
  const request9 = opencodeRequest(target.session);
47857
48022
  return request9 ? {
47858
48023
  actionId: request9.id,
@@ -47860,7 +48025,8 @@ var AgentHooks = class {
47860
48025
  title: request9.title,
47861
48026
  message: request9.message,
47862
48027
  request: approvalSummary({ tool: String(request9.type ?? ""), input: request9, message: typeof request9.message === "string" ? request9.message : void 0 }).request,
47863
- expiresAt: request9.expiresAt
48028
+ expiresAt: request9.expiresAt,
48029
+ options: OPENCODE_APPROVAL_OPTIONS
47864
48030
  } : void 0;
47865
48031
  }
47866
48032
  /** Live fan-out worker asks shown on this parent conversation, oldest first. */
@@ -47902,10 +48068,12 @@ var AgentHooks = class {
47902
48068
  }
47903
48069
  /** Hands the owner's answer to the fan-out launcher waiting on the worker's session. */
47904
48070
  async answerFanout(id2, held, decision) {
47905
- if (!["approve", "deny"].includes(String(decision))) throw new BridgeError(400, "The approval answer is not valid.");
48071
+ const reply = opencodePermissionReply(decision);
48072
+ if (!reply) throw new BridgeError(400, "The approval answer is not valid.");
47906
48073
  const file3 = held.fanout && opencodeApprovalFile(held.fanout.session, "answer");
47907
48074
  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 }));
48075
+ if (decision === "allow-everywhere") await allowOpencodeToolEverywhere(held.request.type);
48076
+ await atomicInPrivateDir(file3, JSON.stringify({ id: id2, decision: decision === "approve" || decision === "deny" ? decision : "always" }));
47909
48077
  this.opencode.delete(id2);
47910
48078
  this.pushBindings.dropAction(id2);
47911
48079
  }
@@ -47934,12 +48102,15 @@ var AgentHooks = class {
47934
48102
  return;
47935
48103
  }
47936
48104
  if (target.source === "opencode") {
47937
- if (!["approve", "deny"].includes(String(decision))) throw new BridgeError(400, "The approval answer is not valid.");
48105
+ const reply = opencodePermissionReply(decision);
48106
+ if (!reply) throw new BridgeError(400, "The approval answer is not valid.");
47938
48107
  const file3 = opencodeApprovalFile(target.session, "answer");
47939
48108
  if (!file3) throw new BridgeError(400, "Invalid conversation identity.");
47940
48109
  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 }));
48110
+ const request9 = opencodeRequest(target.session);
48111
+ if (request9?.id !== id2) throw new BridgeError(409, "This approval is no longer pending.");
48112
+ if (decision === "allow-everywhere") await allowOpencodeToolEverywhere(request9.type);
48113
+ await atomicInPrivateDir(file3, JSON.stringify({ id: id2, decision: decision === "approve" || decision === "deny" ? decision : "always" }));
47943
48114
  this.opencode.delete(id2);
47944
48115
  this.pushBindings.dropAction(id2);
47945
48116
  return;
@@ -48084,7 +48255,7 @@ var AgentHooks = class {
48084
48255
  if (this.dialogPushes.get(key3)?.title === title2) continue;
48085
48256
  this.dropDialogPush(key3);
48086
48257
  if (this.adoptReleasedHold(key3, target, entry2.choice, title2)) continue;
48087
- const action = `dialog-${randomUUID16()}`, binding = randomUUID16(), expiresAt = Date.now() + DIALOG_PUSH_MS;
48258
+ const action = `dialog-${randomUUID17()}`, binding = randomUUID17(), expiresAt = Date.now() + DIALOG_PUSH_MS;
48088
48259
  this.dialogPushes.set(key3, { action, title: title2 });
48089
48260
  this.dialogActions.set(action, { target, choice: entry2.choice, expiresAt });
48090
48261
  this.pushBindings.add(binding, { action, expiresAt });
@@ -48095,7 +48266,7 @@ var AgentHooks = class {
48095
48266
  provider: target.source,
48096
48267
  question: entry2.tool === "AskUserQuestion",
48097
48268
  expiresAt: new Date(expiresAt).toISOString(),
48098
- ...cwd ? { project: path75.basename(cwd) } : {},
48269
+ ...cwd ? { project: path76.basename(cwd) } : {},
48099
48270
  computer: this.computerName,
48100
48271
  ...summary
48101
48272
  }).then((delivered) => {
@@ -48179,7 +48350,7 @@ ${target.source}`) ?? 0) > Date.now();
48179
48350
  else {
48180
48351
  this.dropForwardedDialog(key3);
48181
48352
  while (this.forwardedDialogs.size >= 64) this.dropForwardedDialog(this.forwardedDialogs.keys().next().value);
48182
- action = `dialog-${randomUUID16()}`;
48353
+ action = `dialog-${randomUUID17()}`;
48183
48354
  this.forwardedDialogs.set(key3, { action, title: title2, body: entry2.choice.body });
48184
48355
  this.dialogActions.set(action, { target, choice: entry2.choice, expiresAt: Date.now() + DIALOG_PUSH_MS });
48185
48356
  }
@@ -48201,7 +48372,7 @@ ${target.source}`) ?? 0) > Date.now();
48201
48372
  * dispatch path. */
48202
48373
  pushForwarded(summary, answer) {
48203
48374
  if (!this.push.available || this.closed) return;
48204
- const action = `forward-${randomUUID16()}`, binding = randomUUID16(), expiresAt = Date.now() + DIALOG_PUSH_MS;
48375
+ const action = `forward-${randomUUID17()}`, binding = randomUUID17(), expiresAt = Date.now() + DIALOG_PUSH_MS;
48205
48376
  while (this.forwardedPushes.size >= 64) {
48206
48377
  const oldest = this.forwardedPushes.keys().next().value;
48207
48378
  this.forwardedPushes.delete(oldest);
@@ -48287,7 +48458,7 @@ ${target.source}`) ?? 0) > Date.now();
48287
48458
  known2.appServer.answer = answer;
48288
48459
  return;
48289
48460
  }
48290
- const action = randomUUID16();
48461
+ const action = randomUUID17();
48291
48462
  const held = { requestId: request9.requestId, answer };
48292
48463
  const reply = { destroyed: false, end(body2) {
48293
48464
  if (reply.destroyed) return;
@@ -48301,7 +48472,7 @@ ${target.source}`) ?? 0) > Date.now();
48301
48472
  })()).hookSpecificOutput).decision).behavior;
48302
48473
  if (behavior === "allow" || behavior === "deny") held.answer(appServerDecision(request9, behavior === "allow"));
48303
48474
  } };
48304
- const cwd = typeof request9.params.cwd === "string" && path75.isAbsolute(request9.params.cwd) ? request9.params.cwd : void 0;
48475
+ const cwd = typeof request9.params.cwd === "string" && path76.isAbsolute(request9.params.cwd) ? request9.params.cwd : void 0;
48305
48476
  const summary = approvalSummary({ tool: shown.tool, input: shown.input, cwd });
48306
48477
  const expiresAt = Date.now() + DIALOG_PUSH_MS;
48307
48478
  this.pending.set(action, {
@@ -48316,14 +48487,14 @@ ${target.source}`) ?? 0) > Date.now();
48316
48487
  });
48317
48488
  while (this.pending.size > 64) this.pending.delete(this.pending.keys().next().value);
48318
48489
  if (!this.push.available) return;
48319
- const binding = randomUUID16();
48490
+ const binding = randomUUID17();
48320
48491
  this.pushBindings.add(binding, { action, expiresAt });
48321
48492
  void this.push.notify({
48322
48493
  binding,
48323
48494
  provider: "codex",
48324
48495
  question: false,
48325
48496
  expiresAt: new Date(expiresAt).toISOString(),
48326
- ...cwd ? { project: path75.basename(cwd) } : {},
48497
+ ...cwd ? { project: path76.basename(cwd) } : {},
48327
48498
  computer: this.computerName,
48328
48499
  ...summary
48329
48500
  }).then((delivered) => {
@@ -48343,10 +48514,10 @@ ${target.source}`) ?? 0) > Date.now();
48343
48514
  }
48344
48515
  async start() {
48345
48516
  await this.push.start();
48346
- const previous = await lstat23(localSocket()).catch(() => void 0);
48517
+ const previous = await lstat24(localSocket()).catch(() => void 0);
48347
48518
  if (previous) {
48348
48519
  if (!previous.isSocket() || previous.uid !== process.getuid?.()) throw new Error("Unexpected agent callback socket.");
48349
- await unlink6(localSocket());
48520
+ await unlink7(localSocket());
48350
48521
  }
48351
48522
  this.server = createServer2(async (req, res) => {
48352
48523
  res.setHeader("Content-Type", "application/json");
@@ -48373,7 +48544,7 @@ ${target.source}`) ?? 0) > Date.now();
48373
48544
  const daemon = body2.daemon === true;
48374
48545
  if (daemon) {
48375
48546
  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);
48547
+ const placed = await paneForCodexSession(target.server, target.session, typeof body2.cwd === "string" && path76.isAbsolute(body2.cwd) ? body2.cwd : void 0);
48377
48548
  if (!placed) {
48378
48549
  res.end("{}");
48379
48550
  return;
@@ -48422,7 +48593,7 @@ ${target.source}`) ?? 0) > Date.now();
48422
48593
  if (body2.event === "SessionStart" || body2.event === "Stop") await this.recordTurn(target, pane, body2, dispatch2);
48423
48594
  if ((this.modules?.has("git") ?? true) && ["PreToolUse", "PostToolUse"].includes(String(body2.event)) && capturesChanges(String(body2.tool), input2)) {
48424
48595
  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);
48596
+ 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
48597
  else await this.changes.after(conversation, id2);
48427
48598
  res.end("{}");
48428
48599
  return;
@@ -48459,11 +48630,11 @@ ${target.source}`) ?? 0) > Date.now();
48459
48630
  res.end("{}");
48460
48631
  return;
48461
48632
  }
48462
- const action = randomUUID16();
48633
+ const action = randomUUID17();
48463
48634
  this.dialogReads.delete(JSON.stringify(target));
48464
48635
  const conductor = body2.event === "PermissionRequest" ? conductorCall(String(body2.tool || "action"), body2.input) : void 0;
48465
48636
  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);
48637
+ const cwd = typeof body2.cwd === "string" && path76.isAbsolute(body2.cwd) ? body2.cwd : await trustedDirectory(pane).catch(() => void 0);
48467
48638
  let released = false;
48468
48639
  const timer = setTimeout(() => {
48469
48640
  released = true;
@@ -48496,7 +48667,7 @@ ${target.source}`) ?? 0) > Date.now();
48496
48667
  if (!released) this.dropPushBindings(action);
48497
48668
  });
48498
48669
  if (this.push.available) {
48499
- const binding = randomUUID16(), pushExpiresAt = Date.now() + DIALOG_PUSH_MS;
48670
+ const binding = randomUUID17(), pushExpiresAt = Date.now() + DIALOG_PUSH_MS;
48500
48671
  this.pushBindings.add(binding, { action, expiresAt: pushExpiresAt });
48501
48672
  this.pushedHolds.set(action, pushExpiresAt);
48502
48673
  void this.push.notify({
@@ -48504,7 +48675,7 @@ ${target.source}`) ?? 0) > Date.now();
48504
48675
  provider: target.source,
48505
48676
  question: body2.tool === "AskUserQuestion",
48506
48677
  expiresAt: new Date(pushExpiresAt).toISOString(),
48507
- ...cwd ? { project: path75.basename(cwd) } : {},
48678
+ ...cwd ? { project: path76.basename(cwd) } : {},
48508
48679
  computer: this.computerName,
48509
48680
  ...summary
48510
48681
  }).catch(() => false).then((delivered) => {
@@ -48531,7 +48702,7 @@ ${target.source}`) ?? 0) > Date.now();
48531
48702
  this.server.listen(localSocket(), () => resolve11());
48532
48703
  });
48533
48704
  await chmod4(localSocket(), 384);
48534
- await mkdir19(this.approvalsDirectory(), { recursive: true, mode: 448 }).catch(() => {
48705
+ await mkdir20(this.approvalsDirectory(), { recursive: true, mode: 448 }).catch(() => {
48535
48706
  });
48536
48707
  try {
48537
48708
  this.opencodeWatcher = watch(this.approvalsDirectory(), { persistent: false }, () => this.scheduleOpencodeSweep());
@@ -48675,9 +48846,9 @@ init_protocol();
48675
48846
  init_claude_accounts();
48676
48847
  init_codex_binary();
48677
48848
  import { spawn as spawn10 } from "node:child_process";
48678
- import { readdir as readdir15, readFile as readFile39, stat as stat20 } from "node:fs/promises";
48849
+ import { readdir as readdir15, readFile as readFile40, stat as stat20 } from "node:fs/promises";
48679
48850
  import { homedir as homedir17 } from "node:os";
48680
- import path76 from "node:path";
48851
+ import path77 from "node:path";
48681
48852
  function readCodexModels(executable2 = codexExecutable()) {
48682
48853
  return new Promise((resolve11) => {
48683
48854
  const child = spawn10(executable2, ["app-server"], { cwd: homedir17(), stdio: ["pipe", "pipe", "ignore"] });
@@ -48756,12 +48927,12 @@ var CLAUDE_MENU = [
48756
48927
  { id: "claude-fable-5-1[1m]", name: "Fable 5.1 (1M context)", description: "Fable 5.1 with a 1M context window." }
48757
48928
  ];
48758
48929
  async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
48759
- const directory = path76.join(configDir, "cache", "model-catalog");
48930
+ const directory = path77.join(configDir, "cache", "model-catalog");
48760
48931
  let newest2;
48761
48932
  try {
48762
48933
  for (const name of await readdir15(directory)) {
48763
48934
  if (!name.endsWith("-cc.json")) continue;
48764
- const file3 = path76.join(directory, name), at = (await stat20(file3)).mtimeMs;
48935
+ const file3 = path77.join(directory, name), at = (await stat20(file3)).mtimeMs;
48765
48936
  if (!newest2 || at > newest2.at) newest2 = { file: file3, at };
48766
48937
  }
48767
48938
  } catch {
@@ -48770,7 +48941,7 @@ async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
48770
48941
  if (!newest2) return [];
48771
48942
  let parsed;
48772
48943
  try {
48773
- parsed = JSON.parse(await readFile39(newest2.file, "utf8"));
48944
+ parsed = JSON.parse(await readFile40(newest2.file, "utf8"));
48774
48945
  } catch {
48775
48946
  return [];
48776
48947
  }
@@ -48842,7 +49013,7 @@ async function readClaudeModels(configDir, installed) {
48842
49013
  const live = await readClaudeCatalog(configDir, version3).catch(() => []);
48843
49014
  return live.length ? live : CLAUDE_MENU.map((model) => ({ ...model }));
48844
49015
  }
48845
- async function readOpenCodeModels(executable2 = "opencode", configDir = path76.join(homedir17(), ".config/opencode")) {
49016
+ async function readOpenCodeModels(executable2 = "opencode", configDir = path77.join(homedir17(), ".config/opencode")) {
48846
49017
  const listed2 = await new Promise((resolve11) => {
48847
49018
  const child = spawn10(executable2, ["models"], { cwd: homedir17(), stdio: ["ignore", "pipe", "ignore"] });
48848
49019
  let out = "", done = false;
@@ -48869,7 +49040,7 @@ async function readOpenCodeModels(executable2 = "opencode", configDir = path76.j
48869
49040
  let configured;
48870
49041
  for (const file3 of ["opencode.json", "opencode.jsonc"]) {
48871
49042
  try {
48872
- const text4 = await readFile39(path76.join(configDir, file3), "utf8");
49043
+ const text4 = await readFile40(path77.join(configDir, file3), "utf8");
48873
49044
  const model = /"model"\s*:\s*"([^"]+)"/.exec(text4)?.[1];
48874
49045
  if (model) {
48875
49046
  configured = model.slice(0, 200);
@@ -48927,7 +49098,7 @@ init_protocol();
48927
49098
  // src/bridge/side-questions.ts
48928
49099
  init_herdr();
48929
49100
  init_terminal();
48930
- import { randomUUID as randomUUID17 } from "node:crypto";
49101
+ import { randomUUID as randomUUID18 } from "node:crypto";
48931
49102
  init_protocol();
48932
49103
  var MAX_QUESTION = 4e3;
48933
49104
  var MAX_ANSWER = 65536;
@@ -49024,7 +49195,7 @@ var SideQuestions = class {
49024
49195
  if (!question2) throw new BridgeError(422, "Side questions are for Claude Code: /btw followed by the question.");
49025
49196
  if (question2.length > MAX_QUESTION) throw new BridgeError(413, "The side question is too long.");
49026
49197
  this.assertAvailable(target);
49027
- const key3 = this.paneKey(target), id2 = randomUUID17();
49198
+ const key3 = this.paneKey(target), id2 = randomUUID18();
49028
49199
  this.open.set(key3, id2);
49029
49200
  try {
49030
49201
  if (sidePanel(await this.read(target))) throw new BridgeError(409, "The terminal already shows a side question. Close it there first.");
@@ -49352,12 +49523,111 @@ var ModelSwitcher = class {
49352
49523
  }
49353
49524
  };
49354
49525
 
49526
+ // src/bridge/permission-mode.ts
49527
+ init_terminal_text();
49528
+ init_herdr();
49529
+ init_protocol();
49530
+ init_terminal();
49531
+ init_terminal_choice();
49532
+ var PERMISSION_CYCLE = ["default", "acceptEdits", "plan", "auto"];
49533
+ var PERMISSION_MODE_VALUES = [...PERMISSION_CYCLE, "bypassPermissions"];
49534
+ function permissionModes(bypass) {
49535
+ return [...PERMISSION_CYCLE, ...bypass ? ["bypassPermissions"] : []];
49536
+ }
49537
+ function claudeFooterMode(screen) {
49538
+ for (const line of stripTerminal(screen).split(/\r?\n/).map((line2) => line2.trim()).filter(Boolean).slice(-8).reverse()) {
49539
+ const text4 = line.replace(/^[⏵⏸]+\s*/, "");
49540
+ if (text4 === line) continue;
49541
+ if (/bypass permissions on/i.test(text4)) return "bypassPermissions";
49542
+ if (/^manual mode on\b/i.test(text4)) return "default";
49543
+ if (/^accept edits on\b/i.test(text4)) return "acceptEdits";
49544
+ if (/^plan mode on\b/i.test(text4)) return "plan";
49545
+ if (/^auto mode on\b/i.test(text4)) return "auto";
49546
+ }
49547
+ return void 0;
49548
+ }
49549
+ function refuseAgentOrigin(actor) {
49550
+ if (actor !== void 0) throw new BridgeError(403, "Only the owner changes a session's permission mode, from the phone.");
49551
+ }
49552
+ function attribution() {
49553
+ return { setBy: "owner" };
49554
+ }
49555
+ var STEP_WAIT_MS = 2e3;
49556
+ var POLL_MS2 = 100;
49557
+ var PermissionModeSwitcher = class {
49558
+ constructor(hooks, wait = STEP_WAIT_MS) {
49559
+ this.hooks = hooks;
49560
+ this.wait = wait;
49561
+ }
49562
+ hooks;
49563
+ wait;
49564
+ active = /* @__PURE__ */ new Set();
49565
+ key(target) {
49566
+ return `${target.server}:${target.pane}`;
49567
+ }
49568
+ assertAvailable(target) {
49569
+ if (this.active.has(this.key(target))) throw new BridgeError(409, "A permission-mode change is already in progress. Wait for it to finish.");
49570
+ }
49571
+ /** Steps the pane to `mode`, or refuses. Only Claude offers the cycle; the
49572
+ * machine's authority policy never caps an owner's own choice. */
49573
+ async set(target, mode, actor) {
49574
+ refuseAgentOrigin(actor);
49575
+ this.assertAvailable(target);
49576
+ if (target.source !== "claude") throw new BridgeError(422, "Changing the permission mode is not supported for this harness. Open terminal to change it.");
49577
+ this.active.add(this.key(target));
49578
+ try {
49579
+ return await this.cycle(target, mode, actor);
49580
+ } finally {
49581
+ this.active.delete(this.key(target));
49582
+ }
49583
+ }
49584
+ async cycle(target, mode, actor) {
49585
+ const first = await validateTarget(target, false, true);
49586
+ const terminal2 = first.terminal_id, status = String(first.agent_status);
49587
+ if (status === "working") throw new BridgeError(409, "This agent is mid-turn. Permission changes happen between turns; choose the mode again when the turn ends.");
49588
+ const screen = await this.hooks.paneAnsi(target).catch(() => void 0);
49589
+ if (screen === void 0) throw new BridgeError(409, "Could not read Claude's permission mode from its screen. Open terminal to check.");
49590
+ if (status === "blocked" || status === "waiting" || this.hooks.approval(target) || this.hooks.terminalPrompt(target) || visibleTerminalChoice(stripTerminal(screen))) {
49591
+ throw new BridgeError(409, "A permission prompt or dialog is open. Answer it before changing the permission mode.");
49592
+ }
49593
+ let current2 = claudeFooterMode(screen);
49594
+ if (!current2) throw new BridgeError(409, "Could not read Claude's permission mode from its screen. Open terminal to check.");
49595
+ if (current2 === mode) return { ok: true, permissionMode: current2, ...attribution() };
49596
+ const modes = new Set(PERMISSION_CYCLE);
49597
+ for (let presses = 0; ; presses++) {
49598
+ if (presses >= modes.size + 1) throw new BridgeError(422, `Claude doesn't offer ${mode} in this session.`, { permissionMode: current2 });
49599
+ await this.assertLive(target, terminal2);
49600
+ await terminalProvider().sendKeys(target.server, target.pane, ["shift+tab"]);
49601
+ current2 = await this.changed(target, terminal2, current2);
49602
+ modes.add(current2);
49603
+ if (current2 === mode) return { ok: true, permissionMode: current2, ...attribution() };
49604
+ }
49605
+ }
49606
+ /** The mode after a press: polled from the screen until it differs from
49607
+ * `from`, because the TUI redraws the footer asynchronously. */
49608
+ async changed(target, terminal2, from) {
49609
+ const deadline = Date.now() + this.wait;
49610
+ do {
49611
+ await new Promise((resolve11) => setTimeout(resolve11, POLL_MS2));
49612
+ await this.assertLive(target, terminal2);
49613
+ const mode = claudeFooterMode(await this.hooks.paneAnsi(target).catch(() => ""));
49614
+ if (mode && mode !== from) return mode;
49615
+ } while (Date.now() < deadline);
49616
+ throw new BridgeError(409, "Could not verify Claude's permission mode. Open terminal to check it.");
49617
+ }
49618
+ async assertLive(target, terminal2) {
49619
+ const pane = await validateTarget(target, false, true);
49620
+ if (pane.terminal_id !== terminal2) throw new BridgeError(409, "The terminal changed during the permission-mode change.");
49621
+ if (pane.agent_status === "working") throw new BridgeError(409, "The agent started working during the permission-mode change. The result is unconfirmed; check the terminal.");
49622
+ }
49623
+ };
49624
+
49355
49625
  // src/bridge/session-servers.ts
49356
49626
  init_protocol();
49357
49627
  init_herdr();
49358
49628
  init_terminal();
49359
49629
  import { execFile as execFile15 } from "node:child_process";
49360
- import { open as open16, stat as stat21 } from "node:fs/promises";
49630
+ import { open as open17, stat as stat21 } from "node:fs/promises";
49361
49631
  import { promisify as promisify14 } from "node:util";
49362
49632
  init_transcripts();
49363
49633
  var exec14 = promisify14(execFile15);
@@ -49418,7 +49688,7 @@ async function transcriptHolders(file3) {
49418
49688
  }
49419
49689
  async function transcriptTail(file3) {
49420
49690
  const size = (await stat21(file3)).size;
49421
- const handle = await open16(file3, "r");
49691
+ const handle = await open17(file3, "r");
49422
49692
  try {
49423
49693
  const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
49424
49694
  const buffer = Buffer.alloc(length);
@@ -49459,9 +49729,9 @@ init_transcripts();
49459
49729
 
49460
49730
  // src/bridge/uploads.ts
49461
49731
  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";
49732
+ 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";
49733
+ import path78 from "node:path";
49734
+ import { randomUUID as randomUUID19 } from "node:crypto";
49465
49735
  function imageBytes(bytes) {
49466
49736
  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
49737
  }
@@ -49473,61 +49743,61 @@ async function saveUpload(session, name, bytes) {
49473
49743
  let saved = "";
49474
49744
  const task = uploadQueue.catch(() => {
49475
49745
  }).then(async () => {
49476
- const root = path77.join(bridgeRoot(), "uploads");
49477
- await mkdir20(root, { recursive: true, mode: 448 });
49746
+ const root = path78.join(bridgeRoot(), "uploads");
49747
+ await mkdir21(root, { recursive: true, mode: 448 });
49478
49748
  let used = 0;
49479
49749
  const directories = await readdir16(root, { withFileTypes: true });
49480
49750
  for (const dir of directories) {
49481
49751
  if (!dir.isDirectory()) continue;
49482
- const folder2 = path77.join(root, dir.name);
49752
+ const folder2 = path78.join(root, dir.name);
49483
49753
  for (const entry2 of await readdir16(folder2, { withFileTypes: true })) {
49484
49754
  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);
49755
+ const file3 = path78.join(folder2, entry2.name), metadata = await lstat25(file3);
49756
+ if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink8(file3);
49487
49757
  else used += metadata.size;
49488
49758
  }
49489
49759
  }
49490
49760
  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 });
49761
+ const folder = path78.join(root, session);
49762
+ await mkdir21(folder, { recursive: true, mode: 448 });
49763
+ saved = path78.join(folder, `${randomUUID19()}-${name}`);
49764
+ await writeFile7(saved, bytes, { flag: "wx", mode: 384 });
49495
49765
  });
49496
49766
  uploadQueue = task;
49497
49767
  await task;
49498
49768
  return saved;
49499
49769
  }
49500
49770
  async function listUploads(session) {
49501
- const folder = path77.join(bridgeRoot(), "uploads", session);
49771
+ const folder = path78.join(bridgeRoot(), "uploads", session);
49502
49772
  const entries2 = await readdir16(folder, { withFileTypes: true }).catch(() => []);
49503
49773
  const files = [];
49504
49774
  for (const entry2 of entries2) {
49505
49775
  if (!entry2.isFile()) continue;
49506
- const file3 = path77.join(folder, entry2.name), metadata = await stat22(file3);
49776
+ const file3 = path78.join(folder, entry2.name), metadata = await stat22(file3);
49507
49777
  files.push({ name: entry2.name.replace(/^[0-9a-f-]{36}-/, ""), path: file3, size: metadata.size, modified: metadata.mtime.toISOString() });
49508
49778
  }
49509
49779
  return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
49510
49780
  }
49511
49781
  async function uploadImage(requested) {
49512
49782
  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);
49783
+ if (!requested || requested.length > 4096 || !path78.isAbsolute(requested)) throw missing;
49784
+ const root = await realpath13(path78.join(bridgeRoot(), "uploads")).catch(() => void 0);
49515
49785
  const file3 = await realpath13(requested).catch(() => void 0);
49516
- if (!root || !file3 || !file3.startsWith(root + path77.sep)) throw missing;
49786
+ if (!root || !file3 || !file3.startsWith(root + path78.sep)) throw missing;
49517
49787
  const metadata = await stat22(file3);
49518
49788
  if (!metadata.isFile()) throw missing;
49519
49789
  if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
49520
- const bytes = await readFile40(file3);
49790
+ const bytes = await readFile41(file3);
49521
49791
  if (bytes.length > 8388608) throw new BridgeError(413, "This image is too large.");
49522
49792
  if (!imageBytes(bytes)) throw missing;
49523
49793
  return bytes;
49524
49794
  }
49525
49795
  async function sessionUpload(session, requested) {
49526
49796
  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);
49797
+ if (!requested || requested.length > 4096 || !path78.isAbsolute(requested)) throw refused;
49798
+ const folder = await realpath13(path78.join(bridgeRoot(), "uploads", session)).catch(() => void 0);
49529
49799
  const file3 = await realpath13(requested).catch(() => void 0);
49530
- if (!folder || !file3 || !file3.startsWith(folder + path77.sep)) throw refused;
49800
+ if (!folder || !file3 || !file3.startsWith(folder + path78.sep)) throw refused;
49531
49801
  if (!(await stat22(file3)).isFile()) throw refused;
49532
49802
  return file3;
49533
49803
  }
@@ -49588,7 +49858,7 @@ function herdrWorktreeWorkers(s) {
49588
49858
  const workers = [];
49589
49859
  for (const pane of objects(s.panes)) {
49590
49860
  const cwd = pane.foreground_cwd || pane.cwd;
49591
- if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path78.isAbsolute(cwd)) continue;
49861
+ if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path79.isAbsolute(cwd)) continue;
49592
49862
  const name = paneAgentName(s, pane);
49593
49863
  workers.push({
49594
49864
  cwd,
@@ -49734,7 +50004,7 @@ async function paneRoute(ctx, url2, data, response) {
49734
50004
  );
49735
50005
  }
49736
50006
  async function paneRouteOnce(ctx, url2, data, response, typing) {
49737
- const { agentHooks, modelSwitcher, settingsSwitcher, codexQuestions, sideQuestions } = ctx;
50007
+ const { agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions } = ctx;
49738
50008
  let result;
49739
50009
  if (url2.pathname === "/v1/keys" && object2(data.target).starting === true) {
49740
50010
  const target = startingTargetSchema.parse(data.target);
@@ -49788,16 +50058,18 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
49788
50058
  }
49789
50059
  } else {
49790
50060
  const target = targetSchema.parse(data.target);
49791
- const sendsInput = ["/v1/prompt", "/v1/keys", "/v1/secret", "/v1/model", "/v1/settings"].includes(url2.pathname);
50061
+ const sendsInput = ["/v1/prompt", "/v1/keys", "/v1/secret", "/v1/model", "/v1/settings", "/v1/agents/permission-mode"].includes(url2.pathname);
49792
50062
  if (sendsInput) {
49793
50063
  modelSwitcher.assertAvailable(target);
49794
50064
  settingsSwitcher.assertAvailable(target);
50065
+ permissionModeSwitcher.assertAvailable(target);
49795
50066
  sideQuestions.assertAvailable(target);
49796
50067
  }
49797
50068
  const pane = await validateTarget(target, false, sendsInput || url2.pathname === "/v1/upload");
49798
50069
  if (sendsInput) {
49799
50070
  modelSwitcher.assertAvailable(target);
49800
50071
  settingsSwitcher.assertAvailable(target);
50072
+ permissionModeSwitcher.assertAvailable(target);
49801
50073
  sideQuestions.assertAvailable(target);
49802
50074
  }
49803
50075
  if (url2.pathname === "/v1/prompt") {
@@ -49882,6 +50154,9 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
49882
50154
  result = await modelSwitcher.switch(target, data);
49883
50155
  } else if (url2.pathname === "/v1/settings") {
49884
50156
  result = await settingsSwitcher.switch(target, data);
50157
+ } else if (url2.pathname === "/v1/agents/permission-mode") {
50158
+ refuseAgentOrigin(data && typeof data === "object" && "origin" in data ? data.origin ?? null : void 0);
50159
+ result = await permissionModeSwitcher.set(target, external_exports.enum(PERMISSION_MODE_VALUES).parse(data.mode));
49885
50160
  } else if (url2.pathname === "/v1/keys" && await agentHooks.servedKeys(target, external_exports.array(external_exports.enum(ANSWER_KEYS)).min(1).max(4).parse(data.keys), String(pane.agent_status))) {
49886
50161
  result = { ok: true };
49887
50162
  } else if (url2.pathname === "/v1/keys") {
@@ -49990,9 +50265,9 @@ init_fanouts();
49990
50265
  init_protocol();
49991
50266
  init_transcripts();
49992
50267
  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";
50268
+ import { randomUUID as randomUUID20 } from "node:crypto";
50269
+ 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";
50270
+ import path83 from "node:path";
49996
50271
  var fanoutMessageSchema = external_exports.object({
49997
50272
  target: targetSchema,
49998
50273
  child: external_exports.string().regex(/^[a-f0-9]{32}$/),
@@ -50031,12 +50306,12 @@ var FanoutMessages = class {
50031
50306
  if (!root) return [];
50032
50307
  const jobs = [];
50033
50308
  for (const name of (await readdir17(root)).slice(0, 1024)) {
50034
- const directory = path82.join(root, name);
50309
+ const directory = path83.join(root, name);
50035
50310
  try {
50036
- if (!(await lstat25(directory)).isDirectory() || await realpath14(directory) !== directory) continue;
50037
- const file3 = path82.join(directory, "manifest.json"), info = await lstat25(file3);
50311
+ if (!(await lstat26(directory)).isDirectory() || await realpath14(directory) !== directory) continue;
50312
+ const file3 = path83.join(directory, "manifest.json"), info = await lstat26(file3);
50038
50313
  if (!info.isFile() || info.isSymbolicLink() || info.size > 65536) continue;
50039
- const manifest = manifestSchema.parse(JSON.parse(await readFile41(file3, "utf8")));
50314
+ const manifest = manifestSchema.parse(JSON.parse(await readFile42(file3, "utf8")));
50040
50315
  if (manifest.id === name) jobs.push({ directory, manifest });
50041
50316
  } catch {
50042
50317
  }
@@ -50058,10 +50333,10 @@ var FanoutMessages = class {
50058
50333
  const data = fanoutMessageSchema.parse(input2);
50059
50334
  const job = await this.selected(data.target, data.child);
50060
50335
  const directory = await this.messageDirectory(job);
50061
- const message = { id: randomUUID19(), text: data.text, status: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString() };
50336
+ const message = { id: randomUUID20(), text: data.text, status: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString() };
50062
50337
  const pending = (await this.records(job)).filter((row) => row.message.status === "queued");
50063
50338
  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`);
50339
+ const file3 = path83.join(directory, `${message.createdAt.replace(/[:.]/g, "-")}-${message.id}.queued.json`);
50065
50340
  await atomic(file3, JSON.stringify(message));
50066
50341
  await this.drain(job);
50067
50342
  const fresh = (await this.records(job)).find((row) => row.message.id === message.id)?.message;
@@ -50082,14 +50357,14 @@ var FanoutMessages = class {
50082
50357
  return { messages: (await this.records(job)).map((row) => row.message) };
50083
50358
  }
50084
50359
  async messageDirectory(job) {
50085
- const directory = path82.join(job.directory, "messages");
50086
- await mkdir21(directory, { recursive: true, mode: 448 });
50360
+ const directory = path83.join(job.directory, "messages");
50361
+ await mkdir22(directory, { recursive: true, mode: 448 });
50087
50362
  if (await realpath14(directory) !== directory) throw new BridgeError(400, "Invalid worker message directory.");
50088
50363
  return directory;
50089
50364
  }
50090
50365
  async records(job) {
50091
- const directory = path82.join(job.directory, "messages");
50092
- const info = await lstat25(directory).catch(() => void 0);
50366
+ const directory = path83.join(job.directory, "messages");
50367
+ const info = await lstat26(directory).catch(() => void 0);
50093
50368
  if (!info) return [];
50094
50369
  if (!info.isDirectory() || info.isSymbolicLink() || await realpath14(directory) !== directory) {
50095
50370
  throw new BridgeError(400, "Invalid worker message directory.");
@@ -50097,10 +50372,10 @@ var FanoutMessages = class {
50097
50372
  const rows = [];
50098
50373
  for (const name of (await readdir17(directory)).sort().slice(-512)) {
50099
50374
  if (!/^[0-9TZ-]+-[a-f0-9-]+\.(queued|sent)\.json$/.test(name)) continue;
50100
- const file3 = path82.join(directory, name), info2 = await lstat25(file3);
50375
+ const file3 = path83.join(directory, name), info2 = await lstat26(file3);
50101
50376
  if (!info2.isFile() || info2.isSymbolicLink() || info2.size > 262144) continue;
50102
50377
  try {
50103
- rows.push({ file: file3, message: receiptSchema2.parse(JSON.parse(await readFile41(file3, "utf8"))) });
50378
+ rows.push({ file: file3, message: receiptSchema2.parse(JSON.parse(await readFile42(file3, "utf8"))) });
50104
50379
  } catch {
50105
50380
  }
50106
50381
  }
@@ -50120,9 +50395,9 @@ var FanoutMessages = class {
50120
50395
  }
50121
50396
  }
50122
50397
  async drain(job) {
50123
- const lock = path82.join(job.directory, "message-lock");
50398
+ const lock = path83.join(job.directory, "message-lock");
50124
50399
  try {
50125
- await mkdir21(lock, { mode: 448 });
50400
+ await mkdir22(lock, { mode: 448 });
50126
50401
  } catch {
50127
50402
  return;
50128
50403
  }
@@ -50136,27 +50411,27 @@ var FanoutMessages = class {
50136
50411
  const next = (await this.records(fresh)).find((row) => row.message.status === "queued");
50137
50412
  if (!next) return;
50138
50413
  pending = next;
50139
- if (!(await lstat25(fresh.manifest.worktree)).isDirectory()) throw new BridgeError(409, "The worker's original worktree is unavailable.");
50414
+ if (!(await lstat26(fresh.manifest.worktree)).isDirectory()) throw new BridgeError(409, "The worker's original worktree is unavailable.");
50140
50415
  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);
50416
+ const info = await lstat26(path83.join(fresh.directory, name)).catch(() => void 0);
50142
50417
  if (info && (!info.isFile() || info.isSymbolicLink())) throw new BridgeError(400, "Invalid worker output file.");
50143
50418
  }
50144
- const round = path82.join(fresh.directory, "rounds");
50145
- await mkdir21(round, { recursive: true, mode: 448 });
50419
+ const round = path83.join(fresh.directory, "rounds");
50420
+ await mkdir22(round, { recursive: true, mode: 448 });
50146
50421
  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 });
50422
+ const roundDir = path83.join(round, next.message.id);
50423
+ await mkdir22(roundDir, { mode: 448 });
50424
+ await writeFile8(path83.join(roundDir, "prompt.txt"), next.message.text, { mode: 384 });
50150
50425
  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) => {
50426
+ await rename7(path83.join(fresh.directory, name), path83.join(roundDir, `previous-${name}`)).catch((error62) => {
50152
50427
  if (error62.code !== "ENOENT") throw error62;
50153
50428
  });
50154
50429
  }
50155
- await writeFile7(path82.join(fresh.directory, "prompt.txt"), next.message.text, { mode: 384 });
50430
+ await writeFile8(path83.join(fresh.directory, "prompt.txt"), next.message.text, { mode: 384 });
50156
50431
  const sentFile = next.file.replace(/\.queued\.json$/, ".sent.json");
50157
50432
  const message = { ...next.message, status: "running" };
50158
50433
  await atomic(next.file, JSON.stringify(message));
50159
- await rename6(next.file, sentFile);
50434
+ await rename7(next.file, sentFile);
50160
50435
  pending = { file: sentFile, message };
50161
50436
  const now = (/* @__PURE__ */ new Date()).toISOString();
50162
50437
  const manifest = {
@@ -50168,9 +50443,9 @@ var FanoutMessages = class {
50168
50443
  finishedAt: void 0,
50169
50444
  exitCode: void 0
50170
50445
  };
50171
- await atomic(path82.join(fresh.directory, "manifest.json"), JSON.stringify(manifest));
50446
+ await atomic(path83.join(fresh.directory, "manifest.json"), JSON.stringify(manifest));
50172
50447
  started = manifest;
50173
- await appendFile2(path82.join(fresh.directory, manifest.eventLog), JSON.stringify({
50448
+ await appendFile2(path83.join(fresh.directory, manifest.eventLog), JSON.stringify({
50174
50449
  type: "phren/fanout-message",
50175
50450
  timestamp: now,
50176
50451
  id: message.id,
@@ -50194,7 +50469,7 @@ var FanoutMessages = class {
50194
50469
  await atomic(sentFile, JSON.stringify({ ...message, status: code === 0 ? "completed" : "failed" }));
50195
50470
  }).catch(async () => {
50196
50471
  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() }));
50472
+ await atomic(path83.join(fresh.directory, "manifest.json"), JSON.stringify({ ...manifest, status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString() }));
50198
50473
  }).finally(async () => {
50199
50474
  await rm10(lock, { recursive: true, force: true });
50200
50475
  }).catch(() => {
@@ -50202,8 +50477,8 @@ var FanoutMessages = class {
50202
50477
  } catch (error62) {
50203
50478
  if (!pending) throw error62;
50204
50479
  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({
50480
+ if (pending.file.endsWith(".queued.json")) await rename7(pending.file, pending.file.replace(/\.queued\.json$/, ".sent.json"));
50481
+ if (started) await atomic(path83.join(job.directory, "manifest.json"), JSON.stringify({
50207
50482
  ...started,
50208
50483
  status: "failed",
50209
50484
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -50216,12 +50491,12 @@ var FanoutMessages = class {
50216
50491
 
50217
50492
  // src/bridge/server.ts
50218
50493
  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";
50494
+ import { randomUUID as randomUUID26 } from "node:crypto";
50495
+ 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";
50496
+ import { readFileSync as readFileSync37 } from "node:fs";
50222
50497
  import { createServer as createServer3 } from "node:http";
50223
50498
  import { cpus as cpus2, hostname as hostname12, loadavg as loadavg2 } from "node:os";
50224
- import path110 from "node:path";
50499
+ import path112 from "node:path";
50225
50500
 
50226
50501
  // src/bridge/speech-transcribe.ts
50227
50502
  init_wrapper();
@@ -50336,8 +50611,8 @@ function relayTranscription(client, query, options = {}) {
50336
50611
 
50337
50612
  // src/bridge/activity.ts
50338
50613
  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";
50614
+ import { appendFile as appendFile3, mkdir as mkdir23, readFile as readFile43, rename as rename8, stat as stat23 } from "node:fs/promises";
50615
+ import path84 from "node:path";
50341
50616
  var ActivityJournal = class {
50342
50617
  pending = Promise.resolve();
50343
50618
  previous = /* @__PURE__ */ new Map();
@@ -50364,16 +50639,16 @@ var ActivityJournal = class {
50364
50639
  });
50365
50640
  }
50366
50641
  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");
50642
+ const root = bridgeRoot(), file3 = path84.join(root, "activity.jsonl");
50643
+ await mkdir23(root, { recursive: true, mode: 448 });
50644
+ if ((await stat23(file3).catch(() => null))?.size && (await stat23(file3)).size > 2097152) await rename8(file3, file3 + ".previous");
50370
50645
  await appendFile3(file3, changes.map((row) => JSON.stringify(row)).join("\n") + "\n", { mode: 384 });
50371
50646
  if (this.previous.size > 4096) this.previous.clear();
50372
50647
  });
50373
50648
  return this.pending;
50374
50649
  }
50375
50650
  async recent() {
50376
- const text4 = await readFile42(path83.join(bridgeRoot(), "activity.jsonl"), "utf8").catch(() => "");
50651
+ const text4 = await readFile43(path84.join(bridgeRoot(), "activity.jsonl"), "utf8").catch(() => "");
50377
50652
  return text4.trim().split("\n").slice(-500).flatMap((line) => {
50378
50653
  try {
50379
50654
  return [JSON.parse(line)];
@@ -50392,7 +50667,7 @@ init_changes();
50392
50667
  init_store_registry();
50393
50668
  import { rm as rm11 } from "node:fs/promises";
50394
50669
  import * as fs27 from "node:fs";
50395
- import * as path85 from "node:path";
50670
+ import * as path86 from "node:path";
50396
50671
  init_zod();
50397
50672
  init_shared();
50398
50673
 
@@ -50400,7 +50675,7 @@ init_shared();
50400
50675
  import { execFileSync as execFileSync5 } from "node:child_process";
50401
50676
  import * as fs26 from "node:fs";
50402
50677
  import { homedir as homedir18 } from "node:os";
50403
- import * as path84 from "node:path";
50678
+ import * as path85 from "node:path";
50404
50679
  import { fileURLToPath as fileURLToPath5, pathToFileURL } from "node:url";
50405
50680
  var CODE_PACKAGE_HINT = "phren code needs @phren/code: run phren modules enable code";
50406
50681
  var loaded;
@@ -50409,13 +50684,13 @@ function loadedFrom() {
50409
50684
  return resolvedFrom;
50410
50685
  }
50411
50686
  function bridgeRoot2() {
50412
- return process.env.PHREN_BRIDGE_HOME || path84.join(homedir18(), ".local/share/phren/bridge");
50687
+ return process.env.PHREN_BRIDGE_HOME || path85.join(homedir18(), ".local/share/phren/bridge");
50413
50688
  }
50414
- var EXTRA_PATH = [path84.join(homedir18(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
50689
+ var EXTRA_PATH = [path85.join(homedir18(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
50415
50690
  function npmPath() {
50416
- const entries2 = (process.env.PATH ?? "").split(path84.delimiter).filter(Boolean);
50691
+ const entries2 = (process.env.PATH ?? "").split(path85.delimiter).filter(Boolean);
50417
50692
  for (const entry2 of EXTRA_PATH) if (!entries2.includes(entry2) && fs26.existsSync(entry2)) entries2.push(entry2);
50418
- return entries2.join(path84.delimiter);
50693
+ return entries2.join(path85.delimiter);
50419
50694
  }
50420
50695
  function npm(args, options) {
50421
50696
  const env = { ...process.env, PATH: npmPath() };
@@ -50423,11 +50698,11 @@ function npm(args, options) {
50423
50698
  return String(execFileSync5("npm.cmd", args.map((arg) => `"${arg}"`), { ...options, env, shell: true }) ?? "");
50424
50699
  }
50425
50700
  function packageEntry(directory) {
50426
- const manifest = JSON.parse(fs26.readFileSync(path84.join(directory, "package.json"), "utf8"));
50701
+ const manifest = JSON.parse(fs26.readFileSync(path85.join(directory, "package.json"), "utf8"));
50427
50702
  const exported = typeof manifest.exports === "object" && manifest.exports !== null && "." in manifest.exports ? manifest.exports["."] : manifest.exports;
50428
50703
  const nested = typeof exported === "object" && exported !== null ? exported.default ?? exported.import : exported;
50429
50704
  for (const candidate of [nested, manifest.module, manifest.main, "index.js", "index.mjs"]) {
50430
- if (typeof candidate === "string") return path84.join(directory, candidate);
50705
+ if (typeof candidate === "string") return path85.join(directory, candidate);
50431
50706
  }
50432
50707
  throw new Error(`@phren/code has no entry point in ${directory}.`);
50433
50708
  }
@@ -50437,7 +50712,7 @@ async function importDirectory(directory) {
50437
50712
  function globalPackageDirectory() {
50438
50713
  try {
50439
50714
  const root = npm(["root", "-g"], { encoding: "utf8", timeout: 1e4 }).trim();
50440
- return root ? path84.join(root, "@phren", "code") : void 0;
50715
+ return root ? path85.join(root, "@phren", "code") : void 0;
50441
50716
  } catch {
50442
50717
  return void 0;
50443
50718
  }
@@ -50446,13 +50721,13 @@ async function loadCodePackage(store) {
50446
50721
  if (loaded) return loaded;
50447
50722
  const candidates = [];
50448
50723
  if (process.env.PHREN_CODE_PACKAGE) candidates.push(process.env.PHREN_CODE_PACKAGE);
50449
- candidates.push(path84.join(bridgeRoot2(), "node_modules", "@phren", "code"));
50724
+ candidates.push(path85.join(bridgeRoot2(), "node_modules", "@phren", "code"));
50450
50725
  const root = store || process.env.PHREN_PATH;
50451
- if (root) candidates.push(path84.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
50726
+ if (root) candidates.push(path85.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
50452
50727
  const workspace = workspaceCodeDirectory();
50453
50728
  if (workspace && builtEntryExists(workspace)) candidates.push(workspace);
50454
50729
  for (const directory of candidates) {
50455
- if (!fs26.existsSync(path84.join(directory, "package.json"))) continue;
50730
+ if (!fs26.existsSync(path85.join(directory, "package.json"))) continue;
50456
50731
  try {
50457
50732
  loaded = await importDirectory(directory);
50458
50733
  resolvedFrom = directory;
@@ -50468,7 +50743,7 @@ async function loadCodePackage(store) {
50468
50743
  if (error62.code !== "ERR_MODULE_NOT_FOUND") throw error62;
50469
50744
  }
50470
50745
  const global = globalPackageDirectory();
50471
- if (global && fs26.existsSync(path84.join(global, "package.json"))) {
50746
+ if (global && fs26.existsSync(path85.join(global, "package.json"))) {
50472
50747
  try {
50473
50748
  loaded = await importDirectory(global);
50474
50749
  resolvedFrom = global;
@@ -50479,11 +50754,11 @@ async function loadCodePackage(store) {
50479
50754
  return void 0;
50480
50755
  }
50481
50756
  function workspaceCodeDirectory() {
50482
- let directory = path84.dirname(fileURLToPath5(import.meta.url));
50757
+ let directory = path85.dirname(fileURLToPath5(import.meta.url));
50483
50758
  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);
50759
+ const candidate = path85.join(directory, "packages", "code");
50760
+ if (fs26.existsSync(path85.join(candidate, "package.json"))) return candidate;
50761
+ const parent = path85.dirname(directory);
50487
50762
  if (parent === directory) break;
50488
50763
  directory = parent;
50489
50764
  }
@@ -50498,7 +50773,7 @@ function builtEntryExists(directory) {
50498
50773
  }
50499
50774
  function codePackageHint(store) {
50500
50775
  const root = store || process.env.PHREN_PATH;
50501
- const linked = root && path84.join(root, ".runtime", "packages", "node_modules", "@phren", "code");
50776
+ const linked = root && path85.join(root, ".runtime", "packages", "node_modules", "@phren", "code");
50502
50777
  const workspace = workspaceCodeDirectory();
50503
50778
  let workspaceLink;
50504
50779
  try {
@@ -50506,7 +50781,7 @@ function codePackageHint(store) {
50506
50781
  } catch {
50507
50782
  }
50508
50783
  for (const directory of [workspace, workspaceLink]) {
50509
- if (!directory || !fs26.existsSync(path84.join(directory, "package.json")) || builtEntryExists(directory)) continue;
50784
+ if (!directory || !fs26.existsSync(path85.join(directory, "package.json")) || builtEntryExists(directory)) continue;
50510
50785
  return `${CODE_PACKAGE_HINT}. @phren/code at ${directory} has no built entry. From the source checkout root run: pnpm --filter @phren/code build`;
50511
50786
  }
50512
50787
  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 +50817,7 @@ var projectSchema = external_exports.string().min(1).max(100).refine((value2) =>
50542
50817
  var querySchema = external_exports.string().max(500);
50543
50818
  var symbolSchema = external_exports.string().min(1).max(4600);
50544
50819
  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 === ""));
50820
+ var relativePathSchema = pathSchema.refine((value2) => !path86.isAbsolute(value2) && !path86.win32.isAbsolute(value2) && !value2.includes("\\") && !value2.split("/").some((part) => part === "." || part === ""));
50546
50821
  var optionalPath = (value2) => value2 ? relativePathSchema.parse(value2) : void 0;
50547
50822
  var offsetSchema = external_exports.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
50548
50823
  var kindSchema = external_exports.enum(KIND_VALUES);
@@ -50630,9 +50905,9 @@ var CodeRoutes = class {
50630
50905
  };
50631
50906
  const midnight = new Date(now);
50632
50907
  midnight.setHours(0, 0, 0, 0);
50633
- const dir = path85.join(bridgeRoot(), "changes");
50908
+ const dir = path86.join(bridgeRoot(), "changes");
50634
50909
  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);
50910
+ 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
50911
  for (const log2 of today) {
50637
50912
  for (const line of fs27.readFileSync(log2.file, "utf8").split("\n")) {
50638
50913
  if (!line.trim()) continue;
@@ -50693,7 +50968,7 @@ var CodeRoutes = class {
50693
50968
  for (const file3 of untracked) {
50694
50969
  let count2 = 0;
50695
50970
  try {
50696
- count2 = fs27.readFileSync(path85.join(root, file3), "utf8").split("\n").length;
50971
+ count2 = fs27.readFileSync(path86.join(root, file3), "utf8").split("\n").length;
50697
50972
  } catch {
50698
50973
  continue;
50699
50974
  }
@@ -50723,7 +50998,7 @@ var CodeRoutes = class {
50723
50998
  const project = projectSchema.parse(projectValue ?? "");
50724
50999
  const { codeDatabasePath } = await requireCodePackage(this.store);
50725
51000
  const file3 = codeDatabasePath(this.store, project);
50726
- await Promise.all([file3, `${file3}-journal`, `${file3}-wal`, `${file3}-shm`].map((path112) => rm11(path112, { force: true })));
51001
+ await Promise.all([file3, `${file3}-journal`, `${file3}-wal`, `${file3}-shm`].map((path114) => rm11(path114, { force: true })));
50727
51002
  return { project, disabled: true };
50728
51003
  }
50729
51004
  async reindex(projectValue) {
@@ -50757,7 +51032,7 @@ var CodeRoutes = class {
50757
51032
  } catch {
50758
51033
  throw new BridgeError(400, "Choose valid paths.");
50759
51034
  }
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);
51035
+ 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
51036
  const result = await (await requireCodePackage(this.store)).outlineSummary(this.store, project, [...new Set(paths)]);
50762
51037
  if (!result.available) throw noIndex(project);
50763
51038
  return { project, entries: result.value };
@@ -50832,7 +51107,7 @@ var CodeReindexer = class {
50832
51107
  const { codeDatabasePath, resolveRepoRoot } = await requireCodePackage(this.store);
50833
51108
  const result = [];
50834
51109
  for (const directory of getProjectDirs(this.store)) {
50835
- const project = path85.basename(directory);
51110
+ const project = path86.basename(directory);
50836
51111
  if (!fs27.existsSync(codeDatabasePath(this.store, project))) continue;
50837
51112
  try {
50838
51113
  result.push({ project, root: fs27.realpathSync(resolveRepoRoot(this.store, project)) });
@@ -50874,13 +51149,13 @@ var CodeReindexer = class {
50874
51149
  };
50875
51150
  function readHead(root) {
50876
51151
  try {
50877
- const dotGit = path85.join(root, ".git");
51152
+ const dotGit = path86.join(root, ".git");
50878
51153
  const gitDirectory2 = fs27.statSync(dotGit).isDirectory() ? dotGit : (() => {
50879
51154
  const match = /^gitdir:\s*(.+)$/m.exec(fs27.readFileSync(dotGit, "utf8"));
50880
- return match ? path85.resolve(root, match[1]) : void 0;
51155
+ return match ? path86.resolve(root, match[1]) : void 0;
50881
51156
  })();
50882
51157
  if (!gitDirectory2) return void 0;
50883
- return fs27.readFileSync(path85.join(gitDirectory2, "HEAD"), "utf8").trim();
51158
+ return fs27.readFileSync(path86.join(gitDirectory2, "HEAD"), "utf8").trim();
50884
51159
  } catch {
50885
51160
  return void 0;
50886
51161
  }
@@ -50890,7 +51165,7 @@ function readHead(root) {
50890
51165
  init_herdr();
50891
51166
  init_protocol();
50892
51167
  init_transcripts();
50893
- import { open as open17 } from "node:fs/promises";
51168
+ import { open as open18 } from "node:fs/promises";
50894
51169
  import { constants as constants3 } from "node:fs";
50895
51170
  var MAX_TAIL_BYTES = 262144;
50896
51171
  var MAX_SESSIONS = 32;
@@ -50923,7 +51198,7 @@ function codexContext(tail2, startsAtBeginning) {
50923
51198
  var ContextUsageReader = class {
50924
51199
  cache = /* @__PURE__ */ new Map();
50925
51200
  async read(file3, session) {
50926
- const handle = await open17(file3, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
51201
+ const handle = await open18(file3, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
50927
51202
  try {
50928
51203
  const metadata = await handle.stat();
50929
51204
  if (!metadata.isFile()) return void 0;
@@ -51029,8 +51304,8 @@ init_transcript_index();
51029
51304
  init_codex_question_reply();
51030
51305
  import { execFile as execFile16 } from "node:child_process";
51031
51306
  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";
51307
+ import { mkdir as mkdir24, open as open19, stat as stat24, readFile as readFile44, writeFile as writeFile9 } from "node:fs/promises";
51308
+ import path87 from "node:path";
51034
51309
  import { promisify as promisify15 } from "node:util";
51035
51310
  var exec15 = promisify15(execFile16);
51036
51311
  var text3 = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
@@ -51257,7 +51532,7 @@ var CodexQuestions = class {
51257
51532
  }
51258
51533
  return Promise.all((pending ?? []).map(async (p) => {
51259
51534
  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);
51535
+ const submitted = await readFile44(path87.join(bridgeRoot(), "question-replies", key3), "utf8").then((value2) => value2 === "submitted").catch(() => false);
51261
51536
  return { toolUseId: p.id, isAsync: true, submitted, questions: asPrompt(p.questions) };
51262
51537
  })).then((prompts) => prompts.filter((p) => !p.submitted));
51263
51538
  }
@@ -51290,11 +51565,11 @@ var CodexQuestions = class {
51290
51565
  ] : [];
51291
51566
  const pane = await validateTarget(target);
51292
51567
  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 });
51568
+ const directory = path87.join(bridgeRoot(), "question-replies");
51569
+ await mkdir24(directory, { recursive: true, mode: 448 });
51295
51570
  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) => {
51571
+ const receiptPath = path87.join(directory, key3);
51572
+ const receipt = await open19(receiptPath, "wx", 384).catch((error62) => {
51298
51573
  if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
51299
51574
  throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
51300
51575
  });
@@ -51302,7 +51577,7 @@ var CodexQuestions = class {
51302
51577
  try {
51303
51578
  if (entry2) await this.served.steer(entry2, reply, extra);
51304
51579
  else await exec15(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8e3, maxBuffer: 65536 });
51305
- await writeFile8(receiptPath, "submitted", { mode: 384 });
51580
+ await writeFile9(receiptPath, "submitted", { mode: 384 });
51306
51581
  } catch {
51307
51582
  throw new BridgeError(409, "Codex did not confirm the answer. Check the conversation; Phren has not retried it.");
51308
51583
  }
@@ -51318,14 +51593,57 @@ init_transcripts();
51318
51593
 
51319
51594
  // src/bridge/settings-switch.ts
51320
51595
  init_zod();
51321
- import { open as open19, stat as stat25 } from "node:fs/promises";
51596
+ init_terminal_text();
51597
+ import { open as open20, stat as stat25 } from "node:fs/promises";
51598
+
51599
+ // src/bridge/claude-suggestion.ts
51600
+ init_terminal_text();
51601
+ var MAX_SUGGESTION = 500;
51602
+ var rule = (line) => /^[─━═]{3,}/.test(line.trim());
51603
+ var PLACEHOLDERS = [/^Try ".*"$/, /^Press (?:up|Enter) to /, /^Message @.*…$/];
51604
+ function claudeSuggestion(screen) {
51605
+ const lines = screen.split("\n").map((line) => line.replace(/\r$/, ""));
51606
+ for (let index2 = lines.length - 2; index2 > 0; index2--) {
51607
+ const plain2 = stripTerminal(lines[index2]);
51608
+ if (!/^\s*❯/.test(plain2)) continue;
51609
+ if (!rule(stripTerminal(lines[index2 - 1])) || !rule(stripTerminal(lines[index2 + 1]))) return void 0;
51610
+ const text4 = dimText(lines[index2]);
51611
+ if (!text4 || text4.endsWith("\u2026") || text4.length > MAX_SUGGESTION || PLACEHOLDERS.some((pattern) => pattern.test(text4))) return void 0;
51612
+ return text4;
51613
+ }
51614
+ return void 0;
51615
+ }
51616
+ function dimText(line) {
51617
+ let dim = false, prompt = false, text4 = "";
51618
+ for (const token of line.match(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|[^\x1b]/gu) ?? []) {
51619
+ if (token.startsWith("\x1B")) {
51620
+ if (!token.startsWith("\x1B[") || !token.endsWith("m")) continue;
51621
+ const codes = (token.slice(2, -1) || "0").split(/[;:]/).map(Number);
51622
+ for (let i = 0; i < codes.length; i++) {
51623
+ const code = codes[i];
51624
+ if (code === 38 || code === 48 || code === 58) {
51625
+ i += codes[i + 1] === 5 ? 2 : codes[i + 1] === 2 ? 4 : 0;
51626
+ continue;
51627
+ }
51628
+ if (code === 0 || code === 22) dim = false;
51629
+ else if (code === 2) dim = true;
51630
+ }
51631
+ } else if (!prompt) {
51632
+ if (token === "\u276F") prompt = true;
51633
+ } else if (!token.trim()) text4 += " ";
51634
+ else if (!dim) return "";
51635
+ else text4 += token;
51636
+ }
51637
+ return text4.replace(/\s+/g, " ").trim();
51638
+ }
51639
+
51640
+ // src/bridge/settings-switch.ts
51322
51641
  init_codex_servers();
51323
51642
  init_herdr();
51324
51643
  init_limits();
51325
51644
  init_protocol();
51326
51645
  init_terminal();
51327
51646
  init_transcripts();
51328
- init_terminal_text();
51329
51647
  var CODEX_MODES = {
51330
51648
  supervised: { approvalPolicy: "untrusted", approvalsReviewer: "user", sandboxPolicy: { type: "readOnly" } },
51331
51649
  "auto-edits": { approvalPolicy: "on-request", approvalsReviewer: "user", sandboxPolicy: { type: "workspaceWrite" } },
@@ -51340,25 +51658,13 @@ function codexModeFlags(mode) {
51340
51658
  return ["-a", String(approvalPolicy), "-s", String(sandbox), ...approvalsReviewer === "auto_review" ? ["-c", 'approvals_reviewer="auto_review"'] : []];
51341
51659
  }
51342
51660
  var MAX_PRESSES = 6;
51343
- var STEP_WAIT_MS = 2e3;
51661
+ var STEP_WAIT_MS2 = 2e3;
51344
51662
  function settingsCapabilities(source, codexServed, claudeBypass = false) {
51345
51663
  if (source === "codex") return codexServed ? { permissionModes: [...PERMISSION_MODES], plan: true, fast: false } : { permissionModes: [], plan: false, fast: false };
51346
51664
  if (source === "claude") return { permissionModes: PERMISSION_MODES.filter((mode) => mode !== "full-access" || claudeBypass), plan: true, fast: true };
51347
51665
  return void 0;
51348
51666
  }
51349
51667
  var request8 = external_exports.object({ permissionMode: external_exports.enum(PERMISSION_MODES).optional(), plan: external_exports.boolean().optional(), fast: external_exports.boolean().optional() }).strict().refine((value2) => value2.permissionMode !== void 0 || value2.plan !== void 0 || value2.fast !== void 0, "Choose a setting to change.");
51350
- function claudeFooterMode(screen) {
51351
- for (const line of stripTerminal(screen).split(/\r?\n/).map((line2) => line2.trim()).filter(Boolean).slice(-8).reverse()) {
51352
- const text4 = line.replace(/^[⏵⏸]+\s*/, "");
51353
- if (text4 === line) continue;
51354
- if (/bypass permissions on/i.test(text4)) return "bypassPermissions";
51355
- if (/^manual mode on\b/i.test(text4)) return "default";
51356
- if (/^accept edits on\b/i.test(text4)) return "acceptEdits";
51357
- if (/^plan mode on\b/i.test(text4)) return "plan";
51358
- if (/^auto mode on\b/i.test(text4)) return "auto";
51359
- }
51360
- return void 0;
51361
- }
51362
51668
  var ClaudeSettingsReader = class {
51363
51669
  constructor(hooks, every = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3e3)) {
51364
51670
  this.hooks = hooks;
@@ -51375,16 +51681,25 @@ var ClaudeSettingsReader = class {
51375
51681
  this.cache.set(key3, entry2);
51376
51682
  if (Date.now() - entry2.at >= this.every) {
51377
51683
  entry2.at = Date.now();
51378
- entry2.mode = await this.hooks.paneLines(target).then(claudeFooterMode, () => entry2.mode);
51684
+ const screen = await this.hooks.paneAnsi(target).catch(() => void 0);
51685
+ if (screen !== void 0) entry2.mode = claudeFooterMode(screen);
51686
+ entry2.suggestion = screen === void 0 ? void 0 : claudeSuggestion(screen);
51379
51687
  if (entry2.mode === "bypassPermissions") entry2.bypass = true;
51380
51688
  while (this.cache.size > 64) this.cache.delete(this.cache.keys().next().value);
51381
51689
  }
51382
51690
  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 } } : {} };
51691
+ return {
51692
+ bypass: entry2.bypass,
51693
+ ...phone ? { state: phone === "plan" ? { plan: true } : { permissionMode: phone, plan: false } } : {},
51694
+ ...entry2.suggestion ? { suggestion: { text: entry2.suggestion, readAt: entry2.at } } : {},
51695
+ // The raw Claude mode the phone's mode picker shows, only when the footer
51696
+ // was read: an unreadable one is not a confident "default".
51697
+ ...entry2.mode ? { permissionMode: entry2.mode, permissionModes: permissionModes(entry2.bypass) } : {}
51698
+ };
51384
51699
  }
51385
51700
  };
51386
51701
  async function commandOutput2(file3, from) {
51387
- const handle = await open19(file3, "r");
51702
+ const handle = await open20(file3, "r");
51388
51703
  try {
51389
51704
  const { size } = await handle.stat(), length = Math.min(Math.max(size - from, 0), 1048576), buffer = Buffer.alloc(length);
51390
51705
  await handle.read(buffer, 0, length, from);
@@ -51405,7 +51720,7 @@ async function commandOutput2(file3, from) {
51405
51720
  }
51406
51721
  var fileSize = async (file3) => file3 ? (await stat25(file3).catch(() => void 0))?.size ?? 0 : 0;
51407
51722
  var SettingsSwitcher = class {
51408
- constructor(hooks, wait = STEP_WAIT_MS) {
51723
+ constructor(hooks, wait = STEP_WAIT_MS2) {
51409
51724
  this.hooks = hooks;
51410
51725
  this.wait = wait;
51411
51726
  this.reader = new ClaudeSettingsReader(hooks);
@@ -51414,14 +51729,21 @@ var SettingsSwitcher = class {
51414
51729
  wait;
51415
51730
  active = /* @__PURE__ */ new Set();
51416
51731
  reader;
51417
- /** A Claude pane's footer-read settings and capabilities for the stream. */
51732
+ /** A Claude pane's footer-read settings and capabilities for the stream,
51733
+ * with the suggested next prompt its input box shows and the raw permission
51734
+ * mode (`agentStatus.permissionMode`) its picker offers. */
51418
51735
  async streamSettings(target, terminal2, codexServed) {
51419
51736
  if (target.source !== "claude") {
51420
51737
  const settings = settingsCapabilities(target.source, codexServed);
51421
51738
  return settings ? { settings } : {};
51422
51739
  }
51423
- const { state, bypass } = await this.reader.read(target, terminal2);
51424
- return { settings: settingsCapabilities("claude", false, bypass), ...state ? { settingsState: state } : {} };
51740
+ const { state, bypass, suggestion, permissionMode, permissionModes: permissionModes2 } = await this.reader.read(target, terminal2);
51741
+ return {
51742
+ settings: settingsCapabilities("claude", false, bypass),
51743
+ ...state ? { settingsState: state } : {},
51744
+ ...suggestion ? { suggestion } : {},
51745
+ ...permissionMode ? { permissionMode, permissionModes: permissionModes2 } : {}
51746
+ };
51425
51747
  }
51426
51748
  key(target) {
51427
51749
  return `${target.server}:${target.pane}`;
@@ -51550,13 +51872,208 @@ var SettingsSwitcher = class {
51550
51872
  // src/bridge/resources.ts
51551
51873
  init_home_paths();
51552
51874
  init_herdr();
51553
- init_limits();
51554
- init_protocol();
51555
51875
  import { execFile as execFile17 } from "node:child_process";
51556
- import { readdir as readdir18, readFile as readFile44, statfs } from "node:fs/promises";
51876
+ import { readdir as readdir18, readFile as readFile45, statfs } from "node:fs/promises";
51557
51877
  import { cpus, loadavg, totalmem, uptime } from "node:os";
51558
- import path87 from "node:path";
51878
+ import path89 from "node:path";
51559
51879
  import { promisify as promisify16 } from "node:util";
51880
+
51881
+ // src/bridge/job-registry.ts
51882
+ init_zod();
51883
+ init_protocol();
51884
+ import { readFileSync as readFileSync29 } from "node:fs";
51885
+ import path88 from "node:path";
51886
+ var paneSchema = external_exports.object({
51887
+ server: external_exports.string().min(1).max(200),
51888
+ workspace: external_exports.string().max(200).optional(),
51889
+ pane: external_exports.string().min(1).max(200),
51890
+ agent: external_exports.string().max(60).optional(),
51891
+ label: external_exports.string().max(200).optional()
51892
+ }).strict();
51893
+ var jobSchema = external_exports.object({
51894
+ /** The worker's process group, once the process table has shown it. */
51895
+ pgid: external_exports.number().int().positive().optional(),
51896
+ /** When the group's leader started (epoch ms), recorded with the pgid, so a
51897
+ * group id the system later reuses for another program is never signalled. */
51898
+ leaderStartedAt: external_exports.number().int().nonnegative().optional(),
51899
+ pane: paneSchema.optional(),
51900
+ session: external_exports.string().min(1).max(200).optional(),
51901
+ agent: external_exports.string().max(60).optional(),
51902
+ label: external_exports.string().max(200).optional(),
51903
+ /** The Harness/executable the Hook started, for display and a reuse check. */
51904
+ command: external_exports.string().min(1).max(500),
51905
+ /** Epoch ms. */
51906
+ startedAt: external_exports.number().int().nonnegative()
51907
+ }).strict();
51908
+ var stateSchema2 = external_exports.object({ version: external_exports.literal(1), jobs: external_exports.array(jobSchema).max(1024) }).strict();
51909
+ var paneKey3 = (pane) => `${pane.server}\0${pane.pane}`;
51910
+ function jobKey(job) {
51911
+ if (job.pane) return `pane:${paneKey3(job.pane)}`;
51912
+ if (job.session) return `session:${job.session}`;
51913
+ if (job.pgid !== void 0) return `pgid:${job.pgid}`;
51914
+ return `command:${job.command}`;
51915
+ }
51916
+ function jobPgids(jobs) {
51917
+ const byPgid = /* @__PURE__ */ new Map();
51918
+ for (const job of jobs) if (job.pgid !== void 0 && !byPgid.has(job.pgid)) byPgid.set(job.pgid, job);
51919
+ return byPgid;
51920
+ }
51921
+ function resolveJobGroups(jobs, rows, owners) {
51922
+ const byPane = /* @__PURE__ */ new Map();
51923
+ for (const row of rows) {
51924
+ const pane = owners.get(row.pid);
51925
+ if (pane && row.pgid > 1 && !byPane.has(paneKey3(pane))) byPane.set(paneKey3(pane), row.pgid);
51926
+ }
51927
+ const leaders = new Map(rows.filter((row) => row.pid === row.pgid && row.startedAt !== void 0).map((row) => [row.pid, Math.round(row.startedAt)]));
51928
+ return jobs.map((job) => {
51929
+ if (job.pgid !== void 0 || !job.pane) return job;
51930
+ const pgid = byPane.get(paneKey3(job.pane));
51931
+ if (pgid === void 0) return job;
51932
+ const leaderStartedAt = leaders.get(pgid);
51933
+ return { ...job, pgid, ...leaderStartedAt !== void 0 ? { leaderStartedAt } : {} };
51934
+ });
51935
+ }
51936
+ var CLEANUP_LEASE_MS = 5 * 6e4;
51937
+ var LEADER_START_TOLERANCE_MS = 3e3;
51938
+ var CLEANUP_RETAIN_MS = 24 * 60 * 6e4;
51939
+ function commandMatches(job, row) {
51940
+ return path88.basename(row.command) === path88.basename(job.command) || row.args.includes(job.command);
51941
+ }
51942
+ function planCleanup(jobs, rows, live, options = {}) {
51943
+ const now = options.now ?? Date.now(), leaseMs = options.leaseMs ?? CLEANUP_LEASE_MS, retainMs = options.retainMs ?? CLEANUP_RETAIN_MS;
51944
+ const self = options.selfPid ?? process.pid;
51945
+ const panesKnown = options.panesKnown ?? true;
51946
+ const byPgid = /* @__PURE__ */ new Map();
51947
+ for (const row of rows) {
51948
+ const list = byPgid.get(row.pgid);
51949
+ if (list) list.push(row);
51950
+ else byPgid.set(row.pgid, [row]);
51951
+ }
51952
+ const ownGroup = rows.find((row) => row.pid === self)?.pgid;
51953
+ const kill = [], keep = [], forget = [];
51954
+ for (const job of jobs) {
51955
+ const kept = (reason2) => keep.push({ job, reason: reason2 });
51956
+ if (!panesKnown) {
51957
+ kept("unknown");
51958
+ continue;
51959
+ }
51960
+ if (job.pgid === void 0) {
51961
+ if (job.pane && !live.has(paneKey3(job.pane)) && now - job.startedAt > leaseMs) forget.push(job);
51962
+ else kept("unresolved");
51963
+ continue;
51964
+ }
51965
+ if (job.pgid <= 1 || job.pgid === ownGroup) {
51966
+ kept("reserved");
51967
+ continue;
51968
+ }
51969
+ if (!job.pane) {
51970
+ kept("no-pane");
51971
+ continue;
51972
+ }
51973
+ if (!options.servers?.has(job.pane.server)) {
51974
+ kept("server-unknown");
51975
+ continue;
51976
+ }
51977
+ if (live.has(paneKey3(job.pane))) {
51978
+ kept("pane-alive");
51979
+ continue;
51980
+ }
51981
+ const group = byPgid.get(job.pgid);
51982
+ if (!group || group.length === 0) {
51983
+ forget.push(job);
51984
+ continue;
51985
+ }
51986
+ if (group.some((row) => row.pid === self)) {
51987
+ kept("self");
51988
+ continue;
51989
+ }
51990
+ if (now - job.startedAt < leaseMs) {
51991
+ kept("lease");
51992
+ continue;
51993
+ }
51994
+ if (!group.some((row) => commandMatches(job, row))) {
51995
+ if (now - job.startedAt > retainMs) forget.push(job);
51996
+ else kept("reused");
51997
+ continue;
51998
+ }
51999
+ const leader = group.find((row) => row.pid === job.pgid);
52000
+ if (leader && (job.leaderStartedAt === void 0 || leader.startedAt === void 0 || Math.abs(leader.startedAt - job.leaderStartedAt) > LEADER_START_TOLERANCE_MS)) {
52001
+ if (now - job.startedAt > retainMs) forget.push(job);
52002
+ else kept("leader-unverified");
52003
+ continue;
52004
+ }
52005
+ kill.push(job);
52006
+ }
52007
+ return { kill, keep, forget };
52008
+ }
52009
+ var defaultFile = () => path88.join(bridgeRoot(), "jobs.json");
52010
+ var JobRegistry = class {
52011
+ constructor(file3 = defaultFile(), now = Date.now) {
52012
+ this.file = file3;
52013
+ this.now = now;
52014
+ }
52015
+ file;
52016
+ now;
52017
+ async list() {
52018
+ try {
52019
+ const parsed = stateSchema2.safeParse(JSON.parse(readFileSync29(this.file, "utf8")));
52020
+ return parsed.success ? parsed.data.jobs : [];
52021
+ } catch {
52022
+ return [];
52023
+ }
52024
+ }
52025
+ async replace(jobs) {
52026
+ await atomicInPrivateDir(this.file, JSON.stringify({ version: 1, jobs }, null, 2) + "\n");
52027
+ }
52028
+ /** Record (or refresh) one worker's job, keyed by its pane. */
52029
+ async register(job) {
52030
+ const entry2 = { ...job, startedAt: job.startedAt ?? this.now() };
52031
+ const key3 = jobKey(entry2);
52032
+ const jobs = await this.list();
52033
+ await this.replace([...jobs.filter((existing) => jobKey(existing) !== key3), entry2].slice(-1024));
52034
+ return entry2;
52035
+ }
52036
+ /** Resolve process groups against the current table and persist any change. */
52037
+ async reconcile(rows, owners) {
52038
+ const jobs = await this.list();
52039
+ const resolved = resolveJobGroups(jobs, rows, owners);
52040
+ if (JSON.stringify(resolved) !== JSON.stringify(jobs)) await this.replace(resolved);
52041
+ return resolved;
52042
+ }
52043
+ /**
52044
+ * End every registered process group that is safe to end (`planCleanup`) and
52045
+ * drop the records that are gone. `live` is the set of pane keys the caller
52046
+ * still sees; a caller whose snapshot failed passes `panesKnown: false`, and
52047
+ * nothing is ended.
52048
+ */
52049
+ async cleanup(rows, live, options = {}) {
52050
+ const jobs = options.owners ? await this.reconcile(rows, options.owners) : await this.list();
52051
+ const plan = planCleanup(jobs, rows, live, { ...options, ...options.now === void 0 ? { now: this.now() } : {} });
52052
+ const signal = options.kill ?? ((pgid, value2) => {
52053
+ process.kill(-pgid, value2);
52054
+ });
52055
+ const killed = [];
52056
+ for (const job of plan.kill) {
52057
+ try {
52058
+ signal(job.pgid, "SIGTERM");
52059
+ killed.push(job.pgid);
52060
+ } catch {
52061
+ }
52062
+ }
52063
+ const done = new Set([...plan.forget, ...plan.kill].map(jobKey));
52064
+ const remaining = jobs.filter((job) => !done.has(jobKey(job)));
52065
+ if (remaining.length !== jobs.length) await this.replace(remaining);
52066
+ return {
52067
+ killed,
52068
+ kept: plan.keep.map(({ job, reason: reason2 }) => ({ ...job.pgid !== void 0 ? { pgid: job.pgid } : {}, reason: reason2 })),
52069
+ forgotten: plan.forget.flatMap((job) => job.pgid !== void 0 ? [job.pgid] : [])
52070
+ };
52071
+ }
52072
+ };
52073
+
52074
+ // src/bridge/resources.ts
52075
+ init_limits();
52076
+ init_protocol();
51560
52077
  var exec16 = promisify16(execFile17);
51561
52078
  var RESOURCES_MAX_AGE_MS = intervalFromEnv("PHREN_RESOURCES_MAX_AGE_MS", 1e4, 1e3, 6e4);
51562
52079
  var LOW_DISK_BYTES = 10 * 1024 ** 3;
@@ -51569,15 +52086,27 @@ function parsePs(stats, args) {
51569
52086
  }
51570
52087
  const rows = [];
51571
52088
  for (const line of stats.split("\n")) {
51572
- const match = /^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
52089
+ const six = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
52090
+ const five = six ? void 0 : /^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
52091
+ const match = six ?? five;
51573
52092
  if (!match) continue;
51574
52093
  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() });
52094
+ const pgid = six ? Number(match[3]) : 0;
52095
+ const command = (six ? match[6] : match[5]).trim();
52096
+ rows.push({
52097
+ pid,
52098
+ ppid: Number(match[2]),
52099
+ pgid,
52100
+ cpu: Number(six ? match[4] : match[3]),
52101
+ rssKB: Number(six ? match[5] : match[4]),
52102
+ command,
52103
+ args: argv.get(pid) ?? command
52104
+ });
51576
52105
  }
51577
52106
  return rows;
51578
52107
  }
51579
52108
  function heavyKind(row) {
51580
- const base = path87.basename(row.command);
52109
+ const base = path89.basename(row.command);
51581
52110
  const args = row.args;
51582
52111
  if (base === "launchd_sim") {
51583
52112
  return { kind: "simulator", name: /XCTestDevices|Clone \d+ of /.test(args) ? "Simulator test clone" : "Simulator" };
@@ -51597,7 +52126,7 @@ function heavyKind(row) {
51597
52126
  if (base === "claude" || /(?:^|\/)claude\/versions\/\d+\.\d+\.\d+$/.test(row.command)) return { kind: "claude", name: "Claude Code" };
51598
52127
  return void 0;
51599
52128
  }
51600
- function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), limit = 12) {
52129
+ function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), jobs = [], limit = 12) {
51601
52130
  const byPid = new Map(rows.map((row) => [row.pid, row]));
51602
52131
  const kinds = /* @__PURE__ */ new Map();
51603
52132
  for (const row of rows) {
@@ -51606,11 +52135,12 @@ function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), limit = 12) {
51606
52135
  }
51607
52136
  for (const row of rows) {
51608
52137
  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") {
52138
+ if (kinds.get(row.pid)?.kind === "codex" && parent && path89.basename(parent.command) === "node" && kinds.get(parent.pid)?.kind === "codex") {
51610
52139
  kinds.set(parent.pid, kinds.get(row.pid));
51611
52140
  kinds.delete(row.pid);
51612
52141
  }
51613
52142
  }
52143
+ const jobsByPgid = jobPgids(jobs);
51614
52144
  const totals = /* @__PURE__ */ new Map();
51615
52145
  const busy = /* @__PURE__ */ new Map();
51616
52146
  const claim2 = (row) => {
@@ -51624,20 +52154,30 @@ function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), limit = 12) {
51624
52154
  for (let at = row, hops = 0; at && hops < 64; at = byPid.get(at.ppid), hops++) {
51625
52155
  const pane = owners.get(at.pid);
51626
52156
  if (pane) return pane;
52157
+ const job = jobsByPgid.get(at.pgid);
52158
+ if (job?.pane) return job.pane;
51627
52159
  if (at.ppid === at.pid || at.ppid <= 1) break;
51628
52160
  }
51629
- return void 0;
52161
+ return jobsByPgid.get(row.pgid)?.pane;
51630
52162
  };
52163
+ const trackedRoots = /* @__PURE__ */ new Set();
52164
+ for (const row of rows) {
52165
+ const root = claim2(row);
52166
+ if (root !== void 0 && jobsByPgid.has(row.pgid)) trackedRoots.add(root);
52167
+ }
51631
52168
  for (const row of rows) {
51632
52169
  const root = claim2(row);
52170
+ const tracked = jobsByPgid.has(row.pgid) || root !== void 0 && trackedRoots.has(root);
51633
52171
  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 });
52172
+ const name = path89.basename(row.command).slice(0, 60);
52173
+ const key3 = tracked ? `job:${row.pgid}\0${name}` : name;
52174
+ const group = busy.get(key3);
52175
+ 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
52176
  else {
51638
52177
  group.processes++;
51639
52178
  group.cpuPercent += row.cpu;
51640
52179
  group.memoryBytes += row.rssKB * 1024;
52180
+ if (tracked) group.tracked = true;
51641
52181
  if (row.cpu > group.top) {
51642
52182
  group.top = row.cpu;
51643
52183
  group.pid = row.pid;
@@ -51650,19 +52190,30 @@ function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), limit = 12) {
51650
52190
  if (!total) {
51651
52191
  const { kind, name } = kinds.get(root);
51652
52192
  const pane = owner(byPid.get(root));
51653
- total = { kind, name, pid: root, processes: 0, cpuPercent: 0, memoryBytes: 0, ...pane ? { pane } : {} };
52193
+ total = {
52194
+ kind,
52195
+ name,
52196
+ pid: root,
52197
+ processes: 0,
52198
+ cpuPercent: 0,
52199
+ memoryBytes: 0,
52200
+ ...tracked ? { tracked: true } : {},
52201
+ ...pane ? { pane } : {},
52202
+ ...pane?.agent ? { agent: pane.agent } : {}
52203
+ };
51654
52204
  totals.set(root, total);
51655
52205
  }
51656
52206
  total.processes++;
51657
52207
  total.cpuPercent += row.cpu;
51658
52208
  total.memoryBytes += row.rssKB * 1024;
52209
+ if (tracked) total.tracked = true;
51659
52210
  }
51660
52211
  for (const { top: _top, row, ...group } of busy.values()) {
51661
- if (group.cpuPercent < 50) continue;
52212
+ if (group.cpuPercent < 50 && !group.tracked) continue;
51662
52213
  const pane = owner(row);
51663
- totals.set(group.pid, { ...group, ...pane ? { pane } : {} });
52214
+ totals.set(group.pid, { ...group, ...pane ? { pane } : {}, ...pane?.agent ? { agent: pane.agent } : {} });
51664
52215
  }
51665
- return [...totals.values()].filter((item) => item.kind === "busy" || item.cpuPercent >= 10 || item.memoryBytes >= 200 * 1024 ** 2).map((item) => ({
52216
+ return [...totals.values()].filter((item) => item.kind === "busy" || item.cpuPercent >= 10 || item.memoryBytes >= 200 * 1024 ** 2 || item.tracked).map((item) => ({
51666
52217
  ...item,
51667
52218
  cpuPercent: Math.round(item.cpuPercent * 10) / 10,
51668
52219
  resourceReason: item.cpuPercent >= 10 ? "cpu" : item.memoryBytes >= 200 * 1024 ** 2 ? "memory" : "tracked"
@@ -51737,7 +52288,7 @@ async function linuxBattery() {
51737
52288
  const names = await readdir18(root).catch(() => []);
51738
52289
  const battery = names.find((name) => /^BAT/.test(name));
51739
52290
  if (!battery) return void 0;
51740
- const read = (name, field) => readFile44(path87.join(root, name, field), "utf8").then((text4) => text4.trim()).catch(() => "");
52291
+ const read = (name, field) => readFile45(path89.join(root, name, field), "utf8").then((text4) => text4.trim()).catch(() => "");
51741
52292
  const [capacity2, status] = await Promise.all([read(battery, "capacity"), read(battery, "status")]);
51742
52293
  const online = await Promise.all(names.filter((name) => !/^BAT/.test(name)).map((name) => read(name, "online")));
51743
52294
  const percent = Number(capacity2);
@@ -51745,8 +52296,37 @@ async function linuxBattery() {
51745
52296
  return { percent, charging: status === "Charging" || status === "Full", onAC: online.includes("1") };
51746
52297
  }
51747
52298
  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);
52299
+ const [stats, args, elapsed] = await Promise.all([
52300
+ run("/bin/ps", ["-axo", "pid=,ppid=,pgid=,pcpu=,rss=,comm="]),
52301
+ run("/bin/ps", ["-axo", "pid=,args="]),
52302
+ run("/bin/ps", ["-axo", "pid=,etime="]).catch(() => "")
52303
+ ]);
52304
+ return withStartTimes(parsePs(stats, args), elapsed, Date.now());
52305
+ }
52306
+ function parseEtime(value2) {
52307
+ const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(value2.trim());
52308
+ if (!match) return void 0;
52309
+ return Number(match[1] ?? 0) * 86400 + Number(match[2] ?? 0) * 3600 + Number(match[3]) * 60 + Number(match[4]);
52310
+ }
52311
+ function withStartTimes(rows, elapsed, now) {
52312
+ const started = /* @__PURE__ */ new Map();
52313
+ for (const line of elapsed.split("\n")) {
52314
+ const match = /^\s*(\d+)\s+(\S+)\s*$/.exec(line);
52315
+ const seconds = match ? parseEtime(match[2]) : void 0;
52316
+ if (match && seconds !== void 0) started.set(Number(match[1]), now - seconds * 1e3);
52317
+ }
52318
+ return rows.map((row) => started.has(row.pid) ? { ...row, startedAt: started.get(row.pid) } : row);
52319
+ }
52320
+ async function livePanes() {
52321
+ const panes2 = /* @__PURE__ */ new Set(), servers2 = /* @__PURE__ */ new Set();
52322
+ for (const server of await recentServers()) {
52323
+ const name = String(server.session);
52324
+ const s = await sharedSnapshot(name, RESOURCES_MAX_AGE_MS).catch(() => void 0);
52325
+ if (!s) return void 0;
52326
+ servers2.add(name);
52327
+ for (const pane of objects(s.panes)) panes2.add(paneKey3({ server: name, pane: String(pane.pane_id) }));
52328
+ }
52329
+ return { panes: panes2, servers: servers2 };
51750
52330
  }
51751
52331
  async function paneOwners() {
51752
52332
  const owners = /* @__PURE__ */ new Map();
@@ -51776,14 +52356,17 @@ async function collectResources(deps2) {
51776
52356
  const [one, five, fifteen] = loadavg();
51777
52357
  const cores = cpus().length || 1;
51778
52358
  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() }),
52359
+ const registry2 = deps2.jobs ?? new JobRegistry();
52360
+ const [memory, disk, battery, rows, registered] = await Promise.all([
52361
+ platform === "darwin" ? darwinMemory() : platform === "linux" ? readFile45("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() })) : Promise.resolve({ totalBytes: totalmem() }),
51781
52362
  statfs(deps2.home()).then((info) => ({ path: "~", totalBytes: info.blocks * info.bsize, freeBytes: info.bavail * info.bsize })).catch(() => void 0),
51782
52363
  platform === "darwin" ? run("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => void 0) : platform === "linux" ? linuxBattery() : Promise.resolve(void 0),
51783
- deps2.processes().catch(() => [])
52364
+ deps2.processes().catch(() => []),
52365
+ registry2.list().catch(() => [])
51784
52366
  ]);
51785
- const preliminary = heavyProcesses(rows);
51786
- const owners = preliminary.length ? await deps2.owners().catch(() => /* @__PURE__ */ new Map()) : /* @__PURE__ */ new Map();
52367
+ const preliminary = heavyProcesses(rows, /* @__PURE__ */ new Map(), registered);
52368
+ const owners = preliminary.length || registered.length ? await deps2.owners().catch(() => /* @__PURE__ */ new Map()) : /* @__PURE__ */ new Map();
52369
+ const jobs = owners.size ? await registry2.reconcile(rows, owners).catch(() => registered) : registered;
51787
52370
  const round = (n) => Math.round(n * 100) / 100;
51788
52371
  const value2 = {
51789
52372
  collectedAt: new Date(deps2.now()).toISOString(),
@@ -51793,19 +52376,21 @@ async function collectResources(deps2) {
51793
52376
  memory,
51794
52377
  ...disk ? { disk } : {},
51795
52378
  ...battery ? { battery } : {},
51796
- heavy: owners.size ? heavyProcesses(rows, owners) : preliminary
52379
+ heavy: owners.size || jobs.length ? heavyProcesses(rows, owners, jobs) : preliminary
51797
52380
  };
51798
52381
  return { ...value2, ...assess(value2) };
51799
52382
  }
51800
52383
  var ResourceMonitor = class {
51801
52384
  constructor(deps2 = {}, maxAgeMs = RESOURCES_MAX_AGE_MS) {
51802
52385
  this.maxAgeMs = maxAgeMs;
51803
- this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable4, owners: paneOwners, ...deps2 };
52386
+ this.registry = deps2.jobs ?? new JobRegistry();
52387
+ this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable4, owners: paneOwners, panes: livePanes, ...deps2, jobs: this.registry };
51804
52388
  }
51805
52389
  maxAgeMs;
51806
52390
  cached;
51807
52391
  pending;
51808
52392
  deps;
52393
+ registry;
51809
52394
  async read() {
51810
52395
  if (this.cached && this.deps.now() - this.cached.at < this.maxAgeMs) return this.cached.value;
51811
52396
  this.pending ??= collectResources(this.deps).then((value2) => {
@@ -51816,13 +52401,31 @@ var ResourceMonitor = class {
51816
52401
  });
51817
52402
  return this.pending;
51818
52403
  }
52404
+ /**
52405
+ * End only the registered process groups whose owning pane is gone. The
52406
+ * registry (job-registry.ts) does the safety checks; a failed pane read ends
52407
+ * nothing. Never the Hook's own service, never an owner's session, never an
52408
+ * unregistered process.
52409
+ */
52410
+ async cleanupJobs() {
52411
+ const rows = await this.deps.processes().catch(() => []);
52412
+ const owners = await this.deps.owners().catch(() => /* @__PURE__ */ new Map());
52413
+ const live = await this.deps.panes().catch(() => void 0);
52414
+ const report = await this.registry.cleanup(
52415
+ rows,
52416
+ live?.panes ?? /* @__PURE__ */ new Set(),
52417
+ { owners, panesKnown: live !== void 0, ...live ? { servers: live.servers } : {} }
52418
+ );
52419
+ this.cached = void 0;
52420
+ return report;
52421
+ }
51819
52422
  };
51820
52423
 
51821
52424
  // src/bridge/canary.ts
51822
52425
  init_phren_paths();
51823
- import { lstat as lstat26, mkdtemp as mkdtemp5, realpath as realpath15, rm as rm12 } from "node:fs/promises";
52426
+ import { lstat as lstat27, mkdtemp as mkdtemp5, realpath as realpath15, rm as rm12 } from "node:fs/promises";
51824
52427
  import { hostname as hostname11, tmpdir as tmpdir2 } from "node:os";
51825
- import path88 from "node:path";
52428
+ import path90 from "node:path";
51826
52429
  init_herdr();
51827
52430
  init_terminal();
51828
52431
  init_terminal_tmux();
@@ -51864,7 +52467,7 @@ async function closeCanaryWorkspaces(server, before, created) {
51864
52467
  }
51865
52468
  async function conductorStep(options, server) {
51866
52469
  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-")));
52470
+ const folder = await realpath15(await mkdtemp5(path90.join(tmpdir2(), "phren-canary-")));
51868
52471
  let created, failure2, detail;
51869
52472
  try {
51870
52473
  const launched = await options.launch(server, { role: "conductor", kind: "claude", label: CANARY_LABEL, cwd: folder, timeoutMs: 45e3 });
@@ -51885,12 +52488,12 @@ async function scheduleStep(options) {
51885
52488
  let count2 = 0;
51886
52489
  const broken = [];
51887
52490
  for (const directory of getProjectDirs(options.store)) {
51888
- const present2 = await lstat26(path88.join(directory, "schedules.yaml")).catch(() => void 0);
52491
+ const present2 = await lstat27(path90.join(directory, "schedules.yaml")).catch(() => void 0);
51889
52492
  if (!present2) continue;
51890
52493
  try {
51891
52494
  count2 += (await readScheduleDocument(directory)).schedules.length;
51892
52495
  } catch (error62) {
51893
- broken.push(`${path88.basename(directory)}: ${reason(error62)}`);
52496
+ broken.push(`${path90.basename(directory)}: ${reason(error62)}`);
51894
52497
  }
51895
52498
  }
51896
52499
  const tick = options.scheduler.lastTickAt;
@@ -51960,7 +52563,7 @@ function runCanary(options) {
51960
52563
  }
51961
52564
  async function dailyCanaryEnabled(root = bridgeRoot()) {
51962
52565
  if (process.env.PHREN_CANARY_DAILY === "1") return true;
51963
- return !!(await lstat26(path88.join(root, "canary-daily")).catch(() => void 0))?.isFile();
52566
+ return !!(await lstat27(path90.join(root, "canary-daily")).catch(() => void 0))?.isFile();
51964
52567
  }
51965
52568
  async function dailyCanaryDue(root = bridgeRoot(), now = Date.now()) {
51966
52569
  if (running || !await dailyCanaryEnabled(root)) return false;
@@ -51998,11 +52601,11 @@ async function ownerInboxView(inbox, input2, localOnly = false) {
51998
52601
 
51999
52602
  // src/bridge/server-routes.ts
52000
52603
  init_zod();
52001
- import path108 from "node:path";
52604
+ import path110 from "node:path";
52002
52605
 
52003
52606
  // src/bridge/code-note.ts
52004
52607
  init_zod();
52005
- import * as path94 from "node:path";
52608
+ import * as path96 from "node:path";
52006
52609
 
52007
52610
  // src/content/validate.ts
52008
52611
  init_utils_helpers();
@@ -52016,7 +52619,7 @@ init_store_routing();
52016
52619
  init_locks();
52017
52620
  init_data_utils();
52018
52621
  import * as fs29 from "fs";
52019
- import * as path90 from "path";
52622
+ import * as path92 from "path";
52020
52623
  import * as crypto8 from "crypto";
52021
52624
 
52022
52625
  // src/project-topics.ts
@@ -52028,7 +52631,7 @@ init_data_utils();
52028
52631
  init_filenames();
52029
52632
  import * as crypto7 from "crypto";
52030
52633
  import * as fs28 from "fs";
52031
- import * as path89 from "path";
52634
+ import * as path91 from "path";
52032
52635
  var TOPIC_CONFIG_FILENAME = "topic-config.json";
52033
52636
  var SOFTWARE_TOPICS = [
52034
52637
  {
@@ -52566,7 +53169,7 @@ function topicDocHeader(project, topic) {
52566
53169
  }
52567
53170
  function appendArchivedEntriesToTopicDoc(filePath, project, topic, entries2) {
52568
53171
  if (entries2.length === 0) return;
52569
- fs28.mkdirSync(path89.dirname(filePath), { recursive: true });
53172
+ fs28.mkdirSync(path91.dirname(filePath), { recursive: true });
52570
53173
  withFileLock(filePath, () => {
52571
53174
  let existing = "";
52572
53175
  if (fs28.existsSync(filePath)) existing = fs28.readFileSync(filePath, "utf8");
@@ -52685,7 +53288,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
52685
53288
  if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
52686
53289
  const resolvedDir = storeAwareProjectPath(phrenPath, project);
52687
53290
  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);
53291
+ const learningsPath = path92.join(resolvedDir, FINDINGS_FILENAME);
52689
53292
  if (!fs29.existsSync(learningsPath)) return phrenOk(0);
52690
53293
  const STALE_LOCK_MS = 6e5;
52691
53294
  const lockFile = runtimeFile(phrenPath, `consolidation-${project}.lock`);
@@ -52721,7 +53324,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
52721
53324
  const entries2 = parseActiveEntries(content);
52722
53325
  if (entries2.length <= keepCount) return phrenOk(0);
52723
53326
  const toArchive = entries2.slice(0, entries2.length - keepCount);
52724
- const referenceDir = path90.join(resolvedDir, "reference");
53327
+ const referenceDir = path92.join(resolvedDir, "reference");
52725
53328
  const { topics } = readProjectTopics(phrenPath, project);
52726
53329
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
52727
53330
  const archivedSet = buildArchivedBulletSet(referenceDir);
@@ -53291,7 +53894,7 @@ var DEFAULT_DECAY = {
53291
53894
  var DEFAULT_UNDATED_CONFIDENCE = DEFAULT_DECAY.d120;
53292
53895
 
53293
53896
  // src/content/dedup.ts
53294
- import * as path91 from "path";
53897
+ import * as path93 from "path";
53295
53898
  init_shared();
53296
53899
  init_utils();
53297
53900
  init_store_routing();
@@ -53415,7 +54018,7 @@ function resolveCoref(text4, context) {
53415
54018
  result = result.replace(/\bthe project\b/gi, context.project);
53416
54019
  }
53417
54020
  if (context.file) {
53418
- const basename12 = path91.basename(context.file);
54021
+ const basename12 = path93.basename(context.file);
53419
54022
  result = result.replace(/\b(this file|the file)\b/gi, basename12);
53420
54023
  }
53421
54024
  if (context.project && /\b(it|this|that|they|them)\b/i.test(result)) {
@@ -53432,7 +54035,7 @@ init_shared();
53432
54035
  init_shared();
53433
54036
  init_governance();
53434
54037
  import * as fs31 from "fs";
53435
- import * as path93 from "path";
54038
+ import * as path95 from "path";
53436
54039
  import * as crypto9 from "crypto";
53437
54040
 
53438
54041
  // src/finding-graph-id.ts
@@ -53467,7 +54070,7 @@ init_store_routing();
53467
54070
  // src/finding/context.ts
53468
54071
  init_utils();
53469
54072
  import * as fs30 from "fs";
53470
- import * as path92 from "path";
54073
+ import * as path94 from "path";
53471
54074
 
53472
54075
  // src/session/utils.ts
53473
54076
  init_utils();
@@ -53549,14 +54152,14 @@ function resolveFindingTaskReference(phrenPath, project, match) {
53549
54152
  const projectDir = safeProjectPath(phrenPath, project);
53550
54153
  if (!projectDir) return { error: `Invalid project name: "${project}".` };
53551
54154
  const taskPath = resolveTaskFilePath(phrenPath, project);
53552
- const items = parseTaskItems(taskPath ?? path92.join(projectDir, "tasks.md"));
54155
+ const items = parseTaskItems(taskPath ?? path94.join(projectDir, "tasks.md"));
53553
54156
  return resolveTaskItemMatch(items, match);
53554
54157
  }
53555
54158
  function resolveAutoFindingTaskItem(phrenPath, project) {
53556
54159
  const projectDir = safeProjectPath(phrenPath, project);
53557
54160
  if (!projectDir) return void 0;
53558
54161
  const taskPath = resolveTaskFilePath(phrenPath, project);
53559
- const active = parseTaskItems(taskPath ?? path92.join(projectDir, "tasks.md")).filter(
54162
+ const active = parseTaskItems(taskPath ?? path94.join(projectDir, "tasks.md")).filter(
53560
54163
  (item) => item.section === "Active" && item.stableId
53561
54164
  );
53562
54165
  if (active.length === 1) return active[0].stableId;
@@ -53596,7 +54199,7 @@ function buildFindingCitation(citationInput, nowIso, inferredRepo, headCommit) {
53596
54199
  function resolveInferredCitationRepo(citationInput) {
53597
54200
  if (citationInput?.repo) return citationInput.repo;
53598
54201
  if (citationInput?.file) {
53599
- const fileDir = path93.dirname(citationInput.file);
54202
+ const fileDir = path95.dirname(citationInput.file);
53600
54203
  return getRepoRoot(fileDir);
53601
54204
  }
53602
54205
  return void 0;
@@ -53731,7 +54334,7 @@ function addFindingToFile(phrenPath, project, learning, citationInput, opts) {
53731
54334
  if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
53732
54335
  const resolvedDir = storeAwareProjectPath(phrenPath, project);
53733
54336
  if (!resolvedDir) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
53734
- const learningsPath = path93.join(resolvedDir, FINDINGS_FILENAME);
54337
+ const learningsPath = path95.join(resolvedDir, FINDINGS_FILENAME);
53735
54338
  const nowIso = (opts?.now ?? /* @__PURE__ */ new Date()).toISOString();
53736
54339
  const today = nowIso.slice(0, 10);
53737
54340
  const resolvedCitationInputResult = resolveFindingCitationInput(phrenPath, project, citationInput);
@@ -53913,7 +54516,7 @@ var codeNoteSchema = external_exports.object({
53913
54516
  // phone's spelling, accepted until 0.3.1.
53914
54517
  name: external_exports.string().min(1).max(4600).optional(),
53915
54518
  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("..")),
54519
+ file: external_exports.string().min(1).max(4096).refine((file3) => !path96.isAbsolute(file3) && !file3.includes("\0") && !file3.split(/[\\/]/).includes("..")),
53917
54520
  line: external_exports.number().int().positive(),
53918
54521
  text: external_exports.string().trim().min(1).max(4500).refine((text4) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text4)),
53919
54522
  target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(["codex", "claude", "opencode"]) }).strict()]).optional()
@@ -53967,26 +54570,26 @@ init_transcripts();
53967
54570
  import { execFile as execFile18 } from "node:child_process";
53968
54571
  import { promisify as promisify17 } from "node:util";
53969
54572
  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";
54573
+ import { readdir as readdir19, readFile as readFile46, stat as stat26, mkdir as mkdir25 } from "node:fs/promises";
53971
54574
  import { homedir as homedir19 } from "node:os";
53972
- import path99 from "node:path";
54575
+ import path101 from "node:path";
53973
54576
 
53974
54577
  // src/core/project.ts
53975
54578
  init_shared();
53976
- import * as path97 from "path";
54579
+ import * as path99 from "path";
53977
54580
 
53978
54581
  // src/core/project-registry.ts
53979
54582
  init_phren_paths();
53980
54583
  import * as fs33 from "fs";
53981
- import * as path96 from "path";
54584
+ import * as path98 from "path";
53982
54585
 
53983
54586
  // src/git-worktree.ts
53984
54587
  import * as fs32 from "fs";
53985
- import * as path95 from "path";
54588
+ import * as path97 from "path";
53986
54589
  var WORKTREE_CONTAINER_NAMES = /* @__PURE__ */ new Set(["worktrees", ".worktrees"]);
53987
- var LINKED_WORKTREE_SEGMENT = `${path95.sep}.git${path95.sep}worktrees${path95.sep}`;
54590
+ var LINKED_WORKTREE_SEGMENT = `${path97.sep}.git${path97.sep}worktrees${path97.sep}`;
53988
54591
  function resolveWorktreeParent(dir) {
53989
- const resolved = path95.resolve(dir);
54592
+ const resolved = path97.resolve(dir);
53990
54593
  const agentParent = parentFromAgentWorktreePath(resolved);
53991
54594
  if (agentParent) return { repoRoot: agentParent, reason: "agent-worktree-dir" };
53992
54595
  const linkedParent = parentFromLinkedWorktree(resolved);
@@ -53994,23 +54597,23 @@ function resolveWorktreeParent(dir) {
53994
54597
  return null;
53995
54598
  }
53996
54599
  function parentFromAgentWorktreePath(resolved) {
53997
- const segments = resolved.split(path95.sep);
54600
+ const segments = resolved.split(path97.sep);
53998
54601
  for (let i = 1; i < segments.length; i++) {
53999
54602
  if (!WORKTREE_CONTAINER_NAMES.has(segments[i])) continue;
54000
54603
  let j = i - 1;
54001
54604
  if (!segments[j]?.startsWith(".")) continue;
54002
54605
  while (j >= 1 && segments[j].startsWith(".")) j--;
54003
54606
  if (j < 1) continue;
54004
- return segments.slice(0, j + 1).join(path95.sep) || path95.sep;
54607
+ return segments.slice(0, j + 1).join(path97.sep) || path97.sep;
54005
54608
  }
54006
54609
  return null;
54007
54610
  }
54008
54611
  function parentFromLinkedWorktree(resolved) {
54009
54612
  let current2 = resolved;
54010
54613
  while (true) {
54011
- const parent = repoRootFromGitFile(path95.join(current2, ".git"));
54614
+ const parent = repoRootFromGitFile(path97.join(current2, ".git"));
54012
54615
  if (parent) return parent;
54013
- const next = path95.dirname(current2);
54616
+ const next = path97.dirname(current2);
54014
54617
  if (next === current2) return null;
54015
54618
  current2 = next;
54016
54619
  }
@@ -54025,7 +54628,7 @@ function repoRootFromGitFile(gitPath) {
54025
54628
  }
54026
54629
  const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
54027
54630
  if (!match) return null;
54028
- const gitDir = path95.resolve(path95.dirname(gitPath), match[1].replace(/[/\\]/g, path95.sep));
54631
+ const gitDir = path97.resolve(path97.dirname(gitPath), match[1].replace(/[/\\]/g, path97.sep));
54029
54632
  const idx = gitDir.indexOf(LINKED_WORKTREE_SEGMENT);
54030
54633
  if (idx === -1) return null;
54031
54634
  return gitDir.slice(0, idx);
@@ -54238,7 +54841,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
54238
54841
  return topics;
54239
54842
  }
54240
54843
  function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
54241
- const resolvedRoot = path96.resolve(repoRoot);
54844
+ const resolvedRoot = path98.resolve(repoRoot);
54242
54845
  if (!fs33.existsSync(resolvedRoot)) return null;
54243
54846
  const signal = {
54244
54847
  domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
@@ -54249,7 +54852,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
54249
54852
  usefulSignals: 0
54250
54853
  };
54251
54854
  const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
54252
- const packageJsonPath = path96.join(resolvedRoot, "package.json");
54855
+ const packageJsonPath = path98.join(resolvedRoot, "package.json");
54253
54856
  if (fs33.existsSync(packageJsonPath)) {
54254
54857
  signal.usefulSignals++;
54255
54858
  addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
@@ -54279,33 +54882,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
54279
54882
  debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
54280
54883
  }
54281
54884
  }
54282
- const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs33.existsSync(path96.join(resolvedRoot, fileName)));
54885
+ const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs33.existsSync(path98.join(resolvedRoot, fileName)));
54283
54886
  for (const configName of topLevelConfigs) {
54284
54887
  signal.usefulSignals++;
54285
54888
  const configScore = DOMAIN_CONFIG_HINTS[configName];
54286
54889
  if (configScore) addDomainScores(signal.domainScores, configScore);
54287
54890
  }
54288
54891
  const readmeCandidates = [
54289
- path96.join(resolvedRoot, "README.md"),
54290
- path96.join(resolvedRoot, "readme.md")
54892
+ path98.join(resolvedRoot, "README.md"),
54893
+ path98.join(resolvedRoot, "readme.md")
54291
54894
  ];
54292
54895
  for (const readmePath of readmeCandidates) {
54293
54896
  if (!fs33.existsSync(readmePath)) continue;
54294
54897
  const content = maybeReadUtf8(readmePath);
54295
54898
  if (!content) continue;
54296
54899
  signal.usefulSignals++;
54297
- signal.referenceHints.push(path96.relative(resolvedRoot, readmePath));
54900
+ signal.referenceHints.push(path98.relative(resolvedRoot, readmePath));
54298
54901
  addTermCount(signal.terms, content, 2);
54299
54902
  signal.docsText += ` ${content.toLowerCase()}`;
54300
54903
  break;
54301
54904
  }
54302
- const docsDir = path96.join(resolvedRoot, "docs");
54905
+ const docsDir = path98.join(resolvedRoot, "docs");
54303
54906
  if (fs33.existsSync(docsDir) && fs33.statSync(docsDir).isDirectory()) {
54304
54907
  signal.referenceHints.push("docs/");
54305
54908
  for (const entry2 of fs33.readdirSync(docsDir, { withFileTypes: true })) {
54306
54909
  if (!entry2.isFile()) continue;
54307
54910
  if (!/\.(md|txt|rst)$/i.test(entry2.name)) continue;
54308
- const docsContent = maybeReadUtf8(path96.join(docsDir, entry2.name));
54911
+ const docsContent = maybeReadUtf8(path98.join(docsDir, entry2.name));
54309
54912
  if (!docsContent) continue;
54310
54913
  signal.usefulSignals++;
54311
54914
  addTermCount(signal.terms, docsContent, 1);
@@ -54313,7 +54916,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
54313
54916
  }
54314
54917
  }
54315
54918
  for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
54316
- const fullPath = path96.join(resolvedRoot, folderName);
54919
+ const fullPath = path98.join(resolvedRoot, folderName);
54317
54920
  if (fs33.existsSync(fullPath)) {
54318
54921
  signal.referenceHints.push(`${folderName}/`);
54319
54922
  }
@@ -54324,14 +54927,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
54324
54927
  if (scannedFiles >= maxFiles) return;
54325
54928
  for (const entry2 of fs33.readdirSync(dir, { withFileTypes: true })) {
54326
54929
  if (scannedFiles >= maxFiles) return;
54327
- const fullPath = path96.join(dir, entry2.name);
54930
+ const fullPath = path98.join(dir, entry2.name);
54328
54931
  if (entry2.isDirectory()) {
54329
54932
  if (skipDirs.has(entry2.name)) continue;
54330
54933
  walk(fullPath);
54331
54934
  continue;
54332
54935
  }
54333
54936
  scannedFiles++;
54334
- const ext = path96.extname(entry2.name).toLowerCase();
54937
+ const ext = path98.extname(entry2.name).toLowerCase();
54335
54938
  if (!ext) continue;
54336
54939
  const extScore = EXTENSION_DOMAIN_HINTS[ext];
54337
54940
  if (extScore) {
@@ -54505,7 +55108,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
54505
55108
  return null;
54506
55109
  }
54507
55110
  };
54508
- const resolvedSource = path96.resolve(sourceRoot);
55111
+ const resolvedSource = path98.resolve(sourceRoot);
54509
55112
  for (const project of candidates) {
54510
55113
  if (sourceOf(project) === resolvedSource) return project;
54511
55114
  }
@@ -54519,7 +55122,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
54519
55122
  function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
54520
55123
  const profile = typeof opts === "string" ? opts : opts.profile;
54521
55124
  const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
54522
- const resolvedPath = path96.resolve(projectPath);
55125
+ const resolvedPath = path98.resolve(projectPath);
54523
55126
  if (!fs33.existsSync(resolvedPath)) {
54524
55127
  throw new Error(`Path does not exist: ${resolvedPath}`);
54525
55128
  }
@@ -54530,17 +55133,17 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
54530
55133
  if (worktreeRepoRoot) {
54531
55134
  debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
54532
55135
  }
54533
- const sourceRoot = isProjectLocal ? path96.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
55136
+ const sourceRoot = isProjectLocal ? path98.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
54534
55137
  if (isProjectLocal) {
54535
- const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path96.sep);
55138
+ const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path98.sep);
54536
55139
  if (!matchesWorkspace) {
54537
55140
  throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
54538
55141
  }
54539
55142
  }
54540
55143
  let claudeMdPath = null;
54541
55144
  const candidates = [
54542
- path96.join(sourceRoot, "AGENTS.md"),
54543
- path96.join(sourceRoot, ".claude", "CLAUDE.md")
55145
+ path98.join(sourceRoot, "AGENTS.md"),
55146
+ path98.join(sourceRoot, ".claude", "CLAUDE.md")
54544
55147
  ];
54545
55148
  for (const c of candidates) {
54546
55149
  if (fs33.existsSync(c)) {
@@ -54560,12 +55163,12 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
54560
55163
  `Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
54561
55164
  );
54562
55165
  }
54563
- const projDir = path96.join(phrenPath, projectName2);
55166
+ const projDir = path98.join(phrenPath, projectName2);
54564
55167
  fs33.mkdirSync(projDir, { recursive: true });
54565
55168
  const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
54566
55169
  const existingConfig = readProjectConfig(phrenPath, projectName2);
54567
55170
  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");
55171
+ const claudePath = path98.join(projDir, "AGENTS.md");
54569
55172
  if (ownership !== "repo-managed") {
54570
55173
  if (claudeContent) {
54571
55174
  if (!fs33.existsSync(claudePath)) {
@@ -54600,7 +55203,7 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
54600
55203
  }
54601
55204
  }
54602
55205
  const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
54603
- const summaryPath = path96.join(projDir, "summary.md");
55206
+ const summaryPath = path98.join(projDir, "summary.md");
54604
55207
  if (!fs33.existsSync(summaryPath)) {
54605
55208
  atomicWriteText(
54606
55209
  summaryPath,
@@ -54613,18 +55216,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
54613
55216
  `
54614
55217
  );
54615
55218
  }
54616
- if (!fs33.existsSync(path96.join(projDir, FINDINGS_FILENAME))) {
55219
+ if (!fs33.existsSync(path98.join(projDir, FINDINGS_FILENAME))) {
54617
55220
  atomicWriteText(
54618
- path96.join(projDir, FINDINGS_FILENAME),
55221
+ path98.join(projDir, FINDINGS_FILENAME),
54619
55222
  `# ${projectName2} FINDINGS
54620
55223
 
54621
55224
  <!-- Bootstrapped from ${sourceRoot} -->
54622
55225
  `
54623
55226
  );
54624
55227
  }
54625
- if (moduleEnabled(phrenPath, "tasks") && !fs33.existsSync(path96.join(projDir, TASKS_FILENAME))) {
55228
+ if (moduleEnabled(phrenPath, "tasks") && !fs33.existsSync(path98.join(projDir, TASKS_FILENAME))) {
54626
55229
  atomicWriteText(
54627
- path96.join(projDir, TASKS_FILENAME),
55230
+ path98.join(projDir, TASKS_FILENAME),
54628
55231
  `# ${projectName2} tasks
54629
55232
 
54630
55233
  ## Active
@@ -54635,11 +55238,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
54635
55238
  `
54636
55239
  );
54637
55240
  }
54638
- if (!fs33.existsSync(path96.join(projDir, "topic-config.json"))) {
55241
+ if (!fs33.existsSync(path98.join(projDir, "topic-config.json"))) {
54639
55242
  const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
54640
55243
  const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
54641
55244
  atomicWriteText(
54642
- path96.join(projDir, "topic-config.json"),
55245
+ path98.join(projDir, "topic-config.json"),
54643
55246
  JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
54644
55247
  );
54645
55248
  }
@@ -54671,10 +55274,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
54671
55274
  if (!activeProfile.ok) return activeProfile;
54672
55275
  const writePhrenPath = options.writeToPath ?? phrenPath;
54673
55276
  const manifest = readRootManifest(phrenPath);
54674
- const resolvedPath = path97.resolve(targetPath);
55277
+ const resolvedPath = path99.resolve(targetPath);
54675
55278
  if (manifest?.installMode === "project-local") {
54676
- const workspaceRoot = path97.resolve(manifest.workspaceRoot || "");
54677
- const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path97.sep);
55279
+ const workspaceRoot = path99.resolve(manifest.workspaceRoot || "");
55280
+ const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path99.sep);
54678
55281
  if (!matchesWorkspace) {
54679
55282
  return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
54680
55283
  }
@@ -54692,9 +55295,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
54692
55295
  ownership: added.ownership,
54693
55296
  files: {
54694
55297
  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)
55298
+ summary: path99.join(writePhrenPath, added.project, "summary.md"),
55299
+ findings: path99.join(writePhrenPath, added.project, FINDINGS_FILENAME),
55300
+ task: path99.join(writePhrenPath, added.project, TASKS_FILENAME)
54698
55301
  }
54699
55302
  });
54700
55303
  }
@@ -54720,7 +55323,7 @@ import { execFileSync as execFileSync6, spawnSync as spawnSync2 } from "child_pr
54720
55323
  import * as crypto10 from "crypto";
54721
55324
  import * as fs34 from "fs";
54722
55325
  import * as os3 from "os";
54723
- import * as path98 from "path";
55326
+ import * as path100 from "path";
54724
55327
 
54725
55328
  // src/content/summarize.ts
54726
55329
  init_phren_dotenv();
@@ -54881,7 +55484,7 @@ function mergeTasksByBid(base, ours, theirs) {
54881
55484
  // src/sync/conflict-resolve.ts
54882
55485
  function conflictStrategy(relFile) {
54883
55486
  const file3 = relFile.replace(/\\/g, "/");
54884
- const name = path98.posix.basename(file3).toLowerCase();
55487
+ const name = path100.posix.basename(file3).toLowerCase();
54885
55488
  if (isTaskFileName(name)) return "tasks";
54886
55489
  if (name === "findings.md") return "findings";
54887
55490
  if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file3)) return "archive";
@@ -54916,9 +55519,9 @@ function splitBlock(content, start, end) {
54916
55519
  function mergeText(base, ours, theirs) {
54917
55520
  if (ours === theirs || ours === base) return theirs;
54918
55521
  if (theirs === base) return ours;
54919
- const dir = fs34.mkdtempSync(path98.join(os3.tmpdir(), "phren-merge-"));
55522
+ const dir = fs34.mkdtempSync(path100.join(os3.tmpdir(), "phren-merge-"));
54920
55523
  try {
54921
- const [o, b, t] = ["ours", "base", "theirs"].map((name) => path98.join(dir, name));
55524
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path100.join(dir, name));
54922
55525
  fs34.writeFileSync(o, ours);
54923
55526
  fs34.writeFileSync(b, base);
54924
55527
  fs34.writeFileSync(t, theirs);
@@ -54931,9 +55534,9 @@ function mergeText(base, ours, theirs) {
54931
55534
  function unionText(base, ours, theirs) {
54932
55535
  const clean2 = mergeText(base, ours, theirs);
54933
55536
  if (clean2 !== null) return clean2;
54934
- const dir = fs34.mkdtempSync(path98.join(os3.tmpdir(), "phren-merge-"));
55537
+ const dir = fs34.mkdtempSync(path100.join(os3.tmpdir(), "phren-merge-"));
54935
55538
  try {
54936
- const [o, b, t] = ["ours", "base", "theirs"].map((name) => path98.join(dir, name));
55539
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path100.join(dir, name));
54937
55540
  fs34.writeFileSync(o, ours);
54938
55541
  fs34.writeFileSync(b, base);
54939
55542
  fs34.writeFileSync(t, theirs);
@@ -54993,7 +55596,7 @@ function resolveStoreConflicts(cwd) {
54993
55596
  const base = stage(cwd, 1, relFile) ?? "";
54994
55597
  const ours = stage(cwd, 2, relFile);
54995
55598
  const theirs = stage(cwd, 3, relFile);
54996
- const fullPath = path98.join(cwd, relFile);
55599
+ const fullPath = path100.join(cwd, relFile);
54997
55600
  if (ours === null && theirs === null) {
54998
55601
  unresolved.push(relFile);
54999
55602
  continue;
@@ -55004,7 +55607,7 @@ function resolveStoreConflicts(cwd) {
55004
55607
  continue;
55005
55608
  }
55006
55609
  const tmp = `${fullPath}.tmp-${crypto10.randomUUID()}`;
55007
- fs34.mkdirSync(path98.dirname(fullPath), { recursive: true });
55610
+ fs34.mkdirSync(path100.dirname(fullPath), { recursive: true });
55008
55611
  fs34.writeFileSync(tmp, merged);
55009
55612
  fs34.renameSync(tmp, fullPath);
55010
55613
  git4(cwd, ["add", "--", relFile]);
@@ -55284,7 +55887,7 @@ function repoName(url2) {
55284
55887
  }
55285
55888
  async function isRepository(directory) {
55286
55889
  try {
55287
- await stat26(path99.join(directory, ".git"));
55890
+ await stat26(path101.join(directory, ".git"));
55288
55891
  return true;
55289
55892
  } catch {
55290
55893
  return false;
@@ -55304,7 +55907,7 @@ async function registeredSources(env) {
55304
55907
  const source = readProjectConfig(store, project).sourcePath;
55305
55908
  if (typeof source === "string" && source) {
55306
55909
  try {
55307
- paths.add(realpathSync5.native(path99.resolve(source)));
55910
+ paths.add(realpathSync5.native(path101.resolve(source)));
55308
55911
  } catch {
55309
55912
  }
55310
55913
  }
@@ -55316,7 +55919,7 @@ async function candidateRepos(activity, env = process.env) {
55316
55919
  const found = [];
55317
55920
  const seen = /* @__PURE__ */ new Set();
55318
55921
  const offer = async (directory, source, lastSeen) => {
55319
- let dir = path99.resolve(directory);
55922
+ let dir = path101.resolve(directory);
55320
55923
  try {
55321
55924
  if (!(await stat26(dir)).isDirectory()) return;
55322
55925
  dir = realpathSync5.native(dir);
@@ -55331,7 +55934,7 @@ async function candidateRepos(activity, env = process.env) {
55331
55934
  const toplevel = async (directory) => {
55332
55935
  let existing = directory;
55333
55936
  while (!await stat26(existing).catch(() => void 0)) {
55334
- const parent = path99.dirname(existing);
55937
+ const parent = path101.dirname(existing);
55335
55938
  if (parent === existing) return void 0;
55336
55939
  existing = parent;
55337
55940
  }
@@ -55344,25 +55947,25 @@ async function candidateRepos(activity, env = process.env) {
55344
55947
  };
55345
55948
  for (const event of [...activity].reverse()) {
55346
55949
  const directory = typeof event.directory === "string" ? event.directory : void 0;
55347
- if (!directory || !path99.isAbsolute(directory)) continue;
55950
+ if (!directory || !path101.isAbsolute(directory)) continue;
55348
55951
  const root = await toplevel(directory);
55349
55952
  if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
55350
55953
  }
55351
55954
  try {
55352
- const session = JSON.parse(await readFile45(path99.join(herdrRoot(), "session.json"), "utf8"));
55955
+ const session = JSON.parse(await readFile46(path101.join(herdrRoot(), "session.json"), "utf8"));
55353
55956
  for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
55354
55957
  const directory = JSON.parse(`"${match[1]}"`);
55355
- if (!path99.isAbsolute(directory)) continue;
55958
+ if (!path101.isAbsolute(directory)) continue;
55356
55959
  const root = await toplevel(directory);
55357
55960
  if (root) await offer(root, "herdr");
55358
55961
  }
55359
55962
  } catch {
55360
55963
  }
55361
55964
  const home = homedir19();
55362
- for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path99.join(home, r))]) {
55965
+ for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path101.join(home, r))]) {
55363
55966
  let children = [];
55364
55967
  try {
55365
- children = (await readdir19(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path99.join(root, e.name));
55968
+ children = (await readdir19(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path101.join(root, e.name));
55366
55969
  } catch {
55367
55970
  continue;
55368
55971
  }
@@ -55372,14 +55975,14 @@ async function candidateRepos(activity, env = process.env) {
55372
55975
  }
55373
55976
  async function cloneRoot(env) {
55374
55977
  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))]) {
55978
+ for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path101.join(home, r))]) {
55376
55979
  try {
55377
55980
  if ((await stat26(root)).isDirectory()) return root;
55378
55981
  } catch {
55379
55982
  }
55380
55983
  }
55381
- const fallback2 = path99.join(home, "Projects");
55382
- await mkdir24(fallback2, { recursive: true });
55984
+ const fallback2 = path101.join(home, "Projects");
55985
+ await mkdir25(fallback2, { recursive: true });
55383
55986
  return fallback2;
55384
55987
  }
55385
55988
  async function publishStore(store, project) {
@@ -55400,7 +56003,7 @@ async function publishStore(store, project) {
55400
56003
  async function enrollProject(input2, env = process.env) {
55401
56004
  const store = phrenStoreRoot(env);
55402
56005
  try {
55403
- if (!(await stat26(path99.join(store, ".config"))).isDirectory()) throw new Error();
56006
+ if (!(await stat26(path101.join(store, ".config"))).isDirectory()) throw new Error();
55404
56007
  } catch {
55405
56008
  throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
55406
56009
  }
@@ -55411,7 +56014,7 @@ async function enrollProject(input2, env = process.env) {
55411
56014
  if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
55412
56015
  const name = repoName(url2);
55413
56016
  if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
55414
- directory = path99.join(await cloneRoot(env), name);
56017
+ directory = path101.join(await cloneRoot(env), name);
55415
56018
  try {
55416
56019
  await stat26(directory);
55417
56020
  throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
@@ -55428,7 +56031,7 @@ async function enrollProject(input2, env = process.env) {
55428
56031
  cloned = true;
55429
56032
  } else if (typeof input2.directory === "string" && input2.directory) {
55430
56033
  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.");
56034
+ if (raw.length > 4096 || raw.includes("\0") || !path101.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
55432
56035
  try {
55433
56036
  directory = realpathSync5.native(raw);
55434
56037
  if (!(await stat26(directory)).isDirectory()) throw new Error();
@@ -55444,33 +56047,33 @@ async function enrollProject(input2, env = process.env) {
55444
56047
  // src/bridge/files.ts
55445
56048
  init_protocol();
55446
56049
  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";
56050
+ import { lstat as lstat28, open as open21, readdir as readdir20, realpath as realpath16 } from "node:fs/promises";
56051
+ import path102 from "node:path";
55449
56052
  var MAX_BYTES = 2097152;
55450
56053
  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")) {
56054
+ if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path102.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
55452
56055
  throw new BridgeError(400, "Invalid repository path.");
55453
56056
  }
55454
56057
  const base = await realpath16(root);
55455
56058
  let file3 = base;
55456
56059
  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.");
56060
+ file3 = path102.join(file3, part);
56061
+ if ((await lstat28(file3)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
55459
56062
  }
55460
56063
  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);
56064
+ if (resolved !== base && !resolved.startsWith(base + path102.sep)) throw new BridgeError(403, "The path is outside this repository.");
56065
+ const metadata = await lstat28(resolved);
55463
56066
  if (metadata.isDirectory()) {
55464
56067
  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
56068
  return {
55466
56069
  path: relative3,
55467
56070
  kind: "directory",
55468
56071
  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" }))
56072
+ entries: entries2.slice(0, 500).map((entry2) => ({ name: entry2.name, path: path102.posix.join(relative3, entry2.name), kind: entry2.isDirectory() ? "directory" : "file" }))
55470
56073
  };
55471
56074
  }
55472
56075
  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);
56076
+ const handle = await open21(resolved, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
55474
56077
  try {
55475
56078
  const current2 = await handle.stat();
55476
56079
  if (!current2.isFile() || current2.ino !== metadata.ino || current2.dev !== metadata.dev) throw new BridgeError(409, "The file changed. Refresh and try again.");
@@ -55492,8 +56095,8 @@ async function browseFiles(root, relative3) {
55492
56095
  // src/bridge/file-range.ts
55493
56096
  init_protocol();
55494
56097
  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";
56098
+ import { lstat as lstat29, open as open22, realpath as realpath17 } from "node:fs/promises";
56099
+ import path103 from "node:path";
55497
56100
  var MAX_FILE_RANGE = 4 * 1024 * 1024;
55498
56101
  var types = {
55499
56102
  mp4: "video/mp4",
@@ -55530,7 +56133,7 @@ var types = {
55530
56133
  xml: "text/xml"
55531
56134
  };
55532
56135
  function fileContentType(file3) {
55533
- const ext = path101.extname(file3).slice(1).toLowerCase();
56136
+ const ext = path103.extname(file3).slice(1).toLowerCase();
55534
56137
  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
56138
  }
55536
56139
  function version2(stat29) {
@@ -55548,18 +56151,18 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
55548
56151
  }
55549
56152
  try {
55550
56153
  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.");
56154
+ const relative3 = path103.isAbsolute(requested) ? path103.relative(base, requested) : requested;
56155
+ if (relative3 === ".." || relative3.startsWith(`..${path103.sep}`) || path103.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
55553
56156
  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.");
56157
+ for (const part of relative3.split(path103.sep).filter((part2) => part2 && part2 !== ".")) {
56158
+ file3 = path103.join(file3, part);
56159
+ if ((await lstat29(file3)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
55557
56160
  }
55558
56161
  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);
56162
+ if (!resolved.startsWith(base + path103.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
56163
+ const metadata = await lstat29(resolved);
55561
56164
  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);
56165
+ const handle = await open22(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
55563
56166
  try {
55564
56167
  const current2 = await handle.stat();
55565
56168
  if (!current2.isFile() || version2(current2) !== version2(metadata) || await realpath17(file3) !== resolved) {
@@ -55600,8 +56203,8 @@ init_zod();
55600
56203
  init_protocol();
55601
56204
  import { execFile as execFile19 } from "node:child_process";
55602
56205
  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";
56206
+ 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";
56207
+ import path104 from "node:path";
55605
56208
  import { promisify as promisify18 } from "node:util";
55606
56209
  var exec18 = promisify18(execFile19);
55607
56210
  var SHA = /^[0-9a-f]{40}$/;
@@ -55629,14 +56232,14 @@ function blobSha(content) {
55629
56232
  return createHash26("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
55630
56233
  }
55631
56234
  async function isRepository2(store) {
55632
- return await lstat29(path102.join(store, ".git")).catch(() => void 0) !== void 0;
56235
+ return await lstat30(path104.join(store, ".git")).catch(() => void 0) !== void 0;
55633
56236
  }
55634
- function storeHead(store, indexFile = path102.join(bridgeRoot(), "store-snapshot.index")) {
56237
+ function storeHead(store, indexFile = path104.join(bridgeRoot(), "store-snapshot.index")) {
55635
56238
  return serialized2(async () => {
55636
56239
  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 });
56240
+ await mkdir26(path104.dirname(indexFile), { recursive: true, mode: 448 });
55638
56241
  const env = { GIT_INDEX_FILE: indexFile };
55639
- if (!await lstat29(indexFile).catch(() => void 0)) {
56242
+ if (!await lstat30(indexFile).catch(() => void 0)) {
55640
56243
  const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
55641
56244
  await git5(store, head.trim() ? ["read-tree", "HEAD"] : ["read-tree", "--empty"], env);
55642
56245
  }
@@ -55661,27 +56264,27 @@ async function storeBlob(store, sha) {
55661
56264
  return { sha, encoding: "base64", content: stdout.toString("base64") };
55662
56265
  }
55663
56266
  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)) {
56267
+ const normalized = path104.posix.normalize(relative3);
56268
+ 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
56269
  throw new BridgeError(400, "Invalid store path.");
55667
56270
  }
55668
56271
  const root = await realpath18(store);
55669
- let parent = path102.dirname(path102.join(root, normalized));
56272
+ let parent = path104.dirname(path104.join(root, normalized));
55670
56273
  for (; ; ) {
55671
56274
  const real2 = await realpath18(parent).catch(() => void 0);
55672
56275
  if (real2) {
55673
- if (real2 !== root && !real2.startsWith(root + path102.sep)) throw new BridgeError(400, "Invalid store path.");
56276
+ if (real2 !== root && !real2.startsWith(root + path104.sep)) throw new BridgeError(400, "Invalid store path.");
55674
56277
  break;
55675
56278
  }
55676
- parent = path102.dirname(parent);
56279
+ parent = path104.dirname(parent);
55677
56280
  }
55678
- const file3 = path102.join(root, normalized);
55679
- const info = await lstat29(file3).catch(() => void 0);
56281
+ const file3 = path104.join(root, normalized);
56282
+ const info = await lstat30(file3).catch(() => void 0);
55680
56283
  if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
55681
56284
  return file3;
55682
56285
  }
55683
56286
  async function currentSha(file3) {
55684
- const content = await readFile46(file3).catch((error62) => {
56287
+ const content = await readFile47(file3).catch((error62) => {
55685
56288
  if (error62.code === "ENOENT") return null;
55686
56289
  throw error62;
55687
56290
  });
@@ -55696,10 +56299,10 @@ function putStoreFile(store, data) {
55696
56299
  return serialized2(async () => {
55697
56300
  const file3 = await storeFile(store, input2.path);
55698
56301
  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 });
56302
+ await mkdir26(path104.dirname(file3), { recursive: true });
55700
56303
  const temporary = `${file3}.phren-${process.pid}-${Date.now()}`;
55701
- await writeFile9(temporary, content, { flag: "wx" });
55702
- await rename8(temporary, file3);
56304
+ await writeFile10(temporary, content, { flag: "wx" });
56305
+ await rename9(temporary, file3);
55703
56306
  return { content: { sha: blobSha(content), path: input2.path }, commit: { sha: blobSha(content) } };
55704
56307
  });
55705
56308
  }
@@ -55730,10 +56333,10 @@ init_protocol();
55730
56333
  // src/bridge/simulators.ts
55731
56334
  init_protocol();
55732
56335
  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";
56336
+ 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
56337
  import { tmpdir as tmpdir4 } from "node:os";
55735
- import path103 from "node:path";
55736
- import { createHash as createHash27, randomUUID as randomUUID24 } from "node:crypto";
56338
+ import path105 from "node:path";
56339
+ import { createHash as createHash27, randomUUID as randomUUID25 } from "node:crypto";
55737
56340
  import { promisify as promisify19 } from "node:util";
55738
56341
  var exec19 = promisify19(execFile20);
55739
56342
  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 +56363,15 @@ async function bootedSimulators() {
55760
56363
  async function simulatorScreenshot(udid) {
55761
56364
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
55762
56365
  if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
55763
- const file3 = path103.join(tmpdir4(), `phren-sim-${randomUUID24()}.png`);
56366
+ const file3 = path105.join(tmpdir4(), `phren-sim-${randomUUID25()}.png`);
55764
56367
  try {
55765
56368
  await exec19("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file3], { timeout: 15e3 });
55766
- return await readFile47(file3);
56369
+ return await readFile48(file3);
55767
56370
  } catch (error62) {
55768
56371
  if (error62 instanceof BridgeError) throw error62;
55769
56372
  throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
55770
56373
  } finally {
55771
- await unlink8(file3).catch(() => void 0);
56374
+ await unlink9(file3).catch(() => void 0);
55772
56375
  }
55773
56376
  }
55774
56377
  var building;
@@ -55779,27 +56382,27 @@ function helper() {
55779
56382
  return building;
55780
56383
  }
55781
56384
  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");
56385
+ const dir = path105.join(bridgeRoot(), "native");
56386
+ const binary = path105.join(dir, "simtap");
56387
+ 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
56388
  const digest2 = createHash27("sha256").update(code).digest("hex");
55786
- const saved = await readFile47(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
56389
+ const saved = await readFile48(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
55787
56390
  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";
56391
+ await mkdir27(dir, { recursive: true, mode: 448 });
56392
+ const temporary = path105.join(dir, `simtap.${randomUUID25()}`), source = temporary + ".swift";
55790
56393
  const sidecar = temporary + ".sha256";
55791
56394
  try {
55792
- await writeFile10(source, code, { mode: 384, flag: "wx" });
56395
+ await writeFile11(source, code, { mode: 384, flag: "wx" });
55793
56396
  await exec19("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
55794
56397
  throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
55795
56398
  });
55796
56399
  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");
56400
+ const binarySha = createHash27("sha256").update(await readFile48(temporary)).digest("hex");
56401
+ await writeFile11(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
56402
+ await rename10(temporary, binary);
56403
+ await rename10(sidecar, binary + ".sha256");
55801
56404
  } finally {
55802
- await Promise.all([source, temporary, sidecar].map((file3) => unlink8(file3).catch(() => void 0)));
56405
+ await Promise.all([source, temporary, sidecar].map((file3) => unlink9(file3).catch(() => void 0)));
55803
56406
  }
55804
56407
  return binary;
55805
56408
  }
@@ -55812,8 +56415,8 @@ function simtap(name, ...args) {
55812
56415
  }
55813
56416
  async function executeSimtap(name, ...args) {
55814
56417
  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");
56418
+ const saved = await readFile48(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
56419
+ const binarySha = createHash27("sha256").update(await readFile48(binary)).digest("hex");
55817
56420
  if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
55818
56421
  try {
55819
56422
  await exec19(binary, [name, ...args], { timeout: 6e4 });
@@ -55899,7 +56502,7 @@ init_transcripts();
55899
56502
  init_transcript_index();
55900
56503
  init_transcripts();
55901
56504
  import { homedir as homedir20, tmpdir as tmpdir5 } from "node:os";
55902
- import path104 from "node:path";
56505
+ import path106 from "node:path";
55903
56506
  init_protocol();
55904
56507
  var cache = /* @__PURE__ */ new Map();
55905
56508
  var modelCache = /* @__PURE__ */ new Map();
@@ -56037,7 +56640,7 @@ function describe3(tool, args) {
56037
56640
  return "";
56038
56641
  };
56039
56642
  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";
56643
+ const base = (v) => path106.basename(v.split(" \xB7 ")[0].trim()) || "file";
56041
56644
  const name = tool.toLowerCase();
56042
56645
  let value2;
56043
56646
  if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
@@ -56076,8 +56679,8 @@ init_home_paths();
56076
56679
  init_terminal_text();
56077
56680
  init_codex_servers();
56078
56681
  init_herdr();
56079
- import { open as open22 } from "node:fs/promises";
56080
- import path105 from "node:path";
56682
+ import { open as open23 } from "node:fs/promises";
56683
+ import path107 from "node:path";
56081
56684
  init_protocol();
56082
56685
  init_terminal();
56083
56686
  init_terminal_choice();
@@ -56108,7 +56711,7 @@ function lastIndexedName(text4, thread) {
56108
56711
  return void 0;
56109
56712
  }
56110
56713
  async function tail(file3) {
56111
- const handle = await open22(file3, "r").catch(() => void 0);
56714
+ const handle = await open23(file3, "r").catch(() => void 0);
56112
56715
  if (!handle) return void 0;
56113
56716
  try {
56114
56717
  const { size } = await handle.stat();
@@ -56138,7 +56741,7 @@ var defaultRenameDeps = {
56138
56741
  return text4 === void 0 ? void 0 : lastCustomTitle(text4);
56139
56742
  },
56140
56743
  async codexIndexTitle(thread) {
56141
- const text4 = await tail(path105.join(codexHome(), "session_index.jsonl"));
56744
+ const text4 = await tail(path107.join(codexHome(), "session_index.jsonl"));
56142
56745
  return text4 === void 0 ? void 0 : lastIndexedName(text4, thread);
56143
56746
  },
56144
56747
  sleep: (ms) => new Promise((resolve11) => setTimeout(resolve11, ms)),
@@ -56224,8 +56827,8 @@ async function renameSession(server, data, deps2 = defaultRenameDeps) {
56224
56827
  }
56225
56828
 
56226
56829
  // src/bridge/server-launch.ts
56227
- import { mkdir as mkdir28, readFile as readFile48 } from "node:fs/promises";
56228
- import path107 from "node:path";
56830
+ import { mkdir as mkdir29, readFile as readFile49 } from "node:fs/promises";
56831
+ import path109 from "node:path";
56229
56832
  init_zod();
56230
56833
  init_home_paths();
56231
56834
  init_herdr();
@@ -56238,8 +56841,8 @@ init_zod();
56238
56841
  init_utils_helpers();
56239
56842
  init_metrics();
56240
56843
  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";
56844
+ import { mkdir as mkdir28, realpath as realpath19, rm as rm14, stat as stat28 } from "node:fs/promises";
56845
+ import path108 from "node:path";
56243
56846
  import { promisify as promisify20 } from "node:util";
56244
56847
  init_protocol();
56245
56848
  var exec20 = promisify20(execFile21);
@@ -56268,11 +56871,11 @@ async function createLaunchWorktree(cwd, request9) {
56268
56871
  if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
56269
56872
  throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
56270
56873
  }
56271
- const worktree = path106.join(root, ".claude", "worktrees", worktreeFolderName(branch));
56874
+ const worktree = path108.join(root, ".claude", "worktrees", worktreeFolderName(branch));
56272
56875
  if (await stat28(worktree).then(() => true, () => false)) {
56273
56876
  throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
56274
56877
  }
56275
- await mkdir27(path106.dirname(worktree), { recursive: true });
56878
+ await mkdir28(path108.dirname(worktree), { recursive: true });
56276
56879
  try {
56277
56880
  await git6(root, "worktree", "add", "-b", branch, worktree, head);
56278
56881
  } catch (error62) {
@@ -56280,8 +56883,8 @@ async function createLaunchWorktree(cwd, request9) {
56280
56883
  throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
56281
56884
  }
56282
56885
  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;
56886
+ const inside = path108.relative(root, await realpath19(cwd));
56887
+ const start = inside && !inside.startsWith("..") ? path108.join(abs, inside) : abs;
56285
56888
  const startDir = await stat28(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
56286
56889
  return {
56287
56890
  cwd: startDir,
@@ -56309,12 +56912,12 @@ async function conductorBrief() {
56309
56912
  let source;
56310
56913
  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
56914
  else {
56312
- const here = path107.dirname(fileURLToPath(import.meta.url));
56915
+ const here = path109.dirname(fileURLToPath(import.meta.url));
56313
56916
  for (const candidate of [
56314
- path107.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
56315
- path107.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
56917
+ path109.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
56918
+ path109.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
56316
56919
  ]) {
56317
- source = await readFile48(candidate, "utf8").catch(() => void 0);
56920
+ source = await readFile49(candidate, "utf8").catch(() => void 0);
56318
56921
  if (source !== void 0) break;
56319
56922
  }
56320
56923
  }
@@ -56332,15 +56935,15 @@ function effortArgs(kind, effort) {
56332
56935
  }
56333
56936
  async function prepareConductor(kind, effort, model) {
56334
56937
  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");
56938
+ const briefDirectory2 = path109.join(bridgeRoot(), "conductor");
56939
+ await mkdir29(briefDirectory2, { recursive: true, mode: 448 });
56940
+ const briefFile = path109.join(briefDirectory2, "brief.md");
56941
+ if (await readFile49(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
56339
56942
  if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
56340
56943
  if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
56341
56944
  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");
56945
+ const directory = path109.join(process.env.XDG_CONFIG_HOME || path109.join(homeDir(), ".config"), "opencode", "agents");
56946
+ const file3 = path109.join(directory, "conductor.md");
56344
56947
  const definition = `---
56345
56948
  description: Coordinate the owner's work across agent sessions.
56346
56949
  mode: primary
@@ -56348,8 +56951,8 @@ mode: primary
56348
56951
 
56349
56952
  ${brief}
56350
56953
  `;
56351
- await mkdir28(directory, { recursive: true, mode: 448 });
56352
- if (await readFile48(file3, "utf8").catch(() => void 0) !== definition) await atomic(file3, definition, 420);
56954
+ await mkdir29(directory, { recursive: true, mode: 448 });
56955
+ if (await readFile49(file3, "utf8").catch(() => void 0) !== definition) await atomic(file3, definition, 420);
56353
56956
  return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
56354
56957
  }
56355
56958
  throw new BridgeError(400, "The selected harness cannot run as a conductor.");
@@ -56444,7 +57047,7 @@ async function requireAvailable(kind, account) {
56444
57047
  }
56445
57048
  async function launchSession(server, data, options = {}) {
56446
57049
  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);
57050
+ const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path109.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
56448
57051
  const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
56449
57052
  if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
56450
57053
  const label2 = plainText(200).parse(data.label);
@@ -56587,6 +57190,15 @@ async function launchSession(server, data, options = {}) {
56587
57190
  );
56588
57191
  const chat = !sessionId2 && pane && pane.agent === kind ? await paneChatState(server, pane).catch(() => ({})) : {};
56589
57192
  const target = sessionId2 ? { ...binding, session: sessionId2 } : chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : void 0;
57193
+ if (brief && role === "agent") {
57194
+ await new JobRegistry().register({
57195
+ pane: { server, pane: created.paneId, ...created.workspaceId ? { workspace: created.workspaceId } : {}, agent: kind, label: label2 },
57196
+ ...sessionId2 ? { session: sessionId2 } : {},
57197
+ agent: kind,
57198
+ label: label2,
57199
+ command: kind
57200
+ }).catch(() => void 0);
57201
+ }
56590
57202
  return {
56591
57203
  ok: true,
56592
57204
  ...created,
@@ -56617,7 +57229,7 @@ async function workspaceAction(server, operation, data) {
56617
57229
  if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
56618
57230
  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
57231
  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);
57232
+ 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
57233
  if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
56622
57234
  else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
56623
57235
  else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
@@ -56717,11 +57329,12 @@ init_zod();
56717
57329
  init_protocol();
56718
57330
  import { once } from "node:events";
56719
57331
  var SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
56720
- var SPEECH_FORMATS = ["pcm_44100", "mp3_44100_192", "pcm_24000"];
57332
+ var SPEECH_FORMATS = ["pcm_44100", "mp3_44100_192", "mp3_44100_128", "pcm_24000"];
56721
57333
  var BASE_FORMAT = "pcm_24000";
56722
57334
  var SPEECH_FORMAT_INFO = {
56723
57335
  pcm_44100: { audio: "pcm_s16le;rate=44100;channels=1", sampleRate: 44100, contentType: "application/octet-stream" },
56724
57336
  mp3_44100_192: { audio: "mp3;rate=44100;bitrate=192000;channels=1", sampleRate: 44100, contentType: "audio/mpeg" },
57337
+ mp3_44100_128: { audio: "mp3;rate=44100;bitrate=128000;channels=1", sampleRate: 44100, contentType: "audio/mpeg" },
56725
57338
  pcm_24000: { audio: SPEECH_AUDIO, sampleRate: 24e3, contentType: "application/octet-stream" }
56726
57339
  };
56727
57340
  var SPEECH_SLOW_MS = 1500;
@@ -56953,9 +57566,7 @@ async function childActivity(source, session) {
56953
57566
  const key3 = `${source}\0${session}`, now = Date.now(), cached3 = childActivityCache.get(key3);
56954
57567
  if (cached3 && now - cached3.at < CHILD_ACTIVITY_CACHE_MS) return cached3.result;
56955
57568
  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");
57569
+ const running2 = runningChildAgents(tree);
56959
57570
  return { runningChildren: running2.length, childProviders: [...new Set(running2.map((child) => child.provider))].sort() };
56960
57571
  }).catch(() => ({ runningChildren: 0, childProviders: [] }));
56961
57572
  childActivityCache.set(key3, { at: now, result });
@@ -57307,7 +57918,7 @@ function createRouteHandler(ctx) {
57307
57918
  case "/v1/files/range": {
57308
57919
  let root;
57309
57920
  if (url2.searchParams.get("scope") === "uploads") {
57310
- root = path108.join(bridgeRoot(), "uploads");
57921
+ root = path110.join(bridgeRoot(), "uploads");
57311
57922
  } else if (url2.searchParams.has("session")) {
57312
57923
  const target = targetFromURL(url2), pane = await validateTarget(target);
57313
57924
  const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
@@ -57531,6 +58142,8 @@ function createRouteHandler(ctx) {
57531
58142
  } : void 0);
57532
58143
  } else if (url2.pathname === "/v1/sessions/rename") {
57533
58144
  result = await renameSession(selectedServer(url2), data);
58145
+ } else if (url2.pathname === "/v1/jobs/cleanup") {
58146
+ result = { ok: true, ...await ctx.resources.cleanupJobs() };
57534
58147
  } else if (url2.pathname === "/v1/schedules") {
57535
58148
  result = await scheduler.statuses();
57536
58149
  } else if (url2.pathname === "/v1/schedules/run") {
@@ -57569,7 +58182,7 @@ function createRouteHandler(ctx) {
57569
58182
  } else if (url2.pathname === "/v1/dispatch/returns") {
57570
58183
  result = { returns: await ctx.returns.take() };
57571
58184
  } 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);
58185
+ 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
58186
  await ctx.returns.answerApproval(body2.id, body2.decision, body2.actionId, body2.origin);
57574
58187
  result = { ok: true };
57575
58188
  } else if (url2.pathname === "/v1/conductor/grants") {
@@ -57674,7 +58287,7 @@ init_protocol();
57674
58287
  // src/bridge/transcript-preview.ts
57675
58288
  init_codex_threads();
57676
58289
  import { constants as constants6 } from "node:fs";
57677
- import { open as open23 } from "node:fs/promises";
58290
+ import { open as open24 } from "node:fs/promises";
57678
58291
  init_protocol();
57679
58292
  init_transcript_index();
57680
58293
  init_terminal_text();
@@ -57904,7 +58517,7 @@ async function readDeltaPreview(target, file3, rollout) {
57904
58517
  if (target.source === "codex") return await codexThreadPreview(target.session) ?? (file3 && rollout ? await rollout.read(file3).catch(() => null) : null);
57905
58518
  if (target.source !== "opencode" || !file3) return null;
57906
58519
  try {
57907
- const handle = await open23(file3 + ".preview.json", constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
58520
+ const handle = await open24(file3 + ".preview.json", constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
57908
58521
  let bytes;
57909
58522
  try {
57910
58523
  const stat29 = await handle.stat();
@@ -58015,7 +58628,7 @@ var TranscriptPreviewStream = class {
58015
58628
  }
58016
58629
  }
58017
58630
  async update(status, file3, now) {
58018
- const readAt = now ?? Date.now();
58631
+ const readAt2 = now ?? Date.now();
58019
58632
  let next = null;
58020
58633
  if (status === "working") {
58021
58634
  this.wasWorking = true;
@@ -58026,8 +58639,8 @@ var TranscriptPreviewStream = class {
58026
58639
  if (text4 && [...this.codexCompleted].some((completed2) => completed2.startsWith(text4))) next = null;
58027
58640
  }
58028
58641
  } 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;
58642
+ if (readAt2 - this.lastRead < PREVIEW_INTERVAL_MS) return void 0;
58643
+ this.lastRead = readAt2;
58031
58644
  const pane = await this.pane();
58032
58645
  const text4 = this.landed ? "" : claudePanePreview(
58033
58646
  pane,
@@ -58041,8 +58654,8 @@ var TranscriptPreviewStream = class {
58041
58654
  }
58042
58655
  if (text4) next = { turnStartedAt: this.startedAt, text: text4 };
58043
58656
  } 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;
58657
+ if (readAt2 - this.lastRead < PREVIEW_INTERVAL_MS) return void 0;
58658
+ this.lastRead = readAt2;
58046
58659
  const thinking = copilotThinking(await this.pane());
58047
58660
  if (thinking) {
58048
58661
  this.activity = thinking;
@@ -58114,6 +58727,7 @@ function transcriptStreams(ctx) {
58114
58727
  let busy = false, ready = false, first = true;
58115
58728
  let awaitingTranscript = false, lastTranscriptLookup = 0;
58116
58729
  let initialPane;
58730
+ let busyAt = 0;
58117
58731
  const pending = [];
58118
58732
  const stop = () => {
58119
58733
  abort.abort();
@@ -58182,7 +58796,10 @@ function transcriptStreams(ctx) {
58182
58796
  choice: { title: queued.title, options: queued.options }
58183
58797
  } : void 0).catch(() => void 0) : void 0);
58184
58798
  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 };
58799
+ const { settings, settingsState, suggestion, permissionMode, permissionModes: permissionModes2 } = settingsSwitcher ? await settingsSwitcher.streamSettings(target, pane.terminal_id, codexServed) : { settings: settingsCapabilities(target.source, codexServed), settingsState: void 0, suggestion: void 0, permissionMode: void 0, permissionModes: void 0 };
58800
+ const between = ["idle", "done"].includes(String(pane.agent_status)) && !pendingApproval && !servedQuestion;
58801
+ if (!between) busyAt = Date.now();
58802
+ const nextPrompt = between && suggestion && suggestion.readAt > busyAt ? suggestion.text : void 0;
58186
58803
  const historyHealth = target.source === "codex" ? await threadHealth(target.session, pane.agent_status) : { stalled: false };
58187
58804
  send(client, { agentStatus: {
58188
58805
  source: target.source,
@@ -58193,6 +58810,10 @@ function transcriptStreams(ctx) {
58193
58810
  terminalPrompt,
58194
58811
  ...waiting && agentHooks.passwordPrompt(target) ? { passwordPrompt: true } : {},
58195
58812
  compacting: agentHooks.compacting(target),
58813
+ ...nextPrompt ? { suggestion: nextPrompt } : {},
58814
+ // The mode Claude's footer shows and the cycle its picker offers,
58815
+ // only from a confident read (a Claude pane's readable footer).
58816
+ ...permissionMode ? { permissionMode, permissionModes: permissionModes2 } : {},
58196
58817
  ...historyHealth.stalled ? { historyStalled: true, historyStalledSince: historyHealth.since } : {},
58197
58818
  modules: info.modules,
58198
58819
  store: info.store,
@@ -58384,12 +59005,12 @@ init_codex_servers();
58384
59005
  init_home_paths();
58385
59006
  init_logger();
58386
59007
  init_protocol();
58387
- import { readFile as readFile49 } from "node:fs/promises";
58388
- import path109 from "node:path";
59008
+ import { readFile as readFile50 } from "node:fs/promises";
59009
+ import path111 from "node:path";
58389
59010
  var REFRESH_AFTER_MS = 6 * 864e5;
58390
- async function lastCodexRefresh(file3 = path109.join(codexHome(), "auth.json")) {
59011
+ async function lastCodexRefresh(file3 = path111.join(codexHome(), "auth.json")) {
58391
59012
  try {
58392
- const auth = object2(JSON.parse(await readFile49(file3, "utf8")));
59013
+ const auth = object2(JSON.parse(await readFile50(file3, "utf8")));
58393
59014
  if (!object2(auth.tokens).refresh_token) return void 0;
58394
59015
  const at = Date.parse(String(auth.last_refresh ?? ""));
58395
59016
  return Number.isFinite(at) ? at : 0;
@@ -58440,15 +59061,15 @@ async function serve(version3, options = {}) {
58440
59061
  if (!modules.has("hook")) throw new BridgeError(404, disabledHint("hook"));
58441
59062
  const activeCapabilities = capabilitiesForModules(modules);
58442
59063
  const root = bridgeRoot();
58443
- await mkdir29(root, { recursive: true, mode: 448 });
59064
+ await mkdir30(root, { recursive: true, mode: 448 });
58444
59065
  await chmod6(root, 448);
58445
59066
  let computerID2;
58446
- const identityFile = path110.join(root, "computer-id");
59067
+ const identityFile = path112.join(root, "computer-id");
58447
59068
  try {
58448
- computerID2 = (await readFile50(identityFile, "utf8")).trim();
59069
+ computerID2 = (await readFile51(identityFile, "utf8")).trim();
58449
59070
  } catch {
58450
- computerID2 = randomUUID25();
58451
- await writeFile11(identityFile, computerID2, { flag: "wx", mode: 384 });
59071
+ computerID2 = randomUUID26();
59072
+ await writeFile12(identityFile, computerID2, { flag: "wx", mode: 384 });
58452
59073
  }
58453
59074
  const launches = new LaunchLimiter();
58454
59075
  const dispatches = modules.has("conductor") ? new DispatchService({
@@ -58525,12 +59146,13 @@ async function serve(version3, options = {}) {
58525
59146
  const modelCatalog = options.modelCatalog ?? new ModelCatalog();
58526
59147
  const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
58527
59148
  const settingsSwitcher = new SettingsSwitcher(agentHooks);
59149
+ const permissionModeSwitcher = new PermissionModeSwitcher(agentHooks);
58528
59150
  const sideQuestions = new SideQuestions();
58529
59151
  const handOffs = dispatches ? new HandOffQueue({
58530
59152
  validate: (target) => validateTarget(target, false, true),
58531
59153
  notify: (target, text4, deliveryId, computer) => handOff({ computer, target, text: text4, deliveryId }, { notifySender: false }),
58532
59154
  send: async (target, text4, deliveryId, typing) => await paneRouteOnce(
58533
- { agentHooks, modelSwitcher, settingsSwitcher, codexQuestions, sideQuestions },
59155
+ { agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions },
58534
59156
  new URL("http://phren.local/v1/prompt"),
58535
59157
  { target, text: text4, deliveryId, hookQueued: true },
58536
59158
  {},
@@ -58562,7 +59184,7 @@ async function serve(version3, options = {}) {
58562
59184
  if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
58563
59185
  function gatewayTiming() {
58564
59186
  try {
58565
- const parsed = JSON.parse(readFileSync36(path110.join(root, "gateway.json"), "utf8"));
59187
+ const parsed = JSON.parse(readFileSync37(path112.join(root, "gateway.json"), "utf8"));
58566
59188
  if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
58567
59189
  } catch {
58568
59190
  }
@@ -58591,7 +59213,7 @@ async function serve(version3, options = {}) {
58591
59213
  launch: (server, data) => launches.run(() => launchSession(server, data, { canary: true })),
58592
59214
  scheduler
58593
59215
  });
58594
- const old = await lstat30(socketPath()).catch(() => null);
59216
+ const old = await lstat31(socketPath()).catch(() => null);
58595
59217
  if (old) {
58596
59218
  if (!old.isSocket() || process.getuid && old.uid !== process.getuid()) throw new Error("Refusing to replace an unexpected hook socket.");
58597
59219
  const { connect: connect4 } = await import("node:net");
@@ -58604,11 +59226,11 @@ async function serve(version3, options = {}) {
58604
59226
  s.on("error", () => resolve11(false));
58605
59227
  });
58606
59228
  if (live) throw new Error("Phren Hook is already running.");
58607
- await unlink9(socketPath());
59229
+ await unlink10(socketPath());
58608
59230
  }
58609
59231
  const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
58610
59232
  };
58611
- if (modules.has("git")) await rm15(path110.join(root, "changes-scratch"), { recursive: true, force: true });
59233
+ if (modules.has("git")) await rm15(path112.join(root, "changes-scratch"), { recursive: true, force: true });
58612
59234
  const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
58613
59235
  const { stream } = streams;
58614
59236
  const overview = overviewStream({
@@ -58633,6 +59255,7 @@ async function serve(version3, options = {}) {
58633
59255
  modelCatalog,
58634
59256
  modelSwitcher,
58635
59257
  settingsSwitcher,
59258
+ permissionModeSwitcher,
58636
59259
  sideQuestions,
58637
59260
  accountUsage,
58638
59261
  resources,
@@ -58777,7 +59400,7 @@ async function serve(version3, options = {}) {
58777
59400
  process.once("SIGTERM", stop);
58778
59401
  process.once("SIGINT", stop);
58779
59402
  });
58780
- await unlink9(socketPath()).catch(() => {
59403
+ await unlink10(socketPath()).catch(() => {
58781
59404
  });
58782
59405
  }
58783
59406
 
@@ -58789,9 +59412,9 @@ init_protocol();
58789
59412
  init_profile_store();
58790
59413
  init_phren_paths();
58791
59414
  import { execFile as execFile22 } from "node:child_process";
58792
- import { readFile as readFile51 } from "node:fs/promises";
59415
+ import { readFile as readFile52 } from "node:fs/promises";
58793
59416
  import { homedir as homedir21, hostname as hostname13, userInfo as userInfo5 } from "node:os";
58794
- import path111 from "node:path";
59417
+ import path113 from "node:path";
58795
59418
  import { promisify as promisify21 } from "node:util";
58796
59419
  init_protocol();
58797
59420
  var exec21 = promisify21(execFile22);
@@ -58838,11 +59461,11 @@ async function probe2(host) {
58838
59461
  return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
58839
59462
  }
58840
59463
  async function discoverComputers(options = {}) {
58841
- const config3 = options.sshConfig ?? await readFile51(path111.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
59464
+ const config3 = options.sshConfig ?? await readFile52(path113.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
58842
59465
  const store = options.store !== void 0 ? options.store : findPhrenPath();
58843
59466
  const machines = store ? listMachines(store) : void 0;
58844
59467
  const { peers } = await optionalHookPeers();
58845
- const own2 = (await readFile51(path111.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
59468
+ const own2 = (await readFile52(path113.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
58846
59469
  const known2 = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
58847
59470
  const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known2.has(computerLabel(host))).slice(0, 32);
58848
59471
  const [found, peerIds] = await Promise.all([
@@ -58864,7 +59487,7 @@ function slugName(value2) {
58864
59487
  async function linkComputer(host, options = {}) {
58865
59488
  const remote = await probe2(host);
58866
59489
  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();
59490
+ const own2 = (await readFile52(path113.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
58868
59491
  if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
58869
59492
  const name = computerName.parse(options.name ?? slugName(host));
58870
59493
  const as = computerName.parse(options.as ?? slugName(hostname13()));
@@ -58872,7 +59495,7 @@ async function linkComputer(host, options = {}) {
58872
59495
  if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
58873
59496
  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
59497
  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(" "));
59498
+ const localHostKey = publicComputerKey((await readFile52("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
58876
59499
  const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
58877
59500
  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
59501
  await acceptComputer(name, remoteLine);
@@ -58908,7 +59531,7 @@ async function runBridge(args, version3) {
58908
59531
  case "enroll-computer": {
58909
59532
  if (args.length === 2) console.log(await enrollComputer(args[1]));
58910
59533
  else if (args.length === 4 && args[2] === "--accept") {
58911
- await acceptComputer(args[1], await readFile52(args[3], "utf8"));
59534
+ await acceptComputer(args[1], await readFile53(args[3], "utf8"));
58912
59535
  console.log(`Enrolled ${args[1]} for Phren Hook.`);
58913
59536
  } else throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
58914
59537
  break;
@@ -59036,7 +59659,7 @@ async function runBridge(args, version3) {
59036
59659
  break;
59037
59660
  }
59038
59661
  const readModels = async (source) => {
59039
- const rows = JSON.parse(await readFile52(fixture, "utf8"));
59662
+ const rows = JSON.parse(await readFile53(fixture, "utf8"));
59040
59663
  return Array.isArray(rows[source]) ? rows[source] : [];
59041
59664
  };
59042
59665
  const emptyUsage = (source) => ({ source, windows: [] });
@@ -59144,7 +59767,7 @@ async function readSecret(prompt) {
59144
59767
  // src/bridge/hook-main.ts
59145
59768
  init_utils_helpers();
59146
59769
  Object.assign(process.env, nonInteractiveGitEnv());
59147
- runBridge(process.argv.slice(2), "0.3.16").then((code) => {
59770
+ runBridge(process.argv.slice(2), "0.3.18").then((code) => {
59148
59771
  process.exitCode = code;
59149
59772
  }).catch((error62) => {
59150
59773
  console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");