@phren/cli 0.3.7 → 0.3.9

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, path86) {
272
+ if (!path86)
273
273
  return obj;
274
- return path84.reduce((acc, key2) => acc?.[key2], obj);
274
+ return path86.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(path86, 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(path86);
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, path86 = []) => {
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 }, [...path86, ...issue2.path]));
1062
1062
  } else if (issue2.code === "invalid_key") {
1063
- processError({ issues: issue2.issues }, [...path84, ...issue2.path]);
1063
+ processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
1064
1064
  } else if (issue2.code === "invalid_element") {
1065
- processError({ issues: issue2.issues }, [...path84, ...issue2.path]);
1065
+ processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
1066
1066
  } else {
1067
- const fullpath = [...path84, ...issue2.path];
1067
+ const fullpath = [...path86, ...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, path86 = []) => {
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 }, [...path86, ...issue2.path]));
1111
1111
  } else if (issue2.code === "invalid_key") {
1112
- processError({ issues: issue2.issues }, [...path84, ...issue2.path]);
1112
+ processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
1113
1113
  } else if (issue2.code === "invalid_element") {
1114
- processError({ issues: issue2.issues }, [...path84, ...issue2.path]);
1114
+ processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
1115
1115
  } else {
1116
- const fullpath = [...path84, ...issue2.path];
1116
+ const fullpath = [...path86, ...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 path86 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1156
+ for (const seg of path86) {
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 path86 = ref.slice(1).split("/").filter(Boolean);
19153
+ if (path86.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 (path86[0] === defsKey) {
19158
+ const key2 = path86[1] === void 0 ? void 0 : decodeJSONPointerSegment(path86[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;
@@ -26478,8 +26478,8 @@ function appendAuditLog(phrenPath, event, details) {
26478
26478
  fs3.mkdirSync(path11.dirname(logPath), { recursive: true });
26479
26479
  withFileLock(logPath, () => {
26480
26480
  fs3.appendFileSync(logPath, line);
26481
- const stat26 = fs3.statSync(logPath);
26482
- if (stat26.size > 1e6) {
26481
+ const stat27 = fs3.statSync(logPath);
26482
+ if (stat27.size > 1e6) {
26483
26483
  const content = fs3.readFileSync(logPath, "utf8");
26484
26484
  const lines = content.split("\n");
26485
26485
  fs3.writeFileSync(logPath, lines.slice(-MAX_LOG_LINES).join("\n") + "\n");
@@ -26568,8 +26568,8 @@ ${Date.now()}`, { flag: "wx" });
26568
26568
  } catch (err) {
26569
26569
  logger.debug("acquireFileLock", `lockWrite: ${errorMessage(err)}`);
26570
26570
  try {
26571
- const stat26 = fs5.statSync(lockPath);
26572
- if (Date.now() - stat26.mtimeMs > staleThreshold) {
26571
+ const stat27 = fs5.statSync(lockPath);
26572
+ if (Date.now() - stat27.mtimeMs > staleThreshold) {
26573
26573
  let ownerAlive = false;
26574
26574
  try {
26575
26575
  const content = fs5.readFileSync(lockPath, "utf-8");
@@ -28317,7 +28317,7 @@ var init_package_metadata = __esm({
28317
28317
  __dirname = path24.dirname(fileURLToPath2(import.meta.url));
28318
28318
  ROOT = path24.join(__dirname, "..");
28319
28319
  PACKAGE_JSON_PATH = path24.join(ROOT, "package.json");
28320
- BUNDLED_VERSION = true ? "0.3.7" : "0.0.0";
28320
+ BUNDLED_VERSION = true ? "0.3.9" : "0.0.0";
28321
28321
  PACKAGE_JSON = readPackageJson();
28322
28322
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
28323
28323
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -31513,7 +31513,7 @@ var require_stream = __commonJS({
31513
31513
  };
31514
31514
  duplex._final = function(callback) {
31515
31515
  if (ws.readyState === ws.CONNECTING) {
31516
- ws.once("open", function open16() {
31516
+ ws.once("open", function open17() {
31517
31517
  duplex._final(callback);
31518
31518
  });
31519
31519
  return;
@@ -31534,7 +31534,7 @@ var require_stream = __commonJS({
31534
31534
  };
31535
31535
  duplex._write = function(chunk, encoding, callback) {
31536
31536
  if (ws.readyState === ws.CONNECTING) {
31537
- ws.once("open", function open16() {
31537
+ ws.once("open", function open17() {
31538
31538
  duplex._write(chunk, encoding, callback);
31539
31539
  });
31540
31540
  return;
@@ -32161,6 +32161,162 @@ var init_tab_activity = __esm({
32161
32161
  }
32162
32162
  });
32163
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
+
32164
32320
  // src/bridge/terminal-herdr.ts
32165
32321
  function herdrPanes(server, s) {
32166
32322
  return objects(s.panes).filter((p) => typeof p.pane_id === "string" && typeof p.tab_id === "string" && typeof p.workspace_id === "string").map((p) => {
@@ -32241,14 +32397,14 @@ var init_terminal_herdr = __esm({
32241
32397
  });
32242
32398
 
32243
32399
  // src/bridge/harness-status.ts
32244
- import { open as open5, stat as stat8 } from "node:fs/promises";
32400
+ import { open as open6, stat as stat9 } from "node:fs/promises";
32245
32401
  import { homedir as homedir7 } from "node:os";
32246
- import path32 from "node:path";
32402
+ import path33 from "node:path";
32247
32403
  async function opencodeProcessStatus(pids, root = phrenStoreRoot()) {
32248
- const folder = path32.join(root, ".runtime", "sessions");
32404
+ const folder = path33.join(root, ".runtime", "sessions");
32249
32405
  let current2, latest = -Infinity;
32250
32406
  for (const pid of pids.slice(0, 16)) {
32251
- 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);
32252
32408
  if (!file2) continue;
32253
32409
  try {
32254
32410
  if ((await file2.stat()).size > 4096) continue;
@@ -32320,15 +32476,15 @@ function copilotStatusFromEvents(lines) {
32320
32476
  }
32321
32477
  return status;
32322
32478
  }
32323
- 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")) {
32324
32480
  const session = await copilotForegroundSession(pids, home);
32325
32481
  if (!session) return void 0;
32326
- const file2 = path32.join(home, "session-state", session, "events.jsonl");
32327
- 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);
32328
32484
  if (!info?.isFile()) return void 0;
32329
32485
  const cached2 = copilotCache.get(file2);
32330
32486
  if (cached2 && cached2.size === info.size && cached2.mtime === info.mtimeMs) return cached2.status;
32331
- const handle = await open5(file2, "r");
32487
+ const handle = await open6(file2, "r");
32332
32488
  let text4;
32333
32489
  try {
32334
32490
  const length = Math.min(info.size, TAIL_BYTES);
@@ -32447,6 +32603,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
32447
32603
  await sleep3(120);
32448
32604
  }
32449
32605
  };
32606
+ const ANSWERED_MS = 8e3;
32450
32607
  const initial = await settle2((screen) => screen);
32451
32608
  if (!initial) throw changed("The terminal is not showing Claude's question.");
32452
32609
  if (initial.tabs.length !== questions.length) throw changed("The terminal is asking a different set of questions.");
@@ -32483,7 +32640,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
32483
32640
  } else {
32484
32641
  await io.keys([String(screen.options[answer.options[0]].number)]);
32485
32642
  }
32486
- if (!await settle2(leaves(index2))) throw changed("The terminal did not take the answer.");
32643
+ if (!await settle2(leaves(index2), ANSWERED_MS)) throw changed("The terminal did not take the answer.");
32487
32644
  continue;
32488
32645
  }
32489
32646
  const rows = [...screen.options, ...screen.other ? [screen.other] : []];
@@ -32510,10 +32667,10 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
32510
32667
  } else {
32511
32668
  await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
32512
32669
  }
32513
- if (!await settle2(leaves(index2))) throw changed("The terminal did not move past the question.");
32670
+ if (!await settle2(leaves(index2), ANSWERED_MS)) throw changed("The terminal did not move past the question.");
32514
32671
  }
32515
32672
  if (!submit) return;
32516
- const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0);
32673
+ const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0, ANSWERED_MS);
32517
32674
  if (review === "gone") return;
32518
32675
  if (!review) throw changed("The terminal did not reach the review of the answers.");
32519
32676
  const expected = questions.map((question2) => normalize(question2.question));
@@ -32521,7 +32678,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
32521
32678
  throw changed("Not every question has an answer in the terminal.");
32522
32679
  }
32523
32680
  await io.keys(["1"]);
32524
- if (await settle2((value2) => value2 === void 0 ? "gone" : void 0) !== "gone") throw changed("The terminal did not submit the answers.");
32681
+ if (await settle2((value2) => value2 === void 0 ? "gone" : void 0, ANSWERED_MS) !== "gone") throw changed("The terminal did not submit the answers.");
32525
32682
  }
32526
32683
  var TAB_BAR, ROW, NEXT, normalize, changed, typedKeys;
32527
32684
  var init_claude_question_dialog = __esm({
@@ -32933,11 +33090,11 @@ __export(terminal_tmux_exports, {
32933
33090
  tmuxTerminal: () => tmuxTerminal,
32934
33091
  toTmuxId: () => toTmuxId
32935
33092
  });
32936
- import { execFile as execFile3 } from "node:child_process";
33093
+ import { execFile as execFile4 } from "node:child_process";
32937
33094
  import { accessSync, constants, existsSync as existsSync14, statSync as statSync9 } from "node:fs";
32938
- import { lstat as lstat5, readdir as readdir6 } from "node:fs/promises";
33095
+ import { lstat as lstat5, readdir as readdir7 } from "node:fs/promises";
32939
33096
  import { hostname as hostname4, userInfo } from "node:os";
32940
- import path33 from "node:path";
33097
+ import path34 from "node:path";
32941
33098
  function tmuxSocketName(server) {
32942
33099
  const match = /^tmux(?:-([A-Za-z0-9_][A-Za-z0-9_.-]{0,63}))?$/.exec(server);
32943
33100
  return match ? match[1] ?? "default" : void 0;
@@ -32949,11 +33106,11 @@ function tmuxServerName(socket) {
32949
33106
  function tmuxBinary() {
32950
33107
  if (process.env.PHREN_TMUX === "off") return void 0;
32951
33108
  if (cachedBinary && Date.now() - cachedBinary.at < 6e4) return cachedBinary.value;
32952
- const folders = [...(process.env.PATH ?? "").split(path33.delimiter), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/home/linuxbrew/.linuxbrew/bin"];
33109
+ const folders = [...(process.env.PATH ?? "").split(path34.delimiter), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/home/linuxbrew/.linuxbrew/bin"];
32953
33110
  let value2;
32954
33111
  for (const folder of folders) {
32955
- if (!folder || !path33.isAbsolute(folder)) continue;
32956
- const candidate = path33.join(folder, "tmux");
33112
+ if (!folder || !path34.isAbsolute(folder)) continue;
33113
+ const candidate = path34.join(folder, "tmux");
32957
33114
  try {
32958
33115
  if (statSync9(candidate).isFile()) {
32959
33116
  accessSync(candidate, constants.X_OK);
@@ -32980,8 +33137,8 @@ function tmuxError(stderr, error62) {
32980
33137
  function tmuxSocketFolders(env = process.env) {
32981
33138
  const uid = process.getuid?.();
32982
33139
  if (uid === void 0) return [];
32983
- const base = env.TMUX_TMPDIR && path33.isAbsolute(env.TMUX_TMPDIR) ? env.TMUX_TMPDIR : "/tmp";
32984
- return [.../* @__PURE__ */ new Set([path33.join(base, `tmux-${uid}`), path33.join("/tmp", `tmux-${uid}`)])];
33140
+ const base = env.TMUX_TMPDIR && path34.isAbsolute(env.TMUX_TMPDIR) ? env.TMUX_TMPDIR : "/tmp";
33141
+ return [.../* @__PURE__ */ new Set([path34.join(base, `tmux-${uid}`), path34.join("/tmp", `tmux-${uid}`)])];
32985
33142
  }
32986
33143
  function socketFlags(socket) {
32987
33144
  const file2 = socketPaths.get(socket);
@@ -32989,15 +33146,15 @@ function socketFlags(socket) {
32989
33146
  }
32990
33147
  async function tmuxSocketsIn(folder) {
32991
33148
  const uid = process.getuid?.(), primary = tmuxSocketFolders()[0];
32992
- const names = (await readdir6(folder).catch(() => [])).slice(0, 256);
33149
+ const names = (await readdir7(folder).catch(() => [])).slice(0, 256);
32993
33150
  const found = [];
32994
33151
  for (const name of names) {
32995
33152
  if (found.length >= 32) break;
32996
33153
  if (!tmuxServerName(name)) continue;
32997
- const info = await lstat5(path33.join(folder, name)).catch(() => void 0);
33154
+ const info = await lstat5(path34.join(folder, name)).catch(() => void 0);
32998
33155
  if (!info?.isSocket() || uid !== void 0 && info.uid !== uid) continue;
32999
33156
  found.push(name);
33000
- if (folder !== primary && !socketPaths.has(name) && !existsSync14(path33.join(primary ?? folder, name))) socketPaths.set(name, path33.join(folder, name));
33157
+ if (folder !== primary && !socketPaths.has(name) && !existsSync14(path34.join(primary ?? folder, name))) socketPaths.set(name, path34.join(folder, name));
33001
33158
  }
33002
33159
  return found;
33003
33160
  }
@@ -33024,7 +33181,7 @@ function toTmuxId(value2, kind) {
33024
33181
  }
33025
33182
  function agentFromCommand(command) {
33026
33183
  const words = command.trim().split(/\s+/).filter(Boolean).slice(0, 4);
33027
- const [first, second] = words, base = (word) => word ? path33.basename(word) : "";
33184
+ const [first, second] = words, base = (word) => word ? path34.basename(word) : "";
33028
33185
  const program = /^(node|nodejs|bun|deno)$/.test(base(first)) && second ? second : first;
33029
33186
  if (!program) return void 0;
33030
33187
  const name = base(program);
@@ -33172,14 +33329,14 @@ async function requireDirectExec() {
33172
33329
  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.");
33173
33330
  }
33174
33331
  function loginShell() {
33175
- const shell = process.env.SHELL && path33.isAbsolute(process.env.SHELL) ? process.env.SHELL : (() => {
33332
+ const shell = process.env.SHELL && path34.isAbsolute(process.env.SHELL) ? process.env.SHELL : (() => {
33176
33333
  try {
33177
33334
  return userInfo().shell ?? "";
33178
33335
  } catch {
33179
33336
  return "";
33180
33337
  }
33181
33338
  })();
33182
- return shell && /^(sh|bash|zsh|ksh|dash)$/.test(path33.basename(shell)) && existsSync14(shell) ? shell : "/bin/sh";
33339
+ return shell && /^(sh|bash|zsh|ksh|dash)$/.test(path34.basename(shell)) && existsSync14(shell) ? shell : "/bin/sh";
33183
33340
  }
33184
33341
  function sessionName(label2, taken) {
33185
33342
  const base = (label2 ?? "phren").replace(/[.:\x00-\x1f\x7f]/g, "_").trim().slice(0, 60) || "phren";
@@ -33196,9 +33353,9 @@ async function ownerServers() {
33196
33353
  const running2 = await Promise.all(names.map((name) => tmuxTerminal.ping(name).then(() => true, () => false)));
33197
33354
  return names.filter((_, index2) => running2[index2]);
33198
33355
  }
33199
- async function tmuxServers() {
33356
+ async function tmuxServers(options = {}) {
33200
33357
  if (!deps.binary()) return [];
33201
- return [...await ownerServers(), TMUX_HIDDEN].map((name) => ({ id: `tmux:${name}`, kind: "herdr", terminal: "tmux", session: name, running: true }));
33358
+ return [...await ownerServers(), ...options.hidden ?? true ? [TMUX_HIDDEN] : []].map((name) => ({ id: `tmux:${name}`, kind: "herdr", terminal: "tmux", session: name, running: true }));
33202
33359
  }
33203
33360
  async function tmuxHealth() {
33204
33361
  if (process.env.PHREN_TMUX === "off") return { state: "off" };
@@ -33213,13 +33370,13 @@ async function tmuxHealth() {
33213
33370
  }
33214
33371
  async function tmuxPaneFromEnv(env = process.env) {
33215
33372
  const socket = env.TMUX?.split(",")[0], pane = env.TMUX_PANE;
33216
- if (!socket || !path33.isAbsolute(socket) || !pane || !fromTmuxId(pane)) return void 0;
33217
- const server = tmuxServerName(path33.basename(socket));
33373
+ if (!socket || !path34.isAbsolute(socket) || !pane || !fromTmuxId(pane)) return void 0;
33374
+ const server = tmuxServerName(path34.basename(socket));
33218
33375
  if (!server) return void 0;
33219
33376
  const primary = tmuxSocketFolders(env)[0];
33220
- if (primary && path33.dirname(socket) !== primary && !socketPaths.has(path33.basename(socket))) socketPaths.set(path33.basename(socket), socket);
33377
+ if (primary && path34.dirname(socket) !== primary && !socketPaths.has(path34.basename(socket))) socketPaths.set(path34.basename(socket), socket);
33221
33378
  try {
33222
- const [session, window2] = (await deps.run(path33.basename(socket), ["display-message", "-p", "-t", pane, "#{session_id} #{window_id}"], { timeoutMs: 1500 })).trim().split(" ");
33379
+ const [session, window2] = (await deps.run(path34.basename(socket), ["display-message", "-p", "-t", pane, "#{session_id} #{window_id}"], { timeoutMs: 1500 })).trim().split(" ");
33223
33380
  const workspace = fromTmuxId(session ?? ""), tab = fromTmuxId(window2 ?? "");
33224
33381
  return workspace && tab ? { server, workspace, tab, pane: fromTmuxId(pane) } : void 0;
33225
33382
  } catch {
@@ -33254,7 +33411,7 @@ var init_terminal_tmux = __esm({
33254
33411
  reject(new BridgeError(503, "tmux is not installed on this computer."));
33255
33412
  return;
33256
33413
  }
33257
- const child = execFile3(
33414
+ const child = execFile4(
33258
33415
  binary,
33259
33416
  [...socketFlags(socket), ...args],
33260
33417
  { timeout: options.timeoutMs ?? 5e3, maxBuffer: 4194304, env: tmuxEnvironment(), signal: options.signal },
@@ -33267,7 +33424,7 @@ var init_terminal_tmux = __esm({
33267
33424
  else child.stdin?.end();
33268
33425
  }),
33269
33426
  processes: () => new Promise((resolve11) => {
33270
- execFile3(
33427
+ execFile4(
33271
33428
  "ps",
33272
33429
  ["-A", "-o", "pid=,pgid=,tpgid=,tty=,args="],
33273
33430
  { timeout: 3e3, maxBuffer: 8388608, env: { ...process.env, LC_ALL: "C" } },
@@ -33280,7 +33437,7 @@ var init_terminal_tmux = __esm({
33280
33437
  resolve11("");
33281
33438
  return;
33282
33439
  }
33283
- execFile3(binary, ["-V"], { timeout: 3e3 }, (error62, stdout) => resolve11(error62 ? "" : String(stdout)));
33440
+ execFile4(binary, ["-V"], { timeout: 3e3 }, (error62, stdout) => resolve11(error62 ? "" : String(stdout)));
33284
33441
  }),
33285
33442
  sockets: async () => (await Promise.all(tmuxSocketFolders().map(tmuxSocketsIn))).flat(),
33286
33443
  sleep: (ms, signal) => new Promise((resolve11, reject) => {
@@ -33362,7 +33519,7 @@ var init_terminal_tmux = __esm({
33362
33519
  await tmux(server, ["send-keys", "-t", target, "Enter"], { signal });
33363
33520
  },
33364
33521
  async create(server, { workspace, label: label2, cwd }) {
33365
- const directory = cwd && path33.isAbsolute(cwd) ? ["-c", cwd] : [];
33522
+ const directory = cwd && path34.isAbsolute(cwd) ? ["-c", cwd] : [];
33366
33523
  const name = label2 ? ["-n", label2.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 100)] : [];
33367
33524
  if (workspace) {
33368
33525
  await tmux(server, ["new-window", "-d", "-t", `${toTmuxId(workspace, "s")}:`, ...directory, ...name]);
@@ -33512,6 +33669,7 @@ __export(herdr_exports, {
33512
33669
  opencodePidSession: () => opencodePidSession,
33513
33670
  paneAgentName: () => paneAgentName,
33514
33671
  paneChatState: () => paneChatState,
33672
+ paneForCodexSession: () => paneForCodexSession,
33515
33673
  paneIdentity: () => paneIdentity,
33516
33674
  panes: () => panes,
33517
33675
  recentServers: () => recentServers,
@@ -33527,26 +33685,26 @@ __export(herdr_exports, {
33527
33685
  workspaceSnapshot: () => workspaceSnapshot
33528
33686
  });
33529
33687
  import { createHmac, randomBytes as randomBytes2 } from "node:crypto";
33530
- import { execFile as execFile4 } from "node:child_process";
33688
+ import { execFile as execFile5 } from "node:child_process";
33531
33689
  import { connect } from "node:net";
33532
33690
  import { homedir as homedir8 } from "node:os";
33533
- import { open as open6, readdir as readdir7, readlink, realpath as realpath6, stat as stat9 } from "node:fs/promises";
33534
- import path34 from "node:path";
33535
- import { promisify as promisify3 } from "node:util";
33691
+ import { open as open7, readdir as readdir8, readlink, realpath as realpath7, stat as stat10 } from "node:fs/promises";
33692
+ import path35 from "node:path";
33693
+ import { promisify as promisify4 } from "node:util";
33536
33694
  function herdrRoot() {
33537
- return process.env.PHREN_HERDR_HOME || path34.join(homedir8(), ".config/herdr");
33695
+ return process.env.PHREN_HERDR_HOME || path35.join(homedir8(), ".config/herdr");
33538
33696
  }
33539
33697
  function herdrSocketPath(server) {
33540
33698
  return herdrSocket(server);
33541
33699
  }
33542
33700
  function herdrSocket(server) {
33543
33701
  serverName.parse(server);
33544
- return path34.join(herdrRoot(), ...server === "default" ? [] : ["sessions", server], "herdr.sock");
33702
+ return path35.join(herdrRoot(), ...server === "default" ? [] : ["sessions", server], "herdr.sock");
33545
33703
  }
33546
33704
  function herdrPaneFromEnv(env = process.env) {
33547
33705
  if (env.HERDR_ENV !== "1" || !env.HERDR_SOCKET_PATH) return void 0;
33548
- const socket = path34.resolve(env.HERDR_SOCKET_PATH), root = path34.resolve(herdrRoot());
33549
- const server = socket === path34.join(root, "herdr.sock") ? "default" : socket.startsWith(path34.join(root, "sessions") + path34.sep) ? path34.basename(path34.dirname(socket)) : void 0;
33706
+ const socket = path35.resolve(env.HERDR_SOCKET_PATH), root = path35.resolve(herdrRoot());
33707
+ const server = socket === path35.join(root, "herdr.sock") ? "default" : socket.startsWith(path35.join(root, "sessions") + path35.sep) ? path35.basename(path35.dirname(socket)) : void 0;
33550
33708
  const { HERDR_WORKSPACE_ID: workspace, HERDR_TAB_ID: tab, HERDR_PANE_ID: pane } = env;
33551
33709
  if (!server || !workspace || !tab || !pane) return void 0;
33552
33710
  return { server, workspace, tab, pane };
@@ -33568,7 +33726,7 @@ function noteOptionalReadFailure(what, key2, error62) {
33568
33726
  async function rpc(server, method, params = {}, signal, timeoutMs = 1e4) {
33569
33727
  const socket = herdrSocket(server);
33570
33728
  countHerdr(method);
33571
- const metadata = await stat9(socket).catch((error62) => {
33729
+ const metadata = await stat10(socket).catch((error62) => {
33572
33730
  throw herdrSocketError(error62);
33573
33731
  });
33574
33732
  if (!metadata.isSocket() || process.getuid && metadata.uid !== process.getuid()) throw new BridgeError(503, "The Herdr socket is unavailable.", { code: "herdr-permission" });
@@ -33625,7 +33783,7 @@ async function recentServers(maxAgeMs = SERVER_LIST_REUSE_MS) {
33625
33783
  return value2;
33626
33784
  }
33627
33785
  async function servers() {
33628
- const names = ["default", ...(await readdir7(path34.join(herdrRoot(), "sessions")).catch(() => [])).filter((n) => serverName.safeParse(n).success)].slice(0, 64);
33786
+ const names = ["default", ...(await readdir8(path35.join(herdrRoot(), "sessions")).catch(() => [])).filter((n) => serverName.safeParse(n).success)].slice(0, 64);
33629
33787
  const results = await Promise.all(names.map(async (name) => {
33630
33788
  try {
33631
33789
  await rpc(name, "ping");
@@ -33635,7 +33793,7 @@ async function servers() {
33635
33793
  }
33636
33794
  }));
33637
33795
  const running2 = results.filter((v) => v !== null);
33638
- if (!running2.length) running2.push(...await Promise.resolve().then(() => (init_terminal_tmux(), terminal_tmux_exports)).then((tmux2) => tmux2.tmuxServers()).catch(() => []));
33796
+ running2.push(...await Promise.resolve().then(() => (init_terminal_tmux(), terminal_tmux_exports)).then((tmux2) => tmux2.tmuxServers({ hidden: !running2.length })).catch(() => []));
33639
33797
  knownServers = running2.map((server) => String(server.session));
33640
33798
  return running2;
33641
33799
  }
@@ -33728,10 +33886,10 @@ async function processLogs(pids) {
33728
33886
  if (process.platform === "linux") {
33729
33887
  countIdentity("proc");
33730
33888
  const base = `/proc/${pid}/fd`;
33731
- return Promise.all((await readdir7(base).catch(() => [])).slice(0, 4096).map((fd) => readlink(path34.join(base, fd)).catch(() => "")));
33889
+ return Promise.all((await readdir8(base).catch(() => [])).slice(0, 4096).map((fd) => readlink(path35.join(base, fd)).catch(() => "")));
33732
33890
  }
33733
33891
  countIdentity("lsof");
33734
- const result = await exec3("/usr/sbin/lsof", ["-a", "-p", String(pid), "-Fn"], { timeout: 3e3, maxBuffer: 1048576 }).catch(() => ({ stdout: "" }));
33892
+ const result = await exec4("/usr/sbin/lsof", ["-a", "-p", String(pid), "-Fn"], { timeout: 3e3, maxBuffer: 1048576 }).catch(() => ({ stdout: "" }));
33735
33893
  return result.stdout.split("\n").filter((n) => n.startsWith("n/")).map((n) => n.slice(1));
33736
33894
  }));
33737
33895
  return [...new Set(paths.flat())].filter((p) => p.endsWith(".jsonl") || p.endsWith(".lock"));
@@ -33765,12 +33923,12 @@ async function paneIdentity(server, pane, fresh = false) {
33765
33923
  }
33766
33924
  async function copilotForegroundSession(pids, home = copilotHome()) {
33767
33925
  if (!pids.length) return void 0;
33768
- const folder = path34.join(home, "logs");
33769
- const names = await readdir7(folder).catch(() => []);
33926
+ const folder = path35.join(home, "logs");
33927
+ const names = await readdir8(folder).catch(() => []);
33770
33928
  const logs = names.filter((name) => pids.some((pid) => name.startsWith("process-") && name.endsWith(`-${pid}.log`)));
33771
33929
  let current2, latest = -1;
33772
33930
  for (const name of logs) {
33773
- const file2 = await open6(path34.join(folder, name), "r").catch(() => void 0);
33931
+ const file2 = await open7(path35.join(folder, name), "r").catch(() => void 0);
33774
33932
  if (!file2) continue;
33775
33933
  try {
33776
33934
  const { size } = await file2.stat(), length = Math.min(size, 262144);
@@ -33789,10 +33947,10 @@ async function copilotForegroundSession(pids, home = copilotHome()) {
33789
33947
  return current2;
33790
33948
  }
33791
33949
  async function opencodePidSession(pids, root = phrenStoreRoot()) {
33792
- const folder = path34.join(root, ".runtime", "sessions");
33950
+ const folder = path35.join(root, ".runtime", "sessions");
33793
33951
  let current2, latest = -Infinity;
33794
33952
  for (const pid of pids) {
33795
- const file2 = await open6(path34.join(folder, `opencode-pid-${pid}.json`), "r").catch(() => void 0);
33953
+ const file2 = await open7(path35.join(folder, `opencode-pid-${pid}.json`), "r").catch(() => void 0);
33796
33954
  if (!file2) continue;
33797
33955
  try {
33798
33956
  const { size } = await file2.stat();
@@ -33801,7 +33959,7 @@ async function opencodePidSession(pids, root = phrenStoreRoot()) {
33801
33959
  const session = typeof value2.session === "string" && /^ses_[0-9A-Za-z]{1,64}$/.test(value2.session) ? value2.session : void 0;
33802
33960
  const at = Date.parse(String(value2.at));
33803
33961
  if (!session || !(at > latest)) continue;
33804
- if (!await stat9(path34.join(folder, `opencode-${session}.events.jsonl`)).catch(() => void 0)) continue;
33962
+ if (!await stat10(path35.join(folder, `opencode-${session}.events.jsonl`)).catch(() => void 0)) continue;
33805
33963
  current2 = session;
33806
33964
  latest = at;
33807
33965
  } catch {
@@ -33819,7 +33977,7 @@ async function identityFromProcesses(server, pane, pids) {
33819
33977
  }
33820
33978
  if (pane.agent === "copilot") {
33821
33979
  const current2 = await copilotForegroundSession(pids).catch(() => void 0);
33822
- if (current2) return await stat9(path34.join(copilotHome(), "session-state", current2, "events.jsonl")).then(() => ({ sessionId: current2, noTranscriptLogs: false }), () => ({ noTranscriptLogs: true }));
33980
+ if (current2) return await stat10(path35.join(copilotHome(), "session-state", current2, "events.jsonl")).then(() => ({ sessionId: current2, noTranscriptLogs: false }), () => ({ noTranscriptLogs: true }));
33823
33981
  const reported = object2(pane.agent_session);
33824
33982
  if (reported.kind === "id" && reported.agent === "copilot" && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) return { sessionId: reported.value, noTranscriptLogs: false };
33825
33983
  }
@@ -33829,9 +33987,51 @@ async function identityFromProcesses(server, pane, pids) {
33829
33987
  return match ? [match[1]] : [];
33830
33988
  });
33831
33989
  if (new Set(candidates).size === 1) return { sessionId: candidates[0], noTranscriptLogs: false };
33990
+ if (pane.agent === "codex" && candidates.length === 0) {
33991
+ const daemon = await codexDaemonIdentity(server, pane, pids).catch(() => void 0);
33992
+ if (daemon?.sessionId) return { sessionId: daemon.sessionId, noTranscriptLogs: false };
33993
+ const recorded2 = await recordedSession(server, pane, pids);
33994
+ return { sessionId: recorded2 && !daemon?.known.has(recorded2) ? recorded2 : void 0, noTranscriptLogs: true };
33995
+ }
33832
33996
  const recorded = await recordedSession(server, pane, pids);
33833
33997
  return { sessionId: candidates.length === 0 || recorded && candidates.includes(recorded) ? recorded : void 0, noTranscriptLogs: candidates.length === 0 };
33834
33998
  }
33999
+ async function codexDaemonIdentity(server, pane, pids) {
34000
+ const all = await daemonRollouts(processLogs);
34001
+ const known = new Set(all.map((r) => r.id));
34002
+ const cwd = paneCwd(pane);
34003
+ const here = [];
34004
+ for (const r of all) if (await sameDirectory(r.cwd, cwd)) here.push(r);
34005
+ if (!here.length) return { known };
34006
+ const rows = await processTable(), start = startedAt(rows, pids);
34007
+ if (start === void 0) return { known };
34008
+ const s = await (await terminal()).terminalProvider().snapshot(server).catch(() => ({}));
34009
+ const claimed = /* @__PURE__ */ new Set(), rivals = [];
34010
+ for (const peer of objects(s.panes).filter((p) => p.agent === "codex" && p.pane_id !== pane.pane_id).slice(0, 16)) {
34011
+ if (!await sameDirectory(paneCwd(peer), cwd)) continue;
34012
+ const peerPids = await foregroundPids(server, peer).catch(() => []);
34013
+ if (!peerPids.length) continue;
34014
+ const own2 = rolloutIds(await processLogs(peerPids));
34015
+ if (own2.length) {
34016
+ for (const id2 of own2) claimed.add(id2);
34017
+ continue;
34018
+ }
34019
+ const peerStart = startedAt(rows, peerPids);
34020
+ if (peerStart !== void 0) rivals.push({ key: String(peer.pane_id), start: peerStart });
34021
+ }
34022
+ return { sessionId: assignDaemonConversation(here, { key: String(pane.pane_id), start }, claimed, rivals), known };
34023
+ }
34024
+ async function paneForCodexSession(server, session, cwd) {
34025
+ const s = await snapshot(server);
34026
+ const codex2 = objects(s.panes).filter((p) => p.agent === "codex").slice(0, 32);
34027
+ const identities2 = await Promise.all(codex2.map((p) => paneIdentity(server, p).catch(() => void 0)));
34028
+ const index2 = identities2.indexOf(session);
34029
+ if (index2 >= 0) return codex2[index2];
34030
+ if (!cwd) return void 0;
34031
+ const same = [];
34032
+ for (const [i, p] of codex2.entries()) if (await sameDirectory(paneCwd(p), cwd)) same.push(i);
34033
+ return same.length === 1 && !identities2[same[0]] ? codex2[same[0]] : void 0;
34034
+ }
33835
34035
  async function paneChatState(server, pane, options = {}) {
33836
34036
  if (!provider.safeParse(pane.agent).success) return {};
33837
34037
  const identity = await resolveIdentity(server, pane, false);
@@ -33895,10 +34095,10 @@ async function validateTarget(target, sending = false, refreshIdentity = sending
33895
34095
  }
33896
34096
  async function trustedDirectory(pane) {
33897
34097
  const cwd = pane.foreground_cwd || pane.cwd;
33898
- if (typeof cwd !== "string" || !path34.isAbsolute(cwd)) throw new BridgeError(409, "This pane has no project folder.");
33899
- return realpath6(cwd);
34098
+ if (typeof cwd !== "string" || !path35.isAbsolute(cwd)) throw new BridgeError(409, "This pane has no project folder.");
34099
+ return realpath7(cwd);
33900
34100
  }
33901
- var terminal, exec3, optionalReadFailures, SERVER_LIST_REUSE_MS, serverList, knownServers, SNAPSHOT_SHARE_MS, sharedSnapshots, inFlightSnapshots, IDENTITY_CACHE_MS, identities, identityKey, copilotHome, startingKey, sharedIdentities;
34101
+ 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;
33902
34102
  var init_herdr = __esm({
33903
34103
  "src/bridge/herdr.ts"() {
33904
34104
  "use strict";
@@ -33909,8 +34109,9 @@ var init_herdr = __esm({
33909
34109
  init_limits();
33910
34110
  init_metrics();
33911
34111
  init_transcripts();
34112
+ init_codex_daemon();
33912
34113
  terminal = () => Promise.resolve().then(() => (init_terminal(), terminal_exports));
33913
- exec3 = promisify3(execFile4);
34114
+ exec4 = promisify4(execFile5);
33914
34115
  optionalReadFailures = /* @__PURE__ */ new Map();
33915
34116
  SERVER_LIST_REUSE_MS = intervalFromEnv("PHREN_SERVER_LIST_REUSE_MS", 3e4, 0, 6e5);
33916
34117
  SNAPSHOT_SHARE_MS = intervalFromEnv("PHREN_SNAPSHOT_SHARE_MS", 2500, 0, 1e4);
@@ -33919,7 +34120,9 @@ var init_herdr = __esm({
33919
34120
  IDENTITY_CACHE_MS = intervalFromEnv("PHREN_IDENTITY_CACHE_MS", 2e3);
33920
34121
  identities = /* @__PURE__ */ new Map();
33921
34122
  identityKey = (server, pane, pids) => JSON.stringify([server, pane.pane_id, pane.terminal_id, pids, pane.agent]);
33922
- copilotHome = () => process.env.COPILOT_HOME || path34.join(homedir8(), ".copilot");
34123
+ copilotHome = () => process.env.COPILOT_HOME || path35.join(homedir8(), ".copilot");
34124
+ rolloutIds = (files) => files.flatMap((file2) => /rollout-.*-([a-f0-9-]{36})\.jsonl$/i.exec(file2)?.[1] ?? []);
34125
+ paneCwd = (pane) => pane.foreground_cwd || pane.cwd;
33923
34126
  startingKey = randomBytes2(32);
33924
34127
  sharedIdentities = /* @__PURE__ */ new WeakMap();
33925
34128
  }
@@ -33955,7 +34158,7 @@ var init_preferences = __esm({
33955
34158
  // src/project-config.ts
33956
34159
  import * as crypto4 from "crypto";
33957
34160
  import * as fs23 from "fs";
33958
- import * as path42 from "path";
34161
+ import * as path43 from "path";
33959
34162
  function parseProjectOwnershipMode(raw) {
33960
34163
  if (!raw) return void 0;
33961
34164
  const normalized = raw.trim().toLowerCase();
@@ -33970,7 +34173,7 @@ function resolveProjectConfigPath(phrenPath, project) {
33970
34173
  return storeAwareProjectPath(phrenPath, project, "phren.project.yaml");
33971
34174
  }
33972
34175
  function writeProjectConfigFile(configPath, next) {
33973
- fs23.mkdirSync(path42.dirname(configPath), { recursive: true });
34176
+ fs23.mkdirSync(path43.dirname(configPath), { recursive: true });
33974
34177
  const tmpPath = `${configPath}.tmp-${crypto4.randomUUID()}`;
33975
34178
  fs23.writeFileSync(tmpPath, dump(next, { lineWidth: 1e3 }));
33976
34179
  fs23.renameSync(tmpPath, configPath);
@@ -34023,7 +34226,7 @@ function getProjectSourcePath(phrenPath, project, config3, machine = getMachineN
34023
34226
  const resolved = config3 ?? readProjectConfig(phrenPath, project);
34024
34227
  const perMachine = resolved.sourcePaths && typeof resolved.sourcePaths === "object" && !Array.isArray(resolved.sourcePaths) ? resolved.sourcePaths[machine] : void 0;
34025
34228
  const raw = typeof perMachine === "string" && perMachine.trim() ? perMachine : resolved.sourcePath;
34026
- return typeof raw === "string" && raw.trim() ? path42.resolve(raw) : void 0;
34229
+ return typeof raw === "string" && raw.trim() ? path43.resolve(raw) : void 0;
34027
34230
  }
34028
34231
  function recordProjectSourcePath(phrenPath, project, sourceRoot, patch = {}, machine = getMachineName()) {
34029
34232
  const current2 = readProjectConfig(phrenPath, project);
@@ -34066,11 +34269,11 @@ __export(agent_package_exports, {
34066
34269
  import { execFileSync as execFileSync4, spawn as spawn4 } from "node:child_process";
34067
34270
  import * as fs24 from "node:fs";
34068
34271
  import { createRequire } from "node:module";
34069
- import * as path45 from "node:path";
34272
+ import * as path47 from "node:path";
34070
34273
  import { fileURLToPath as fileURLToPath4 } from "node:url";
34071
34274
  function readManifest(directory) {
34072
34275
  try {
34073
- return JSON.parse(fs24.readFileSync(path45.join(directory, "package.json"), "utf8"));
34276
+ return JSON.parse(fs24.readFileSync(path47.join(directory, "package.json"), "utf8"));
34074
34277
  } catch {
34075
34278
  return void 0;
34076
34279
  }
@@ -34080,15 +34283,15 @@ function agentPackageAt(directory, source) {
34080
34283
  if (manifest?.name !== "@phren/agent") return void 0;
34081
34284
  const relative3 = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.["phren-agent"];
34082
34285
  if (!relative3) return void 0;
34083
- const bin = path45.join(directory, relative3);
34286
+ const bin = path47.join(directory, relative3);
34084
34287
  return fs24.existsSync(bin) ? { directory, bin, version: manifest.version, source } : void 0;
34085
34288
  }
34086
34289
  function workspaceDirectory() {
34087
- let directory = path45.dirname(fileURLToPath4(import.meta.url));
34290
+ let directory = path47.dirname(fileURLToPath4(import.meta.url));
34088
34291
  for (let depth = 0; depth < 8; depth++) {
34089
- const candidate = path45.join(directory, "packages", "agent");
34090
- if (fs24.existsSync(path45.join(candidate, "package.json"))) return candidate;
34091
- const parent = path45.dirname(directory);
34292
+ const candidate = path47.join(directory, "packages", "agent");
34293
+ if (fs24.existsSync(path47.join(candidate, "package.json"))) return candidate;
34294
+ const parent = path47.dirname(directory);
34092
34295
  if (parent === directory) break;
34093
34296
  directory = parent;
34094
34297
  }
@@ -34096,7 +34299,7 @@ function workspaceDirectory() {
34096
34299
  }
34097
34300
  function resolvedDirectory() {
34098
34301
  try {
34099
- return path45.dirname(createRequire(import.meta.url).resolve("@phren/agent/package.json"));
34302
+ return path47.dirname(createRequire(import.meta.url).resolve("@phren/agent/package.json"));
34100
34303
  } catch {
34101
34304
  return void 0;
34102
34305
  }
@@ -34105,7 +34308,7 @@ function globalDirectory() {
34105
34308
  try {
34106
34309
  const options = { encoding: "utf8", timeout: 1e4, stdio: ["ignore", "pipe", "ignore"] };
34107
34310
  const root = (process.platform === "win32" ? execFileSync4("npm.cmd", ["root", "-g"], { ...options, shell: true }) : execFileSync4("npm", ["root", "-g"], options)).trim();
34108
- return root ? path45.join(root, "@phren", "agent") : void 0;
34311
+ return root ? path47.join(root, "@phren", "agent") : void 0;
34109
34312
  } catch {
34110
34313
  return void 0;
34111
34314
  }
@@ -34244,7 +34447,7 @@ var init_audit = __esm({
34244
34447
 
34245
34448
  // src/governance/activity.ts
34246
34449
  import * as fs25 from "fs";
34247
- import * as path55 from "path";
34450
+ import * as path57 from "path";
34248
34451
  function clampSnippet(snippet) {
34249
34452
  if (!snippet) return void 0;
34250
34453
  const flat = snippet.replace(/\s+/g, " ").trim();
@@ -34255,7 +34458,7 @@ function recordLookupEvents(phrenPath, events) {
34255
34458
  if (!events.length) return;
34256
34459
  const logPath = lookupEventsLogFile(phrenPath);
34257
34460
  try {
34258
- fs25.mkdirSync(path55.dirname(logPath), { recursive: true });
34461
+ fs25.mkdirSync(path57.dirname(logPath), { recursive: true });
34259
34462
  const now = (/* @__PURE__ */ new Date()).toISOString();
34260
34463
  const lines = events.map(
34261
34464
  (e) => JSON.stringify({
@@ -34277,8 +34480,8 @@ function recordLookupEvents(phrenPath, events) {
34277
34480
  return;
34278
34481
  }
34279
34482
  try {
34280
- const stat26 = fs25.statSync(logPath);
34281
- if (stat26.size > ROTATE_BYTES) {
34483
+ const stat27 = fs25.statSync(logPath);
34484
+ if (stat27.size > ROTATE_BYTES) {
34282
34485
  const content = fs25.readFileSync(logPath, "utf8");
34283
34486
  const kept = content.split("\n").filter(Boolean).slice(-MAX_LOG_LINES2);
34284
34487
  fs25.writeFileSync(logPath, kept.join("\n") + "\n");
@@ -34540,7 +34743,7 @@ var init_metadata = __esm({
34540
34743
 
34541
34744
  // src/governance/policy.ts
34542
34745
  import * as fs26 from "fs";
34543
- import * as path56 from "path";
34746
+ import * as path58 from "path";
34544
34747
  function assessSyncOutage(sync, nowMs = Date.now()) {
34545
34748
  const consecutiveFailures = sync?.consecutiveFailures ?? 0;
34546
34749
  const failingNow = sync?.lastPushStatus !== void 0 && FAILED_PUSH_STATUSES.has(sync.lastPushStatus);
@@ -34677,7 +34880,7 @@ function normalizeIndexPolicy(data) {
34677
34880
  function readJsonFile(filePath, fallback) {
34678
34881
  try {
34679
34882
  if (!fs26.existsSync(filePath)) return fallback;
34680
- const basename12 = path56.basename(filePath);
34883
+ const basename12 = path58.basename(filePath);
34681
34884
  const schema = GOVERNANCE_FILE_SCHEMAS[basename12];
34682
34885
  if (schema && !validateGovernanceJson(filePath, schema)) {
34683
34886
  debugLog(`readJsonFile: ${filePath} failed validation, using defaults`);
@@ -35077,9 +35280,9 @@ import * as path23 from "node:path";
35077
35280
  function gitDirectory(store) {
35078
35281
  const dotGit = path23.join(store, ".git");
35079
35282
  try {
35080
- const stat26 = fs15.statSync(dotGit);
35081
- if (stat26.isDirectory()) return dotGit;
35082
- if (!stat26.isFile()) return void 0;
35283
+ const stat27 = fs15.statSync(dotGit);
35284
+ if (stat27.isDirectory()) return dotGit;
35285
+ if (!stat27.isFile()) return void 0;
35083
35286
  const match = /^gitdir:\s*(.+)\s*$/i.exec(fs15.readFileSync(dotGit, "utf8"));
35084
35287
  if (!match) return void 0;
35085
35288
  return path23.resolve(store, match[1]);
@@ -35114,7 +35317,7 @@ import * as fs17 from "node:fs";
35114
35317
  import * as path25 from "node:path";
35115
35318
  var core = (names) => names.map((name) => ({ name, profiles: ["core", "full"] }));
35116
35319
  var full = (names) => names.map((name) => ({ name, profiles: ["full"] }));
35117
- var routes = (method, paths) => paths.map((path84) => ({ method, path: path84 }));
35320
+ var routes = (method, paths) => paths.map((path86) => ({ method, path: path86 }));
35118
35321
  var BUILTIN_MODULES = [
35119
35322
  {
35120
35323
  schemaVersion: 1,
@@ -35637,7 +35840,7 @@ import { chmod as chmod5, lstat as lstat20, mkdir as mkdir21, readFile as readFi
35637
35840
  import { readFileSync as readFileSync32 } from "node:fs";
35638
35841
  import { createServer as createServer2 } from "node:http";
35639
35842
  import { cpus, hostname as hostname9, loadavg } from "node:os";
35640
- import path82 from "node:path";
35843
+ import path84 from "node:path";
35641
35844
 
35642
35845
  // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs
35643
35846
  var import_stream = __toESM(require_stream(), 1);
@@ -35903,11 +36106,12 @@ init_shared();
35903
36106
  init_logger();
35904
36107
  init_protocol();
35905
36108
  init_herdr();
36109
+ init_codex_daemon();
35906
36110
  init_terminal();
35907
36111
  import { request, createServer } from "node:http";
35908
36112
  import { mkdir as mkdir9, readFile as readFile14, chmod, unlink as unlink3, lstat as lstat7 } from "node:fs/promises";
35909
36113
  import { watch } from "node:fs";
35910
- import path37 from "node:path";
36114
+ import path38 from "node:path";
35911
36115
  import { randomUUID as randomUUID7 } from "node:crypto";
35912
36116
 
35913
36117
  // src/bridge/pane-text.ts
@@ -35934,7 +36138,7 @@ init_js_yaml();
35934
36138
  init_zod();
35935
36139
  init_protocol();
35936
36140
  import { lstat as lstat6, mkdir as mkdir8, readFile as readFile12 } from "node:fs/promises";
35937
- import path35 from "node:path";
36141
+ import path36 from "node:path";
35938
36142
  var grantAction = external_exports.enum(["dispatch", "hand_off"]);
35939
36143
  var grantScope = external_exports.union([
35940
36144
  external_exports.literal("global"),
@@ -35946,7 +36150,7 @@ var grantSchema = external_exports.object({
35946
36150
  computers: external_exports.array(computerName).min(1).max(32).optional().describe("Named verified peers; omitted means any."),
35947
36151
  until: external_exports.string().datetime({ offset: true }).optional().describe("Expiry timestamp; omitted means until revoked.")
35948
36152
  }).strict();
35949
- var grantFile = (root = bridgeRoot()) => path35.join(root, "conductor.yaml");
36153
+ var grantFile = (root = bridgeRoot()) => path36.join(root, "conductor.yaml");
35950
36154
  var fileSchema = external_exports.object({ grants: external_exports.array(grantSchema).max(64) }).strict();
35951
36155
  async function regularPrivateFile(file2) {
35952
36156
  const info = await lstat6(file2).catch(() => void 0);
@@ -36007,7 +36211,7 @@ function grantLabel(grant) {
36007
36211
  }
36008
36212
  var mutations = /* @__PURE__ */ new Map();
36009
36213
  async function mutateGrants(root, action) {
36010
- const key2 = path35.resolve(root);
36214
+ const key2 = path36.resolve(root);
36011
36215
  const previous = mutations.get(key2) ?? Promise.resolve();
36012
36216
  const pending = previous.catch(() => {
36013
36217
  }).then(async () => {
@@ -36086,9 +36290,9 @@ async function removeGrant(input2, root = bridgeRoot()) {
36086
36290
  init_zod();
36087
36291
  init_protocol();
36088
36292
  import { createCipheriv, createHmac as createHmac2, createPrivateKey, randomBytes as randomBytes3, sign } from "node:crypto";
36089
- import { readFile as readFile13, stat as stat10 } from "node:fs/promises";
36293
+ import { readFile as readFile13, stat as stat11 } from "node:fs/promises";
36090
36294
  import { connect as connect2 } from "node:http2";
36091
- import path36 from "node:path";
36295
+ import path37 from "node:path";
36092
36296
  var relaySchema = external_exports.object({
36093
36297
  url: external_exports.string().url().refine(
36094
36298
  (value2) => /^https:\/\//.test(value2) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${value2}/`),
@@ -36160,7 +36364,7 @@ function schedulePushPayload(value2) {
36160
36364
  }
36161
36365
  async function secureJSON(file2, schema) {
36162
36366
  try {
36163
- const metadata = await stat10(file2);
36367
+ const metadata = await stat11(file2);
36164
36368
  if ((metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
36165
36369
  return schema.parse(JSON.parse(await readFile13(file2, "utf8")));
36166
36370
  } catch {
@@ -36169,14 +36373,14 @@ async function secureJSON(file2, schema) {
36169
36373
  }
36170
36374
  async function secureFile(file2) {
36171
36375
  try {
36172
- const metadata = await stat10(file2);
36376
+ const metadata = await stat11(file2);
36173
36377
  if (!metadata.isFile() || (metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
36174
36378
  return await readFile13(file2, "utf8");
36175
36379
  } catch {
36176
36380
  return void 0;
36177
36381
  }
36178
36382
  }
36179
- function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path36.join(bridgeRoot(), "apns.json")) {
36383
+ function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path37.join(bridgeRoot(), "apns.json")) {
36180
36384
  return [
36181
36385
  "Approval push is not configured: the phone only alerts while Phren runs, and a registered phone gets nothing while suspended.",
36182
36386
  "1. In your Apple developer account, create an APNs key (Keys, Apple Push Notifications service) and download AuthKey_<KEYID>.p8.",
@@ -36298,13 +36502,13 @@ var APNsSender = class {
36298
36502
  var ApprovalPushService = class {
36299
36503
  devices = [];
36300
36504
  sender;
36301
- devicesFile = path36.join(bridgeRoot(), "push-devices.json");
36505
+ devicesFile = path37.join(bridgeRoot(), "push-devices.json");
36302
36506
  async start() {
36303
36507
  this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
36304
- const configFile = process.env.PHREN_APNS_CONFIG || path36.join(bridgeRoot(), "apns.json");
36508
+ const configFile = process.env.PHREN_APNS_CONFIG || path37.join(bridgeRoot(), "apns.json");
36305
36509
  const config3 = await secureJSON(configFile, configSchema2);
36306
36510
  if (!config3) return;
36307
- const keyPath = path36.isAbsolute(config3.privateKeyPath) ? config3.privateKeyPath : path36.resolve(path36.dirname(configFile), config3.privateKeyPath);
36511
+ const keyPath = path37.isAbsolute(config3.privateKeyPath) ? config3.privateKeyPath : path37.resolve(path37.dirname(configFile), config3.privateKeyPath);
36308
36512
  const key2 = await secureFile(keyPath);
36309
36513
  if (key2) this.sender = new APNsSender(config3, key2);
36310
36514
  }
@@ -36479,7 +36683,7 @@ var AgentHooks = class {
36479
36683
  fanoutTimer;
36480
36684
  fanoutArchiveTimer;
36481
36685
  approvalsDirectory() {
36482
- return path37.join(phrenStoreRoot(), ".runtime", "approvals");
36686
+ return path38.join(phrenStoreRoot(), ".runtime", "approvals");
36483
36687
  }
36484
36688
  scheduleOpencodeSweep() {
36485
36689
  if (this.closed || this.opencodeDebounce) return;
@@ -36548,13 +36752,13 @@ var AgentHooks = class {
36548
36752
  /** A session's exact pane. A recorded binding carries the full target; when
36549
36753
  * there is none, Herdr's explicit session identity names the pane. */
36550
36754
  async resolveTarget(source, session) {
36551
- const root = path37.join(bridgeRoot(), "bindings");
36755
+ const root = path38.join(bridgeRoot(), "bindings");
36552
36756
  for await (const folder of directoryNames(root, 64)) {
36553
- for await (const name of directoryNames(path37.join(root, folder), 1024)) {
36757
+ for await (const name of directoryNames(path38.join(root, folder), 1024)) {
36554
36758
  if (!name.endsWith(".json")) continue;
36555
36759
  let value2;
36556
36760
  try {
36557
- const file2 = path37.join(root, folder, name), info = await lstat7(file2);
36761
+ const file2 = path38.join(root, folder, name), info = await lstat7(file2);
36558
36762
  if (!info.isFile() || info.size > 65536) continue;
36559
36763
  value2 = object2(JSON.parse(await readFile14(file2, "utf8")));
36560
36764
  } catch {
@@ -37296,18 +37500,29 @@ var AgentHooks = class {
37296
37500
  if (size > 1048576) throw new Error("Oversized hook");
37297
37501
  chunks.push(bytes);
37298
37502
  }
37299
- const body2 = object2(JSON.parse(Buffer.concat(chunks).toString())), target = targetSchema.parse(body2.target);
37503
+ const body2 = object2(JSON.parse(Buffer.concat(chunks).toString()));
37504
+ let target = targetSchema.parse(body2.target);
37300
37505
  if (this.modules?.has("git") === false && ["PreToolUse", "PostToolUse"].includes(String(body2.event))) {
37301
37506
  res.statusCode = 404;
37302
37507
  res.end(JSON.stringify({ error: disabledHint("git") }));
37303
37508
  return;
37304
37509
  }
37510
+ const daemon = body2.daemon === true;
37511
+ if (daemon) {
37512
+ if (target.source !== "codex") throw new Error("Invalid callback");
37513
+ const placed = await paneForCodexSession(target.server, target.session, typeof body2.cwd === "string" && path38.isAbsolute(body2.cwd) ? body2.cwd : void 0);
37514
+ if (!placed) {
37515
+ res.end("{}");
37516
+ return;
37517
+ }
37518
+ target = targetSchema.parse({ ...target, workspace: placed.workspace_id, tab: placed.tab_id, pane: placed.pane_id });
37519
+ }
37305
37520
  const s = await snapshot(target.server);
37306
37521
  const pane = findPane(s, { workspace: target.workspace, tab: target.tab, pane: target.pane });
37307
37522
  if (!pane || pane.agent && pane.agent !== target.source) throw new Error("The pane changed");
37308
37523
  const pids = (await terminalProvider().processes(target.server, target.pane)).foregroundPids;
37309
37524
  if (!pids.length) throw new Error("No foreground process");
37310
- await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({
37525
+ if (!daemon) await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({
37311
37526
  terminal: pane.terminal_id,
37312
37527
  source: target.source,
37313
37528
  session: target.session,
@@ -37332,7 +37547,7 @@ var AgentHooks = class {
37332
37547
  }
37333
37548
  if ((this.modules?.has("git") ?? true) && ["PreToolUse", "PostToolUse"].includes(String(body2.event)) && capturesChanges(String(body2.tool), input2)) {
37334
37549
  const conversation = `${target.source}:${target.session}`, id2 = String(body2.toolUseId || "").slice(0, 200);
37335
- 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);
37550
+ 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);
37336
37551
  else await this.changes.after(conversation, id2);
37337
37552
  res.end("{}");
37338
37553
  return;
@@ -37503,9 +37718,11 @@ async function agentHook(source) {
37503
37718
  const event = String(value2.hook_event_name || "SessionStart");
37504
37719
  const modules = activateModules(defaultPhrenPath(), void 0, true);
37505
37720
  if (!modules.has("hook") || event.endsWith("ToolUse") && !modules.has("git")) return;
37721
+ const daemon = source === "codex" && await underCodexDaemon().catch(() => false);
37506
37722
  const data = JSON.stringify({
37507
37723
  target,
37508
37724
  event,
37725
+ ...daemon ? { daemon: true } : {},
37509
37726
  tool: value2.tool_name,
37510
37727
  input: value2.tool_input,
37511
37728
  toolUseId: value2.tool_use_id,
@@ -37547,27 +37764,27 @@ init_changes();
37547
37764
  init_store_registry();
37548
37765
  import { rm as rm4 } from "node:fs/promises";
37549
37766
  import * as fs21 from "node:fs";
37550
- import * as path41 from "node:path";
37767
+ import * as path42 from "node:path";
37551
37768
 
37552
37769
  // src/bridge/projects.ts
37553
37770
  init_utils_helpers();
37554
37771
  init_home_paths();
37555
37772
  init_transcripts();
37556
- import { execFile as execFile5 } from "node:child_process";
37557
- import { promisify as promisify4 } from "node:util";
37773
+ import { execFile as execFile6 } from "node:child_process";
37774
+ import { promisify as promisify5 } from "node:util";
37558
37775
  import { request as request2 } from "node:http";
37559
37776
  import { userInfo as userInfo2 } from "node:os";
37560
- import { readFile as readFile16, realpath as realpath7, stat as stat12 } from "node:fs/promises";
37561
- import path39 from "node:path";
37777
+ import { readFile as readFile16, realpath as realpath8, stat as stat13 } from "node:fs/promises";
37778
+ import path40 from "node:path";
37562
37779
 
37563
37780
  // src/bridge/locate.ts
37564
37781
  init_protocol();
37565
37782
  init_herdr();
37566
37783
  init_transcripts();
37567
37784
  import { realpathSync as realpathSync3 } from "node:fs";
37568
- import { readFile as readFile15, stat as stat11 } from "node:fs/promises";
37785
+ import { readFile as readFile15, stat as stat12 } from "node:fs/promises";
37569
37786
  import { homedir as homedir9 } from "node:os";
37570
- import path38 from "node:path";
37787
+ import path39 from "node:path";
37571
37788
  var PROJECT_NAME = /^[a-z0-9][a-z0-9-]*$/;
37572
37789
  var SEARCH_ROOTS = ["", "Sites", "Projects", "projects", "Code", "code", "dev", "src", "repos", "workspace"];
37573
37790
  async function locateProject(project, activity, env = process.env) {
@@ -37575,9 +37792,9 @@ async function locateProject(project, activity, env = process.env) {
37575
37792
  const found = [];
37576
37793
  const seen = /* @__PURE__ */ new Set();
37577
37794
  const offer = async (directory, source, lastSeen) => {
37578
- let dir = path38.resolve(directory);
37795
+ let dir = path39.resolve(directory);
37579
37796
  try {
37580
- if (!(await stat11(dir)).isDirectory()) return;
37797
+ if (!(await stat12(dir)).isDirectory()) return;
37581
37798
  dir = realpathSync3.native(dir);
37582
37799
  } catch {
37583
37800
  return;
@@ -37590,33 +37807,33 @@ async function locateProject(project, activity, env = process.env) {
37590
37807
  const namesProject = (directory) => segments(directory).includes(project);
37591
37808
  const trimmed = (directory) => {
37592
37809
  const parts = segments(directory);
37593
- return parts.slice(0, parts.lastIndexOf(project) + 1).join(path38.sep);
37810
+ return parts.slice(0, parts.lastIndexOf(project) + 1).join(path39.sep);
37594
37811
  };
37595
37812
  for (const event of [...activity].reverse()) {
37596
37813
  const directory = typeof event.directory === "string" ? event.directory : void 0;
37597
- if (directory && path38.isAbsolute(directory) && namesProject(directory)) {
37814
+ if (directory && path39.isAbsolute(directory) && namesProject(directory)) {
37598
37815
  await offer(trimmed(directory), "activity", typeof event.at === "string" ? event.at : void 0);
37599
37816
  }
37600
37817
  }
37601
37818
  try {
37602
- const session = JSON.parse(await readFile15(path38.join(herdrRoot(), "session.json"), "utf8"));
37819
+ const session = JSON.parse(await readFile15(path39.join(herdrRoot(), "session.json"), "utf8"));
37603
37820
  for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
37604
37821
  const directory = JSON.parse(`"${match[1]}"`);
37605
- if (path38.isAbsolute(directory) && namesProject(directory)) {
37822
+ if (path39.isAbsolute(directory) && namesProject(directory)) {
37606
37823
  await offer(trimmed(directory), "herdr");
37607
37824
  }
37608
37825
  }
37609
37826
  } catch {
37610
37827
  }
37611
37828
  try {
37612
- const config3 = await readFile15(path38.join(phrenStoreRoot(env), project, "phren.project.yaml"), "utf8");
37829
+ const config3 = await readFile15(path39.join(phrenStoreRoot(env), project, "phren.project.yaml"), "utf8");
37613
37830
  const match = /^sourcePath:\s*(.+)$/m.exec(config3);
37614
37831
  if (match) await offer(match[1].trim().replace(/^['"]|['"]$/g, ""), "phren");
37615
37832
  } catch {
37616
37833
  }
37617
37834
  const home = homedir9();
37618
- for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS.map((r) => path38.join(home, r))]) {
37619
- await offer(path38.join(root, project), "search");
37835
+ for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS.map((r) => path39.join(home, r))]) {
37836
+ await offer(path39.join(root, project), "search");
37620
37837
  }
37621
37838
  return found.slice(0, 8);
37622
37839
  }
@@ -37624,10 +37841,10 @@ async function locateProject(project, activity, env = process.env) {
37624
37841
  // src/bridge/projects.ts
37625
37842
  init_protocol();
37626
37843
  init_metrics();
37627
- var exec4 = promisify4(execFile5);
37844
+ var exec5 = promisify5(execFile6);
37628
37845
  async function git2(cwd, ...args) {
37629
37846
  countGit("projects");
37630
- return (await exec4("git", ["-C", cwd, "--no-pager", ...args], {
37847
+ return (await exec5("git", ["-C", cwd, "--no-pager", ...args], {
37631
37848
  timeout: 1e4,
37632
37849
  maxBuffer: 4194304,
37633
37850
  env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" })
@@ -37635,7 +37852,7 @@ async function git2(cwd, ...args) {
37635
37852
  }
37636
37853
  async function gitRoot(dir) {
37637
37854
  try {
37638
- return await realpath7((await git2(dir, "rev-parse", "--show-toplevel")).trim());
37855
+ return await realpath8((await git2(dir, "rev-parse", "--show-toplevel")).trim());
37639
37856
  } catch {
37640
37857
  return void 0;
37641
37858
  }
@@ -37670,16 +37887,16 @@ async function committed(root, pathspec) {
37670
37887
  async function resolveTouched(raw, cwd) {
37671
37888
  if (typeof raw !== "string" || !raw || raw.length > 4096 || raw.includes("\0")) return void 0;
37672
37889
  const home = homeDir();
37673
- const absolute = raw === "~" || raw.startsWith("~/") ? path39.join(home, raw.slice(1)) : path39.resolve(cwd, raw);
37890
+ const absolute = raw === "~" || raw.startsWith("~/") ? path40.join(home, raw.slice(1)) : path40.resolve(cwd, raw);
37674
37891
  let existing = absolute, rest = [];
37675
- while (!await stat12(existing).catch(() => void 0)) {
37676
- const parent = path39.dirname(existing);
37892
+ while (!await stat13(existing).catch(() => void 0)) {
37893
+ const parent = path40.dirname(existing);
37677
37894
  if (parent === existing) return void 0;
37678
- rest.unshift(path39.basename(existing));
37895
+ rest.unshift(path40.basename(existing));
37679
37896
  existing = parent;
37680
37897
  }
37681
- const real = path39.join(await realpath7(existing), ...rest);
37682
- return real;
37898
+ const real2 = path40.join(await realpath8(existing), ...rest);
37899
+ return real2;
37683
37900
  }
37684
37901
  async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
37685
37902
  const root = await gitRoot(cwd);
@@ -37688,16 +37905,16 @@ async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
37688
37905
  const requested = [];
37689
37906
  for (const raw of touched.slice(0, 24)) {
37690
37907
  const file2 = await resolveTouched(raw, cwd);
37691
- 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.");
37908
+ 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.");
37692
37909
  requested.push(file2);
37693
37910
  }
37694
37911
  const branch = (await git2(root, "branch", "--show-current")).trim();
37695
37912
  const files = await statusFiles(root);
37696
37913
  const byRoot = /* @__PURE__ */ new Map();
37697
37914
  for (const file2 of requested) {
37698
- const owner = await gitRoot((await stat12(file2).catch(() => void 0))?.isDirectory() ? file2 : path39.dirname(file2));
37915
+ const owner = await gitRoot((await stat13(file2).catch(() => void 0))?.isDirectory() ? file2 : path40.dirname(file2));
37699
37916
  if (!owner) continue;
37700
- const rel = (path39.relative(owner, file2) || ".").split(path39.sep).join("/");
37917
+ const rel = (path40.relative(owner, file2) || ".").split(path40.sep).join("/");
37701
37918
  if (rel.startsWith(":")) throw new BridgeError(400, "Invalid diff pathspec.");
37702
37919
  const list = byRoot.get(owner) ?? [];
37703
37920
  if (!list.includes(rel)) list.push(rel);
@@ -37723,14 +37940,14 @@ async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
37723
37940
  async function headFile(cwd) {
37724
37941
  let directory = cwd;
37725
37942
  for (let depth = 0; depth < 64; depth++) {
37726
- const dotGit = path39.join(directory, ".git");
37727
- const info = await stat12(dotGit).catch(() => void 0);
37728
- if (info?.isDirectory()) return path39.join(dotGit, "HEAD");
37943
+ const dotGit = path40.join(directory, ".git");
37944
+ const info = await stat13(dotGit).catch(() => void 0);
37945
+ if (info?.isDirectory()) return path40.join(dotGit, "HEAD");
37729
37946
  if (info?.isFile()) {
37730
37947
  const match = /^gitdir:\s*(.+)$/m.exec(await readFile16(dotGit, "utf8").catch(() => ""));
37731
- return match ? path39.join(path39.resolve(directory, match[1].trim()), "HEAD") : void 0;
37948
+ return match ? path40.join(path40.resolve(directory, match[1].trim()), "HEAD") : void 0;
37732
37949
  }
37733
- const parent = path39.dirname(directory);
37950
+ const parent = path40.dirname(directory);
37734
37951
  if (parent === directory) return void 0;
37735
37952
  directory = parent;
37736
37953
  }
@@ -37758,7 +37975,7 @@ async function repositoryBranch(cwd) {
37758
37975
  let value2;
37759
37976
  try {
37760
37977
  countGit("branch");
37761
- const { stdout } = await exec4("git", ["-C", cwd, "--no-pager", "branch", "--show-current"], {
37978
+ const { stdout } = await exec5("git", ["-C", cwd, "--no-pager", "branch", "--show-current"], {
37762
37979
  timeout: 5e3,
37763
37980
  maxBuffer: 65536,
37764
37981
  env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" })
@@ -37817,7 +38034,7 @@ function addListener(ports, address, port, processName, pid) {
37817
38034
  ports.set(`${host}:${port}`, { name: "", port, origin: `http://${host}:${port}`, process: processName, pid });
37818
38035
  }
37819
38036
  async function listenersFromLsof(ports) {
37820
- const result = await exec4(
38037
+ const result = await exec5(
37821
38038
  process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof",
37822
38039
  ["-nP", "-a", "-u", userInfo2().username, "-iTCP", "-sTCP:LISTEN", "-Fpcn"],
37823
38040
  { timeout: 4e3, maxBuffer: 1048576 }
@@ -37833,7 +38050,7 @@ async function listenersFromLsof(ports) {
37833
38050
  }
37834
38051
  }
37835
38052
  async function listenersFromSs(ports) {
37836
- const result = await exec4("ss", ["-ltnpH"], { timeout: 4e3, maxBuffer: 1048576 });
38053
+ const result = await exec5("ss", ["-ltnpH"], { timeout: 4e3, maxBuffer: 1048576 });
37837
38054
  for (const line of result.stdout.split("\n")) {
37838
38055
  const columns = line.trim().split(/\s+/);
37839
38056
  if (columns.length < 4) continue;
@@ -37869,24 +38086,24 @@ async function webServers() {
37869
38086
  return found.sort((a, b) => a.port - b.port);
37870
38087
  }
37871
38088
  async function launchDirectory(raw, activity = [], located = []) {
37872
- if (typeof raw !== "string" || raw.length > 4096 || !path39.isAbsolute(raw) || /[\x00-\x1f\x7f]/.test(raw)) throw new BridgeError(400, "Invalid workspace directory.");
38089
+ if (typeof raw !== "string" || raw.length > 4096 || !path40.isAbsolute(raw) || /[\x00-\x1f\x7f]/.test(raw)) throw new BridgeError(400, "Invalid workspace directory.");
37873
38090
  let dir;
37874
38091
  try {
37875
- dir = await realpath7(raw);
37876
- if (!(await stat12(dir)).isDirectory()) throw new Error();
38092
+ dir = await realpath8(raw);
38093
+ if (!(await stat13(dir)).isDirectory()) throw new Error();
37877
38094
  } catch {
37878
38095
  throw new BridgeError(400, "Workspace directory does not exist.");
37879
38096
  }
37880
- const home = await realpath7(homeDir());
37881
- if (dir === home || dir.startsWith(home + path39.sep)) return dir;
38097
+ const home = await realpath8(homeDir());
38098
+ if (dir === home || dir.startsWith(home + path40.sep)) return dir;
37882
38099
  for (const candidate of located) {
37883
- const real = await realpath7(candidate).catch(() => void 0);
37884
- if (real && (dir === real || dir.startsWith(real + path39.sep))) return dir;
38100
+ const real2 = await realpath8(candidate).catch(() => void 0);
38101
+ if (real2 && (dir === real2 || dir.startsWith(real2 + path40.sep))) return dir;
37885
38102
  }
37886
- const names = [...new Set(dir.split(path39.sep).filter((name) => /^[a-z0-9][a-z0-9-]{0,99}$/.test(name)))];
38103
+ const names = [...new Set(dir.split(path40.sep).filter((name) => /^[a-z0-9][a-z0-9-]{0,99}$/.test(name)))];
37887
38104
  for (const name of names) {
37888
38105
  for (const candidate of await locateProject(name, activity)) {
37889
- if (dir === candidate.directory || dir.startsWith(candidate.directory + path39.sep)) return dir;
38106
+ if (dir === candidate.directory || dir.startsWith(candidate.directory + path40.sep)) return dir;
37890
38107
  }
37891
38108
  }
37892
38109
  throw new BridgeError(403, "Workspace directory must be under home or a located project.");
@@ -37900,7 +38117,7 @@ init_shared();
37900
38117
  import { execFileSync as execFileSync3 } from "node:child_process";
37901
38118
  import * as fs20 from "node:fs";
37902
38119
  import { homedir as homedir10 } from "node:os";
37903
- import * as path40 from "node:path";
38120
+ import * as path41 from "node:path";
37904
38121
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
37905
38122
  var CODE_PACKAGE_HINT = "phren code needs @phren/code: run phren modules enable code";
37906
38123
  var loaded;
@@ -37909,13 +38126,13 @@ function loadedFrom() {
37909
38126
  return resolvedFrom;
37910
38127
  }
37911
38128
  function bridgeRoot2() {
37912
- return process.env.PHREN_BRIDGE_HOME || path40.join(homedir10(), ".local/share/phren/bridge");
38129
+ return process.env.PHREN_BRIDGE_HOME || path41.join(homedir10(), ".local/share/phren/bridge");
37913
38130
  }
37914
- var EXTRA_PATH = [path40.join(homedir10(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
38131
+ var EXTRA_PATH = [path41.join(homedir10(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
37915
38132
  function npmPath() {
37916
- const entries2 = (process.env.PATH ?? "").split(path40.delimiter).filter(Boolean);
38133
+ const entries2 = (process.env.PATH ?? "").split(path41.delimiter).filter(Boolean);
37917
38134
  for (const entry of EXTRA_PATH) if (!entries2.includes(entry) && fs20.existsSync(entry)) entries2.push(entry);
37918
- return entries2.join(path40.delimiter);
38135
+ return entries2.join(path41.delimiter);
37919
38136
  }
37920
38137
  function npm(args, options) {
37921
38138
  const env = { ...process.env, PATH: npmPath() };
@@ -37923,11 +38140,11 @@ function npm(args, options) {
37923
38140
  return String(execFileSync3("npm.cmd", args.map((arg) => `"${arg}"`), { ...options, env, shell: true }) ?? "");
37924
38141
  }
37925
38142
  function packageEntry(directory) {
37926
- const manifest = JSON.parse(fs20.readFileSync(path40.join(directory, "package.json"), "utf8"));
38143
+ const manifest = JSON.parse(fs20.readFileSync(path41.join(directory, "package.json"), "utf8"));
37927
38144
  const exported = typeof manifest.exports === "object" && manifest.exports !== null && "." in manifest.exports ? manifest.exports["."] : manifest.exports;
37928
38145
  const nested = typeof exported === "object" && exported !== null ? exported.default ?? exported.import : exported;
37929
38146
  for (const candidate of [nested, manifest.module, manifest.main, "index.js", "index.mjs"]) {
37930
- if (typeof candidate === "string") return path40.join(directory, candidate);
38147
+ if (typeof candidate === "string") return path41.join(directory, candidate);
37931
38148
  }
37932
38149
  throw new Error(`@phren/code has no entry point in ${directory}.`);
37933
38150
  }
@@ -37937,7 +38154,7 @@ async function importDirectory(directory) {
37937
38154
  function globalPackageDirectory() {
37938
38155
  try {
37939
38156
  const root = npm(["root", "-g"], { encoding: "utf8", timeout: 1e4 }).trim();
37940
- return root ? path40.join(root, "@phren", "code") : void 0;
38157
+ return root ? path41.join(root, "@phren", "code") : void 0;
37941
38158
  } catch {
37942
38159
  return void 0;
37943
38160
  }
@@ -37946,11 +38163,11 @@ async function loadCodePackage(store) {
37946
38163
  if (loaded) return loaded;
37947
38164
  const candidates = [];
37948
38165
  if (process.env.PHREN_CODE_PACKAGE) candidates.push(process.env.PHREN_CODE_PACKAGE);
37949
- candidates.push(path40.join(bridgeRoot2(), "node_modules", "@phren", "code"));
38166
+ candidates.push(path41.join(bridgeRoot2(), "node_modules", "@phren", "code"));
37950
38167
  const root = store || process.env.PHREN_PATH;
37951
- if (root) candidates.push(path40.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
38168
+ if (root) candidates.push(path41.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
37952
38169
  for (const directory of candidates) {
37953
- if (!fs20.existsSync(path40.join(directory, "package.json"))) continue;
38170
+ if (!fs20.existsSync(path41.join(directory, "package.json"))) continue;
37954
38171
  try {
37955
38172
  loaded = await importDirectory(directory);
37956
38173
  resolvedFrom = directory;
@@ -37966,7 +38183,7 @@ async function loadCodePackage(store) {
37966
38183
  if (error62.code !== "ERR_MODULE_NOT_FOUND") throw error62;
37967
38184
  }
37968
38185
  const global = globalPackageDirectory();
37969
- if (global && fs20.existsSync(path40.join(global, "package.json"))) {
38186
+ if (global && fs20.existsSync(path41.join(global, "package.json"))) {
37970
38187
  try {
37971
38188
  loaded = await importDirectory(global);
37972
38189
  resolvedFrom = global;
@@ -38007,7 +38224,7 @@ var projectSchema = external_exports.string().min(1).max(100).refine((value2) =>
38007
38224
  var querySchema = external_exports.string().max(500);
38008
38225
  var symbolSchema = external_exports.string().min(1).max(4600);
38009
38226
  var pathSchema = external_exports.string().min(1).max(4096).refine((value2) => !value2.includes("\0") && !value2.split("/").includes(".."), "Choose a valid file path.");
38010
- var relativePathSchema = pathSchema.refine((value2) => !path41.isAbsolute(value2) && !path41.win32.isAbsolute(value2) && !value2.includes("\\") && !value2.split("/").some((part) => part === "." || part === ""));
38227
+ var relativePathSchema = pathSchema.refine((value2) => !path42.isAbsolute(value2) && !path42.win32.isAbsolute(value2) && !value2.includes("\\") && !value2.split("/").some((part) => part === "." || part === ""));
38011
38228
  var optionalPath = (value2) => value2 ? relativePathSchema.parse(value2) : void 0;
38012
38229
  var offsetSchema = external_exports.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
38013
38230
  var kindSchema = external_exports.enum(KIND_VALUES);
@@ -38095,9 +38312,9 @@ var CodeRoutes = class {
38095
38312
  };
38096
38313
  const midnight = new Date(now);
38097
38314
  midnight.setHours(0, 0, 0, 0);
38098
- const dir = path41.join(bridgeRoot(), "changes");
38315
+ const dir = path42.join(bridgeRoot(), "changes");
38099
38316
  const logs = fs21.existsSync(dir) ? fs21.readdirSync(dir).filter((name) => name.endsWith(".jsonl")) : [];
38100
- 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);
38317
+ 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);
38101
38318
  for (const log2 of today) {
38102
38319
  for (const line of fs21.readFileSync(log2.file, "utf8").split("\n")) {
38103
38320
  if (!line.trim()) continue;
@@ -38158,7 +38375,7 @@ var CodeRoutes = class {
38158
38375
  for (const file2 of untracked) {
38159
38376
  let count2 = 0;
38160
38377
  try {
38161
- count2 = fs21.readFileSync(path41.join(root, file2), "utf8").split("\n").length;
38378
+ count2 = fs21.readFileSync(path42.join(root, file2), "utf8").split("\n").length;
38162
38379
  } catch {
38163
38380
  continue;
38164
38381
  }
@@ -38188,7 +38405,7 @@ var CodeRoutes = class {
38188
38405
  const project = projectSchema.parse(projectValue ?? "");
38189
38406
  const { codeDatabasePath } = await requireCodePackage(this.store);
38190
38407
  const file2 = codeDatabasePath(this.store, project);
38191
- await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path84) => rm4(path84, { force: true })));
38408
+ await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path86) => rm4(path86, { force: true })));
38192
38409
  return { project, disabled: true };
38193
38410
  }
38194
38411
  async reindex(projectValue) {
@@ -38222,7 +38439,7 @@ var CodeRoutes = class {
38222
38439
  } catch {
38223
38440
  throw new BridgeError(400, "Choose valid paths.");
38224
38441
  }
38225
- const paths = external_exports.array(pathSchema.refine((value2) => !path41.isAbsolute(value2) && !path41.win32.isAbsolute(value2) && !value2.split(/[\\/]/).includes(".."))).min(1).max(200).parse(raw);
38442
+ const paths = external_exports.array(pathSchema.refine((value2) => !path42.isAbsolute(value2) && !path42.win32.isAbsolute(value2) && !value2.split(/[\\/]/).includes(".."))).min(1).max(200).parse(raw);
38226
38443
  const result = await (await requireCodePackage(this.store)).outlineSummary(this.store, project, [...new Set(paths)]);
38227
38444
  if (!result.available) throw noIndex(project);
38228
38445
  return { project, entries: result.value };
@@ -38297,7 +38514,7 @@ var CodeReindexer = class {
38297
38514
  const { codeDatabasePath, resolveRepoRoot } = await requireCodePackage(this.store);
38298
38515
  const result = [];
38299
38516
  for (const directory of getProjectDirs(this.store)) {
38300
- const project = path41.basename(directory);
38517
+ const project = path42.basename(directory);
38301
38518
  if (!fs21.existsSync(codeDatabasePath(this.store, project))) continue;
38302
38519
  try {
38303
38520
  result.push({ project, root: fs21.realpathSync(resolveRepoRoot(this.store, project)) });
@@ -38339,13 +38556,13 @@ var CodeReindexer = class {
38339
38556
  };
38340
38557
  function readHead(root) {
38341
38558
  try {
38342
- const dotGit = path41.join(root, ".git");
38559
+ const dotGit = path42.join(root, ".git");
38343
38560
  const gitDirectory2 = fs21.statSync(dotGit).isDirectory() ? dotGit : (() => {
38344
38561
  const match = /^gitdir:\s*(.+)$/m.exec(fs21.readFileSync(dotGit, "utf8"));
38345
- return match ? path41.resolve(root, match[1]) : void 0;
38562
+ return match ? path42.resolve(root, match[1]) : void 0;
38346
38563
  })();
38347
38564
  if (!gitDirectory2) return void 0;
38348
- return fs21.readFileSync(path41.join(gitDirectory2, "HEAD"), "utf8").trim();
38565
+ return fs21.readFileSync(path42.join(gitDirectory2, "HEAD"), "utf8").trim();
38349
38566
  } catch {
38350
38567
  return void 0;
38351
38568
  }
@@ -38355,7 +38572,7 @@ function readHead(root) {
38355
38572
  init_herdr();
38356
38573
  init_protocol();
38357
38574
  init_transcripts();
38358
- import { open as open7 } from "node:fs/promises";
38575
+ import { open as open8 } from "node:fs/promises";
38359
38576
  import { constants as constants2 } from "node:fs";
38360
38577
  var MAX_TAIL_BYTES = 262144;
38361
38578
  var MAX_SESSIONS = 32;
@@ -38388,15 +38605,15 @@ function codexContext(tail, startsAtBeginning) {
38388
38605
  var ContextUsageReader = class {
38389
38606
  cache = /* @__PURE__ */ new Map();
38390
38607
  async read(file2, session) {
38391
- const handle = await open7(file2, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
38608
+ const handle = await open8(file2, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
38392
38609
  try {
38393
38610
  const metadata = await handle.stat();
38394
38611
  if (!metadata.isFile()) return void 0;
38395
38612
  const key2 = `codex:${session}:${file2}`;
38396
- const stat26 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
38613
+ const stat27 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
38397
38614
  const cached2 = this.cache.get(key2);
38398
38615
  this.cache.delete(key2);
38399
- if (cached2?.stat === stat26) {
38616
+ if (cached2?.stat === stat27) {
38400
38617
  this.cache.set(key2, cached2);
38401
38618
  return cached2.percent;
38402
38619
  }
@@ -38407,7 +38624,7 @@ var ContextUsageReader = class {
38407
38624
  const after = await handle.stat();
38408
38625
  if (after.size !== metadata.size || after.mtimeMs !== metadata.mtimeMs || after.ctimeMs !== metadata.ctimeMs) return void 0;
38409
38626
  const percent = codexContext(tail, start === 0);
38410
- this.cache.set(key2, { stat: stat26, percent });
38627
+ this.cache.set(key2, { stat: stat27, percent });
38411
38628
  while (this.cache.size > MAX_SESSIONS) this.cache.delete(this.cache.keys().next().value);
38412
38629
  return percent;
38413
38630
  } finally {
@@ -38484,33 +38701,76 @@ init_zod();
38484
38701
  init_logger();
38485
38702
  init_project_config();
38486
38703
  import { randomUUID as randomUUID9 } from "node:crypto";
38487
- import { lstat as lstat12, mkdir as mkdir12, readFile as readFile21, readdir as readdir9, realpath as realpath9, stat as stat14 } from "node:fs/promises";
38488
- import path49 from "node:path";
38704
+ import { lstat as lstat12, mkdir as mkdir12, readFile as readFile21, readdir as readdir10, realpath as realpath10, stat as stat15 } from "node:fs/promises";
38705
+ import path51 from "node:path";
38489
38706
 
38490
38707
  // src/bridge/computers.ts
38491
- import { execFile as execFile8 } from "node:child_process";
38708
+ import { execFile as execFile9 } from "node:child_process";
38492
38709
  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";
38493
38710
  import { homedir as homedir14 } from "node:os";
38494
- import path47 from "node:path";
38495
- import { promisify as promisify7 } from "node:util";
38711
+ import path49 from "node:path";
38712
+ import { promisify as promisify8 } from "node:util";
38496
38713
 
38497
38714
  // src/bridge/install.ts
38498
38715
  init_shared();
38499
- import { execFile as execFile7 } from "node:child_process";
38716
+ import { execFile as execFile8 } from "node:child_process";
38500
38717
 
38501
38718
  // src/bridge/usage.ts
38502
38719
  init_home_paths();
38503
38720
  init_fanouts();
38504
38721
  init_protocol();
38505
38722
  init_terminal_text();
38506
- import { execFile as execFile6, spawn as spawn2 } from "node:child_process";
38723
+ import { execFile as execFile7, spawn as spawn2 } from "node:child_process";
38507
38724
  import { createHash as createHash9 } from "node:crypto";
38508
- import { lstat as lstat8, open as open8, readFile as readFile17, readdir as readdir8, realpath as realpath8, stat as stat13 } from "node:fs/promises";
38725
+ import { lstat as lstat8, open as open9, readFile as readFile17, readdir as readdir9, realpath as realpath9, stat as stat14 } from "node:fs/promises";
38509
38726
  import { homedir as homedir11 } from "node:os";
38510
- import path43 from "node:path";
38511
- import { promisify as promisify5 } from "node:util";
38512
- var exec5 = promisify5(execFile6);
38513
- var claudeFile = () => path43.join(bridgeRoot(), "usage", "claude.json");
38727
+ import path45 from "node:path";
38728
+ import { promisify as promisify6 } from "node:util";
38729
+
38730
+ // src/bridge/codex-binary.ts
38731
+ import { accessSync as accessSync2, closeSync as closeSync2, constants as constants3, openSync as openSync2, readSync, statSync as statSync12 } from "node:fs";
38732
+ import path44 from "node:path";
38733
+ function codexExecutable(env = process.env) {
38734
+ if (process.platform === "win32") return "codex";
38735
+ for (const directory of (env.PATH ?? "").split(path44.delimiter)) {
38736
+ if (!path44.isAbsolute(directory)) continue;
38737
+ const candidate = path44.join(directory, "codex");
38738
+ if (!executable(candidate)) continue;
38739
+ const wrapped = phrenWrapperTarget(candidate);
38740
+ if (wrapped === void 0) return candidate;
38741
+ if (wrapped && executable(wrapped)) return wrapped;
38742
+ }
38743
+ return "codex";
38744
+ }
38745
+ function executable(file2) {
38746
+ try {
38747
+ return statSync12(file2).isFile() && (accessSync2(file2, constants3.X_OK), true);
38748
+ } catch {
38749
+ return false;
38750
+ }
38751
+ }
38752
+ function phrenWrapperTarget(file2) {
38753
+ let head = "";
38754
+ try {
38755
+ const fd = openSync2(file2, "r");
38756
+ try {
38757
+ const buffer = Buffer.alloc(4096);
38758
+ head = buffer.subarray(0, readSync(fd, buffer, 0, buffer.length, 0)).toString("utf8");
38759
+ } finally {
38760
+ closeSync2(fd);
38761
+ }
38762
+ } catch {
38763
+ return void 0;
38764
+ }
38765
+ if (!head.startsWith("#!/bin/sh") || !head.includes("phren wrapper error:")) return void 0;
38766
+ const match = /^REAL_BIN='((?:[^']|'\\'')*)'$/m.exec(head);
38767
+ const target = match?.[1].replace(/'\\''/g, "'");
38768
+ return target && path44.isAbsolute(target) ? target : "";
38769
+ }
38770
+
38771
+ // src/bridge/usage.ts
38772
+ var exec6 = promisify6(execFile7);
38773
+ var claudeFile = () => path45.join(bridgeRoot(), "usage", "claude.json");
38514
38774
  var safeText = (v) => typeof v === "string" ? v.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 100) : void 0;
38515
38775
  function window(id2, name, percent, reset) {
38516
38776
  if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100) return;
@@ -38551,9 +38811,9 @@ function openCodeUsage(output2, now = /* @__PURE__ */ new Date()) {
38551
38811
  }
38552
38812
  return { source: "opencode", windows: [], spend: { amountUSD, period: "rolling_7_days" }, updatedAt: now.toISOString() };
38553
38813
  }
38554
- async function readOpenCodeUsage(executable = "opencode", now = /* @__PURE__ */ new Date()) {
38814
+ async function readOpenCodeUsage(executable2 = "opencode", now = /* @__PURE__ */ new Date()) {
38555
38815
  try {
38556
- const { stdout } = await exec5(executable, ["stats", "--days", "7", "--pure"], { timeout: 12e3, maxBuffer: 1048576 });
38816
+ const { stdout } = await exec6(executable2, ["stats", "--days", "7", "--pure"], { timeout: 12e3, maxBuffer: 1048576 });
38557
38817
  return openCodeUsage(stdout, now);
38558
38818
  } catch (error62) {
38559
38819
  return { source: "opencode", windows: [], message: openCodeFailure(error62) };
@@ -38569,16 +38829,16 @@ function openCodeFailure(error62) {
38569
38829
  const exit = typeof failure2?.code === "number" ? ` (exit ${failure2.code})` : "";
38570
38830
  return `opencode stats --days 7 failed${exit}${said ? `: ${said}` : ""}. Run it on this computer to see why.`;
38571
38831
  }
38572
- var openCodeAuthFile = () => path43.join(
38573
- process.env.OPENCODE_DATA_DIR || path43.join(process.env.XDG_DATA_HOME || path43.join(homedir11(), ".local", "share"), "opencode"),
38832
+ var openCodeAuthFile = () => path45.join(
38833
+ process.env.OPENCODE_DATA_DIR || path45.join(process.env.XDG_DATA_HOME || path45.join(homedir11(), ".local", "share"), "opencode"),
38574
38834
  "auth.json"
38575
38835
  );
38576
38836
  async function readOpenRouterKey() {
38577
38837
  try {
38578
- const handle = await open8(openCodeAuthFile(), "r");
38838
+ const handle = await open9(openCodeAuthFile(), "r");
38579
38839
  try {
38580
- const stat26 = await handle.stat();
38581
- if (!stat26.isFile() || stat26.size > 65536) return void 0;
38840
+ const stat27 = await handle.stat();
38841
+ if (!stat27.isFile() || stat27.size > 65536) return void 0;
38582
38842
  const key2 = object2(object2(JSON.parse(await handle.readFile("utf8"))).openrouter).key;
38583
38843
  return typeof key2 === "string" && key2.length >= 16 && key2.length <= 4096 && !/[\x00-\x1f\x7f]/.test(key2) ? key2 : void 0;
38584
38844
  } finally {
@@ -38590,7 +38850,7 @@ async function readOpenRouterKey() {
38590
38850
  }
38591
38851
  async function readOpenCodeGoKey() {
38592
38852
  try {
38593
- const handle = await open8(openCodeAuthFile(), "r");
38853
+ const handle = await open9(openCodeAuthFile(), "r");
38594
38854
  try {
38595
38855
  const metadata = await handle.stat();
38596
38856
  if (!metadata.isFile() || metadata.size > 65536) return void 0;
@@ -38763,9 +39023,9 @@ async function containedRegularFile(root, candidate, maximum) {
38763
39023
  try {
38764
39024
  const link = await lstat8(candidate);
38765
39025
  if (!link.isFile() || link.isSymbolicLink() || link.size > maximum) return void 0;
38766
- const resolved = await realpath8(candidate);
38767
- if (!resolved.startsWith(root + path43.sep)) return void 0;
38768
- const metadata = await stat13(resolved);
39026
+ const resolved = await realpath9(candidate);
39027
+ if (!resolved.startsWith(root + path45.sep)) return void 0;
39028
+ const metadata = await stat14(resolved);
38769
39029
  return metadata.isFile() && metadata.size <= maximum ? resolved : void 0;
38770
39030
  } catch {
38771
39031
  return void 0;
@@ -38795,14 +39055,14 @@ async function readOpenCodeGoLedger(root = fanoutRoot(), now = /* @__PURE__ */ n
38795
39055
  const totals = /* @__PURE__ */ new Map();
38796
39056
  let directory;
38797
39057
  try {
38798
- directory = await realpath8(root);
39058
+ directory = await realpath9(root);
38799
39059
  } catch {
38800
39060
  return totals;
38801
39061
  }
38802
- const names = (await readdir8(directory).catch(() => [])).slice(0, MAX_GO_JOBS);
39062
+ const names = (await readdir9(directory).catch(() => [])).slice(0, MAX_GO_JOBS);
38803
39063
  for (const name of names) {
38804
39064
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name)) continue;
38805
- const manifestFile = await containedRegularFile(directory, path43.join(directory, name, "manifest.json"), MAX_GO_MANIFEST_BYTES);
39065
+ const manifestFile = await containedRegularFile(directory, path45.join(directory, name, "manifest.json"), MAX_GO_MANIFEST_BYTES);
38806
39066
  if (!manifestFile) continue;
38807
39067
  let manifest;
38808
39068
  try {
@@ -38813,9 +39073,9 @@ async function readOpenCodeGoLedger(root = fanoutRoot(), now = /* @__PURE__ */ n
38813
39073
  const model = goModel(manifest.model);
38814
39074
  const eventLog = typeof manifest.eventLog === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jsonl$/.test(manifest.eventLog) ? manifest.eventLog : void 0;
38815
39075
  if (manifest.provider !== "opencode" || !model || !eventLog) continue;
38816
- const jobRoot = await realpath8(path43.join(directory, name)).catch(() => void 0);
38817
- if (!jobRoot || !jobRoot.startsWith(directory + path43.sep)) continue;
38818
- const eventsFile = await containedRegularFile(jobRoot, path43.join(jobRoot, eventLog), MAX_GO_EVENTS_BYTES);
39076
+ const jobRoot = await realpath9(path45.join(directory, name)).catch(() => void 0);
39077
+ if (!jobRoot || !jobRoot.startsWith(directory + path45.sep)) continue;
39078
+ const eventsFile = await containedRegularFile(jobRoot, path45.join(jobRoot, eventLog), MAX_GO_EVENTS_BYTES);
38819
39079
  if (!eventsFile) continue;
38820
39080
  let events;
38821
39081
  try {
@@ -38992,8 +39252,8 @@ function claudeScopedWindows(config3, now = /* @__PURE__ */ new Date()) {
38992
39252
  }
38993
39253
  return windows;
38994
39254
  }
38995
- var claudeConfigFile = () => path43.join(process.env.CLAUDE_CONFIG_DIR?.trim() ? claudeConfigDir() : homeDir(), ".claude.json");
38996
- var claudeCredentialsFile = () => path43.join(claudeConfigDir(), ".credentials.json");
39255
+ var claudeConfigFile = () => path45.join(process.env.CLAUDE_CONFIG_DIR?.trim() ? claudeConfigDir() : homeDir(), ".claude.json");
39256
+ var claudeCredentialsFile = () => path45.join(claudeConfigDir(), ".credentials.json");
38997
39257
  function claudeOAuthUsage(value2, now = /* @__PURE__ */ new Date()) {
38998
39258
  const limits = object2(value2).limits;
38999
39259
  const windows = [];
@@ -39024,7 +39284,7 @@ function claudeOAuthUsage(value2, now = /* @__PURE__ */ new Date()) {
39024
39284
  ...!windows.length ? { message: "Claude has not reported account limits on this computer." } : {}
39025
39285
  };
39026
39286
  }
39027
- async function readClaudeToken(execSecurity = exec5, platform = process.platform) {
39287
+ async function readClaudeToken(execSecurity = exec6, platform = process.platform) {
39028
39288
  const parse4 = (raw) => {
39029
39289
  if (raw.length > 16384) return void 0;
39030
39290
  const oauth = object2(object2(JSON.parse(raw)).claudeAiOauth);
@@ -39072,9 +39332,9 @@ async function liveClaudeUsage(now) {
39072
39332
  return void 0;
39073
39333
  }
39074
39334
  }
39075
- function readCodexLimits(executable = "codex") {
39335
+ function readCodexLimits(executable2 = codexExecutable()) {
39076
39336
  return new Promise((resolve11) => {
39077
- const child = spawn2(executable, ["app-server"], { cwd: homedir11(), stdio: ["pipe", "pipe", "ignore"] });
39337
+ const child = spawn2(executable2, ["app-server"], { cwd: homedir11(), stdio: ["pipe", "pipe", "ignore"] });
39078
39338
  let pending = "", bytes = 0, initialized = false, done = false;
39079
39339
  const finish = (result) => {
39080
39340
  if (done) return;
@@ -39200,10 +39460,10 @@ var AccountUsageReader = class {
39200
39460
  async snapshotClaude() {
39201
39461
  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." };
39202
39462
  try {
39203
- const handle = await open8(claudeFile(), "r");
39463
+ const handle = await open9(claudeFile(), "r");
39204
39464
  try {
39205
- const stat26 = await handle.stat();
39206
- if (!stat26.isFile() || stat26.size > 16384) throw new Error("Invalid usage snapshot");
39465
+ const stat27 = await handle.stat();
39466
+ if (!stat27.isFile() || stat27.size > 16384) throw new Error("Invalid usage snapshot");
39207
39467
  const saved = object2(JSON.parse(await handle.readFile("utf8")));
39208
39468
  const date5 = new Date(String(saved.updatedAt));
39209
39469
  if (!Number.isFinite(date5.getTime()) || date5.getTime() > this.now() + 6e4) throw new Error("Invalid usage timestamp");
@@ -39214,10 +39474,10 @@ var AccountUsageReader = class {
39214
39474
  } catch {
39215
39475
  }
39216
39476
  try {
39217
- const handle = await open8(claudeConfigFile(), "r");
39477
+ const handle = await open9(claudeConfigFile(), "r");
39218
39478
  try {
39219
- const stat26 = await handle.stat();
39220
- if (!stat26.isFile() || stat26.size > 16777216) throw new Error("Invalid Claude config");
39479
+ const stat27 = await handle.stat();
39480
+ if (!stat27.isFile() || stat27.size > 16777216) throw new Error("Invalid Claude config");
39221
39481
  const scoped = claudeScopedWindows(JSON.parse(await handle.readFile("utf8")), new Date(this.now())).filter((entry) => !claude2.windows.some((existing) => existing.id === entry.id));
39222
39482
  if (scoped.length) claude2 = { ...claude2, windows: [...claude2.windows, ...scoped], message: void 0 };
39223
39483
  } finally {
@@ -39277,11 +39537,11 @@ async function captureClaudeUsage(original) {
39277
39537
  init_home_paths();
39278
39538
  init_protocol();
39279
39539
  init_herdr();
39280
- 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";
39540
+ 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";
39281
39541
  import { homedir as homedir13 } from "node:os";
39282
- import path46 from "node:path";
39542
+ import path48 from "node:path";
39283
39543
  import { fileURLToPath as fileURLToPath5 } from "node:url";
39284
- import { promisify as promisify6 } from "node:util";
39544
+ import { promisify as promisify7 } from "node:util";
39285
39545
 
39286
39546
  // src/bridge/transport.ts
39287
39547
  init_shared();
@@ -39292,17 +39552,17 @@ import { connect as connect3 } from "node:net";
39292
39552
  import { request as request3 } from "node:http";
39293
39553
  import { spawn as spawn3 } from "node:child_process";
39294
39554
  import { homedir as homedir12 } from "node:os";
39295
- import path44 from "node:path";
39555
+ import path46 from "node:path";
39296
39556
  function decodeShellDirectory(encoded) {
39297
39557
  if (!/^[A-Za-z0-9_-]{1,8192}$/.test(encoded)) return void 0;
39298
39558
  const decoded = Buffer.from(encoded, "base64url");
39299
39559
  if (decoded.toString("base64url") !== encoded) return void 0;
39300
39560
  const dir = decoded.toString("utf8");
39301
- return path44.isAbsolute(dir) && !/[\x00-\x1f\x7f]/.test(dir) && !dir.includes("\uFFFD") ? dir : void 0;
39561
+ return path46.isAbsolute(dir) && !/[\x00-\x1f\x7f]/.test(dir) && !dir.includes("\uFFFD") ? dir : void 0;
39302
39562
  }
39303
39563
  function shellEnvironment(base = process.env) {
39304
39564
  const env = Object.fromEntries(Object.entries(base).filter(([key2]) => !key2.startsWith("HERDR_") && key2 !== "TMUX" && key2 !== "TMUX_PANE"));
39305
- env.PATH = [path44.join(homedir12(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":");
39565
+ env.PATH = [path46.join(homedir12(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":");
39306
39566
  return env;
39307
39567
  }
39308
39568
  async function health() {
@@ -39363,7 +39623,7 @@ async function dispatch(command) {
39363
39623
  };
39364
39624
  if (command === "phren-hook v1 pipe") {
39365
39625
  requireHook();
39366
- await pipe2({ path: socketPath() }, path44.join(bridgeRoot(), "gateway.json"), true);
39626
+ await pipe2({ path: socketPath() }, path46.join(bridgeRoot(), "gateway.json"), true);
39367
39627
  return;
39368
39628
  }
39369
39629
  const preview = /^phren-hook v1 web (127\.0\.0\.1|::1) ([1-9][0-9]{0,4})$/.exec(command);
@@ -39379,7 +39639,7 @@ async function dispatch(command) {
39379
39639
  if (!raw) throw new BridgeError(403, "The shell folder is not a valid absolute path.");
39380
39640
  const cwd = await launchDirectory(raw);
39381
39641
  if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("Request an SSH terminal first.");
39382
- const login = process.env.SHELL && path44.isAbsolute(process.env.SHELL) ? process.env.SHELL : "/bin/sh";
39642
+ const login = process.env.SHELL && path46.isAbsolute(process.env.SHELL) ? process.env.SHELL : "/bin/sh";
39383
39643
  const [file2, args] = shell[2] ? [shell[2], []] : [login, ["-l"]];
39384
39644
  await attach(file2, args, { cwd, env: shellEnvironment() }, shell[2] ? `${shell[2]} exited.` : "The shell exited.");
39385
39645
  return;
@@ -39413,7 +39673,7 @@ async function attach(file2, args, options, failure2) {
39413
39673
  }
39414
39674
 
39415
39675
  // src/bridge/install.ts
39416
- var exec6 = promisify6(execFile7);
39676
+ var exec7 = promisify7(execFile8);
39417
39677
  var label = "com.phren.hook";
39418
39678
  var unit = "phren-hook.service";
39419
39679
  var forcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch"';
@@ -39458,7 +39718,7 @@ var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&
39458
39718
  var systemdQuote = (s) => '"' + s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%") + '"';
39459
39719
  async function commandOutput(file2, args, env) {
39460
39720
  try {
39461
- const { stdout, stderr } = await exec6(file2, args, { env, timeout: 2e3 });
39721
+ const { stdout, stderr } = await exec7(file2, args, { env, timeout: 2e3 });
39462
39722
  return stdout + stderr || void 0;
39463
39723
  } catch (error62) {
39464
39724
  const value2 = error62;
@@ -39491,9 +39751,9 @@ ${pipe3}exec ${quote2(node2)} ${quote2(bundle)} ssh
39491
39751
  }
39492
39752
  async function activate(version3) {
39493
39753
  const root = bridgeRoot();
39494
- const next = path46.join(root, `current-${process.pid}`);
39495
- await symlink(path46.join("versions", version3), next);
39496
- await rename5(next, path46.join(root, "current"));
39754
+ const next = path48.join(root, `current-${process.pid}`);
39755
+ await symlink(path48.join("versions", version3), next);
39756
+ await rename5(next, path48.join(root, "current"));
39497
39757
  }
39498
39758
  function launchDomain(uid, guiSession2) {
39499
39759
  return guiSession2 ? `gui/${uid}` : `user/${uid}`;
@@ -39501,15 +39761,15 @@ function launchDomain(uid, guiSession2) {
39501
39761
  function launchCommands(domain2, plist) {
39502
39762
  return [`launchctl bootout ${domain2}/${label}`, `launchctl bootstrap ${domain2} ${quote2(plist)}`, `launchctl kickstart -k ${domain2}/${label}`];
39503
39763
  }
39504
- var launchAgentPlist = () => path46.join(homedir13(), "Library/LaunchAgents", `${label}.plist`);
39764
+ var launchAgentPlist = () => path48.join(homedir13(), "Library/LaunchAgents", `${label}.plist`);
39505
39765
  async function guiSession(uid) {
39506
- return exec6("launchctl", ["print", `gui/${uid}`]).then(() => true, () => false);
39766
+ return exec7("launchctl", ["print", `gui/${uid}`]).then(() => true, () => false);
39507
39767
  }
39508
39768
  async function stopService() {
39509
39769
  if (process.platform === "darwin") {
39510
- for (const gui of [true, false]) await exec6("launchctl", ["bootout", `${launchDomain(process.getuid(), gui)}/${label}`]).catch(() => {
39770
+ for (const gui of [true, false]) await exec7("launchctl", ["bootout", `${launchDomain(process.getuid(), gui)}/${label}`]).catch(() => {
39511
39771
  });
39512
- } else await exec6("systemctl", ["--user", "stop", unit]).catch(() => {
39772
+ } else await exec7("systemctl", ["--user", "stop", unit]).catch(() => {
39513
39773
  });
39514
39774
  }
39515
39775
  async function startService() {
@@ -39517,7 +39777,7 @@ async function startService() {
39517
39777
  const uid = process.getuid(), gui = await guiSession(uid), domain2 = launchDomain(uid, gui);
39518
39778
  for (let attempt = 0; ; attempt++) {
39519
39779
  try {
39520
- await exec6("launchctl", ["bootstrap", domain2, launchAgentPlist()]);
39780
+ await exec7("launchctl", ["bootstrap", domain2, launchAgentPlist()]);
39521
39781
  break;
39522
39782
  } catch (error62) {
39523
39783
  const stderr = String(error62.stderr ?? "");
@@ -39530,12 +39790,12 @@ To start it by hand:
39530
39790
  ${launchCommands(domain2, launchAgentPlist()).join("\n ")}`);
39531
39791
  }
39532
39792
  }
39533
- await exec6("launchctl", ["kickstart", `${domain2}/${label}`]).catch(() => {
39793
+ await exec7("launchctl", ["kickstart", `${domain2}/${label}`]).catch(() => {
39534
39794
  });
39535
39795
  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}.`);
39536
39796
  } else {
39537
- await exec6("systemctl", ["--user", "daemon-reload"]);
39538
- await exec6("systemctl", ["--user", "enable", "--now", unit]);
39797
+ await exec7("systemctl", ["--user", "daemon-reload"]);
39798
+ await exec7("systemctl", ["--user", "enable", "--now", unit]);
39539
39799
  }
39540
39800
  }
39541
39801
  async function install(version3, noService = false) {
@@ -39543,52 +39803,52 @@ async function install(version3, noService = false) {
39543
39803
  if (!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version3)) throw new Error("Invalid helper version.");
39544
39804
  const modules = activateModules(defaultPhrenPath(), void 0, true);
39545
39805
  if (!modules.has("hook")) throw new Error(disabledHint("hook"));
39546
- const root = bridgeRoot(), herdr = herdrRoot(), versions = path46.join(root, "versions");
39806
+ const root = bridgeRoot(), herdr = herdrRoot(), versions = path48.join(root, "versions");
39547
39807
  await mkdir10(versions, { recursive: true, mode: 448 });
39548
39808
  await chmod2(root, 448);
39549
- const serviceLog = path46.join(root, "service.log");
39550
- const log2 = await open9(serviceLog, "a", 384);
39809
+ const serviceLog = path48.join(root, "service.log");
39810
+ const log2 = await open10(serviceLog, "a", 384);
39551
39811
  try {
39552
39812
  await log2.chmod(384);
39553
39813
  } finally {
39554
39814
  await log2.close();
39555
39815
  }
39556
- const hookEdits = await planAgentHooks(path46.join(root, "current/bridge-hook.mjs"), false, modules);
39816
+ const hookEdits = await planAgentHooks(path48.join(root, "current/bridge-hook.mjs"), false, modules);
39557
39817
  const own2 = fileURLToPath5(import.meta.url);
39558
- const bundle = own2.endsWith("bridge-hook.mjs") ? own2 : path46.join(path46.dirname(own2), "..", "bridge-hook.mjs");
39559
- const destination2 = path46.join(versions, version3);
39818
+ const bundle = own2.endsWith("bridge-hook.mjs") ? own2 : path48.join(path48.dirname(own2), "..", "bridge-hook.mjs");
39819
+ const destination2 = path48.join(versions, version3);
39560
39820
  await mkdir10(destination2, { recursive: true, mode: 448 });
39561
- const installedBundle = path46.join(destination2, "bridge-hook.mjs");
39821
+ const installedBundle = path48.join(destination2, "bridge-hook.mjs");
39562
39822
  const previousBundle = await missingFile(readFile18(installedBundle));
39563
39823
  const stagedBundle = installedBundle + `.phren-${process.pid}`;
39564
39824
  await copyFile2(bundle, stagedBundle);
39565
39825
  await rename5(stagedBundle, installedBundle);
39566
- const previous = await readFile18(path46.join(root, "installed.json"), "utf8").then((v) => JSON.parse(v)).catch(() => null);
39826
+ const previous = await readFile18(path48.join(root, "installed.json"), "utf8").then((v) => JSON.parse(v)).catch(() => null);
39567
39827
  const gateway = await detectGateway();
39568
- await atomic(path46.join(root, "dispatch"), gatewayScript(gateway, {
39828
+ await atomic(path48.join(root, "dispatch"), gatewayScript(gateway, {
39569
39829
  root,
39570
39830
  herdr,
39571
39831
  store: modules.store,
39572
39832
  profile: modules.profile,
39573
39833
  node: process.execPath,
39574
- bundle: path46.join(root, "current/bridge-hook.mjs"),
39834
+ bundle: path48.join(root, "current/bridge-hook.mjs"),
39575
39835
  socket: socketPath(),
39576
- timing: path46.join(root, "gateway.json")
39836
+ timing: path48.join(root, "gateway.json")
39577
39837
  }), 448);
39578
- const environmentPath = [path46.dirname(process.execPath), path46.join(homedir13(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"].join(":");
39579
- const program = path46.join(root, "current/bridge-hook.mjs");
39838
+ const environmentPath = [path48.dirname(process.execPath), path48.join(homedir13(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"].join(":");
39839
+ const program = path48.join(root, "current/bridge-hook.mjs");
39580
39840
  if (!noService) {
39581
39841
  if (process.platform === "darwin") {
39582
- const folder = path46.join(homedir13(), "Library/LaunchAgents");
39842
+ const folder = path48.join(homedir13(), "Library/LaunchAgents");
39583
39843
  await mkdir10(folder, { recursive: true });
39584
- await atomic(path46.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>
39844
+ await atomic(path48.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>
39585
39845
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
39586
- <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>
39846
+ <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(path48.join(root, "service.log"))}</string></dict></plist>
39587
39847
  `);
39588
39848
  } else {
39589
- const folder = path46.join(homedir13(), ".config/systemd/user");
39849
+ const folder = path48.join(homedir13(), ".config/systemd/user");
39590
39850
  await mkdir10(folder, { recursive: true });
39591
- await atomic(path46.join(folder, unit), `[Unit]
39851
+ await atomic(path48.join(folder, unit), `[Unit]
39592
39852
  Description=Phren Hook
39593
39853
  [Service]
39594
39854
  ExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve
@@ -39630,7 +39890,7 @@ WantedBy=default.target
39630
39890
  if ((await Promise.resolve().then(() => (init_agent_package(), agent_package_exports))).agentInstalled()) {
39631
39891
  console.log("phren-agent chat: found; it reports to this Hook itself, so restart any phren-agent session started before now.");
39632
39892
  }
39633
- const keys = path46.join(homedir13(), ".ssh/authorized_keys");
39893
+ const keys = path48.join(homedir13(), ".ssh/authorized_keys");
39634
39894
  const keyStat = await lstat9(keys).catch(() => null);
39635
39895
  if (keyStat && !keyStat.isSymbolicLink() && keyStat.isFile()) {
39636
39896
  const before = await readFile18(keys, "utf8"), after = upgradeKeys(before);
@@ -39641,7 +39901,7 @@ WantedBy=default.target
39641
39901
  }
39642
39902
  console.log(`Updated ${after.changed} Phren iPhone key(s); other keys were preserved.`);
39643
39903
  }
39644
- 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");
39904
+ await atomic(path48.join(root, "installed.json"), JSON.stringify({ version: version3, previous: previous?.version === version3 ? previous.previous : previous?.version, node: process.execPath, gateway }, null, 2) + "\n");
39645
39905
  console.log("Agent hooks installed. In Codex, review the new Phren entries in /hooks. Existing agents may need to resume before new hooks load.");
39646
39906
  console.log(`SSH gateway: ${gateway}${gateway === "node" ? " (no socat or nc -U found)" : ""}.`);
39647
39907
  console.log(`Phren Hook ${version3} installed${noService ? " (service not started)" : " and running"}. Run phren bridge doctor.`);
@@ -39664,14 +39924,14 @@ async function uninstall() {
39664
39924
  if (process.platform === "darwin") await unlink4(launchAgentPlist()).catch(() => {
39665
39925
  });
39666
39926
  else {
39667
- await exec6("systemctl", ["--user", "disable", unit]).catch(() => {
39927
+ await exec7("systemctl", ["--user", "disable", unit]).catch(() => {
39668
39928
  });
39669
- await unlink4(path46.join(homedir13(), ".config/systemd/user", unit)).catch(() => {
39929
+ await unlink4(path48.join(homedir13(), ".config/systemd/user", unit)).catch(() => {
39670
39930
  });
39671
- await exec6("systemctl", ["--user", "daemon-reload"]).catch(() => {
39931
+ await exec7("systemctl", ["--user", "daemon-reload"]).catch(() => {
39672
39932
  });
39673
39933
  }
39674
- await applyAgentHooks(await planAgentHooks(path46.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
39934
+ await applyAgentHooks(await planAgentHooks(path48.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
39675
39935
  await applyOpencodePlugin(true);
39676
39936
  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());
39677
39937
  }
@@ -39686,9 +39946,9 @@ async function missingFile(operation) {
39686
39946
  async function planAgentHooks(program, remove = false, modules) {
39687
39947
  const edits = [];
39688
39948
  for (const [source, file2] of [
39689
- ["codex", path46.join(codexHome(), "hooks.json")],
39690
- ["claude", path46.join(claudeConfigDir(), "settings.json")],
39691
- ["copilot", path46.join(process.env.COPILOT_HOME || path46.join(homedir13(), ".copilot"), "hooks/phren.json")]
39949
+ ["codex", path48.join(codexHome(), "hooks.json")],
39950
+ ["claude", path48.join(claudeConfigDir(), "settings.json")],
39951
+ ["copilot", path48.join(process.env.COPILOT_HOME || path48.join(homedir13(), ".copilot"), "hooks/phren.json")]
39692
39952
  ]) {
39693
39953
  const metadata = await missingFile(lstat9(file2));
39694
39954
  if (metadata && (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 2097152)) {
@@ -39738,7 +39998,7 @@ async function planAgentHooks(program, remove = false, modules) {
39738
39998
  }
39739
39999
  return edits;
39740
40000
  }
39741
- var opencodePluginsDir = () => path46.join(process.env.XDG_CONFIG_HOME || path46.join(homedir13(), ".config"), "opencode", "plugins");
40001
+ var opencodePluginsDir = () => path48.join(process.env.XDG_CONFIG_HOME || path48.join(homedir13(), ".config"), "opencode", "plugins");
39742
40002
  var OPENCODE_PLUGIN_MARKER = "// Installed by Phren Hook";
39743
40003
  function opencodePluginNeedsWrite(existing, source) {
39744
40004
  if (existing === void 0) return true;
@@ -39747,10 +40007,10 @@ function opencodePluginNeedsWrite(existing, source) {
39747
40007
  }
39748
40008
  async function opencodePluginSource() {
39749
40009
  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';
39750
- const here = path46.dirname(fileURLToPath5(import.meta.url));
40010
+ const here = path48.dirname(fileURLToPath5(import.meta.url));
39751
40011
  for (const candidate of [
39752
- path46.join(here, "..", "..", "plugins", "opencode", "phren-transcript.js"),
39753
- path46.join(here, "..", "plugins", "opencode", "phren-transcript.js")
40012
+ path48.join(here, "..", "..", "plugins", "opencode", "phren-transcript.js"),
40013
+ path48.join(here, "..", "plugins", "opencode", "phren-transcript.js")
39754
40014
  ]) {
39755
40015
  const source = await missingFile(readFile18(candidate, "utf8"));
39756
40016
  if (source !== void 0) return source;
@@ -39758,7 +40018,7 @@ async function opencodePluginSource() {
39758
40018
  return void 0;
39759
40019
  }
39760
40020
  async function applyOpencodePlugin(remove = false) {
39761
- const dir = opencodePluginsDir(), file2 = path46.join(dir, "phren-transcript.js");
40021
+ const dir = opencodePluginsDir(), file2 = path48.join(dir, "phren-transcript.js");
39762
40022
  const source = await opencodePluginSource();
39763
40023
  const existing = await missingFile(readFile18(file2, "utf8"));
39764
40024
  if (remove) {
@@ -39766,14 +40026,14 @@ async function applyOpencodePlugin(remove = false) {
39766
40026
  return false;
39767
40027
  }
39768
40028
  if (source === void 0 || !opencodePluginNeedsWrite(existing, source)) return false;
39769
- if (!(await lstat9(path46.dirname(dir)).catch(() => null))?.isDirectory()) return false;
40029
+ if (!(await lstat9(path48.dirname(dir)).catch(() => null))?.isDirectory()) return false;
39770
40030
  await mkdir10(dir, { recursive: true });
39771
40031
  await atomic(file2, source, 420);
39772
40032
  return true;
39773
40033
  }
39774
40034
  async function applyAgentHooks(edits) {
39775
40035
  for (const { file: file2, before, after } of edits) {
39776
- await mkdir10(path46.dirname(file2), { recursive: true, mode: 448 });
40036
+ await mkdir10(path48.dirname(file2), { recursive: true, mode: 448 });
39777
40037
  if (await missingFile(readFile18(file2, "utf8")) !== before) throw new Error("Agent settings changed during installation. Run install again.");
39778
40038
  if (before !== void 0) await copyFile2(file2, file2 + `.phren-hook-${Date.now()}.bak`);
39779
40039
  await atomic(file2, after);
@@ -39787,18 +40047,18 @@ async function restoreAgentHooks(edits) {
39787
40047
  }
39788
40048
  }
39789
40049
  async function rollback() {
39790
- const config3 = JSON.parse(await readFile18(path46.join(bridgeRoot(), "installed.json"), "utf8"));
40050
+ const config3 = JSON.parse(await readFile18(path48.join(bridgeRoot(), "installed.json"), "utf8"));
39791
40051
  if (!config3.previous || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(config3.previous)) throw new Error("No previous helper version is available.");
39792
40052
  await stopService();
39793
40053
  await activate(config3.previous);
39794
40054
  await startService();
39795
- await atomic(path46.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config3.previous, previous: config3.version }) + "\n");
40055
+ await atomic(path48.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config3.previous, previous: config3.version }) + "\n");
39796
40056
  }
39797
40057
 
39798
40058
  // src/bridge/computers.ts
39799
40059
  init_protocol();
39800
- var exec7 = promisify7(execFile8);
39801
- var dispatchKeyPath = (root = bridgeRoot()) => path47.join(root, "id_ed25519_dispatch");
40060
+ var exec8 = promisify8(execFile9);
40061
+ var dispatchKeyPath = (root = bridgeRoot()) => path49.join(root, "id_ed25519_dispatch");
39802
40062
  function publicComputerKey(value2) {
39803
40063
  const match = /^ssh-ed25519 ([A-Za-z0-9+/]+={0,2})(?: [^\r\n]*)?$/.exec(value2.trim());
39804
40064
  if (!match) throw new BridgeError(400, "Supply one ed25519 public key.");
@@ -39824,7 +40084,7 @@ async function enrollComputer(name, root = bridgeRoot()) {
39824
40084
  computerName.parse(name);
39825
40085
  await mkdir11(root, { recursive: true, mode: 448 });
39826
40086
  await chmod3(root, 448);
39827
- const lock = path47.join(root, "enroll-computer.lock");
40087
+ const lock = path49.join(root, "enroll-computer.lock");
39828
40088
  try {
39829
40089
  await mkdir11(lock, { mode: 448 });
39830
40090
  } catch {
@@ -39833,23 +40093,23 @@ async function enrollComputer(name, root = bridgeRoot()) {
39833
40093
  try {
39834
40094
  const key2 = dispatchKeyPath(root);
39835
40095
  if (!await regularFile(key2)) {
39836
- const temporary = await mkdtemp2(path47.join(root, "enroll-"));
40096
+ const temporary = await mkdtemp2(path49.join(root, "enroll-"));
39837
40097
  try {
39838
- const generated = path47.join(temporary, "key");
39839
- await exec7("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", "phren-computer", "-f", generated], { timeout: 1e4 });
40098
+ const generated = path49.join(temporary, "key");
40099
+ await exec8("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", "phren-computer", "-f", generated], { timeout: 1e4 });
39840
40100
  await rename6(generated, key2);
39841
40101
  } finally {
39842
40102
  await rm5(temporary, { recursive: true, force: true });
39843
40103
  }
39844
40104
  }
39845
40105
  await chmod3(key2, 384);
39846
- const { stdout } = await exec7("ssh-keygen", ["-y", "-P", "", "-f", key2], { timeout: 1e4, maxBuffer: 4096 });
40106
+ const { stdout } = await exec8("ssh-keygen", ["-y", "-P", "", "-f", key2], { timeout: 1e4, maxBuffer: 4096 });
39847
40107
  return computerKeyLine(name, stdout.trim());
39848
40108
  } finally {
39849
40109
  await rm5(lock, { recursive: true, force: true });
39850
40110
  }
39851
40111
  }
39852
- async function acceptComputer(name, input2, sshDirectory = path47.join(homedir14(), ".ssh")) {
40112
+ async function acceptComputer(name, input2, sshDirectory = path49.join(homedir14(), ".ssh")) {
39853
40113
  computerName.parse(name);
39854
40114
  const prefix = `restrict,pty,${forcedCommand} `;
39855
40115
  const raw = input2.trim();
@@ -39863,19 +40123,19 @@ async function acceptComputer(name, input2, sshDirectory = path47.join(homedir14
39863
40123
  sshDirectory
39864
40124
  );
39865
40125
  }
39866
- async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory = path47.join(homedir14(), ".ssh")) {
40126
+ async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory = path49.join(homedir14(), ".ssh")) {
39867
40127
  const directory = await lstat10(sshDirectory).catch(() => void 0);
39868
40128
  if (directory && (!directory.isDirectory() || directory.isSymbolicLink())) throw new BridgeError(409, "Refusing an unexpected SSH directory.");
39869
40129
  await mkdir11(sshDirectory, { recursive: true, mode: 448 });
39870
40130
  await chmod3(sshDirectory, 448);
39871
- const lock = path47.join(sshDirectory, ".phren-enroll.lock");
40131
+ const lock = path49.join(sshDirectory, ".phren-enroll.lock");
39872
40132
  try {
39873
40133
  await mkdir11(lock, { mode: 448 });
39874
40134
  } catch {
39875
40135
  throw new BridgeError(409, "SSH enrollment is already running; inspect .phren-enroll.lock if interrupted.");
39876
40136
  }
39877
- const file2 = path47.join(sshDirectory, "authorized_keys");
39878
- const temporary = path47.join(lock, "authorized_keys");
40137
+ const file2 = path49.join(sshDirectory, "authorized_keys");
40138
+ const temporary = path49.join(lock, "authorized_keys");
39879
40139
  try {
39880
40140
  const before = await regularFile(file2) ? await readFile19(file2, "utf8") : "";
39881
40141
  const lines = before.split("\n").filter(Boolean);
@@ -39982,10 +40242,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
39982
40242
  for (const value2 of values.slice(0, 128)) {
39983
40243
  if (state.count >= 128) break;
39984
40244
  const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
39985
- const path84 = publicLabel(raw.path);
40245
+ const path86 = publicLabel(raw.path);
39986
40246
  const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
39987
40247
  const routed = destination(raw, fallbackComputer, fallbackTarget);
39988
- if (!id2.success || !source.success || !path84 || !callId || !routed) continue;
40248
+ if (!id2.success || !source.success || !path86 || !callId || !routed) continue;
39989
40249
  const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
39990
40250
  const nestedSession = sessionId.safeParse(raw.session);
39991
40251
  const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
@@ -39998,7 +40258,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
39998
40258
  projected.push({
39999
40259
  id: publicID(parent, routed.computer.id, receipt.id, descendant),
40000
40260
  provider: source.data,
40001
- path: path84,
40261
+ path: path86,
40002
40262
  callId,
40003
40263
  state: raw.failed === true ? "failed" : childState,
40004
40264
  ...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
@@ -40060,7 +40320,7 @@ init_logger();
40060
40320
  init_client();
40061
40321
  import { spawn as spawn5 } from "node:child_process";
40062
40322
  import { lstat as lstat11, mkdtemp as mkdtemp3, readFile as readFile20, rm as rm6, writeFile as writeFile6 } from "node:fs/promises";
40063
- import path48 from "node:path";
40323
+ import path50 from "node:path";
40064
40324
  import { Duplex } from "node:stream";
40065
40325
  init_protocol();
40066
40326
  var peerSchema = external_exports.object({
@@ -40072,7 +40332,7 @@ var peerSchema = external_exports.object({
40072
40332
  server: serverName.default("default")
40073
40333
  }).strict();
40074
40334
  async function hookPeers(root = bridgeRoot()) {
40075
- const file2 = path48.join(root, "hooks.yaml");
40335
+ const file2 = path50.join(root, "hooks.yaml");
40076
40336
  const info = await lstat11(file2).catch((error62) => {
40077
40337
  if (error62.code === "ENOENT") return void 0;
40078
40338
  throw new BridgeError(409, `hooks.yaml could not be read (${error62.code ?? "unknown error"}).`);
@@ -40094,7 +40354,7 @@ async function addHookPeer(input2, root = bridgeRoot()) {
40094
40354
  const clash = existing.find((other) => other.name === peer.name || other.address === peer.address && other.port === peer.port && other.server === peer.server);
40095
40355
  if (clash) throw new BridgeError(409, `hooks.yaml already has ${clash.name} at ${clash.address}; remove that entry first to link it differently.`);
40096
40356
  if (existing.length >= 32) throw new BridgeError(409, "hooks.yaml already has 32 computers.");
40097
- await atomic(path48.join(root, "hooks.yaml"), dump({ version: 1, computers: [...existing, peer] }, { lineWidth: -1 }));
40357
+ await atomic(path50.join(root, "hooks.yaml"), dump({ version: 1, computers: [...existing, peer] }, { lineWidth: -1 }));
40098
40358
  return { added: true, peer };
40099
40359
  }
40100
40360
  async function optionalHookPeers(root = bridgeRoot()) {
@@ -40175,10 +40435,10 @@ async function peerRequest(peer, route2, data, timeout) {
40175
40435
  const root = bridgeRoot(), key2 = dispatchKeyPath(root);
40176
40436
  const info = await lstat11(key2).catch(() => void 0);
40177
40437
  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" });
40178
- const temporary = await mkdtemp3(path48.join(root, "peer-"));
40438
+ const temporary = await mkdtemp3(path50.join(root, "peer-"));
40179
40439
  let child, stream;
40180
40440
  try {
40181
- const knownHosts = path48.join(temporary, "known_hosts");
40441
+ const knownHosts = path50.join(temporary, "known_hosts");
40182
40442
  await writeFile6(knownHosts, `phren-peer ${peer.hostKey}
40183
40443
  `, { mode: 384 });
40184
40444
  const ssh2 = spawn5("ssh", peerSSHArgs(peer, knownHosts, key2), { stdio: ["pipe", "pipe", "pipe"] });
@@ -40315,21 +40575,21 @@ var receiptSchema2 = dispatchSchema.omit({ prompt: true }).extend({
40315
40575
  async function dispatchProjectDirectory(project) {
40316
40576
  const name = projectName.parse(project);
40317
40577
  const source = readProjectConfig(phrenStoreRoot(), name).sourcePath;
40318
- if (typeof source !== "string" || !path49.isAbsolute(source) || /[\x00-\x1f\x7f]/.test(source)) throw new BridgeError(404, "Project has no absolute sourcePath on this computer.");
40319
- const directory = await realpath9(source).catch(() => void 0);
40320
- if (!directory || !(await stat14(directory)).isDirectory()) throw new BridgeError(404, "Project is not on this computer.");
40578
+ if (typeof source !== "string" || !path51.isAbsolute(source) || /[\x00-\x1f\x7f]/.test(source)) throw new BridgeError(404, "Project has no absolute sourcePath on this computer.");
40579
+ const directory = await realpath10(source).catch(() => void 0);
40580
+ if (!directory || !(await stat15(directory)).isDirectory()) throw new BridgeError(404, "Project is not on this computer.");
40321
40581
  return directory;
40322
40582
  }
40323
40583
  async function save(receipt) {
40324
- const root = path49.join(bridgeRoot(), "dispatches");
40584
+ const root = path51.join(bridgeRoot(), "dispatches");
40325
40585
  await mkdir12(root, { recursive: true, mode: 448 });
40326
- await atomic(path49.join(root, `${receipt.id}.json`), receipt);
40586
+ await atomic(path51.join(root, `${receipt.id}.json`), receipt);
40327
40587
  }
40328
40588
  var MAX_RECEIPT_BYTES = 65536;
40329
40589
  var receiptUpdates = Promise.resolve();
40330
40590
  function updateReceipt(receiptID, change) {
40331
40591
  const run = receiptUpdates.then(async () => {
40332
- const file2 = path49.join(bridgeRoot(), "dispatches", `${external_exports.string().uuid().parse(receiptID)}.json`);
40592
+ const file2 = path51.join(bridgeRoot(), "dispatches", `${external_exports.string().uuid().parse(receiptID)}.json`);
40333
40593
  const info = await lstat12(file2).catch(() => void 0);
40334
40594
  if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) return void 0;
40335
40595
  const receipt = receiptSchema2.parse(JSON.parse(await readFile21(file2, "utf8")));
@@ -40344,7 +40604,7 @@ function updateReceipt(receiptID, change) {
40344
40604
  }
40345
40605
  async function receiptNames(root) {
40346
40606
  try {
40347
- return await readdir9(root);
40607
+ return await readdir10(root);
40348
40608
  } catch (error62) {
40349
40609
  if (error62.code !== "ENOENT") logger.warn("dispatch", `Could not list dispatch receipts: ${failureReason(error62)}`);
40350
40610
  return [];
@@ -40357,12 +40617,12 @@ function failureReason(error62) {
40357
40617
  return `${typeof code === "string" && !(error62 instanceof BridgeError) ? `${code}: ` : ""}${message}`.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200);
40358
40618
  }
40359
40619
  async function dispatchStatus() {
40360
- const root = path49.join(bridgeRoot(), "dispatches");
40620
+ const root = path51.join(bridgeRoot(), "dispatches");
40361
40621
  const names = (await receiptNames(root)).filter((name) => /^[a-f0-9-]{36}\.json$/.test(name)).slice(0, 1024);
40362
40622
  const receipts = [];
40363
40623
  for (const name of names) {
40364
40624
  try {
40365
- const file2 = path49.join(root, name);
40625
+ const file2 = path51.join(root, name);
40366
40626
  const info = await lstat12(file2);
40367
40627
  if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) continue;
40368
40628
  const receipt = receiptSchema2.parse(JSON.parse(await readFile21(file2, "utf8")));
@@ -40437,7 +40697,7 @@ var DispatchService = class {
40437
40697
  if (!this.identity) throw new BridgeError(503, "This Hook cannot validate a dispatch parent.");
40438
40698
  await validateDispatchParent(data, this.identity.computerID, this.identity.validateParentTarget);
40439
40699
  }
40440
- if ((await receiptNames(path49.join(bridgeRoot(), "dispatches"))).length >= 1024) throw new BridgeError(429, "Dispatch history is full. Archive old receipts before dispatching again.");
40700
+ if ((await receiptNames(path51.join(bridgeRoot(), "dispatches"))).length >= 1024) throw new BridgeError(429, "Dispatch history is full. Archive old receipts before dispatching again.");
40441
40701
  const here = this.local();
40442
40702
  const toLocal = data.computer !== "anywhere" && isLocalComputer(data.computer, here.names);
40443
40703
  const enrolled = await hookPeers().catch((error62) => {
@@ -40649,7 +40909,7 @@ init_protocol();
40649
40909
 
40650
40910
  // src/bridge/schedule-watch.ts
40651
40911
  init_herdr();
40652
- import { open as open10, stat as stat15 } from "node:fs/promises";
40912
+ import { open as open11, stat as stat16 } from "node:fs/promises";
40653
40913
  init_protocol();
40654
40914
  init_transcripts();
40655
40915
  init_terminal_text();
@@ -40744,7 +41004,7 @@ async function readFinalTurn(source, sessionId2) {
40744
41004
  if (!sessionId2) return void 0;
40745
41005
  const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
40746
41006
  if (!file2) return void 0;
40747
- const handle = await open10(file2, "r").catch(() => void 0);
41007
+ const handle = await open11(file2, "r").catch(() => void 0);
40748
41008
  if (!handle) return void 0;
40749
41009
  try {
40750
41010
  const { size } = await handle.stat();
@@ -40784,7 +41044,7 @@ function ownerQuestion(text4) {
40784
41044
  async function realTranscriptStamp(source, sessionId2) {
40785
41045
  if (!sessionId2) return void 0;
40786
41046
  const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
40787
- const metadata = file2 ? await stat15(file2).catch(() => void 0) : void 0;
41047
+ const metadata = file2 ? await stat16(file2).catch(() => void 0) : void 0;
40788
41048
  return metadata ? { size: metadata.size, mtimeMs: metadata.mtimeMs } : void 0;
40789
41049
  }
40790
41050
  async function watchHerdrRun(server, target, signal, startup, env = {}) {
@@ -41037,11 +41297,11 @@ var DispatchReturns = class {
41037
41297
  /** Ask each peer, once, about every open dispatch placed on it. */
41038
41298
  async poll() {
41039
41299
  const now = this.now();
41040
- 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);
41041
- if (!open16.length) return;
41300
+ 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);
41301
+ if (!open17.length) return;
41042
41302
  const peers = await this.peers().catch(() => []);
41043
41303
  const byComputer = /* @__PURE__ */ new Map();
41044
- for (const receipt of open16) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
41304
+ for (const receipt of open17) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
41045
41305
  await Promise.all([...byComputer].map(async ([computer, receipts]) => {
41046
41306
  const peer = peers.find((candidate) => candidate.name === computer);
41047
41307
  const local = !peer && this.isLocal(computer);
@@ -41112,13 +41372,13 @@ init_zod();
41112
41372
  init_protocol();
41113
41373
  init_herdr();
41114
41374
  init_transcripts();
41115
- init_transcript_index();
41116
- import { execFile as execFile9 } from "node:child_process";
41375
+ import { execFile as execFile10 } from "node:child_process";
41117
41376
  import { createHash as createHash12 } from "node:crypto";
41118
- import { mkdir as mkdir13, open as open11, stat as stat16, readFile as readFile22, writeFile as writeFile7 } from "node:fs/promises";
41119
- import path50 from "node:path";
41120
- import { promisify as promisify8 } from "node:util";
41121
- var exec8 = promisify8(execFile9);
41377
+ import { mkdir as mkdir13, open as open12, stat as stat17, readFile as readFile22, writeFile as writeFile7 } from "node:fs/promises";
41378
+ import path52 from "node:path";
41379
+ import { promisify as promisify9 } from "node:util";
41380
+ init_transcript_index();
41381
+ var exec9 = promisify9(execFile10);
41122
41382
  var text3 = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
41123
41383
  var question = external_exports.object({ title: text3, options: external_exports.array(text3).max(12).nullable().optional() });
41124
41384
  var questionSet = external_exports.array(question).min(1).max(8);
@@ -41161,7 +41421,7 @@ var answersQuestions = (reply, questions) => questions.every((q) => {
41161
41421
  });
41162
41422
  async function pendingAsyncQuestions(file2, targetID) {
41163
41423
  return withTranscriptIndex(file2, async (handle, index2) => {
41164
- const replies = [], acknowledged = /* @__PURE__ */ new Set(), resolved = /* @__PURE__ */ new Set(), pending = [];
41424
+ const replies = [], acknowledged = /* @__PURE__ */ new Set(), resolved = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set(), pending = [];
41165
41425
  let bytes = 0;
41166
41426
  for await (const row of index2.rows(handle, index2.lines, Math.max(0, index2.lines - 1e4))) {
41167
41427
  if (!row.bytes || (bytes += row.bytes.length) > 8388608) throw new BridgeError(413, "The pending question history is too large to verify.");
@@ -41187,10 +41447,11 @@ async function pendingAsyncQuestions(file2, targetID) {
41187
41447
  if (targetID && resolved.has(targetID)) return [];
41188
41448
  if (!id2 || !acknowledged.has(id2)) continue;
41189
41449
  const questions = asyncQuestion(raw, id2);
41190
- if (questions && !replies.some((reply) => answersQuestions(reply, questions))) {
41450
+ if (questions && !seen.has(id2) && !replies.some((reply) => answersQuestions(reply, questions))) {
41191
41451
  pending.push({ id: id2, questions });
41192
41452
  if (pending.length >= 64) throw new BridgeError(413, "Too many pending questions to verify.");
41193
41453
  }
41454
+ if (questions) seen.add(id2);
41194
41455
  if (targetID && questions && id2 === targetID) return pending.filter((p2) => p2.id === targetID);
41195
41456
  }
41196
41457
  if (index2.lines > 1e4) throw new BridgeError(413, "The pending question history is too large to verify.");
@@ -41203,10 +41464,11 @@ async function pendingAsyncQuestion(file2, id2) {
41203
41464
  return pending.questions;
41204
41465
  }
41205
41466
  var CodexQuestions = class {
41206
- constructor(executable = "codex") {
41207
- this.executable = executable;
41467
+ /** No executable: the real `codex` on PATH, past phren's session wrapper. */
41468
+ constructor(configured) {
41469
+ this.configured = configured;
41208
41470
  }
41209
- executable;
41471
+ configured;
41210
41472
  snapshots = /* @__PURE__ */ new Map();
41211
41473
  failedSnapshots = /* @__PURE__ */ new Map();
41212
41474
  inboxAvailable = false;
@@ -41216,8 +41478,11 @@ var CodexQuestions = class {
41216
41478
  return this.inboxAvailable;
41217
41479
  }
41218
41480
  probe;
41481
+ get executable() {
41482
+ return this.configured ?? codexExecutable();
41483
+ }
41219
41484
  supported() {
41220
- 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) => {
41485
+ 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) => {
41221
41486
  this.inboxAvailable = available;
41222
41487
  return available;
41223
41488
  }) };
@@ -41230,7 +41495,7 @@ var CodexQuestions = class {
41230
41495
  const cached2 = this.snapshots.get(target.session);
41231
41496
  let pending = cached2?.pending;
41232
41497
  if (!cached2 || Date.now() - cached2.at > 1e3) {
41233
- const metadata = await stat16(file2), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
41498
+ const metadata = await stat17(file2), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
41234
41499
  pending = cached2?.stamp === stamp ? cached2.pending : await pendingAsyncQuestions(file2).catch((error62) => {
41235
41500
  if (this.failedSnapshots.size >= 64) this.failedSnapshots.delete(this.failedSnapshots.keys().next().value);
41236
41501
  this.failedSnapshots.set(target.session, Date.now());
@@ -41242,7 +41507,7 @@ var CodexQuestions = class {
41242
41507
  }
41243
41508
  return Promise.all((pending ?? []).map(async (p) => {
41244
41509
  const key2 = createHash12("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
41245
- const submitted = await readFile22(path50.join(bridgeRoot(), "question-replies", key2), "utf8").then((value2) => value2 === "submitted").catch(() => false);
41510
+ const submitted = await readFile22(path52.join(bridgeRoot(), "question-replies", key2), "utf8").then((value2) => value2 === "submitted").catch(() => false);
41246
41511
  return { toolUseId: p.id, isAsync: true, submitted, questions: p.questions.map((q) => ({
41247
41512
  question: q.title,
41248
41513
  options: (q.options ?? []).map((label2) => ({ label: label2 })),
@@ -41258,17 +41523,17 @@ var CodexQuestions = class {
41258
41523
  const reply = questionReply(questions, data.answers);
41259
41524
  const pane = await validateTarget(target);
41260
41525
  if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
41261
- const directory = path50.join(bridgeRoot(), "question-replies");
41526
+ const directory = path52.join(bridgeRoot(), "question-replies");
41262
41527
  await mkdir13(directory, { recursive: true, mode: 448 });
41263
41528
  const key2 = createHash12("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
41264
- const receiptPath = path50.join(directory, key2);
41265
- const receipt = await open11(receiptPath, "wx", 384).catch((error62) => {
41529
+ const receiptPath = path52.join(directory, key2);
41530
+ const receipt = await open12(receiptPath, "wx", 384).catch((error62) => {
41266
41531
  if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
41267
41532
  throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
41268
41533
  });
41269
41534
  await receipt.close();
41270
41535
  try {
41271
- await exec8(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8e3, maxBuffer: 65536 });
41536
+ await exec9(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8e3, maxBuffer: 65536 });
41272
41537
  await writeFile7(receiptPath, "submitted", { mode: 384 });
41273
41538
  } catch {
41274
41539
  throw new BridgeError(409, "Codex did not confirm the answer. Check the conversation; Phren has not retried it.");
@@ -41284,12 +41549,12 @@ init_transcripts();
41284
41549
  init_home_paths();
41285
41550
  init_protocol();
41286
41551
  import { spawn as spawn6 } from "node:child_process";
41287
- import { readdir as readdir10, readFile as readFile23, stat as stat17 } from "node:fs/promises";
41552
+ import { readdir as readdir11, readFile as readFile23, stat as stat18 } from "node:fs/promises";
41288
41553
  import { homedir as homedir15 } from "node:os";
41289
- import path51 from "node:path";
41290
- function readCodexModels(executable = "codex") {
41554
+ import path53 from "node:path";
41555
+ function readCodexModels(executable2 = codexExecutable()) {
41291
41556
  return new Promise((resolve11) => {
41292
- const child = spawn6(executable, ["app-server"], { cwd: homedir15(), stdio: ["pipe", "pipe", "ignore"] });
41557
+ const child = spawn6(executable2, ["app-server"], { cwd: homedir15(), stdio: ["pipe", "pipe", "ignore"] });
41293
41558
  let pending = "", bytes = 0, initialized = false, done = false;
41294
41559
  const finish = (result = []) => {
41295
41560
  if (done) return;
@@ -41365,12 +41630,12 @@ var CLAUDE_MENU = [
41365
41630
  { id: "claude-fable-5-1[1m]", name: "Fable 5.1 (1M context)", description: "Fable 5.1 with a 1M context window." }
41366
41631
  ];
41367
41632
  async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
41368
- const directory = path51.join(configDir, "cache", "model-catalog");
41633
+ const directory = path53.join(configDir, "cache", "model-catalog");
41369
41634
  let newest;
41370
41635
  try {
41371
- for (const name of await readdir10(directory)) {
41636
+ for (const name of await readdir11(directory)) {
41372
41637
  if (!name.endsWith("-cc.json")) continue;
41373
- const file2 = path51.join(directory, name), at = (await stat17(file2)).mtimeMs;
41638
+ const file2 = path53.join(directory, name), at = (await stat18(file2)).mtimeMs;
41374
41639
  if (!newest || at > newest.at) newest = { file: file2, at };
41375
41640
  }
41376
41641
  } catch {
@@ -41424,9 +41689,9 @@ function olderVersion(installed, required2) {
41424
41689
  for (let index2 = 0; index2 < 3; index2++) if (have[index2] !== need[index2]) return have[index2] < need[index2];
41425
41690
  return false;
41426
41691
  }
41427
- function claudeVersion(executable = "claude") {
41692
+ function claudeVersion(executable2 = "claude") {
41428
41693
  return new Promise((resolve11) => {
41429
- const child = spawn6(executable, ["--version"], { cwd: homedir15(), stdio: ["ignore", "pipe", "ignore"] });
41694
+ const child = spawn6(executable2, ["--version"], { cwd: homedir15(), stdio: ["ignore", "pipe", "ignore"] });
41430
41695
  let out = "";
41431
41696
  const timer = setTimeout(() => {
41432
41697
  child.kill("SIGKILL");
@@ -41451,9 +41716,9 @@ async function readClaudeModels(configDir, installed) {
41451
41716
  const live = await readClaudeCatalog(configDir, version3).catch(() => []);
41452
41717
  return live.length ? live : CLAUDE_MENU.map((model) => ({ ...model }));
41453
41718
  }
41454
- async function readOpenCodeModels(executable = "opencode", configDir = path51.join(homedir15(), ".config/opencode")) {
41719
+ async function readOpenCodeModels(executable2 = "opencode", configDir = path53.join(homedir15(), ".config/opencode")) {
41455
41720
  const listed2 = await new Promise((resolve11) => {
41456
- const child = spawn6(executable, ["models"], { cwd: homedir15(), stdio: ["ignore", "pipe", "ignore"] });
41721
+ const child = spawn6(executable2, ["models"], { cwd: homedir15(), stdio: ["ignore", "pipe", "ignore"] });
41457
41722
  let out = "", done = false;
41458
41723
  const finish = () => {
41459
41724
  if (!done) {
@@ -41478,7 +41743,7 @@ async function readOpenCodeModels(executable = "opencode", configDir = path51.jo
41478
41743
  let configured;
41479
41744
  for (const file2 of ["opencode.json", "opencode.jsonc"]) {
41480
41745
  try {
41481
- const text4 = await readFile23(path51.join(configDir, file2), "utf8");
41746
+ const text4 = await readFile23(path53.join(configDir, file2), "utf8");
41482
41747
  const model = /"model"\s*:\s*"([^"]+)"/.exec(text4)?.[1];
41483
41748
  if (model) {
41484
41749
  configured = model.slice(0, 200);
@@ -41948,14 +42213,14 @@ init_project_config();
41948
42213
  init_shared();
41949
42214
  import { randomUUID as randomUUID11 } from "node:crypto";
41950
42215
  import { hostname as hostname6 } from "node:os";
41951
- import path54 from "node:path";
42216
+ import path56 from "node:path";
41952
42217
 
41953
42218
  // src/bridge/schedule-format.ts
41954
42219
  init_js_yaml();
41955
42220
  init_zod();
41956
42221
  init_protocol();
41957
42222
  import { readFile as readFile24 } from "node:fs/promises";
41958
- import path52 from "node:path";
42223
+ import path54 from "node:path";
41959
42224
  var SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
41960
42225
  var SCHEDULE_HARNESSES = ["claude", "codex", "opencode"];
41961
42226
  var SCHEDULE_NOTIFY = ["start", "finish", "failure"];
@@ -41968,7 +42233,7 @@ var scheduleName = singleLine(80);
41968
42233
  var timestamp3 = external_exports.string().datetime({ offset: true });
41969
42234
  var localTimestamp = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/);
41970
42235
  var clockTime = external_exports.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
41971
- var schedulePath = (projectDir) => path52.join(projectDir, "schedules.yaml");
42236
+ var schedulePath = (projectDir) => path54.join(projectDir, "schedules.yaml");
41972
42237
  var runningStatuses = /* @__PURE__ */ new Set(["launched", "running", "blocked"]);
41973
42238
  var MAX_SCHEDULES = 64;
41974
42239
  var MAX_RUNS = 2e3;
@@ -42168,7 +42433,7 @@ async function writeScheduleRuns(file2, runs) {
42168
42433
  await atomicInPrivateDir(file2, kept.map((run) => JSON.stringify(run)).join("\n") + (kept.length ? "\n" : ""));
42169
42434
  }
42170
42435
  function scheduleRunsFile() {
42171
- return path52.join(bridgeRoot(), "schedule-runs.jsonl");
42436
+ return path54.join(bridgeRoot(), "schedule-runs.jsonl");
42172
42437
  }
42173
42438
 
42174
42439
  // src/bridge/schedule-launch.ts
@@ -42181,8 +42446,8 @@ init_logger();
42181
42446
  init_shared();
42182
42447
  import { spawn as spawn7 } from "node:child_process";
42183
42448
  import { createWriteStream } from "node:fs";
42184
- import { mkdir as mkdir14, readFile as readFile25, stat as stat18 } from "node:fs/promises";
42185
- import path53 from "node:path";
42449
+ import { mkdir as mkdir14, readFile as readFile25, stat as stat19 } from "node:fs/promises";
42450
+ import path55 from "node:path";
42186
42451
  import { finished as streamFinished } from "node:stream/promises";
42187
42452
  var CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
42188
42453
  function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
@@ -42215,7 +42480,7 @@ async function resumeScheduleRun(run, schedule, signal, watch2 = watchHerdrRun)
42215
42480
  );
42216
42481
  }
42217
42482
  if (launch2.mode === "headless" && launch2.jobDir) {
42218
- const manifest = await readFile25(path53.join(launch2.jobDir, "manifest.json"), "utf8").then((text4) => JSON.parse(text4)).catch(() => void 0);
42483
+ const manifest = await readFile25(path55.join(launch2.jobDir, "manifest.json"), "utf8").then((text4) => JSON.parse(text4)).catch(() => void 0);
42219
42484
  if (manifest?.status === "completed") return { status: "finished" };
42220
42485
  if (manifest?.status === "failed") {
42221
42486
  return { status: "failed", reason: typeof manifest.exitCode === "number" ? `The scheduled agent exited with code ${manifest.exitCode}.` : "The scheduled agent failed." };
@@ -42263,7 +42528,7 @@ async function promptWhenReady(server, paneId, text4, signal, waitMs = 6e4) {
42263
42528
  }
42264
42529
  }
42265
42530
  async function launchHeadless(context, store, started) {
42266
- const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path53.join(root, context.runId);
42531
+ const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path55.join(root, context.runId);
42267
42532
  await mkdir14(jobDir, { recursive: true, mode: 448 });
42268
42533
  const eventLog = "events.jsonl", now = (/* @__PURE__ */ new Date()).toISOString();
42269
42534
  const manifest = {
@@ -42283,7 +42548,7 @@ async function launchHeadless(context, store, started) {
42283
42548
  };
42284
42549
  await writeManifest2(jobDir, manifest);
42285
42550
  const command = headlessCommand(context.schedule, context.cwd);
42286
- 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)}`));
42551
+ if (context.schedule.harness === "codex") await ensureCodexDirTrusted(context.cwd).catch((error62) => logger.warn("schedule", `Could not mark ${path55.basename(context.cwd)} trusted for Codex (run ${context.runId}): ${error62 instanceof Error ? error62.message.split("\n")[0] : String(error62)}`));
42287
42552
  let child;
42288
42553
  try {
42289
42554
  child = spawn7(command.file, command.args, { cwd: command.cwd, env: process.env, stdio: ["pipe", "pipe", "pipe"] });
@@ -42295,8 +42560,8 @@ async function launchHeadless(context, store, started) {
42295
42560
  const closed = new Promise((resolve11) => {
42296
42561
  child.once("close", (code, signal) => resolve11({ code, signal }));
42297
42562
  });
42298
- const output2 = createWriteStream(path53.join(jobDir, eventLog), { flags: "a", mode: 384 });
42299
- const errors = createWriteStream(path53.join(jobDir, "stderr.log"), { flags: "a", mode: 384 });
42563
+ const output2 = createWriteStream(path55.join(jobDir, eventLog), { flags: "a", mode: 384 });
42564
+ const errors = createWriteStream(path55.join(jobDir, "stderr.log"), { flags: "a", mode: 384 });
42300
42565
  const streamsFinished = Promise.all([streamFinished(output2), streamFinished(errors)]).then(() => void 0).catch(() => void 0);
42301
42566
  child.stdin?.on("error", () => {
42302
42567
  });
@@ -42349,7 +42614,7 @@ function tomlQuote(value2) {
42349
42614
  }
42350
42615
  async function ensureCodexDirTrusted(cwd) {
42351
42616
  const directory = codexHome();
42352
- const file2 = path53.join(directory, "config.toml");
42617
+ const file2 = path55.join(directory, "config.toml");
42353
42618
  let text4 = "";
42354
42619
  try {
42355
42620
  text4 = await readFile25(file2, "utf8");
@@ -42381,12 +42646,12 @@ ${trustLine}
42381
42646
  `;
42382
42647
  }
42383
42648
  await mkdir14(directory, { recursive: true, mode: 448 });
42384
- const metadata = await stat18(file2).catch(() => void 0);
42649
+ const metadata = await stat19(file2).catch(() => void 0);
42385
42650
  const mode = metadata ? metadata.mode & 511 : 384;
42386
42651
  await atomic(file2, next, mode);
42387
42652
  }
42388
42653
  async function writeManifest2(jobDir, manifest) {
42389
- await atomicInPrivateDir(path53.join(jobDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
42654
+ await atomicInPrivateDir(path55.join(jobDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
42390
42655
  }
42391
42656
 
42392
42657
  // src/bridge/schedules.ts
@@ -42424,7 +42689,7 @@ var Scheduler = class {
42424
42689
  return getProjectDirs(this.store);
42425
42690
  }
42426
42691
  projectDirectory(project) {
42427
- const found = this.projectDirectories().find((directory) => path54.basename(directory).toLowerCase() === project.toLowerCase());
42692
+ const found = this.projectDirectories().find((directory) => path56.basename(directory).toLowerCase() === project.toLowerCase());
42428
42693
  if (!found) throw new BridgeError(404, `Unknown project "${project}".`);
42429
42694
  return found;
42430
42695
  }
@@ -42450,7 +42715,7 @@ var Scheduler = class {
42450
42715
  } catch {
42451
42716
  continue;
42452
42717
  }
42453
- const project = path54.basename(directory);
42718
+ const project = path56.basename(directory);
42454
42719
  for (const schedule of schedules) {
42455
42720
  const matching = runs.filter((run) => run.project === project && run.scheduleId === schedule.id);
42456
42721
  const last = matching.at(-1), running2 = matching.some((run) => runningStatuses.has(run.status));
@@ -42480,7 +42745,7 @@ var Scheduler = class {
42480
42745
  }
42481
42746
  async launchNow(projectName2, id2) {
42482
42747
  const prepared = await this.exclusive(async () => {
42483
- const projectDir = this.projectDirectory(projectName2), project = path54.basename(projectDir);
42748
+ const projectDir = this.projectDirectory(projectName2), project = path56.basename(projectDir);
42484
42749
  const file2 = await readScheduleDocument(projectDir), schedule = file2.schedules.find((item) => item.id === id2);
42485
42750
  if (!schedule) throw new BridgeError(404, `Schedule "${id2}" was not found in ${project}.`);
42486
42751
  if (!computerMatches(schedule.computer, this.computer())) throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
@@ -42594,8 +42859,8 @@ var Scheduler = class {
42594
42859
  const resume = this.launch.resume;
42595
42860
  if (this.recovered || !resume) return;
42596
42861
  this.recovered = true;
42597
- const open16 = (await readScheduleRuns(this.runsFile)).filter((run) => runningStatuses.has(run.status) && !this.own.has(run.id));
42598
- for (const run of open16) {
42862
+ const open17 = (await readScheduleRuns(this.runsFile)).filter((run) => runningStatuses.has(run.status) && !this.own.has(run.id));
42863
+ for (const run of open17) {
42599
42864
  this.own.add(run.id);
42600
42865
  let schedule;
42601
42866
  try {
@@ -42639,23 +42904,23 @@ var Scheduler = class {
42639
42904
 
42640
42905
  // src/bridge/canary.ts
42641
42906
  init_phren_paths();
42642
- import { lstat as lstat14, mkdtemp as mkdtemp4, realpath as realpath10, rm as rm7 } from "node:fs/promises";
42907
+ import { lstat as lstat14, mkdtemp as mkdtemp4, realpath as realpath11, rm as rm7 } from "node:fs/promises";
42643
42908
  import { hostname as hostname8, tmpdir } from "node:os";
42644
- import path58 from "node:path";
42909
+ import path60 from "node:path";
42645
42910
 
42646
42911
  // src/bridge/health.ts
42647
42912
  init_policy();
42648
42913
  init_phren_paths();
42649
42914
  init_store_registry();
42650
- import { execFile as execFile10, spawn as spawn8 } from "node:child_process";
42915
+ import { execFile as execFile11, spawn as spawn8 } from "node:child_process";
42651
42916
  import { lstat as lstat13, readFile as readFile26 } from "node:fs/promises";
42652
42917
  import { homedir as homedir16, hostname as hostname7 } from "node:os";
42653
- import path57 from "node:path";
42654
- import { promisify as promisify9 } from "node:util";
42918
+ import path59 from "node:path";
42919
+ import { promisify as promisify10 } from "node:util";
42655
42920
  init_protocol();
42656
42921
  init_metrics();
42657
42922
  init_terminal_tmux();
42658
- var exec9 = promisify9(execFile10);
42923
+ var exec10 = promisify10(execFile11);
42659
42924
  async function terminalHealth() {
42660
42925
  const [{ servers: servers2 }, tmux2] = await Promise.all([Promise.resolve().then(() => (init_herdr(), herdr_exports)), tmuxHealth()]);
42661
42926
  const running2 = (await servers2().catch(() => [])).map((server) => ({
@@ -42678,12 +42943,12 @@ var VERSION_TIMEOUT_MS = 3e3;
42678
42943
  var VERSION_CACHE_MS = 5 * 6e4;
42679
42944
  var PEER_TIMEOUT_MS = 5e3;
42680
42945
  var versionCache = /* @__PURE__ */ new Map();
42681
- function toolVersion(tool, executable = tool) {
42946
+ function toolVersion(tool, executable2 = tool) {
42682
42947
  const cached2 = versionCache.get(tool);
42683
42948
  if (cached2 && Date.now() - cached2.at < VERSION_CACHE_MS) return cached2.value;
42684
42949
  const value2 = new Promise((resolve11) => {
42685
42950
  let out = "", done = false;
42686
- const child = spawn8(executable, ["--version"], { cwd: homedir16(), stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
42951
+ const child = spawn8(executable2, ["--version"], { cwd: homedir16(), stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
42687
42952
  const finish = (result) => {
42688
42953
  if (!done) {
42689
42954
  done = true;
@@ -42716,7 +42981,7 @@ function plainError(value2) {
42716
42981
  async function git3(cwd, args) {
42717
42982
  try {
42718
42983
  countGit("health");
42719
- const { stdout } = await exec9("git", args, { cwd, timeout: 5e3, maxBuffer: 65536, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
42984
+ const { stdout } = await exec10("git", args, { cwd, timeout: 5e3, maxBuffer: 65536, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
42720
42985
  return stdout.trim();
42721
42986
  } catch {
42722
42987
  return void 0;
@@ -42764,7 +43029,7 @@ async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
42764
43029
  const last = runs.reduce((newest, run) => !newest || run.startedAt >= newest.startedAt ? run : newest, void 0);
42765
43030
  if (!last) return null;
42766
43031
  let name;
42767
- const directory = getProjectDirs(store).find((dir) => path57.basename(dir).toLowerCase() === last.project.toLowerCase());
43032
+ const directory = getProjectDirs(store).find((dir) => path59.basename(dir).toLowerCase() === last.project.toLowerCase());
42768
43033
  if (directory) name = (await readScheduleDocument(directory).catch(() => void 0))?.schedules.find((item) => item.id === last.scheduleId)?.name;
42769
43034
  return {
42770
43035
  ...name ? { name } : {},
@@ -42818,7 +43083,7 @@ async function probePeer(peer, caller) {
42818
43083
  }
42819
43084
  }
42820
43085
  function canaryFile(root = bridgeRoot()) {
42821
- return path57.join(root, "canary.json");
43086
+ return path59.join(root, "canary.json");
42822
43087
  }
42823
43088
  async function readCanary(root = bridgeRoot()) {
42824
43089
  try {
@@ -42831,7 +43096,7 @@ async function readCanary(root = bridgeRoot()) {
42831
43096
  }
42832
43097
  }
42833
43098
  async function pushConfigured() {
42834
- const file2 = process.env.PHREN_APNS_CONFIG || path57.join(bridgeRoot(), "apns.json");
43099
+ const file2 = process.env.PHREN_APNS_CONFIG || path59.join(bridgeRoot(), "apns.json");
42835
43100
  const info = await lstat13(file2).catch(() => void 0);
42836
43101
  return { configured: !!info?.isFile() };
42837
43102
  }
@@ -42920,7 +43185,7 @@ async function closeCanaryWorkspaces(server, before, created) {
42920
43185
  }
42921
43186
  async function conductorStep(options, server) {
42922
43187
  const before = new Set(objects((await snapshot(server)).workspaces).map((workspace) => String(workspace.workspace_id)));
42923
- const folder = await realpath10(await mkdtemp4(path58.join(tmpdir(), "phren-canary-")));
43188
+ const folder = await realpath11(await mkdtemp4(path60.join(tmpdir(), "phren-canary-")));
42924
43189
  let created, failure2, detail;
42925
43190
  try {
42926
43191
  const launched = await options.launch(server, { role: "conductor", kind: "claude", label: CANARY_LABEL, cwd: folder, timeoutMs: 45e3 });
@@ -42941,12 +43206,12 @@ async function scheduleStep(options) {
42941
43206
  let count2 = 0;
42942
43207
  const broken = [];
42943
43208
  for (const directory of getProjectDirs(options.store)) {
42944
- const present2 = await lstat14(path58.join(directory, "schedules.yaml")).catch(() => void 0);
43209
+ const present2 = await lstat14(path60.join(directory, "schedules.yaml")).catch(() => void 0);
42945
43210
  if (!present2) continue;
42946
43211
  try {
42947
43212
  count2 += (await readScheduleDocument(directory)).schedules.length;
42948
43213
  } catch (error62) {
42949
- broken.push(`${path58.basename(directory)}: ${reason(error62)}`);
43214
+ broken.push(`${path60.basename(directory)}: ${reason(error62)}`);
42950
43215
  }
42951
43216
  }
42952
43217
  const tick = options.scheduler.lastTickAt;
@@ -43016,7 +43281,7 @@ function runCanary(options) {
43016
43281
  }
43017
43282
  async function dailyCanaryEnabled(root = bridgeRoot()) {
43018
43283
  if (process.env.PHREN_CANARY_DAILY === "1") return true;
43019
- return !!(await lstat14(path58.join(root, "canary-daily")).catch(() => void 0))?.isFile();
43284
+ return !!(await lstat14(path60.join(root, "canary-daily")).catch(() => void 0))?.isFile();
43020
43285
  }
43021
43286
  async function dailyCanaryDue(root = bridgeRoot(), now = Date.now()) {
43022
43287
  if (running || !await dailyCanaryEnabled(root)) return false;
@@ -43029,11 +43294,11 @@ init_shared();
43029
43294
 
43030
43295
  // src/bridge/server-routes.ts
43031
43296
  init_zod();
43032
- import path81 from "node:path";
43297
+ import path83 from "node:path";
43033
43298
 
43034
43299
  // src/bridge/code-note.ts
43035
43300
  init_zod();
43036
- import * as path64 from "node:path";
43301
+ import * as path66 from "node:path";
43037
43302
 
43038
43303
  // src/content/validate.ts
43039
43304
  init_utils_helpers();
@@ -43047,7 +43312,7 @@ init_store_routing();
43047
43312
  init_locks();
43048
43313
  init_data_utils();
43049
43314
  import * as fs28 from "fs";
43050
- import * as path60 from "path";
43315
+ import * as path62 from "path";
43051
43316
  import * as crypto7 from "crypto";
43052
43317
 
43053
43318
  // src/project-topics.ts
@@ -43059,7 +43324,7 @@ init_data_utils();
43059
43324
  init_filenames();
43060
43325
  import * as crypto6 from "crypto";
43061
43326
  import * as fs27 from "fs";
43062
- import * as path59 from "path";
43327
+ import * as path61 from "path";
43063
43328
  var TOPIC_CONFIG_FILENAME = "topic-config.json";
43064
43329
  var SOFTWARE_TOPICS = [
43065
43330
  {
@@ -43597,7 +43862,7 @@ function topicDocHeader(project, topic) {
43597
43862
  }
43598
43863
  function appendArchivedEntriesToTopicDoc(filePath, project, topic, entries2) {
43599
43864
  if (entries2.length === 0) return;
43600
- fs27.mkdirSync(path59.dirname(filePath), { recursive: true });
43865
+ fs27.mkdirSync(path61.dirname(filePath), { recursive: true });
43601
43866
  withFileLock(filePath, () => {
43602
43867
  let existing = "";
43603
43868
  if (fs27.existsSync(filePath)) existing = fs27.readFileSync(filePath, "utf8");
@@ -43716,7 +43981,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
43716
43981
  if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
43717
43982
  const resolvedDir = storeAwareProjectPath(phrenPath, project);
43718
43983
  if (!resolvedDir || !fs28.existsSync(resolvedDir)) return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
43719
- const learningsPath = path60.join(resolvedDir, FINDINGS_FILENAME);
43984
+ const learningsPath = path62.join(resolvedDir, FINDINGS_FILENAME);
43720
43985
  if (!fs28.existsSync(learningsPath)) return phrenOk(0);
43721
43986
  const STALE_LOCK_MS = 6e5;
43722
43987
  const lockFile = runtimeFile(phrenPath, `consolidation-${project}.lock`);
@@ -43725,8 +43990,8 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
43725
43990
  } catch (e) {
43726
43991
  if (e.code === "EEXIST") {
43727
43992
  try {
43728
- const stat26 = fs28.statSync(lockFile);
43729
- if (Date.now() - stat26.mtimeMs < STALE_LOCK_MS) {
43993
+ const stat27 = fs28.statSync(lockFile);
43994
+ if (Date.now() - stat27.mtimeMs < STALE_LOCK_MS) {
43730
43995
  return phrenErr("Consolidation already running", PhrenError.LOCK_TIMEOUT);
43731
43996
  }
43732
43997
  tryUnlink(lockFile);
@@ -43752,7 +44017,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
43752
44017
  const entries2 = parseActiveEntries(content);
43753
44018
  if (entries2.length <= keepCount) return phrenOk(0);
43754
44019
  const toArchive = entries2.slice(0, entries2.length - keepCount);
43755
- const referenceDir = path60.join(resolvedDir, "reference");
44020
+ const referenceDir = path62.join(resolvedDir, "reference");
43756
44021
  const { topics } = readProjectTopics(phrenPath, project);
43757
44022
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
43758
44023
  const archivedSet = buildArchivedBulletSet(referenceDir);
@@ -44316,7 +44581,7 @@ var DEFAULT_DECAY = {
44316
44581
  var DEFAULT_UNDATED_CONFIDENCE = DEFAULT_DECAY.d120;
44317
44582
 
44318
44583
  // src/content/dedup.ts
44319
- import * as path61 from "path";
44584
+ import * as path63 from "path";
44320
44585
  init_shared();
44321
44586
  init_utils();
44322
44587
  init_store_routing();
@@ -44440,7 +44705,7 @@ function resolveCoref(text4, context) {
44440
44705
  result = result.replace(/\bthe project\b/gi, context.project);
44441
44706
  }
44442
44707
  if (context.file) {
44443
- const basename12 = path61.basename(context.file);
44708
+ const basename12 = path63.basename(context.file);
44444
44709
  result = result.replace(/\b(this file|the file)\b/gi, basename12);
44445
44710
  }
44446
44711
  if (context.project && /\b(it|this|that|they|them)\b/i.test(result)) {
@@ -44457,7 +44722,7 @@ init_shared();
44457
44722
  init_shared();
44458
44723
  init_governance();
44459
44724
  import * as fs30 from "fs";
44460
- import * as path63 from "path";
44725
+ import * as path65 from "path";
44461
44726
  import * as crypto8 from "crypto";
44462
44727
 
44463
44728
  // src/finding-graph-id.ts
@@ -44492,7 +44757,7 @@ init_store_routing();
44492
44757
  // src/finding/context.ts
44493
44758
  init_utils();
44494
44759
  import * as fs29 from "fs";
44495
- import * as path62 from "path";
44760
+ import * as path64 from "path";
44496
44761
 
44497
44762
  // src/session/utils.ts
44498
44763
  init_utils();
@@ -44574,14 +44839,14 @@ function resolveFindingTaskReference(phrenPath, project, match) {
44574
44839
  const projectDir = safeProjectPath(phrenPath, project);
44575
44840
  if (!projectDir) return { error: `Invalid project name: "${project}".` };
44576
44841
  const taskPath = resolveTaskFilePath(phrenPath, project);
44577
- const items = parseTaskItems(taskPath ?? path62.join(projectDir, "tasks.md"));
44842
+ const items = parseTaskItems(taskPath ?? path64.join(projectDir, "tasks.md"));
44578
44843
  return resolveTaskItemMatch(items, match);
44579
44844
  }
44580
44845
  function resolveAutoFindingTaskItem(phrenPath, project) {
44581
44846
  const projectDir = safeProjectPath(phrenPath, project);
44582
44847
  if (!projectDir) return void 0;
44583
44848
  const taskPath = resolveTaskFilePath(phrenPath, project);
44584
- const active = parseTaskItems(taskPath ?? path62.join(projectDir, "tasks.md")).filter(
44849
+ const active = parseTaskItems(taskPath ?? path64.join(projectDir, "tasks.md")).filter(
44585
44850
  (item) => item.section === "Active" && item.stableId
44586
44851
  );
44587
44852
  if (active.length === 1) return active[0].stableId;
@@ -44621,7 +44886,7 @@ function buildFindingCitation(citationInput, nowIso, inferredRepo, headCommit) {
44621
44886
  function resolveInferredCitationRepo(citationInput) {
44622
44887
  if (citationInput?.repo) return citationInput.repo;
44623
44888
  if (citationInput?.file) {
44624
- const fileDir = path63.dirname(citationInput.file);
44889
+ const fileDir = path65.dirname(citationInput.file);
44625
44890
  return getRepoRoot(fileDir);
44626
44891
  }
44627
44892
  return void 0;
@@ -44756,7 +45021,7 @@ function addFindingToFile(phrenPath, project, learning, citationInput, opts) {
44756
45021
  if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
44757
45022
  const resolvedDir = storeAwareProjectPath(phrenPath, project);
44758
45023
  if (!resolvedDir) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
44759
- const learningsPath = path63.join(resolvedDir, FINDINGS_FILENAME);
45024
+ const learningsPath = path65.join(resolvedDir, FINDINGS_FILENAME);
44760
45025
  const nowIso = (opts?.now ?? /* @__PURE__ */ new Date()).toISOString();
44761
45026
  const today = nowIso.slice(0, 10);
44762
45027
  const resolvedCitationInputResult = resolveFindingCitationInput(phrenPath, project, citationInput);
@@ -44938,7 +45203,7 @@ var codeNoteSchema = external_exports.object({
44938
45203
  // phone's spelling, accepted until 0.3.1.
44939
45204
  name: external_exports.string().min(1).max(4600).optional(),
44940
45205
  symbol: external_exports.string().min(1).max(4600).optional(),
44941
- file: external_exports.string().min(1).max(4096).refine((file2) => !path64.isAbsolute(file2) && !file2.includes("\0") && !file2.split(/[\\/]/).includes("..")),
45206
+ file: external_exports.string().min(1).max(4096).refine((file2) => !path66.isAbsolute(file2) && !file2.includes("\0") && !file2.split(/[\\/]/).includes("..")),
44942
45207
  line: external_exports.number().int().positive(),
44943
45208
  text: external_exports.string().trim().min(1).max(4500).refine((text4) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text4)),
44944
45209
  target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(["codex", "claude", "opencode"]) }).strict()]).optional()
@@ -44988,29 +45253,29 @@ init_utils_helpers();
44988
45253
  init_protocol();
44989
45254
  init_herdr();
44990
45255
  init_transcripts();
44991
- import { execFile as execFile11 } from "node:child_process";
44992
- import { promisify as promisify10 } from "node:util";
45256
+ import { execFile as execFile12 } from "node:child_process";
45257
+ import { promisify as promisify11 } from "node:util";
44993
45258
  import { realpathSync as realpathSync5 } from "node:fs";
44994
- import { readdir as readdir11, readFile as readFile27, stat as stat19, mkdir as mkdir15 } from "node:fs/promises";
45259
+ import { readdir as readdir12, readFile as readFile27, stat as stat20, mkdir as mkdir15 } from "node:fs/promises";
44995
45260
  import { homedir as homedir17 } from "node:os";
44996
- import path69 from "node:path";
45261
+ import path71 from "node:path";
44997
45262
 
44998
45263
  // src/core/project.ts
44999
45264
  init_shared();
45000
- import * as path67 from "path";
45265
+ import * as path69 from "path";
45001
45266
 
45002
45267
  // src/core/project-registry.ts
45003
45268
  init_phren_paths();
45004
45269
  import * as fs32 from "fs";
45005
- import * as path66 from "path";
45270
+ import * as path68 from "path";
45006
45271
 
45007
45272
  // src/git-worktree.ts
45008
45273
  import * as fs31 from "fs";
45009
- import * as path65 from "path";
45274
+ import * as path67 from "path";
45010
45275
  var WORKTREE_CONTAINER_NAMES = /* @__PURE__ */ new Set(["worktrees", ".worktrees"]);
45011
- var LINKED_WORKTREE_SEGMENT = `${path65.sep}.git${path65.sep}worktrees${path65.sep}`;
45276
+ var LINKED_WORKTREE_SEGMENT = `${path67.sep}.git${path67.sep}worktrees${path67.sep}`;
45012
45277
  function resolveWorktreeParent(dir) {
45013
- const resolved = path65.resolve(dir);
45278
+ const resolved = path67.resolve(dir);
45014
45279
  const agentParent = parentFromAgentWorktreePath(resolved);
45015
45280
  if (agentParent) return { repoRoot: agentParent, reason: "agent-worktree-dir" };
45016
45281
  const linkedParent = parentFromLinkedWorktree(resolved);
@@ -45018,23 +45283,23 @@ function resolveWorktreeParent(dir) {
45018
45283
  return null;
45019
45284
  }
45020
45285
  function parentFromAgentWorktreePath(resolved) {
45021
- const segments = resolved.split(path65.sep);
45286
+ const segments = resolved.split(path67.sep);
45022
45287
  for (let i = 1; i < segments.length; i++) {
45023
45288
  if (!WORKTREE_CONTAINER_NAMES.has(segments[i])) continue;
45024
45289
  let j = i - 1;
45025
45290
  if (!segments[j]?.startsWith(".")) continue;
45026
45291
  while (j >= 1 && segments[j].startsWith(".")) j--;
45027
45292
  if (j < 1) continue;
45028
- return segments.slice(0, j + 1).join(path65.sep) || path65.sep;
45293
+ return segments.slice(0, j + 1).join(path67.sep) || path67.sep;
45029
45294
  }
45030
45295
  return null;
45031
45296
  }
45032
45297
  function parentFromLinkedWorktree(resolved) {
45033
45298
  let current2 = resolved;
45034
45299
  while (true) {
45035
- const parent = repoRootFromGitFile(path65.join(current2, ".git"));
45300
+ const parent = repoRootFromGitFile(path67.join(current2, ".git"));
45036
45301
  if (parent) return parent;
45037
- const next = path65.dirname(current2);
45302
+ const next = path67.dirname(current2);
45038
45303
  if (next === current2) return null;
45039
45304
  current2 = next;
45040
45305
  }
@@ -45049,7 +45314,7 @@ function repoRootFromGitFile(gitPath) {
45049
45314
  }
45050
45315
  const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
45051
45316
  if (!match) return null;
45052
- const gitDir = path65.resolve(path65.dirname(gitPath), match[1].replace(/[/\\]/g, path65.sep));
45317
+ const gitDir = path67.resolve(path67.dirname(gitPath), match[1].replace(/[/\\]/g, path67.sep));
45053
45318
  const idx = gitDir.indexOf(LINKED_WORKTREE_SEGMENT);
45054
45319
  if (idx === -1) return null;
45055
45320
  return gitDir.slice(0, idx);
@@ -45202,8 +45467,8 @@ function addTermCount(terms, rawText, weight = 1) {
45202
45467
  }
45203
45468
  function maybeReadUtf8(filePath, maxBytes = 256e3) {
45204
45469
  try {
45205
- const stat26 = fs32.statSync(filePath);
45206
- if (!stat26.isFile() || stat26.size > maxBytes) return "";
45470
+ const stat27 = fs32.statSync(filePath);
45471
+ if (!stat27.isFile() || stat27.size > maxBytes) return "";
45207
45472
  return fs32.readFileSync(filePath, "utf8");
45208
45473
  } catch {
45209
45474
  return "";
@@ -45262,7 +45527,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
45262
45527
  return topics;
45263
45528
  }
45264
45529
  function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
45265
- const resolvedRoot = path66.resolve(repoRoot);
45530
+ const resolvedRoot = path68.resolve(repoRoot);
45266
45531
  if (!fs32.existsSync(resolvedRoot)) return null;
45267
45532
  const signal = {
45268
45533
  domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
@@ -45273,7 +45538,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
45273
45538
  usefulSignals: 0
45274
45539
  };
45275
45540
  const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
45276
- const packageJsonPath = path66.join(resolvedRoot, "package.json");
45541
+ const packageJsonPath = path68.join(resolvedRoot, "package.json");
45277
45542
  if (fs32.existsSync(packageJsonPath)) {
45278
45543
  signal.usefulSignals++;
45279
45544
  addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
@@ -45303,33 +45568,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
45303
45568
  debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
45304
45569
  }
45305
45570
  }
45306
- const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(path66.join(resolvedRoot, fileName)));
45571
+ const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(path68.join(resolvedRoot, fileName)));
45307
45572
  for (const configName of topLevelConfigs) {
45308
45573
  signal.usefulSignals++;
45309
45574
  const configScore = DOMAIN_CONFIG_HINTS[configName];
45310
45575
  if (configScore) addDomainScores(signal.domainScores, configScore);
45311
45576
  }
45312
45577
  const readmeCandidates = [
45313
- path66.join(resolvedRoot, "README.md"),
45314
- path66.join(resolvedRoot, "readme.md")
45578
+ path68.join(resolvedRoot, "README.md"),
45579
+ path68.join(resolvedRoot, "readme.md")
45315
45580
  ];
45316
45581
  for (const readmePath of readmeCandidates) {
45317
45582
  if (!fs32.existsSync(readmePath)) continue;
45318
45583
  const content = maybeReadUtf8(readmePath);
45319
45584
  if (!content) continue;
45320
45585
  signal.usefulSignals++;
45321
- signal.referenceHints.push(path66.relative(resolvedRoot, readmePath));
45586
+ signal.referenceHints.push(path68.relative(resolvedRoot, readmePath));
45322
45587
  addTermCount(signal.terms, content, 2);
45323
45588
  signal.docsText += ` ${content.toLowerCase()}`;
45324
45589
  break;
45325
45590
  }
45326
- const docsDir = path66.join(resolvedRoot, "docs");
45591
+ const docsDir = path68.join(resolvedRoot, "docs");
45327
45592
  if (fs32.existsSync(docsDir) && fs32.statSync(docsDir).isDirectory()) {
45328
45593
  signal.referenceHints.push("docs/");
45329
45594
  for (const entry of fs32.readdirSync(docsDir, { withFileTypes: true })) {
45330
45595
  if (!entry.isFile()) continue;
45331
45596
  if (!/\.(md|txt|rst)$/i.test(entry.name)) continue;
45332
- const docsContent = maybeReadUtf8(path66.join(docsDir, entry.name));
45597
+ const docsContent = maybeReadUtf8(path68.join(docsDir, entry.name));
45333
45598
  if (!docsContent) continue;
45334
45599
  signal.usefulSignals++;
45335
45600
  addTermCount(signal.terms, docsContent, 1);
@@ -45337,7 +45602,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
45337
45602
  }
45338
45603
  }
45339
45604
  for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
45340
- const fullPath = path66.join(resolvedRoot, folderName);
45605
+ const fullPath = path68.join(resolvedRoot, folderName);
45341
45606
  if (fs32.existsSync(fullPath)) {
45342
45607
  signal.referenceHints.push(`${folderName}/`);
45343
45608
  }
@@ -45348,14 +45613,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
45348
45613
  if (scannedFiles >= maxFiles) return;
45349
45614
  for (const entry of fs32.readdirSync(dir, { withFileTypes: true })) {
45350
45615
  if (scannedFiles >= maxFiles) return;
45351
- const fullPath = path66.join(dir, entry.name);
45616
+ const fullPath = path68.join(dir, entry.name);
45352
45617
  if (entry.isDirectory()) {
45353
45618
  if (skipDirs.has(entry.name)) continue;
45354
45619
  walk(fullPath);
45355
45620
  continue;
45356
45621
  }
45357
45622
  scannedFiles++;
45358
- const ext = path66.extname(entry.name).toLowerCase();
45623
+ const ext = path68.extname(entry.name).toLowerCase();
45359
45624
  if (!ext) continue;
45360
45625
  const extScore = EXTENSION_DOMAIN_HINTS[ext];
45361
45626
  if (extScore) {
@@ -45529,7 +45794,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
45529
45794
  return null;
45530
45795
  }
45531
45796
  };
45532
- const resolvedSource = path66.resolve(sourceRoot);
45797
+ const resolvedSource = path68.resolve(sourceRoot);
45533
45798
  for (const project of candidates) {
45534
45799
  if (sourceOf(project) === resolvedSource) return project;
45535
45800
  }
@@ -45543,7 +45808,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
45543
45808
  function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
45544
45809
  const profile = typeof opts === "string" ? opts : opts.profile;
45545
45810
  const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
45546
- const resolvedPath = path66.resolve(projectPath);
45811
+ const resolvedPath = path68.resolve(projectPath);
45547
45812
  if (!fs32.existsSync(resolvedPath)) {
45548
45813
  throw new Error(`Path does not exist: ${resolvedPath}`);
45549
45814
  }
@@ -45554,17 +45819,17 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
45554
45819
  if (worktreeRepoRoot) {
45555
45820
  debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
45556
45821
  }
45557
- const sourceRoot = isProjectLocal ? path66.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
45822
+ const sourceRoot = isProjectLocal ? path68.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
45558
45823
  if (isProjectLocal) {
45559
- const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path66.sep);
45824
+ const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path68.sep);
45560
45825
  if (!matchesWorkspace) {
45561
45826
  throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
45562
45827
  }
45563
45828
  }
45564
45829
  let claudeMdPath = null;
45565
45830
  const candidates = [
45566
- path66.join(sourceRoot, "AGENTS.md"),
45567
- path66.join(sourceRoot, ".claude", "CLAUDE.md")
45831
+ path68.join(sourceRoot, "AGENTS.md"),
45832
+ path68.join(sourceRoot, ".claude", "CLAUDE.md")
45568
45833
  ];
45569
45834
  for (const c of candidates) {
45570
45835
  if (fs32.existsSync(c)) {
@@ -45584,12 +45849,12 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
45584
45849
  `Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
45585
45850
  );
45586
45851
  }
45587
- const projDir = path66.join(phrenPath, projectName2);
45852
+ const projDir = path68.join(phrenPath, projectName2);
45588
45853
  fs32.mkdirSync(projDir, { recursive: true });
45589
45854
  const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
45590
45855
  const existingConfig = readProjectConfig(phrenPath, projectName2);
45591
45856
  const ownership = typeof opts === "string" ? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath) : opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath);
45592
- const claudePath = path66.join(projDir, "AGENTS.md");
45857
+ const claudePath = path68.join(projDir, "AGENTS.md");
45593
45858
  if (ownership !== "repo-managed") {
45594
45859
  if (claudeContent) {
45595
45860
  if (!fs32.existsSync(claudePath)) {
@@ -45624,7 +45889,7 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
45624
45889
  }
45625
45890
  }
45626
45891
  const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
45627
- const summaryPath = path66.join(projDir, "summary.md");
45892
+ const summaryPath = path68.join(projDir, "summary.md");
45628
45893
  if (!fs32.existsSync(summaryPath)) {
45629
45894
  atomicWriteText(
45630
45895
  summaryPath,
@@ -45637,18 +45902,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
45637
45902
  `
45638
45903
  );
45639
45904
  }
45640
- if (!fs32.existsSync(path66.join(projDir, FINDINGS_FILENAME))) {
45905
+ if (!fs32.existsSync(path68.join(projDir, FINDINGS_FILENAME))) {
45641
45906
  atomicWriteText(
45642
- path66.join(projDir, FINDINGS_FILENAME),
45907
+ path68.join(projDir, FINDINGS_FILENAME),
45643
45908
  `# ${projectName2} FINDINGS
45644
45909
 
45645
45910
  <!-- Bootstrapped from ${sourceRoot} -->
45646
45911
  `
45647
45912
  );
45648
45913
  }
45649
- if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(path66.join(projDir, TASKS_FILENAME))) {
45914
+ if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(path68.join(projDir, TASKS_FILENAME))) {
45650
45915
  atomicWriteText(
45651
- path66.join(projDir, TASKS_FILENAME),
45916
+ path68.join(projDir, TASKS_FILENAME),
45652
45917
  `# ${projectName2} tasks
45653
45918
 
45654
45919
  ## Active
@@ -45659,11 +45924,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
45659
45924
  `
45660
45925
  );
45661
45926
  }
45662
- if (!fs32.existsSync(path66.join(projDir, "topic-config.json"))) {
45927
+ if (!fs32.existsSync(path68.join(projDir, "topic-config.json"))) {
45663
45928
  const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
45664
45929
  const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
45665
45930
  atomicWriteText(
45666
- path66.join(projDir, "topic-config.json"),
45931
+ path68.join(projDir, "topic-config.json"),
45667
45932
  JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
45668
45933
  );
45669
45934
  }
@@ -45695,10 +45960,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
45695
45960
  if (!activeProfile.ok) return activeProfile;
45696
45961
  const writePhrenPath = options.writeToPath ?? phrenPath;
45697
45962
  const manifest = readRootManifest(phrenPath);
45698
- const resolvedPath = path67.resolve(targetPath);
45963
+ const resolvedPath = path69.resolve(targetPath);
45699
45964
  if (manifest?.installMode === "project-local") {
45700
- const workspaceRoot = path67.resolve(manifest.workspaceRoot || "");
45701
- const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path67.sep);
45965
+ const workspaceRoot = path69.resolve(manifest.workspaceRoot || "");
45966
+ const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path69.sep);
45702
45967
  if (!matchesWorkspace) {
45703
45968
  return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
45704
45969
  }
@@ -45716,9 +45981,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
45716
45981
  ownership: added.ownership,
45717
45982
  files: {
45718
45983
  claude: added.claudePath,
45719
- summary: path67.join(writePhrenPath, added.project, "summary.md"),
45720
- findings: path67.join(writePhrenPath, added.project, FINDINGS_FILENAME),
45721
- task: path67.join(writePhrenPath, added.project, TASKS_FILENAME)
45984
+ summary: path69.join(writePhrenPath, added.project, "summary.md"),
45985
+ findings: path69.join(writePhrenPath, added.project, FINDINGS_FILENAME),
45986
+ task: path69.join(writePhrenPath, added.project, TASKS_FILENAME)
45722
45987
  }
45723
45988
  });
45724
45989
  }
@@ -45744,7 +46009,7 @@ import { execFileSync as execFileSync6, spawnSync as spawnSync2 } from "child_pr
45744
46009
  import * as crypto9 from "crypto";
45745
46010
  import * as fs33 from "fs";
45746
46011
  import * as os3 from "os";
45747
- import * as path68 from "path";
46012
+ import * as path70 from "path";
45748
46013
 
45749
46014
  // src/content/summarize.ts
45750
46015
  init_phren_dotenv();
@@ -45905,7 +46170,7 @@ function mergeTasksByBid(base, ours, theirs) {
45905
46170
  // src/sync/conflict-resolve.ts
45906
46171
  function conflictStrategy(relFile) {
45907
46172
  const file2 = relFile.replace(/\\/g, "/");
45908
- const name = path68.posix.basename(file2).toLowerCase();
46173
+ const name = path70.posix.basename(file2).toLowerCase();
45909
46174
  if (isTaskFileName(name)) return "tasks";
45910
46175
  if (name === "findings.md") return "findings";
45911
46176
  if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file2)) return "archive";
@@ -45940,9 +46205,9 @@ function splitBlock(content, start, end) {
45940
46205
  function mergeText(base, ours, theirs) {
45941
46206
  if (ours === theirs || ours === base) return theirs;
45942
46207
  if (theirs === base) return ours;
45943
- const dir = fs33.mkdtempSync(path68.join(os3.tmpdir(), "phren-merge-"));
46208
+ const dir = fs33.mkdtempSync(path70.join(os3.tmpdir(), "phren-merge-"));
45944
46209
  try {
45945
- const [o, b, t] = ["ours", "base", "theirs"].map((name) => path68.join(dir, name));
46210
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path70.join(dir, name));
45946
46211
  fs33.writeFileSync(o, ours);
45947
46212
  fs33.writeFileSync(b, base);
45948
46213
  fs33.writeFileSync(t, theirs);
@@ -45955,9 +46220,9 @@ function mergeText(base, ours, theirs) {
45955
46220
  function unionText(base, ours, theirs) {
45956
46221
  const clean2 = mergeText(base, ours, theirs);
45957
46222
  if (clean2 !== null) return clean2;
45958
- const dir = fs33.mkdtempSync(path68.join(os3.tmpdir(), "phren-merge-"));
46223
+ const dir = fs33.mkdtempSync(path70.join(os3.tmpdir(), "phren-merge-"));
45959
46224
  try {
45960
- const [o, b, t] = ["ours", "base", "theirs"].map((name) => path68.join(dir, name));
46225
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path70.join(dir, name));
45961
46226
  fs33.writeFileSync(o, ours);
45962
46227
  fs33.writeFileSync(b, base);
45963
46228
  fs33.writeFileSync(t, theirs);
@@ -46017,7 +46282,7 @@ function resolveStoreConflicts(cwd) {
46017
46282
  const base = stage(cwd, 1, relFile) ?? "";
46018
46283
  const ours = stage(cwd, 2, relFile);
46019
46284
  const theirs = stage(cwd, 3, relFile);
46020
- const fullPath = path68.join(cwd, relFile);
46285
+ const fullPath = path70.join(cwd, relFile);
46021
46286
  if (ours === null && theirs === null) {
46022
46287
  unresolved.push(relFile);
46023
46288
  continue;
@@ -46028,7 +46293,7 @@ function resolveStoreConflicts(cwd) {
46028
46293
  continue;
46029
46294
  }
46030
46295
  const tmp = `${fullPath}.tmp-${crypto9.randomUUID()}`;
46031
- fs33.mkdirSync(path68.dirname(fullPath), { recursive: true });
46296
+ fs33.mkdirSync(path70.dirname(fullPath), { recursive: true });
46032
46297
  fs33.writeFileSync(tmp, merged);
46033
46298
  fs33.renameSync(tmp, fullPath);
46034
46299
  git4(cwd, ["add", "--", relFile]);
@@ -46295,7 +46560,7 @@ async function runBestEffortGit(args, cwd) {
46295
46560
  // src/bridge/enroll.ts
46296
46561
  init_metrics();
46297
46562
  init_machine_identity();
46298
- var exec10 = promisify10(execFile11);
46563
+ var exec11 = promisify11(execFile12);
46299
46564
  var runEnrollStoreGit = async (cwd, args) => {
46300
46565
  const result = await runBestEffortGit(args, cwd);
46301
46566
  return { ok: result.ok, output: result.output ?? "", error: result.error };
@@ -46308,7 +46573,7 @@ function repoName(url2) {
46308
46573
  }
46309
46574
  async function isRepository(directory) {
46310
46575
  try {
46311
- await stat19(path69.join(directory, ".git"));
46576
+ await stat20(path71.join(directory, ".git"));
46312
46577
  return true;
46313
46578
  } catch {
46314
46579
  return false;
@@ -46319,7 +46584,7 @@ async function registeredSources(env) {
46319
46584
  const paths = /* @__PURE__ */ new Set(), names = /* @__PURE__ */ new Set();
46320
46585
  let entries2 = [];
46321
46586
  try {
46322
- entries2 = (await readdir11(store, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
46587
+ entries2 = (await readdir12(store, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
46323
46588
  } catch {
46324
46589
  return { paths, names };
46325
46590
  }
@@ -46328,7 +46593,7 @@ async function registeredSources(env) {
46328
46593
  const source = readProjectConfig(store, project).sourcePath;
46329
46594
  if (typeof source === "string" && source) {
46330
46595
  try {
46331
- paths.add(realpathSync5.native(path69.resolve(source)));
46596
+ paths.add(realpathSync5.native(path71.resolve(source)));
46332
46597
  } catch {
46333
46598
  }
46334
46599
  }
@@ -46340,9 +46605,9 @@ async function candidateRepos(activity, env = process.env) {
46340
46605
  const found = [];
46341
46606
  const seen = /* @__PURE__ */ new Set();
46342
46607
  const offer = async (directory, source, lastSeen) => {
46343
- let dir = path69.resolve(directory);
46608
+ let dir = path71.resolve(directory);
46344
46609
  try {
46345
- if (!(await stat19(dir)).isDirectory()) return;
46610
+ if (!(await stat20(dir)).isDirectory()) return;
46346
46611
  dir = realpathSync5.native(dir);
46347
46612
  } catch {
46348
46613
  return;
@@ -46354,39 +46619,39 @@ async function candidateRepos(activity, env = process.env) {
46354
46619
  };
46355
46620
  const toplevel = async (directory) => {
46356
46621
  let existing = directory;
46357
- while (!await stat19(existing).catch(() => void 0)) {
46358
- const parent = path69.dirname(existing);
46622
+ while (!await stat20(existing).catch(() => void 0)) {
46623
+ const parent = path71.dirname(existing);
46359
46624
  if (parent === existing) return void 0;
46360
46625
  existing = parent;
46361
46626
  }
46362
46627
  try {
46363
46628
  countGit("enroll");
46364
- return (await exec10("git", ["-C", existing, "rev-parse", "--show-toplevel"], { env: nonInteractiveGitEnv(), timeout: 5e3 })).stdout.trim() || void 0;
46629
+ return (await exec11("git", ["-C", existing, "rev-parse", "--show-toplevel"], { env: nonInteractiveGitEnv(), timeout: 5e3 })).stdout.trim() || void 0;
46365
46630
  } catch {
46366
46631
  return void 0;
46367
46632
  }
46368
46633
  };
46369
46634
  for (const event of [...activity].reverse()) {
46370
46635
  const directory = typeof event.directory === "string" ? event.directory : void 0;
46371
- if (!directory || !path69.isAbsolute(directory)) continue;
46636
+ if (!directory || !path71.isAbsolute(directory)) continue;
46372
46637
  const root = await toplevel(directory);
46373
46638
  if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
46374
46639
  }
46375
46640
  try {
46376
- const session = JSON.parse(await readFile27(path69.join(herdrRoot(), "session.json"), "utf8"));
46641
+ const session = JSON.parse(await readFile27(path71.join(herdrRoot(), "session.json"), "utf8"));
46377
46642
  for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
46378
46643
  const directory = JSON.parse(`"${match[1]}"`);
46379
- if (!path69.isAbsolute(directory)) continue;
46644
+ if (!path71.isAbsolute(directory)) continue;
46380
46645
  const root = await toplevel(directory);
46381
46646
  if (root) await offer(root, "herdr");
46382
46647
  }
46383
46648
  } catch {
46384
46649
  }
46385
46650
  const home = homedir17();
46386
- for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path69.join(home, r))]) {
46651
+ for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path71.join(home, r))]) {
46387
46652
  let children = [];
46388
46653
  try {
46389
- children = (await readdir11(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path69.join(root, e.name));
46654
+ children = (await readdir12(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path71.join(root, e.name));
46390
46655
  } catch {
46391
46656
  continue;
46392
46657
  }
@@ -46396,13 +46661,13 @@ async function candidateRepos(activity, env = process.env) {
46396
46661
  }
46397
46662
  async function cloneRoot(env) {
46398
46663
  const home = homedir17();
46399
- for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path69.join(home, r))]) {
46664
+ for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path71.join(home, r))]) {
46400
46665
  try {
46401
- if ((await stat19(root)).isDirectory()) return root;
46666
+ if ((await stat20(root)).isDirectory()) return root;
46402
46667
  } catch {
46403
46668
  }
46404
46669
  }
46405
- const fallback = path69.join(home, "Projects");
46670
+ const fallback = path71.join(home, "Projects");
46406
46671
  await mkdir15(fallback, { recursive: true });
46407
46672
  return fallback;
46408
46673
  }
@@ -46424,7 +46689,7 @@ async function publishStore(store, project) {
46424
46689
  async function enrollProject(input2, env = process.env) {
46425
46690
  const store = phrenStoreRoot(env);
46426
46691
  try {
46427
- if (!(await stat19(path69.join(store, ".config"))).isDirectory()) throw new Error();
46692
+ if (!(await stat20(path71.join(store, ".config"))).isDirectory()) throw new Error();
46428
46693
  } catch {
46429
46694
  throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
46430
46695
  }
@@ -46435,16 +46700,16 @@ async function enrollProject(input2, env = process.env) {
46435
46700
  if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
46436
46701
  const name = repoName(url2);
46437
46702
  if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
46438
- directory = path69.join(await cloneRoot(env), name);
46703
+ directory = path71.join(await cloneRoot(env), name);
46439
46704
  try {
46440
- await stat19(directory);
46705
+ await stat20(directory);
46441
46706
  throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
46442
46707
  } catch (error62) {
46443
46708
  if (error62 instanceof BridgeError) throw error62;
46444
46709
  }
46445
46710
  try {
46446
46711
  countGit("enroll");
46447
- await exec10("git", ["clone", "--", url2, directory], { timeout: 18e4, maxBuffer: 4194304, env: nonInteractiveGitEnv(env) });
46712
+ await exec11("git", ["clone", "--", url2, directory], { timeout: 18e4, maxBuffer: 4194304, env: nonInteractiveGitEnv(env) });
46448
46713
  } catch (error62) {
46449
46714
  const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").pop() : void 0;
46450
46715
  throw new BridgeError(502, `git clone failed${detail ? `: ${detail}` : ""}.`);
@@ -46452,10 +46717,10 @@ async function enrollProject(input2, env = process.env) {
46452
46717
  cloned = true;
46453
46718
  } else if (typeof input2.directory === "string" && input2.directory) {
46454
46719
  const raw = input2.directory;
46455
- if (raw.length > 4096 || raw.includes("\0") || !path69.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
46720
+ if (raw.length > 4096 || raw.includes("\0") || !path71.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
46456
46721
  try {
46457
46722
  directory = realpathSync5.native(raw);
46458
- if (!(await stat19(directory)).isDirectory()) throw new Error();
46723
+ if (!(await stat20(directory)).isDirectory()) throw new Error();
46459
46724
  } catch {
46460
46725
  throw new BridgeError(404, "That folder is not on this computer.");
46461
46726
  }
@@ -46467,34 +46732,34 @@ async function enrollProject(input2, env = process.env) {
46467
46732
 
46468
46733
  // src/bridge/files.ts
46469
46734
  init_protocol();
46470
- import { constants as constants3 } from "node:fs";
46471
- import { lstat as lstat15, open as open12, readdir as readdir12, realpath as realpath11 } from "node:fs/promises";
46472
- import path70 from "node:path";
46735
+ import { constants as constants4 } from "node:fs";
46736
+ import { lstat as lstat15, open as open13, readdir as readdir13, realpath as realpath12 } from "node:fs/promises";
46737
+ import path72 from "node:path";
46473
46738
  var MAX_BYTES = 2097152;
46474
46739
  async function browseFiles(root, relative3) {
46475
- if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path70.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
46740
+ if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path72.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
46476
46741
  throw new BridgeError(400, "Invalid repository path.");
46477
46742
  }
46478
- const base = await realpath11(root);
46743
+ const base = await realpath12(root);
46479
46744
  let file2 = base;
46480
46745
  for (const part of relative3.split("/").filter((part2) => part2 && part2 !== ".")) {
46481
- file2 = path70.join(file2, part);
46746
+ file2 = path72.join(file2, part);
46482
46747
  if ((await lstat15(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
46483
46748
  }
46484
- const resolved = await realpath11(file2);
46485
- if (resolved !== base && !resolved.startsWith(base + path70.sep)) throw new BridgeError(403, "The path is outside this repository.");
46749
+ const resolved = await realpath12(file2);
46750
+ if (resolved !== base && !resolved.startsWith(base + path72.sep)) throw new BridgeError(403, "The path is outside this repository.");
46486
46751
  const metadata = await lstat15(resolved);
46487
46752
  if (metadata.isDirectory()) {
46488
- 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));
46753
+ 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));
46489
46754
  return {
46490
46755
  path: relative3,
46491
46756
  kind: "directory",
46492
46757
  truncated: entries2.length > 500,
46493
- entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path: path70.posix.join(relative3, entry.name), kind: entry.isDirectory() ? "directory" : "file" }))
46758
+ entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path: path72.posix.join(relative3, entry.name), kind: entry.isDirectory() ? "directory" : "file" }))
46494
46759
  };
46495
46760
  }
46496
46761
  if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
46497
- const handle = await open12(resolved, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
46762
+ const handle = await open13(resolved, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
46498
46763
  try {
46499
46764
  const current2 = await handle.stat();
46500
46765
  if (!current2.isFile() || current2.ino !== metadata.ino || current2.dev !== metadata.dev) throw new BridgeError(409, "The file changed. Refresh and try again.");
@@ -46515,9 +46780,9 @@ async function browseFiles(root, relative3) {
46515
46780
 
46516
46781
  // src/bridge/file-range.ts
46517
46782
  init_protocol();
46518
- import { constants as constants4 } from "node:fs";
46519
- import { lstat as lstat16, open as open13, realpath as realpath12 } from "node:fs/promises";
46520
- import path71 from "node:path";
46783
+ import { constants as constants5 } from "node:fs";
46784
+ import { lstat as lstat16, open as open14, realpath as realpath13 } from "node:fs/promises";
46785
+ import path73 from "node:path";
46521
46786
  var MAX_FILE_RANGE = 4 * 1024 * 1024;
46522
46787
  var types = {
46523
46788
  mp4: "video/mp4",
@@ -46554,11 +46819,11 @@ var types = {
46554
46819
  xml: "text/xml"
46555
46820
  };
46556
46821
  function fileContentType(file2) {
46557
- const ext = path71.extname(file2).slice(1).toLowerCase();
46822
+ const ext = path73.extname(file2).slice(1).toLowerCase();
46558
46823
  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");
46559
46824
  }
46560
- function version2(stat26) {
46561
- return `${stat26.dev}:${stat26.ino}:${stat26.size}:${stat26.mtimeMs}:${stat26.ctimeMs}`;
46825
+ function version2(stat27) {
46826
+ return `${stat27.dev}:${stat27.ino}:${stat27.size}:${stat27.mtimeMs}:${stat27.ctimeMs}`;
46562
46827
  }
46563
46828
  function rangeInteger(value2, fallback) {
46564
46829
  if (value2 === null) return fallback;
@@ -46571,22 +46836,22 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
46571
46836
  throw new BridgeError(400, "File ranges must be between 0 and 4 MiB.");
46572
46837
  }
46573
46838
  try {
46574
- const base = await realpath12(root);
46575
- const relative3 = path71.isAbsolute(requested) ? path71.relative(base, requested) : requested;
46576
- if (relative3 === ".." || relative3.startsWith(`..${path71.sep}`) || path71.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
46839
+ const base = await realpath13(root);
46840
+ const relative3 = path73.isAbsolute(requested) ? path73.relative(base, requested) : requested;
46841
+ if (relative3 === ".." || relative3.startsWith(`..${path73.sep}`) || path73.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
46577
46842
  let file2 = base;
46578
- for (const part of relative3.split(path71.sep).filter((part2) => part2 && part2 !== ".")) {
46579
- file2 = path71.join(file2, part);
46843
+ for (const part of relative3.split(path73.sep).filter((part2) => part2 && part2 !== ".")) {
46844
+ file2 = path73.join(file2, part);
46580
46845
  if ((await lstat16(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
46581
46846
  }
46582
- const resolved = await realpath12(file2);
46583
- if (!resolved.startsWith(base + path71.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
46847
+ const resolved = await realpath13(file2);
46848
+ if (!resolved.startsWith(base + path73.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
46584
46849
  const metadata = await lstat16(resolved);
46585
46850
  if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be opened.");
46586
- const handle = await open13(resolved, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
46851
+ const handle = await open14(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
46587
46852
  try {
46588
46853
  const current2 = await handle.stat();
46589
- if (!current2.isFile() || version2(current2) !== version2(metadata) || await realpath12(file2) !== resolved) {
46854
+ if (!current2.isFile() || version2(current2) !== version2(metadata) || await realpath13(file2) !== resolved) {
46590
46855
  throw new BridgeError(409, "The file changed. Open it again.");
46591
46856
  }
46592
46857
  const revision = version2(current2);
@@ -46622,12 +46887,12 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
46622
46887
  // src/bridge/memory-store.ts
46623
46888
  init_zod();
46624
46889
  init_protocol();
46625
- import { execFile as execFile12 } from "node:child_process";
46890
+ import { execFile as execFile13 } from "node:child_process";
46626
46891
  import { createHash as createHash15 } from "node:crypto";
46627
- 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";
46628
- import path72 from "node:path";
46629
- import { promisify as promisify11 } from "node:util";
46630
- var exec11 = promisify11(execFile12);
46892
+ 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";
46893
+ import path74 from "node:path";
46894
+ import { promisify as promisify12 } from "node:util";
46895
+ var exec12 = promisify12(execFile13);
46631
46896
  var SHA = /^[0-9a-f]{40}$/;
46632
46897
  var MAX_FILE = 4 * 1024 * 1024;
46633
46898
  var queue = Promise.resolve();
@@ -46638,7 +46903,7 @@ function serialized(work) {
46638
46903
  }
46639
46904
  async function git5(store, args, env = {}) {
46640
46905
  try {
46641
- const { stdout } = await exec11("git", ["-C", store, ...args], {
46906
+ const { stdout } = await exec12("git", ["-C", store, ...args], {
46642
46907
  env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" },
46643
46908
  maxBuffer: 64 * 1024 * 1024,
46644
46909
  timeout: 6e4
@@ -46653,12 +46918,12 @@ function blobSha(content) {
46653
46918
  return createHash15("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
46654
46919
  }
46655
46920
  async function isRepository2(store) {
46656
- return await lstat17(path72.join(store, ".git")).catch(() => void 0) !== void 0;
46921
+ return await lstat17(path74.join(store, ".git")).catch(() => void 0) !== void 0;
46657
46922
  }
46658
- function storeHead(store, indexFile = path72.join(bridgeRoot(), "store-snapshot.index")) {
46923
+ function storeHead(store, indexFile = path74.join(bridgeRoot(), "store-snapshot.index")) {
46659
46924
  return serialized(async () => {
46660
46925
  if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
46661
- await mkdir16(path72.dirname(indexFile), { recursive: true, mode: 448 });
46926
+ await mkdir16(path74.dirname(indexFile), { recursive: true, mode: 448 });
46662
46927
  const env = { GIT_INDEX_FILE: indexFile };
46663
46928
  if (!await lstat17(indexFile).catch(() => void 0)) {
46664
46929
  const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
@@ -46681,25 +46946,25 @@ async function storeTree(store, sha) {
46681
46946
  async function storeBlob(store, sha) {
46682
46947
  if (!SHA.test(sha)) throw new BridgeError(400, "Invalid blob sha.");
46683
46948
  if ((await git5(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "blob") throw new BridgeError(404, "Unknown blob.");
46684
- const { stdout } = await exec11("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE * 4 });
46949
+ const { stdout } = await exec12("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE * 4 });
46685
46950
  return { sha, encoding: "base64", content: stdout.toString("base64") };
46686
46951
  }
46687
46952
  async function storeFile(store, relative3) {
46688
- const normalized = path72.posix.normalize(relative3);
46689
- if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path72.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
46953
+ const normalized = path74.posix.normalize(relative3);
46954
+ if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path74.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
46690
46955
  throw new BridgeError(400, "Invalid store path.");
46691
46956
  }
46692
- const root = await realpath13(store);
46693
- let parent = path72.dirname(path72.join(root, normalized));
46957
+ const root = await realpath14(store);
46958
+ let parent = path74.dirname(path74.join(root, normalized));
46694
46959
  for (; ; ) {
46695
- const real = await realpath13(parent).catch(() => void 0);
46696
- if (real) {
46697
- if (real !== root && !real.startsWith(root + path72.sep)) throw new BridgeError(400, "Invalid store path.");
46960
+ const real2 = await realpath14(parent).catch(() => void 0);
46961
+ if (real2) {
46962
+ if (real2 !== root && !real2.startsWith(root + path74.sep)) throw new BridgeError(400, "Invalid store path.");
46698
46963
  break;
46699
46964
  }
46700
- parent = path72.dirname(parent);
46965
+ parent = path74.dirname(parent);
46701
46966
  }
46702
- const file2 = path72.join(root, normalized);
46967
+ const file2 = path74.join(root, normalized);
46703
46968
  const info = await lstat17(file2).catch(() => void 0);
46704
46969
  if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
46705
46970
  return file2;
@@ -46720,7 +46985,7 @@ function putStoreFile(store, data) {
46720
46985
  return serialized(async () => {
46721
46986
  const file2 = await storeFile(store, input2.path);
46722
46987
  if (await currentSha(file2) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
46723
- await mkdir16(path72.dirname(file2), { recursive: true });
46988
+ await mkdir16(path74.dirname(file2), { recursive: true });
46724
46989
  const temporary = `${file2}.phren-${process.pid}-${Date.now()}`;
46725
46990
  await writeFile8(temporary, content, { flag: "wx" });
46726
46991
  await rename7(temporary, file2);
@@ -46752,17 +47017,17 @@ init_protocol();
46752
47017
 
46753
47018
  // src/bridge/simulators.ts
46754
47019
  init_protocol();
46755
- import { execFile as execFile13 } from "node:child_process";
46756
- 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";
47020
+ import { execFile as execFile14 } from "node:child_process";
47021
+ 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";
46757
47022
  import { tmpdir as tmpdir3 } from "node:os";
46758
- import path73 from "node:path";
47023
+ import path75 from "node:path";
46759
47024
  import { createHash as createHash16, randomUUID as randomUUID17 } from "node:crypto";
46760
- import { promisify as promisify12 } from "node:util";
46761
- var exec12 = promisify12(execFile13);
47025
+ import { promisify as promisify13 } from "node:util";
47026
+ var exec13 = promisify13(execFile14);
46762
47027
  var UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
46763
47028
  async function bootedSimulators() {
46764
47029
  if (process.platform !== "darwin") return [];
46765
- const { stdout } = await exec12("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
47030
+ const { stdout } = await exec13("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
46766
47031
  let parsed = {};
46767
47032
  try {
46768
47033
  parsed = JSON.parse(stdout);
@@ -46783,9 +47048,9 @@ async function bootedSimulators() {
46783
47048
  async function simulatorScreenshot(udid) {
46784
47049
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
46785
47050
  if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
46786
- const file2 = path73.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
47051
+ const file2 = path75.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
46787
47052
  try {
46788
- await exec12("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
47053
+ await exec13("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
46789
47054
  return await readFile29(file2);
46790
47055
  } catch (error62) {
46791
47056
  if (error62 instanceof BridgeError) throw error62;
@@ -46802,18 +47067,18 @@ function helper() {
46802
47067
  return building;
46803
47068
  }
46804
47069
  async function buildHelper() {
46805
- const dir = path73.join(bridgeRoot(), "native");
46806
- const binary = path73.join(dir, "simtap");
47070
+ const dir = path75.join(bridgeRoot(), "native");
47071
+ const binary = path75.join(dir, "simtap");
46807
47072
  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");
46808
47073
  const digest2 = createHash16("sha256").update(code).digest("hex");
46809
47074
  const saved = await readFile29(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
46810
- if (await stat20(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
47075
+ if (await stat21(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
46811
47076
  await mkdir17(dir, { recursive: true, mode: 448 });
46812
- const temporary = path73.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
47077
+ const temporary = path75.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
46813
47078
  const sidecar = temporary + ".sha256";
46814
47079
  try {
46815
47080
  await writeFile9(source, code, { mode: 384, flag: "wx" });
46816
- await exec12("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
47081
+ await exec13("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
46817
47082
  throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
46818
47083
  });
46819
47084
  await chmod4(temporary, 448);
@@ -46839,7 +47104,7 @@ async function executeSimtap(name, ...args) {
46839
47104
  const binarySha = createHash16("sha256").update(await readFile29(binary)).digest("hex");
46840
47105
  if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
46841
47106
  try {
46842
- await exec12(binary, [name, ...args], { timeout: 6e4 });
47107
+ await exec13(binary, [name, ...args], { timeout: 6e4 });
46843
47108
  } catch (error62) {
46844
47109
  const failure2 = error62;
46845
47110
  const message = String(failure2?.stderr ?? failure2?.message ?? "");
@@ -46855,7 +47120,7 @@ async function simulatorAct(udid, request6) {
46855
47120
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
46856
47121
  if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready"].includes(request6.action)) throw new BridgeError(400, "Unknown simulator action.");
46857
47122
  if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
46858
- const simctl = (...args) => exec12("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
47123
+ const simctl = (...args) => exec13("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
46859
47124
  throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`);
46860
47125
  });
46861
47126
  switch (request6.action) {
@@ -46904,7 +47169,7 @@ async function deviceName(udid) {
46904
47169
  async function simulatorApps(udid) {
46905
47170
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
46906
47171
  if (process.platform !== "darwin") return [];
46907
- const { stdout } = await exec12("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
47172
+ const { stdout } = await exec13("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
46908
47173
  const apps = [];
46909
47174
  const blocks = stdout.split(/\n(?=\s{4}"[^"]+" =\s+\{)/);
46910
47175
  for (const block of blocks) {
@@ -46920,8 +47185,8 @@ init_transcripts();
46920
47185
 
46921
47186
  // src/bridge/uploads.ts
46922
47187
  init_protocol();
46923
- 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";
46924
- import path74 from "node:path";
47188
+ 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";
47189
+ import path76 from "node:path";
46925
47190
  import { randomUUID as randomUUID18 } from "node:crypto";
46926
47191
  function imageBytes(bytes) {
46927
47192
  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";
@@ -46934,24 +47199,24 @@ async function saveUpload(session, name, bytes) {
46934
47199
  let saved = "";
46935
47200
  const task = uploadQueue.catch(() => {
46936
47201
  }).then(async () => {
46937
- const root = path74.join(bridgeRoot(), "uploads");
47202
+ const root = path76.join(bridgeRoot(), "uploads");
46938
47203
  await mkdir18(root, { recursive: true, mode: 448 });
46939
47204
  let used = 0;
46940
- const directories = await readdir13(root, { withFileTypes: true });
47205
+ const directories = await readdir14(root, { withFileTypes: true });
46941
47206
  for (const dir of directories) {
46942
47207
  if (!dir.isDirectory()) continue;
46943
- const folder2 = path74.join(root, dir.name);
46944
- for (const entry of await readdir13(folder2, { withFileTypes: true })) {
47208
+ const folder2 = path76.join(root, dir.name);
47209
+ for (const entry of await readdir14(folder2, { withFileTypes: true })) {
46945
47210
  if (!entry.isFile()) continue;
46946
- const file2 = path74.join(folder2, entry.name), metadata = await lstat18(file2);
47211
+ const file2 = path76.join(folder2, entry.name), metadata = await lstat18(file2);
46947
47212
  if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink6(file2);
46948
47213
  else used += metadata.size;
46949
47214
  }
46950
47215
  }
46951
47216
  if (used + bytes.length > 268435456) throw new BridgeError(413, "Phren's image storage is full. Remove older uploads on the computer.");
46952
- const folder = path74.join(root, session);
47217
+ const folder = path76.join(root, session);
46953
47218
  await mkdir18(folder, { recursive: true, mode: 448 });
46954
- saved = path74.join(folder, `${randomUUID18()}-${name}`);
47219
+ saved = path76.join(folder, `${randomUUID18()}-${name}`);
46955
47220
  await writeFile10(saved, bytes, { flag: "wx", mode: 384 });
46956
47221
  });
46957
47222
  uploadQueue = task;
@@ -46959,23 +47224,23 @@ async function saveUpload(session, name, bytes) {
46959
47224
  return saved;
46960
47225
  }
46961
47226
  async function listUploads(session) {
46962
- const folder = path74.join(bridgeRoot(), "uploads", session);
46963
- const entries2 = await readdir13(folder, { withFileTypes: true }).catch(() => []);
47227
+ const folder = path76.join(bridgeRoot(), "uploads", session);
47228
+ const entries2 = await readdir14(folder, { withFileTypes: true }).catch(() => []);
46964
47229
  const files = [];
46965
47230
  for (const entry of entries2) {
46966
47231
  if (!entry.isFile()) continue;
46967
- const file2 = path74.join(folder, entry.name), metadata = await stat21(file2);
47232
+ const file2 = path76.join(folder, entry.name), metadata = await stat22(file2);
46968
47233
  files.push({ name: entry.name.replace(/^[0-9a-f-]{36}-/, ""), path: file2, size: metadata.size, modified: metadata.mtime.toISOString() });
46969
47234
  }
46970
47235
  return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
46971
47236
  }
46972
47237
  async function uploadImage(requested) {
46973
47238
  const missing = new BridgeError(404, "This image is not one of the phone's uploads.");
46974
- if (!requested || requested.length > 4096 || !path74.isAbsolute(requested)) throw missing;
46975
- const root = await realpath14(path74.join(bridgeRoot(), "uploads")).catch(() => void 0);
46976
- const file2 = await realpath14(requested).catch(() => void 0);
46977
- if (!root || !file2 || !file2.startsWith(root + path74.sep)) throw missing;
46978
- const metadata = await stat21(file2);
47239
+ if (!requested || requested.length > 4096 || !path76.isAbsolute(requested)) throw missing;
47240
+ const root = await realpath15(path76.join(bridgeRoot(), "uploads")).catch(() => void 0);
47241
+ const file2 = await realpath15(requested).catch(() => void 0);
47242
+ if (!root || !file2 || !file2.startsWith(root + path76.sep)) throw missing;
47243
+ const metadata = await stat22(file2);
46979
47244
  if (!metadata.isFile()) throw missing;
46980
47245
  if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
46981
47246
  const bytes = await readFile30(file2);
@@ -46988,7 +47253,7 @@ async function uploadImage(requested) {
46988
47253
  init_transcript_index();
46989
47254
  init_transcripts();
46990
47255
  import { homedir as homedir18, tmpdir as tmpdir4 } from "node:os";
46991
- import path75 from "node:path";
47256
+ import path77 from "node:path";
46992
47257
  init_protocol();
46993
47258
  var cache = /* @__PURE__ */ new Map();
46994
47259
  var modelCache = /* @__PURE__ */ new Map();
@@ -47126,7 +47391,7 @@ function describe3(tool, args) {
47126
47391
  return "";
47127
47392
  };
47128
47393
  const firstLine = (v) => v.split(/\r?\n/).map((l) => l.trim()).find((l) => l) ?? "";
47129
- const base = (v) => path75.basename(v.split(" \xB7 ")[0].trim()) || "file";
47394
+ const base = (v) => path77.basename(v.split(" \xB7 ")[0].trim()) || "file";
47130
47395
  const name = tool.toLowerCase();
47131
47396
  let value2;
47132
47397
  if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
@@ -47161,17 +47426,17 @@ init_shared();
47161
47426
 
47162
47427
  // src/bridge/server-pane-routes.ts
47163
47428
  init_zod();
47164
- import path78 from "node:path";
47429
+ import path80 from "node:path";
47165
47430
  import { setTimeout as sleep2 } from "node:timers/promises";
47166
47431
 
47167
47432
  // src/bridge/git.ts
47168
47433
  init_protocol();
47169
47434
  import { createHash as createHash17 } from "node:crypto";
47170
- import { execFile as execFile14 } from "node:child_process";
47171
- import { lstat as lstat19, readdir as readdir14, readFile as readFile31, realpath as realpath15, stat as stat22 } from "node:fs/promises";
47172
- import path76 from "node:path";
47173
- import { promisify as promisify13 } from "node:util";
47174
- var exec13 = promisify13(execFile14);
47435
+ import { execFile as execFile15 } from "node:child_process";
47436
+ import { lstat as lstat19, readdir as readdir15, readFile as readFile31, realpath as realpath16, stat as stat23 } from "node:fs/promises";
47437
+ import path78 from "node:path";
47438
+ import { promisify as promisify14 } from "node:util";
47439
+ var exec14 = promisify14(execFile15);
47175
47440
  function statusLetter(code) {
47176
47441
  const letter = code[0];
47177
47442
  return ["M", "A", "D", "R", "C", "U"].includes(letter) ? letter : "M";
@@ -47215,8 +47480,8 @@ function parseNumstat(out) {
47215
47480
  }
47216
47481
  async function countLines(root, rel) {
47217
47482
  try {
47218
- const abs = path76.join(root, await repositoryPath(root, rel));
47219
- if ((await stat22(abs)).size > 5e6) return 0;
47483
+ const abs = path78.join(root, await repositoryPath(root, rel));
47484
+ if ((await stat23(abs)).size > 5e6) return 0;
47220
47485
  const bytes = await readFile31(abs);
47221
47486
  if (!bytes.length || bytes.includes(0)) return 0;
47222
47487
  let lines = 0;
@@ -47383,7 +47648,7 @@ function checkRollup(items) {
47383
47648
  }
47384
47649
  async function currentPull(root, branch) {
47385
47650
  try {
47386
- const { stdout } = await exec13("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
47651
+ const { stdout } = await exec14("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
47387
47652
  cwd: root,
47388
47653
  timeout: 15e3,
47389
47654
  maxBuffer: 4194304,
@@ -47410,7 +47675,7 @@ async function gitPulls(cwd) {
47410
47675
  const branch = (await git2(root, "branch", "--show-current").catch(() => "")).trim();
47411
47676
  try {
47412
47677
  const [{ stdout }, current2] = await Promise.all([
47413
- exec13("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
47678
+ exec14("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
47414
47679
  cwd: root,
47415
47680
  timeout: 15e3,
47416
47681
  maxBuffer: 4194304,
@@ -47439,13 +47704,13 @@ async function gitPulls(cwd) {
47439
47704
  }
47440
47705
  }
47441
47706
  async function repositoryPath(root, raw, allowRoot = false) {
47442
- 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.");
47707
+ if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path78.isAbsolute(raw) || path78.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
47443
47708
  const segments = raw.split(/[\\/]/);
47444
47709
  if (segments.includes("..")) throw new BridgeError(400, "Invalid path.");
47445
47710
  const clean2 = segments.filter((part) => part && part !== ".").join("/");
47446
47711
  if (!clean2 && !allowRoot || clean2.startsWith("-")) throw new BridgeError(400, "Invalid path.");
47447
- const abs = path76.resolve(root, clean2);
47448
- if (abs !== root && !abs.startsWith(root + path76.sep)) throw new BridgeError(403, "This path is outside the repository.");
47712
+ const abs = path78.resolve(root, clean2);
47713
+ if (abs !== root && !abs.startsWith(root + path78.sep)) throw new BridgeError(403, "This path is outside the repository.");
47449
47714
  let existing = abs;
47450
47715
  while (true) {
47451
47716
  try {
@@ -47453,16 +47718,16 @@ async function repositoryPath(root, raw, allowRoot = false) {
47453
47718
  break;
47454
47719
  } catch (error62) {
47455
47720
  if (error62.code !== "ENOENT" || existing === root) throw new BridgeError(400, "Invalid path.");
47456
- existing = path76.dirname(existing);
47721
+ existing = path78.dirname(existing);
47457
47722
  }
47458
47723
  }
47459
47724
  let resolved;
47460
47725
  try {
47461
- resolved = await realpath15(existing);
47726
+ resolved = await realpath16(existing);
47462
47727
  } catch {
47463
47728
  throw new BridgeError(403, "This path cannot be resolved inside the repository.");
47464
47729
  }
47465
- if (resolved !== root && !resolved.startsWith(root + path76.sep)) throw new BridgeError(403, "This path is outside the repository.");
47730
+ if (resolved !== root && !resolved.startsWith(root + path78.sep)) throw new BridgeError(403, "This path is outside the repository.");
47466
47731
  return clean2;
47467
47732
  }
47468
47733
  var treeCache = /* @__PURE__ */ new Map();
@@ -47544,7 +47809,7 @@ async function ignoredEntries(root, prefix, shown) {
47544
47809
  const entries2 = /* @__PURE__ */ new Map();
47545
47810
  const inside = prefix && listing.some((item) => item.endsWith("/") && (prefix + "/").startsWith(item));
47546
47811
  if (inside) {
47547
- const dirents = await readdir14(path76.join(root, prefix), { withFileTypes: true }).catch(() => []);
47812
+ const dirents = await readdir15(path78.join(root, prefix), { withFileTypes: true }).catch(() => []);
47548
47813
  for (const dirent of dirents) {
47549
47814
  if (dirent.name === ".git" || taken.has(dirent.name) || entries2.size >= MAX_IGNORED_ENTRIES) continue;
47550
47815
  entries2.set(dirent.name, { name: dirent.name, path: `${prefix}/${dirent.name}`, kind: dirent.isDirectory() ? "dir" : "file", ignored: true });
@@ -47641,9 +47906,9 @@ init_fanouts();
47641
47906
  // src/bridge/git-worktrees.ts
47642
47907
  init_protocol();
47643
47908
  import { createHash as createHash18 } from "node:crypto";
47644
- import { realpath as realpath16, stat as stat23 } from "node:fs/promises";
47909
+ import { realpath as realpath17, stat as stat24 } from "node:fs/promises";
47645
47910
  import { homedir as homedir19 } from "node:os";
47646
- import path77 from "node:path";
47911
+ import path79 from "node:path";
47647
47912
  var MAX_WORKTREES = 64;
47648
47913
  var worktreeIdPattern = /^[a-f0-9]{32}$/;
47649
47914
  function worktreeId(abs) {
@@ -47671,8 +47936,8 @@ async function listed(root) {
47671
47936
  let main;
47672
47937
  for (const [index2, block] of blocks.entries()) {
47673
47938
  if (block.bare !== void 0 || block.prunable !== void 0) continue;
47674
- const abs = await realpath16(block.worktree).catch(() => void 0);
47675
- if (!abs || !(await stat23(abs).catch(() => void 0))?.isDirectory()) continue;
47939
+ const abs = await realpath17(block.worktree).catch(() => void 0);
47940
+ if (!abs || !(await stat24(abs).catch(() => void 0))?.isDirectory()) continue;
47676
47941
  if (index2 === 0) main = abs;
47677
47942
  const branch = block.branch?.startsWith("refs/heads/") ? block.branch.slice("refs/heads/".length) : null;
47678
47943
  worktrees.push({ abs, head: block.HEAD ?? "", branch, locked: block.locked !== void 0 });
@@ -47682,11 +47947,11 @@ async function listed(root) {
47682
47947
  }
47683
47948
  function displayPath(abs, roots) {
47684
47949
  for (const root of roots) {
47685
- const rel = path77.relative(root, abs);
47686
- if (rel && !rel.startsWith("..") && !path77.isAbsolute(rel)) return rel.split(path77.sep).join("/");
47950
+ const rel = path79.relative(root, abs);
47951
+ if (rel && !rel.startsWith("..") && !path79.isAbsolute(rel)) return rel.split(path79.sep).join("/");
47687
47952
  }
47688
47953
  const home = homedir19();
47689
- return abs === home ? "~" : abs.startsWith(home + path77.sep) ? "~/" + path77.relative(home, abs).split(path77.sep).join("/") : abs;
47954
+ return abs === home ? "~" : abs.startsWith(home + path79.sep) ? "~/" + path79.relative(home, abs).split(path79.sep).join("/") : abs;
47690
47955
  }
47691
47956
  function uncommitted(status) {
47692
47957
  const tokens = status.split("\0");
@@ -47700,12 +47965,12 @@ function uncommitted(status) {
47700
47965
  return count2;
47701
47966
  }
47702
47967
  async function workerFor(abs, workers, all = []) {
47703
- const nested = all.filter((other) => other.startsWith(abs + path77.sep));
47968
+ const nested = all.filter((other) => other.startsWith(abs + path79.sep));
47704
47969
  let best;
47705
47970
  for (const worker of workers) {
47706
- const cwd = await realpath16(worker.cwd).catch(() => path77.resolve(worker.cwd));
47707
- if (cwd !== abs && !cwd.startsWith(abs + path77.sep)) continue;
47708
- if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path77.sep))) continue;
47971
+ const cwd = await realpath17(worker.cwd).catch(() => path79.resolve(worker.cwd));
47972
+ if (cwd !== abs && !cwd.startsWith(abs + path79.sep)) continue;
47973
+ if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path79.sep))) continue;
47709
47974
  const score = (cwd === abs ? 2 : 0) + (worker.child ? 1 : 0);
47710
47975
  if (!best || score > best.score) best = { worker, score };
47711
47976
  }
@@ -47898,11 +48163,11 @@ init_terminal();
47898
48163
  init_protocol();
47899
48164
  init_herdr();
47900
48165
  init_terminal();
47901
- import { execFile as execFile15 } from "node:child_process";
47902
- import { open as open14, stat as stat24 } from "node:fs/promises";
47903
- import { promisify as promisify14 } from "node:util";
48166
+ import { execFile as execFile16 } from "node:child_process";
48167
+ import { open as open15, stat as stat25 } from "node:fs/promises";
48168
+ import { promisify as promisify15 } from "node:util";
47904
48169
  init_transcripts();
47905
- var exec14 = promisify14(execFile15);
48170
+ var exec15 = promisify15(execFile16);
47906
48171
  var MAX_DEPTH = 64;
47907
48172
  var TRANSCRIPT_TAIL_BYTES = 1048576;
47908
48173
  var MAX_OTHER_PANES = 48;
@@ -47933,8 +48198,8 @@ function attributeServers(input2) {
47933
48198
  }
47934
48199
  return result.sort((a, b) => Number(a.source === "mentioned") - Number(b.source === "mentioned") || a.port - b.port);
47935
48200
  }
47936
- async function processTable(session) {
47937
- const { stdout } = await exec14("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4e3, maxBuffer: 16777216 });
48201
+ async function processTable2(session) {
48202
+ const { stdout } = await exec15("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4e3, maxBuffer: 16777216 });
47938
48203
  const parents = /* @__PURE__ */ new Map();
47939
48204
  const runners = [];
47940
48205
  const flag = `--session-id ${session}`;
@@ -47955,12 +48220,12 @@ async function paneRoots(server, paneId) {
47955
48220
  }
47956
48221
  async function transcriptHolders(file2) {
47957
48222
  const lsof = process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof";
47958
- const { stdout } = await exec14(lsof, ["-t", "--", file2], { timeout: 3e3 }).catch(() => ({ stdout: "" }));
48223
+ const { stdout } = await exec15(lsof, ["-t", "--", file2], { timeout: 3e3 }).catch(() => ({ stdout: "" }));
47959
48224
  return stdout.split("\n").map(Number).filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid);
47960
48225
  }
47961
48226
  async function transcriptTail(file2) {
47962
- const size = (await stat24(file2)).size;
47963
- const handle = await open14(file2, "r");
48227
+ const size = (await stat25(file2)).size;
48228
+ const handle = await open15(file2, "r");
47964
48229
  try {
47965
48230
  const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
47966
48231
  const buffer = Buffer.alloc(length);
@@ -47971,14 +48236,14 @@ async function transcriptTail(file2) {
47971
48236
  }
47972
48237
  }
47973
48238
  async function sessionWebServers(target, pane) {
47974
- const [servers2, table, own2, file2] = await Promise.all([
48239
+ const [servers2, table2, own2, file2] = await Promise.all([
47975
48240
  webServers(),
47976
- processTable(target.session),
48241
+ processTable2(target.session),
47977
48242
  paneRoots(target.server, pane.pane_id),
47978
48243
  transcriptPath(target.source, target.session).catch(() => void 0)
47979
48244
  ]);
47980
- const parents = table.parents;
47981
- const ownRoots = /* @__PURE__ */ new Set([...own2, ...table.runners]);
48245
+ const parents = table2.parents;
48246
+ const ownRoots = /* @__PURE__ */ new Set([...own2, ...table2.runners]);
47982
48247
  let mentioned = /* @__PURE__ */ new Set();
47983
48248
  if (file2) {
47984
48249
  for (const pid of await transcriptHolders(file2)) ownRoots.add(pid);
@@ -48089,7 +48354,7 @@ function herdrWorktreeWorkers(s) {
48089
48354
  const workers = [];
48090
48355
  for (const pane of objects(s.panes)) {
48091
48356
  const cwd = pane.foreground_cwd || pane.cwd;
48092
- if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path78.isAbsolute(cwd)) continue;
48357
+ if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path80.isAbsolute(cwd)) continue;
48093
48358
  const name = paneAgentName(s, pane);
48094
48359
  workers.push({
48095
48360
  cwd,
@@ -48408,7 +48673,7 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
48408
48673
 
48409
48674
  // src/bridge/server-launch.ts
48410
48675
  import { mkdir as mkdir20, readFile as readFile32 } from "node:fs/promises";
48411
- import path80 from "node:path";
48676
+ import path82 from "node:path";
48412
48677
  init_zod();
48413
48678
  init_home_paths();
48414
48679
  init_herdr();
@@ -48418,15 +48683,15 @@ init_terminal();
48418
48683
  init_zod();
48419
48684
  init_utils_helpers();
48420
48685
  init_metrics();
48421
- import { execFile as execFile16 } from "node:child_process";
48422
- import { mkdir as mkdir19, realpath as realpath17, rm as rm9, stat as stat25 } from "node:fs/promises";
48423
- import path79 from "node:path";
48424
- import { promisify as promisify15 } from "node:util";
48686
+ import { execFile as execFile17 } from "node:child_process";
48687
+ import { mkdir as mkdir19, realpath as realpath18, rm as rm9, stat as stat26 } from "node:fs/promises";
48688
+ import path81 from "node:path";
48689
+ import { promisify as promisify16 } from "node:util";
48425
48690
  init_protocol();
48426
- var exec15 = promisify15(execFile16);
48691
+ var exec16 = promisify16(execFile17);
48427
48692
  async function git6(cwd, ...args) {
48428
48693
  countGit("launch-worktree");
48429
- return (await exec15("git", ["-C", cwd, "--no-pager", ...args], {
48694
+ return (await exec16("git", ["-C", cwd, "--no-pager", ...args], {
48430
48695
  timeout: 12e4,
48431
48696
  maxBuffer: 1048576,
48432
48697
  env: nonInteractiveGitEnv({ ...process.env, GIT_CONFIG_NOSYSTEM: "1" })
@@ -48449,21 +48714,21 @@ async function createLaunchWorktree(cwd, request6) {
48449
48714
  if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
48450
48715
  throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
48451
48716
  }
48452
- const worktree = path79.join(root, ".claude", "worktrees", worktreeFolderName(branch));
48453
- if (await stat25(worktree).then(() => true, () => false)) {
48717
+ const worktree = path81.join(root, ".claude", "worktrees", worktreeFolderName(branch));
48718
+ if (await stat26(worktree).then(() => true, () => false)) {
48454
48719
  throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
48455
48720
  }
48456
- await mkdir19(path79.dirname(worktree), { recursive: true });
48721
+ await mkdir19(path81.dirname(worktree), { recursive: true });
48457
48722
  try {
48458
48723
  await git6(root, "worktree", "add", "-b", branch, worktree, head);
48459
48724
  } catch (error62) {
48460
48725
  const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").at(-1) : "";
48461
48726
  throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
48462
48727
  }
48463
- const abs = await realpath17(worktree);
48464
- const inside = path79.relative(root, await realpath17(cwd));
48465
- const start = inside && !inside.startsWith("..") ? path79.join(abs, inside) : abs;
48466
- const startDir = await stat25(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
48728
+ const abs = await realpath18(worktree);
48729
+ const inside = path81.relative(root, await realpath18(cwd));
48730
+ const start = inside && !inside.startsWith("..") ? path81.join(abs, inside) : abs;
48731
+ const startDir = await stat26(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
48467
48732
  return {
48468
48733
  cwd: startDir,
48469
48734
  path: abs,
@@ -48505,10 +48770,10 @@ async function conductorBrief() {
48505
48770
  let source;
48506
48771
  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";
48507
48772
  else {
48508
- const here = path80.dirname(fileURLToPath(import.meta.url));
48773
+ const here = path82.dirname(fileURLToPath(import.meta.url));
48509
48774
  for (const candidate of [
48510
- path80.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
48511
- path80.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
48775
+ path82.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
48776
+ path82.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
48512
48777
  ]) {
48513
48778
  source = await readFile32(candidate, "utf8").catch(() => void 0);
48514
48779
  if (source !== void 0) break;
@@ -48529,15 +48794,15 @@ function effortArgs(kind, effort) {
48529
48794
  }
48530
48795
  async function prepareConductor(kind, effort, model) {
48531
48796
  const brief = await conductorBrief();
48532
- const briefDirectory = path80.join(bridgeRoot(), "conductor");
48797
+ const briefDirectory = path82.join(bridgeRoot(), "conductor");
48533
48798
  await mkdir20(briefDirectory, { recursive: true, mode: 448 });
48534
- const briefFile = path80.join(briefDirectory, "brief.md");
48799
+ const briefFile = path82.join(briefDirectory, "brief.md");
48535
48800
  if (await readFile32(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
48536
48801
  if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
48537
48802
  if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
48538
48803
  if (kind === "opencode") {
48539
- const directory = path80.join(process.env.XDG_CONFIG_HOME || path80.join(homeDir(), ".config"), "opencode", "agents");
48540
- const file2 = path80.join(directory, "conductor.md");
48804
+ const directory = path82.join(process.env.XDG_CONFIG_HOME || path82.join(homeDir(), ".config"), "opencode", "agents");
48805
+ const file2 = path82.join(directory, "conductor.md");
48541
48806
  const definition = `---
48542
48807
  description: Coordinate the owner's work across agent sessions.
48543
48808
  mode: primary
@@ -48574,7 +48839,7 @@ function herdrAgentName(label2) {
48574
48839
  }
48575
48840
  async function launchSession(server, data, options = {}) {
48576
48841
  const role = external_exports.enum(["agent", "conductor"]).default("agent").parse(data.role);
48577
- const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path80.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
48842
+ const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path82.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
48578
48843
  const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
48579
48844
  if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
48580
48845
  const label2 = plainText(200).parse(data.label);
@@ -48666,7 +48931,7 @@ async function workspaceAction(server, operation, data) {
48666
48931
  if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
48667
48932
  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.");
48668
48933
  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);
48669
- 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);
48934
+ const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path82.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
48670
48935
  if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
48671
48936
  else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
48672
48937
  else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
@@ -49038,7 +49303,7 @@ function createRouteHandler(ctx) {
49038
49303
  case "/v1/files/range": {
49039
49304
  let root;
49040
49305
  if (url2.searchParams.get("scope") === "uploads") {
49041
- root = path81.join(bridgeRoot(), "uploads");
49306
+ root = path83.join(bridgeRoot(), "uploads");
49042
49307
  } else if (url2.searchParams.has("session")) {
49043
49308
  const target = targetFromURL(url2), pane = await validateTarget(target);
49044
49309
  const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
@@ -49344,8 +49609,8 @@ init_protocol();
49344
49609
 
49345
49610
  // src/bridge/transcript-preview.ts
49346
49611
  init_codex_threads();
49347
- import { constants as constants5 } from "node:fs";
49348
- import { open as open15 } from "node:fs/promises";
49612
+ import { constants as constants6 } from "node:fs";
49613
+ import { open as open16 } from "node:fs/promises";
49349
49614
  init_protocol();
49350
49615
  init_transcript_index();
49351
49616
  init_terminal_text();
@@ -49575,11 +49840,11 @@ async function readDeltaPreview(target, file2, rollout) {
49575
49840
  if (target.source === "codex") return await codexThreadPreview(target.session) ?? (file2 && rollout ? await rollout.read(file2).catch(() => null) : null);
49576
49841
  if (target.source !== "opencode" || !file2) return null;
49577
49842
  try {
49578
- const handle = await open15(file2 + ".preview.json", constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
49843
+ const handle = await open16(file2 + ".preview.json", constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
49579
49844
  let bytes;
49580
49845
  try {
49581
- const stat26 = await handle.stat();
49582
- if (!stat26.isFile() || stat26.size > MAX_PREVIEW_BYTES) return null;
49846
+ const stat27 = await handle.stat();
49847
+ if (!stat27.isFile() || stat27.size > MAX_PREVIEW_BYTES) return null;
49583
49848
  const buffer = Buffer.alloc(MAX_PREVIEW_BYTES + 1);
49584
49849
  const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
49585
49850
  if (bytesRead > MAX_PREVIEW_BYTES) return null;
@@ -50010,7 +50275,7 @@ async function serve(version3) {
50010
50275
  await mkdir21(root, { recursive: true, mode: 448 });
50011
50276
  await chmod5(root, 448);
50012
50277
  let computerID2;
50013
- const identityFile = path82.join(root, "computer-id");
50278
+ const identityFile = path84.join(root, "computer-id");
50014
50279
  try {
50015
50280
  computerID2 = (await readFile33(identityFile, "utf8")).trim();
50016
50281
  } catch {
@@ -50060,7 +50325,7 @@ async function serve(version3) {
50060
50325
  if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
50061
50326
  function gatewayTiming() {
50062
50327
  try {
50063
- const parsed = JSON.parse(readFileSync32(path82.join(root, "gateway.json"), "utf8"));
50328
+ const parsed = JSON.parse(readFileSync32(path84.join(root, "gateway.json"), "utf8"));
50064
50329
  if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
50065
50330
  } catch {
50066
50331
  }
@@ -50106,7 +50371,7 @@ async function serve(version3) {
50106
50371
  }
50107
50372
  const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
50108
50373
  };
50109
- if (modules.has("git")) await rm10(path82.join(root, "changes-scratch"), { recursive: true, force: true });
50374
+ if (modules.has("git")) await rm10(path84.join(root, "changes-scratch"), { recursive: true, force: true });
50110
50375
  const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
50111
50376
  const { stream } = streams;
50112
50377
  const overview = overviewStream({
@@ -50253,13 +50518,13 @@ init_protocol();
50253
50518
  // src/bridge/link.ts
50254
50519
  init_profile_store();
50255
50520
  init_phren_paths();
50256
- import { execFile as execFile17 } from "node:child_process";
50521
+ import { execFile as execFile18 } from "node:child_process";
50257
50522
  import { readFile as readFile34 } from "node:fs/promises";
50258
50523
  import { homedir as homedir20, hostname as hostname10, userInfo as userInfo3 } from "node:os";
50259
- import path83 from "node:path";
50260
- import { promisify as promisify16 } from "node:util";
50524
+ import path85 from "node:path";
50525
+ import { promisify as promisify17 } from "node:util";
50261
50526
  init_protocol();
50262
- var exec16 = promisify16(execFile17);
50527
+ var exec17 = promisify17(execFile18);
50263
50528
  var REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"';
50264
50529
  var GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
50265
50530
  function sshConfigHosts(text4) {
@@ -50284,7 +50549,7 @@ function sshConfigHosts(text4) {
50284
50549
  }
50285
50550
  async function ssh(host, command, input2, timeout = 2e4) {
50286
50551
  return new Promise((resolve11, reject) => {
50287
- const child = execFile17(
50552
+ const child = execFile18(
50288
50553
  "ssh",
50289
50554
  ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", host, command],
50290
50555
  { timeout, maxBuffer: 1048576 },
@@ -50303,11 +50568,11 @@ async function probe2(host) {
50303
50568
  return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
50304
50569
  }
50305
50570
  async function discoverComputers(options = {}) {
50306
- const config3 = options.sshConfig ?? await readFile34(path83.join(homedir20(), ".ssh", "config"), "utf8").catch(() => "");
50571
+ const config3 = options.sshConfig ?? await readFile34(path85.join(homedir20(), ".ssh", "config"), "utf8").catch(() => "");
50307
50572
  const store = options.store !== void 0 ? options.store : findPhrenPath();
50308
50573
  const machines = store ? listMachines(store) : void 0;
50309
50574
  const { peers } = await optionalHookPeers();
50310
- const own2 = (await readFile34(path83.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
50575
+ const own2 = (await readFile34(path85.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
50311
50576
  const known = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
50312
50577
  const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known.has(computerLabel(host))).slice(0, 32);
50313
50578
  const [found, peerIds] = await Promise.all([
@@ -50329,13 +50594,13 @@ function slugName(value2) {
50329
50594
  async function linkComputer(host, options = {}) {
50330
50595
  const remote = await probe2(host);
50331
50596
  if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
50332
- const own2 = (await readFile34(path83.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
50597
+ const own2 = (await readFile34(path85.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
50333
50598
  if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
50334
50599
  const name = computerName.parse(options.name ?? slugName(host));
50335
50600
  const as = computerName.parse(options.as ?? slugName(hostname10()));
50336
50601
  const backAddress = options.backAddress ?? remote.client;
50337
50602
  if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
50338
- 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(" ")]));
50603
+ 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(" ")]));
50339
50604
  const remoteHostKey = publicComputerKey((await ssh(host, "cat /etc/ssh/ssh_host_ed25519_key.pub")).trim().split(/\s+/).slice(0, 2).join(" "));
50340
50605
  const localHostKey = publicComputerKey((await readFile34("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
50341
50606
  const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
@@ -50530,7 +50795,7 @@ async function readSecret(prompt) {
50530
50795
  // src/bridge/hook-main.ts
50531
50796
  init_utils_helpers();
50532
50797
  Object.assign(process.env, nonInteractiveGitEnv());
50533
- runBridge(process.argv.slice(2), "0.3.7").then((code) => {
50798
+ runBridge(process.argv.slice(2), "0.3.9").then((code) => {
50534
50799
  process.exitCode = code;
50535
50800
  }).catch((error62) => {
50536
50801
  console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");