@phren/cli 0.3.6 → 0.3.8

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.
@@ -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, path84) {
272
- if (!path84)
271
+ function getElementAtPath(obj, path85) {
272
+ if (!path85)
273
273
  return obj;
274
- return path84.reduce((acc, key2) => acc?.[key2], obj);
274
+ return path85.reduce((acc, key2) => acc?.[key2], 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(path84, issues) {
533
+ function prefixIssues(path85, issues) {
534
534
  return issues.map((iss) => {
535
535
  var _a3;
536
536
  (_a3 = iss).path ?? (_a3.path = []);
537
- iss.path.unshift(path84);
537
+ iss.path.unshift(path85);
538
538
  return iss;
539
539
  });
540
540
  }
@@ -675,9 +675,9 @@ function hexToUint8Array(hex3) {
675
675
  function uint8ArrayToHex(bytes) {
676
676
  return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
677
677
  }
678
- function members(proto, table) {
679
- for (const key2 in table) {
680
- const desc = Object.getOwnPropertyDescriptor(table, key2);
678
+ function members(proto, table2) {
679
+ for (const key2 in table2) {
680
+ const desc = Object.getOwnPropertyDescriptor(table2, key2);
681
681
  if (desc.get)
682
682
  Object.defineProperty(proto, key2, { ...desc, enumerable: false });
683
683
  else
@@ -692,10 +692,10 @@ function hide(inst, key2, value2) {
692
692
  return own(inst, key2, value2, false);
693
693
  }
694
694
  // @__NO_SIDE_EFFECTS__
695
- function derived(computes, table) {
695
+ function derived(computes, table2) {
696
696
  for (const key2 in computes) {
697
697
  const compute = computes[key2];
698
- Object.defineProperty(table, key2, {
698
+ Object.defineProperty(table2, key2, {
699
699
  configurable: true,
700
700
  enumerable: true,
701
701
  get() {
@@ -706,7 +706,7 @@ function derived(computes, table) {
706
706
  }
707
707
  });
708
708
  }
709
- return table;
709
+ return table2;
710
710
  }
711
711
  function defineBound(proto, key2, fn) {
712
712
  Object.defineProperty(proto, key2, {
@@ -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, path84 = []) => {
1058
+ const processError = (error63, path85 = []) => {
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 }, [...path84, ...issue2.path]));
1061
+ issue2.errors.map((issues) => processError({ issues }, [...path85, ...issue2.path]));
1062
1062
  } else if (issue2.code === "invalid_key") {
1063
- processError({ issues: issue2.issues }, [...path84, ...issue2.path]);
1063
+ processError({ issues: issue2.issues }, [...path85, ...issue2.path]);
1064
1064
  } else if (issue2.code === "invalid_element") {
1065
- processError({ issues: issue2.issues }, [...path84, ...issue2.path]);
1065
+ processError({ issues: issue2.issues }, [...path85, ...issue2.path]);
1066
1066
  } else {
1067
- const fullpath = [...path84, ...issue2.path];
1067
+ const fullpath = [...path85, ...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, path84 = []) => {
1106
+ const processError = (error63, path85 = []) => {
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 }, [...path84, ...issue2.path]));
1110
+ issue2.errors.map((issues) => processError({ issues }, [...path85, ...issue2.path]));
1111
1111
  } else if (issue2.code === "invalid_key") {
1112
- processError({ issues: issue2.issues }, [...path84, ...issue2.path]);
1112
+ processError({ issues: issue2.issues }, [...path85, ...issue2.path]);
1113
1113
  } else if (issue2.code === "invalid_element") {
1114
- processError({ issues: issue2.issues }, [...path84, ...issue2.path]);
1114
+ processError({ issues: issue2.issues }, [...path85, ...issue2.path]);
1115
1115
  } else {
1116
- const fullpath = [...path84, ...issue2.path];
1116
+ const fullpath = [...path85, ...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 path84 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1156
- for (const seg of path84) {
1155
+ const path85 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1156
+ for (const seg of path85) {
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 path84 = ref.slice(1).split("/").filter(Boolean);
19153
- if (path84.length === 0) {
19152
+ const path85 = ref.slice(1).split("/").filter(Boolean);
19153
+ if (path85.length === 0) {
19154
19154
  return ctx.rootSchema;
19155
19155
  }
19156
19156
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
19157
- if (path84[0] === defsKey) {
19158
- const key2 = path84[1] === void 0 ? void 0 : decodeJSONPointerSegment(path84[1]);
19157
+ if (path85[0] === defsKey) {
19158
+ const key2 = path85[1] === void 0 ? void 0 : decodeJSONPointerSegment(path85[1]);
19159
19159
  if (!key2 || !ctx.defs[key2]) {
19160
19160
  throw new Error(`Reference not found: ${ref}`);
19161
19161
  }
@@ -21380,10 +21380,10 @@ async function repositoryOf(target, cwd, home = homeDir(), signal) {
21380
21380
  if (parent === existing) return void 0;
21381
21381
  existing = parent;
21382
21382
  }
21383
- const real = await realpath(existing);
21383
+ const real2 = await realpath(existing);
21384
21384
  home = await realpath(home);
21385
- if (real !== home && !real.startsWith(home + path5.sep)) return void 0;
21386
- const dir = (await stat2(real)).isDirectory() ? real : path5.dirname(real);
21385
+ if (real2 !== home && !real2.startsWith(home + path5.sep)) return void 0;
21386
+ const dir = (await stat2(real2)).isDirectory() ? real2 : path5.dirname(real2);
21387
21387
  try {
21388
21388
  return await realpath((await git(dir, ["rev-parse", "--show-toplevel"], {}, signal)).trim());
21389
21389
  } catch {
@@ -22137,9 +22137,9 @@ function resolveString(expression, source) {
22137
22137
  const declaration = new RegExp(`\\b(?:const|let|var)\\s+${identifier}\\s*=\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`)`).exec(source);
22138
22138
  return declaration ? unescapeJs(declaration[1].slice(1, -1)) : void 0;
22139
22139
  }
22140
- function callArguments(source, open16) {
22140
+ function callArguments(source, open17) {
22141
22141
  let depth = 0, quote3 = "";
22142
- for (let index2 = open16; index2 < source.length; index2++) {
22142
+ for (let index2 = open17; index2 < source.length; index2++) {
22143
22143
  const character = source[index2];
22144
22144
  if (quote3) {
22145
22145
  if (character === "\\") index2++;
@@ -22152,7 +22152,7 @@ function callArguments(source, open16) {
22152
22152
  }
22153
22153
  if (character === "(" || character === "{" || character === "[") depth++;
22154
22154
  else if (character === ")" || character === "}" || character === "]") {
22155
- if (--depth === 0) return source.slice(open16 + 1, index2);
22155
+ if (--depth === 0) return source.slice(open17 + 1, index2);
22156
22156
  }
22157
22157
  }
22158
22158
  return void 0;
@@ -22258,10 +22258,20 @@ var init_transcript_codex = __esm({
22258
22258
 
22259
22259
  // src/bridge/transcript-copilot.ts
22260
22260
  function visibleCopilotEvent(raw) {
22261
- if (raw.agentId || raw.ephemeral || !["user.message", "assistant.message", "assistant.message_delta", "tool.execution_start", "tool.execution_complete", "assistant.turn_start", "assistant.turn_end", "session.idle", "abort", "session.error", "session.usage_info", "assistant.usage"].includes(String(raw.type))) return void 0;
22261
+ if (raw.agentId || raw.ephemeral) return void 0;
22262
+ if (raw.type === "skill.invoked") {
22263
+ const data2 = object2(raw.data);
22264
+ if (typeof data2.name !== "string" || typeof data2.content !== "string") return void 0;
22265
+ return { type: raw.type, timestamp: raw.timestamp, data: {
22266
+ name: data2.name.slice(0, 200),
22267
+ content: data2.content.slice(0, 65536),
22268
+ ...typeof data2.description === "string" ? { description: data2.description.slice(0, 1e3) } : {}
22269
+ } };
22270
+ }
22271
+ if (!["user.message", "assistant.message", "assistant.message_delta", "tool.execution_start", "tool.execution_complete", "assistant.turn_start", "assistant.turn_end", "session.idle", "abort", "session.error", "session.usage_info", "assistant.usage"].includes(String(raw.type))) return void 0;
22262
22272
  const data = object2(raw.data);
22263
- const allowed = ["content", "source", "messageId", "deltaContent", "toolName", "toolCallId", "arguments", "result", "error", "success", "phase", "aborted", "inputTokens", "outputTokens", "cacheReadTokens"];
22264
- return { type: raw.type, timestamp: raw.timestamp, data: Object.fromEntries(Object.entries(data).filter(([key2]) => allowed.includes(key2))) };
22273
+ const allowed = ["content", "source", "messageId", "deltaContent", "toolName", "toolCallId", "arguments", "result", "error", "success", "phase", "aborted", "reasoningText", "mcpServerName", "mcpToolName", "inputTokens", "outputTokens", "cacheReadTokens"];
22274
+ return { type: raw.type, timestamp: raw.timestamp, data: Object.fromEntries(Object.entries(data).filter(([key2, value2]) => allowed.includes(key2) && (key2 !== "reasoningText" || raw.type === "assistant.message" && typeof value2 === "string") && (!["mcpServerName", "mcpToolName"].includes(key2) || typeof value2 === "string" && value2.length <= 200)).map(([key2, value2]) => [key2, key2 === "reasoningText" ? String(value2).slice(0, 8e3) : value2])) };
22265
22275
  }
22266
22276
  var init_transcript_copilot = __esm({
22267
22277
  "src/bridge/transcript-copilot.ts"() {
@@ -26468,8 +26478,8 @@ function appendAuditLog(phrenPath, event, details) {
26468
26478
  fs3.mkdirSync(path11.dirname(logPath), { recursive: true });
26469
26479
  withFileLock(logPath, () => {
26470
26480
  fs3.appendFileSync(logPath, line);
26471
- const stat26 = fs3.statSync(logPath);
26472
- if (stat26.size > 1e6) {
26481
+ const stat27 = fs3.statSync(logPath);
26482
+ if (stat27.size > 1e6) {
26473
26483
  const content = fs3.readFileSync(logPath, "utf8");
26474
26484
  const lines = content.split("\n");
26475
26485
  fs3.writeFileSync(logPath, lines.slice(-MAX_LOG_LINES).join("\n") + "\n");
@@ -26558,8 +26568,8 @@ ${Date.now()}`, { flag: "wx" });
26558
26568
  } catch (err) {
26559
26569
  logger.debug("acquireFileLock", `lockWrite: ${errorMessage(err)}`);
26560
26570
  try {
26561
- const stat26 = fs5.statSync(lockPath);
26562
- if (Date.now() - stat26.mtimeMs > staleThreshold) {
26571
+ const stat27 = fs5.statSync(lockPath);
26572
+ if (Date.now() - stat27.mtimeMs > staleThreshold) {
26563
26573
  let ownerAlive = false;
26564
26574
  try {
26565
26575
  const content = fs5.readFileSync(lockPath, "utf-8");
@@ -28307,7 +28317,7 @@ var init_package_metadata = __esm({
28307
28317
  __dirname = path24.dirname(fileURLToPath2(import.meta.url));
28308
28318
  ROOT = path24.join(__dirname, "..");
28309
28319
  PACKAGE_JSON_PATH = path24.join(ROOT, "package.json");
28310
- BUNDLED_VERSION = true ? "0.3.6" : "0.0.0";
28320
+ BUNDLED_VERSION = true ? "0.3.8" : "0.0.0";
28311
28321
  PACKAGE_JSON = readPackageJson();
28312
28322
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
28313
28323
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -31503,7 +31513,7 @@ var require_stream = __commonJS({
31503
31513
  };
31504
31514
  duplex._final = function(callback) {
31505
31515
  if (ws.readyState === ws.CONNECTING) {
31506
- ws.once("open", function open16() {
31516
+ ws.once("open", function open17() {
31507
31517
  duplex._final(callback);
31508
31518
  });
31509
31519
  return;
@@ -31524,7 +31534,7 @@ var require_stream = __commonJS({
31524
31534
  };
31525
31535
  duplex._write = function(chunk, encoding, callback) {
31526
31536
  if (ws.readyState === ws.CONNECTING) {
31527
- ws.once("open", function open16() {
31537
+ ws.once("open", function open17() {
31528
31538
  duplex._write(chunk, encoding, callback);
31529
31539
  });
31530
31540
  return;
@@ -32151,6 +32161,162 @@ var init_tab_activity = __esm({
32151
32161
  }
32152
32162
  });
32153
32163
 
32164
+ // src/bridge/codex-daemon.ts
32165
+ import { execFile as execFile3 } from "node:child_process";
32166
+ import { open as open5, readdir as readdir6, realpath as realpath6, stat as stat8 } from "node:fs/promises";
32167
+ import path32 from "node:path";
32168
+ import { promisify as promisify3 } from "node:util";
32169
+ function parseElapsed(text4) {
32170
+ const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(text4.trim());
32171
+ if (!match) return void 0;
32172
+ const [, days = "0", hours = "0", minutes, seconds] = match;
32173
+ return (((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds)) * 1e3;
32174
+ }
32175
+ function processTable(now = Date.now()) {
32176
+ if (table && now - table.at < CACHE_MS) return table.rows;
32177
+ countIdentity("ps");
32178
+ const rows = exec3("ps", ["-Aww", "-o", "pid=,ppid=,etime=,command="], { timeout: 3e3, maxBuffer: 8388608 }).then(({ stdout }) => {
32179
+ const out = [];
32180
+ for (const line of String(stdout).split("\n")) {
32181
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
32182
+ const elapsed = match ? parseElapsed(match[3]) : void 0;
32183
+ if (match && elapsed !== void 0) out.push({ pid: Number(match[1]), ppid: Number(match[2]), startedAt: now - elapsed, command: match[4].slice(0, 4096) });
32184
+ }
32185
+ return out;
32186
+ }, () => []);
32187
+ table = { at: now, rows };
32188
+ return rows;
32189
+ }
32190
+ function isCodexDaemon(command) {
32191
+ return DAEMON_COMMAND.test(command);
32192
+ }
32193
+ function startedAt(rows, pids) {
32194
+ const times = rows.filter((row) => pids.includes(row.pid)).map((row) => row.startedAt);
32195
+ return times.length ? Math.min(...times) : void 0;
32196
+ }
32197
+ async function underCodexDaemon(env = process.env, pid = process.pid) {
32198
+ if (env.CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED !== void 0) return true;
32199
+ if (process.platform === "win32") return false;
32200
+ const rows = await processTable(), byPid = new Map(rows.map((row) => [row.pid, row]));
32201
+ let current2 = byPid.get(pid)?.ppid ?? process.ppid;
32202
+ for (let depth = 0; depth < 8 && current2 > 1; depth++) {
32203
+ const row = byPid.get(current2);
32204
+ if (!row) return false;
32205
+ if (isCodexDaemon(row.command)) return true;
32206
+ current2 = row.ppid;
32207
+ }
32208
+ return false;
32209
+ }
32210
+ async function rolloutMeta(file2) {
32211
+ const handle = await open5(file2, "r").catch(() => void 0);
32212
+ if (!handle) return void 0;
32213
+ let text4;
32214
+ try {
32215
+ const { buffer, bytesRead } = await handle.read(Buffer.alloc(META_BYTES), 0, META_BYTES, 0);
32216
+ text4 = buffer.subarray(0, bytesRead).toString("utf8");
32217
+ } catch {
32218
+ return void 0;
32219
+ } finally {
32220
+ await handle.close();
32221
+ }
32222
+ const newline = text4.indexOf("\n");
32223
+ let payload;
32224
+ if (newline >= 0) {
32225
+ try {
32226
+ const raw = object2(JSON.parse(text4.slice(0, newline)));
32227
+ if (raw.type !== "session_meta") return void 0;
32228
+ payload = object2(raw.payload);
32229
+ } catch {
32230
+ }
32231
+ }
32232
+ if (!payload) {
32233
+ if (!text4.slice(0, 256).includes('"type":"session_meta"')) return void 0;
32234
+ payload = {};
32235
+ for (const key2 of ["id", "session_id", "timestamp", "cwd", "thread_source"]) {
32236
+ const match = new RegExp(`"${key2}":("(?:[^"\\\\]|\\\\.)*")`).exec(text4);
32237
+ if (match) try {
32238
+ payload[key2] = JSON.parse(match[1]);
32239
+ } catch {
32240
+ }
32241
+ }
32242
+ if (/"source":\{"subagent"/.test(text4)) payload.source = { subagent: true };
32243
+ }
32244
+ const id2 = String(payload.id ?? payload.session_id ?? ""), fromName = ROLLOUT.exec(file2)?.[1];
32245
+ const at = Date.parse(String(payload.timestamp ?? ""));
32246
+ if (!sessionId.safeParse(id2).success || fromName && fromName.toLowerCase() !== id2.toLowerCase() || typeof payload.cwd !== "string" || !path32.isAbsolute(payload.cwd) || !Number.isFinite(at)) return void 0;
32247
+ const subagent = !!object2(payload.source).subagent || typeof payload.thread_source === "string" && /sub.?agent/i.test(payload.thread_source);
32248
+ return { id: id2, cwd: payload.cwd, startedAt: at, subagent };
32249
+ }
32250
+ async function recentRollouts(now) {
32251
+ const files = [];
32252
+ for (const offset of [0, 1]) {
32253
+ const day = new Date(now - offset * 864e5);
32254
+ const folder = path32.join(codexHome(), "sessions", String(day.getFullYear()), String(day.getMonth() + 1).padStart(2, "0"), String(day.getDate()).padStart(2, "0"));
32255
+ const names = (await readdir6(folder).catch(() => [])).filter((name) => ROLLOUT.test(name)).sort().reverse();
32256
+ files.push(...names.slice(0, MAX_ROLLOUTS).map((name) => path32.join(folder, name)));
32257
+ }
32258
+ return files.slice(0, MAX_ROLLOUTS);
32259
+ }
32260
+ function daemonRollouts(openFiles, now = Date.now()) {
32261
+ if (rollouts && now - rollouts.at < CACHE_MS) return rollouts.value;
32262
+ const value2 = (async () => {
32263
+ const daemons = (await processTable(now)).filter((row) => isCodexDaemon(row.command)).map((row) => row.pid).slice(0, MAX_DAEMONS);
32264
+ if (!daemons.length) return [];
32265
+ countIdentity("codex-daemon");
32266
+ const held = (await openFiles(daemons).catch(() => [])).filter((file2) => ROLLOUT.test(file2)).slice(0, MAX_ROLLOUTS);
32267
+ const files = held.length ? held : await recentRollouts(now);
32268
+ const out = [];
32269
+ for (const file2 of files) {
32270
+ const meta3 = await rolloutMeta(file2);
32271
+ if (!meta3 || meta3.subagent) continue;
32272
+ const info = await stat8(file2).catch(() => void 0);
32273
+ out.push({ id: meta3.id, cwd: meta3.cwd, startedAt: meta3.startedAt, activeAt: info?.mtimeMs ?? meta3.startedAt, held: held.length > 0 });
32274
+ }
32275
+ return out;
32276
+ })().catch(() => []);
32277
+ rollouts = { at: now, value: value2 };
32278
+ return value2;
32279
+ }
32280
+ async function sameDirectory(a, b) {
32281
+ if (typeof a !== "string" || typeof b !== "string" || !path32.isAbsolute(a) || !path32.isAbsolute(b)) return false;
32282
+ return path32.resolve(a) === path32.resolve(b) || await real(a) === await real(b);
32283
+ }
32284
+ function assignDaemonConversation(here, self, claimed, rivals, now = Date.now()) {
32285
+ const open17 = here.filter((r) => !claimed.has(r.id) && r.startedAt <= now + 6e4);
32286
+ const after = (from) => open17.filter((r) => r.startedAt >= from - START_SLACK_MS);
32287
+ if (!rivals.length) {
32288
+ const pool = after(self.start);
32289
+ const held = pool.filter((r) => r.held);
32290
+ return (held.length ? held : pool).sort((a, b) => b.activeAt - a.activeAt)[0]?.id;
32291
+ }
32292
+ const order = [...rivals, self].sort((a, b) => b.start - a.start || (a.key < b.key ? 1 : a.key > b.key ? -1 : 0));
32293
+ const taken = /* @__PURE__ */ new Set();
32294
+ for (const pane of order) {
32295
+ const pick3 = after(pane.start).filter((r) => !taken.has(r.id)).sort((a, b) => a.startedAt - b.startedAt)[0];
32296
+ if (pane === self) return pick3?.id;
32297
+ if (pick3) taken.add(pick3.id);
32298
+ }
32299
+ return void 0;
32300
+ }
32301
+ var exec3, DAEMON_COMMAND, ROLLOUT, CACHE_MS, META_BYTES, MAX_ROLLOUTS, MAX_DAEMONS, START_SLACK_MS, table, rollouts, real;
32302
+ var init_codex_daemon = __esm({
32303
+ "src/bridge/codex-daemon.ts"() {
32304
+ "use strict";
32305
+ init_home_paths();
32306
+ init_metrics();
32307
+ init_protocol();
32308
+ exec3 = promisify3(execFile3);
32309
+ DAEMON_COMMAND = /(?:^|\/)codex\s+app-server(?:\s|$)/;
32310
+ ROLLOUT = /rollout-[^/]*-([a-f0-9-]{36})\.jsonl$/i;
32311
+ CACHE_MS = 2e3;
32312
+ META_BYTES = 65536;
32313
+ MAX_ROLLOUTS = 32;
32314
+ MAX_DAEMONS = 4;
32315
+ START_SLACK_MS = 5e3;
32316
+ real = async (dir) => realpath6(dir).catch(() => path32.resolve(dir));
32317
+ }
32318
+ });
32319
+
32154
32320
  // src/bridge/terminal-herdr.ts
32155
32321
  function herdrPanes(server, s) {
32156
32322
  return objects(s.panes).filter((p) => typeof p.pane_id === "string" && typeof p.tab_id === "string" && typeof p.workspace_id === "string").map((p) => {
@@ -32231,14 +32397,14 @@ var init_terminal_herdr = __esm({
32231
32397
  });
32232
32398
 
32233
32399
  // src/bridge/harness-status.ts
32234
- import { open as open5, stat as stat8 } from "node:fs/promises";
32400
+ import { open as open6, stat as stat9 } from "node:fs/promises";
32235
32401
  import { homedir as homedir7 } from "node:os";
32236
- import path32 from "node:path";
32402
+ import path33 from "node:path";
32237
32403
  async function opencodeProcessStatus(pids, root = phrenStoreRoot()) {
32238
- const folder = path32.join(root, ".runtime", "sessions");
32404
+ const folder = path33.join(root, ".runtime", "sessions");
32239
32405
  let current2, latest = -Infinity;
32240
32406
  for (const pid of pids.slice(0, 16)) {
32241
- const file2 = await open5(path32.join(folder, `opencode-status-${pid}.json`), "r").catch(() => void 0);
32407
+ const file2 = await open6(path33.join(folder, `opencode-status-${pid}.json`), "r").catch(() => void 0);
32242
32408
  if (!file2) continue;
32243
32409
  try {
32244
32410
  if ((await file2.stat()).size > 4096) continue;
@@ -32310,15 +32476,15 @@ function copilotStatusFromEvents(lines) {
32310
32476
  }
32311
32477
  return status;
32312
32478
  }
32313
- async function copilotProcessStatus(pids, home = process.env.COPILOT_HOME || path32.join(homedir7(), ".copilot")) {
32479
+ async function copilotProcessStatus(pids, home = process.env.COPILOT_HOME || path33.join(homedir7(), ".copilot")) {
32314
32480
  const session = await copilotForegroundSession(pids, home);
32315
32481
  if (!session) return void 0;
32316
- const file2 = path32.join(home, "session-state", session, "events.jsonl");
32317
- const info = await stat8(file2).catch(() => void 0);
32482
+ const file2 = path33.join(home, "session-state", session, "events.jsonl");
32483
+ const info = await stat9(file2).catch(() => void 0);
32318
32484
  if (!info?.isFile()) return void 0;
32319
32485
  const cached2 = copilotCache.get(file2);
32320
32486
  if (cached2 && cached2.size === info.size && cached2.mtime === info.mtimeMs) return cached2.status;
32321
- const handle = await open5(file2, "r");
32487
+ const handle = await open6(file2, "r");
32322
32488
  let text4;
32323
32489
  try {
32324
32490
  const length = Math.min(info.size, TAIL_BYTES);
@@ -32641,7 +32807,11 @@ function opencodePermissionDialog(ansi) {
32641
32807
  const row = plain2.findIndex((line, index2) => index2 > header2 && OPENCODE_OPTIONS.every((label2) => line.includes(label2)));
32642
32808
  if (row < 0 || row - header2 > 24) return void 0;
32643
32809
  const body2 = plain2.slice(header2 + 1, row).map(content).filter((line) => line.trim() && !/^\s{24,}/.test(line)).map((line) => line.trim());
32644
- const title = ["Permission required", ...body2].join("\n").slice(0, 4e3);
32810
+ const [asks, ...rest] = body2;
32811
+ const title = (asks?.replace(/^[←→]\s*/, "") || "Permission required").slice(0, 4e3);
32812
+ const patterns = rest.indexOf("Patterns");
32813
+ const details = patterns < 0 ? rest : [...rest.slice(0, patterns), ...rest.slice(patterns + 1).map((line) => line.replace(/^-\s+/, ""))];
32814
+ const detail = details.join("\n").slice(0, 4e3);
32645
32815
  const backgrounds = OPENCODE_OPTIONS.map((label2) => {
32646
32816
  const at = raw[row].indexOf(label2);
32647
32817
  if (at < 0) return void 0;
@@ -32652,6 +32822,7 @@ function opencodePermissionDialog(ansi) {
32652
32822
  const selected = unique.length === 1 && backgrounds.every((background) => background !== void 0) ? unique[0] : void 0;
32653
32823
  return { choice: {
32654
32824
  title,
32825
+ ...detail ? { body: detail } : {},
32655
32826
  options: [{ label: "Allow once", key: "1", hasKey: false }, { label: "Reject", key: "Escape", hasKey: true }],
32656
32827
  ...selected === 0 ? { highlightedIndex: 0 } : {}
32657
32828
  }, ...selected !== void 0 ? { selected } : {} };
@@ -32918,11 +33089,11 @@ __export(terminal_tmux_exports, {
32918
33089
  tmuxTerminal: () => tmuxTerminal,
32919
33090
  toTmuxId: () => toTmuxId
32920
33091
  });
32921
- import { execFile as execFile3 } from "node:child_process";
33092
+ import { execFile as execFile4 } from "node:child_process";
32922
33093
  import { accessSync, constants, existsSync as existsSync14, statSync as statSync9 } from "node:fs";
32923
- import { lstat as lstat5, readdir as readdir6 } from "node:fs/promises";
33094
+ import { lstat as lstat5, readdir as readdir7 } from "node:fs/promises";
32924
33095
  import { hostname as hostname4, userInfo } from "node:os";
32925
- import path33 from "node:path";
33096
+ import path34 from "node:path";
32926
33097
  function tmuxSocketName(server) {
32927
33098
  const match = /^tmux(?:-([A-Za-z0-9_][A-Za-z0-9_.-]{0,63}))?$/.exec(server);
32928
33099
  return match ? match[1] ?? "default" : void 0;
@@ -32934,11 +33105,11 @@ function tmuxServerName(socket) {
32934
33105
  function tmuxBinary() {
32935
33106
  if (process.env.PHREN_TMUX === "off") return void 0;
32936
33107
  if (cachedBinary && Date.now() - cachedBinary.at < 6e4) return cachedBinary.value;
32937
- const folders = [...(process.env.PATH ?? "").split(path33.delimiter), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/home/linuxbrew/.linuxbrew/bin"];
33108
+ const folders = [...(process.env.PATH ?? "").split(path34.delimiter), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/home/linuxbrew/.linuxbrew/bin"];
32938
33109
  let value2;
32939
33110
  for (const folder of folders) {
32940
- if (!folder || !path33.isAbsolute(folder)) continue;
32941
- const candidate = path33.join(folder, "tmux");
33111
+ if (!folder || !path34.isAbsolute(folder)) continue;
33112
+ const candidate = path34.join(folder, "tmux");
32942
33113
  try {
32943
33114
  if (statSync9(candidate).isFile()) {
32944
33115
  accessSync(candidate, constants.X_OK);
@@ -32965,8 +33136,8 @@ function tmuxError(stderr, error62) {
32965
33136
  function tmuxSocketFolders(env = process.env) {
32966
33137
  const uid = process.getuid?.();
32967
33138
  if (uid === void 0) return [];
32968
- const base = env.TMUX_TMPDIR && path33.isAbsolute(env.TMUX_TMPDIR) ? env.TMUX_TMPDIR : "/tmp";
32969
- return [.../* @__PURE__ */ new Set([path33.join(base, `tmux-${uid}`), path33.join("/tmp", `tmux-${uid}`)])];
33139
+ const base = env.TMUX_TMPDIR && path34.isAbsolute(env.TMUX_TMPDIR) ? env.TMUX_TMPDIR : "/tmp";
33140
+ return [.../* @__PURE__ */ new Set([path34.join(base, `tmux-${uid}`), path34.join("/tmp", `tmux-${uid}`)])];
32970
33141
  }
32971
33142
  function socketFlags(socket) {
32972
33143
  const file2 = socketPaths.get(socket);
@@ -32974,15 +33145,15 @@ function socketFlags(socket) {
32974
33145
  }
32975
33146
  async function tmuxSocketsIn(folder) {
32976
33147
  const uid = process.getuid?.(), primary = tmuxSocketFolders()[0];
32977
- const names = (await readdir6(folder).catch(() => [])).slice(0, 256);
33148
+ const names = (await readdir7(folder).catch(() => [])).slice(0, 256);
32978
33149
  const found = [];
32979
33150
  for (const name of names) {
32980
33151
  if (found.length >= 32) break;
32981
33152
  if (!tmuxServerName(name)) continue;
32982
- const info = await lstat5(path33.join(folder, name)).catch(() => void 0);
33153
+ const info = await lstat5(path34.join(folder, name)).catch(() => void 0);
32983
33154
  if (!info?.isSocket() || uid !== void 0 && info.uid !== uid) continue;
32984
33155
  found.push(name);
32985
- if (folder !== primary && !socketPaths.has(name) && !existsSync14(path33.join(primary ?? folder, name))) socketPaths.set(name, path33.join(folder, name));
33156
+ if (folder !== primary && !socketPaths.has(name) && !existsSync14(path34.join(primary ?? folder, name))) socketPaths.set(name, path34.join(folder, name));
32986
33157
  }
32987
33158
  return found;
32988
33159
  }
@@ -33009,7 +33180,7 @@ function toTmuxId(value2, kind) {
33009
33180
  }
33010
33181
  function agentFromCommand(command) {
33011
33182
  const words = command.trim().split(/\s+/).filter(Boolean).slice(0, 4);
33012
- const [first, second] = words, base = (word) => word ? path33.basename(word) : "";
33183
+ const [first, second] = words, base = (word) => word ? path34.basename(word) : "";
33013
33184
  const program = /^(node|nodejs|bun|deno)$/.test(base(first)) && second ? second : first;
33014
33185
  if (!program) return void 0;
33015
33186
  const name = base(program);
@@ -33157,14 +33328,14 @@ async function requireDirectExec() {
33157
33328
  if (!match || Number(match[1]) < 3) throw new BridgeError(409, "Phren needs tmux 3.0 or later to start agents. Update tmux on the computer.");
33158
33329
  }
33159
33330
  function loginShell() {
33160
- const shell = process.env.SHELL && path33.isAbsolute(process.env.SHELL) ? process.env.SHELL : (() => {
33331
+ const shell = process.env.SHELL && path34.isAbsolute(process.env.SHELL) ? process.env.SHELL : (() => {
33161
33332
  try {
33162
33333
  return userInfo().shell ?? "";
33163
33334
  } catch {
33164
33335
  return "";
33165
33336
  }
33166
33337
  })();
33167
- return shell && /^(sh|bash|zsh|ksh|dash)$/.test(path33.basename(shell)) && existsSync14(shell) ? shell : "/bin/sh";
33338
+ return shell && /^(sh|bash|zsh|ksh|dash)$/.test(path34.basename(shell)) && existsSync14(shell) ? shell : "/bin/sh";
33168
33339
  }
33169
33340
  function sessionName(label2, taken) {
33170
33341
  const base = (label2 ?? "phren").replace(/[.:\x00-\x1f\x7f]/g, "_").trim().slice(0, 60) || "phren";
@@ -33181,9 +33352,9 @@ async function ownerServers() {
33181
33352
  const running2 = await Promise.all(names.map((name) => tmuxTerminal.ping(name).then(() => true, () => false)));
33182
33353
  return names.filter((_, index2) => running2[index2]);
33183
33354
  }
33184
- async function tmuxServers() {
33355
+ async function tmuxServers(options = {}) {
33185
33356
  if (!deps.binary()) return [];
33186
- return [...await ownerServers(), TMUX_HIDDEN].map((name) => ({ id: `tmux:${name}`, kind: "herdr", terminal: "tmux", session: name, running: true }));
33357
+ return [...await ownerServers(), ...options.hidden ?? true ? [TMUX_HIDDEN] : []].map((name) => ({ id: `tmux:${name}`, kind: "herdr", terminal: "tmux", session: name, running: true }));
33187
33358
  }
33188
33359
  async function tmuxHealth() {
33189
33360
  if (process.env.PHREN_TMUX === "off") return { state: "off" };
@@ -33198,13 +33369,13 @@ async function tmuxHealth() {
33198
33369
  }
33199
33370
  async function tmuxPaneFromEnv(env = process.env) {
33200
33371
  const socket = env.TMUX?.split(",")[0], pane = env.TMUX_PANE;
33201
- if (!socket || !path33.isAbsolute(socket) || !pane || !fromTmuxId(pane)) return void 0;
33202
- const server = tmuxServerName(path33.basename(socket));
33372
+ if (!socket || !path34.isAbsolute(socket) || !pane || !fromTmuxId(pane)) return void 0;
33373
+ const server = tmuxServerName(path34.basename(socket));
33203
33374
  if (!server) return void 0;
33204
33375
  const primary = tmuxSocketFolders(env)[0];
33205
- if (primary && path33.dirname(socket) !== primary && !socketPaths.has(path33.basename(socket))) socketPaths.set(path33.basename(socket), socket);
33376
+ if (primary && path34.dirname(socket) !== primary && !socketPaths.has(path34.basename(socket))) socketPaths.set(path34.basename(socket), socket);
33206
33377
  try {
33207
- const [session, window2] = (await deps.run(path33.basename(socket), ["display-message", "-p", "-t", pane, "#{session_id} #{window_id}"], { timeoutMs: 1500 })).trim().split(" ");
33378
+ const [session, window2] = (await deps.run(path34.basename(socket), ["display-message", "-p", "-t", pane, "#{session_id} #{window_id}"], { timeoutMs: 1500 })).trim().split(" ");
33208
33379
  const workspace = fromTmuxId(session ?? ""), tab = fromTmuxId(window2 ?? "");
33209
33380
  return workspace && tab ? { server, workspace, tab, pane: fromTmuxId(pane) } : void 0;
33210
33381
  } catch {
@@ -33239,7 +33410,7 @@ var init_terminal_tmux = __esm({
33239
33410
  reject(new BridgeError(503, "tmux is not installed on this computer."));
33240
33411
  return;
33241
33412
  }
33242
- const child = execFile3(
33413
+ const child = execFile4(
33243
33414
  binary,
33244
33415
  [...socketFlags(socket), ...args],
33245
33416
  { timeout: options.timeoutMs ?? 5e3, maxBuffer: 4194304, env: tmuxEnvironment(), signal: options.signal },
@@ -33252,7 +33423,7 @@ var init_terminal_tmux = __esm({
33252
33423
  else child.stdin?.end();
33253
33424
  }),
33254
33425
  processes: () => new Promise((resolve11) => {
33255
- execFile3(
33426
+ execFile4(
33256
33427
  "ps",
33257
33428
  ["-A", "-o", "pid=,pgid=,tpgid=,tty=,args="],
33258
33429
  { timeout: 3e3, maxBuffer: 8388608, env: { ...process.env, LC_ALL: "C" } },
@@ -33265,7 +33436,7 @@ var init_terminal_tmux = __esm({
33265
33436
  resolve11("");
33266
33437
  return;
33267
33438
  }
33268
- execFile3(binary, ["-V"], { timeout: 3e3 }, (error62, stdout) => resolve11(error62 ? "" : String(stdout)));
33439
+ execFile4(binary, ["-V"], { timeout: 3e3 }, (error62, stdout) => resolve11(error62 ? "" : String(stdout)));
33269
33440
  }),
33270
33441
  sockets: async () => (await Promise.all(tmuxSocketFolders().map(tmuxSocketsIn))).flat(),
33271
33442
  sleep: (ms, signal) => new Promise((resolve11, reject) => {
@@ -33347,7 +33518,7 @@ var init_terminal_tmux = __esm({
33347
33518
  await tmux(server, ["send-keys", "-t", target, "Enter"], { signal });
33348
33519
  },
33349
33520
  async create(server, { workspace, label: label2, cwd }) {
33350
- const directory = cwd && path33.isAbsolute(cwd) ? ["-c", cwd] : [];
33521
+ const directory = cwd && path34.isAbsolute(cwd) ? ["-c", cwd] : [];
33351
33522
  const name = label2 ? ["-n", label2.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 100)] : [];
33352
33523
  if (workspace) {
33353
33524
  await tmux(server, ["new-window", "-d", "-t", `${toTmuxId(workspace, "s")}:`, ...directory, ...name]);
@@ -33497,6 +33668,7 @@ __export(herdr_exports, {
33497
33668
  opencodePidSession: () => opencodePidSession,
33498
33669
  paneAgentName: () => paneAgentName,
33499
33670
  paneChatState: () => paneChatState,
33671
+ paneForCodexSession: () => paneForCodexSession,
33500
33672
  paneIdentity: () => paneIdentity,
33501
33673
  panes: () => panes,
33502
33674
  recentServers: () => recentServers,
@@ -33512,26 +33684,26 @@ __export(herdr_exports, {
33512
33684
  workspaceSnapshot: () => workspaceSnapshot
33513
33685
  });
33514
33686
  import { createHmac, randomBytes as randomBytes2 } from "node:crypto";
33515
- import { execFile as execFile4 } from "node:child_process";
33687
+ import { execFile as execFile5 } from "node:child_process";
33516
33688
  import { connect } from "node:net";
33517
33689
  import { homedir as homedir8 } from "node:os";
33518
- import { open as open6, readdir as readdir7, readlink, realpath as realpath6, stat as stat9 } from "node:fs/promises";
33519
- import path34 from "node:path";
33520
- import { promisify as promisify3 } from "node:util";
33690
+ import { open as open7, readdir as readdir8, readlink, realpath as realpath7, stat as stat10 } from "node:fs/promises";
33691
+ import path35 from "node:path";
33692
+ import { promisify as promisify4 } from "node:util";
33521
33693
  function herdrRoot() {
33522
- return process.env.PHREN_HERDR_HOME || path34.join(homedir8(), ".config/herdr");
33694
+ return process.env.PHREN_HERDR_HOME || path35.join(homedir8(), ".config/herdr");
33523
33695
  }
33524
33696
  function herdrSocketPath(server) {
33525
33697
  return herdrSocket(server);
33526
33698
  }
33527
33699
  function herdrSocket(server) {
33528
33700
  serverName.parse(server);
33529
- return path34.join(herdrRoot(), ...server === "default" ? [] : ["sessions", server], "herdr.sock");
33701
+ return path35.join(herdrRoot(), ...server === "default" ? [] : ["sessions", server], "herdr.sock");
33530
33702
  }
33531
33703
  function herdrPaneFromEnv(env = process.env) {
33532
33704
  if (env.HERDR_ENV !== "1" || !env.HERDR_SOCKET_PATH) return void 0;
33533
- const socket = path34.resolve(env.HERDR_SOCKET_PATH), root = path34.resolve(herdrRoot());
33534
- const server = socket === path34.join(root, "herdr.sock") ? "default" : socket.startsWith(path34.join(root, "sessions") + path34.sep) ? path34.basename(path34.dirname(socket)) : void 0;
33705
+ const socket = path35.resolve(env.HERDR_SOCKET_PATH), root = path35.resolve(herdrRoot());
33706
+ const server = socket === path35.join(root, "herdr.sock") ? "default" : socket.startsWith(path35.join(root, "sessions") + path35.sep) ? path35.basename(path35.dirname(socket)) : void 0;
33535
33707
  const { HERDR_WORKSPACE_ID: workspace, HERDR_TAB_ID: tab, HERDR_PANE_ID: pane } = env;
33536
33708
  if (!server || !workspace || !tab || !pane) return void 0;
33537
33709
  return { server, workspace, tab, pane };
@@ -33553,7 +33725,7 @@ function noteOptionalReadFailure(what, key2, error62) {
33553
33725
  async function rpc(server, method, params = {}, signal, timeoutMs = 1e4) {
33554
33726
  const socket = herdrSocket(server);
33555
33727
  countHerdr(method);
33556
- const metadata = await stat9(socket).catch((error62) => {
33728
+ const metadata = await stat10(socket).catch((error62) => {
33557
33729
  throw herdrSocketError(error62);
33558
33730
  });
33559
33731
  if (!metadata.isSocket() || process.getuid && metadata.uid !== process.getuid()) throw new BridgeError(503, "The Herdr socket is unavailable.", { code: "herdr-permission" });
@@ -33610,7 +33782,7 @@ async function recentServers(maxAgeMs = SERVER_LIST_REUSE_MS) {
33610
33782
  return value2;
33611
33783
  }
33612
33784
  async function servers() {
33613
- const names = ["default", ...(await readdir7(path34.join(herdrRoot(), "sessions")).catch(() => [])).filter((n) => serverName.safeParse(n).success)].slice(0, 64);
33785
+ const names = ["default", ...(await readdir8(path35.join(herdrRoot(), "sessions")).catch(() => [])).filter((n) => serverName.safeParse(n).success)].slice(0, 64);
33614
33786
  const results = await Promise.all(names.map(async (name) => {
33615
33787
  try {
33616
33788
  await rpc(name, "ping");
@@ -33620,7 +33792,7 @@ async function servers() {
33620
33792
  }
33621
33793
  }));
33622
33794
  const running2 = results.filter((v) => v !== null);
33623
- if (!running2.length) running2.push(...await Promise.resolve().then(() => (init_terminal_tmux(), terminal_tmux_exports)).then((tmux2) => tmux2.tmuxServers()).catch(() => []));
33795
+ running2.push(...await Promise.resolve().then(() => (init_terminal_tmux(), terminal_tmux_exports)).then((tmux2) => tmux2.tmuxServers({ hidden: !running2.length })).catch(() => []));
33624
33796
  knownServers = running2.map((server) => String(server.session));
33625
33797
  return running2;
33626
33798
  }
@@ -33713,10 +33885,10 @@ async function processLogs(pids) {
33713
33885
  if (process.platform === "linux") {
33714
33886
  countIdentity("proc");
33715
33887
  const base = `/proc/${pid}/fd`;
33716
- return Promise.all((await readdir7(base).catch(() => [])).slice(0, 4096).map((fd) => readlink(path34.join(base, fd)).catch(() => "")));
33888
+ return Promise.all((await readdir8(base).catch(() => [])).slice(0, 4096).map((fd) => readlink(path35.join(base, fd)).catch(() => "")));
33717
33889
  }
33718
33890
  countIdentity("lsof");
33719
- const result = await exec3("/usr/sbin/lsof", ["-a", "-p", String(pid), "-Fn"], { timeout: 3e3, maxBuffer: 1048576 }).catch(() => ({ stdout: "" }));
33891
+ const result = await exec4("/usr/sbin/lsof", ["-a", "-p", String(pid), "-Fn"], { timeout: 3e3, maxBuffer: 1048576 }).catch(() => ({ stdout: "" }));
33720
33892
  return result.stdout.split("\n").filter((n) => n.startsWith("n/")).map((n) => n.slice(1));
33721
33893
  }));
33722
33894
  return [...new Set(paths.flat())].filter((p) => p.endsWith(".jsonl") || p.endsWith(".lock"));
@@ -33750,12 +33922,12 @@ async function paneIdentity(server, pane, fresh = false) {
33750
33922
  }
33751
33923
  async function copilotForegroundSession(pids, home = copilotHome()) {
33752
33924
  if (!pids.length) return void 0;
33753
- const folder = path34.join(home, "logs");
33754
- const names = await readdir7(folder).catch(() => []);
33925
+ const folder = path35.join(home, "logs");
33926
+ const names = await readdir8(folder).catch(() => []);
33755
33927
  const logs = names.filter((name) => pids.some((pid) => name.startsWith("process-") && name.endsWith(`-${pid}.log`)));
33756
33928
  let current2, latest = -1;
33757
33929
  for (const name of logs) {
33758
- const file2 = await open6(path34.join(folder, name), "r").catch(() => void 0);
33930
+ const file2 = await open7(path35.join(folder, name), "r").catch(() => void 0);
33759
33931
  if (!file2) continue;
33760
33932
  try {
33761
33933
  const { size } = await file2.stat(), length = Math.min(size, 262144);
@@ -33774,10 +33946,10 @@ async function copilotForegroundSession(pids, home = copilotHome()) {
33774
33946
  return current2;
33775
33947
  }
33776
33948
  async function opencodePidSession(pids, root = phrenStoreRoot()) {
33777
- const folder = path34.join(root, ".runtime", "sessions");
33949
+ const folder = path35.join(root, ".runtime", "sessions");
33778
33950
  let current2, latest = -Infinity;
33779
33951
  for (const pid of pids) {
33780
- const file2 = await open6(path34.join(folder, `opencode-pid-${pid}.json`), "r").catch(() => void 0);
33952
+ const file2 = await open7(path35.join(folder, `opencode-pid-${pid}.json`), "r").catch(() => void 0);
33781
33953
  if (!file2) continue;
33782
33954
  try {
33783
33955
  const { size } = await file2.stat();
@@ -33786,7 +33958,7 @@ async function opencodePidSession(pids, root = phrenStoreRoot()) {
33786
33958
  const session = typeof value2.session === "string" && /^ses_[0-9A-Za-z]{1,64}$/.test(value2.session) ? value2.session : void 0;
33787
33959
  const at = Date.parse(String(value2.at));
33788
33960
  if (!session || !(at > latest)) continue;
33789
- if (!await stat9(path34.join(folder, `opencode-${session}.events.jsonl`)).catch(() => void 0)) continue;
33961
+ if (!await stat10(path35.join(folder, `opencode-${session}.events.jsonl`)).catch(() => void 0)) continue;
33790
33962
  current2 = session;
33791
33963
  latest = at;
33792
33964
  } catch {
@@ -33804,7 +33976,7 @@ async function identityFromProcesses(server, pane, pids) {
33804
33976
  }
33805
33977
  if (pane.agent === "copilot") {
33806
33978
  const current2 = await copilotForegroundSession(pids).catch(() => void 0);
33807
- if (current2) return await stat9(path34.join(copilotHome(), "session-state", current2, "events.jsonl")).then(() => ({ sessionId: current2, noTranscriptLogs: false }), () => ({ noTranscriptLogs: true }));
33979
+ if (current2) return await stat10(path35.join(copilotHome(), "session-state", current2, "events.jsonl")).then(() => ({ sessionId: current2, noTranscriptLogs: false }), () => ({ noTranscriptLogs: true }));
33808
33980
  const reported = object2(pane.agent_session);
33809
33981
  if (reported.kind === "id" && reported.agent === "copilot" && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) return { sessionId: reported.value, noTranscriptLogs: false };
33810
33982
  }
@@ -33814,9 +33986,51 @@ async function identityFromProcesses(server, pane, pids) {
33814
33986
  return match ? [match[1]] : [];
33815
33987
  });
33816
33988
  if (new Set(candidates).size === 1) return { sessionId: candidates[0], noTranscriptLogs: false };
33989
+ if (pane.agent === "codex" && candidates.length === 0) {
33990
+ const daemon = await codexDaemonIdentity(server, pane, pids).catch(() => void 0);
33991
+ if (daemon?.sessionId) return { sessionId: daemon.sessionId, noTranscriptLogs: false };
33992
+ const recorded2 = await recordedSession(server, pane, pids);
33993
+ return { sessionId: recorded2 && !daemon?.known.has(recorded2) ? recorded2 : void 0, noTranscriptLogs: true };
33994
+ }
33817
33995
  const recorded = await recordedSession(server, pane, pids);
33818
33996
  return { sessionId: candidates.length === 0 || recorded && candidates.includes(recorded) ? recorded : void 0, noTranscriptLogs: candidates.length === 0 };
33819
33997
  }
33998
+ async function codexDaemonIdentity(server, pane, pids) {
33999
+ const all = await daemonRollouts(processLogs);
34000
+ const known = new Set(all.map((r) => r.id));
34001
+ const cwd = paneCwd(pane);
34002
+ const here = [];
34003
+ for (const r of all) if (await sameDirectory(r.cwd, cwd)) here.push(r);
34004
+ if (!here.length) return { known };
34005
+ const rows = await processTable(), start = startedAt(rows, pids);
34006
+ if (start === void 0) return { known };
34007
+ const s = await (await terminal()).terminalProvider().snapshot(server).catch(() => ({}));
34008
+ const claimed = /* @__PURE__ */ new Set(), rivals = [];
34009
+ for (const peer of objects(s.panes).filter((p) => p.agent === "codex" && p.pane_id !== pane.pane_id).slice(0, 16)) {
34010
+ if (!await sameDirectory(paneCwd(peer), cwd)) continue;
34011
+ const peerPids = await foregroundPids(server, peer).catch(() => []);
34012
+ if (!peerPids.length) continue;
34013
+ const own2 = rolloutIds(await processLogs(peerPids));
34014
+ if (own2.length) {
34015
+ for (const id2 of own2) claimed.add(id2);
34016
+ continue;
34017
+ }
34018
+ const peerStart = startedAt(rows, peerPids);
34019
+ if (peerStart !== void 0) rivals.push({ key: String(peer.pane_id), start: peerStart });
34020
+ }
34021
+ return { sessionId: assignDaemonConversation(here, { key: String(pane.pane_id), start }, claimed, rivals), known };
34022
+ }
34023
+ async function paneForCodexSession(server, session, cwd) {
34024
+ const s = await snapshot(server);
34025
+ const codex2 = objects(s.panes).filter((p) => p.agent === "codex").slice(0, 32);
34026
+ const identities2 = await Promise.all(codex2.map((p) => paneIdentity(server, p).catch(() => void 0)));
34027
+ const index2 = identities2.indexOf(session);
34028
+ if (index2 >= 0) return codex2[index2];
34029
+ if (!cwd) return void 0;
34030
+ const same = [];
34031
+ for (const [i, p] of codex2.entries()) if (await sameDirectory(paneCwd(p), cwd)) same.push(i);
34032
+ return same.length === 1 && !identities2[same[0]] ? codex2[same[0]] : void 0;
34033
+ }
33820
34034
  async function paneChatState(server, pane, options = {}) {
33821
34035
  if (!provider.safeParse(pane.agent).success) return {};
33822
34036
  const identity = await resolveIdentity(server, pane, false);
@@ -33880,10 +34094,10 @@ async function validateTarget(target, sending = false, refreshIdentity = sending
33880
34094
  }
33881
34095
  async function trustedDirectory(pane) {
33882
34096
  const cwd = pane.foreground_cwd || pane.cwd;
33883
- if (typeof cwd !== "string" || !path34.isAbsolute(cwd)) throw new BridgeError(409, "This pane has no project folder.");
33884
- return realpath6(cwd);
34097
+ if (typeof cwd !== "string" || !path35.isAbsolute(cwd)) throw new BridgeError(409, "This pane has no project folder.");
34098
+ return realpath7(cwd);
33885
34099
  }
33886
- var terminal, exec3, optionalReadFailures, SERVER_LIST_REUSE_MS, serverList, knownServers, SNAPSHOT_SHARE_MS, sharedSnapshots, inFlightSnapshots, IDENTITY_CACHE_MS, identities, identityKey, copilotHome, startingKey, sharedIdentities;
34100
+ var terminal, exec4, optionalReadFailures, SERVER_LIST_REUSE_MS, serverList, knownServers, SNAPSHOT_SHARE_MS, sharedSnapshots, inFlightSnapshots, IDENTITY_CACHE_MS, identities, identityKey, copilotHome, rolloutIds, paneCwd, startingKey, sharedIdentities;
33887
34101
  var init_herdr = __esm({
33888
34102
  "src/bridge/herdr.ts"() {
33889
34103
  "use strict";
@@ -33894,8 +34108,9 @@ var init_herdr = __esm({
33894
34108
  init_limits();
33895
34109
  init_metrics();
33896
34110
  init_transcripts();
34111
+ init_codex_daemon();
33897
34112
  terminal = () => Promise.resolve().then(() => (init_terminal(), terminal_exports));
33898
- exec3 = promisify3(execFile4);
34113
+ exec4 = promisify4(execFile5);
33899
34114
  optionalReadFailures = /* @__PURE__ */ new Map();
33900
34115
  SERVER_LIST_REUSE_MS = intervalFromEnv("PHREN_SERVER_LIST_REUSE_MS", 3e4, 0, 6e5);
33901
34116
  SNAPSHOT_SHARE_MS = intervalFromEnv("PHREN_SNAPSHOT_SHARE_MS", 2500, 0, 1e4);
@@ -33904,7 +34119,9 @@ var init_herdr = __esm({
33904
34119
  IDENTITY_CACHE_MS = intervalFromEnv("PHREN_IDENTITY_CACHE_MS", 2e3);
33905
34120
  identities = /* @__PURE__ */ new Map();
33906
34121
  identityKey = (server, pane, pids) => JSON.stringify([server, pane.pane_id, pane.terminal_id, pids, pane.agent]);
33907
- copilotHome = () => process.env.COPILOT_HOME || path34.join(homedir8(), ".copilot");
34122
+ copilotHome = () => process.env.COPILOT_HOME || path35.join(homedir8(), ".copilot");
34123
+ rolloutIds = (files) => files.flatMap((file2) => /rollout-.*-([a-f0-9-]{36})\.jsonl$/i.exec(file2)?.[1] ?? []);
34124
+ paneCwd = (pane) => pane.foreground_cwd || pane.cwd;
33908
34125
  startingKey = randomBytes2(32);
33909
34126
  sharedIdentities = /* @__PURE__ */ new WeakMap();
33910
34127
  }
@@ -33940,7 +34157,7 @@ var init_preferences = __esm({
33940
34157
  // src/project-config.ts
33941
34158
  import * as crypto4 from "crypto";
33942
34159
  import * as fs23 from "fs";
33943
- import * as path42 from "path";
34160
+ import * as path43 from "path";
33944
34161
  function parseProjectOwnershipMode(raw) {
33945
34162
  if (!raw) return void 0;
33946
34163
  const normalized = raw.trim().toLowerCase();
@@ -33955,7 +34172,7 @@ function resolveProjectConfigPath(phrenPath, project) {
33955
34172
  return storeAwareProjectPath(phrenPath, project, "phren.project.yaml");
33956
34173
  }
33957
34174
  function writeProjectConfigFile(configPath, next) {
33958
- fs23.mkdirSync(path42.dirname(configPath), { recursive: true });
34175
+ fs23.mkdirSync(path43.dirname(configPath), { recursive: true });
33959
34176
  const tmpPath = `${configPath}.tmp-${crypto4.randomUUID()}`;
33960
34177
  fs23.writeFileSync(tmpPath, dump(next, { lineWidth: 1e3 }));
33961
34178
  fs23.renameSync(tmpPath, configPath);
@@ -34008,7 +34225,7 @@ function getProjectSourcePath(phrenPath, project, config3, machine = getMachineN
34008
34225
  const resolved = config3 ?? readProjectConfig(phrenPath, project);
34009
34226
  const perMachine = resolved.sourcePaths && typeof resolved.sourcePaths === "object" && !Array.isArray(resolved.sourcePaths) ? resolved.sourcePaths[machine] : void 0;
34010
34227
  const raw = typeof perMachine === "string" && perMachine.trim() ? perMachine : resolved.sourcePath;
34011
- return typeof raw === "string" && raw.trim() ? path42.resolve(raw) : void 0;
34228
+ return typeof raw === "string" && raw.trim() ? path43.resolve(raw) : void 0;
34012
34229
  }
34013
34230
  function recordProjectSourcePath(phrenPath, project, sourceRoot, patch = {}, machine = getMachineName()) {
34014
34231
  const current2 = readProjectConfig(phrenPath, project);
@@ -34051,11 +34268,11 @@ __export(agent_package_exports, {
34051
34268
  import { execFileSync as execFileSync4, spawn as spawn4 } from "node:child_process";
34052
34269
  import * as fs24 from "node:fs";
34053
34270
  import { createRequire } from "node:module";
34054
- import * as path45 from "node:path";
34271
+ import * as path46 from "node:path";
34055
34272
  import { fileURLToPath as fileURLToPath4 } from "node:url";
34056
34273
  function readManifest(directory) {
34057
34274
  try {
34058
- return JSON.parse(fs24.readFileSync(path45.join(directory, "package.json"), "utf8"));
34275
+ return JSON.parse(fs24.readFileSync(path46.join(directory, "package.json"), "utf8"));
34059
34276
  } catch {
34060
34277
  return void 0;
34061
34278
  }
@@ -34065,15 +34282,15 @@ function agentPackageAt(directory, source) {
34065
34282
  if (manifest?.name !== "@phren/agent") return void 0;
34066
34283
  const relative3 = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.["phren-agent"];
34067
34284
  if (!relative3) return void 0;
34068
- const bin = path45.join(directory, relative3);
34285
+ const bin = path46.join(directory, relative3);
34069
34286
  return fs24.existsSync(bin) ? { directory, bin, version: manifest.version, source } : void 0;
34070
34287
  }
34071
34288
  function workspaceDirectory() {
34072
- let directory = path45.dirname(fileURLToPath4(import.meta.url));
34289
+ let directory = path46.dirname(fileURLToPath4(import.meta.url));
34073
34290
  for (let depth = 0; depth < 8; depth++) {
34074
- const candidate = path45.join(directory, "packages", "agent");
34075
- if (fs24.existsSync(path45.join(candidate, "package.json"))) return candidate;
34076
- const parent = path45.dirname(directory);
34291
+ const candidate = path46.join(directory, "packages", "agent");
34292
+ if (fs24.existsSync(path46.join(candidate, "package.json"))) return candidate;
34293
+ const parent = path46.dirname(directory);
34077
34294
  if (parent === directory) break;
34078
34295
  directory = parent;
34079
34296
  }
@@ -34081,7 +34298,7 @@ function workspaceDirectory() {
34081
34298
  }
34082
34299
  function resolvedDirectory() {
34083
34300
  try {
34084
- return path45.dirname(createRequire(import.meta.url).resolve("@phren/agent/package.json"));
34301
+ return path46.dirname(createRequire(import.meta.url).resolve("@phren/agent/package.json"));
34085
34302
  } catch {
34086
34303
  return void 0;
34087
34304
  }
@@ -34090,7 +34307,7 @@ function globalDirectory() {
34090
34307
  try {
34091
34308
  const options = { encoding: "utf8", timeout: 1e4, stdio: ["ignore", "pipe", "ignore"] };
34092
34309
  const root = (process.platform === "win32" ? execFileSync4("npm.cmd", ["root", "-g"], { ...options, shell: true }) : execFileSync4("npm", ["root", "-g"], options)).trim();
34093
- return root ? path45.join(root, "@phren", "agent") : void 0;
34310
+ return root ? path46.join(root, "@phren", "agent") : void 0;
34094
34311
  } catch {
34095
34312
  return void 0;
34096
34313
  }
@@ -34229,7 +34446,7 @@ var init_audit = __esm({
34229
34446
 
34230
34447
  // src/governance/activity.ts
34231
34448
  import * as fs25 from "fs";
34232
- import * as path55 from "path";
34449
+ import * as path56 from "path";
34233
34450
  function clampSnippet(snippet) {
34234
34451
  if (!snippet) return void 0;
34235
34452
  const flat = snippet.replace(/\s+/g, " ").trim();
@@ -34240,7 +34457,7 @@ function recordLookupEvents(phrenPath, events) {
34240
34457
  if (!events.length) return;
34241
34458
  const logPath = lookupEventsLogFile(phrenPath);
34242
34459
  try {
34243
- fs25.mkdirSync(path55.dirname(logPath), { recursive: true });
34460
+ fs25.mkdirSync(path56.dirname(logPath), { recursive: true });
34244
34461
  const now = (/* @__PURE__ */ new Date()).toISOString();
34245
34462
  const lines = events.map(
34246
34463
  (e) => JSON.stringify({
@@ -34262,8 +34479,8 @@ function recordLookupEvents(phrenPath, events) {
34262
34479
  return;
34263
34480
  }
34264
34481
  try {
34265
- const stat26 = fs25.statSync(logPath);
34266
- if (stat26.size > ROTATE_BYTES) {
34482
+ const stat27 = fs25.statSync(logPath);
34483
+ if (stat27.size > ROTATE_BYTES) {
34267
34484
  const content = fs25.readFileSync(logPath, "utf8");
34268
34485
  const kept = content.split("\n").filter(Boolean).slice(-MAX_LOG_LINES2);
34269
34486
  fs25.writeFileSync(logPath, kept.join("\n") + "\n");
@@ -34525,7 +34742,7 @@ var init_metadata = __esm({
34525
34742
 
34526
34743
  // src/governance/policy.ts
34527
34744
  import * as fs26 from "fs";
34528
- import * as path56 from "path";
34745
+ import * as path57 from "path";
34529
34746
  function assessSyncOutage(sync, nowMs = Date.now()) {
34530
34747
  const consecutiveFailures = sync?.consecutiveFailures ?? 0;
34531
34748
  const failingNow = sync?.lastPushStatus !== void 0 && FAILED_PUSH_STATUSES.has(sync.lastPushStatus);
@@ -34662,7 +34879,7 @@ function normalizeIndexPolicy(data) {
34662
34879
  function readJsonFile(filePath, fallback) {
34663
34880
  try {
34664
34881
  if (!fs26.existsSync(filePath)) return fallback;
34665
- const basename12 = path56.basename(filePath);
34882
+ const basename12 = path57.basename(filePath);
34666
34883
  const schema = GOVERNANCE_FILE_SCHEMAS[basename12];
34667
34884
  if (schema && !validateGovernanceJson(filePath, schema)) {
34668
34885
  debugLog(`readJsonFile: ${filePath} failed validation, using defaults`);
@@ -35062,9 +35279,9 @@ import * as path23 from "node:path";
35062
35279
  function gitDirectory(store) {
35063
35280
  const dotGit = path23.join(store, ".git");
35064
35281
  try {
35065
- const stat26 = fs15.statSync(dotGit);
35066
- if (stat26.isDirectory()) return dotGit;
35067
- if (!stat26.isFile()) return void 0;
35282
+ const stat27 = fs15.statSync(dotGit);
35283
+ if (stat27.isDirectory()) return dotGit;
35284
+ if (!stat27.isFile()) return void 0;
35068
35285
  const match = /^gitdir:\s*(.+)\s*$/i.exec(fs15.readFileSync(dotGit, "utf8"));
35069
35286
  if (!match) return void 0;
35070
35287
  return path23.resolve(store, match[1]);
@@ -35099,7 +35316,7 @@ import * as fs17 from "node:fs";
35099
35316
  import * as path25 from "node:path";
35100
35317
  var core = (names) => names.map((name) => ({ name, profiles: ["core", "full"] }));
35101
35318
  var full = (names) => names.map((name) => ({ name, profiles: ["full"] }));
35102
- var routes = (method, paths) => paths.map((path84) => ({ method, path: path84 }));
35319
+ var routes = (method, paths) => paths.map((path85) => ({ method, path: path85 }));
35103
35320
  var BUILTIN_MODULES = [
35104
35321
  {
35105
35322
  schemaVersion: 1,
@@ -35622,7 +35839,7 @@ import { chmod as chmod5, lstat as lstat20, mkdir as mkdir21, readFile as readFi
35622
35839
  import { readFileSync as readFileSync32 } from "node:fs";
35623
35840
  import { createServer as createServer2 } from "node:http";
35624
35841
  import { cpus, hostname as hostname9, loadavg } from "node:os";
35625
- import path82 from "node:path";
35842
+ import path83 from "node:path";
35626
35843
 
35627
35844
  // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs
35628
35845
  var import_stream = __toESM(require_stream(), 1);
@@ -35888,11 +36105,12 @@ init_shared();
35888
36105
  init_logger();
35889
36106
  init_protocol();
35890
36107
  init_herdr();
36108
+ init_codex_daemon();
35891
36109
  init_terminal();
35892
36110
  import { request, createServer } from "node:http";
35893
36111
  import { mkdir as mkdir9, readFile as readFile14, chmod, unlink as unlink3, lstat as lstat7 } from "node:fs/promises";
35894
36112
  import { watch } from "node:fs";
35895
- import path37 from "node:path";
36113
+ import path38 from "node:path";
35896
36114
  import { randomUUID as randomUUID7 } from "node:crypto";
35897
36115
 
35898
36116
  // src/bridge/pane-text.ts
@@ -35919,7 +36137,7 @@ init_js_yaml();
35919
36137
  init_zod();
35920
36138
  init_protocol();
35921
36139
  import { lstat as lstat6, mkdir as mkdir8, readFile as readFile12 } from "node:fs/promises";
35922
- import path35 from "node:path";
36140
+ import path36 from "node:path";
35923
36141
  var grantAction = external_exports.enum(["dispatch", "hand_off"]);
35924
36142
  var grantScope = external_exports.union([
35925
36143
  external_exports.literal("global"),
@@ -35931,7 +36149,7 @@ var grantSchema = external_exports.object({
35931
36149
  computers: external_exports.array(computerName).min(1).max(32).optional().describe("Named verified peers; omitted means any."),
35932
36150
  until: external_exports.string().datetime({ offset: true }).optional().describe("Expiry timestamp; omitted means until revoked.")
35933
36151
  }).strict();
35934
- var grantFile = (root = bridgeRoot()) => path35.join(root, "conductor.yaml");
36152
+ var grantFile = (root = bridgeRoot()) => path36.join(root, "conductor.yaml");
35935
36153
  var fileSchema = external_exports.object({ grants: external_exports.array(grantSchema).max(64) }).strict();
35936
36154
  async function regularPrivateFile(file2) {
35937
36155
  const info = await lstat6(file2).catch(() => void 0);
@@ -35992,7 +36210,7 @@ function grantLabel(grant) {
35992
36210
  }
35993
36211
  var mutations = /* @__PURE__ */ new Map();
35994
36212
  async function mutateGrants(root, action) {
35995
- const key2 = path35.resolve(root);
36213
+ const key2 = path36.resolve(root);
35996
36214
  const previous = mutations.get(key2) ?? Promise.resolve();
35997
36215
  const pending = previous.catch(() => {
35998
36216
  }).then(async () => {
@@ -36071,9 +36289,9 @@ async function removeGrant(input2, root = bridgeRoot()) {
36071
36289
  init_zod();
36072
36290
  init_protocol();
36073
36291
  import { createCipheriv, createHmac as createHmac2, createPrivateKey, randomBytes as randomBytes3, sign } from "node:crypto";
36074
- import { readFile as readFile13, stat as stat10 } from "node:fs/promises";
36292
+ import { readFile as readFile13, stat as stat11 } from "node:fs/promises";
36075
36293
  import { connect as connect2 } from "node:http2";
36076
- import path36 from "node:path";
36294
+ import path37 from "node:path";
36077
36295
  var relaySchema = external_exports.object({
36078
36296
  url: external_exports.string().url().refine(
36079
36297
  (value2) => /^https:\/\//.test(value2) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${value2}/`),
@@ -36145,7 +36363,7 @@ function schedulePushPayload(value2) {
36145
36363
  }
36146
36364
  async function secureJSON(file2, schema) {
36147
36365
  try {
36148
- const metadata = await stat10(file2);
36366
+ const metadata = await stat11(file2);
36149
36367
  if ((metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
36150
36368
  return schema.parse(JSON.parse(await readFile13(file2, "utf8")));
36151
36369
  } catch {
@@ -36154,14 +36372,14 @@ async function secureJSON(file2, schema) {
36154
36372
  }
36155
36373
  async function secureFile(file2) {
36156
36374
  try {
36157
- const metadata = await stat10(file2);
36375
+ const metadata = await stat11(file2);
36158
36376
  if (!metadata.isFile() || (metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
36159
36377
  return await readFile13(file2, "utf8");
36160
36378
  } catch {
36161
36379
  return void 0;
36162
36380
  }
36163
36381
  }
36164
- function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path36.join(bridgeRoot(), "apns.json")) {
36382
+ function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path37.join(bridgeRoot(), "apns.json")) {
36165
36383
  return [
36166
36384
  "Approval push is not configured: the phone only alerts while Phren runs, and a registered phone gets nothing while suspended.",
36167
36385
  "1. In your Apple developer account, create an APNs key (Keys, Apple Push Notifications service) and download AuthKey_<KEYID>.p8.",
@@ -36283,13 +36501,13 @@ var APNsSender = class {
36283
36501
  var ApprovalPushService = class {
36284
36502
  devices = [];
36285
36503
  sender;
36286
- devicesFile = path36.join(bridgeRoot(), "push-devices.json");
36504
+ devicesFile = path37.join(bridgeRoot(), "push-devices.json");
36287
36505
  async start() {
36288
36506
  this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
36289
- const configFile = process.env.PHREN_APNS_CONFIG || path36.join(bridgeRoot(), "apns.json");
36507
+ const configFile = process.env.PHREN_APNS_CONFIG || path37.join(bridgeRoot(), "apns.json");
36290
36508
  const config3 = await secureJSON(configFile, configSchema2);
36291
36509
  if (!config3) return;
36292
- const keyPath = path36.isAbsolute(config3.privateKeyPath) ? config3.privateKeyPath : path36.resolve(path36.dirname(configFile), config3.privateKeyPath);
36510
+ const keyPath = path37.isAbsolute(config3.privateKeyPath) ? config3.privateKeyPath : path37.resolve(path37.dirname(configFile), config3.privateKeyPath);
36293
36511
  const key2 = await secureFile(keyPath);
36294
36512
  if (key2) this.sender = new APNsSender(config3, key2);
36295
36513
  }
@@ -36464,7 +36682,7 @@ var AgentHooks = class {
36464
36682
  fanoutTimer;
36465
36683
  fanoutArchiveTimer;
36466
36684
  approvalsDirectory() {
36467
- return path37.join(phrenStoreRoot(), ".runtime", "approvals");
36685
+ return path38.join(phrenStoreRoot(), ".runtime", "approvals");
36468
36686
  }
36469
36687
  scheduleOpencodeSweep() {
36470
36688
  if (this.closed || this.opencodeDebounce) return;
@@ -36533,13 +36751,13 @@ var AgentHooks = class {
36533
36751
  /** A session's exact pane. A recorded binding carries the full target; when
36534
36752
  * there is none, Herdr's explicit session identity names the pane. */
36535
36753
  async resolveTarget(source, session) {
36536
- const root = path37.join(bridgeRoot(), "bindings");
36754
+ const root = path38.join(bridgeRoot(), "bindings");
36537
36755
  for await (const folder of directoryNames(root, 64)) {
36538
- for await (const name of directoryNames(path37.join(root, folder), 1024)) {
36756
+ for await (const name of directoryNames(path38.join(root, folder), 1024)) {
36539
36757
  if (!name.endsWith(".json")) continue;
36540
36758
  let value2;
36541
36759
  try {
36542
- const file2 = path37.join(root, folder, name), info = await lstat7(file2);
36760
+ const file2 = path38.join(root, folder, name), info = await lstat7(file2);
36543
36761
  if (!info.isFile() || info.size > 65536) continue;
36544
36762
  value2 = object2(JSON.parse(await readFile14(file2, "utf8")));
36545
36763
  } catch {
@@ -37281,18 +37499,29 @@ var AgentHooks = class {
37281
37499
  if (size > 1048576) throw new Error("Oversized hook");
37282
37500
  chunks.push(bytes);
37283
37501
  }
37284
- const body2 = object2(JSON.parse(Buffer.concat(chunks).toString())), target = targetSchema.parse(body2.target);
37502
+ const body2 = object2(JSON.parse(Buffer.concat(chunks).toString()));
37503
+ let target = targetSchema.parse(body2.target);
37285
37504
  if (this.modules?.has("git") === false && ["PreToolUse", "PostToolUse"].includes(String(body2.event))) {
37286
37505
  res.statusCode = 404;
37287
37506
  res.end(JSON.stringify({ error: disabledHint("git") }));
37288
37507
  return;
37289
37508
  }
37509
+ const daemon = body2.daemon === true;
37510
+ if (daemon) {
37511
+ if (target.source !== "codex") throw new Error("Invalid callback");
37512
+ const placed = await paneForCodexSession(target.server, target.session, typeof body2.cwd === "string" && path38.isAbsolute(body2.cwd) ? body2.cwd : void 0);
37513
+ if (!placed) {
37514
+ res.end("{}");
37515
+ return;
37516
+ }
37517
+ target = targetSchema.parse({ ...target, workspace: placed.workspace_id, tab: placed.tab_id, pane: placed.pane_id });
37518
+ }
37290
37519
  const s = await snapshot(target.server);
37291
37520
  const pane = findPane(s, { workspace: target.workspace, tab: target.tab, pane: target.pane });
37292
37521
  if (!pane || pane.agent && pane.agent !== target.source) throw new Error("The pane changed");
37293
37522
  const pids = (await terminalProvider().processes(target.server, target.pane)).foregroundPids;
37294
37523
  if (!pids.length) throw new Error("No foreground process");
37295
- await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({
37524
+ if (!daemon) await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({
37296
37525
  terminal: pane.terminal_id,
37297
37526
  source: target.source,
37298
37527
  session: target.session,
@@ -37317,7 +37546,7 @@ var AgentHooks = class {
37317
37546
  }
37318
37547
  if ((this.modules?.has("git") ?? true) && ["PreToolUse", "PostToolUse"].includes(String(body2.event)) && capturesChanges(String(body2.tool), input2)) {
37319
37548
  const conversation = `${target.source}:${target.session}`, id2 = String(body2.toolUseId || "").slice(0, 200);
37320
- if (body2.event === "PreToolUse") await this.changes.before(conversation, id2, typeof body2.cwd === "string" && path37.isAbsolute(body2.cwd) ? body2.cwd : await trustedDirectory(pane), command ?? "", input2);
37549
+ if (body2.event === "PreToolUse") await this.changes.before(conversation, id2, typeof body2.cwd === "string" && path38.isAbsolute(body2.cwd) ? body2.cwd : await trustedDirectory(pane), command ?? "", input2);
37321
37550
  else await this.changes.after(conversation, id2);
37322
37551
  res.end("{}");
37323
37552
  return;
@@ -37488,9 +37717,11 @@ async function agentHook(source) {
37488
37717
  const event = String(value2.hook_event_name || "SessionStart");
37489
37718
  const modules = activateModules(defaultPhrenPath(), void 0, true);
37490
37719
  if (!modules.has("hook") || event.endsWith("ToolUse") && !modules.has("git")) return;
37720
+ const daemon = source === "codex" && await underCodexDaemon().catch(() => false);
37491
37721
  const data = JSON.stringify({
37492
37722
  target,
37493
37723
  event,
37724
+ ...daemon ? { daemon: true } : {},
37494
37725
  tool: value2.tool_name,
37495
37726
  input: value2.tool_input,
37496
37727
  toolUseId: value2.tool_use_id,
@@ -37532,27 +37763,27 @@ init_changes();
37532
37763
  init_store_registry();
37533
37764
  import { rm as rm4 } from "node:fs/promises";
37534
37765
  import * as fs21 from "node:fs";
37535
- import * as path41 from "node:path";
37766
+ import * as path42 from "node:path";
37536
37767
 
37537
37768
  // src/bridge/projects.ts
37538
37769
  init_utils_helpers();
37539
37770
  init_home_paths();
37540
37771
  init_transcripts();
37541
- import { execFile as execFile5 } from "node:child_process";
37542
- import { promisify as promisify4 } from "node:util";
37772
+ import { execFile as execFile6 } from "node:child_process";
37773
+ import { promisify as promisify5 } from "node:util";
37543
37774
  import { request as request2 } from "node:http";
37544
37775
  import { userInfo as userInfo2 } from "node:os";
37545
- import { readFile as readFile16, realpath as realpath7, stat as stat12 } from "node:fs/promises";
37546
- import path39 from "node:path";
37776
+ import { readFile as readFile16, realpath as realpath8, stat as stat13 } from "node:fs/promises";
37777
+ import path40 from "node:path";
37547
37778
 
37548
37779
  // src/bridge/locate.ts
37549
37780
  init_protocol();
37550
37781
  init_herdr();
37551
37782
  init_transcripts();
37552
37783
  import { realpathSync as realpathSync3 } from "node:fs";
37553
- import { readFile as readFile15, stat as stat11 } from "node:fs/promises";
37784
+ import { readFile as readFile15, stat as stat12 } from "node:fs/promises";
37554
37785
  import { homedir as homedir9 } from "node:os";
37555
- import path38 from "node:path";
37786
+ import path39 from "node:path";
37556
37787
  var PROJECT_NAME = /^[a-z0-9][a-z0-9-]*$/;
37557
37788
  var SEARCH_ROOTS = ["", "Sites", "Projects", "projects", "Code", "code", "dev", "src", "repos", "workspace"];
37558
37789
  async function locateProject(project, activity, env = process.env) {
@@ -37560,9 +37791,9 @@ async function locateProject(project, activity, env = process.env) {
37560
37791
  const found = [];
37561
37792
  const seen = /* @__PURE__ */ new Set();
37562
37793
  const offer = async (directory, source, lastSeen) => {
37563
- let dir = path38.resolve(directory);
37794
+ let dir = path39.resolve(directory);
37564
37795
  try {
37565
- if (!(await stat11(dir)).isDirectory()) return;
37796
+ if (!(await stat12(dir)).isDirectory()) return;
37566
37797
  dir = realpathSync3.native(dir);
37567
37798
  } catch {
37568
37799
  return;
@@ -37575,33 +37806,33 @@ async function locateProject(project, activity, env = process.env) {
37575
37806
  const namesProject = (directory) => segments(directory).includes(project);
37576
37807
  const trimmed = (directory) => {
37577
37808
  const parts = segments(directory);
37578
- return parts.slice(0, parts.lastIndexOf(project) + 1).join(path38.sep);
37809
+ return parts.slice(0, parts.lastIndexOf(project) + 1).join(path39.sep);
37579
37810
  };
37580
37811
  for (const event of [...activity].reverse()) {
37581
37812
  const directory = typeof event.directory === "string" ? event.directory : void 0;
37582
- if (directory && path38.isAbsolute(directory) && namesProject(directory)) {
37813
+ if (directory && path39.isAbsolute(directory) && namesProject(directory)) {
37583
37814
  await offer(trimmed(directory), "activity", typeof event.at === "string" ? event.at : void 0);
37584
37815
  }
37585
37816
  }
37586
37817
  try {
37587
- const session = JSON.parse(await readFile15(path38.join(herdrRoot(), "session.json"), "utf8"));
37818
+ const session = JSON.parse(await readFile15(path39.join(herdrRoot(), "session.json"), "utf8"));
37588
37819
  for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
37589
37820
  const directory = JSON.parse(`"${match[1]}"`);
37590
- if (path38.isAbsolute(directory) && namesProject(directory)) {
37821
+ if (path39.isAbsolute(directory) && namesProject(directory)) {
37591
37822
  await offer(trimmed(directory), "herdr");
37592
37823
  }
37593
37824
  }
37594
37825
  } catch {
37595
37826
  }
37596
37827
  try {
37597
- const config3 = await readFile15(path38.join(phrenStoreRoot(env), project, "phren.project.yaml"), "utf8");
37828
+ const config3 = await readFile15(path39.join(phrenStoreRoot(env), project, "phren.project.yaml"), "utf8");
37598
37829
  const match = /^sourcePath:\s*(.+)$/m.exec(config3);
37599
37830
  if (match) await offer(match[1].trim().replace(/^['"]|['"]$/g, ""), "phren");
37600
37831
  } catch {
37601
37832
  }
37602
37833
  const home = homedir9();
37603
- for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS.map((r) => path38.join(home, r))]) {
37604
- await offer(path38.join(root, project), "search");
37834
+ for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS.map((r) => path39.join(home, r))]) {
37835
+ await offer(path39.join(root, project), "search");
37605
37836
  }
37606
37837
  return found.slice(0, 8);
37607
37838
  }
@@ -37609,10 +37840,10 @@ async function locateProject(project, activity, env = process.env) {
37609
37840
  // src/bridge/projects.ts
37610
37841
  init_protocol();
37611
37842
  init_metrics();
37612
- var exec4 = promisify4(execFile5);
37843
+ var exec5 = promisify5(execFile6);
37613
37844
  async function git2(cwd, ...args) {
37614
37845
  countGit("projects");
37615
- return (await exec4("git", ["-C", cwd, "--no-pager", ...args], {
37846
+ return (await exec5("git", ["-C", cwd, "--no-pager", ...args], {
37616
37847
  timeout: 1e4,
37617
37848
  maxBuffer: 4194304,
37618
37849
  env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" })
@@ -37620,7 +37851,7 @@ async function git2(cwd, ...args) {
37620
37851
  }
37621
37852
  async function gitRoot(dir) {
37622
37853
  try {
37623
- return await realpath7((await git2(dir, "rev-parse", "--show-toplevel")).trim());
37854
+ return await realpath8((await git2(dir, "rev-parse", "--show-toplevel")).trim());
37624
37855
  } catch {
37625
37856
  return void 0;
37626
37857
  }
@@ -37655,16 +37886,16 @@ async function committed(root, pathspec) {
37655
37886
  async function resolveTouched(raw, cwd) {
37656
37887
  if (typeof raw !== "string" || !raw || raw.length > 4096 || raw.includes("\0")) return void 0;
37657
37888
  const home = homeDir();
37658
- const absolute = raw === "~" || raw.startsWith("~/") ? path39.join(home, raw.slice(1)) : path39.resolve(cwd, raw);
37889
+ const absolute = raw === "~" || raw.startsWith("~/") ? path40.join(home, raw.slice(1)) : path40.resolve(cwd, raw);
37659
37890
  let existing = absolute, rest = [];
37660
- while (!await stat12(existing).catch(() => void 0)) {
37661
- const parent = path39.dirname(existing);
37891
+ while (!await stat13(existing).catch(() => void 0)) {
37892
+ const parent = path40.dirname(existing);
37662
37893
  if (parent === existing) return void 0;
37663
- rest.unshift(path39.basename(existing));
37894
+ rest.unshift(path40.basename(existing));
37664
37895
  existing = parent;
37665
37896
  }
37666
- const real = path39.join(await realpath7(existing), ...rest);
37667
- return real;
37897
+ const real2 = path40.join(await realpath8(existing), ...rest);
37898
+ return real2;
37668
37899
  }
37669
37900
  async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
37670
37901
  const root = await gitRoot(cwd);
@@ -37673,16 +37904,16 @@ async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
37673
37904
  const requested = [];
37674
37905
  for (const raw of touched.slice(0, 24)) {
37675
37906
  const file2 = await resolveTouched(raw, cwd);
37676
- if (!file2 || !allowed.some((base) => file2 === base || file2.startsWith(base + path39.sep))) throw new BridgeError(403, "This path is outside the conversation's recorded changes and commands.");
37907
+ if (!file2 || !allowed.some((base) => file2 === base || file2.startsWith(base + path40.sep))) throw new BridgeError(403, "This path is outside the conversation's recorded changes and commands.");
37677
37908
  requested.push(file2);
37678
37909
  }
37679
37910
  const branch = (await git2(root, "branch", "--show-current")).trim();
37680
37911
  const files = await statusFiles(root);
37681
37912
  const byRoot = /* @__PURE__ */ new Map();
37682
37913
  for (const file2 of requested) {
37683
- const owner = await gitRoot((await stat12(file2).catch(() => void 0))?.isDirectory() ? file2 : path39.dirname(file2));
37914
+ const owner = await gitRoot((await stat13(file2).catch(() => void 0))?.isDirectory() ? file2 : path40.dirname(file2));
37684
37915
  if (!owner) continue;
37685
- const rel = (path39.relative(owner, file2) || ".").split(path39.sep).join("/");
37916
+ const rel = (path40.relative(owner, file2) || ".").split(path40.sep).join("/");
37686
37917
  if (rel.startsWith(":")) throw new BridgeError(400, "Invalid diff pathspec.");
37687
37918
  const list = byRoot.get(owner) ?? [];
37688
37919
  if (!list.includes(rel)) list.push(rel);
@@ -37708,14 +37939,14 @@ async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
37708
37939
  async function headFile(cwd) {
37709
37940
  let directory = cwd;
37710
37941
  for (let depth = 0; depth < 64; depth++) {
37711
- const dotGit = path39.join(directory, ".git");
37712
- const info = await stat12(dotGit).catch(() => void 0);
37713
- if (info?.isDirectory()) return path39.join(dotGit, "HEAD");
37942
+ const dotGit = path40.join(directory, ".git");
37943
+ const info = await stat13(dotGit).catch(() => void 0);
37944
+ if (info?.isDirectory()) return path40.join(dotGit, "HEAD");
37714
37945
  if (info?.isFile()) {
37715
37946
  const match = /^gitdir:\s*(.+)$/m.exec(await readFile16(dotGit, "utf8").catch(() => ""));
37716
- return match ? path39.join(path39.resolve(directory, match[1].trim()), "HEAD") : void 0;
37947
+ return match ? path40.join(path40.resolve(directory, match[1].trim()), "HEAD") : void 0;
37717
37948
  }
37718
- const parent = path39.dirname(directory);
37949
+ const parent = path40.dirname(directory);
37719
37950
  if (parent === directory) return void 0;
37720
37951
  directory = parent;
37721
37952
  }
@@ -37743,7 +37974,7 @@ async function repositoryBranch(cwd) {
37743
37974
  let value2;
37744
37975
  try {
37745
37976
  countGit("branch");
37746
- const { stdout } = await exec4("git", ["-C", cwd, "--no-pager", "branch", "--show-current"], {
37977
+ const { stdout } = await exec5("git", ["-C", cwd, "--no-pager", "branch", "--show-current"], {
37747
37978
  timeout: 5e3,
37748
37979
  maxBuffer: 65536,
37749
37980
  env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" })
@@ -37802,7 +38033,7 @@ function addListener(ports, address, port, processName, pid) {
37802
38033
  ports.set(`${host}:${port}`, { name: "", port, origin: `http://${host}:${port}`, process: processName, pid });
37803
38034
  }
37804
38035
  async function listenersFromLsof(ports) {
37805
- const result = await exec4(
38036
+ const result = await exec5(
37806
38037
  process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof",
37807
38038
  ["-nP", "-a", "-u", userInfo2().username, "-iTCP", "-sTCP:LISTEN", "-Fpcn"],
37808
38039
  { timeout: 4e3, maxBuffer: 1048576 }
@@ -37818,7 +38049,7 @@ async function listenersFromLsof(ports) {
37818
38049
  }
37819
38050
  }
37820
38051
  async function listenersFromSs(ports) {
37821
- const result = await exec4("ss", ["-ltnpH"], { timeout: 4e3, maxBuffer: 1048576 });
38052
+ const result = await exec5("ss", ["-ltnpH"], { timeout: 4e3, maxBuffer: 1048576 });
37822
38053
  for (const line of result.stdout.split("\n")) {
37823
38054
  const columns = line.trim().split(/\s+/);
37824
38055
  if (columns.length < 4) continue;
@@ -37854,24 +38085,24 @@ async function webServers() {
37854
38085
  return found.sort((a, b) => a.port - b.port);
37855
38086
  }
37856
38087
  async function launchDirectory(raw, activity = [], located = []) {
37857
- if (typeof raw !== "string" || raw.length > 4096 || !path39.isAbsolute(raw) || /[\x00-\x1f\x7f]/.test(raw)) throw new BridgeError(400, "Invalid workspace directory.");
38088
+ if (typeof raw !== "string" || raw.length > 4096 || !path40.isAbsolute(raw) || /[\x00-\x1f\x7f]/.test(raw)) throw new BridgeError(400, "Invalid workspace directory.");
37858
38089
  let dir;
37859
38090
  try {
37860
- dir = await realpath7(raw);
37861
- if (!(await stat12(dir)).isDirectory()) throw new Error();
38091
+ dir = await realpath8(raw);
38092
+ if (!(await stat13(dir)).isDirectory()) throw new Error();
37862
38093
  } catch {
37863
38094
  throw new BridgeError(400, "Workspace directory does not exist.");
37864
38095
  }
37865
- const home = await realpath7(homeDir());
37866
- if (dir === home || dir.startsWith(home + path39.sep)) return dir;
38096
+ const home = await realpath8(homeDir());
38097
+ if (dir === home || dir.startsWith(home + path40.sep)) return dir;
37867
38098
  for (const candidate of located) {
37868
- const real = await realpath7(candidate).catch(() => void 0);
37869
- if (real && (dir === real || dir.startsWith(real + path39.sep))) return dir;
38099
+ const real2 = await realpath8(candidate).catch(() => void 0);
38100
+ if (real2 && (dir === real2 || dir.startsWith(real2 + path40.sep))) return dir;
37870
38101
  }
37871
- const names = [...new Set(dir.split(path39.sep).filter((name) => /^[a-z0-9][a-z0-9-]{0,99}$/.test(name)))];
38102
+ const names = [...new Set(dir.split(path40.sep).filter((name) => /^[a-z0-9][a-z0-9-]{0,99}$/.test(name)))];
37872
38103
  for (const name of names) {
37873
38104
  for (const candidate of await locateProject(name, activity)) {
37874
- if (dir === candidate.directory || dir.startsWith(candidate.directory + path39.sep)) return dir;
38105
+ if (dir === candidate.directory || dir.startsWith(candidate.directory + path40.sep)) return dir;
37875
38106
  }
37876
38107
  }
37877
38108
  throw new BridgeError(403, "Workspace directory must be under home or a located project.");
@@ -37885,7 +38116,7 @@ init_shared();
37885
38116
  import { execFileSync as execFileSync3 } from "node:child_process";
37886
38117
  import * as fs20 from "node:fs";
37887
38118
  import { homedir as homedir10 } from "node:os";
37888
- import * as path40 from "node:path";
38119
+ import * as path41 from "node:path";
37889
38120
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
37890
38121
  var CODE_PACKAGE_HINT = "phren code needs @phren/code: run phren modules enable code";
37891
38122
  var loaded;
@@ -37894,13 +38125,13 @@ function loadedFrom() {
37894
38125
  return resolvedFrom;
37895
38126
  }
37896
38127
  function bridgeRoot2() {
37897
- return process.env.PHREN_BRIDGE_HOME || path40.join(homedir10(), ".local/share/phren/bridge");
38128
+ return process.env.PHREN_BRIDGE_HOME || path41.join(homedir10(), ".local/share/phren/bridge");
37898
38129
  }
37899
- var EXTRA_PATH = [path40.join(homedir10(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
38130
+ var EXTRA_PATH = [path41.join(homedir10(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
37900
38131
  function npmPath() {
37901
- const entries2 = (process.env.PATH ?? "").split(path40.delimiter).filter(Boolean);
38132
+ const entries2 = (process.env.PATH ?? "").split(path41.delimiter).filter(Boolean);
37902
38133
  for (const entry of EXTRA_PATH) if (!entries2.includes(entry) && fs20.existsSync(entry)) entries2.push(entry);
37903
- return entries2.join(path40.delimiter);
38134
+ return entries2.join(path41.delimiter);
37904
38135
  }
37905
38136
  function npm(args, options) {
37906
38137
  const env = { ...process.env, PATH: npmPath() };
@@ -37908,11 +38139,11 @@ function npm(args, options) {
37908
38139
  return String(execFileSync3("npm.cmd", args.map((arg) => `"${arg}"`), { ...options, env, shell: true }) ?? "");
37909
38140
  }
37910
38141
  function packageEntry(directory) {
37911
- const manifest = JSON.parse(fs20.readFileSync(path40.join(directory, "package.json"), "utf8"));
38142
+ const manifest = JSON.parse(fs20.readFileSync(path41.join(directory, "package.json"), "utf8"));
37912
38143
  const exported = typeof manifest.exports === "object" && manifest.exports !== null && "." in manifest.exports ? manifest.exports["."] : manifest.exports;
37913
38144
  const nested = typeof exported === "object" && exported !== null ? exported.default ?? exported.import : exported;
37914
38145
  for (const candidate of [nested, manifest.module, manifest.main, "index.js", "index.mjs"]) {
37915
- if (typeof candidate === "string") return path40.join(directory, candidate);
38146
+ if (typeof candidate === "string") return path41.join(directory, candidate);
37916
38147
  }
37917
38148
  throw new Error(`@phren/code has no entry point in ${directory}.`);
37918
38149
  }
@@ -37922,7 +38153,7 @@ async function importDirectory(directory) {
37922
38153
  function globalPackageDirectory() {
37923
38154
  try {
37924
38155
  const root = npm(["root", "-g"], { encoding: "utf8", timeout: 1e4 }).trim();
37925
- return root ? path40.join(root, "@phren", "code") : void 0;
38156
+ return root ? path41.join(root, "@phren", "code") : void 0;
37926
38157
  } catch {
37927
38158
  return void 0;
37928
38159
  }
@@ -37931,11 +38162,11 @@ async function loadCodePackage(store) {
37931
38162
  if (loaded) return loaded;
37932
38163
  const candidates = [];
37933
38164
  if (process.env.PHREN_CODE_PACKAGE) candidates.push(process.env.PHREN_CODE_PACKAGE);
37934
- candidates.push(path40.join(bridgeRoot2(), "node_modules", "@phren", "code"));
38165
+ candidates.push(path41.join(bridgeRoot2(), "node_modules", "@phren", "code"));
37935
38166
  const root = store || process.env.PHREN_PATH;
37936
- if (root) candidates.push(path40.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
38167
+ if (root) candidates.push(path41.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
37937
38168
  for (const directory of candidates) {
37938
- if (!fs20.existsSync(path40.join(directory, "package.json"))) continue;
38169
+ if (!fs20.existsSync(path41.join(directory, "package.json"))) continue;
37939
38170
  try {
37940
38171
  loaded = await importDirectory(directory);
37941
38172
  resolvedFrom = directory;
@@ -37951,7 +38182,7 @@ async function loadCodePackage(store) {
37951
38182
  if (error62.code !== "ERR_MODULE_NOT_FOUND") throw error62;
37952
38183
  }
37953
38184
  const global = globalPackageDirectory();
37954
- if (global && fs20.existsSync(path40.join(global, "package.json"))) {
38185
+ if (global && fs20.existsSync(path41.join(global, "package.json"))) {
37955
38186
  try {
37956
38187
  loaded = await importDirectory(global);
37957
38188
  resolvedFrom = global;
@@ -37992,7 +38223,7 @@ var projectSchema = external_exports.string().min(1).max(100).refine((value2) =>
37992
38223
  var querySchema = external_exports.string().max(500);
37993
38224
  var symbolSchema = external_exports.string().min(1).max(4600);
37994
38225
  var pathSchema = external_exports.string().min(1).max(4096).refine((value2) => !value2.includes("\0") && !value2.split("/").includes(".."), "Choose a valid file path.");
37995
- var relativePathSchema = pathSchema.refine((value2) => !path41.isAbsolute(value2) && !path41.win32.isAbsolute(value2) && !value2.includes("\\") && !value2.split("/").some((part) => part === "." || part === ""));
38226
+ var relativePathSchema = pathSchema.refine((value2) => !path42.isAbsolute(value2) && !path42.win32.isAbsolute(value2) && !value2.includes("\\") && !value2.split("/").some((part) => part === "." || part === ""));
37996
38227
  var optionalPath = (value2) => value2 ? relativePathSchema.parse(value2) : void 0;
37997
38228
  var offsetSchema = external_exports.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
37998
38229
  var kindSchema = external_exports.enum(KIND_VALUES);
@@ -38080,9 +38311,9 @@ var CodeRoutes = class {
38080
38311
  };
38081
38312
  const midnight = new Date(now);
38082
38313
  midnight.setHours(0, 0, 0, 0);
38083
- const dir = path41.join(bridgeRoot(), "changes");
38314
+ const dir = path42.join(bridgeRoot(), "changes");
38084
38315
  const logs = fs21.existsSync(dir) ? fs21.readdirSync(dir).filter((name) => name.endsWith(".jsonl")) : [];
38085
- const today = logs.map((name) => ({ file: path41.join(dir, name), at: fs21.statSync(path41.join(dir, name)).mtimeMs })).filter((entry) => entry.at >= midnight.getTime()).sort((a, b) => b.at - a.at);
38316
+ const today = logs.map((name) => ({ file: path42.join(dir, name), at: fs21.statSync(path42.join(dir, name)).mtimeMs })).filter((entry) => entry.at >= midnight.getTime()).sort((a, b) => b.at - a.at);
38086
38317
  for (const log2 of today) {
38087
38318
  for (const line of fs21.readFileSync(log2.file, "utf8").split("\n")) {
38088
38319
  if (!line.trim()) continue;
@@ -38143,7 +38374,7 @@ var CodeRoutes = class {
38143
38374
  for (const file2 of untracked) {
38144
38375
  let count2 = 0;
38145
38376
  try {
38146
- count2 = fs21.readFileSync(path41.join(root, file2), "utf8").split("\n").length;
38377
+ count2 = fs21.readFileSync(path42.join(root, file2), "utf8").split("\n").length;
38147
38378
  } catch {
38148
38379
  continue;
38149
38380
  }
@@ -38173,7 +38404,7 @@ var CodeRoutes = class {
38173
38404
  const project = projectSchema.parse(projectValue ?? "");
38174
38405
  const { codeDatabasePath } = await requireCodePackage(this.store);
38175
38406
  const file2 = codeDatabasePath(this.store, project);
38176
- await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path84) => rm4(path84, { force: true })));
38407
+ await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path85) => rm4(path85, { force: true })));
38177
38408
  return { project, disabled: true };
38178
38409
  }
38179
38410
  async reindex(projectValue) {
@@ -38207,7 +38438,7 @@ var CodeRoutes = class {
38207
38438
  } catch {
38208
38439
  throw new BridgeError(400, "Choose valid paths.");
38209
38440
  }
38210
- const paths = external_exports.array(pathSchema.refine((value2) => !path41.isAbsolute(value2) && !path41.win32.isAbsolute(value2) && !value2.split(/[\\/]/).includes(".."))).min(1).max(200).parse(raw);
38441
+ const paths = external_exports.array(pathSchema.refine((value2) => !path42.isAbsolute(value2) && !path42.win32.isAbsolute(value2) && !value2.split(/[\\/]/).includes(".."))).min(1).max(200).parse(raw);
38211
38442
  const result = await (await requireCodePackage(this.store)).outlineSummary(this.store, project, [...new Set(paths)]);
38212
38443
  if (!result.available) throw noIndex(project);
38213
38444
  return { project, entries: result.value };
@@ -38282,7 +38513,7 @@ var CodeReindexer = class {
38282
38513
  const { codeDatabasePath, resolveRepoRoot } = await requireCodePackage(this.store);
38283
38514
  const result = [];
38284
38515
  for (const directory of getProjectDirs(this.store)) {
38285
- const project = path41.basename(directory);
38516
+ const project = path42.basename(directory);
38286
38517
  if (!fs21.existsSync(codeDatabasePath(this.store, project))) continue;
38287
38518
  try {
38288
38519
  result.push({ project, root: fs21.realpathSync(resolveRepoRoot(this.store, project)) });
@@ -38324,13 +38555,13 @@ var CodeReindexer = class {
38324
38555
  };
38325
38556
  function readHead(root) {
38326
38557
  try {
38327
- const dotGit = path41.join(root, ".git");
38558
+ const dotGit = path42.join(root, ".git");
38328
38559
  const gitDirectory2 = fs21.statSync(dotGit).isDirectory() ? dotGit : (() => {
38329
38560
  const match = /^gitdir:\s*(.+)$/m.exec(fs21.readFileSync(dotGit, "utf8"));
38330
- return match ? path41.resolve(root, match[1]) : void 0;
38561
+ return match ? path42.resolve(root, match[1]) : void 0;
38331
38562
  })();
38332
38563
  if (!gitDirectory2) return void 0;
38333
- return fs21.readFileSync(path41.join(gitDirectory2, "HEAD"), "utf8").trim();
38564
+ return fs21.readFileSync(path42.join(gitDirectory2, "HEAD"), "utf8").trim();
38334
38565
  } catch {
38335
38566
  return void 0;
38336
38567
  }
@@ -38340,7 +38571,7 @@ function readHead(root) {
38340
38571
  init_herdr();
38341
38572
  init_protocol();
38342
38573
  init_transcripts();
38343
- import { open as open7 } from "node:fs/promises";
38574
+ import { open as open8 } from "node:fs/promises";
38344
38575
  import { constants as constants2 } from "node:fs";
38345
38576
  var MAX_TAIL_BYTES = 262144;
38346
38577
  var MAX_SESSIONS = 32;
@@ -38373,15 +38604,15 @@ function codexContext(tail, startsAtBeginning) {
38373
38604
  var ContextUsageReader = class {
38374
38605
  cache = /* @__PURE__ */ new Map();
38375
38606
  async read(file2, session) {
38376
- const handle = await open7(file2, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
38607
+ const handle = await open8(file2, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
38377
38608
  try {
38378
38609
  const metadata = await handle.stat();
38379
38610
  if (!metadata.isFile()) return void 0;
38380
38611
  const key2 = `codex:${session}:${file2}`;
38381
- const stat26 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
38612
+ const stat27 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
38382
38613
  const cached2 = this.cache.get(key2);
38383
38614
  this.cache.delete(key2);
38384
- if (cached2?.stat === stat26) {
38615
+ if (cached2?.stat === stat27) {
38385
38616
  this.cache.set(key2, cached2);
38386
38617
  return cached2.percent;
38387
38618
  }
@@ -38392,7 +38623,7 @@ var ContextUsageReader = class {
38392
38623
  const after = await handle.stat();
38393
38624
  if (after.size !== metadata.size || after.mtimeMs !== metadata.mtimeMs || after.ctimeMs !== metadata.ctimeMs) return void 0;
38394
38625
  const percent = codexContext(tail, start === 0);
38395
- this.cache.set(key2, { stat: stat26, percent });
38626
+ this.cache.set(key2, { stat: stat27, percent });
38396
38627
  while (this.cache.size > MAX_SESSIONS) this.cache.delete(this.cache.keys().next().value);
38397
38628
  return percent;
38398
38629
  } finally {
@@ -38469,33 +38700,33 @@ init_zod();
38469
38700
  init_logger();
38470
38701
  init_project_config();
38471
38702
  import { randomUUID as randomUUID9 } from "node:crypto";
38472
- import { lstat as lstat12, mkdir as mkdir12, readFile as readFile21, readdir as readdir9, realpath as realpath9, stat as stat14 } from "node:fs/promises";
38473
- import path49 from "node:path";
38703
+ import { lstat as lstat12, mkdir as mkdir12, readFile as readFile21, readdir as readdir10, realpath as realpath10, stat as stat15 } from "node:fs/promises";
38704
+ import path50 from "node:path";
38474
38705
 
38475
38706
  // src/bridge/computers.ts
38476
- import { execFile as execFile8 } from "node:child_process";
38707
+ import { execFile as execFile9 } from "node:child_process";
38477
38708
  import { chmod as chmod3, lstat as lstat10, mkdir as mkdir11, mkdtemp as mkdtemp2, readFile as readFile19, rename as rename6, rm as rm5, writeFile as writeFile5 } from "node:fs/promises";
38478
38709
  import { homedir as homedir14 } from "node:os";
38479
- import path47 from "node:path";
38480
- import { promisify as promisify7 } from "node:util";
38710
+ import path48 from "node:path";
38711
+ import { promisify as promisify8 } from "node:util";
38481
38712
 
38482
38713
  // src/bridge/install.ts
38483
38714
  init_shared();
38484
- import { execFile as execFile7 } from "node:child_process";
38715
+ import { execFile as execFile8 } from "node:child_process";
38485
38716
 
38486
38717
  // src/bridge/usage.ts
38487
38718
  init_home_paths();
38488
38719
  init_fanouts();
38489
38720
  init_protocol();
38490
38721
  init_terminal_text();
38491
- import { execFile as execFile6, spawn as spawn2 } from "node:child_process";
38722
+ import { execFile as execFile7, spawn as spawn2 } from "node:child_process";
38492
38723
  import { createHash as createHash9 } from "node:crypto";
38493
- import { lstat as lstat8, open as open8, readFile as readFile17, readdir as readdir8, realpath as realpath8, stat as stat13 } from "node:fs/promises";
38724
+ import { lstat as lstat8, open as open9, readFile as readFile17, readdir as readdir9, realpath as realpath9, stat as stat14 } from "node:fs/promises";
38494
38725
  import { homedir as homedir11 } from "node:os";
38495
- import path43 from "node:path";
38496
- import { promisify as promisify5 } from "node:util";
38497
- var exec5 = promisify5(execFile6);
38498
- var claudeFile = () => path43.join(bridgeRoot(), "usage", "claude.json");
38726
+ import path44 from "node:path";
38727
+ import { promisify as promisify6 } from "node:util";
38728
+ var exec6 = promisify6(execFile7);
38729
+ var claudeFile = () => path44.join(bridgeRoot(), "usage", "claude.json");
38499
38730
  var safeText = (v) => typeof v === "string" ? v.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 100) : void 0;
38500
38731
  function window(id2, name, percent, reset) {
38501
38732
  if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100) return;
@@ -38538,7 +38769,7 @@ function openCodeUsage(output2, now = /* @__PURE__ */ new Date()) {
38538
38769
  }
38539
38770
  async function readOpenCodeUsage(executable = "opencode", now = /* @__PURE__ */ new Date()) {
38540
38771
  try {
38541
- const { stdout } = await exec5(executable, ["stats", "--days", "7", "--pure"], { timeout: 12e3, maxBuffer: 1048576 });
38772
+ const { stdout } = await exec6(executable, ["stats", "--days", "7", "--pure"], { timeout: 12e3, maxBuffer: 1048576 });
38542
38773
  return openCodeUsage(stdout, now);
38543
38774
  } catch (error62) {
38544
38775
  return { source: "opencode", windows: [], message: openCodeFailure(error62) };
@@ -38554,16 +38785,16 @@ function openCodeFailure(error62) {
38554
38785
  const exit = typeof failure2?.code === "number" ? ` (exit ${failure2.code})` : "";
38555
38786
  return `opencode stats --days 7 failed${exit}${said ? `: ${said}` : ""}. Run it on this computer to see why.`;
38556
38787
  }
38557
- var openCodeAuthFile = () => path43.join(
38558
- process.env.OPENCODE_DATA_DIR || path43.join(process.env.XDG_DATA_HOME || path43.join(homedir11(), ".local", "share"), "opencode"),
38788
+ var openCodeAuthFile = () => path44.join(
38789
+ process.env.OPENCODE_DATA_DIR || path44.join(process.env.XDG_DATA_HOME || path44.join(homedir11(), ".local", "share"), "opencode"),
38559
38790
  "auth.json"
38560
38791
  );
38561
38792
  async function readOpenRouterKey() {
38562
38793
  try {
38563
- const handle = await open8(openCodeAuthFile(), "r");
38794
+ const handle = await open9(openCodeAuthFile(), "r");
38564
38795
  try {
38565
- const stat26 = await handle.stat();
38566
- if (!stat26.isFile() || stat26.size > 65536) return void 0;
38796
+ const stat27 = await handle.stat();
38797
+ if (!stat27.isFile() || stat27.size > 65536) return void 0;
38567
38798
  const key2 = object2(object2(JSON.parse(await handle.readFile("utf8"))).openrouter).key;
38568
38799
  return typeof key2 === "string" && key2.length >= 16 && key2.length <= 4096 && !/[\x00-\x1f\x7f]/.test(key2) ? key2 : void 0;
38569
38800
  } finally {
@@ -38575,7 +38806,7 @@ async function readOpenRouterKey() {
38575
38806
  }
38576
38807
  async function readOpenCodeGoKey() {
38577
38808
  try {
38578
- const handle = await open8(openCodeAuthFile(), "r");
38809
+ const handle = await open9(openCodeAuthFile(), "r");
38579
38810
  try {
38580
38811
  const metadata = await handle.stat();
38581
38812
  if (!metadata.isFile() || metadata.size > 65536) return void 0;
@@ -38748,9 +38979,9 @@ async function containedRegularFile(root, candidate, maximum) {
38748
38979
  try {
38749
38980
  const link = await lstat8(candidate);
38750
38981
  if (!link.isFile() || link.isSymbolicLink() || link.size > maximum) return void 0;
38751
- const resolved = await realpath8(candidate);
38752
- if (!resolved.startsWith(root + path43.sep)) return void 0;
38753
- const metadata = await stat13(resolved);
38982
+ const resolved = await realpath9(candidate);
38983
+ if (!resolved.startsWith(root + path44.sep)) return void 0;
38984
+ const metadata = await stat14(resolved);
38754
38985
  return metadata.isFile() && metadata.size <= maximum ? resolved : void 0;
38755
38986
  } catch {
38756
38987
  return void 0;
@@ -38780,14 +39011,14 @@ async function readOpenCodeGoLedger(root = fanoutRoot(), now = /* @__PURE__ */ n
38780
39011
  const totals = /* @__PURE__ */ new Map();
38781
39012
  let directory;
38782
39013
  try {
38783
- directory = await realpath8(root);
39014
+ directory = await realpath9(root);
38784
39015
  } catch {
38785
39016
  return totals;
38786
39017
  }
38787
- const names = (await readdir8(directory).catch(() => [])).slice(0, MAX_GO_JOBS);
39018
+ const names = (await readdir9(directory).catch(() => [])).slice(0, MAX_GO_JOBS);
38788
39019
  for (const name of names) {
38789
39020
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name)) continue;
38790
- const manifestFile = await containedRegularFile(directory, path43.join(directory, name, "manifest.json"), MAX_GO_MANIFEST_BYTES);
39021
+ const manifestFile = await containedRegularFile(directory, path44.join(directory, name, "manifest.json"), MAX_GO_MANIFEST_BYTES);
38791
39022
  if (!manifestFile) continue;
38792
39023
  let manifest;
38793
39024
  try {
@@ -38798,9 +39029,9 @@ async function readOpenCodeGoLedger(root = fanoutRoot(), now = /* @__PURE__ */ n
38798
39029
  const model = goModel(manifest.model);
38799
39030
  const eventLog = typeof manifest.eventLog === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jsonl$/.test(manifest.eventLog) ? manifest.eventLog : void 0;
38800
39031
  if (manifest.provider !== "opencode" || !model || !eventLog) continue;
38801
- const jobRoot = await realpath8(path43.join(directory, name)).catch(() => void 0);
38802
- if (!jobRoot || !jobRoot.startsWith(directory + path43.sep)) continue;
38803
- const eventsFile = await containedRegularFile(jobRoot, path43.join(jobRoot, eventLog), MAX_GO_EVENTS_BYTES);
39032
+ const jobRoot = await realpath9(path44.join(directory, name)).catch(() => void 0);
39033
+ if (!jobRoot || !jobRoot.startsWith(directory + path44.sep)) continue;
39034
+ const eventsFile = await containedRegularFile(jobRoot, path44.join(jobRoot, eventLog), MAX_GO_EVENTS_BYTES);
38804
39035
  if (!eventsFile) continue;
38805
39036
  let events;
38806
39037
  try {
@@ -38977,8 +39208,8 @@ function claudeScopedWindows(config3, now = /* @__PURE__ */ new Date()) {
38977
39208
  }
38978
39209
  return windows;
38979
39210
  }
38980
- var claudeConfigFile = () => path43.join(process.env.CLAUDE_CONFIG_DIR?.trim() ? claudeConfigDir() : homeDir(), ".claude.json");
38981
- var claudeCredentialsFile = () => path43.join(claudeConfigDir(), ".credentials.json");
39211
+ var claudeConfigFile = () => path44.join(process.env.CLAUDE_CONFIG_DIR?.trim() ? claudeConfigDir() : homeDir(), ".claude.json");
39212
+ var claudeCredentialsFile = () => path44.join(claudeConfigDir(), ".credentials.json");
38982
39213
  function claudeOAuthUsage(value2, now = /* @__PURE__ */ new Date()) {
38983
39214
  const limits = object2(value2).limits;
38984
39215
  const windows = [];
@@ -39009,7 +39240,7 @@ function claudeOAuthUsage(value2, now = /* @__PURE__ */ new Date()) {
39009
39240
  ...!windows.length ? { message: "Claude has not reported account limits on this computer." } : {}
39010
39241
  };
39011
39242
  }
39012
- async function readClaudeToken(execSecurity = exec5, platform = process.platform) {
39243
+ async function readClaudeToken(execSecurity = exec6, platform = process.platform) {
39013
39244
  const parse4 = (raw) => {
39014
39245
  if (raw.length > 16384) return void 0;
39015
39246
  const oauth = object2(object2(JSON.parse(raw)).claudeAiOauth);
@@ -39185,10 +39416,10 @@ var AccountUsageReader = class {
39185
39416
  async snapshotClaude() {
39186
39417
  let claude2 = { source: "claude", windows: [], message: "Usage appears after Claude Code replies on this computer. Run phren bridge install if usage reporting is not set up yet." };
39187
39418
  try {
39188
- const handle = await open8(claudeFile(), "r");
39419
+ const handle = await open9(claudeFile(), "r");
39189
39420
  try {
39190
- const stat26 = await handle.stat();
39191
- if (!stat26.isFile() || stat26.size > 16384) throw new Error("Invalid usage snapshot");
39421
+ const stat27 = await handle.stat();
39422
+ if (!stat27.isFile() || stat27.size > 16384) throw new Error("Invalid usage snapshot");
39192
39423
  const saved = object2(JSON.parse(await handle.readFile("utf8")));
39193
39424
  const date5 = new Date(String(saved.updatedAt));
39194
39425
  if (!Number.isFinite(date5.getTime()) || date5.getTime() > this.now() + 6e4) throw new Error("Invalid usage timestamp");
@@ -39199,10 +39430,10 @@ var AccountUsageReader = class {
39199
39430
  } catch {
39200
39431
  }
39201
39432
  try {
39202
- const handle = await open8(claudeConfigFile(), "r");
39433
+ const handle = await open9(claudeConfigFile(), "r");
39203
39434
  try {
39204
- const stat26 = await handle.stat();
39205
- if (!stat26.isFile() || stat26.size > 16777216) throw new Error("Invalid Claude config");
39435
+ const stat27 = await handle.stat();
39436
+ if (!stat27.isFile() || stat27.size > 16777216) throw new Error("Invalid Claude config");
39206
39437
  const scoped = claudeScopedWindows(JSON.parse(await handle.readFile("utf8")), new Date(this.now())).filter((entry) => !claude2.windows.some((existing) => existing.id === entry.id));
39207
39438
  if (scoped.length) claude2 = { ...claude2, windows: [...claude2.windows, ...scoped], message: void 0 };
39208
39439
  } finally {
@@ -39262,11 +39493,11 @@ async function captureClaudeUsage(original) {
39262
39493
  init_home_paths();
39263
39494
  init_protocol();
39264
39495
  init_herdr();
39265
- import { chmod as chmod2, copyFile as copyFile2, mkdir as mkdir10, open as open9, readFile as readFile18, rename as rename5, symlink, unlink as unlink4, lstat as lstat9, writeFile as writeFile4 } from "node:fs/promises";
39496
+ import { chmod as chmod2, copyFile as copyFile2, mkdir as mkdir10, open as open10, readFile as readFile18, rename as rename5, symlink, unlink as unlink4, lstat as lstat9, writeFile as writeFile4 } from "node:fs/promises";
39266
39497
  import { homedir as homedir13 } from "node:os";
39267
- import path46 from "node:path";
39498
+ import path47 from "node:path";
39268
39499
  import { fileURLToPath as fileURLToPath5 } from "node:url";
39269
- import { promisify as promisify6 } from "node:util";
39500
+ import { promisify as promisify7 } from "node:util";
39270
39501
 
39271
39502
  // src/bridge/transport.ts
39272
39503
  init_shared();
@@ -39277,17 +39508,17 @@ import { connect as connect3 } from "node:net";
39277
39508
  import { request as request3 } from "node:http";
39278
39509
  import { spawn as spawn3 } from "node:child_process";
39279
39510
  import { homedir as homedir12 } from "node:os";
39280
- import path44 from "node:path";
39511
+ import path45 from "node:path";
39281
39512
  function decodeShellDirectory(encoded) {
39282
39513
  if (!/^[A-Za-z0-9_-]{1,8192}$/.test(encoded)) return void 0;
39283
39514
  const decoded = Buffer.from(encoded, "base64url");
39284
39515
  if (decoded.toString("base64url") !== encoded) return void 0;
39285
39516
  const dir = decoded.toString("utf8");
39286
- return path44.isAbsolute(dir) && !/[\x00-\x1f\x7f]/.test(dir) && !dir.includes("\uFFFD") ? dir : void 0;
39517
+ return path45.isAbsolute(dir) && !/[\x00-\x1f\x7f]/.test(dir) && !dir.includes("\uFFFD") ? dir : void 0;
39287
39518
  }
39288
39519
  function shellEnvironment(base = process.env) {
39289
39520
  const env = Object.fromEntries(Object.entries(base).filter(([key2]) => !key2.startsWith("HERDR_") && key2 !== "TMUX" && key2 !== "TMUX_PANE"));
39290
- env.PATH = [path44.join(homedir12(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":");
39521
+ env.PATH = [path45.join(homedir12(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":");
39291
39522
  return env;
39292
39523
  }
39293
39524
  async function health() {
@@ -39348,7 +39579,7 @@ async function dispatch(command) {
39348
39579
  };
39349
39580
  if (command === "phren-hook v1 pipe") {
39350
39581
  requireHook();
39351
- await pipe2({ path: socketPath() }, path44.join(bridgeRoot(), "gateway.json"), true);
39582
+ await pipe2({ path: socketPath() }, path45.join(bridgeRoot(), "gateway.json"), true);
39352
39583
  return;
39353
39584
  }
39354
39585
  const preview = /^phren-hook v1 web (127\.0\.0\.1|::1) ([1-9][0-9]{0,4})$/.exec(command);
@@ -39364,7 +39595,7 @@ async function dispatch(command) {
39364
39595
  if (!raw) throw new BridgeError(403, "The shell folder is not a valid absolute path.");
39365
39596
  const cwd = await launchDirectory(raw);
39366
39597
  if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("Request an SSH terminal first.");
39367
- const login = process.env.SHELL && path44.isAbsolute(process.env.SHELL) ? process.env.SHELL : "/bin/sh";
39598
+ const login = process.env.SHELL && path45.isAbsolute(process.env.SHELL) ? process.env.SHELL : "/bin/sh";
39368
39599
  const [file2, args] = shell[2] ? [shell[2], []] : [login, ["-l"]];
39369
39600
  await attach(file2, args, { cwd, env: shellEnvironment() }, shell[2] ? `${shell[2]} exited.` : "The shell exited.");
39370
39601
  return;
@@ -39398,7 +39629,7 @@ async function attach(file2, args, options, failure2) {
39398
39629
  }
39399
39630
 
39400
39631
  // src/bridge/install.ts
39401
- var exec6 = promisify6(execFile7);
39632
+ var exec7 = promisify7(execFile8);
39402
39633
  var label = "com.phren.hook";
39403
39634
  var unit = "phren-hook.service";
39404
39635
  var forcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch"';
@@ -39443,7 +39674,7 @@ var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&
39443
39674
  var systemdQuote = (s) => '"' + s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%") + '"';
39444
39675
  async function commandOutput(file2, args, env) {
39445
39676
  try {
39446
- const { stdout, stderr } = await exec6(file2, args, { env, timeout: 2e3 });
39677
+ const { stdout, stderr } = await exec7(file2, args, { env, timeout: 2e3 });
39447
39678
  return stdout + stderr || void 0;
39448
39679
  } catch (error62) {
39449
39680
  const value2 = error62;
@@ -39476,9 +39707,9 @@ ${pipe3}exec ${quote2(node2)} ${quote2(bundle)} ssh
39476
39707
  }
39477
39708
  async function activate(version3) {
39478
39709
  const root = bridgeRoot();
39479
- const next = path46.join(root, `current-${process.pid}`);
39480
- await symlink(path46.join("versions", version3), next);
39481
- await rename5(next, path46.join(root, "current"));
39710
+ const next = path47.join(root, `current-${process.pid}`);
39711
+ await symlink(path47.join("versions", version3), next);
39712
+ await rename5(next, path47.join(root, "current"));
39482
39713
  }
39483
39714
  function launchDomain(uid, guiSession2) {
39484
39715
  return guiSession2 ? `gui/${uid}` : `user/${uid}`;
@@ -39486,15 +39717,15 @@ function launchDomain(uid, guiSession2) {
39486
39717
  function launchCommands(domain2, plist) {
39487
39718
  return [`launchctl bootout ${domain2}/${label}`, `launchctl bootstrap ${domain2} ${quote2(plist)}`, `launchctl kickstart -k ${domain2}/${label}`];
39488
39719
  }
39489
- var launchAgentPlist = () => path46.join(homedir13(), "Library/LaunchAgents", `${label}.plist`);
39720
+ var launchAgentPlist = () => path47.join(homedir13(), "Library/LaunchAgents", `${label}.plist`);
39490
39721
  async function guiSession(uid) {
39491
- return exec6("launchctl", ["print", `gui/${uid}`]).then(() => true, () => false);
39722
+ return exec7("launchctl", ["print", `gui/${uid}`]).then(() => true, () => false);
39492
39723
  }
39493
39724
  async function stopService() {
39494
39725
  if (process.platform === "darwin") {
39495
- for (const gui of [true, false]) await exec6("launchctl", ["bootout", `${launchDomain(process.getuid(), gui)}/${label}`]).catch(() => {
39726
+ for (const gui of [true, false]) await exec7("launchctl", ["bootout", `${launchDomain(process.getuid(), gui)}/${label}`]).catch(() => {
39496
39727
  });
39497
- } else await exec6("systemctl", ["--user", "stop", unit]).catch(() => {
39728
+ } else await exec7("systemctl", ["--user", "stop", unit]).catch(() => {
39498
39729
  });
39499
39730
  }
39500
39731
  async function startService() {
@@ -39502,7 +39733,7 @@ async function startService() {
39502
39733
  const uid = process.getuid(), gui = await guiSession(uid), domain2 = launchDomain(uid, gui);
39503
39734
  for (let attempt = 0; ; attempt++) {
39504
39735
  try {
39505
- await exec6("launchctl", ["bootstrap", domain2, launchAgentPlist()]);
39736
+ await exec7("launchctl", ["bootstrap", domain2, launchAgentPlist()]);
39506
39737
  break;
39507
39738
  } catch (error62) {
39508
39739
  const stderr = String(error62.stderr ?? "");
@@ -39515,12 +39746,12 @@ To start it by hand:
39515
39746
  ${launchCommands(domain2, launchAgentPlist()).join("\n ")}`);
39516
39747
  }
39517
39748
  }
39518
- await exec6("launchctl", ["kickstart", `${domain2}/${label}`]).catch(() => {
39749
+ await exec7("launchctl", ["kickstart", `${domain2}/${label}`]).catch(() => {
39519
39750
  });
39520
39751
  if (!gui) console.log(`No one is logged in at this Mac's screen, so the Phren Hook runs in ${domain2}. After a screen login, run phren bridge install again to move it into gui/${uid}.`);
39521
39752
  } else {
39522
- await exec6("systemctl", ["--user", "daemon-reload"]);
39523
- await exec6("systemctl", ["--user", "enable", "--now", unit]);
39753
+ await exec7("systemctl", ["--user", "daemon-reload"]);
39754
+ await exec7("systemctl", ["--user", "enable", "--now", unit]);
39524
39755
  }
39525
39756
  }
39526
39757
  async function install(version3, noService = false) {
@@ -39528,52 +39759,52 @@ async function install(version3, noService = false) {
39528
39759
  if (!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version3)) throw new Error("Invalid helper version.");
39529
39760
  const modules = activateModules(defaultPhrenPath(), void 0, true);
39530
39761
  if (!modules.has("hook")) throw new Error(disabledHint("hook"));
39531
- const root = bridgeRoot(), herdr = herdrRoot(), versions = path46.join(root, "versions");
39762
+ const root = bridgeRoot(), herdr = herdrRoot(), versions = path47.join(root, "versions");
39532
39763
  await mkdir10(versions, { recursive: true, mode: 448 });
39533
39764
  await chmod2(root, 448);
39534
- const serviceLog = path46.join(root, "service.log");
39535
- const log2 = await open9(serviceLog, "a", 384);
39765
+ const serviceLog = path47.join(root, "service.log");
39766
+ const log2 = await open10(serviceLog, "a", 384);
39536
39767
  try {
39537
39768
  await log2.chmod(384);
39538
39769
  } finally {
39539
39770
  await log2.close();
39540
39771
  }
39541
- const hookEdits = await planAgentHooks(path46.join(root, "current/bridge-hook.mjs"), false, modules);
39772
+ const hookEdits = await planAgentHooks(path47.join(root, "current/bridge-hook.mjs"), false, modules);
39542
39773
  const own2 = fileURLToPath5(import.meta.url);
39543
- const bundle = own2.endsWith("bridge-hook.mjs") ? own2 : path46.join(path46.dirname(own2), "..", "bridge-hook.mjs");
39544
- const destination2 = path46.join(versions, version3);
39774
+ const bundle = own2.endsWith("bridge-hook.mjs") ? own2 : path47.join(path47.dirname(own2), "..", "bridge-hook.mjs");
39775
+ const destination2 = path47.join(versions, version3);
39545
39776
  await mkdir10(destination2, { recursive: true, mode: 448 });
39546
- const installedBundle = path46.join(destination2, "bridge-hook.mjs");
39777
+ const installedBundle = path47.join(destination2, "bridge-hook.mjs");
39547
39778
  const previousBundle = await missingFile(readFile18(installedBundle));
39548
39779
  const stagedBundle = installedBundle + `.phren-${process.pid}`;
39549
39780
  await copyFile2(bundle, stagedBundle);
39550
39781
  await rename5(stagedBundle, installedBundle);
39551
- const previous = await readFile18(path46.join(root, "installed.json"), "utf8").then((v) => JSON.parse(v)).catch(() => null);
39782
+ const previous = await readFile18(path47.join(root, "installed.json"), "utf8").then((v) => JSON.parse(v)).catch(() => null);
39552
39783
  const gateway = await detectGateway();
39553
- await atomic(path46.join(root, "dispatch"), gatewayScript(gateway, {
39784
+ await atomic(path47.join(root, "dispatch"), gatewayScript(gateway, {
39554
39785
  root,
39555
39786
  herdr,
39556
39787
  store: modules.store,
39557
39788
  profile: modules.profile,
39558
39789
  node: process.execPath,
39559
- bundle: path46.join(root, "current/bridge-hook.mjs"),
39790
+ bundle: path47.join(root, "current/bridge-hook.mjs"),
39560
39791
  socket: socketPath(),
39561
- timing: path46.join(root, "gateway.json")
39792
+ timing: path47.join(root, "gateway.json")
39562
39793
  }), 448);
39563
- const environmentPath = [path46.dirname(process.execPath), path46.join(homedir13(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"].join(":");
39564
- const program = path46.join(root, "current/bridge-hook.mjs");
39794
+ const environmentPath = [path47.dirname(process.execPath), path47.join(homedir13(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"].join(":");
39795
+ const program = path47.join(root, "current/bridge-hook.mjs");
39565
39796
  if (!noService) {
39566
39797
  if (process.platform === "darwin") {
39567
- const folder = path46.join(homedir13(), "Library/LaunchAgents");
39798
+ const folder = path47.join(homedir13(), "Library/LaunchAgents");
39568
39799
  await mkdir10(folder, { recursive: true });
39569
- await atomic(path46.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>
39800
+ await atomic(path47.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>
39570
39801
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
39571
- <plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(program)}</string><string>serve</string></array><key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string><key>PHREN_HERDR_HOME</key><string>${xml(herdr)}</string><key>PHREN_PATH</key><string>${xml(modules.store)}</string><key>PHREN_PROFILE</key><string>${xml(modules.profile)}</string></dict><key>StandardErrorPath</key><string>${xml(path46.join(root, "service.log"))}</string></dict></plist>
39802
+ <plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(program)}</string><string>serve</string></array><key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string><key>PHREN_HERDR_HOME</key><string>${xml(herdr)}</string><key>PHREN_PATH</key><string>${xml(modules.store)}</string><key>PHREN_PROFILE</key><string>${xml(modules.profile)}</string></dict><key>StandardErrorPath</key><string>${xml(path47.join(root, "service.log"))}</string></dict></plist>
39572
39803
  `);
39573
39804
  } else {
39574
- const folder = path46.join(homedir13(), ".config/systemd/user");
39805
+ const folder = path47.join(homedir13(), ".config/systemd/user");
39575
39806
  await mkdir10(folder, { recursive: true });
39576
- await atomic(path46.join(folder, unit), `[Unit]
39807
+ await atomic(path47.join(folder, unit), `[Unit]
39577
39808
  Description=Phren Hook
39578
39809
  [Service]
39579
39810
  ExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve
@@ -39615,7 +39846,7 @@ WantedBy=default.target
39615
39846
  if ((await Promise.resolve().then(() => (init_agent_package(), agent_package_exports))).agentInstalled()) {
39616
39847
  console.log("phren-agent chat: found; it reports to this Hook itself, so restart any phren-agent session started before now.");
39617
39848
  }
39618
- const keys = path46.join(homedir13(), ".ssh/authorized_keys");
39849
+ const keys = path47.join(homedir13(), ".ssh/authorized_keys");
39619
39850
  const keyStat = await lstat9(keys).catch(() => null);
39620
39851
  if (keyStat && !keyStat.isSymbolicLink() && keyStat.isFile()) {
39621
39852
  const before = await readFile18(keys, "utf8"), after = upgradeKeys(before);
@@ -39626,7 +39857,7 @@ WantedBy=default.target
39626
39857
  }
39627
39858
  console.log(`Updated ${after.changed} Phren iPhone key(s); other keys were preserved.`);
39628
39859
  }
39629
- await atomic(path46.join(root, "installed.json"), JSON.stringify({ version: version3, previous: previous?.version === version3 ? previous.previous : previous?.version, node: process.execPath, gateway }, null, 2) + "\n");
39860
+ await atomic(path47.join(root, "installed.json"), JSON.stringify({ version: version3, previous: previous?.version === version3 ? previous.previous : previous?.version, node: process.execPath, gateway }, null, 2) + "\n");
39630
39861
  console.log("Agent hooks installed. In Codex, review the new Phren entries in /hooks. Existing agents may need to resume before new hooks load.");
39631
39862
  console.log(`SSH gateway: ${gateway}${gateway === "node" ? " (no socat or nc -U found)" : ""}.`);
39632
39863
  console.log(`Phren Hook ${version3} installed${noService ? " (service not started)" : " and running"}. Run phren bridge doctor.`);
@@ -39649,14 +39880,14 @@ async function uninstall() {
39649
39880
  if (process.platform === "darwin") await unlink4(launchAgentPlist()).catch(() => {
39650
39881
  });
39651
39882
  else {
39652
- await exec6("systemctl", ["--user", "disable", unit]).catch(() => {
39883
+ await exec7("systemctl", ["--user", "disable", unit]).catch(() => {
39653
39884
  });
39654
- await unlink4(path46.join(homedir13(), ".config/systemd/user", unit)).catch(() => {
39885
+ await unlink4(path47.join(homedir13(), ".config/systemd/user", unit)).catch(() => {
39655
39886
  });
39656
- await exec6("systemctl", ["--user", "daemon-reload"]).catch(() => {
39887
+ await exec7("systemctl", ["--user", "daemon-reload"]).catch(() => {
39657
39888
  });
39658
39889
  }
39659
- await applyAgentHooks(await planAgentHooks(path46.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
39890
+ await applyAgentHooks(await planAgentHooks(path47.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
39660
39891
  await applyOpencodePlugin(true);
39661
39892
  console.log("Phren Hook stopped and its background service removed. Remove phren-iphone, phren-android and phren-computer keys from authorized_keys to revoke device access. Local data remains in " + bridgeRoot());
39662
39893
  }
@@ -39671,9 +39902,9 @@ async function missingFile(operation) {
39671
39902
  async function planAgentHooks(program, remove = false, modules) {
39672
39903
  const edits = [];
39673
39904
  for (const [source, file2] of [
39674
- ["codex", path46.join(codexHome(), "hooks.json")],
39675
- ["claude", path46.join(claudeConfigDir(), "settings.json")],
39676
- ["copilot", path46.join(process.env.COPILOT_HOME || path46.join(homedir13(), ".copilot"), "hooks/phren.json")]
39905
+ ["codex", path47.join(codexHome(), "hooks.json")],
39906
+ ["claude", path47.join(claudeConfigDir(), "settings.json")],
39907
+ ["copilot", path47.join(process.env.COPILOT_HOME || path47.join(homedir13(), ".copilot"), "hooks/phren.json")]
39677
39908
  ]) {
39678
39909
  const metadata = await missingFile(lstat9(file2));
39679
39910
  if (metadata && (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 2097152)) {
@@ -39723,7 +39954,7 @@ async function planAgentHooks(program, remove = false, modules) {
39723
39954
  }
39724
39955
  return edits;
39725
39956
  }
39726
- var opencodePluginsDir = () => path46.join(process.env.XDG_CONFIG_HOME || path46.join(homedir13(), ".config"), "opencode", "plugins");
39957
+ var opencodePluginsDir = () => path47.join(process.env.XDG_CONFIG_HOME || path47.join(homedir13(), ".config"), "opencode", "plugins");
39727
39958
  var OPENCODE_PLUGIN_MARKER = "// Installed by Phren Hook";
39728
39959
  function opencodePluginNeedsWrite(existing, source) {
39729
39960
  if (existing === void 0) return true;
@@ -39732,10 +39963,10 @@ function opencodePluginNeedsWrite(existing, source) {
39732
39963
  }
39733
39964
  async function opencodePluginSource() {
39734
39965
  if (true) return '// Installed by Phren Hook and replaced on every update. Copy it under another name to customize.\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\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\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 () => {\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 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 mkdirSync(path.dirname(statusFile()), { recursive: true });\n writeJsonAtomic(statusFile(), { status: next, ...(sessionID ? { session: sessionID } : {}), at: new Date().toISOString() });\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\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) { 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) { 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 }\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 } else if (event?.type === "permission.replied") {\n const id = permissionId(properties);\n if (id) asking.delete(id); else asking.clear();\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';
39735
- const here = path46.dirname(fileURLToPath5(import.meta.url));
39966
+ const here = path47.dirname(fileURLToPath5(import.meta.url));
39736
39967
  for (const candidate of [
39737
- path46.join(here, "..", "..", "plugins", "opencode", "phren-transcript.js"),
39738
- path46.join(here, "..", "plugins", "opencode", "phren-transcript.js")
39968
+ path47.join(here, "..", "..", "plugins", "opencode", "phren-transcript.js"),
39969
+ path47.join(here, "..", "plugins", "opencode", "phren-transcript.js")
39739
39970
  ]) {
39740
39971
  const source = await missingFile(readFile18(candidate, "utf8"));
39741
39972
  if (source !== void 0) return source;
@@ -39743,7 +39974,7 @@ async function opencodePluginSource() {
39743
39974
  return void 0;
39744
39975
  }
39745
39976
  async function applyOpencodePlugin(remove = false) {
39746
- const dir = opencodePluginsDir(), file2 = path46.join(dir, "phren-transcript.js");
39977
+ const dir = opencodePluginsDir(), file2 = path47.join(dir, "phren-transcript.js");
39747
39978
  const source = await opencodePluginSource();
39748
39979
  const existing = await missingFile(readFile18(file2, "utf8"));
39749
39980
  if (remove) {
@@ -39751,14 +39982,14 @@ async function applyOpencodePlugin(remove = false) {
39751
39982
  return false;
39752
39983
  }
39753
39984
  if (source === void 0 || !opencodePluginNeedsWrite(existing, source)) return false;
39754
- if (!(await lstat9(path46.dirname(dir)).catch(() => null))?.isDirectory()) return false;
39985
+ if (!(await lstat9(path47.dirname(dir)).catch(() => null))?.isDirectory()) return false;
39755
39986
  await mkdir10(dir, { recursive: true });
39756
39987
  await atomic(file2, source, 420);
39757
39988
  return true;
39758
39989
  }
39759
39990
  async function applyAgentHooks(edits) {
39760
39991
  for (const { file: file2, before, after } of edits) {
39761
- await mkdir10(path46.dirname(file2), { recursive: true, mode: 448 });
39992
+ await mkdir10(path47.dirname(file2), { recursive: true, mode: 448 });
39762
39993
  if (await missingFile(readFile18(file2, "utf8")) !== before) throw new Error("Agent settings changed during installation. Run install again.");
39763
39994
  if (before !== void 0) await copyFile2(file2, file2 + `.phren-hook-${Date.now()}.bak`);
39764
39995
  await atomic(file2, after);
@@ -39772,18 +40003,18 @@ async function restoreAgentHooks(edits) {
39772
40003
  }
39773
40004
  }
39774
40005
  async function rollback() {
39775
- const config3 = JSON.parse(await readFile18(path46.join(bridgeRoot(), "installed.json"), "utf8"));
40006
+ const config3 = JSON.parse(await readFile18(path47.join(bridgeRoot(), "installed.json"), "utf8"));
39776
40007
  if (!config3.previous || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(config3.previous)) throw new Error("No previous helper version is available.");
39777
40008
  await stopService();
39778
40009
  await activate(config3.previous);
39779
40010
  await startService();
39780
- await atomic(path46.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config3.previous, previous: config3.version }) + "\n");
40011
+ await atomic(path47.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config3.previous, previous: config3.version }) + "\n");
39781
40012
  }
39782
40013
 
39783
40014
  // src/bridge/computers.ts
39784
40015
  init_protocol();
39785
- var exec7 = promisify7(execFile8);
39786
- var dispatchKeyPath = (root = bridgeRoot()) => path47.join(root, "id_ed25519_dispatch");
40016
+ var exec8 = promisify8(execFile9);
40017
+ var dispatchKeyPath = (root = bridgeRoot()) => path48.join(root, "id_ed25519_dispatch");
39787
40018
  function publicComputerKey(value2) {
39788
40019
  const match = /^ssh-ed25519 ([A-Za-z0-9+/]+={0,2})(?: [^\r\n]*)?$/.exec(value2.trim());
39789
40020
  if (!match) throw new BridgeError(400, "Supply one ed25519 public key.");
@@ -39809,7 +40040,7 @@ async function enrollComputer(name, root = bridgeRoot()) {
39809
40040
  computerName.parse(name);
39810
40041
  await mkdir11(root, { recursive: true, mode: 448 });
39811
40042
  await chmod3(root, 448);
39812
- const lock = path47.join(root, "enroll-computer.lock");
40043
+ const lock = path48.join(root, "enroll-computer.lock");
39813
40044
  try {
39814
40045
  await mkdir11(lock, { mode: 448 });
39815
40046
  } catch {
@@ -39818,23 +40049,23 @@ async function enrollComputer(name, root = bridgeRoot()) {
39818
40049
  try {
39819
40050
  const key2 = dispatchKeyPath(root);
39820
40051
  if (!await regularFile(key2)) {
39821
- const temporary = await mkdtemp2(path47.join(root, "enroll-"));
40052
+ const temporary = await mkdtemp2(path48.join(root, "enroll-"));
39822
40053
  try {
39823
- const generated = path47.join(temporary, "key");
39824
- await exec7("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", "phren-computer", "-f", generated], { timeout: 1e4 });
40054
+ const generated = path48.join(temporary, "key");
40055
+ await exec8("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", "phren-computer", "-f", generated], { timeout: 1e4 });
39825
40056
  await rename6(generated, key2);
39826
40057
  } finally {
39827
40058
  await rm5(temporary, { recursive: true, force: true });
39828
40059
  }
39829
40060
  }
39830
40061
  await chmod3(key2, 384);
39831
- const { stdout } = await exec7("ssh-keygen", ["-y", "-P", "", "-f", key2], { timeout: 1e4, maxBuffer: 4096 });
40062
+ const { stdout } = await exec8("ssh-keygen", ["-y", "-P", "", "-f", key2], { timeout: 1e4, maxBuffer: 4096 });
39832
40063
  return computerKeyLine(name, stdout.trim());
39833
40064
  } finally {
39834
40065
  await rm5(lock, { recursive: true, force: true });
39835
40066
  }
39836
40067
  }
39837
- async function acceptComputer(name, input2, sshDirectory = path47.join(homedir14(), ".ssh")) {
40068
+ async function acceptComputer(name, input2, sshDirectory = path48.join(homedir14(), ".ssh")) {
39838
40069
  computerName.parse(name);
39839
40070
  const prefix = `restrict,pty,${forcedCommand} `;
39840
40071
  const raw = input2.trim();
@@ -39848,19 +40079,19 @@ async function acceptComputer(name, input2, sshDirectory = path47.join(homedir14
39848
40079
  sshDirectory
39849
40080
  );
39850
40081
  }
39851
- async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory = path47.join(homedir14(), ".ssh")) {
40082
+ async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory = path48.join(homedir14(), ".ssh")) {
39852
40083
  const directory = await lstat10(sshDirectory).catch(() => void 0);
39853
40084
  if (directory && (!directory.isDirectory() || directory.isSymbolicLink())) throw new BridgeError(409, "Refusing an unexpected SSH directory.");
39854
40085
  await mkdir11(sshDirectory, { recursive: true, mode: 448 });
39855
40086
  await chmod3(sshDirectory, 448);
39856
- const lock = path47.join(sshDirectory, ".phren-enroll.lock");
40087
+ const lock = path48.join(sshDirectory, ".phren-enroll.lock");
39857
40088
  try {
39858
40089
  await mkdir11(lock, { mode: 448 });
39859
40090
  } catch {
39860
40091
  throw new BridgeError(409, "SSH enrollment is already running; inspect .phren-enroll.lock if interrupted.");
39861
40092
  }
39862
- const file2 = path47.join(sshDirectory, "authorized_keys");
39863
- const temporary = path47.join(lock, "authorized_keys");
40093
+ const file2 = path48.join(sshDirectory, "authorized_keys");
40094
+ const temporary = path48.join(lock, "authorized_keys");
39864
40095
  try {
39865
40096
  const before = await regularFile(file2) ? await readFile19(file2, "utf8") : "";
39866
40097
  const lines = before.split("\n").filter(Boolean);
@@ -39967,10 +40198,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
39967
40198
  for (const value2 of values.slice(0, 128)) {
39968
40199
  if (state.count >= 128) break;
39969
40200
  const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
39970
- const path84 = publicLabel(raw.path);
40201
+ const path85 = publicLabel(raw.path);
39971
40202
  const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
39972
40203
  const routed = destination(raw, fallbackComputer, fallbackTarget);
39973
- if (!id2.success || !source.success || !path84 || !callId || !routed) continue;
40204
+ if (!id2.success || !source.success || !path85 || !callId || !routed) continue;
39974
40205
  const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
39975
40206
  const nestedSession = sessionId.safeParse(raw.session);
39976
40207
  const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
@@ -39983,7 +40214,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
39983
40214
  projected.push({
39984
40215
  id: publicID(parent, routed.computer.id, receipt.id, descendant),
39985
40216
  provider: source.data,
39986
- path: path84,
40217
+ path: path85,
39987
40218
  callId,
39988
40219
  state: raw.failed === true ? "failed" : childState,
39989
40220
  ...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
@@ -40045,7 +40276,7 @@ init_logger();
40045
40276
  init_client();
40046
40277
  import { spawn as spawn5 } from "node:child_process";
40047
40278
  import { lstat as lstat11, mkdtemp as mkdtemp3, readFile as readFile20, rm as rm6, writeFile as writeFile6 } from "node:fs/promises";
40048
- import path48 from "node:path";
40279
+ import path49 from "node:path";
40049
40280
  import { Duplex } from "node:stream";
40050
40281
  init_protocol();
40051
40282
  var peerSchema = external_exports.object({
@@ -40057,7 +40288,7 @@ var peerSchema = external_exports.object({
40057
40288
  server: serverName.default("default")
40058
40289
  }).strict();
40059
40290
  async function hookPeers(root = bridgeRoot()) {
40060
- const file2 = path48.join(root, "hooks.yaml");
40291
+ const file2 = path49.join(root, "hooks.yaml");
40061
40292
  const info = await lstat11(file2).catch((error62) => {
40062
40293
  if (error62.code === "ENOENT") return void 0;
40063
40294
  throw new BridgeError(409, `hooks.yaml could not be read (${error62.code ?? "unknown error"}).`);
@@ -40079,7 +40310,7 @@ async function addHookPeer(input2, root = bridgeRoot()) {
40079
40310
  const clash = existing.find((other) => other.name === peer.name || other.address === peer.address && other.port === peer.port && other.server === peer.server);
40080
40311
  if (clash) throw new BridgeError(409, `hooks.yaml already has ${clash.name} at ${clash.address}; remove that entry first to link it differently.`);
40081
40312
  if (existing.length >= 32) throw new BridgeError(409, "hooks.yaml already has 32 computers.");
40082
- await atomic(path48.join(root, "hooks.yaml"), dump({ version: 1, computers: [...existing, peer] }, { lineWidth: -1 }));
40313
+ await atomic(path49.join(root, "hooks.yaml"), dump({ version: 1, computers: [...existing, peer] }, { lineWidth: -1 }));
40083
40314
  return { added: true, peer };
40084
40315
  }
40085
40316
  async function optionalHookPeers(root = bridgeRoot()) {
@@ -40160,10 +40391,10 @@ async function peerRequest(peer, route2, data, timeout) {
40160
40391
  const root = bridgeRoot(), key2 = dispatchKeyPath(root);
40161
40392
  const info = await lstat11(key2).catch(() => void 0);
40162
40393
  if (!info?.isFile() || info.isSymbolicLink() || info.mode & 63) throw new BridgeError(409, "Run phren bridge enroll-computer on this computer first (private key mode 0600).", { code: "dispatch-key-missing" });
40163
- const temporary = await mkdtemp3(path48.join(root, "peer-"));
40394
+ const temporary = await mkdtemp3(path49.join(root, "peer-"));
40164
40395
  let child, stream;
40165
40396
  try {
40166
- const knownHosts = path48.join(temporary, "known_hosts");
40397
+ const knownHosts = path49.join(temporary, "known_hosts");
40167
40398
  await writeFile6(knownHosts, `phren-peer ${peer.hostKey}
40168
40399
  `, { mode: 384 });
40169
40400
  const ssh2 = spawn5("ssh", peerSSHArgs(peer, knownHosts, key2), { stdio: ["pipe", "pipe", "pipe"] });
@@ -40300,21 +40531,21 @@ var receiptSchema2 = dispatchSchema.omit({ prompt: true }).extend({
40300
40531
  async function dispatchProjectDirectory(project) {
40301
40532
  const name = projectName.parse(project);
40302
40533
  const source = readProjectConfig(phrenStoreRoot(), name).sourcePath;
40303
- if (typeof source !== "string" || !path49.isAbsolute(source) || /[\x00-\x1f\x7f]/.test(source)) throw new BridgeError(404, "Project has no absolute sourcePath on this computer.");
40304
- const directory = await realpath9(source).catch(() => void 0);
40305
- if (!directory || !(await stat14(directory)).isDirectory()) throw new BridgeError(404, "Project is not on this computer.");
40534
+ if (typeof source !== "string" || !path50.isAbsolute(source) || /[\x00-\x1f\x7f]/.test(source)) throw new BridgeError(404, "Project has no absolute sourcePath on this computer.");
40535
+ const directory = await realpath10(source).catch(() => void 0);
40536
+ if (!directory || !(await stat15(directory)).isDirectory()) throw new BridgeError(404, "Project is not on this computer.");
40306
40537
  return directory;
40307
40538
  }
40308
40539
  async function save(receipt) {
40309
- const root = path49.join(bridgeRoot(), "dispatches");
40540
+ const root = path50.join(bridgeRoot(), "dispatches");
40310
40541
  await mkdir12(root, { recursive: true, mode: 448 });
40311
- await atomic(path49.join(root, `${receipt.id}.json`), receipt);
40542
+ await atomic(path50.join(root, `${receipt.id}.json`), receipt);
40312
40543
  }
40313
40544
  var MAX_RECEIPT_BYTES = 65536;
40314
40545
  var receiptUpdates = Promise.resolve();
40315
40546
  function updateReceipt(receiptID, change) {
40316
40547
  const run = receiptUpdates.then(async () => {
40317
- const file2 = path49.join(bridgeRoot(), "dispatches", `${external_exports.string().uuid().parse(receiptID)}.json`);
40548
+ const file2 = path50.join(bridgeRoot(), "dispatches", `${external_exports.string().uuid().parse(receiptID)}.json`);
40318
40549
  const info = await lstat12(file2).catch(() => void 0);
40319
40550
  if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) return void 0;
40320
40551
  const receipt = receiptSchema2.parse(JSON.parse(await readFile21(file2, "utf8")));
@@ -40329,7 +40560,7 @@ function updateReceipt(receiptID, change) {
40329
40560
  }
40330
40561
  async function receiptNames(root) {
40331
40562
  try {
40332
- return await readdir9(root);
40563
+ return await readdir10(root);
40333
40564
  } catch (error62) {
40334
40565
  if (error62.code !== "ENOENT") logger.warn("dispatch", `Could not list dispatch receipts: ${failureReason(error62)}`);
40335
40566
  return [];
@@ -40342,12 +40573,12 @@ function failureReason(error62) {
40342
40573
  return `${typeof code === "string" && !(error62 instanceof BridgeError) ? `${code}: ` : ""}${message}`.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200);
40343
40574
  }
40344
40575
  async function dispatchStatus() {
40345
- const root = path49.join(bridgeRoot(), "dispatches");
40576
+ const root = path50.join(bridgeRoot(), "dispatches");
40346
40577
  const names = (await receiptNames(root)).filter((name) => /^[a-f0-9-]{36}\.json$/.test(name)).slice(0, 1024);
40347
40578
  const receipts = [];
40348
40579
  for (const name of names) {
40349
40580
  try {
40350
- const file2 = path49.join(root, name);
40581
+ const file2 = path50.join(root, name);
40351
40582
  const info = await lstat12(file2);
40352
40583
  if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) continue;
40353
40584
  const receipt = receiptSchema2.parse(JSON.parse(await readFile21(file2, "utf8")));
@@ -40422,7 +40653,7 @@ var DispatchService = class {
40422
40653
  if (!this.identity) throw new BridgeError(503, "This Hook cannot validate a dispatch parent.");
40423
40654
  await validateDispatchParent(data, this.identity.computerID, this.identity.validateParentTarget);
40424
40655
  }
40425
- if ((await receiptNames(path49.join(bridgeRoot(), "dispatches"))).length >= 1024) throw new BridgeError(429, "Dispatch history is full. Archive old receipts before dispatching again.");
40656
+ if ((await receiptNames(path50.join(bridgeRoot(), "dispatches"))).length >= 1024) throw new BridgeError(429, "Dispatch history is full. Archive old receipts before dispatching again.");
40426
40657
  const here = this.local();
40427
40658
  const toLocal = data.computer !== "anywhere" && isLocalComputer(data.computer, here.names);
40428
40659
  const enrolled = await hookPeers().catch((error62) => {
@@ -40634,7 +40865,7 @@ init_protocol();
40634
40865
 
40635
40866
  // src/bridge/schedule-watch.ts
40636
40867
  init_herdr();
40637
- import { open as open10, stat as stat15 } from "node:fs/promises";
40868
+ import { open as open11, stat as stat16 } from "node:fs/promises";
40638
40869
  init_protocol();
40639
40870
  init_transcripts();
40640
40871
  init_terminal_text();
@@ -40729,7 +40960,7 @@ async function readFinalTurn(source, sessionId2) {
40729
40960
  if (!sessionId2) return void 0;
40730
40961
  const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
40731
40962
  if (!file2) return void 0;
40732
- const handle = await open10(file2, "r").catch(() => void 0);
40963
+ const handle = await open11(file2, "r").catch(() => void 0);
40733
40964
  if (!handle) return void 0;
40734
40965
  try {
40735
40966
  const { size } = await handle.stat();
@@ -40769,7 +41000,7 @@ function ownerQuestion(text4) {
40769
41000
  async function realTranscriptStamp(source, sessionId2) {
40770
41001
  if (!sessionId2) return void 0;
40771
41002
  const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
40772
- const metadata = file2 ? await stat15(file2).catch(() => void 0) : void 0;
41003
+ const metadata = file2 ? await stat16(file2).catch(() => void 0) : void 0;
40773
41004
  return metadata ? { size: metadata.size, mtimeMs: metadata.mtimeMs } : void 0;
40774
41005
  }
40775
41006
  async function watchHerdrRun(server, target, signal, startup, env = {}) {
@@ -41022,11 +41253,11 @@ var DispatchReturns = class {
41022
41253
  /** Ask each peer, once, about every open dispatch placed on it. */
41023
41254
  async poll() {
41024
41255
  const now = this.now();
41025
- const open16 = (await dispatchStatus()).filter((receipt) => (receipt.state === "accepted" || receipt.state === "uncertain") && receipt.target && receipt.worker?.state !== "gone" && now - Date.parse(receipt.createdAt) < WATCH_MS);
41026
- if (!open16.length) return;
41256
+ const open17 = (await dispatchStatus()).filter((receipt) => (receipt.state === "accepted" || receipt.state === "uncertain") && receipt.target && receipt.worker?.state !== "gone" && now - Date.parse(receipt.createdAt) < WATCH_MS);
41257
+ if (!open17.length) return;
41027
41258
  const peers = await this.peers().catch(() => []);
41028
41259
  const byComputer = /* @__PURE__ */ new Map();
41029
- for (const receipt of open16) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
41260
+ for (const receipt of open17) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
41030
41261
  await Promise.all([...byComputer].map(async ([computer, receipts]) => {
41031
41262
  const peer = peers.find((candidate) => candidate.name === computer);
41032
41263
  const local = !peer && this.isLocal(computer);
@@ -41098,12 +41329,12 @@ init_protocol();
41098
41329
  init_herdr();
41099
41330
  init_transcripts();
41100
41331
  init_transcript_index();
41101
- import { execFile as execFile9 } from "node:child_process";
41332
+ import { execFile as execFile10 } from "node:child_process";
41102
41333
  import { createHash as createHash12 } from "node:crypto";
41103
- import { mkdir as mkdir13, open as open11, stat as stat16, readFile as readFile22, writeFile as writeFile7 } from "node:fs/promises";
41104
- import path50 from "node:path";
41105
- import { promisify as promisify8 } from "node:util";
41106
- var exec8 = promisify8(execFile9);
41334
+ import { mkdir as mkdir13, open as open12, stat as stat17, readFile as readFile22, writeFile as writeFile7 } from "node:fs/promises";
41335
+ import path51 from "node:path";
41336
+ import { promisify as promisify9 } from "node:util";
41337
+ var exec9 = promisify9(execFile10);
41107
41338
  var text3 = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
41108
41339
  var question = external_exports.object({ title: text3, options: external_exports.array(text3).max(12).nullable().optional() });
41109
41340
  var questionSet = external_exports.array(question).min(1).max(8);
@@ -41202,7 +41433,7 @@ var CodexQuestions = class {
41202
41433
  }
41203
41434
  probe;
41204
41435
  supported() {
41205
- if (!this.probe || Date.now() - this.probe.at > 3e5) this.probe = { at: Date.now(), result: exec8(this.executable, ["queue", "--help"], { timeout: 5e3, maxBuffer: 65536 }).then(({ stdout }) => stdout.includes("--thread") && stdout.includes("--message")).catch(() => false).then((available) => {
41436
+ if (!this.probe || Date.now() - this.probe.at > 3e5) this.probe = { at: Date.now(), result: exec9(this.executable, ["queue", "--help"], { timeout: 5e3, maxBuffer: 65536 }).then(({ stdout }) => stdout.includes("--thread") && stdout.includes("--message")).catch(() => false).then((available) => {
41206
41437
  this.inboxAvailable = available;
41207
41438
  return available;
41208
41439
  }) };
@@ -41215,7 +41446,7 @@ var CodexQuestions = class {
41215
41446
  const cached2 = this.snapshots.get(target.session);
41216
41447
  let pending = cached2?.pending;
41217
41448
  if (!cached2 || Date.now() - cached2.at > 1e3) {
41218
- const metadata = await stat16(file2), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
41449
+ const metadata = await stat17(file2), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
41219
41450
  pending = cached2?.stamp === stamp ? cached2.pending : await pendingAsyncQuestions(file2).catch((error62) => {
41220
41451
  if (this.failedSnapshots.size >= 64) this.failedSnapshots.delete(this.failedSnapshots.keys().next().value);
41221
41452
  this.failedSnapshots.set(target.session, Date.now());
@@ -41227,7 +41458,7 @@ var CodexQuestions = class {
41227
41458
  }
41228
41459
  return Promise.all((pending ?? []).map(async (p) => {
41229
41460
  const key2 = createHash12("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
41230
- const submitted = await readFile22(path50.join(bridgeRoot(), "question-replies", key2), "utf8").then((value2) => value2 === "submitted").catch(() => false);
41461
+ const submitted = await readFile22(path51.join(bridgeRoot(), "question-replies", key2), "utf8").then((value2) => value2 === "submitted").catch(() => false);
41231
41462
  return { toolUseId: p.id, isAsync: true, submitted, questions: p.questions.map((q) => ({
41232
41463
  question: q.title,
41233
41464
  options: (q.options ?? []).map((label2) => ({ label: label2 })),
@@ -41243,17 +41474,17 @@ var CodexQuestions = class {
41243
41474
  const reply = questionReply(questions, data.answers);
41244
41475
  const pane = await validateTarget(target);
41245
41476
  if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
41246
- const directory = path50.join(bridgeRoot(), "question-replies");
41477
+ const directory = path51.join(bridgeRoot(), "question-replies");
41247
41478
  await mkdir13(directory, { recursive: true, mode: 448 });
41248
41479
  const key2 = createHash12("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
41249
- const receiptPath = path50.join(directory, key2);
41250
- const receipt = await open11(receiptPath, "wx", 384).catch((error62) => {
41480
+ const receiptPath = path51.join(directory, key2);
41481
+ const receipt = await open12(receiptPath, "wx", 384).catch((error62) => {
41251
41482
  if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
41252
41483
  throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
41253
41484
  });
41254
41485
  await receipt.close();
41255
41486
  try {
41256
- await exec8(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8e3, maxBuffer: 65536 });
41487
+ await exec9(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8e3, maxBuffer: 65536 });
41257
41488
  await writeFile7(receiptPath, "submitted", { mode: 384 });
41258
41489
  } catch {
41259
41490
  throw new BridgeError(409, "Codex did not confirm the answer. Check the conversation; Phren has not retried it.");
@@ -41269,9 +41500,9 @@ init_transcripts();
41269
41500
  init_home_paths();
41270
41501
  init_protocol();
41271
41502
  import { spawn as spawn6 } from "node:child_process";
41272
- import { readdir as readdir10, readFile as readFile23, stat as stat17 } from "node:fs/promises";
41503
+ import { readdir as readdir11, readFile as readFile23, stat as stat18 } from "node:fs/promises";
41273
41504
  import { homedir as homedir15 } from "node:os";
41274
- import path51 from "node:path";
41505
+ import path52 from "node:path";
41275
41506
  function readCodexModels(executable = "codex") {
41276
41507
  return new Promise((resolve11) => {
41277
41508
  const child = spawn6(executable, ["app-server"], { cwd: homedir15(), stdio: ["pipe", "pipe", "ignore"] });
@@ -41350,12 +41581,12 @@ var CLAUDE_MENU = [
41350
41581
  { id: "claude-fable-5-1[1m]", name: "Fable 5.1 (1M context)", description: "Fable 5.1 with a 1M context window." }
41351
41582
  ];
41352
41583
  async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
41353
- const directory = path51.join(configDir, "cache", "model-catalog");
41584
+ const directory = path52.join(configDir, "cache", "model-catalog");
41354
41585
  let newest;
41355
41586
  try {
41356
- for (const name of await readdir10(directory)) {
41587
+ for (const name of await readdir11(directory)) {
41357
41588
  if (!name.endsWith("-cc.json")) continue;
41358
- const file2 = path51.join(directory, name), at = (await stat17(file2)).mtimeMs;
41589
+ const file2 = path52.join(directory, name), at = (await stat18(file2)).mtimeMs;
41359
41590
  if (!newest || at > newest.at) newest = { file: file2, at };
41360
41591
  }
41361
41592
  } catch {
@@ -41436,7 +41667,7 @@ async function readClaudeModels(configDir, installed) {
41436
41667
  const live = await readClaudeCatalog(configDir, version3).catch(() => []);
41437
41668
  return live.length ? live : CLAUDE_MENU.map((model) => ({ ...model }));
41438
41669
  }
41439
- async function readOpenCodeModels(executable = "opencode", configDir = path51.join(homedir15(), ".config/opencode")) {
41670
+ async function readOpenCodeModels(executable = "opencode", configDir = path52.join(homedir15(), ".config/opencode")) {
41440
41671
  const listed2 = await new Promise((resolve11) => {
41441
41672
  const child = spawn6(executable, ["models"], { cwd: homedir15(), stdio: ["ignore", "pipe", "ignore"] });
41442
41673
  let out = "", done = false;
@@ -41463,7 +41694,7 @@ async function readOpenCodeModels(executable = "opencode", configDir = path51.jo
41463
41694
  let configured;
41464
41695
  for (const file2 of ["opencode.json", "opencode.jsonc"]) {
41465
41696
  try {
41466
- const text4 = await readFile23(path51.join(configDir, file2), "utf8");
41697
+ const text4 = await readFile23(path52.join(configDir, file2), "utf8");
41467
41698
  const model = /"model"\s*:\s*"([^"]+)"/.exec(text4)?.[1];
41468
41699
  if (model) {
41469
41700
  configured = model.slice(0, 200);
@@ -41933,14 +42164,14 @@ init_project_config();
41933
42164
  init_shared();
41934
42165
  import { randomUUID as randomUUID11 } from "node:crypto";
41935
42166
  import { hostname as hostname6 } from "node:os";
41936
- import path54 from "node:path";
42167
+ import path55 from "node:path";
41937
42168
 
41938
42169
  // src/bridge/schedule-format.ts
41939
42170
  init_js_yaml();
41940
42171
  init_zod();
41941
42172
  init_protocol();
41942
42173
  import { readFile as readFile24 } from "node:fs/promises";
41943
- import path52 from "node:path";
42174
+ import path53 from "node:path";
41944
42175
  var SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
41945
42176
  var SCHEDULE_HARNESSES = ["claude", "codex", "opencode"];
41946
42177
  var SCHEDULE_NOTIFY = ["start", "finish", "failure"];
@@ -41953,7 +42184,7 @@ var scheduleName = singleLine(80);
41953
42184
  var timestamp3 = external_exports.string().datetime({ offset: true });
41954
42185
  var localTimestamp = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/);
41955
42186
  var clockTime = external_exports.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
41956
- var schedulePath = (projectDir) => path52.join(projectDir, "schedules.yaml");
42187
+ var schedulePath = (projectDir) => path53.join(projectDir, "schedules.yaml");
41957
42188
  var runningStatuses = /* @__PURE__ */ new Set(["launched", "running", "blocked"]);
41958
42189
  var MAX_SCHEDULES = 64;
41959
42190
  var MAX_RUNS = 2e3;
@@ -42153,7 +42384,7 @@ async function writeScheduleRuns(file2, runs) {
42153
42384
  await atomicInPrivateDir(file2, kept.map((run) => JSON.stringify(run)).join("\n") + (kept.length ? "\n" : ""));
42154
42385
  }
42155
42386
  function scheduleRunsFile() {
42156
- return path52.join(bridgeRoot(), "schedule-runs.jsonl");
42387
+ return path53.join(bridgeRoot(), "schedule-runs.jsonl");
42157
42388
  }
42158
42389
 
42159
42390
  // src/bridge/schedule-launch.ts
@@ -42166,8 +42397,8 @@ init_logger();
42166
42397
  init_shared();
42167
42398
  import { spawn as spawn7 } from "node:child_process";
42168
42399
  import { createWriteStream } from "node:fs";
42169
- import { mkdir as mkdir14, readFile as readFile25, stat as stat18 } from "node:fs/promises";
42170
- import path53 from "node:path";
42400
+ import { mkdir as mkdir14, readFile as readFile25, stat as stat19 } from "node:fs/promises";
42401
+ import path54 from "node:path";
42171
42402
  import { finished as streamFinished } from "node:stream/promises";
42172
42403
  var CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
42173
42404
  function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
@@ -42200,7 +42431,7 @@ async function resumeScheduleRun(run, schedule, signal, watch2 = watchHerdrRun)
42200
42431
  );
42201
42432
  }
42202
42433
  if (launch2.mode === "headless" && launch2.jobDir) {
42203
- const manifest = await readFile25(path53.join(launch2.jobDir, "manifest.json"), "utf8").then((text4) => JSON.parse(text4)).catch(() => void 0);
42434
+ const manifest = await readFile25(path54.join(launch2.jobDir, "manifest.json"), "utf8").then((text4) => JSON.parse(text4)).catch(() => void 0);
42204
42435
  if (manifest?.status === "completed") return { status: "finished" };
42205
42436
  if (manifest?.status === "failed") {
42206
42437
  return { status: "failed", reason: typeof manifest.exitCode === "number" ? `The scheduled agent exited with code ${manifest.exitCode}.` : "The scheduled agent failed." };
@@ -42248,7 +42479,7 @@ async function promptWhenReady(server, paneId, text4, signal, waitMs = 6e4) {
42248
42479
  }
42249
42480
  }
42250
42481
  async function launchHeadless(context, store, started) {
42251
- const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path53.join(root, context.runId);
42482
+ const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path54.join(root, context.runId);
42252
42483
  await mkdir14(jobDir, { recursive: true, mode: 448 });
42253
42484
  const eventLog = "events.jsonl", now = (/* @__PURE__ */ new Date()).toISOString();
42254
42485
  const manifest = {
@@ -42268,7 +42499,7 @@ async function launchHeadless(context, store, started) {
42268
42499
  };
42269
42500
  await writeManifest2(jobDir, manifest);
42270
42501
  const command = headlessCommand(context.schedule, context.cwd);
42271
- if (context.schedule.harness === "codex") await ensureCodexDirTrusted(context.cwd).catch((error62) => logger.warn("schedule", `Could not mark ${path53.basename(context.cwd)} trusted for Codex (run ${context.runId}): ${error62 instanceof Error ? error62.message.split("\n")[0] : String(error62)}`));
42502
+ if (context.schedule.harness === "codex") await ensureCodexDirTrusted(context.cwd).catch((error62) => logger.warn("schedule", `Could not mark ${path54.basename(context.cwd)} trusted for Codex (run ${context.runId}): ${error62 instanceof Error ? error62.message.split("\n")[0] : String(error62)}`));
42272
42503
  let child;
42273
42504
  try {
42274
42505
  child = spawn7(command.file, command.args, { cwd: command.cwd, env: process.env, stdio: ["pipe", "pipe", "pipe"] });
@@ -42280,8 +42511,8 @@ async function launchHeadless(context, store, started) {
42280
42511
  const closed = new Promise((resolve11) => {
42281
42512
  child.once("close", (code, signal) => resolve11({ code, signal }));
42282
42513
  });
42283
- const output2 = createWriteStream(path53.join(jobDir, eventLog), { flags: "a", mode: 384 });
42284
- const errors = createWriteStream(path53.join(jobDir, "stderr.log"), { flags: "a", mode: 384 });
42514
+ const output2 = createWriteStream(path54.join(jobDir, eventLog), { flags: "a", mode: 384 });
42515
+ const errors = createWriteStream(path54.join(jobDir, "stderr.log"), { flags: "a", mode: 384 });
42285
42516
  const streamsFinished = Promise.all([streamFinished(output2), streamFinished(errors)]).then(() => void 0).catch(() => void 0);
42286
42517
  child.stdin?.on("error", () => {
42287
42518
  });
@@ -42334,7 +42565,7 @@ function tomlQuote(value2) {
42334
42565
  }
42335
42566
  async function ensureCodexDirTrusted(cwd) {
42336
42567
  const directory = codexHome();
42337
- const file2 = path53.join(directory, "config.toml");
42568
+ const file2 = path54.join(directory, "config.toml");
42338
42569
  let text4 = "";
42339
42570
  try {
42340
42571
  text4 = await readFile25(file2, "utf8");
@@ -42366,12 +42597,12 @@ ${trustLine}
42366
42597
  `;
42367
42598
  }
42368
42599
  await mkdir14(directory, { recursive: true, mode: 448 });
42369
- const metadata = await stat18(file2).catch(() => void 0);
42600
+ const metadata = await stat19(file2).catch(() => void 0);
42370
42601
  const mode = metadata ? metadata.mode & 511 : 384;
42371
42602
  await atomic(file2, next, mode);
42372
42603
  }
42373
42604
  async function writeManifest2(jobDir, manifest) {
42374
- await atomicInPrivateDir(path53.join(jobDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
42605
+ await atomicInPrivateDir(path54.join(jobDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
42375
42606
  }
42376
42607
 
42377
42608
  // src/bridge/schedules.ts
@@ -42409,7 +42640,7 @@ var Scheduler = class {
42409
42640
  return getProjectDirs(this.store);
42410
42641
  }
42411
42642
  projectDirectory(project) {
42412
- const found = this.projectDirectories().find((directory) => path54.basename(directory).toLowerCase() === project.toLowerCase());
42643
+ const found = this.projectDirectories().find((directory) => path55.basename(directory).toLowerCase() === project.toLowerCase());
42413
42644
  if (!found) throw new BridgeError(404, `Unknown project "${project}".`);
42414
42645
  return found;
42415
42646
  }
@@ -42435,7 +42666,7 @@ var Scheduler = class {
42435
42666
  } catch {
42436
42667
  continue;
42437
42668
  }
42438
- const project = path54.basename(directory);
42669
+ const project = path55.basename(directory);
42439
42670
  for (const schedule of schedules) {
42440
42671
  const matching = runs.filter((run) => run.project === project && run.scheduleId === schedule.id);
42441
42672
  const last = matching.at(-1), running2 = matching.some((run) => runningStatuses.has(run.status));
@@ -42465,7 +42696,7 @@ var Scheduler = class {
42465
42696
  }
42466
42697
  async launchNow(projectName2, id2) {
42467
42698
  const prepared = await this.exclusive(async () => {
42468
- const projectDir = this.projectDirectory(projectName2), project = path54.basename(projectDir);
42699
+ const projectDir = this.projectDirectory(projectName2), project = path55.basename(projectDir);
42469
42700
  const file2 = await readScheduleDocument(projectDir), schedule = file2.schedules.find((item) => item.id === id2);
42470
42701
  if (!schedule) throw new BridgeError(404, `Schedule "${id2}" was not found in ${project}.`);
42471
42702
  if (!computerMatches(schedule.computer, this.computer())) throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
@@ -42579,8 +42810,8 @@ var Scheduler = class {
42579
42810
  const resume = this.launch.resume;
42580
42811
  if (this.recovered || !resume) return;
42581
42812
  this.recovered = true;
42582
- const open16 = (await readScheduleRuns(this.runsFile)).filter((run) => runningStatuses.has(run.status) && !this.own.has(run.id));
42583
- for (const run of open16) {
42813
+ const open17 = (await readScheduleRuns(this.runsFile)).filter((run) => runningStatuses.has(run.status) && !this.own.has(run.id));
42814
+ for (const run of open17) {
42584
42815
  this.own.add(run.id);
42585
42816
  let schedule;
42586
42817
  try {
@@ -42624,23 +42855,23 @@ var Scheduler = class {
42624
42855
 
42625
42856
  // src/bridge/canary.ts
42626
42857
  init_phren_paths();
42627
- import { lstat as lstat14, mkdtemp as mkdtemp4, realpath as realpath10, rm as rm7 } from "node:fs/promises";
42858
+ import { lstat as lstat14, mkdtemp as mkdtemp4, realpath as realpath11, rm as rm7 } from "node:fs/promises";
42628
42859
  import { hostname as hostname8, tmpdir } from "node:os";
42629
- import path58 from "node:path";
42860
+ import path59 from "node:path";
42630
42861
 
42631
42862
  // src/bridge/health.ts
42632
42863
  init_policy();
42633
42864
  init_phren_paths();
42634
42865
  init_store_registry();
42635
- import { execFile as execFile10, spawn as spawn8 } from "node:child_process";
42866
+ import { execFile as execFile11, spawn as spawn8 } from "node:child_process";
42636
42867
  import { lstat as lstat13, readFile as readFile26 } from "node:fs/promises";
42637
42868
  import { homedir as homedir16, hostname as hostname7 } from "node:os";
42638
- import path57 from "node:path";
42639
- import { promisify as promisify9 } from "node:util";
42869
+ import path58 from "node:path";
42870
+ import { promisify as promisify10 } from "node:util";
42640
42871
  init_protocol();
42641
42872
  init_metrics();
42642
42873
  init_terminal_tmux();
42643
- var exec9 = promisify9(execFile10);
42874
+ var exec10 = promisify10(execFile11);
42644
42875
  async function terminalHealth() {
42645
42876
  const [{ servers: servers2 }, tmux2] = await Promise.all([Promise.resolve().then(() => (init_herdr(), herdr_exports)), tmuxHealth()]);
42646
42877
  const running2 = (await servers2().catch(() => [])).map((server) => ({
@@ -42701,7 +42932,7 @@ function plainError(value2) {
42701
42932
  async function git3(cwd, args) {
42702
42933
  try {
42703
42934
  countGit("health");
42704
- const { stdout } = await exec9("git", args, { cwd, timeout: 5e3, maxBuffer: 65536, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
42935
+ const { stdout } = await exec10("git", args, { cwd, timeout: 5e3, maxBuffer: 65536, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
42705
42936
  return stdout.trim();
42706
42937
  } catch {
42707
42938
  return void 0;
@@ -42749,7 +42980,7 @@ async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
42749
42980
  const last = runs.reduce((newest, run) => !newest || run.startedAt >= newest.startedAt ? run : newest, void 0);
42750
42981
  if (!last) return null;
42751
42982
  let name;
42752
- const directory = getProjectDirs(store).find((dir) => path57.basename(dir).toLowerCase() === last.project.toLowerCase());
42983
+ const directory = getProjectDirs(store).find((dir) => path58.basename(dir).toLowerCase() === last.project.toLowerCase());
42753
42984
  if (directory) name = (await readScheduleDocument(directory).catch(() => void 0))?.schedules.find((item) => item.id === last.scheduleId)?.name;
42754
42985
  return {
42755
42986
  ...name ? { name } : {},
@@ -42803,7 +43034,7 @@ async function probePeer(peer, caller) {
42803
43034
  }
42804
43035
  }
42805
43036
  function canaryFile(root = bridgeRoot()) {
42806
- return path57.join(root, "canary.json");
43037
+ return path58.join(root, "canary.json");
42807
43038
  }
42808
43039
  async function readCanary(root = bridgeRoot()) {
42809
43040
  try {
@@ -42816,7 +43047,7 @@ async function readCanary(root = bridgeRoot()) {
42816
43047
  }
42817
43048
  }
42818
43049
  async function pushConfigured() {
42819
- const file2 = process.env.PHREN_APNS_CONFIG || path57.join(bridgeRoot(), "apns.json");
43050
+ const file2 = process.env.PHREN_APNS_CONFIG || path58.join(bridgeRoot(), "apns.json");
42820
43051
  const info = await lstat13(file2).catch(() => void 0);
42821
43052
  return { configured: !!info?.isFile() };
42822
43053
  }
@@ -42905,7 +43136,7 @@ async function closeCanaryWorkspaces(server, before, created) {
42905
43136
  }
42906
43137
  async function conductorStep(options, server) {
42907
43138
  const before = new Set(objects((await snapshot(server)).workspaces).map((workspace) => String(workspace.workspace_id)));
42908
- const folder = await realpath10(await mkdtemp4(path58.join(tmpdir(), "phren-canary-")));
43139
+ const folder = await realpath11(await mkdtemp4(path59.join(tmpdir(), "phren-canary-")));
42909
43140
  let created, failure2, detail;
42910
43141
  try {
42911
43142
  const launched = await options.launch(server, { role: "conductor", kind: "claude", label: CANARY_LABEL, cwd: folder, timeoutMs: 45e3 });
@@ -42926,12 +43157,12 @@ async function scheduleStep(options) {
42926
43157
  let count2 = 0;
42927
43158
  const broken = [];
42928
43159
  for (const directory of getProjectDirs(options.store)) {
42929
- const present2 = await lstat14(path58.join(directory, "schedules.yaml")).catch(() => void 0);
43160
+ const present2 = await lstat14(path59.join(directory, "schedules.yaml")).catch(() => void 0);
42930
43161
  if (!present2) continue;
42931
43162
  try {
42932
43163
  count2 += (await readScheduleDocument(directory)).schedules.length;
42933
43164
  } catch (error62) {
42934
- broken.push(`${path58.basename(directory)}: ${reason(error62)}`);
43165
+ broken.push(`${path59.basename(directory)}: ${reason(error62)}`);
42935
43166
  }
42936
43167
  }
42937
43168
  const tick = options.scheduler.lastTickAt;
@@ -43001,7 +43232,7 @@ function runCanary(options) {
43001
43232
  }
43002
43233
  async function dailyCanaryEnabled(root = bridgeRoot()) {
43003
43234
  if (process.env.PHREN_CANARY_DAILY === "1") return true;
43004
- return !!(await lstat14(path58.join(root, "canary-daily")).catch(() => void 0))?.isFile();
43235
+ return !!(await lstat14(path59.join(root, "canary-daily")).catch(() => void 0))?.isFile();
43005
43236
  }
43006
43237
  async function dailyCanaryDue(root = bridgeRoot(), now = Date.now()) {
43007
43238
  if (running || !await dailyCanaryEnabled(root)) return false;
@@ -43014,11 +43245,11 @@ init_shared();
43014
43245
 
43015
43246
  // src/bridge/server-routes.ts
43016
43247
  init_zod();
43017
- import path81 from "node:path";
43248
+ import path82 from "node:path";
43018
43249
 
43019
43250
  // src/bridge/code-note.ts
43020
43251
  init_zod();
43021
- import * as path64 from "node:path";
43252
+ import * as path65 from "node:path";
43022
43253
 
43023
43254
  // src/content/validate.ts
43024
43255
  init_utils_helpers();
@@ -43032,7 +43263,7 @@ init_store_routing();
43032
43263
  init_locks();
43033
43264
  init_data_utils();
43034
43265
  import * as fs28 from "fs";
43035
- import * as path60 from "path";
43266
+ import * as path61 from "path";
43036
43267
  import * as crypto7 from "crypto";
43037
43268
 
43038
43269
  // src/project-topics.ts
@@ -43044,7 +43275,7 @@ init_data_utils();
43044
43275
  init_filenames();
43045
43276
  import * as crypto6 from "crypto";
43046
43277
  import * as fs27 from "fs";
43047
- import * as path59 from "path";
43278
+ import * as path60 from "path";
43048
43279
  var TOPIC_CONFIG_FILENAME = "topic-config.json";
43049
43280
  var SOFTWARE_TOPICS = [
43050
43281
  {
@@ -43582,7 +43813,7 @@ function topicDocHeader(project, topic) {
43582
43813
  }
43583
43814
  function appendArchivedEntriesToTopicDoc(filePath, project, topic, entries2) {
43584
43815
  if (entries2.length === 0) return;
43585
- fs27.mkdirSync(path59.dirname(filePath), { recursive: true });
43816
+ fs27.mkdirSync(path60.dirname(filePath), { recursive: true });
43586
43817
  withFileLock(filePath, () => {
43587
43818
  let existing = "";
43588
43819
  if (fs27.existsSync(filePath)) existing = fs27.readFileSync(filePath, "utf8");
@@ -43701,7 +43932,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
43701
43932
  if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
43702
43933
  const resolvedDir = storeAwareProjectPath(phrenPath, project);
43703
43934
  if (!resolvedDir || !fs28.existsSync(resolvedDir)) return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
43704
- const learningsPath = path60.join(resolvedDir, FINDINGS_FILENAME);
43935
+ const learningsPath = path61.join(resolvedDir, FINDINGS_FILENAME);
43705
43936
  if (!fs28.existsSync(learningsPath)) return phrenOk(0);
43706
43937
  const STALE_LOCK_MS = 6e5;
43707
43938
  const lockFile = runtimeFile(phrenPath, `consolidation-${project}.lock`);
@@ -43710,8 +43941,8 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
43710
43941
  } catch (e) {
43711
43942
  if (e.code === "EEXIST") {
43712
43943
  try {
43713
- const stat26 = fs28.statSync(lockFile);
43714
- if (Date.now() - stat26.mtimeMs < STALE_LOCK_MS) {
43944
+ const stat27 = fs28.statSync(lockFile);
43945
+ if (Date.now() - stat27.mtimeMs < STALE_LOCK_MS) {
43715
43946
  return phrenErr("Consolidation already running", PhrenError.LOCK_TIMEOUT);
43716
43947
  }
43717
43948
  tryUnlink(lockFile);
@@ -43737,7 +43968,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
43737
43968
  const entries2 = parseActiveEntries(content);
43738
43969
  if (entries2.length <= keepCount) return phrenOk(0);
43739
43970
  const toArchive = entries2.slice(0, entries2.length - keepCount);
43740
- const referenceDir = path60.join(resolvedDir, "reference");
43971
+ const referenceDir = path61.join(resolvedDir, "reference");
43741
43972
  const { topics } = readProjectTopics(phrenPath, project);
43742
43973
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
43743
43974
  const archivedSet = buildArchivedBulletSet(referenceDir);
@@ -44301,7 +44532,7 @@ var DEFAULT_DECAY = {
44301
44532
  var DEFAULT_UNDATED_CONFIDENCE = DEFAULT_DECAY.d120;
44302
44533
 
44303
44534
  // src/content/dedup.ts
44304
- import * as path61 from "path";
44535
+ import * as path62 from "path";
44305
44536
  init_shared();
44306
44537
  init_utils();
44307
44538
  init_store_routing();
@@ -44425,7 +44656,7 @@ function resolveCoref(text4, context) {
44425
44656
  result = result.replace(/\bthe project\b/gi, context.project);
44426
44657
  }
44427
44658
  if (context.file) {
44428
- const basename12 = path61.basename(context.file);
44659
+ const basename12 = path62.basename(context.file);
44429
44660
  result = result.replace(/\b(this file|the file)\b/gi, basename12);
44430
44661
  }
44431
44662
  if (context.project && /\b(it|this|that|they|them)\b/i.test(result)) {
@@ -44442,7 +44673,7 @@ init_shared();
44442
44673
  init_shared();
44443
44674
  init_governance();
44444
44675
  import * as fs30 from "fs";
44445
- import * as path63 from "path";
44676
+ import * as path64 from "path";
44446
44677
  import * as crypto8 from "crypto";
44447
44678
 
44448
44679
  // src/finding-graph-id.ts
@@ -44477,7 +44708,7 @@ init_store_routing();
44477
44708
  // src/finding/context.ts
44478
44709
  init_utils();
44479
44710
  import * as fs29 from "fs";
44480
- import * as path62 from "path";
44711
+ import * as path63 from "path";
44481
44712
 
44482
44713
  // src/session/utils.ts
44483
44714
  init_utils();
@@ -44559,14 +44790,14 @@ function resolveFindingTaskReference(phrenPath, project, match) {
44559
44790
  const projectDir = safeProjectPath(phrenPath, project);
44560
44791
  if (!projectDir) return { error: `Invalid project name: "${project}".` };
44561
44792
  const taskPath = resolveTaskFilePath(phrenPath, project);
44562
- const items = parseTaskItems(taskPath ?? path62.join(projectDir, "tasks.md"));
44793
+ const items = parseTaskItems(taskPath ?? path63.join(projectDir, "tasks.md"));
44563
44794
  return resolveTaskItemMatch(items, match);
44564
44795
  }
44565
44796
  function resolveAutoFindingTaskItem(phrenPath, project) {
44566
44797
  const projectDir = safeProjectPath(phrenPath, project);
44567
44798
  if (!projectDir) return void 0;
44568
44799
  const taskPath = resolveTaskFilePath(phrenPath, project);
44569
- const active = parseTaskItems(taskPath ?? path62.join(projectDir, "tasks.md")).filter(
44800
+ const active = parseTaskItems(taskPath ?? path63.join(projectDir, "tasks.md")).filter(
44570
44801
  (item) => item.section === "Active" && item.stableId
44571
44802
  );
44572
44803
  if (active.length === 1) return active[0].stableId;
@@ -44606,7 +44837,7 @@ function buildFindingCitation(citationInput, nowIso, inferredRepo, headCommit) {
44606
44837
  function resolveInferredCitationRepo(citationInput) {
44607
44838
  if (citationInput?.repo) return citationInput.repo;
44608
44839
  if (citationInput?.file) {
44609
- const fileDir = path63.dirname(citationInput.file);
44840
+ const fileDir = path64.dirname(citationInput.file);
44610
44841
  return getRepoRoot(fileDir);
44611
44842
  }
44612
44843
  return void 0;
@@ -44741,7 +44972,7 @@ function addFindingToFile(phrenPath, project, learning, citationInput, opts) {
44741
44972
  if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
44742
44973
  const resolvedDir = storeAwareProjectPath(phrenPath, project);
44743
44974
  if (!resolvedDir) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
44744
- const learningsPath = path63.join(resolvedDir, FINDINGS_FILENAME);
44975
+ const learningsPath = path64.join(resolvedDir, FINDINGS_FILENAME);
44745
44976
  const nowIso = (opts?.now ?? /* @__PURE__ */ new Date()).toISOString();
44746
44977
  const today = nowIso.slice(0, 10);
44747
44978
  const resolvedCitationInputResult = resolveFindingCitationInput(phrenPath, project, citationInput);
@@ -44923,7 +45154,7 @@ var codeNoteSchema = external_exports.object({
44923
45154
  // phone's spelling, accepted until 0.3.1.
44924
45155
  name: external_exports.string().min(1).max(4600).optional(),
44925
45156
  symbol: external_exports.string().min(1).max(4600).optional(),
44926
- file: external_exports.string().min(1).max(4096).refine((file2) => !path64.isAbsolute(file2) && !file2.includes("\0") && !file2.split(/[\\/]/).includes("..")),
45157
+ file: external_exports.string().min(1).max(4096).refine((file2) => !path65.isAbsolute(file2) && !file2.includes("\0") && !file2.split(/[\\/]/).includes("..")),
44927
45158
  line: external_exports.number().int().positive(),
44928
45159
  text: external_exports.string().trim().min(1).max(4500).refine((text4) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text4)),
44929
45160
  target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(["codex", "claude", "opencode"]) }).strict()]).optional()
@@ -44973,29 +45204,29 @@ init_utils_helpers();
44973
45204
  init_protocol();
44974
45205
  init_herdr();
44975
45206
  init_transcripts();
44976
- import { execFile as execFile11 } from "node:child_process";
44977
- import { promisify as promisify10 } from "node:util";
45207
+ import { execFile as execFile12 } from "node:child_process";
45208
+ import { promisify as promisify11 } from "node:util";
44978
45209
  import { realpathSync as realpathSync5 } from "node:fs";
44979
- import { readdir as readdir11, readFile as readFile27, stat as stat19, mkdir as mkdir15 } from "node:fs/promises";
45210
+ import { readdir as readdir12, readFile as readFile27, stat as stat20, mkdir as mkdir15 } from "node:fs/promises";
44980
45211
  import { homedir as homedir17 } from "node:os";
44981
- import path69 from "node:path";
45212
+ import path70 from "node:path";
44982
45213
 
44983
45214
  // src/core/project.ts
44984
45215
  init_shared();
44985
- import * as path67 from "path";
45216
+ import * as path68 from "path";
44986
45217
 
44987
45218
  // src/core/project-registry.ts
44988
45219
  init_phren_paths();
44989
45220
  import * as fs32 from "fs";
44990
- import * as path66 from "path";
45221
+ import * as path67 from "path";
44991
45222
 
44992
45223
  // src/git-worktree.ts
44993
45224
  import * as fs31 from "fs";
44994
- import * as path65 from "path";
45225
+ import * as path66 from "path";
44995
45226
  var WORKTREE_CONTAINER_NAMES = /* @__PURE__ */ new Set(["worktrees", ".worktrees"]);
44996
- var LINKED_WORKTREE_SEGMENT = `${path65.sep}.git${path65.sep}worktrees${path65.sep}`;
45227
+ var LINKED_WORKTREE_SEGMENT = `${path66.sep}.git${path66.sep}worktrees${path66.sep}`;
44997
45228
  function resolveWorktreeParent(dir) {
44998
- const resolved = path65.resolve(dir);
45229
+ const resolved = path66.resolve(dir);
44999
45230
  const agentParent = parentFromAgentWorktreePath(resolved);
45000
45231
  if (agentParent) return { repoRoot: agentParent, reason: "agent-worktree-dir" };
45001
45232
  const linkedParent = parentFromLinkedWorktree(resolved);
@@ -45003,23 +45234,23 @@ function resolveWorktreeParent(dir) {
45003
45234
  return null;
45004
45235
  }
45005
45236
  function parentFromAgentWorktreePath(resolved) {
45006
- const segments = resolved.split(path65.sep);
45237
+ const segments = resolved.split(path66.sep);
45007
45238
  for (let i = 1; i < segments.length; i++) {
45008
45239
  if (!WORKTREE_CONTAINER_NAMES.has(segments[i])) continue;
45009
45240
  let j = i - 1;
45010
45241
  if (!segments[j]?.startsWith(".")) continue;
45011
45242
  while (j >= 1 && segments[j].startsWith(".")) j--;
45012
45243
  if (j < 1) continue;
45013
- return segments.slice(0, j + 1).join(path65.sep) || path65.sep;
45244
+ return segments.slice(0, j + 1).join(path66.sep) || path66.sep;
45014
45245
  }
45015
45246
  return null;
45016
45247
  }
45017
45248
  function parentFromLinkedWorktree(resolved) {
45018
45249
  let current2 = resolved;
45019
45250
  while (true) {
45020
- const parent = repoRootFromGitFile(path65.join(current2, ".git"));
45251
+ const parent = repoRootFromGitFile(path66.join(current2, ".git"));
45021
45252
  if (parent) return parent;
45022
- const next = path65.dirname(current2);
45253
+ const next = path66.dirname(current2);
45023
45254
  if (next === current2) return null;
45024
45255
  current2 = next;
45025
45256
  }
@@ -45034,7 +45265,7 @@ function repoRootFromGitFile(gitPath) {
45034
45265
  }
45035
45266
  const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
45036
45267
  if (!match) return null;
45037
- const gitDir = path65.resolve(path65.dirname(gitPath), match[1].replace(/[/\\]/g, path65.sep));
45268
+ const gitDir = path66.resolve(path66.dirname(gitPath), match[1].replace(/[/\\]/g, path66.sep));
45038
45269
  const idx = gitDir.indexOf(LINKED_WORKTREE_SEGMENT);
45039
45270
  if (idx === -1) return null;
45040
45271
  return gitDir.slice(0, idx);
@@ -45187,8 +45418,8 @@ function addTermCount(terms, rawText, weight = 1) {
45187
45418
  }
45188
45419
  function maybeReadUtf8(filePath, maxBytes = 256e3) {
45189
45420
  try {
45190
- const stat26 = fs32.statSync(filePath);
45191
- if (!stat26.isFile() || stat26.size > maxBytes) return "";
45421
+ const stat27 = fs32.statSync(filePath);
45422
+ if (!stat27.isFile() || stat27.size > maxBytes) return "";
45192
45423
  return fs32.readFileSync(filePath, "utf8");
45193
45424
  } catch {
45194
45425
  return "";
@@ -45247,7 +45478,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
45247
45478
  return topics;
45248
45479
  }
45249
45480
  function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
45250
- const resolvedRoot = path66.resolve(repoRoot);
45481
+ const resolvedRoot = path67.resolve(repoRoot);
45251
45482
  if (!fs32.existsSync(resolvedRoot)) return null;
45252
45483
  const signal = {
45253
45484
  domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
@@ -45258,7 +45489,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
45258
45489
  usefulSignals: 0
45259
45490
  };
45260
45491
  const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
45261
- const packageJsonPath = path66.join(resolvedRoot, "package.json");
45492
+ const packageJsonPath = path67.join(resolvedRoot, "package.json");
45262
45493
  if (fs32.existsSync(packageJsonPath)) {
45263
45494
  signal.usefulSignals++;
45264
45495
  addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
@@ -45288,33 +45519,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
45288
45519
  debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
45289
45520
  }
45290
45521
  }
45291
- const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(path66.join(resolvedRoot, fileName)));
45522
+ const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(path67.join(resolvedRoot, fileName)));
45292
45523
  for (const configName of topLevelConfigs) {
45293
45524
  signal.usefulSignals++;
45294
45525
  const configScore = DOMAIN_CONFIG_HINTS[configName];
45295
45526
  if (configScore) addDomainScores(signal.domainScores, configScore);
45296
45527
  }
45297
45528
  const readmeCandidates = [
45298
- path66.join(resolvedRoot, "README.md"),
45299
- path66.join(resolvedRoot, "readme.md")
45529
+ path67.join(resolvedRoot, "README.md"),
45530
+ path67.join(resolvedRoot, "readme.md")
45300
45531
  ];
45301
45532
  for (const readmePath of readmeCandidates) {
45302
45533
  if (!fs32.existsSync(readmePath)) continue;
45303
45534
  const content = maybeReadUtf8(readmePath);
45304
45535
  if (!content) continue;
45305
45536
  signal.usefulSignals++;
45306
- signal.referenceHints.push(path66.relative(resolvedRoot, readmePath));
45537
+ signal.referenceHints.push(path67.relative(resolvedRoot, readmePath));
45307
45538
  addTermCount(signal.terms, content, 2);
45308
45539
  signal.docsText += ` ${content.toLowerCase()}`;
45309
45540
  break;
45310
45541
  }
45311
- const docsDir = path66.join(resolvedRoot, "docs");
45542
+ const docsDir = path67.join(resolvedRoot, "docs");
45312
45543
  if (fs32.existsSync(docsDir) && fs32.statSync(docsDir).isDirectory()) {
45313
45544
  signal.referenceHints.push("docs/");
45314
45545
  for (const entry of fs32.readdirSync(docsDir, { withFileTypes: true })) {
45315
45546
  if (!entry.isFile()) continue;
45316
45547
  if (!/\.(md|txt|rst)$/i.test(entry.name)) continue;
45317
- const docsContent = maybeReadUtf8(path66.join(docsDir, entry.name));
45548
+ const docsContent = maybeReadUtf8(path67.join(docsDir, entry.name));
45318
45549
  if (!docsContent) continue;
45319
45550
  signal.usefulSignals++;
45320
45551
  addTermCount(signal.terms, docsContent, 1);
@@ -45322,7 +45553,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
45322
45553
  }
45323
45554
  }
45324
45555
  for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
45325
- const fullPath = path66.join(resolvedRoot, folderName);
45556
+ const fullPath = path67.join(resolvedRoot, folderName);
45326
45557
  if (fs32.existsSync(fullPath)) {
45327
45558
  signal.referenceHints.push(`${folderName}/`);
45328
45559
  }
@@ -45333,14 +45564,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
45333
45564
  if (scannedFiles >= maxFiles) return;
45334
45565
  for (const entry of fs32.readdirSync(dir, { withFileTypes: true })) {
45335
45566
  if (scannedFiles >= maxFiles) return;
45336
- const fullPath = path66.join(dir, entry.name);
45567
+ const fullPath = path67.join(dir, entry.name);
45337
45568
  if (entry.isDirectory()) {
45338
45569
  if (skipDirs.has(entry.name)) continue;
45339
45570
  walk(fullPath);
45340
45571
  continue;
45341
45572
  }
45342
45573
  scannedFiles++;
45343
- const ext = path66.extname(entry.name).toLowerCase();
45574
+ const ext = path67.extname(entry.name).toLowerCase();
45344
45575
  if (!ext) continue;
45345
45576
  const extScore = EXTENSION_DOMAIN_HINTS[ext];
45346
45577
  if (extScore) {
@@ -45514,7 +45745,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
45514
45745
  return null;
45515
45746
  }
45516
45747
  };
45517
- const resolvedSource = path66.resolve(sourceRoot);
45748
+ const resolvedSource = path67.resolve(sourceRoot);
45518
45749
  for (const project of candidates) {
45519
45750
  if (sourceOf(project) === resolvedSource) return project;
45520
45751
  }
@@ -45528,7 +45759,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
45528
45759
  function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
45529
45760
  const profile = typeof opts === "string" ? opts : opts.profile;
45530
45761
  const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
45531
- const resolvedPath = path66.resolve(projectPath);
45762
+ const resolvedPath = path67.resolve(projectPath);
45532
45763
  if (!fs32.existsSync(resolvedPath)) {
45533
45764
  throw new Error(`Path does not exist: ${resolvedPath}`);
45534
45765
  }
@@ -45539,17 +45770,17 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
45539
45770
  if (worktreeRepoRoot) {
45540
45771
  debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
45541
45772
  }
45542
- const sourceRoot = isProjectLocal ? path66.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
45773
+ const sourceRoot = isProjectLocal ? path67.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
45543
45774
  if (isProjectLocal) {
45544
- const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path66.sep);
45775
+ const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path67.sep);
45545
45776
  if (!matchesWorkspace) {
45546
45777
  throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
45547
45778
  }
45548
45779
  }
45549
45780
  let claudeMdPath = null;
45550
45781
  const candidates = [
45551
- path66.join(sourceRoot, "AGENTS.md"),
45552
- path66.join(sourceRoot, ".claude", "CLAUDE.md")
45782
+ path67.join(sourceRoot, "AGENTS.md"),
45783
+ path67.join(sourceRoot, ".claude", "CLAUDE.md")
45553
45784
  ];
45554
45785
  for (const c of candidates) {
45555
45786
  if (fs32.existsSync(c)) {
@@ -45569,12 +45800,12 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
45569
45800
  `Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
45570
45801
  );
45571
45802
  }
45572
- const projDir = path66.join(phrenPath, projectName2);
45803
+ const projDir = path67.join(phrenPath, projectName2);
45573
45804
  fs32.mkdirSync(projDir, { recursive: true });
45574
45805
  const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
45575
45806
  const existingConfig = readProjectConfig(phrenPath, projectName2);
45576
45807
  const ownership = typeof opts === "string" ? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath) : opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath);
45577
- const claudePath = path66.join(projDir, "AGENTS.md");
45808
+ const claudePath = path67.join(projDir, "AGENTS.md");
45578
45809
  if (ownership !== "repo-managed") {
45579
45810
  if (claudeContent) {
45580
45811
  if (!fs32.existsSync(claudePath)) {
@@ -45609,7 +45840,7 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
45609
45840
  }
45610
45841
  }
45611
45842
  const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
45612
- const summaryPath = path66.join(projDir, "summary.md");
45843
+ const summaryPath = path67.join(projDir, "summary.md");
45613
45844
  if (!fs32.existsSync(summaryPath)) {
45614
45845
  atomicWriteText(
45615
45846
  summaryPath,
@@ -45622,18 +45853,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
45622
45853
  `
45623
45854
  );
45624
45855
  }
45625
- if (!fs32.existsSync(path66.join(projDir, FINDINGS_FILENAME))) {
45856
+ if (!fs32.existsSync(path67.join(projDir, FINDINGS_FILENAME))) {
45626
45857
  atomicWriteText(
45627
- path66.join(projDir, FINDINGS_FILENAME),
45858
+ path67.join(projDir, FINDINGS_FILENAME),
45628
45859
  `# ${projectName2} FINDINGS
45629
45860
 
45630
45861
  <!-- Bootstrapped from ${sourceRoot} -->
45631
45862
  `
45632
45863
  );
45633
45864
  }
45634
- if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(path66.join(projDir, TASKS_FILENAME))) {
45865
+ if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(path67.join(projDir, TASKS_FILENAME))) {
45635
45866
  atomicWriteText(
45636
- path66.join(projDir, TASKS_FILENAME),
45867
+ path67.join(projDir, TASKS_FILENAME),
45637
45868
  `# ${projectName2} tasks
45638
45869
 
45639
45870
  ## Active
@@ -45644,11 +45875,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
45644
45875
  `
45645
45876
  );
45646
45877
  }
45647
- if (!fs32.existsSync(path66.join(projDir, "topic-config.json"))) {
45878
+ if (!fs32.existsSync(path67.join(projDir, "topic-config.json"))) {
45648
45879
  const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
45649
45880
  const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
45650
45881
  atomicWriteText(
45651
- path66.join(projDir, "topic-config.json"),
45882
+ path67.join(projDir, "topic-config.json"),
45652
45883
  JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
45653
45884
  );
45654
45885
  }
@@ -45680,10 +45911,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
45680
45911
  if (!activeProfile.ok) return activeProfile;
45681
45912
  const writePhrenPath = options.writeToPath ?? phrenPath;
45682
45913
  const manifest = readRootManifest(phrenPath);
45683
- const resolvedPath = path67.resolve(targetPath);
45914
+ const resolvedPath = path68.resolve(targetPath);
45684
45915
  if (manifest?.installMode === "project-local") {
45685
- const workspaceRoot = path67.resolve(manifest.workspaceRoot || "");
45686
- const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path67.sep);
45916
+ const workspaceRoot = path68.resolve(manifest.workspaceRoot || "");
45917
+ const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path68.sep);
45687
45918
  if (!matchesWorkspace) {
45688
45919
  return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
45689
45920
  }
@@ -45701,9 +45932,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
45701
45932
  ownership: added.ownership,
45702
45933
  files: {
45703
45934
  claude: added.claudePath,
45704
- summary: path67.join(writePhrenPath, added.project, "summary.md"),
45705
- findings: path67.join(writePhrenPath, added.project, FINDINGS_FILENAME),
45706
- task: path67.join(writePhrenPath, added.project, TASKS_FILENAME)
45935
+ summary: path68.join(writePhrenPath, added.project, "summary.md"),
45936
+ findings: path68.join(writePhrenPath, added.project, FINDINGS_FILENAME),
45937
+ task: path68.join(writePhrenPath, added.project, TASKS_FILENAME)
45707
45938
  }
45708
45939
  });
45709
45940
  }
@@ -45729,7 +45960,7 @@ import { execFileSync as execFileSync6, spawnSync as spawnSync2 } from "child_pr
45729
45960
  import * as crypto9 from "crypto";
45730
45961
  import * as fs33 from "fs";
45731
45962
  import * as os3 from "os";
45732
- import * as path68 from "path";
45963
+ import * as path69 from "path";
45733
45964
 
45734
45965
  // src/content/summarize.ts
45735
45966
  init_phren_dotenv();
@@ -45890,7 +46121,7 @@ function mergeTasksByBid(base, ours, theirs) {
45890
46121
  // src/sync/conflict-resolve.ts
45891
46122
  function conflictStrategy(relFile) {
45892
46123
  const file2 = relFile.replace(/\\/g, "/");
45893
- const name = path68.posix.basename(file2).toLowerCase();
46124
+ const name = path69.posix.basename(file2).toLowerCase();
45894
46125
  if (isTaskFileName(name)) return "tasks";
45895
46126
  if (name === "findings.md") return "findings";
45896
46127
  if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file2)) return "archive";
@@ -45925,9 +46156,9 @@ function splitBlock(content, start, end) {
45925
46156
  function mergeText(base, ours, theirs) {
45926
46157
  if (ours === theirs || ours === base) return theirs;
45927
46158
  if (theirs === base) return ours;
45928
- const dir = fs33.mkdtempSync(path68.join(os3.tmpdir(), "phren-merge-"));
46159
+ const dir = fs33.mkdtempSync(path69.join(os3.tmpdir(), "phren-merge-"));
45929
46160
  try {
45930
- const [o, b, t] = ["ours", "base", "theirs"].map((name) => path68.join(dir, name));
46161
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path69.join(dir, name));
45931
46162
  fs33.writeFileSync(o, ours);
45932
46163
  fs33.writeFileSync(b, base);
45933
46164
  fs33.writeFileSync(t, theirs);
@@ -45940,9 +46171,9 @@ function mergeText(base, ours, theirs) {
45940
46171
  function unionText(base, ours, theirs) {
45941
46172
  const clean2 = mergeText(base, ours, theirs);
45942
46173
  if (clean2 !== null) return clean2;
45943
- const dir = fs33.mkdtempSync(path68.join(os3.tmpdir(), "phren-merge-"));
46174
+ const dir = fs33.mkdtempSync(path69.join(os3.tmpdir(), "phren-merge-"));
45944
46175
  try {
45945
- const [o, b, t] = ["ours", "base", "theirs"].map((name) => path68.join(dir, name));
46176
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path69.join(dir, name));
45946
46177
  fs33.writeFileSync(o, ours);
45947
46178
  fs33.writeFileSync(b, base);
45948
46179
  fs33.writeFileSync(t, theirs);
@@ -46002,7 +46233,7 @@ function resolveStoreConflicts(cwd) {
46002
46233
  const base = stage(cwd, 1, relFile) ?? "";
46003
46234
  const ours = stage(cwd, 2, relFile);
46004
46235
  const theirs = stage(cwd, 3, relFile);
46005
- const fullPath = path68.join(cwd, relFile);
46236
+ const fullPath = path69.join(cwd, relFile);
46006
46237
  if (ours === null && theirs === null) {
46007
46238
  unresolved.push(relFile);
46008
46239
  continue;
@@ -46013,7 +46244,7 @@ function resolveStoreConflicts(cwd) {
46013
46244
  continue;
46014
46245
  }
46015
46246
  const tmp = `${fullPath}.tmp-${crypto9.randomUUID()}`;
46016
- fs33.mkdirSync(path68.dirname(fullPath), { recursive: true });
46247
+ fs33.mkdirSync(path69.dirname(fullPath), { recursive: true });
46017
46248
  fs33.writeFileSync(tmp, merged);
46018
46249
  fs33.renameSync(tmp, fullPath);
46019
46250
  git4(cwd, ["add", "--", relFile]);
@@ -46280,7 +46511,7 @@ async function runBestEffortGit(args, cwd) {
46280
46511
  // src/bridge/enroll.ts
46281
46512
  init_metrics();
46282
46513
  init_machine_identity();
46283
- var exec10 = promisify10(execFile11);
46514
+ var exec11 = promisify11(execFile12);
46284
46515
  var runEnrollStoreGit = async (cwd, args) => {
46285
46516
  const result = await runBestEffortGit(args, cwd);
46286
46517
  return { ok: result.ok, output: result.output ?? "", error: result.error };
@@ -46293,7 +46524,7 @@ function repoName(url2) {
46293
46524
  }
46294
46525
  async function isRepository(directory) {
46295
46526
  try {
46296
- await stat19(path69.join(directory, ".git"));
46527
+ await stat20(path70.join(directory, ".git"));
46297
46528
  return true;
46298
46529
  } catch {
46299
46530
  return false;
@@ -46304,7 +46535,7 @@ async function registeredSources(env) {
46304
46535
  const paths = /* @__PURE__ */ new Set(), names = /* @__PURE__ */ new Set();
46305
46536
  let entries2 = [];
46306
46537
  try {
46307
- entries2 = (await readdir11(store, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
46538
+ entries2 = (await readdir12(store, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
46308
46539
  } catch {
46309
46540
  return { paths, names };
46310
46541
  }
@@ -46313,7 +46544,7 @@ async function registeredSources(env) {
46313
46544
  const source = readProjectConfig(store, project).sourcePath;
46314
46545
  if (typeof source === "string" && source) {
46315
46546
  try {
46316
- paths.add(realpathSync5.native(path69.resolve(source)));
46547
+ paths.add(realpathSync5.native(path70.resolve(source)));
46317
46548
  } catch {
46318
46549
  }
46319
46550
  }
@@ -46325,9 +46556,9 @@ async function candidateRepos(activity, env = process.env) {
46325
46556
  const found = [];
46326
46557
  const seen = /* @__PURE__ */ new Set();
46327
46558
  const offer = async (directory, source, lastSeen) => {
46328
- let dir = path69.resolve(directory);
46559
+ let dir = path70.resolve(directory);
46329
46560
  try {
46330
- if (!(await stat19(dir)).isDirectory()) return;
46561
+ if (!(await stat20(dir)).isDirectory()) return;
46331
46562
  dir = realpathSync5.native(dir);
46332
46563
  } catch {
46333
46564
  return;
@@ -46339,39 +46570,39 @@ async function candidateRepos(activity, env = process.env) {
46339
46570
  };
46340
46571
  const toplevel = async (directory) => {
46341
46572
  let existing = directory;
46342
- while (!await stat19(existing).catch(() => void 0)) {
46343
- const parent = path69.dirname(existing);
46573
+ while (!await stat20(existing).catch(() => void 0)) {
46574
+ const parent = path70.dirname(existing);
46344
46575
  if (parent === existing) return void 0;
46345
46576
  existing = parent;
46346
46577
  }
46347
46578
  try {
46348
46579
  countGit("enroll");
46349
- return (await exec10("git", ["-C", existing, "rev-parse", "--show-toplevel"], { env: nonInteractiveGitEnv(), timeout: 5e3 })).stdout.trim() || void 0;
46580
+ return (await exec11("git", ["-C", existing, "rev-parse", "--show-toplevel"], { env: nonInteractiveGitEnv(), timeout: 5e3 })).stdout.trim() || void 0;
46350
46581
  } catch {
46351
46582
  return void 0;
46352
46583
  }
46353
46584
  };
46354
46585
  for (const event of [...activity].reverse()) {
46355
46586
  const directory = typeof event.directory === "string" ? event.directory : void 0;
46356
- if (!directory || !path69.isAbsolute(directory)) continue;
46587
+ if (!directory || !path70.isAbsolute(directory)) continue;
46357
46588
  const root = await toplevel(directory);
46358
46589
  if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
46359
46590
  }
46360
46591
  try {
46361
- const session = JSON.parse(await readFile27(path69.join(herdrRoot(), "session.json"), "utf8"));
46592
+ const session = JSON.parse(await readFile27(path70.join(herdrRoot(), "session.json"), "utf8"));
46362
46593
  for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
46363
46594
  const directory = JSON.parse(`"${match[1]}"`);
46364
- if (!path69.isAbsolute(directory)) continue;
46595
+ if (!path70.isAbsolute(directory)) continue;
46365
46596
  const root = await toplevel(directory);
46366
46597
  if (root) await offer(root, "herdr");
46367
46598
  }
46368
46599
  } catch {
46369
46600
  }
46370
46601
  const home = homedir17();
46371
- for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path69.join(home, r))]) {
46602
+ for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path70.join(home, r))]) {
46372
46603
  let children = [];
46373
46604
  try {
46374
- children = (await readdir11(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path69.join(root, e.name));
46605
+ children = (await readdir12(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path70.join(root, e.name));
46375
46606
  } catch {
46376
46607
  continue;
46377
46608
  }
@@ -46381,13 +46612,13 @@ async function candidateRepos(activity, env = process.env) {
46381
46612
  }
46382
46613
  async function cloneRoot(env) {
46383
46614
  const home = homedir17();
46384
- for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path69.join(home, r))]) {
46615
+ for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path70.join(home, r))]) {
46385
46616
  try {
46386
- if ((await stat19(root)).isDirectory()) return root;
46617
+ if ((await stat20(root)).isDirectory()) return root;
46387
46618
  } catch {
46388
46619
  }
46389
46620
  }
46390
- const fallback = path69.join(home, "Projects");
46621
+ const fallback = path70.join(home, "Projects");
46391
46622
  await mkdir15(fallback, { recursive: true });
46392
46623
  return fallback;
46393
46624
  }
@@ -46409,7 +46640,7 @@ async function publishStore(store, project) {
46409
46640
  async function enrollProject(input2, env = process.env) {
46410
46641
  const store = phrenStoreRoot(env);
46411
46642
  try {
46412
- if (!(await stat19(path69.join(store, ".config"))).isDirectory()) throw new Error();
46643
+ if (!(await stat20(path70.join(store, ".config"))).isDirectory()) throw new Error();
46413
46644
  } catch {
46414
46645
  throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
46415
46646
  }
@@ -46420,16 +46651,16 @@ async function enrollProject(input2, env = process.env) {
46420
46651
  if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
46421
46652
  const name = repoName(url2);
46422
46653
  if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
46423
- directory = path69.join(await cloneRoot(env), name);
46654
+ directory = path70.join(await cloneRoot(env), name);
46424
46655
  try {
46425
- await stat19(directory);
46656
+ await stat20(directory);
46426
46657
  throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
46427
46658
  } catch (error62) {
46428
46659
  if (error62 instanceof BridgeError) throw error62;
46429
46660
  }
46430
46661
  try {
46431
46662
  countGit("enroll");
46432
- await exec10("git", ["clone", "--", url2, directory], { timeout: 18e4, maxBuffer: 4194304, env: nonInteractiveGitEnv(env) });
46663
+ await exec11("git", ["clone", "--", url2, directory], { timeout: 18e4, maxBuffer: 4194304, env: nonInteractiveGitEnv(env) });
46433
46664
  } catch (error62) {
46434
46665
  const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").pop() : void 0;
46435
46666
  throw new BridgeError(502, `git clone failed${detail ? `: ${detail}` : ""}.`);
@@ -46437,10 +46668,10 @@ async function enrollProject(input2, env = process.env) {
46437
46668
  cloned = true;
46438
46669
  } else if (typeof input2.directory === "string" && input2.directory) {
46439
46670
  const raw = input2.directory;
46440
- if (raw.length > 4096 || raw.includes("\0") || !path69.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
46671
+ if (raw.length > 4096 || raw.includes("\0") || !path70.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
46441
46672
  try {
46442
46673
  directory = realpathSync5.native(raw);
46443
- if (!(await stat19(directory)).isDirectory()) throw new Error();
46674
+ if (!(await stat20(directory)).isDirectory()) throw new Error();
46444
46675
  } catch {
46445
46676
  throw new BridgeError(404, "That folder is not on this computer.");
46446
46677
  }
@@ -46453,33 +46684,33 @@ async function enrollProject(input2, env = process.env) {
46453
46684
  // src/bridge/files.ts
46454
46685
  init_protocol();
46455
46686
  import { constants as constants3 } from "node:fs";
46456
- import { lstat as lstat15, open as open12, readdir as readdir12, realpath as realpath11 } from "node:fs/promises";
46457
- import path70 from "node:path";
46687
+ import { lstat as lstat15, open as open13, readdir as readdir13, realpath as realpath12 } from "node:fs/promises";
46688
+ import path71 from "node:path";
46458
46689
  var MAX_BYTES = 2097152;
46459
46690
  async function browseFiles(root, relative3) {
46460
- if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path70.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
46691
+ if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path71.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
46461
46692
  throw new BridgeError(400, "Invalid repository path.");
46462
46693
  }
46463
- const base = await realpath11(root);
46694
+ const base = await realpath12(root);
46464
46695
  let file2 = base;
46465
46696
  for (const part of relative3.split("/").filter((part2) => part2 && part2 !== ".")) {
46466
- file2 = path70.join(file2, part);
46697
+ file2 = path71.join(file2, part);
46467
46698
  if ((await lstat15(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
46468
46699
  }
46469
- const resolved = await realpath11(file2);
46470
- if (resolved !== base && !resolved.startsWith(base + path70.sep)) throw new BridgeError(403, "The path is outside this repository.");
46700
+ const resolved = await realpath12(file2);
46701
+ if (resolved !== base && !resolved.startsWith(base + path71.sep)) throw new BridgeError(403, "The path is outside this repository.");
46471
46702
  const metadata = await lstat15(resolved);
46472
46703
  if (metadata.isDirectory()) {
46473
- const entries2 = (await readdir12(resolved, { withFileTypes: true })).filter((entry) => entry.name !== ".git" && (entry.isDirectory() || entry.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
46704
+ const entries2 = (await readdir13(resolved, { withFileTypes: true })).filter((entry) => entry.name !== ".git" && (entry.isDirectory() || entry.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
46474
46705
  return {
46475
46706
  path: relative3,
46476
46707
  kind: "directory",
46477
46708
  truncated: entries2.length > 500,
46478
- entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path: path70.posix.join(relative3, entry.name), kind: entry.isDirectory() ? "directory" : "file" }))
46709
+ entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path: path71.posix.join(relative3, entry.name), kind: entry.isDirectory() ? "directory" : "file" }))
46479
46710
  };
46480
46711
  }
46481
46712
  if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
46482
- const handle = await open12(resolved, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
46713
+ const handle = await open13(resolved, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
46483
46714
  try {
46484
46715
  const current2 = await handle.stat();
46485
46716
  if (!current2.isFile() || current2.ino !== metadata.ino || current2.dev !== metadata.dev) throw new BridgeError(409, "The file changed. Refresh and try again.");
@@ -46501,8 +46732,8 @@ async function browseFiles(root, relative3) {
46501
46732
  // src/bridge/file-range.ts
46502
46733
  init_protocol();
46503
46734
  import { constants as constants4 } from "node:fs";
46504
- import { lstat as lstat16, open as open13, realpath as realpath12 } from "node:fs/promises";
46505
- import path71 from "node:path";
46735
+ import { lstat as lstat16, open as open14, realpath as realpath13 } from "node:fs/promises";
46736
+ import path72 from "node:path";
46506
46737
  var MAX_FILE_RANGE = 4 * 1024 * 1024;
46507
46738
  var types = {
46508
46739
  mp4: "video/mp4",
@@ -46539,11 +46770,11 @@ var types = {
46539
46770
  xml: "text/xml"
46540
46771
  };
46541
46772
  function fileContentType(file2) {
46542
- const ext = path71.extname(file2).slice(1).toLowerCase();
46773
+ const ext = path72.extname(file2).slice(1).toLowerCase();
46543
46774
  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");
46544
46775
  }
46545
- function version2(stat26) {
46546
- return `${stat26.dev}:${stat26.ino}:${stat26.size}:${stat26.mtimeMs}:${stat26.ctimeMs}`;
46776
+ function version2(stat27) {
46777
+ return `${stat27.dev}:${stat27.ino}:${stat27.size}:${stat27.mtimeMs}:${stat27.ctimeMs}`;
46547
46778
  }
46548
46779
  function rangeInteger(value2, fallback) {
46549
46780
  if (value2 === null) return fallback;
@@ -46556,22 +46787,22 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
46556
46787
  throw new BridgeError(400, "File ranges must be between 0 and 4 MiB.");
46557
46788
  }
46558
46789
  try {
46559
- const base = await realpath12(root);
46560
- const relative3 = path71.isAbsolute(requested) ? path71.relative(base, requested) : requested;
46561
- if (relative3 === ".." || relative3.startsWith(`..${path71.sep}`) || path71.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
46790
+ const base = await realpath13(root);
46791
+ const relative3 = path72.isAbsolute(requested) ? path72.relative(base, requested) : requested;
46792
+ if (relative3 === ".." || relative3.startsWith(`..${path72.sep}`) || path72.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
46562
46793
  let file2 = base;
46563
- for (const part of relative3.split(path71.sep).filter((part2) => part2 && part2 !== ".")) {
46564
- file2 = path71.join(file2, part);
46794
+ for (const part of relative3.split(path72.sep).filter((part2) => part2 && part2 !== ".")) {
46795
+ file2 = path72.join(file2, part);
46565
46796
  if ((await lstat16(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
46566
46797
  }
46567
- const resolved = await realpath12(file2);
46568
- if (!resolved.startsWith(base + path71.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
46798
+ const resolved = await realpath13(file2);
46799
+ if (!resolved.startsWith(base + path72.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
46569
46800
  const metadata = await lstat16(resolved);
46570
46801
  if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be opened.");
46571
- const handle = await open13(resolved, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
46802
+ const handle = await open14(resolved, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
46572
46803
  try {
46573
46804
  const current2 = await handle.stat();
46574
- if (!current2.isFile() || version2(current2) !== version2(metadata) || await realpath12(file2) !== resolved) {
46805
+ if (!current2.isFile() || version2(current2) !== version2(metadata) || await realpath13(file2) !== resolved) {
46575
46806
  throw new BridgeError(409, "The file changed. Open it again.");
46576
46807
  }
46577
46808
  const revision = version2(current2);
@@ -46607,12 +46838,12 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
46607
46838
  // src/bridge/memory-store.ts
46608
46839
  init_zod();
46609
46840
  init_protocol();
46610
- import { execFile as execFile12 } from "node:child_process";
46841
+ import { execFile as execFile13 } from "node:child_process";
46611
46842
  import { createHash as createHash15 } from "node:crypto";
46612
- import { lstat as lstat17, mkdir as mkdir16, readFile as readFile28, realpath as realpath13, rename as rename7, rm as rm8, writeFile as writeFile8 } from "node:fs/promises";
46613
- import path72 from "node:path";
46614
- import { promisify as promisify11 } from "node:util";
46615
- var exec11 = promisify11(execFile12);
46843
+ import { lstat as lstat17, mkdir as mkdir16, readFile as readFile28, realpath as realpath14, rename as rename7, rm as rm8, writeFile as writeFile8 } from "node:fs/promises";
46844
+ import path73 from "node:path";
46845
+ import { promisify as promisify12 } from "node:util";
46846
+ var exec12 = promisify12(execFile13);
46616
46847
  var SHA = /^[0-9a-f]{40}$/;
46617
46848
  var MAX_FILE = 4 * 1024 * 1024;
46618
46849
  var queue = Promise.resolve();
@@ -46623,7 +46854,7 @@ function serialized(work) {
46623
46854
  }
46624
46855
  async function git5(store, args, env = {}) {
46625
46856
  try {
46626
- const { stdout } = await exec11("git", ["-C", store, ...args], {
46857
+ const { stdout } = await exec12("git", ["-C", store, ...args], {
46627
46858
  env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" },
46628
46859
  maxBuffer: 64 * 1024 * 1024,
46629
46860
  timeout: 6e4
@@ -46638,12 +46869,12 @@ function blobSha(content) {
46638
46869
  return createHash15("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
46639
46870
  }
46640
46871
  async function isRepository2(store) {
46641
- return await lstat17(path72.join(store, ".git")).catch(() => void 0) !== void 0;
46872
+ return await lstat17(path73.join(store, ".git")).catch(() => void 0) !== void 0;
46642
46873
  }
46643
- function storeHead(store, indexFile = path72.join(bridgeRoot(), "store-snapshot.index")) {
46874
+ function storeHead(store, indexFile = path73.join(bridgeRoot(), "store-snapshot.index")) {
46644
46875
  return serialized(async () => {
46645
46876
  if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
46646
- await mkdir16(path72.dirname(indexFile), { recursive: true, mode: 448 });
46877
+ await mkdir16(path73.dirname(indexFile), { recursive: true, mode: 448 });
46647
46878
  const env = { GIT_INDEX_FILE: indexFile };
46648
46879
  if (!await lstat17(indexFile).catch(() => void 0)) {
46649
46880
  const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
@@ -46666,25 +46897,25 @@ async function storeTree(store, sha) {
46666
46897
  async function storeBlob(store, sha) {
46667
46898
  if (!SHA.test(sha)) throw new BridgeError(400, "Invalid blob sha.");
46668
46899
  if ((await git5(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "blob") throw new BridgeError(404, "Unknown blob.");
46669
- const { stdout } = await exec11("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE * 4 });
46900
+ const { stdout } = await exec12("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE * 4 });
46670
46901
  return { sha, encoding: "base64", content: stdout.toString("base64") };
46671
46902
  }
46672
46903
  async function storeFile(store, relative3) {
46673
- const normalized = path72.posix.normalize(relative3);
46674
- if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path72.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
46904
+ const normalized = path73.posix.normalize(relative3);
46905
+ if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path73.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
46675
46906
  throw new BridgeError(400, "Invalid store path.");
46676
46907
  }
46677
- const root = await realpath13(store);
46678
- let parent = path72.dirname(path72.join(root, normalized));
46908
+ const root = await realpath14(store);
46909
+ let parent = path73.dirname(path73.join(root, normalized));
46679
46910
  for (; ; ) {
46680
- const real = await realpath13(parent).catch(() => void 0);
46681
- if (real) {
46682
- if (real !== root && !real.startsWith(root + path72.sep)) throw new BridgeError(400, "Invalid store path.");
46911
+ const real2 = await realpath14(parent).catch(() => void 0);
46912
+ if (real2) {
46913
+ if (real2 !== root && !real2.startsWith(root + path73.sep)) throw new BridgeError(400, "Invalid store path.");
46683
46914
  break;
46684
46915
  }
46685
- parent = path72.dirname(parent);
46916
+ parent = path73.dirname(parent);
46686
46917
  }
46687
- const file2 = path72.join(root, normalized);
46918
+ const file2 = path73.join(root, normalized);
46688
46919
  const info = await lstat17(file2).catch(() => void 0);
46689
46920
  if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
46690
46921
  return file2;
@@ -46705,7 +46936,7 @@ function putStoreFile(store, data) {
46705
46936
  return serialized(async () => {
46706
46937
  const file2 = await storeFile(store, input2.path);
46707
46938
  if (await currentSha(file2) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
46708
- await mkdir16(path72.dirname(file2), { recursive: true });
46939
+ await mkdir16(path73.dirname(file2), { recursive: true });
46709
46940
  const temporary = `${file2}.phren-${process.pid}-${Date.now()}`;
46710
46941
  await writeFile8(temporary, content, { flag: "wx" });
46711
46942
  await rename7(temporary, file2);
@@ -46737,17 +46968,17 @@ init_protocol();
46737
46968
 
46738
46969
  // src/bridge/simulators.ts
46739
46970
  init_protocol();
46740
- import { execFile as execFile13 } from "node:child_process";
46741
- import { chmod as chmod4, mkdir as mkdir17, readFile as readFile29, rename as rename8, stat as stat20, unlink as unlink5, writeFile as writeFile9 } from "node:fs/promises";
46971
+ import { execFile as execFile14 } from "node:child_process";
46972
+ import { chmod as chmod4, mkdir as mkdir17, readFile as readFile29, rename as rename8, stat as stat21, unlink as unlink5, writeFile as writeFile9 } from "node:fs/promises";
46742
46973
  import { tmpdir as tmpdir3 } from "node:os";
46743
- import path73 from "node:path";
46974
+ import path74 from "node:path";
46744
46975
  import { createHash as createHash16, randomUUID as randomUUID17 } from "node:crypto";
46745
- import { promisify as promisify12 } from "node:util";
46746
- var exec12 = promisify12(execFile13);
46976
+ import { promisify as promisify13 } from "node:util";
46977
+ var exec13 = promisify13(execFile14);
46747
46978
  var UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
46748
46979
  async function bootedSimulators() {
46749
46980
  if (process.platform !== "darwin") return [];
46750
- const { stdout } = await exec12("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
46981
+ const { stdout } = await exec13("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
46751
46982
  let parsed = {};
46752
46983
  try {
46753
46984
  parsed = JSON.parse(stdout);
@@ -46768,9 +46999,9 @@ async function bootedSimulators() {
46768
46999
  async function simulatorScreenshot(udid) {
46769
47000
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
46770
47001
  if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
46771
- const file2 = path73.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
47002
+ const file2 = path74.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
46772
47003
  try {
46773
- await exec12("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
47004
+ await exec13("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
46774
47005
  return await readFile29(file2);
46775
47006
  } catch (error62) {
46776
47007
  if (error62 instanceof BridgeError) throw error62;
@@ -46787,18 +47018,18 @@ function helper() {
46787
47018
  return building;
46788
47019
  }
46789
47020
  async function buildHelper() {
46790
- const dir = path73.join(bridgeRoot(), "native");
46791
- const binary = path73.join(dir, "simtap");
47021
+ const dir = path74.join(bridgeRoot(), "native");
47022
+ const binary = path74.join(dir, "simtap");
46792
47023
  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 readFile29(new URL("./native/simtap.swift", import.meta.url), "utf8");
46793
47024
  const digest2 = createHash16("sha256").update(code).digest("hex");
46794
47025
  const saved = await readFile29(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
46795
- if (await stat20(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
47026
+ if (await stat21(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
46796
47027
  await mkdir17(dir, { recursive: true, mode: 448 });
46797
- const temporary = path73.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
47028
+ const temporary = path74.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
46798
47029
  const sidecar = temporary + ".sha256";
46799
47030
  try {
46800
47031
  await writeFile9(source, code, { mode: 384, flag: "wx" });
46801
- await exec12("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
47032
+ await exec13("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
46802
47033
  throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
46803
47034
  });
46804
47035
  await chmod4(temporary, 448);
@@ -46824,7 +47055,7 @@ async function executeSimtap(name, ...args) {
46824
47055
  const binarySha = createHash16("sha256").update(await readFile29(binary)).digest("hex");
46825
47056
  if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
46826
47057
  try {
46827
- await exec12(binary, [name, ...args], { timeout: 6e4 });
47058
+ await exec13(binary, [name, ...args], { timeout: 6e4 });
46828
47059
  } catch (error62) {
46829
47060
  const failure2 = error62;
46830
47061
  const message = String(failure2?.stderr ?? failure2?.message ?? "");
@@ -46840,7 +47071,7 @@ async function simulatorAct(udid, request6) {
46840
47071
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
46841
47072
  if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready"].includes(request6.action)) throw new BridgeError(400, "Unknown simulator action.");
46842
47073
  if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
46843
- const simctl = (...args) => exec12("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
47074
+ const simctl = (...args) => exec13("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
46844
47075
  throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`);
46845
47076
  });
46846
47077
  switch (request6.action) {
@@ -46889,7 +47120,7 @@ async function deviceName(udid) {
46889
47120
  async function simulatorApps(udid) {
46890
47121
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
46891
47122
  if (process.platform !== "darwin") return [];
46892
- const { stdout } = await exec12("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
47123
+ const { stdout } = await exec13("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
46893
47124
  const apps = [];
46894
47125
  const blocks = stdout.split(/\n(?=\s{4}"[^"]+" =\s+\{)/);
46895
47126
  for (const block of blocks) {
@@ -46905,8 +47136,8 @@ init_transcripts();
46905
47136
 
46906
47137
  // src/bridge/uploads.ts
46907
47138
  init_protocol();
46908
- import { mkdir as mkdir18, readdir as readdir13, lstat as lstat18, realpath as realpath14, readFile as readFile30, stat as stat21, unlink as unlink6, writeFile as writeFile10 } from "node:fs/promises";
46909
- import path74 from "node:path";
47139
+ import { mkdir as mkdir18, readdir as readdir14, lstat as lstat18, realpath as realpath15, readFile as readFile30, stat as stat22, unlink as unlink6, writeFile as writeFile10 } from "node:fs/promises";
47140
+ import path75 from "node:path";
46910
47141
  import { randomUUID as randomUUID18 } from "node:crypto";
46911
47142
  function imageBytes(bytes) {
46912
47143
  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";
@@ -46919,24 +47150,24 @@ async function saveUpload(session, name, bytes) {
46919
47150
  let saved = "";
46920
47151
  const task = uploadQueue.catch(() => {
46921
47152
  }).then(async () => {
46922
- const root = path74.join(bridgeRoot(), "uploads");
47153
+ const root = path75.join(bridgeRoot(), "uploads");
46923
47154
  await mkdir18(root, { recursive: true, mode: 448 });
46924
47155
  let used = 0;
46925
- const directories = await readdir13(root, { withFileTypes: true });
47156
+ const directories = await readdir14(root, { withFileTypes: true });
46926
47157
  for (const dir of directories) {
46927
47158
  if (!dir.isDirectory()) continue;
46928
- const folder2 = path74.join(root, dir.name);
46929
- for (const entry of await readdir13(folder2, { withFileTypes: true })) {
47159
+ const folder2 = path75.join(root, dir.name);
47160
+ for (const entry of await readdir14(folder2, { withFileTypes: true })) {
46930
47161
  if (!entry.isFile()) continue;
46931
- const file2 = path74.join(folder2, entry.name), metadata = await lstat18(file2);
47162
+ const file2 = path75.join(folder2, entry.name), metadata = await lstat18(file2);
46932
47163
  if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink6(file2);
46933
47164
  else used += metadata.size;
46934
47165
  }
46935
47166
  }
46936
47167
  if (used + bytes.length > 268435456) throw new BridgeError(413, "Phren's image storage is full. Remove older uploads on the computer.");
46937
- const folder = path74.join(root, session);
47168
+ const folder = path75.join(root, session);
46938
47169
  await mkdir18(folder, { recursive: true, mode: 448 });
46939
- saved = path74.join(folder, `${randomUUID18()}-${name}`);
47170
+ saved = path75.join(folder, `${randomUUID18()}-${name}`);
46940
47171
  await writeFile10(saved, bytes, { flag: "wx", mode: 384 });
46941
47172
  });
46942
47173
  uploadQueue = task;
@@ -46944,23 +47175,23 @@ async function saveUpload(session, name, bytes) {
46944
47175
  return saved;
46945
47176
  }
46946
47177
  async function listUploads(session) {
46947
- const folder = path74.join(bridgeRoot(), "uploads", session);
46948
- const entries2 = await readdir13(folder, { withFileTypes: true }).catch(() => []);
47178
+ const folder = path75.join(bridgeRoot(), "uploads", session);
47179
+ const entries2 = await readdir14(folder, { withFileTypes: true }).catch(() => []);
46949
47180
  const files = [];
46950
47181
  for (const entry of entries2) {
46951
47182
  if (!entry.isFile()) continue;
46952
- const file2 = path74.join(folder, entry.name), metadata = await stat21(file2);
47183
+ const file2 = path75.join(folder, entry.name), metadata = await stat22(file2);
46953
47184
  files.push({ name: entry.name.replace(/^[0-9a-f-]{36}-/, ""), path: file2, size: metadata.size, modified: metadata.mtime.toISOString() });
46954
47185
  }
46955
47186
  return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
46956
47187
  }
46957
47188
  async function uploadImage(requested) {
46958
47189
  const missing = new BridgeError(404, "This image is not one of the phone's uploads.");
46959
- if (!requested || requested.length > 4096 || !path74.isAbsolute(requested)) throw missing;
46960
- const root = await realpath14(path74.join(bridgeRoot(), "uploads")).catch(() => void 0);
46961
- const file2 = await realpath14(requested).catch(() => void 0);
46962
- if (!root || !file2 || !file2.startsWith(root + path74.sep)) throw missing;
46963
- const metadata = await stat21(file2);
47190
+ if (!requested || requested.length > 4096 || !path75.isAbsolute(requested)) throw missing;
47191
+ const root = await realpath15(path75.join(bridgeRoot(), "uploads")).catch(() => void 0);
47192
+ const file2 = await realpath15(requested).catch(() => void 0);
47193
+ if (!root || !file2 || !file2.startsWith(root + path75.sep)) throw missing;
47194
+ const metadata = await stat22(file2);
46964
47195
  if (!metadata.isFile()) throw missing;
46965
47196
  if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
46966
47197
  const bytes = await readFile30(file2);
@@ -46973,7 +47204,7 @@ async function uploadImage(requested) {
46973
47204
  init_transcript_index();
46974
47205
  init_transcripts();
46975
47206
  import { homedir as homedir18, tmpdir as tmpdir4 } from "node:os";
46976
- import path75 from "node:path";
47207
+ import path76 from "node:path";
46977
47208
  init_protocol();
46978
47209
  var cache = /* @__PURE__ */ new Map();
46979
47210
  var modelCache = /* @__PURE__ */ new Map();
@@ -47111,7 +47342,7 @@ function describe3(tool, args) {
47111
47342
  return "";
47112
47343
  };
47113
47344
  const firstLine = (v) => v.split(/\r?\n/).map((l) => l.trim()).find((l) => l) ?? "";
47114
- const base = (v) => path75.basename(v.split(" \xB7 ")[0].trim()) || "file";
47345
+ const base = (v) => path76.basename(v.split(" \xB7 ")[0].trim()) || "file";
47115
47346
  const name = tool.toLowerCase();
47116
47347
  let value2;
47117
47348
  if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
@@ -47146,17 +47377,17 @@ init_shared();
47146
47377
 
47147
47378
  // src/bridge/server-pane-routes.ts
47148
47379
  init_zod();
47149
- import path78 from "node:path";
47380
+ import path79 from "node:path";
47150
47381
  import { setTimeout as sleep2 } from "node:timers/promises";
47151
47382
 
47152
47383
  // src/bridge/git.ts
47153
47384
  init_protocol();
47154
47385
  import { createHash as createHash17 } from "node:crypto";
47155
- import { execFile as execFile14 } from "node:child_process";
47156
- import { lstat as lstat19, readdir as readdir14, readFile as readFile31, realpath as realpath15, stat as stat22 } from "node:fs/promises";
47157
- import path76 from "node:path";
47158
- import { promisify as promisify13 } from "node:util";
47159
- var exec13 = promisify13(execFile14);
47386
+ import { execFile as execFile15 } from "node:child_process";
47387
+ import { lstat as lstat19, readdir as readdir15, readFile as readFile31, realpath as realpath16, stat as stat23 } from "node:fs/promises";
47388
+ import path77 from "node:path";
47389
+ import { promisify as promisify14 } from "node:util";
47390
+ var exec14 = promisify14(execFile15);
47160
47391
  function statusLetter(code) {
47161
47392
  const letter = code[0];
47162
47393
  return ["M", "A", "D", "R", "C", "U"].includes(letter) ? letter : "M";
@@ -47200,8 +47431,8 @@ function parseNumstat(out) {
47200
47431
  }
47201
47432
  async function countLines(root, rel) {
47202
47433
  try {
47203
- const abs = path76.join(root, await repositoryPath(root, rel));
47204
- if ((await stat22(abs)).size > 5e6) return 0;
47434
+ const abs = path77.join(root, await repositoryPath(root, rel));
47435
+ if ((await stat23(abs)).size > 5e6) return 0;
47205
47436
  const bytes = await readFile31(abs);
47206
47437
  if (!bytes.length || bytes.includes(0)) return 0;
47207
47438
  let lines = 0;
@@ -47368,7 +47599,7 @@ function checkRollup(items) {
47368
47599
  }
47369
47600
  async function currentPull(root, branch) {
47370
47601
  try {
47371
- const { stdout } = await exec13("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
47602
+ const { stdout } = await exec14("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
47372
47603
  cwd: root,
47373
47604
  timeout: 15e3,
47374
47605
  maxBuffer: 4194304,
@@ -47395,7 +47626,7 @@ async function gitPulls(cwd) {
47395
47626
  const branch = (await git2(root, "branch", "--show-current").catch(() => "")).trim();
47396
47627
  try {
47397
47628
  const [{ stdout }, current2] = await Promise.all([
47398
- exec13("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
47629
+ exec14("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
47399
47630
  cwd: root,
47400
47631
  timeout: 15e3,
47401
47632
  maxBuffer: 4194304,
@@ -47424,13 +47655,13 @@ async function gitPulls(cwd) {
47424
47655
  }
47425
47656
  }
47426
47657
  async function repositoryPath(root, raw, allowRoot = false) {
47427
- if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path76.isAbsolute(raw) || path76.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
47658
+ if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path77.isAbsolute(raw) || path77.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
47428
47659
  const segments = raw.split(/[\\/]/);
47429
47660
  if (segments.includes("..")) throw new BridgeError(400, "Invalid path.");
47430
47661
  const clean2 = segments.filter((part) => part && part !== ".").join("/");
47431
47662
  if (!clean2 && !allowRoot || clean2.startsWith("-")) throw new BridgeError(400, "Invalid path.");
47432
- const abs = path76.resolve(root, clean2);
47433
- if (abs !== root && !abs.startsWith(root + path76.sep)) throw new BridgeError(403, "This path is outside the repository.");
47663
+ const abs = path77.resolve(root, clean2);
47664
+ if (abs !== root && !abs.startsWith(root + path77.sep)) throw new BridgeError(403, "This path is outside the repository.");
47434
47665
  let existing = abs;
47435
47666
  while (true) {
47436
47667
  try {
@@ -47438,16 +47669,16 @@ async function repositoryPath(root, raw, allowRoot = false) {
47438
47669
  break;
47439
47670
  } catch (error62) {
47440
47671
  if (error62.code !== "ENOENT" || existing === root) throw new BridgeError(400, "Invalid path.");
47441
- existing = path76.dirname(existing);
47672
+ existing = path77.dirname(existing);
47442
47673
  }
47443
47674
  }
47444
47675
  let resolved;
47445
47676
  try {
47446
- resolved = await realpath15(existing);
47677
+ resolved = await realpath16(existing);
47447
47678
  } catch {
47448
47679
  throw new BridgeError(403, "This path cannot be resolved inside the repository.");
47449
47680
  }
47450
- if (resolved !== root && !resolved.startsWith(root + path76.sep)) throw new BridgeError(403, "This path is outside the repository.");
47681
+ if (resolved !== root && !resolved.startsWith(root + path77.sep)) throw new BridgeError(403, "This path is outside the repository.");
47451
47682
  return clean2;
47452
47683
  }
47453
47684
  var treeCache = /* @__PURE__ */ new Map();
@@ -47529,7 +47760,7 @@ async function ignoredEntries(root, prefix, shown) {
47529
47760
  const entries2 = /* @__PURE__ */ new Map();
47530
47761
  const inside = prefix && listing.some((item) => item.endsWith("/") && (prefix + "/").startsWith(item));
47531
47762
  if (inside) {
47532
- const dirents = await readdir14(path76.join(root, prefix), { withFileTypes: true }).catch(() => []);
47763
+ const dirents = await readdir15(path77.join(root, prefix), { withFileTypes: true }).catch(() => []);
47533
47764
  for (const dirent of dirents) {
47534
47765
  if (dirent.name === ".git" || taken.has(dirent.name) || entries2.size >= MAX_IGNORED_ENTRIES) continue;
47535
47766
  entries2.set(dirent.name, { name: dirent.name, path: `${prefix}/${dirent.name}`, kind: dirent.isDirectory() ? "dir" : "file", ignored: true });
@@ -47626,9 +47857,9 @@ init_fanouts();
47626
47857
  // src/bridge/git-worktrees.ts
47627
47858
  init_protocol();
47628
47859
  import { createHash as createHash18 } from "node:crypto";
47629
- import { realpath as realpath16, stat as stat23 } from "node:fs/promises";
47860
+ import { realpath as realpath17, stat as stat24 } from "node:fs/promises";
47630
47861
  import { homedir as homedir19 } from "node:os";
47631
- import path77 from "node:path";
47862
+ import path78 from "node:path";
47632
47863
  var MAX_WORKTREES = 64;
47633
47864
  var worktreeIdPattern = /^[a-f0-9]{32}$/;
47634
47865
  function worktreeId(abs) {
@@ -47656,8 +47887,8 @@ async function listed(root) {
47656
47887
  let main;
47657
47888
  for (const [index2, block] of blocks.entries()) {
47658
47889
  if (block.bare !== void 0 || block.prunable !== void 0) continue;
47659
- const abs = await realpath16(block.worktree).catch(() => void 0);
47660
- if (!abs || !(await stat23(abs).catch(() => void 0))?.isDirectory()) continue;
47890
+ const abs = await realpath17(block.worktree).catch(() => void 0);
47891
+ if (!abs || !(await stat24(abs).catch(() => void 0))?.isDirectory()) continue;
47661
47892
  if (index2 === 0) main = abs;
47662
47893
  const branch = block.branch?.startsWith("refs/heads/") ? block.branch.slice("refs/heads/".length) : null;
47663
47894
  worktrees.push({ abs, head: block.HEAD ?? "", branch, locked: block.locked !== void 0 });
@@ -47667,11 +47898,11 @@ async function listed(root) {
47667
47898
  }
47668
47899
  function displayPath(abs, roots) {
47669
47900
  for (const root of roots) {
47670
- const rel = path77.relative(root, abs);
47671
- if (rel && !rel.startsWith("..") && !path77.isAbsolute(rel)) return rel.split(path77.sep).join("/");
47901
+ const rel = path78.relative(root, abs);
47902
+ if (rel && !rel.startsWith("..") && !path78.isAbsolute(rel)) return rel.split(path78.sep).join("/");
47672
47903
  }
47673
47904
  const home = homedir19();
47674
- return abs === home ? "~" : abs.startsWith(home + path77.sep) ? "~/" + path77.relative(home, abs).split(path77.sep).join("/") : abs;
47905
+ return abs === home ? "~" : abs.startsWith(home + path78.sep) ? "~/" + path78.relative(home, abs).split(path78.sep).join("/") : abs;
47675
47906
  }
47676
47907
  function uncommitted(status) {
47677
47908
  const tokens = status.split("\0");
@@ -47685,12 +47916,12 @@ function uncommitted(status) {
47685
47916
  return count2;
47686
47917
  }
47687
47918
  async function workerFor(abs, workers, all = []) {
47688
- const nested = all.filter((other) => other.startsWith(abs + path77.sep));
47919
+ const nested = all.filter((other) => other.startsWith(abs + path78.sep));
47689
47920
  let best;
47690
47921
  for (const worker of workers) {
47691
- const cwd = await realpath16(worker.cwd).catch(() => path77.resolve(worker.cwd));
47692
- if (cwd !== abs && !cwd.startsWith(abs + path77.sep)) continue;
47693
- if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path77.sep))) continue;
47922
+ const cwd = await realpath17(worker.cwd).catch(() => path78.resolve(worker.cwd));
47923
+ if (cwd !== abs && !cwd.startsWith(abs + path78.sep)) continue;
47924
+ if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path78.sep))) continue;
47694
47925
  const score = (cwd === abs ? 2 : 0) + (worker.child ? 1 : 0);
47695
47926
  if (!best || score > best.score) best = { worker, score };
47696
47927
  }
@@ -47883,11 +48114,11 @@ init_terminal();
47883
48114
  init_protocol();
47884
48115
  init_herdr();
47885
48116
  init_terminal();
47886
- import { execFile as execFile15 } from "node:child_process";
47887
- import { open as open14, stat as stat24 } from "node:fs/promises";
47888
- import { promisify as promisify14 } from "node:util";
48117
+ import { execFile as execFile16 } from "node:child_process";
48118
+ import { open as open15, stat as stat25 } from "node:fs/promises";
48119
+ import { promisify as promisify15 } from "node:util";
47889
48120
  init_transcripts();
47890
- var exec14 = promisify14(execFile15);
48121
+ var exec15 = promisify15(execFile16);
47891
48122
  var MAX_DEPTH = 64;
47892
48123
  var TRANSCRIPT_TAIL_BYTES = 1048576;
47893
48124
  var MAX_OTHER_PANES = 48;
@@ -47918,8 +48149,8 @@ function attributeServers(input2) {
47918
48149
  }
47919
48150
  return result.sort((a, b) => Number(a.source === "mentioned") - Number(b.source === "mentioned") || a.port - b.port);
47920
48151
  }
47921
- async function processTable(session) {
47922
- const { stdout } = await exec14("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4e3, maxBuffer: 16777216 });
48152
+ async function processTable2(session) {
48153
+ const { stdout } = await exec15("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4e3, maxBuffer: 16777216 });
47923
48154
  const parents = /* @__PURE__ */ new Map();
47924
48155
  const runners = [];
47925
48156
  const flag = `--session-id ${session}`;
@@ -47940,12 +48171,12 @@ async function paneRoots(server, paneId) {
47940
48171
  }
47941
48172
  async function transcriptHolders(file2) {
47942
48173
  const lsof = process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof";
47943
- const { stdout } = await exec14(lsof, ["-t", "--", file2], { timeout: 3e3 }).catch(() => ({ stdout: "" }));
48174
+ const { stdout } = await exec15(lsof, ["-t", "--", file2], { timeout: 3e3 }).catch(() => ({ stdout: "" }));
47944
48175
  return stdout.split("\n").map(Number).filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid);
47945
48176
  }
47946
48177
  async function transcriptTail(file2) {
47947
- const size = (await stat24(file2)).size;
47948
- const handle = await open14(file2, "r");
48178
+ const size = (await stat25(file2)).size;
48179
+ const handle = await open15(file2, "r");
47949
48180
  try {
47950
48181
  const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
47951
48182
  const buffer = Buffer.alloc(length);
@@ -47956,14 +48187,14 @@ async function transcriptTail(file2) {
47956
48187
  }
47957
48188
  }
47958
48189
  async function sessionWebServers(target, pane) {
47959
- const [servers2, table, own2, file2] = await Promise.all([
48190
+ const [servers2, table2, own2, file2] = await Promise.all([
47960
48191
  webServers(),
47961
- processTable(target.session),
48192
+ processTable2(target.session),
47962
48193
  paneRoots(target.server, pane.pane_id),
47963
48194
  transcriptPath(target.source, target.session).catch(() => void 0)
47964
48195
  ]);
47965
- const parents = table.parents;
47966
- const ownRoots = /* @__PURE__ */ new Set([...own2, ...table.runners]);
48196
+ const parents = table2.parents;
48197
+ const ownRoots = /* @__PURE__ */ new Set([...own2, ...table2.runners]);
47967
48198
  let mentioned = /* @__PURE__ */ new Set();
47968
48199
  if (file2) {
47969
48200
  for (const pid of await transcriptHolders(file2)) ownRoots.add(pid);
@@ -48074,7 +48305,7 @@ function herdrWorktreeWorkers(s) {
48074
48305
  const workers = [];
48075
48306
  for (const pane of objects(s.panes)) {
48076
48307
  const cwd = pane.foreground_cwd || pane.cwd;
48077
- if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path78.isAbsolute(cwd)) continue;
48308
+ if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path79.isAbsolute(cwd)) continue;
48078
48309
  const name = paneAgentName(s, pane);
48079
48310
  workers.push({
48080
48311
  cwd,
@@ -48393,7 +48624,7 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
48393
48624
 
48394
48625
  // src/bridge/server-launch.ts
48395
48626
  import { mkdir as mkdir20, readFile as readFile32 } from "node:fs/promises";
48396
- import path80 from "node:path";
48627
+ import path81 from "node:path";
48397
48628
  init_zod();
48398
48629
  init_home_paths();
48399
48630
  init_herdr();
@@ -48403,15 +48634,15 @@ init_terminal();
48403
48634
  init_zod();
48404
48635
  init_utils_helpers();
48405
48636
  init_metrics();
48406
- import { execFile as execFile16 } from "node:child_process";
48407
- import { mkdir as mkdir19, realpath as realpath17, rm as rm9, stat as stat25 } from "node:fs/promises";
48408
- import path79 from "node:path";
48409
- import { promisify as promisify15 } from "node:util";
48637
+ import { execFile as execFile17 } from "node:child_process";
48638
+ import { mkdir as mkdir19, realpath as realpath18, rm as rm9, stat as stat26 } from "node:fs/promises";
48639
+ import path80 from "node:path";
48640
+ import { promisify as promisify16 } from "node:util";
48410
48641
  init_protocol();
48411
- var exec15 = promisify15(execFile16);
48642
+ var exec16 = promisify16(execFile17);
48412
48643
  async function git6(cwd, ...args) {
48413
48644
  countGit("launch-worktree");
48414
- return (await exec15("git", ["-C", cwd, "--no-pager", ...args], {
48645
+ return (await exec16("git", ["-C", cwd, "--no-pager", ...args], {
48415
48646
  timeout: 12e4,
48416
48647
  maxBuffer: 1048576,
48417
48648
  env: nonInteractiveGitEnv({ ...process.env, GIT_CONFIG_NOSYSTEM: "1" })
@@ -48434,21 +48665,21 @@ async function createLaunchWorktree(cwd, request6) {
48434
48665
  if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
48435
48666
  throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
48436
48667
  }
48437
- const worktree = path79.join(root, ".claude", "worktrees", worktreeFolderName(branch));
48438
- if (await stat25(worktree).then(() => true, () => false)) {
48668
+ const worktree = path80.join(root, ".claude", "worktrees", worktreeFolderName(branch));
48669
+ if (await stat26(worktree).then(() => true, () => false)) {
48439
48670
  throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
48440
48671
  }
48441
- await mkdir19(path79.dirname(worktree), { recursive: true });
48672
+ await mkdir19(path80.dirname(worktree), { recursive: true });
48442
48673
  try {
48443
48674
  await git6(root, "worktree", "add", "-b", branch, worktree, head);
48444
48675
  } catch (error62) {
48445
48676
  const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").at(-1) : "";
48446
48677
  throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
48447
48678
  }
48448
- const abs = await realpath17(worktree);
48449
- const inside = path79.relative(root, await realpath17(cwd));
48450
- const start = inside && !inside.startsWith("..") ? path79.join(abs, inside) : abs;
48451
- const startDir = await stat25(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
48679
+ const abs = await realpath18(worktree);
48680
+ const inside = path80.relative(root, await realpath18(cwd));
48681
+ const start = inside && !inside.startsWith("..") ? path80.join(abs, inside) : abs;
48682
+ const startDir = await stat26(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
48452
48683
  return {
48453
48684
  cwd: startDir,
48454
48685
  path: abs,
@@ -48490,10 +48721,10 @@ async function conductorBrief() {
48490
48721
  let source;
48491
48722
  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- `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, 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- `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.\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.\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?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>]`.\n`anywhere` chooses the connected computer with the fewest working agents. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\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\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\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";
48492
48723
  else {
48493
- const here = path80.dirname(fileURLToPath(import.meta.url));
48724
+ const here = path81.dirname(fileURLToPath(import.meta.url));
48494
48725
  for (const candidate of [
48495
- path80.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
48496
- path80.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
48726
+ path81.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
48727
+ path81.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
48497
48728
  ]) {
48498
48729
  source = await readFile32(candidate, "utf8").catch(() => void 0);
48499
48730
  if (source !== void 0) break;
@@ -48514,15 +48745,15 @@ function effortArgs(kind, effort) {
48514
48745
  }
48515
48746
  async function prepareConductor(kind, effort, model) {
48516
48747
  const brief = await conductorBrief();
48517
- const briefDirectory = path80.join(bridgeRoot(), "conductor");
48748
+ const briefDirectory = path81.join(bridgeRoot(), "conductor");
48518
48749
  await mkdir20(briefDirectory, { recursive: true, mode: 448 });
48519
- const briefFile = path80.join(briefDirectory, "brief.md");
48750
+ const briefFile = path81.join(briefDirectory, "brief.md");
48520
48751
  if (await readFile32(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
48521
48752
  if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
48522
48753
  if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
48523
48754
  if (kind === "opencode") {
48524
- const directory = path80.join(process.env.XDG_CONFIG_HOME || path80.join(homeDir(), ".config"), "opencode", "agents");
48525
- const file2 = path80.join(directory, "conductor.md");
48755
+ const directory = path81.join(process.env.XDG_CONFIG_HOME || path81.join(homeDir(), ".config"), "opencode", "agents");
48756
+ const file2 = path81.join(directory, "conductor.md");
48526
48757
  const definition = `---
48527
48758
  description: Coordinate the owner's work across agent sessions.
48528
48759
  mode: primary
@@ -48559,7 +48790,7 @@ function herdrAgentName(label2) {
48559
48790
  }
48560
48791
  async function launchSession(server, data, options = {}) {
48561
48792
  const role = external_exports.enum(["agent", "conductor"]).default("agent").parse(data.role);
48562
- const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path80.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
48793
+ const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path81.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
48563
48794
  const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
48564
48795
  if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
48565
48796
  const label2 = plainText(200).parse(data.label);
@@ -48651,7 +48882,7 @@ async function workspaceAction(server, operation, data) {
48651
48882
  if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
48652
48883
  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.");
48653
48884
  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);
48654
- const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path80.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
48885
+ const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path81.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
48655
48886
  if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
48656
48887
  else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
48657
48888
  else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
@@ -49023,7 +49254,7 @@ function createRouteHandler(ctx) {
49023
49254
  case "/v1/files/range": {
49024
49255
  let root;
49025
49256
  if (url2.searchParams.get("scope") === "uploads") {
49026
- root = path81.join(bridgeRoot(), "uploads");
49257
+ root = path82.join(bridgeRoot(), "uploads");
49027
49258
  } else if (url2.searchParams.has("session")) {
49028
49259
  const target = targetFromURL(url2), pane = await validateTarget(target);
49029
49260
  const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
@@ -49330,7 +49561,7 @@ init_protocol();
49330
49561
  // src/bridge/transcript-preview.ts
49331
49562
  init_codex_threads();
49332
49563
  import { constants as constants5 } from "node:fs";
49333
- import { open as open15 } from "node:fs/promises";
49564
+ import { open as open16 } from "node:fs/promises";
49334
49565
  init_protocol();
49335
49566
  init_transcript_index();
49336
49567
  init_terminal_text();
@@ -49560,11 +49791,11 @@ async function readDeltaPreview(target, file2, rollout) {
49560
49791
  if (target.source === "codex") return await codexThreadPreview(target.session) ?? (file2 && rollout ? await rollout.read(file2).catch(() => null) : null);
49561
49792
  if (target.source !== "opencode" || !file2) return null;
49562
49793
  try {
49563
- const handle = await open15(file2 + ".preview.json", constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
49794
+ const handle = await open16(file2 + ".preview.json", constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
49564
49795
  let bytes;
49565
49796
  try {
49566
- const stat26 = await handle.stat();
49567
- if (!stat26.isFile() || stat26.size > MAX_PREVIEW_BYTES) return null;
49797
+ const stat27 = await handle.stat();
49798
+ if (!stat27.isFile() || stat27.size > MAX_PREVIEW_BYTES) return null;
49568
49799
  const buffer = Buffer.alloc(MAX_PREVIEW_BYTES + 1);
49569
49800
  const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
49570
49801
  if (bytesRead > MAX_PREVIEW_BYTES) return null;
@@ -49995,7 +50226,7 @@ async function serve(version3) {
49995
50226
  await mkdir21(root, { recursive: true, mode: 448 });
49996
50227
  await chmod5(root, 448);
49997
50228
  let computerID2;
49998
- const identityFile = path82.join(root, "computer-id");
50229
+ const identityFile = path83.join(root, "computer-id");
49999
50230
  try {
50000
50231
  computerID2 = (await readFile33(identityFile, "utf8")).trim();
50001
50232
  } catch {
@@ -50045,7 +50276,7 @@ async function serve(version3) {
50045
50276
  if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
50046
50277
  function gatewayTiming() {
50047
50278
  try {
50048
- const parsed = JSON.parse(readFileSync32(path82.join(root, "gateway.json"), "utf8"));
50279
+ const parsed = JSON.parse(readFileSync32(path83.join(root, "gateway.json"), "utf8"));
50049
50280
  if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
50050
50281
  } catch {
50051
50282
  }
@@ -50091,7 +50322,7 @@ async function serve(version3) {
50091
50322
  }
50092
50323
  const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
50093
50324
  };
50094
- if (modules.has("git")) await rm10(path82.join(root, "changes-scratch"), { recursive: true, force: true });
50325
+ if (modules.has("git")) await rm10(path83.join(root, "changes-scratch"), { recursive: true, force: true });
50095
50326
  const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
50096
50327
  const { stream } = streams;
50097
50328
  const overview = overviewStream({
@@ -50238,13 +50469,13 @@ init_protocol();
50238
50469
  // src/bridge/link.ts
50239
50470
  init_profile_store();
50240
50471
  init_phren_paths();
50241
- import { execFile as execFile17 } from "node:child_process";
50472
+ import { execFile as execFile18 } from "node:child_process";
50242
50473
  import { readFile as readFile34 } from "node:fs/promises";
50243
50474
  import { homedir as homedir20, hostname as hostname10, userInfo as userInfo3 } from "node:os";
50244
- import path83 from "node:path";
50245
- import { promisify as promisify16 } from "node:util";
50475
+ import path84 from "node:path";
50476
+ import { promisify as promisify17 } from "node:util";
50246
50477
  init_protocol();
50247
- var exec16 = promisify16(execFile17);
50478
+ var exec17 = promisify17(execFile18);
50248
50479
  var REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"';
50249
50480
  var GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
50250
50481
  function sshConfigHosts(text4) {
@@ -50269,7 +50500,7 @@ function sshConfigHosts(text4) {
50269
50500
  }
50270
50501
  async function ssh(host, command, input2, timeout = 2e4) {
50271
50502
  return new Promise((resolve11, reject) => {
50272
- const child = execFile17(
50503
+ const child = execFile18(
50273
50504
  "ssh",
50274
50505
  ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", host, command],
50275
50506
  { timeout, maxBuffer: 1048576 },
@@ -50288,11 +50519,11 @@ async function probe2(host) {
50288
50519
  return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
50289
50520
  }
50290
50521
  async function discoverComputers(options = {}) {
50291
- const config3 = options.sshConfig ?? await readFile34(path83.join(homedir20(), ".ssh", "config"), "utf8").catch(() => "");
50522
+ const config3 = options.sshConfig ?? await readFile34(path84.join(homedir20(), ".ssh", "config"), "utf8").catch(() => "");
50292
50523
  const store = options.store !== void 0 ? options.store : findPhrenPath();
50293
50524
  const machines = store ? listMachines(store) : void 0;
50294
50525
  const { peers } = await optionalHookPeers();
50295
- const own2 = (await readFile34(path83.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
50526
+ const own2 = (await readFile34(path84.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
50296
50527
  const known = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
50297
50528
  const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known.has(computerLabel(host))).slice(0, 32);
50298
50529
  const [found, peerIds] = await Promise.all([
@@ -50314,13 +50545,13 @@ function slugName(value2) {
50314
50545
  async function linkComputer(host, options = {}) {
50315
50546
  const remote = await probe2(host);
50316
50547
  if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
50317
- const own2 = (await readFile34(path83.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
50548
+ const own2 = (await readFile34(path84.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
50318
50549
  if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
50319
50550
  const name = computerName.parse(options.name ?? slugName(host));
50320
50551
  const as = computerName.parse(options.as ?? slugName(hostname10()));
50321
50552
  const backAddress = options.backAddress ?? remote.client;
50322
50553
  if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
50323
- const resolved = Object.fromEntries((await exec16("ssh", ["-G", "--", host], { timeout: 5e3 })).stdout.split("\n").map((line) => line.split(" ")).filter((parts) => parts.length >= 2).map(([key2, ...rest]) => [key2, rest.join(" ")]));
50554
+ const resolved = Object.fromEntries((await exec17("ssh", ["-G", "--", host], { timeout: 5e3 })).stdout.split("\n").map((line) => line.split(" ")).filter((parts) => parts.length >= 2).map(([key2, ...rest]) => [key2, rest.join(" ")]));
50324
50555
  const remoteHostKey = publicComputerKey((await ssh(host, "cat /etc/ssh/ssh_host_ed25519_key.pub")).trim().split(/\s+/).slice(0, 2).join(" "));
50325
50556
  const localHostKey = publicComputerKey((await readFile34("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
50326
50557
  const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
@@ -50515,7 +50746,7 @@ async function readSecret(prompt) {
50515
50746
  // src/bridge/hook-main.ts
50516
50747
  init_utils_helpers();
50517
50748
  Object.assign(process.env, nonInteractiveGitEnv());
50518
- runBridge(process.argv.slice(2), "0.3.6").then((code) => {
50749
+ runBridge(process.argv.slice(2), "0.3.8").then((code) => {
50519
50750
  process.exitCode = code;
50520
50751
  }).catch((error62) => {
50521
50752
  console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");