@phren/cli 0.3.45 → 0.3.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/bridge/agent-hook-asks.d.ts +34 -0
  2. package/dist/bridge/agent-hook-asks.js +72 -0
  3. package/dist/bridge/agent-hook-callback.d.ts +22 -0
  4. package/dist/bridge/agent-hook-callback.js +114 -0
  5. package/dist/bridge/agent-hooks.d.ts +7 -74
  6. package/dist/bridge/agent-hooks.js +22 -186
  7. package/dist/bridge/claude-question-dialog.d.ts +6 -0
  8. package/dist/bridge/claude-question-dialog.js +29 -7
  9. package/dist/bridge/codex-app-server.d.ts +5 -0
  10. package/dist/bridge/codex-app-server.js +15 -0
  11. package/dist/bridge/codex-auth-refresh.js +7 -0
  12. package/dist/bridge/dispatch-command.js +7 -1
  13. package/dist/bridge/file-write.js +3 -1
  14. package/dist/bridge/git-host-auth.d.ts +6 -0
  15. package/dist/bridge/git-host-auth.js +45 -0
  16. package/dist/bridge/git-publish.d.ts +1 -1
  17. package/dist/bridge/git-publish.js +75 -8
  18. package/dist/bridge/git-review.js +23 -2
  19. package/dist/bridge/git.d.ts +5 -1
  20. package/dist/bridge/git.js +103 -8
  21. package/dist/bridge/health.d.ts +1 -0
  22. package/dist/bridge/health.js +8 -5
  23. package/dist/bridge/lookup-cache.d.ts +17 -0
  24. package/dist/bridge/lookup-cache.js +70 -0
  25. package/dist/bridge/memory-store.js +40 -14
  26. package/dist/bridge/pair.js +4 -0
  27. package/dist/bridge/peers.js +36 -0
  28. package/dist/bridge/projects.d.ts +14 -0
  29. package/dist/bridge/projects.js +48 -1
  30. package/dist/bridge/prompt-deliveries.d.ts +38 -3
  31. package/dist/bridge/prompt-deliveries.js +196 -36
  32. package/dist/bridge/schedule-format.d.ts +4 -0
  33. package/dist/bridge/schedule-format.js +34 -0
  34. package/dist/bridge/schedule-problems.js +4 -0
  35. package/dist/bridge/scoped-gateway.d.ts +1 -0
  36. package/dist/bridge/scoped-gateway.js +10 -1
  37. package/dist/bridge/server-launch.js +6 -2
  38. package/dist/bridge/session-servers.js +3 -0
  39. package/dist/bridge/{codex-thread-origin.d.ts → thread-origin.d.ts} +8 -0
  40. package/dist/bridge/{codex-thread-origin.js → thread-origin.js} +24 -6
  41. package/dist/bridge/usage.d.ts +4 -0
  42. package/dist/bridge/usage.js +22 -8
  43. package/dist/bridge-hook.mjs +1137 -468
  44. package/dist/cli/namespaces-tasks.js +19 -5
  45. package/dist/cli/ops.d.ts +1 -1
  46. package/dist/cli/ops.js +2 -2
  47. package/dist/cli/schedules.js +16 -9
  48. package/dist/content/summarize.js +46 -6
  49. package/dist/content/validate.d.ts +3 -1
  50. package/dist/content/validate.js +33 -4
  51. package/dist/data/access.d.ts +8 -1
  52. package/dist/data/access.js +27 -9
  53. package/dist/data/notes.d.ts +2 -0
  54. package/dist/data/notes.js +2 -1
  55. package/dist/entrypoint.js +2 -1
  56. package/dist/generated/memory-ui-graph.browser.js +1 -1
  57. package/dist/governance/locks.js +17 -1
  58. package/dist/governance/policy.js +37 -23
  59. package/dist/memory-ui-graph.runtime.js +1 -1
  60. package/dist/sync/conflict-resolve.d.ts +1 -1
  61. package/dist/sync/conflict-resolve.js +91 -8
  62. package/dist/task/lifecycle.js +2 -1
  63. package/package.json +1 -1
@@ -20016,21 +20016,21 @@ function visit(schema, fnOrHandlers) {
20016
20016
  case "object": {
20017
20017
  const oldShape = def.shape;
20018
20018
  const keys2 = Object.keys(oldShape);
20019
- let changed2 = false;
20019
+ let changed = false;
20020
20020
  const newShape = {};
20021
20021
  for (const k2 of keys2) {
20022
20022
  const mapped = run4(oldShape[k2]);
20023
20023
  if (mapped !== oldShape[k2])
20024
- changed2 = true;
20024
+ changed = true;
20025
20025
  newShape[k2] = mapped;
20026
20026
  }
20027
20027
  let newCatchall = def.catchall;
20028
20028
  if (def.catchall) {
20029
20029
  newCatchall = run4(def.catchall);
20030
20030
  if (newCatchall !== def.catchall)
20031
- changed2 = true;
20031
+ changed = true;
20032
20032
  }
20033
- return changed2 ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s;
20033
+ return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s;
20034
20034
  }
20035
20035
  case "array": {
20036
20036
  const mapped = run4(def.element);
@@ -20038,21 +20038,21 @@ function visit(schema, fnOrHandlers) {
20038
20038
  }
20039
20039
  case "tuple": {
20040
20040
  const oldItems = def.items;
20041
- let changed2 = false;
20041
+ let changed = false;
20042
20042
  const newItems = [];
20043
20043
  for (const item of oldItems) {
20044
20044
  const mapped = run4(item);
20045
20045
  if (mapped !== item)
20046
- changed2 = true;
20046
+ changed = true;
20047
20047
  newItems.push(mapped);
20048
20048
  }
20049
20049
  let newRest = def.rest;
20050
20050
  if (def.rest) {
20051
20051
  newRest = run4(def.rest);
20052
20052
  if (newRest !== def.rest)
20053
- changed2 = true;
20053
+ changed = true;
20054
20054
  }
20055
- return changed2 ? clone(s, { ...def, items: newItems, rest: newRest }) : s;
20055
+ return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s;
20056
20056
  }
20057
20057
  case "record":
20058
20058
  case "map": {
@@ -20066,15 +20066,15 @@ function visit(schema, fnOrHandlers) {
20066
20066
  }
20067
20067
  case "union": {
20068
20068
  const oldOptions = def.options;
20069
- let changed2 = false;
20069
+ let changed = false;
20070
20070
  const newOptions = [];
20071
20071
  for (const opt of oldOptions) {
20072
20072
  const mapped = run4(opt);
20073
20073
  if (mapped !== opt)
20074
- changed2 = true;
20074
+ changed = true;
20075
20075
  newOptions.push(mapped);
20076
20076
  }
20077
- return changed2 ? clone(s, { ...def, options: newOptions }) : s;
20077
+ return changed ? clone(s, { ...def, options: newOptions }) : s;
20078
20078
  }
20079
20079
  case "intersection": {
20080
20080
  const newLeft = run4(def.left);
@@ -24366,7 +24366,18 @@ ${Math.random()}`;
24366
24366
  }
24367
24367
  };
24368
24368
  } catch (err) {
24369
- if (err.code !== "EEXIST") throw err;
24369
+ const code = err.code;
24370
+ if (process.platform === "win32" && (code === "EPERM" || code === "EACCES" || code === "EBUSY")) {
24371
+ let present2 = true;
24372
+ try {
24373
+ fs3.statSync(lockPath);
24374
+ } catch (statErr) {
24375
+ present2 = statErr.code !== "ENOENT";
24376
+ }
24377
+ if (present2) return null;
24378
+ throw err;
24379
+ }
24380
+ if (code !== "EEXIST") throw err;
24370
24381
  try {
24371
24382
  const contents = fs3.readFileSync(lockPath, "utf8");
24372
24383
  const pid = Number.parseInt(contents.split("\n")[0], 10);
@@ -26309,6 +26320,74 @@ var init_locate = __esm({
26309
26320
  }
26310
26321
  });
26311
26322
 
26323
+ // src/bridge/lookup-cache.ts
26324
+ var LookupCache;
26325
+ var init_lookup_cache = __esm({
26326
+ "src/bridge/lookup-cache.ts"() {
26327
+ "use strict";
26328
+ init_protocol();
26329
+ LookupCache = class {
26330
+ constructor(ttl, maxAge = 3e5, limit = 64, available = () => true, pendingTimeout = 45e3, revokes = () => false) {
26331
+ this.ttl = ttl;
26332
+ this.maxAge = maxAge;
26333
+ this.limit = limit;
26334
+ this.available = available;
26335
+ this.pendingTimeout = pendingTimeout;
26336
+ this.revokes = revokes;
26337
+ }
26338
+ ttl;
26339
+ maxAge;
26340
+ limit;
26341
+ available;
26342
+ pendingTimeout;
26343
+ revokes;
26344
+ entries = /* @__PURE__ */ new Map();
26345
+ invalidate(matches) {
26346
+ for (const key4 of this.entries.keys()) if (matches(key4)) this.entries.delete(key4);
26347
+ }
26348
+ get(key4, read) {
26349
+ let entry2 = this.entries.get(key4);
26350
+ if (!entry2) {
26351
+ entry2 = {};
26352
+ this.entries.set(key4, entry2);
26353
+ if (this.entries.size > this.limit) this.entries.delete(this.entries.keys().next().value);
26354
+ }
26355
+ const cached3 = entry2.value;
26356
+ const age = cached3 ? Date.now() - cached3.at : Infinity;
26357
+ const available = cached3 && this.available(cached3.data);
26358
+ const ttl = available ? this.ttl : 5e3;
26359
+ const maxAge = available ? this.maxAge : 5e3;
26360
+ if (cached3 && age < ttl) return Promise.resolve(cached3.data);
26361
+ if (!entry2.pending) {
26362
+ const current2 = entry2;
26363
+ let timer;
26364
+ const timeout = new Promise((_2, reject) => {
26365
+ timer = setTimeout(() => reject(new BridgeError(504, "Lookup did not finish within the request time limit.", { code: "lookup-timeout" })), this.pendingTimeout);
26366
+ });
26367
+ const pending = Promise.race([Promise.resolve().then(read), timeout]).then((data) => {
26368
+ if (this.entries.get(key4) === current2 && current2.pending === pending) {
26369
+ const previous = current2.value;
26370
+ const keepSuccess = previous && this.available(previous.data) && !this.available(data) && !this.revokes(data) && Date.now() - previous.at < this.maxAge;
26371
+ if (!keepSuccess) current2.value = { data, at: Date.now() };
26372
+ }
26373
+ return data;
26374
+ }).finally(() => {
26375
+ clearTimeout(timer);
26376
+ if (current2.pending === pending) current2.pending = void 0;
26377
+ });
26378
+ entry2.pending = pending;
26379
+ }
26380
+ if (cached3 && age < maxAge && !this.revokes(cached3.data)) {
26381
+ void entry2.pending.catch(() => {
26382
+ });
26383
+ return Promise.resolve(cached3.data);
26384
+ }
26385
+ return entry2.pending;
26386
+ }
26387
+ };
26388
+ }
26389
+ });
26390
+
26312
26391
  // src/bridge/metrics.ts
26313
26392
  var MAX_NAMES, NAME, HookMetrics, hookMetrics, countHerdr, countIdentity, countGit, countTick;
26314
26393
  var init_metrics = __esm({
@@ -26423,6 +26502,12 @@ async function withGitReadDeadline(read) {
26423
26502
  await Promise.allSettled([...budget.pending]);
26424
26503
  }
26425
26504
  }
26505
+ function withoutGitReadDeadline(read) {
26506
+ return gitReadBudget.exit(read);
26507
+ }
26508
+ function withIndependentGitReadDeadline(read) {
26509
+ return gitReadBudget.exit(() => withGitReadDeadline(read));
26510
+ }
26426
26511
  function checkoutGitEnv() {
26427
26512
  const env = nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" });
26428
26513
  for (const key4 of ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_PREFIX"]) delete env[key4];
@@ -26653,9 +26738,14 @@ function probe(port, host) {
26653
26738
  const finish = (value2) => {
26654
26739
  if (!settled3) {
26655
26740
  settled3 = true;
26741
+ clearTimeout(deadline);
26656
26742
  resolve17(value2);
26657
26743
  }
26658
26744
  };
26745
+ const deadline = setTimeout(() => {
26746
+ finish(null);
26747
+ req.destroy();
26748
+ }, 1200);
26659
26749
  const req = request({ hostname: host, port, path: "/", method: "GET", timeout: 1200, headers: { Host: `localhost:${port}` } }, (res) => {
26660
26750
  let body2 = "";
26661
26751
  res.on("data", (data) => {
@@ -26709,6 +26799,18 @@ async function listenersFromSs(ports) {
26709
26799
  }
26710
26800
  }
26711
26801
  async function webServers() {
26802
+ const servers2 = await serversCache.get("listeners", scanWebServers);
26803
+ if (!servers2.some((server) => server.pid !== void 0) || Date.now() - (scanStarted.get(servers2) ?? 0) < LISTENER_TRUST_MS) return servers2;
26804
+ const live = await readListeners().catch(() => void 0);
26805
+ if (!live) return servers2.map(({ pid: _pid, ...server }) => ({ ...server, unverified: true }));
26806
+ const kept = servers2.filter((server) => server.pid === void 0 || live.get(listenerKey(server))?.pid === server.pid);
26807
+ if (kept.length !== servers2.length) serversCache.invalidate(() => true);
26808
+ return kept;
26809
+ }
26810
+ function listenerKey(server) {
26811
+ return `${server.origin.includes("[::1]") ? "[::1]" : "127.0.0.1"}:${server.port}`;
26812
+ }
26813
+ async function readListeners() {
26712
26814
  const ports = /* @__PURE__ */ new Map();
26713
26815
  const readers = process.platform === "linux" ? [listenersFromSs, listenersFromLsof] : [listenersFromLsof, listenersFromSs];
26714
26816
  let lastError;
@@ -26722,6 +26824,11 @@ async function webServers() {
26722
26824
  }
26723
26825
  }
26724
26826
  if (lastError && ports.size === 0) throw new BridgeError(503, "No socket listing tool found: install lsof (or iproute2's ss on Linux).");
26827
+ return ports;
26828
+ }
26829
+ async function scanWebServers() {
26830
+ const started = Date.now();
26831
+ const ports = await readListeners();
26725
26832
  const candidates = [...ports.values()].sort((a, b) => Number(a.port >= EPHEMERAL_PORT) - Number(b.port >= EPHEMERAL_PORT) || a.port - b.port).slice(0, 64);
26726
26833
  const found = [];
26727
26834
  for (let i = 0; i < candidates.length; i += 8) {
@@ -26730,7 +26837,9 @@ async function webServers() {
26730
26837
  if (name !== null) found.push({ ...server, name });
26731
26838
  }));
26732
26839
  }
26733
- return found.sort((a, b) => a.port - b.port);
26840
+ const listing = found.sort((a, b) => a.port - b.port);
26841
+ scanStarted.set(listing, started);
26842
+ return listing;
26734
26843
  }
26735
26844
  async function launchDirectory(raw, activity = [], located = []) {
26736
26845
  if (typeof raw !== "string" || raw.length > 4096 || !path17.isAbsolute(raw) || /[\x00-\x1f\x7f]/.test(raw)) throw new BridgeError(400, "Invalid workspace directory.");
@@ -26755,7 +26864,7 @@ async function launchDirectory(raw, activity = [], located = []) {
26755
26864
  }
26756
26865
  throw new BridgeError(403, "Workspace directory must be under home or a located project.");
26757
26866
  }
26758
- var exec, gitReadBudget, GIT_READ_MS, gitTimeout, BRANCH_FRESH_MS, BRANCH_MAX_MS, branches, ENTITIES, LISTEN_HOST, EPHEMERAL_PORT;
26867
+ var exec, gitReadBudget, GIT_READ_MS, gitTimeout, BRANCH_FRESH_MS, BRANCH_MAX_MS, branches, ENTITIES, LISTEN_HOST, EPHEMERAL_PORT, serversCache, scanStarted, LISTENER_TRUST_MS;
26759
26868
  var init_projects = __esm({
26760
26869
  "src/bridge/projects.ts"() {
26761
26870
  "use strict";
@@ -26764,6 +26873,7 @@ var init_projects = __esm({
26764
26873
  init_transcripts();
26765
26874
  init_locate();
26766
26875
  init_protocol();
26876
+ init_lookup_cache();
26767
26877
  init_metrics();
26768
26878
  exec = promisify(execFile);
26769
26879
  gitReadBudget = new AsyncLocalStorage();
@@ -26775,6 +26885,9 @@ var init_projects = __esm({
26775
26885
  ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
26776
26886
  LISTEN_HOST = /^(\*|127\.0\.0\.1|localhost|0\.0\.0\.0|\[::\]|\[::1\]|::|::1)$/;
26777
26887
  EPHEMERAL_PORT = 32768;
26888
+ serversCache = new LookupCache(1e4, 3e5, 1, () => true, 2e4);
26889
+ scanStarted = /* @__PURE__ */ new WeakMap();
26890
+ LISTENER_TRUST_MS = 1e3;
26778
26891
  }
26779
26892
  });
26780
26893
 
@@ -27719,8 +27832,8 @@ function boundedValue(value2, depth, cap) {
27719
27832
  if (value2 && typeof value2 === "object") {
27720
27833
  const out = /* @__PURE__ */ Object.create(null);
27721
27834
  for (const [key4, item] of Object.entries(value2).slice(0, 64)) {
27722
- const bounded = boundedValue(item, depth + 1, cap);
27723
- if (bounded !== void 0) out[key4] = bounded;
27835
+ const bounded2 = boundedValue(item, depth + 1, cap);
27836
+ if (bounded2 !== void 0) out[key4] = bounded2;
27724
27837
  }
27725
27838
  return out;
27726
27839
  }
@@ -29689,7 +29802,7 @@ var init_tab_activity = __esm({
29689
29802
  await this.load();
29690
29803
  const prefix = JSON.stringify(server) + ":";
29691
29804
  const seen = /* @__PURE__ */ new Set(), times = /* @__PURE__ */ new Map();
29692
- let changed2 = false;
29805
+ let changed = false;
29693
29806
  for (const tab of objects(snapshot2.tabs)) {
29694
29807
  const tabKey = tabActivityKey(tab.workspace_id, tab.tab_id), key4 = prefix + tabKey;
29695
29808
  seen.add(key4);
@@ -29699,17 +29812,17 @@ var init_tab_activity = __esm({
29699
29812
  if (stamp2?.signature !== signature) {
29700
29813
  stamp2 = { signature, lastChangedAt: at2 };
29701
29814
  this.entries.set(key4, stamp2);
29702
- changed2 = true;
29815
+ changed = true;
29703
29816
  }
29704
29817
  times.set(tabKey, stamp2.lastChangedAt);
29705
29818
  }
29706
29819
  for (const key4 of this.entries.keys()) {
29707
29820
  if (key4.startsWith(prefix) && !seen.has(key4)) {
29708
29821
  this.entries.delete(key4);
29709
- changed2 = true;
29822
+ changed = true;
29710
29823
  }
29711
29824
  }
29712
- this.dirty ||= changed2;
29825
+ this.dirty ||= changed;
29713
29826
  await this.persist();
29714
29827
  return times;
29715
29828
  });
@@ -32179,7 +32292,7 @@ var require_websocket = __commonJS({
32179
32292
  var http = __require("http");
32180
32293
  var net2 = __require("net");
32181
32294
  var tls = __require("tls");
32182
- var { randomBytes: randomBytes10, createHash: createHash31 } = __require("crypto");
32295
+ var { randomBytes: randomBytes10, createHash: createHash32 } = __require("crypto");
32183
32296
  var { Duplex: Duplex2, Readable: Readable2 } = __require("stream");
32184
32297
  var { URL: URL2 } = __require("url");
32185
32298
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -32860,7 +32973,7 @@ var require_websocket = __commonJS({
32860
32973
  abortHandshake(websocket, socket, "Invalid Upgrade header");
32861
32974
  return;
32862
32975
  }
32863
- const digest2 = createHash31("sha1").update(key4 + GUID).digest("base64");
32976
+ const digest2 = createHash32("sha1").update(key4 + GUID).digest("base64");
32864
32977
  if (res.headers["sec-websocket-accept"] !== digest2) {
32865
32978
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
32866
32979
  return;
@@ -33229,7 +33342,7 @@ var require_websocket_server = __commonJS({
33229
33342
  var EventEmitter2 = __require("events");
33230
33343
  var http = __require("http");
33231
33344
  var { Duplex: Duplex2 } = __require("stream");
33232
- var { createHash: createHash31 } = __require("crypto");
33345
+ var { createHash: createHash32 } = __require("crypto");
33233
33346
  var extension2 = require_extension();
33234
33347
  var PerMessageDeflate2 = require_permessage_deflate();
33235
33348
  var subprotocol2 = require_subprotocol();
@@ -33536,7 +33649,7 @@ var require_websocket_server = __commonJS({
33536
33649
  );
33537
33650
  }
33538
33651
  if (this._state > RUNNING) return abortHandshake(socket, 503);
33539
- const digest2 = createHash31("sha1").update(key4 + GUID).digest("base64");
33652
+ const digest2 = createHash32("sha1").update(key4 + GUID).digest("base64");
33540
33653
  const headers = [
33541
33654
  "HTTP/1.1 101 Switching Protocols",
33542
33655
  "Upgrade: websocket",
@@ -33694,6 +33807,8 @@ import path28 from "node:path";
33694
33807
  async function spawnAppServer(options) {
33695
33808
  const env = { ...options.replaceEnv ? {} : process.env, ...options.env ?? {}, ...options.codexHome ? { CODEX_HOME: options.codexHome } : {} };
33696
33809
  const codexBin = options.codexBin ?? codexExecutable(env);
33810
+ const known2 = unixListenUnsupported.get(codexBin);
33811
+ if (known2) throw new AppServerUnsupportedError(known2);
33697
33812
  await mkdir7(path28.dirname(options.socketPath), { recursive: true, mode: 448 });
33698
33813
  await rm4(options.socketPath, { force: true });
33699
33814
  const log2 = options.logFile ? await open8(options.logFile, "a", 384) : void 0;
@@ -33728,6 +33843,12 @@ async function spawnAppServer(options) {
33728
33843
  while (true) {
33729
33844
  if (failure2) throw new Error(`codex app-server could not start: ${failure2.message}`);
33730
33845
  if (child.exitCode !== null || child.signalCode !== null) {
33846
+ const detail = await why();
33847
+ if (/unsupported --listen URL/.test(detail)) {
33848
+ const message = `this codex build cannot listen on a unix socket (needs a newer codex)${detail}`;
33849
+ unixListenUnsupported.set(codexBin, message);
33850
+ throw new AppServerUnsupportedError(message);
33851
+ }
33731
33852
  throw new Error(`codex app-server exited before ${options.socketPath} was ready (${child.exitCode ?? child.signalCode})${await why()}`);
33732
33853
  }
33733
33854
  if (await socketAccepts(options.socketPath)) break;
@@ -33839,7 +33960,7 @@ function declineResult(method) {
33839
33960
  return {};
33840
33961
  }
33841
33962
  }
33842
- var STARTUP_TIMEOUT_MS, STARTUP_POLL_MS, DEFAULT_REQUEST_TIMEOUT_MS, KILL_GRACE_MS, AppServerRpcError, AppServerConnection;
33963
+ var STARTUP_TIMEOUT_MS, STARTUP_POLL_MS, DEFAULT_REQUEST_TIMEOUT_MS, KILL_GRACE_MS, AppServerRpcError, AppServerUnsupportedError, unixListenUnsupported, AppServerConnection;
33843
33964
  var init_codex_app_server = __esm({
33844
33965
  "src/bridge/codex-app-server.ts"() {
33845
33966
  "use strict";
@@ -33860,6 +33981,9 @@ var init_codex_app_server = __esm({
33860
33981
  code;
33861
33982
  method;
33862
33983
  };
33984
+ AppServerUnsupportedError = class extends Error {
33985
+ };
33986
+ unixListenUnsupported = /* @__PURE__ */ new Map();
33863
33987
  AppServerConnection = class {
33864
33988
  constructor(ws2) {
33865
33989
  this.ws = ws2;
@@ -34742,8 +34866,15 @@ function claudeQuestionDialog(text5) {
34742
34866
  }
34743
34867
  async function answerClaudeQuestionDialog(io, questions, answers, options = {}) {
34744
34868
  const from = options.from ?? 0, submit = options.submit ?? true;
34869
+ let sent = false;
34870
+ const changed = (message) => refusal(message, sent);
34871
+ const realKeys = io.keys.bind(io);
34872
+ io = { ...io, keys: async (keys2) => {
34873
+ sent = true;
34874
+ await realKeys(keys2);
34875
+ } };
34745
34876
  const sleep5 = io.sleep ?? ((ms2) => new Promise((resolve17) => setTimeout(resolve17, ms2)));
34746
- const matches = (screen, index2) => screen?.kind === "question" && screen.title === normalize(questions[index2].question);
34877
+ const matches = (screen, index2) => screen?.kind === "question" && sameTitle(screen.title, questions[index2].question);
34747
34878
  const settle2 = async (check2, ms2 = 2e3) => {
34748
34879
  for (let waited = 0; ; waited += 120) {
34749
34880
  const value2 = check2(claudeQuestionDialog(await io.read()));
@@ -34757,8 +34888,8 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
34757
34888
  if (initial.tabs.length !== questions.length) throw changed("The terminal is asking a different set of questions.");
34758
34889
  const reach = async (index2) => {
34759
34890
  const screen = await settle2((value2) => value2);
34760
- if (screen?.kind === "question" && screen.title === normalize(questions[index2].question)) return screen;
34761
- const at2 = screen?.kind === "review" ? questions.length : screen?.kind === "question" ? questions.findIndex((question2) => normalize(question2.question) === screen.title) : -1;
34891
+ if (screen?.kind === "question" && sameTitle(screen.title, questions[index2].question)) return screen;
34892
+ const at2 = screen?.kind === "review" ? questions.length : screen?.kind === "question" ? questions.findIndex((question2) => sameTitle(screen.title, question2.question)) : -1;
34762
34893
  if (at2 < 0) throw changed("The terminal is showing a different question.");
34763
34894
  if (screen?.kind === "question" && screen.other && screen.cursor === screen.other.number) await io.keys(["up"]);
34764
34895
  await io.keys(Array(Math.abs(index2 - at2)).fill(index2 > at2 ? "right" : "left"));
@@ -34772,7 +34903,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
34772
34903
  if (!question2) throw new BridgeError(400, "The answer names a question that was not asked.");
34773
34904
  const typed = answer.text?.trim() ?? "";
34774
34905
  let screen = await reach(index2);
34775
- if (screen.multiSelect !== !!question2.multiSelect || screen.options.length !== question2.options.length || screen.options.some((row, position) => row.label !== question2.options[position].label.trim())) {
34906
+ if (screen.multiSelect !== !!question2.multiSelect || screen.options.length !== question2.options.length || screen.options.some((row, position) => !sameLabel(row.label, question2.options[position].label))) {
34776
34907
  throw changed("The terminal's options differ from the question being answered.");
34777
34908
  }
34778
34909
  if (!screen.multiSelect) {
@@ -34821,14 +34952,13 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
34821
34952
  const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0, ANSWERED_MS);
34822
34953
  if (review === "gone") return;
34823
34954
  if (!review) throw changed("The terminal did not reach the review of the answers.");
34824
- const expected = questions.map((question2) => normalize(question2.question));
34825
- if (review.answers.length !== questions.length || review.answers.some((row, position) => normalize(row.question) !== expected[position] || !row.answer)) {
34955
+ if (review.answers.length !== questions.length || review.answers.some((row, position) => !sameTitle(normalize(row.question), questions[position].question) || !row.answer)) {
34826
34956
  throw changed("Not every question has an answer in the terminal.");
34827
34957
  }
34828
34958
  await io.keys(["1"]);
34829
34959
  if (await settle2((value2) => value2 === void 0 ? "gone" : void 0, ANSWERED_MS) !== "gone") throw changed("The terminal did not submit the answers.");
34830
34960
  }
34831
- var TAB_BAR, ROW, NEXT, normalize, GUTTER, changed, typedKeys;
34961
+ var TAB_BAR, ROW, NEXT, normalize, sameTitle, sameLabel, GUTTER, refusal, typedKeys;
34832
34962
  var init_claude_question_dialog = __esm({
34833
34963
  "src/bridge/claude-question-dialog.ts"() {
34834
34964
  "use strict";
@@ -34837,8 +34967,17 @@ var init_claude_question_dialog = __esm({
34837
34967
  ROW = /^\s*(❯)?\s*(\d)\.\s+(?:\[([ ✔])\]\s+)?(.*?)\s*$/;
34838
34968
  NEXT = /^\s*(❯)?\s+(?:Next|Submit)\s*$/;
34839
34969
  normalize = (text5) => text5.replace(/\s+/g, " ").trim();
34970
+ sameTitle = (shown, asked) => {
34971
+ const want = normalize(asked);
34972
+ if (shown === want) return true;
34973
+ return shown.endsWith("\u2026") && shown.length > 200 && want.startsWith(shown.slice(0, -1).trimEnd());
34974
+ };
34975
+ sameLabel = (shown, asked) => {
34976
+ const want = normalize(asked);
34977
+ return shown === want || shown.length >= 30 && want.startsWith(shown);
34978
+ };
34840
34979
  GUTTER = /^(\s*)│(?: |$)/;
34841
- changed = (message) => new BridgeError(409, `${message} Nothing else was sent; check the question and answer again, or cancel it.`);
34980
+ refusal = (message, sent) => sent ? new BridgeError(409, `${message} Some keys were already sent, so check the terminal before answering again, or cancel the question.`, { code: "question-unconfirmed" }) : new BridgeError(409, `${message} Nothing was sent; check the question and answer again, or cancel it.`, { code: "question-not-shown" });
34842
34981
  typedKeys = (text5) => [...text5].map((character) => character === " " ? "space" : character);
34843
34982
  }
34844
34983
  });
@@ -36200,7 +36339,7 @@ function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged, co
36200
36339
  children: objects(s.tabs).filter((t) => t.workspace_id === w.workspace_id).map((t) => {
36201
36340
  const panes2 = objects(s.panes).filter((p) => p.tab_id === t.tab_id && p.workspace_id === t.workspace_id);
36202
36341
  const agent = panes2.find((p) => p.agent);
36203
- const changed2 = Math.max(0, ...panes2.map((p) => Number.isSafeInteger(p.state_change_seq) ? Number(p.state_change_seq) : 0));
36342
+ const changed = Math.max(0, ...panes2.map((p) => Number.isSafeInteger(p.state_change_seq) ? Number(p.state_change_seq) : 0));
36204
36343
  return {
36205
36344
  id: t.tab_id,
36206
36345
  label: t.label,
@@ -36210,7 +36349,7 @@ function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged, co
36210
36349
  agentStatus: t.agent_status,
36211
36350
  cwd: agent?.foreground_cwd || agent?.cwd,
36212
36351
  role: (conductorPane2 === void 0 ? isConductorName(paneAgentName(s, agent)) : !!agent && agent.pane_id === conductorPane2) ? "conductor" : void 0,
36213
- changedSeq: changed2 || void 0,
36352
+ changedSeq: changed || void 0,
36214
36353
  lastChangedAt: lastChanged?.get(tabActivityKey(t.workspace_id, t.tab_id)),
36215
36354
  approvalPending: panes2.some((p) => approvalPanes?.has(String(p.pane_id))) || void 0,
36216
36355
  contextUsedPercent: agent && panes2.filter((p) => p.agent).length === 1 ? contextUsedPercent?.get(agent) : void 0,
@@ -37861,7 +38000,7 @@ var init_package_metadata = __esm({
37861
38000
  __dirname = path37.dirname(fileURLToPath2(import.meta.url));
37862
38001
  ROOT = path37.join(__dirname, "..");
37863
38002
  PACKAGE_JSON_PATH = path37.join(ROOT, "package.json");
37864
- BUNDLED_VERSION = true ? "0.3.45" : "0.0.0";
38003
+ BUNDLED_VERSION = true ? "0.3.46" : "0.0.0";
37865
38004
  PACKAGE_JSON = readPackageJson();
37866
38005
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
37867
38006
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -40371,6 +40510,14 @@ function settleClaudeUsage(usage, now) {
40371
40510
  const since = usage.updatedAt?.slice(0, 10);
40372
40511
  return { ...usage, windows, message: `No usage report from Claude on this computer${since ? ` since ${since}` : ""}. It updates when Claude Code runs here.` };
40373
40512
  }
40513
+ function bounded(read, fallback2, ms2 = USAGE_READ_LIMIT_MS) {
40514
+ let timer;
40515
+ const late = new Promise((resolve17) => {
40516
+ timer = setTimeout(() => resolve17(fallback2()), ms2);
40517
+ timer.unref?.();
40518
+ });
40519
+ return Promise.race([read, late]).finally(() => clearTimeout(timer));
40520
+ }
40374
40521
  function usageStatusLine(current2, program, remove) {
40375
40522
  const prefix = `${quote2(process.execPath)} ${quote2(program)} usage-statusline `;
40376
40523
  const command = object2(current2).command;
@@ -40417,7 +40564,7 @@ async function captureClaudeUsage(original) {
40417
40564
  });
40418
40565
  }
40419
40566
  }
40420
- var exec7, claudeFile, safeText, openCodeAuthFile, GO_GATEWAY, GO_KEY_MESSAGE, GO_WINDOWS, openCodeLogDir, refusalScans, FIRST_SCAN_BYTES, clock, goPlanCached, goPlanPending, claudeCredentialsFile, isCreditWindow, CLAUDE_REPORT_MAX_AGE_MS, OPENCODE_STATS_REUSE_MS, AccountUsageReader, quote2;
40567
+ var exec7, claudeFile, safeText, openCodeAuthFile, GO_GATEWAY, GO_KEY_MESSAGE, GO_WINDOWS, openCodeLogDir, refusalScans, FIRST_SCAN_BYTES, clock, goPlanCached, goPlanPending, claudeCredentialsFile, isCreditWindow, CLAUDE_REPORT_MAX_AGE_MS, OPENCODE_STATS_REUSE_MS, USAGE_READ_LIMIT_MS, unanswered, AccountUsageReader, quote2;
40421
40568
  var init_usage = __esm({
40422
40569
  "src/bridge/usage.ts"() {
40423
40570
  "use strict";
@@ -40453,6 +40600,8 @@ var init_usage = __esm({
40453
40600
  isCreditWindow = (window2) => window2.id.startsWith("credit:");
40454
40601
  CLAUDE_REPORT_MAX_AGE_MS = 3 * 864e5;
40455
40602
  OPENCODE_STATS_REUSE_MS = 10 * 6e4;
40603
+ USAGE_READ_LIMIT_MS = 3e4;
40604
+ unanswered = (source, name) => ({ source, windows: [], message: `${name} did not answer in time on this computer. Phren will ask again shortly.` });
40456
40605
  AccountUsageReader = class {
40457
40606
  constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = (now2) => readOpenCodeUsage("opencode", now2), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage, readCopilot = readCopilotUsage, platform = process.platform, readElevenLabs = liveElevenLabsUsage, readAuth = (home) => claudeAuthStatus(home)) {
40458
40607
  this.readCodex = readCodex;
@@ -40496,7 +40645,7 @@ var init_usage = __esm({
40496
40645
  /** Codex and every Claude home, without the spend readers: what a dispatch capacity probe asks. */
40497
40646
  async limits(allAccounts = true) {
40498
40647
  if (!this.cached || this.now() - this.cached.at >= 6e4) {
40499
- this.pending ??= this.readCodex().then((value2) => {
40648
+ this.pending ??= bounded(this.readCodex(), () => unanswered("codex", "Codex")).then((value2) => {
40500
40649
  this.cached = { at: this.now(), value: value2 };
40501
40650
  return value2;
40502
40651
  }).finally(() => {
@@ -40509,7 +40658,7 @@ var init_usage = __esm({
40509
40658
  const now = new Date(this.now());
40510
40659
  const email3 = claudeAccountEmail(home);
40511
40660
  const credits = claudeCredits(home.id);
40512
- const auth = credits.length || claudePlanUnknown(home) ? await this.readAuth(home).catch(() => void 0) : void 0;
40661
+ const auth = credits.length || claudePlanUnknown(home) ? await bounded(this.readAuth(home).catch(() => void 0), () => void 0) : void 0;
40513
40662
  const fallback2 = auth?.console ? "Console" : auth?.plan ? claudePlan({ subscriptionType: auth.plan }) : void 0;
40514
40663
  const subscription2 = claudeAccountSubscription(home, now, fallback2);
40515
40664
  const usage = settleClaudeUsage(await this.claude(home), this.now());
@@ -40529,10 +40678,10 @@ var init_usage = __esm({
40529
40678
  if (!this.spendingPending.has(key4)) {
40530
40679
  const pending = Promise.all([
40531
40680
  this.openCode(at2),
40532
- this.readOpenCodeGo(new Date(at2)),
40533
- this.readOpenRouter(new Date(at2)),
40534
- includeCopilot ? this.readCopilot(new Date(at2)) : Promise.resolve(void 0),
40535
- includeElevenLabs ? this.readElevenLabs(new Date(at2)).catch(() => void 0) : Promise.resolve(void 0)
40681
+ bounded(this.readOpenCodeGo(new Date(at2)), () => unanswered("opencode-go", "OpenCode Go")),
40682
+ bounded(this.readOpenRouter(new Date(at2)), () => void 0),
40683
+ includeCopilot ? bounded(this.readCopilot(new Date(at2)), () => unanswered("copilot", "GitHub Copilot")) : Promise.resolve(void 0),
40684
+ includeElevenLabs ? bounded(this.readElevenLabs(new Date(at2)).catch(() => void 0), () => void 0) : Promise.resolve(void 0)
40536
40685
  ]).then(([openCode, openCodeGo, openRouter, copilot, elevenLabs2]) => [openCode, openCodeGo, ...openRouter ? [openRouter] : [], ...copilot ? [copilot] : [], ...elevenLabs2 ? [elevenLabs2] : []]).then((value2) => {
40537
40686
  this.spendingCached.set(key4, { at: at2, value: value2 });
40538
40687
  return value2;
@@ -40547,8 +40696,12 @@ var init_usage = __esm({
40547
40696
  /** One `opencode stats` run serves every spending key for `OPENCODE_STATS_REUSE_MS`. */
40548
40697
  openCode(at2) {
40549
40698
  if (this.openCodeCached && at2 - this.openCodeCached.at < OPENCODE_STATS_REUSE_MS) return Promise.resolve(this.openCodeCached.value);
40550
- this.openCodePending ??= this.readOpenCode(new Date(at2)).then((value2) => {
40551
- this.openCodeCached = { at: at2, value: value2 };
40699
+ let late = false;
40700
+ this.openCodePending ??= bounded(this.readOpenCode(new Date(at2)), () => {
40701
+ late = true;
40702
+ return unanswered("opencode", "opencode stats");
40703
+ }).then((value2) => {
40704
+ if (!late) this.openCodeCached = { at: at2, value: value2 };
40552
40705
  return value2;
40553
40706
  }).finally(() => {
40554
40707
  this.openCodePending = void 0;
@@ -40564,7 +40717,7 @@ var init_usage = __esm({
40564
40717
  const cached3 = this.claudeCached.get(home.dir);
40565
40718
  if (!cached3 || this.now() - cached3.at >= 6e4) {
40566
40719
  const at2 = this.now();
40567
- if (!this.claudePending.has(home.dir)) this.claudePending.set(home.dir, this.readClaudeLive(new Date(at2), home).then((value2) => {
40720
+ if (!this.claudePending.has(home.dir)) this.claudePending.set(home.dir, bounded(this.readClaudeLive(new Date(at2), home), () => void 0).then((value2) => {
40568
40721
  this.claudeCached.set(home.dir, { at: at2, value: value2 });
40569
40722
  return value2;
40570
40723
  }).catch(() => {
@@ -40643,9 +40796,9 @@ async function mergeMcpServers(file4, servers2) {
40643
40796
  async function syncAccountMcpServers(env = process.env) {
40644
40797
  const homes = claudeHomes(env);
40645
40798
  const servers2 = await mcpServersOf(homes[0].configFile);
40646
- const changed2 = [];
40647
- for (const home of homes.slice(1)) if (await mergeMcpServers(home.configFile, servers2)) changed2.push(home.id);
40648
- return changed2;
40799
+ const changed = [];
40800
+ for (const home of homes.slice(1)) if (await mergeMcpServers(home.configFile, servers2)) changed.push(home.id);
40801
+ return changed;
40649
40802
  }
40650
40803
  async function addClaudeAccount(slug, opts = {}) {
40651
40804
  const env = opts.env ?? process.env;
@@ -41398,7 +41551,7 @@ function keyOptions(line) {
41398
41551
  return void 0;
41399
41552
  }
41400
41553
  function upgradeKeys(text5) {
41401
- let changed2 = 0;
41554
+ let changed = 0;
41402
41555
  const result = text5.split(/(?<=\n)/).map((line) => {
41403
41556
  const parsed = keyOptions(line);
41404
41557
  if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest)) return line;
@@ -41407,10 +41560,10 @@ function upgradeKeys(text5) {
41407
41560
  const options = parsed.options.filter((option) => option.toLowerCase() !== "port-forwarding" && !option.toLowerCase().startsWith("permitopen=")).map((option) => old.test(option) ? forcedCommand : option);
41408
41561
  if (!options.includes("pty")) options.splice(1, 0, "pty");
41409
41562
  const next = options.join(",") + parsed.rest;
41410
- if (next !== line) changed2++;
41563
+ if (next !== line) changed++;
41411
41564
  return next;
41412
41565
  }).join("");
41413
- return { text: result, changed: changed2 };
41566
+ return { text: result, changed };
41414
41567
  }
41415
41568
  async function extraLaunchAgentEnvironment(file4, read = async (f) => (await exec8("plutil", ["-convert", "json", "-o", "-", f])).stdout) {
41416
41569
  let parsed;
@@ -42097,6 +42250,33 @@ async function hookPeers(root = bridgeRoot()) {
42097
42250
  }
42098
42251
  async function addHookPeer(input2, root = bridgeRoot()) {
42099
42252
  const peer = peerSchema.parse(input2);
42253
+ return lockedHooksYaml(root, () => addHookPeerNow(peer, root));
42254
+ }
42255
+ async function lockedHooksYaml(root, work) {
42256
+ const file4 = path55.join(path55.resolve(root), "hooks.yaml");
42257
+ const previous = hooksYamlQueues.get(file4) ?? Promise.resolve();
42258
+ const next = previous.catch(() => void 0).then(async () => {
42259
+ const deadline = Date.now() + HOOKS_YAML_LOCK_WAIT_MS;
42260
+ let release = tryFileLock(file4);
42261
+ while (!release) {
42262
+ if (Date.now() >= deadline) throw new BridgeError(409, "hooks.yaml is being changed by another process. Try again.");
42263
+ await new Promise((resolve17) => setTimeout(resolve17, 50));
42264
+ release = tryFileLock(file4);
42265
+ }
42266
+ try {
42267
+ return await work();
42268
+ } finally {
42269
+ release();
42270
+ }
42271
+ });
42272
+ hooksYamlQueues.set(file4, next);
42273
+ try {
42274
+ return await next;
42275
+ } finally {
42276
+ if (hooksYamlQueues.get(file4) === next) hooksYamlQueues.delete(file4);
42277
+ }
42278
+ }
42279
+ async function addHookPeerNow(peer, root) {
42100
42280
  const existing = await hookPeers(root).catch((error62) => {
42101
42281
  if (error62 instanceof BridgeError && error62.details?.hooksYaml === "missing") return [];
42102
42282
  throw error62;
@@ -42242,12 +42422,13 @@ async function peerRequest(peer, route2, data, timeout) {
42242
42422
  await rm8(temporary, { recursive: true, force: true });
42243
42423
  }
42244
42424
  }
42245
- var peerSchema, lastPeerError;
42425
+ var peerSchema, hooksYamlQueues, HOOKS_YAML_LOCK_WAIT_MS, lastPeerError;
42246
42426
  var init_peers = __esm({
42247
42427
  "src/bridge/peers.ts"() {
42248
42428
  "use strict";
42249
42429
  init_js_yaml();
42250
42430
  init_zod();
42431
+ init_locks();
42251
42432
  init_logger();
42252
42433
  init_client();
42253
42434
  init_computers();
@@ -42260,6 +42441,8 @@ var init_peers = __esm({
42260
42441
  hostKey: external_exports.string().transform(publicComputerKey),
42261
42442
  server: serverName.default("default")
42262
42443
  }).strict();
42444
+ hooksYamlQueues = /* @__PURE__ */ new Map();
42445
+ HOOKS_YAML_LOCK_WAIT_MS = 5e3;
42263
42446
  }
42264
42447
  });
42265
42448
 
@@ -42537,6 +42720,7 @@ var init_schedule_format = __esm({
42537
42720
  init_zod();
42538
42721
  init_protocol();
42539
42722
  init_utils_paths();
42723
+ init_locks();
42540
42724
  init_claude_accounts();
42541
42725
  SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
42542
42726
  SCHEDULE_HARNESSES = ["claude", "codex", "opencode", "copilot"];
@@ -42564,6 +42748,9 @@ import { stat as stat15 } from "node:fs/promises";
42564
42748
  import path57 from "node:path";
42565
42749
  async function scheduleProblems(schedule, project, options) {
42566
42750
  const problems = [];
42751
+ if ((schedule.prompt.match(/[\p{L}\p{N}]/gu) ?? []).length < 3) {
42752
+ problems.push("The prompt has no words in it, so every run would start with an empty brief. Set a prompt with --prompt or --prompt-file.");
42753
+ }
42567
42754
  const machines = listMachines(options.store);
42568
42755
  if (!options.owned && machines.ok && !Object.keys(machines.data).some((name) => canonicalComputer(name) === canonicalComputer(schedule.computer))) {
42569
42756
  problems.push(`Computer "${schedule.computer}" is not a machine in this store, so no Hook will run this schedule.`);
@@ -44749,8 +44936,8 @@ async function readIntegrator() {
44749
44936
  }
44750
44937
  async function setIntegrator(input2) {
44751
44938
  if (input2 === null) {
44752
- const { rm: rm19 } = await import("node:fs/promises");
44753
- await rm19(path62.join(bridgeRoot(), "integrator.json"), { force: true });
44939
+ const { rm: rm18 } = await import("node:fs/promises");
44940
+ await rm18(path62.join(bridgeRoot(), "integrator.json"), { force: true });
44754
44941
  return { ok: true, integrator: null };
44755
44942
  }
44756
44943
  const data = integratorSchema.parse(input2);
@@ -44982,11 +45169,11 @@ function approvalSummary(value2) {
44982
45169
  requestKind = "tool";
44983
45170
  } else {
44984
45171
  const patch = string4(input2.patch) ?? (typeof value2.input === "string" ? value2.input : void 0);
44985
- const changed2 = patch ? new Set([...patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$|^diff --git a\/(.+?) b\/(.+)$/gm)].map((match) => match[1] ?? match[3])).size : 0;
45172
+ const changed = patch ? new Set([...patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$|^diff --git a\/(.+?) b\/(.+)$/gm)].map((match) => match[1] ?? match[3])).size : 0;
44986
45173
  const file4 = string4(input2.file_path) ?? string4(input2.filePath) ?? string4(input2.path);
44987
- if (changed2 > 1) line = `Apply patch: ${changed2} files`;
45174
+ if (changed > 1) line = `Apply patch: ${changed} files`;
44988
45175
  else if (file4 && /(?:edit|write|patch|apply)/i.test(tool)) line = `${/write/i.test(tool) || /\*\*\* Add File:/.test(patch ?? "") ? "Write" : "Edit"}: ${relativeFile(file4, value2.cwd)}`;
44989
- else if (changed2 === 1 && patch) {
45176
+ else if (changed === 1 && patch) {
44990
45177
  const match = /^\*\*\* (Add|Update|Delete) File: (.+)$/m.exec(patch);
44991
45178
  line = match ? `${match[1] === "Add" ? "Write" : "Edit"}: ${relativeFile(match[2], value2.cwd)}` : "Apply patch: 1 file";
44992
45179
  }
@@ -46308,7 +46495,7 @@ function observeApproval(receipt, value2, now) {
46308
46495
  function observeState(receipt, parsed, now) {
46309
46496
  let seen = parsed;
46310
46497
  const at2 = new Date(now).toISOString();
46311
- let changed2 = false;
46498
+ let changed = false;
46312
46499
  if (seen.session && receipt.target && !("session" in receipt.target)) {
46313
46500
  const full2 = targetSchema.safeParse({
46314
46501
  server: receipt.target.server,
@@ -46320,7 +46507,7 @@ function observeState(receipt, parsed, now) {
46320
46507
  });
46321
46508
  if (full2.success) {
46322
46509
  receipt.target = full2.data;
46323
- changed2 = true;
46510
+ changed = true;
46324
46511
  }
46325
46512
  }
46326
46513
  const carried = seen.state === "working" && receipt.worker && receipt.worker.state !== "working" ? 0 : receipt.worker?.background ?? 0;
@@ -46348,18 +46535,18 @@ function observeState(receipt, parsed, now) {
46348
46535
  if (repeated) {
46349
46536
  if (receipt.worker && receipt.worker.sawWorking !== sawWorking) {
46350
46537
  receipt.worker.sawWorking = sawWorking;
46351
- changed2 = true;
46538
+ changed = true;
46352
46539
  }
46353
46540
  if (receipt.worker && background > (receipt.worker.background ?? 0)) {
46354
46541
  receipt.worker.background = background;
46355
- changed2 = true;
46542
+ changed = true;
46356
46543
  }
46357
46544
  if (receipt.worker && receipt.worker.waitingSince !== waitingSince) {
46358
46545
  if (waitingSince) receipt.worker.waitingSince = waitingSince;
46359
46546
  else delete receipt.worker.waitingSince;
46360
- changed2 = true;
46547
+ changed = true;
46361
46548
  }
46362
- return changed2;
46549
+ return changed;
46363
46550
  }
46364
46551
  receipt.worker = {
46365
46552
  state: next,
@@ -46681,9 +46868,9 @@ var init_dispatch_returns = __esm({
46681
46868
  const seen = await this.grantAnswered(receipt, workers[index2]);
46682
46869
  let fresh;
46683
46870
  const current2 = await updateReceipt(receipt.id, (value2) => {
46684
- const before = value2.approval?.actionId, changed2 = observe(value2, seen, this.now());
46871
+ const before = value2.approval?.actionId, changed = observe(value2, seen, this.now());
46685
46872
  if (value2.approval && value2.approval.actionId !== before) fresh = value2.approval;
46686
- return changed2;
46873
+ return changed;
46687
46874
  }).catch(() => void 0);
46688
46875
  if (!fresh || !current2) continue;
46689
46876
  const pushed = await Promise.resolve(this.onApproval?.(current2, fresh)).catch(() => void 0);
@@ -48735,10 +48922,12 @@ function unionTrailing(ourTrailing, theirTrailing) {
48735
48922
  function significantLines(content) {
48736
48923
  return content.split("\n").slice(1).map((line) => line.trim()).filter((line) => line !== "").filter((line) => !(line.startsWith("## ") && /^\d{4}-\d{2}-\d{2}$/.test(line.slice(3).trim())));
48737
48924
  }
48738
- function mergeFindings(ours, theirs) {
48739
- const { text: text5, dedupedContinuations } = buildMergedFindings(ours, theirs);
48925
+ function mergeFindings(ours, theirs, base) {
48926
+ const removed = base === void 0 ? /* @__PURE__ */ new Map() : removedFindings(base, ours, theirs);
48927
+ const { text: text5, dedupedContinuations } = buildMergedFindings(ours, theirs, removed);
48928
+ const removedLines = new Set([...removed.values()].flatMap((block) => block.split("\n").map((line) => line.trim())));
48740
48929
  const present2 = new Set(text5.split("\n").map((line) => line.trim()));
48741
- const lost = [...significantLines(ours), ...significantLines(theirs)].filter((line) => !present2.has(line)).filter((line) => !dedupedContinuations.has(line));
48930
+ const lost = [...significantLines(ours), ...significantLines(theirs)].filter((line) => !present2.has(line)).filter((line) => !dedupedContinuations.has(line)).filter((line) => !removedLines.has(line));
48742
48931
  if (lost.length > 0) {
48743
48932
  throw new FindingsMergeLossError(
48744
48933
  `Refusing to auto-merge ${FINDINGS_FILENAME}: ${lost.length} line(s) would be dropped, starting with "${lost[0].slice(0, 80)}". Resolve this conflict by hand.`
@@ -48746,7 +48935,20 @@ function mergeFindings(ours, theirs) {
48746
48935
  }
48747
48936
  return text5;
48748
48937
  }
48749
- function buildMergedFindings(ours, theirs) {
48938
+ function removedFindings(base, ours, theirs) {
48939
+ const blocks = (content) => {
48940
+ const byKey = /* @__PURE__ */ new Map();
48941
+ for (const list of parseFindings(content).dates.values()) for (const block of list) byKey.set(findingBulletText(block), block);
48942
+ return byKey;
48943
+ };
48944
+ const [b, o, t] = [blocks(base), blocks(ours), blocks(theirs)];
48945
+ const removed = /* @__PURE__ */ new Map();
48946
+ for (const [key4, block] of b) {
48947
+ if (!o.has(key4) && t.get(key4) === block || !t.has(key4) && o.get(key4) === block) removed.set(key4, block);
48948
+ }
48949
+ return removed;
48950
+ }
48951
+ function buildMergedFindings(ours, theirs, removed = /* @__PURE__ */ new Map()) {
48750
48952
  const ourSide = parseFindings(ours);
48751
48953
  const theirSide = parseFindings(theirs);
48752
48954
  const allDates = [.../* @__PURE__ */ new Set([...ourSide.dates.keys(), ...theirSide.dates.keys()])].sort().reverse();
@@ -48760,6 +48962,7 @@ function buildMergedFindings(ours, theirs) {
48760
48962
  const merged = [];
48761
48963
  for (const block of [...ourSide.dates.get(date5) ?? [], ...theirSide.dates.get(date5) ?? []]) {
48762
48964
  const key4 = findingBulletText(block);
48965
+ if (removed.has(key4)) continue;
48763
48966
  if (seen.has(key4)) {
48764
48967
  for (const line of block.split("\n").slice(1)) {
48765
48968
  const trimmed = line.trim();
@@ -49239,7 +49442,8 @@ var init_task_format = __esm({
49239
49442
  // src/bridge/memory-store.ts
49240
49443
  import { execFile as execFile16, spawn as spawn8 } from "node:child_process";
49241
49444
  import { createHash as createHash21 } from "node:crypto";
49242
- import { lstat as lstat21, mkdir as mkdir21, readFile as readFile35, realpath as realpath11, rename as rename6, rm as rm11, writeFile as writeFile6 } from "node:fs/promises";
49445
+ import { mkdirSync as mkdirSync16, readFileSync as readFileSync32, renameSync as renameSync9, unlinkSync as unlinkSync6, writeFileSync as writeFileSync14 } from "node:fs";
49446
+ import { lstat as lstat21, mkdir as mkdir21, realpath as realpath11 } from "node:fs/promises";
49243
49447
  import path75 from "node:path";
49244
49448
  import { promisify as promisify14 } from "node:util";
49245
49449
  function serialized2(work) {
@@ -49416,12 +49620,21 @@ async function storeFile(store, relative5) {
49416
49620
  if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
49417
49621
  return file4;
49418
49622
  }
49419
- async function currentSha(file4) {
49420
- const content = await readFile35(file4).catch((error62) => {
49623
+ function lockedStoreFile(file4, rel, work) {
49624
+ try {
49625
+ withFileLock(file4, work);
49626
+ } catch (error62) {
49627
+ if (error62 instanceof BridgeError || !/could not acquire lock/.test(String(error62?.message))) throw error62;
49628
+ throw new BridgeError(409, `${rel} is being written on this computer (its lock is held). Try again.`);
49629
+ }
49630
+ }
49631
+ function currentShaSync(file4) {
49632
+ try {
49633
+ return blobSha(readFileSync32(file4));
49634
+ } catch (error62) {
49421
49635
  if (error62.code === "ENOENT") return null;
49422
49636
  throw error62;
49423
- });
49424
- return content === null ? null : blobSha(content);
49637
+ }
49425
49638
  }
49426
49639
  function putStoreFile(store, data) {
49427
49640
  const input2 = putSchema.parse(data);
@@ -49429,11 +49642,13 @@ function putStoreFile(store, data) {
49429
49642
  if (content.length > MAX_FILE) throw new BridgeError(413, "This file is too large for the phone to write.");
49430
49643
  return serialized2(async () => {
49431
49644
  const file4 = await storeFile(store, input2.path);
49432
- if (await currentSha(file4) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
49433
- await mkdir21(path75.dirname(file4), { recursive: true });
49434
- const temporary = `${file4}.phren-${process.pid}-${Date.now()}`;
49435
- await writeFile6(temporary, content, { flag: "wx" });
49436
- await rename6(temporary, file4);
49645
+ lockedStoreFile(file4, input2.path, () => {
49646
+ if (currentShaSync(file4) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
49647
+ mkdirSync16(path75.dirname(file4), { recursive: true });
49648
+ const temporary = `${file4}.phren-${process.pid}-${Date.now()}`;
49649
+ writeFileSync14(temporary, content, { flag: "wx" });
49650
+ renameSync9(temporary, file4);
49651
+ });
49437
49652
  return { content: { sha: blobSha(content), path: input2.path }, commit: { sha: blobSha(content) } };
49438
49653
  });
49439
49654
  }
@@ -49441,8 +49656,10 @@ function deleteStoreFile(store, data) {
49441
49656
  const input2 = deleteSchema.parse(data);
49442
49657
  return serialized2(async () => {
49443
49658
  const file4 = await storeFile(store, input2.path);
49444
- if (await currentSha(file4) !== input2.sha) throw new BridgeError(409, `${input2.path} changed on this computer.`);
49445
- await rm11(file4);
49659
+ lockedStoreFile(file4, input2.path, () => {
49660
+ if (currentShaSync(file4) !== input2.sha) throw new BridgeError(409, `${input2.path} changed on this computer.`);
49661
+ unlinkSync6(file4);
49662
+ });
49446
49663
  return { ok: true };
49447
49664
  });
49448
49665
  }
@@ -49460,6 +49677,7 @@ var init_memory_store = __esm({
49460
49677
  "src/bridge/memory-store.ts"() {
49461
49678
  "use strict";
49462
49679
  init_zod();
49680
+ init_locks();
49463
49681
  init_protocol();
49464
49682
  exec12 = promisify14(execFile16);
49465
49683
  SHA = /^[0-9a-f]{40}$/;
@@ -50985,7 +51203,7 @@ function resolveDuplicateMatches(matches) {
50985
51203
  const first = bulletContentKey(matches[0].line);
50986
51204
  return matches.every(({ line }) => bulletContentKey(line) === first) ? matches[0] : null;
50987
51205
  }
50988
- function findMatchingFindingBullet(bulletLines, needle, match) {
51206
+ function findMatchingFindingBullet(bulletLines, needle, match, exactOnly = false) {
50989
51207
  const fidNeedle = needle.replace(/^fid:/, "");
50990
51208
  const fidMatch = /^[a-z0-9]{8}$/.test(fidNeedle) ? bulletLines.filter(({ line }) => new RegExp(`<!--\\s*fid:${fidNeedle}\\s*-->`).test(line)) : [];
50991
51209
  const exactMatches = bulletLines.filter(
@@ -50999,6 +51217,14 @@ function findMatchingFindingBullet(bulletLines, needle, match) {
50999
51217
  if (dup) return { kind: "found", idx: dup.i };
51000
51218
  return { kind: "ambiguous", error: `"${match}" is ambiguous (${exactMatches.length} exact matches). Use a more specific phrase.` };
51001
51219
  }
51220
+ if (exactOnly) {
51221
+ const bare = withoutTypeTag(needle);
51222
+ const tagged = bulletLines.filter(({ line }) => withoutTypeTag(normalizeFindingText(line)) === bare);
51223
+ if (tagged.length === 0) return { kind: "not_found" };
51224
+ const dup = tagged.length === 1 ? tagged[0] : resolveDuplicateMatches(tagged);
51225
+ if (dup) return { kind: "found", idx: dup.i };
51226
+ return { kind: "ambiguous", error: `"${match}" is ambiguous (${tagged.length} matches). Use a more specific phrase.` };
51227
+ }
51002
51228
  if (partialMatches.length === 1) return { kind: "found", idx: partialMatches[0].i };
51003
51229
  if (partialMatches.length > 1) {
51004
51230
  const dup = resolveDuplicateMatches(partialMatches);
@@ -51116,7 +51342,7 @@ function parseFindingsContent(content, opts = {}) {
51116
51342
  }
51117
51343
  return items;
51118
51344
  }
51119
- function removeFinding(phrenPath, project, match) {
51345
+ function removeFinding(phrenPath, project, match, opts = {}) {
51120
51346
  const ensured = ensureProject(phrenPath, project);
51121
51347
  if (!ensured.ok) return forwardErr(ensured);
51122
51348
  const findingsPath = path83.resolve(path83.join(ensured.data, FINDINGS_FILENAME));
@@ -51129,12 +51355,12 @@ function removeFinding(phrenPath, project, match) {
51129
51355
  const lines = fs36.readFileSync(filePath, "utf8").split("\n");
51130
51356
  const needle = normalizeFindingText(match);
51131
51357
  const bulletLines = collectFindingBulletLines(lines);
51132
- const activeMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => !archived), needle, match);
51358
+ const activeMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => !archived), needle, match, opts.exactOnly);
51133
51359
  if (activeMatch.kind === "ambiguous") {
51134
51360
  return phrenErr(activeMatch.error, PhrenError.AMBIGUOUS_MATCH);
51135
51361
  }
51136
51362
  if (activeMatch.kind === "not_found") {
51137
- const archivedMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => archived), needle, match);
51363
+ const archivedMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => archived), needle, match, opts.exactOnly);
51138
51364
  if (archivedMatch.kind === "ambiguous" || archivedMatch.kind === "found") {
51139
51365
  return phrenErr(`Finding "${match}" is archived and read-only. Restore or re-add it before mutating history.`, PhrenError.VALIDATION_ERROR);
51140
51366
  }
@@ -51190,6 +51416,7 @@ function editFinding(phrenPath, project, oldText, newText) {
51190
51416
  return phrenOk(`Updated finding in ${project}`);
51191
51417
  });
51192
51418
  }
51419
+ var withoutTypeTag;
51193
51420
  var init_access = __esm({
51194
51421
  "src/data/access.ts"() {
51195
51422
  "use strict";
@@ -51210,6 +51437,7 @@ var init_access = __esm({
51210
51437
  init_governance();
51211
51438
  init_filenames();
51212
51439
  init_filenames();
51440
+ withoutTypeTag = (text5) => text5.replace(/^\[[a-z-]+\]\s*/i, "");
51213
51441
  }
51214
51442
  });
51215
51443
 
@@ -52016,6 +52244,7 @@ var init_summarize = __esm({
52016
52244
  init_store_routing();
52017
52245
  init_phren_paths();
52018
52246
  init_utils();
52247
+ init_locks();
52019
52248
  NOW_START = "<!-- phren:now:start -->";
52020
52249
  NOW_END = "<!-- phren:now:end -->";
52021
52250
  KNOWS_START = "<!-- phren:knows:start -->";
@@ -52214,6 +52443,19 @@ ${entry2.lines.join("\n")}` : void 0;
52214
52443
  }
52215
52444
  });
52216
52445
 
52446
+ // src/data/notes.ts
52447
+ var NOTE_HEADING_RE;
52448
+ var init_notes = __esm({
52449
+ "src/data/notes.ts"() {
52450
+ "use strict";
52451
+ init_shared();
52452
+ init_dedup();
52453
+ init_phren_paths();
52454
+ init_data_utils();
52455
+ NOTE_HEADING_RE = /^##\s+(\d{2}:\d{2}(?::\d{2})?)\s+<!--\s*nid:([a-f0-9]{8})\s*-->(?:\s+<!--\s*promoted\s*-->)?\s*$/i;
52456
+ }
52457
+ });
52458
+
52217
52459
  // src/sync/conflict-resolve.ts
52218
52460
  import { execFileSync as execFileSync5, spawnSync as spawnSync2 } from "child_process";
52219
52461
  import * as crypto11 from "crypto";
@@ -52230,7 +52472,8 @@ function conflictStrategy(relFile) {
52230
52472
  if (name === "summary.md") return "summary";
52231
52473
  if (name === "review.md" || name === "truths.md") return "union";
52232
52474
  if (file4 === ".config/maintenance-writer.json") return "theirs";
52233
- if (/(^|\/)(notes|journal)\/[^/]+\.md$/i.test(file4)) return "union";
52475
+ if (/(^|\/)notes\/[^/]+\.md$/i.test(file4)) return "notes";
52476
+ if (/(^|\/)journal\/[^/]+\.md$/i.test(file4)) return "union";
52234
52477
  return null;
52235
52478
  }
52236
52479
  function git4(cwd, args) {
@@ -52286,6 +52529,51 @@ function unionText(base, ours, theirs) {
52286
52529
  fs39.rmSync(dir, { recursive: true, force: true });
52287
52530
  }
52288
52531
  }
52532
+ function noteBlocks(content) {
52533
+ const lines = content.split("\n");
52534
+ const first = lines.findIndex((line) => NOTE_HEADING_RE.test(line));
52535
+ const notes = /* @__PURE__ */ new Map();
52536
+ if (first === -1) return { header: content.trimEnd(), notes };
52537
+ let id2 = "";
52538
+ let body2 = [];
52539
+ const flush = () => {
52540
+ if (id2) notes.set(id2, body2.join("\n").trimEnd());
52541
+ };
52542
+ for (const line of lines.slice(first)) {
52543
+ const m = NOTE_HEADING_RE.exec(line);
52544
+ if (!m) {
52545
+ body2.push(line);
52546
+ continue;
52547
+ }
52548
+ flush();
52549
+ if (notes.has(m[2])) return null;
52550
+ id2 = m[2];
52551
+ body2 = [line];
52552
+ }
52553
+ flush();
52554
+ return { header: lines.slice(0, first).join("\n").trimEnd(), notes };
52555
+ }
52556
+ function mergeNotes(base, ours, theirs) {
52557
+ const b = noteBlocks(base);
52558
+ if (!b) return null;
52559
+ const deleted = { header: b.header, notes: /* @__PURE__ */ new Map() };
52560
+ const [o, t] = [ours === null ? deleted : noteBlocks(ours), theirs === null ? deleted : noteBlocks(theirs)];
52561
+ if (!o || !t) return null;
52562
+ const header = mergeText(b.header, o.header, t.header);
52563
+ if (header === null) return null;
52564
+ const out = [];
52565
+ for (const id2 of /* @__PURE__ */ new Set([...o.notes.keys(), ...t.notes.keys()])) {
52566
+ const [was, mine, incoming] = [b.notes.get(id2), o.notes.get(id2), t.notes.get(id2)];
52567
+ let note;
52568
+ if (mine === incoming || incoming === was) note = mine;
52569
+ else if (mine === was) note = incoming;
52570
+ else if (mine === void 0 || incoming === void 0) note = mine ?? incoming;
52571
+ else return null;
52572
+ if (note !== void 0) out.push(note);
52573
+ }
52574
+ if (!out.length && (ours === null || theirs === null)) return DELETED_FILE;
52575
+ return [header, ...out].join("\n\n") + "\n";
52576
+ }
52289
52577
  function mergeWithGeneratedBlock(base, ours, theirs, start, end, where, merge2 = unionText) {
52290
52578
  const b = splitBlock(base, start, end);
52291
52579
  const o = splitBlock(ours, start, end);
@@ -52312,7 +52600,7 @@ function resolveContent(strategy, base, ours, theirs) {
52312
52600
  case "tasks":
52313
52601
  return orUnion(() => mergeTasksByBid(base, ours, theirs), base, ours, theirs, dedupe);
52314
52602
  case "findings":
52315
- return orUnion(() => mergeFindings(ours, theirs), base, ours, theirs);
52603
+ return orUnion(() => mergeFindings(ours, theirs, base), base, ours, theirs);
52316
52604
  // Archived tasks only accumulate: keep both sides, the incoming version of any duplicate.
52317
52605
  case "archive":
52318
52606
  return dedupe(orUnion(() => mergeTask(theirs, ours), base, ours, theirs));
@@ -52323,6 +52611,10 @@ function resolveContent(strategy, base, ours, theirs) {
52323
52611
  // summarize pass fold in anything only this machine had.
52324
52612
  case "summary":
52325
52613
  return mergeWithGeneratedBlock(base, ours, theirs, KNOWS_START, KNOWS_END, "bottom", mergeText) ?? theirs;
52614
+ case "notes": {
52615
+ const merged = mergeNotes(base, ours, theirs);
52616
+ return typeof merged === "string" ? merged : unionText(base, ours, theirs);
52617
+ }
52326
52618
  case "union":
52327
52619
  return unionText(base, ours, theirs);
52328
52620
  case "theirs":
@@ -52354,7 +52646,13 @@ function resolveStoreConflicts(cwd) {
52354
52646
  unresolved.push(relFile);
52355
52647
  continue;
52356
52648
  }
52357
- const merged = ours === null ? theirs : theirs === null ? ours : resolveContent(strategy, base, ours, theirs);
52649
+ const notesMerge = strategy === "notes" && (ours === null || theirs === null) ? mergeNotes(base, ours, theirs) : null;
52650
+ if (notesMerge === DELETED_FILE) {
52651
+ git4(cwd, ["rm", "--quiet", "--force", "--ignore-unmatch", "--", relFile]);
52652
+ resolved.push(relFile);
52653
+ continue;
52654
+ }
52655
+ const merged = notesMerge ?? (ours === null ? theirs : theirs === null ? ours : resolveContent(strategy, base, ours, theirs));
52358
52656
  if (merged === null) {
52359
52657
  unresolved.push(relFile);
52360
52658
  continue;
@@ -52372,7 +52670,7 @@ function resolveStoreConflicts(cwd) {
52372
52670
  }
52373
52671
  return { resolved, unresolved };
52374
52672
  }
52375
- var dedupe;
52673
+ var DELETED_FILE, dedupe;
52376
52674
  var init_conflict_resolve = __esm({
52377
52675
  "src/sync/conflict-resolve.ts"() {
52378
52676
  "use strict";
@@ -52383,6 +52681,8 @@ var init_conflict_resolve = __esm({
52383
52681
  init_validate();
52384
52682
  init_summarize();
52385
52683
  init_task_merge();
52684
+ init_notes();
52685
+ DELETED_FILE = /* @__PURE__ */ Symbol("deleted");
52386
52686
  dedupe = (content) => content === null ? null : dedupeTaskIds(content).content;
52387
52687
  }
52388
52688
  });
@@ -52817,7 +53117,7 @@ var init_store_sync = __esm({
52817
53117
 
52818
53118
  // src/bridge/health.ts
52819
53119
  import { execFile as execFile19, spawn as spawn9 } from "node:child_process";
52820
- import { lstat as lstat22, readFile as readFile36 } from "node:fs/promises";
53120
+ import { lstat as lstat22, readFile as readFile35 } from "node:fs/promises";
52821
53121
  import { homedir as homedir14, hostname as hostname7 } from "node:os";
52822
53122
  import path89 from "node:path";
52823
53123
  import { promisify as promisify17 } from "node:util";
@@ -52951,11 +53251,16 @@ async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
52951
53251
  const owner2 = newest2.scheduleProject ?? newest2.project;
52952
53252
  const matching = runs.filter((run4) => (run4.scheduleProject ?? run4.project) === owner2 && run4.scheduleId === newest2.scheduleId && (newest2.batchId ? run4.batchId === newest2.batchId : run4.id === newest2.id));
52953
53253
  const last = latestScheduleBatch(matching).lastRun;
52954
- let name;
53254
+ let name, paused = false;
52955
53255
  const directory = getProjectDirs(store).find((dir) => path89.basename(dir).toLowerCase() === owner2.toLowerCase());
52956
- if (directory) name = (await readScheduleDocument(directory).catch(() => void 0))?.schedules.find((item) => item.id === last.scheduleId)?.name;
53256
+ if (directory) {
53257
+ const found = (await readScheduleDocument(directory).catch(() => void 0))?.schedules.find((item) => item.id === last.scheduleId);
53258
+ name = found?.name;
53259
+ paused = found?.enabled === false;
53260
+ }
52957
53261
  return {
52958
53262
  ...name ? { name } : {},
53263
+ ...paused ? { paused } : {},
52959
53264
  project: owner2,
52960
53265
  status: last.status,
52961
53266
  ...last.reason ? { reason: plainError(last.reason) } : {},
@@ -53013,7 +53318,7 @@ async function readCanary(root = bridgeRoot()) {
53013
53318
  try {
53014
53319
  const info = await lstat22(canaryFile(root));
53015
53320
  if (!info.isFile() || info.size > 65536) return null;
53016
- const value2 = JSON.parse(await readFile36(canaryFile(root), "utf8"));
53321
+ const value2 = JSON.parse(await readFile35(canaryFile(root), "utf8"));
53017
53322
  return value2 && value2.version === 1 && Array.isArray(value2.steps) ? value2 : null;
53018
53323
  } catch {
53019
53324
  return null;
@@ -53166,7 +53471,7 @@ var init_harnesses = __esm({
53166
53471
  });
53167
53472
 
53168
53473
  // src/bridge/account-choice.ts
53169
- import { readFile as readFile37 } from "node:fs/promises";
53474
+ import { readFile as readFile36 } from "node:fs/promises";
53170
53475
  import path91 from "node:path";
53171
53476
  function windowRoom2(window2, now) {
53172
53477
  if (!window2) return void 0;
@@ -53212,7 +53517,7 @@ function claudeRooms(inventory, usage, now) {
53212
53517
  }
53213
53518
  async function readAccountLimits(now = Date.now()) {
53214
53519
  try {
53215
- const parsed = ledgerSchema.parse(JSON.parse(await readFile37(limitsFile(), "utf8")));
53520
+ const parsed = ledgerSchema.parse(JSON.parse(await readFile36(limitsFile(), "utf8")));
53216
53521
  return parsed.limits.filter((entry2) => Date.parse(entry2.until) > now);
53217
53522
  } catch (error62) {
53218
53523
  if (error62.code !== "ENOENT") logger.warn("accounts", `Could not read account-limits.json: ${error62 instanceof Error ? error62.message : String(error62)}`);
@@ -53306,7 +53611,7 @@ var init_account_choice = __esm({
53306
53611
 
53307
53612
  // src/bridge/owner-inbox.ts
53308
53613
  import { randomUUID as randomUUID21 } from "node:crypto";
53309
- import { lstat as lstat23, mkdir as mkdir22, readFile as readFile38 } from "node:fs/promises";
53614
+ import { lstat as lstat23, mkdir as mkdir22, readFile as readFile37 } from "node:fs/promises";
53310
53615
  import path92 from "node:path";
53311
53616
  function sourceKey(row) {
53312
53617
  const t = row.target;
@@ -53371,7 +53676,7 @@ var init_owner_inbox = __esm({
53371
53676
  });
53372
53677
  if (!info) return [];
53373
53678
  if (!info.isFile() || info.isSymbolicLink() || info.size > 4 * 1024 * 1024) throw new BridgeError(409, "The owner inbox cannot be read safely.");
53374
- return external_exports.array(itemSchema).max(1e4).parse(JSON.parse(await readFile38(this.file, "utf8")));
53679
+ return external_exports.array(itemSchema).max(1e4).parse(JSON.parse(await readFile37(this.file, "utf8")));
53375
53680
  }
53376
53681
  run(input2) {
53377
53682
  const run4 = this.pending.then(async () => {
@@ -53386,7 +53691,7 @@ var init_owner_inbox = __esm({
53386
53691
  }
53387
53692
  try {
53388
53693
  const rows2 = await this.read(), at2 = (/* @__PURE__ */ new Date()).toISOString();
53389
- let changed2 = false;
53694
+ let changed = false;
53390
53695
  if (data.action === "list") {
53391
53696
  const observed = await this.sources();
53392
53697
  const { sources, unavailableDispatches = [] } = Array.isArray(observed) ? { sources: observed } : observed;
@@ -53398,7 +53703,7 @@ var init_owner_inbox = __esm({
53398
53703
  row.resolvedAt = at2;
53399
53704
  row.updatedAt = at2;
53400
53705
  row.resolution = reason2;
53401
- changed2 = true;
53706
+ changed = true;
53402
53707
  };
53403
53708
  for (const row of rows2) {
53404
53709
  if (row.kind === "manual") continue;
@@ -53409,7 +53714,7 @@ var init_owner_inbox = __esm({
53409
53714
  if (row.live !== live) {
53410
53715
  row.live = live;
53411
53716
  row.updatedAt = at2;
53412
- changed2 = true;
53717
+ changed = true;
53413
53718
  }
53414
53719
  if (!source) {
53415
53720
  if (row.state === "open" && !unavailable) resolve17(row, "stale: source gone");
@@ -53422,14 +53727,14 @@ var init_owner_inbox = __esm({
53422
53727
  retained.add(key4);
53423
53728
  if (row.state === "open" && JSON.stringify({ ...row, ...source }) !== JSON.stringify(row)) {
53424
53729
  Object.assign(row, source, { updatedAt: at2 });
53425
- changed2 = true;
53730
+ changed = true;
53426
53731
  }
53427
53732
  }
53428
53733
  for (const [key4, source] of active) {
53429
53734
  if (retained.has(key4)) continue;
53430
53735
  if (rows2.length >= 1e4) throw new BridgeError(409, "The owner inbox is full.");
53431
53736
  rows2.push(itemSchema.parse({ ...source, id: randomUUID21(), state: "open", live: true, createdAt: at2, updatedAt: at2 }));
53432
- changed2 = true;
53737
+ changed = true;
53433
53738
  }
53434
53739
  }
53435
53740
  if (data.action === "add") {
@@ -53440,9 +53745,9 @@ var init_owner_inbox = __esm({
53440
53745
  if (!prior) {
53441
53746
  if (rows2.length >= 1e4) throw new BridgeError(409, "The owner inbox is full.");
53442
53747
  rows2.push(item);
53443
- changed2 = true;
53748
+ changed = true;
53444
53749
  }
53445
- if (changed2) await atomicInPrivateDir(this.file, rows2);
53750
+ if (changed) await atomicInPrivateDir(this.file, rows2);
53446
53751
  return { ok: true, item: prior ?? item };
53447
53752
  }
53448
53753
  if (data.action === "resolve") {
@@ -53453,12 +53758,12 @@ var init_owner_inbox = __esm({
53453
53758
  item.resolvedAt = at2;
53454
53759
  item.updatedAt = at2;
53455
53760
  item.resolution = data.resolution;
53456
- changed2 = true;
53761
+ changed = true;
53457
53762
  }
53458
- if (changed2) await atomicInPrivateDir(this.file, rows2);
53763
+ if (changed) await atomicInPrivateDir(this.file, rows2);
53459
53764
  return { ok: true, item };
53460
53765
  }
53461
- if (changed2) await atomicInPrivateDir(this.file, rows2);
53766
+ if (changed) await atomicInPrivateDir(this.file, rows2);
53462
53767
  return { ok: true, items: rows2.filter((row) => data.includeResolved || row.state === "open" && (row.kind === "manual" || row.live === true)).sort((a, b) => a.createdAt.localeCompare(b.createdAt)) };
53463
53768
  } finally {
53464
53769
  release();
@@ -53577,7 +53882,7 @@ var init_owner_inbox_sources = __esm({
53577
53882
 
53578
53883
  // src/bridge/hand-off-queue.ts
53579
53884
  import { createHash as createHash24, randomUUID as randomUUID22 } from "node:crypto";
53580
- import { lstat as lstat24, open as open16, readFile as readFile39, readdir as readdir14, unlink as unlink5 } from "node:fs/promises";
53885
+ import { lstat as lstat24, open as open16, readFile as readFile38, readdir as readdir14, unlink as unlink5 } from "node:fs/promises";
53581
53886
  import path93 from "node:path";
53582
53887
  var queuedHandOffSchema, rowSchema, DAY3, HAND_OFF_RETENTION_MS, HAND_OFF_MAX_ROWS, settled2, samePane, HandOffQueue;
53583
53888
  var init_hand_off_queue = __esm({
@@ -53649,7 +53954,7 @@ var init_hand_off_queue = __esm({
53649
53954
  });
53650
53955
  if (!info) return void 0;
53651
53956
  if (!info.isFile() || info.isSymbolicLink() || info.size > 1e5) throw new BridgeError(409, "The hand-off record cannot be read safely.");
53652
- const row = rowSchema.parse(JSON.parse(await readFile39(file4, "utf8")));
53957
+ const row = rowSchema.parse(JSON.parse(await readFile38(file4, "utf8")));
53653
53958
  if (row.state === "attempting") {
53654
53959
  row.state = "uncertain";
53655
53960
  row.error = "The Hook restarted before delivery was confirmed.";
@@ -53856,8 +54161,9 @@ var init_hand_off_queue = __esm({
53856
54161
  });
53857
54162
 
53858
54163
  // src/bridge/git-host-auth.ts
54164
+ import { createHash as createHash25 } from "node:crypto";
53859
54165
  import { execFile as execFile20 } from "node:child_process";
53860
- import { mkdir as mkdir23, readFile as readFile40, stat as stat19 } from "node:fs/promises";
54166
+ import { mkdir as mkdir23, readFile as readFile39, stat as stat19 } from "node:fs/promises";
53861
54167
  import path94 from "node:path";
53862
54168
  import { promisify as promisify18 } from "node:util";
53863
54169
  function gitHostsFile() {
@@ -53879,7 +54185,7 @@ async function readStore(file4 = gitHostsFile()) {
53879
54185
  if (!info.isFile()) return null;
53880
54186
  if (process.platform !== "win32" && ((info.mode & 63) !== 0 || process.getuid && info.uid !== process.getuid())) return "unsafe";
53881
54187
  try {
53882
- const parsed = JSON.parse(await readFile40(file4, "utf8"));
54188
+ const parsed = JSON.parse(await readFile39(file4, "utf8"));
53883
54189
  const hosts = {};
53884
54190
  if (parsed.hosts && typeof parsed.hosts === "object") {
53885
54191
  for (const [domain2, raw] of Object.entries(parsed.hosts)) {
@@ -53904,6 +54210,7 @@ async function writeHostToken(domain2, kind, token, user, file4 = gitHostsFile()
53904
54210
  else delete hosts[key4];
53905
54211
  await mkdir23(path94.dirname(file4), { recursive: true, mode: 448 });
53906
54212
  await atomic(file4, JSON.stringify({ hosts }, null, 2) + "\n", 384);
54213
+ invalidatePullsForDomain(key4);
53907
54214
  }
53908
54215
  function fromEnv(kind, domain2, env) {
53909
54216
  if (kind === "gitlab") {
@@ -53941,10 +54248,49 @@ async function listHostTokens(file4 = gitHostsFile()) {
53941
54248
  if (store === "unsafe") return "unsafe";
53942
54249
  return Object.entries(store?.hosts ?? {}).map(([domain2, { kind, user, savedAt }]) => ({ domain: domain2, kind, ...user ? { user } : {}, ...savedAt ? { savedAt } : {} }));
53943
54250
  }
54251
+ function ghHostBlock(hostsYml, domain2) {
54252
+ const want = domain2.trim().toLowerCase().replace(/\.$/, "");
54253
+ const out = [];
54254
+ let inside = false;
54255
+ for (const line of hostsYml.split(/\r?\n/)) {
54256
+ const top = /^(\S[^:]*):\s*$/.exec(line);
54257
+ if (top) {
54258
+ inside = top[1].trim().replace(/^["']|["']$/g, "").toLowerCase() === want;
54259
+ if (inside) out.push(line);
54260
+ continue;
54261
+ }
54262
+ if (inside && (line.startsWith(" ") || line.startsWith(" ") || line.trim() === "")) out.push(line);
54263
+ else if (line.trim()) inside = false;
54264
+ }
54265
+ return out.join("\n").trimEnd();
54266
+ }
54267
+ async function hostCredentialIdentity(host) {
54268
+ let state = null;
54269
+ if (host.kind === "github") {
54270
+ const dir = process.env.GH_CONFIG_DIR || path94.join(process.env.XDG_CONFIG_HOME || path94.join(homeDir(), ".config"), "gh");
54271
+ const hosts = await readFile39(path94.join(dir, "hosts.yml"), "utf8").catch(() => "");
54272
+ state = [
54273
+ process.env.GH_TOKEN,
54274
+ process.env.GITHUB_TOKEN,
54275
+ process.env.GH_ENTERPRISE_TOKEN,
54276
+ process.env.GITHUB_ENTERPRISE_TOKEN,
54277
+ ghHostBlock(hosts, host.domain ?? "github.com")
54278
+ ];
54279
+ } else if (host.kind && host.domain) {
54280
+ const store = await readStore();
54281
+ state = [
54282
+ await resolveHostToken(host.kind, host.domain),
54283
+ store && store !== "unsafe" ? store.hosts[normalDomain(host.domain)] : store
54284
+ ];
54285
+ }
54286
+ return createHash25("sha256").update(JSON.stringify(state)).digest("hex");
54287
+ }
53944
54288
  var exec15;
53945
54289
  var init_git_host_auth = __esm({
53946
54290
  "src/bridge/git-host-auth.ts"() {
53947
54291
  "use strict";
54292
+ init_home_paths();
54293
+ init_git();
53948
54294
  init_protocol();
53949
54295
  exec15 = promisify18(execFile20);
53950
54296
  }
@@ -54017,18 +54363,21 @@ var init_git_host_http = __esm({
54017
54363
 
54018
54364
  // src/bridge/git-publish.ts
54019
54365
  import { spawn as spawn10 } from "node:child_process";
54020
- function runCombined(command, args, cwd, timeout, extraEnv = {}) {
54366
+ function runCombined(command, args, cwd, timeout, extraEnv = {}, killGraceMs = KILL_GRACE_MS2) {
54021
54367
  return new Promise((resolve17) => {
54022
54368
  let output2 = "", truncated = false, timedOut = false, settled3 = false;
54369
+ let deadline;
54023
54370
  const finish = (run4) => {
54024
- if (!settled3) {
54025
- settled3 = true;
54026
- resolve17(run4);
54027
- }
54371
+ if (settled3) return;
54372
+ settled3 = true;
54373
+ clearTimeout(deadline);
54374
+ resolve17(run4);
54028
54375
  };
54376
+ const group = process.platform !== "win32";
54029
54377
  const child = spawn10(command, args, {
54030
54378
  cwd,
54031
54379
  stdio: ["ignore", "pipe", "pipe"],
54380
+ detached: group,
54032
54381
  env: nonInteractiveGitEnv({ ...process.env, ...extraEnv, GIT_CONFIG_NOSYSTEM: "1", GIT_EDITOR: "true", GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1", NO_COLOR: "1" })
54033
54382
  });
54034
54383
  const append = (chunk) => {
@@ -54041,9 +54390,38 @@ function runCombined(command, args, cwd, timeout, extraEnv = {}) {
54041
54390
  };
54042
54391
  child.stdout.on("data", append);
54043
54392
  child.stderr.on("data", append);
54393
+ const kill = (signal) => {
54394
+ try {
54395
+ if (group && child.pid) process.kill(-child.pid, signal);
54396
+ else child.kill(signal);
54397
+ } catch {
54398
+ child.kill(signal);
54399
+ }
54400
+ };
54401
+ const escalate = () => {
54402
+ if (!group || !child.pid) {
54403
+ child.kill("SIGKILL");
54404
+ return;
54405
+ }
54406
+ try {
54407
+ process.kill(-child.pid, 0);
54408
+ } catch {
54409
+ return;
54410
+ }
54411
+ try {
54412
+ process.kill(-child.pid, "SIGKILL");
54413
+ } catch {
54414
+ }
54415
+ };
54044
54416
  const timer = setTimeout(() => {
54045
54417
  timedOut = true;
54046
- child.kill("SIGTERM");
54418
+ kill("SIGTERM");
54419
+ setTimeout(escalate, killGraceMs).unref();
54420
+ deadline = setTimeout(() => {
54421
+ child.stdout.destroy();
54422
+ child.stderr.destroy();
54423
+ finish({ code: null, output: output2.trimEnd(), missing: false, timedOut: true });
54424
+ }, killGraceMs * 2);
54047
54425
  }, timeout);
54048
54426
  child.on("error", (error62) => {
54049
54427
  clearTimeout(timer);
@@ -54123,7 +54501,11 @@ async function gitPullRequest(cwd, draft) {
54123
54501
  const { reason: reason2, message } = unknownHost(host);
54124
54502
  return { ok: false, reason: reason2, message, host };
54125
54503
  }
54126
- return { ...await provider2.open(root, branch, draft === true, host), host };
54504
+ try {
54505
+ return { ...await provider2.open(root, branch, draft === true, host), host };
54506
+ } finally {
54507
+ invalidatePulls(root);
54508
+ }
54127
54509
  }
54128
54510
  async function gitMergeRequest(cwd, data) {
54129
54511
  const request9 = MergeBody.parse(data);
@@ -54135,7 +54517,11 @@ async function gitMergeRequest(cwd, data) {
54135
54517
  const { reason: reason2, message } = unknownHost(host);
54136
54518
  return { ok: false, reason: reason2, message, host };
54137
54519
  }
54138
- return { ...await provider2.merge(root, request9, host), host };
54520
+ try {
54521
+ return { ...await provider2.merge(root, request9, host), host };
54522
+ } finally {
54523
+ invalidatePulls(root);
54524
+ }
54139
54525
  }
54140
54526
  async function gitHostToken(cwd, data) {
54141
54527
  const { token } = external_exports.object({ token: external_exports.string().max(4096) }).parse(data);
@@ -54162,7 +54548,7 @@ async function gitHostToken(cwd, data) {
54162
54548
  throw error62;
54163
54549
  }
54164
54550
  }
54165
- var MAX_OUTPUT, COMMIT_TIMEOUT_MS, PUSH_TIMEOUT_MS, MAX_MESSAGE, MergeBody;
54551
+ var MAX_OUTPUT, COMMIT_TIMEOUT_MS, PUSH_TIMEOUT_MS, MAX_MESSAGE, KILL_GRACE_MS2, MergeBody;
54166
54552
  var init_git_publish = __esm({
54167
54553
  "src/bridge/git-publish.ts"() {
54168
54554
  "use strict";
@@ -54179,6 +54565,7 @@ var init_git_publish = __esm({
54179
54565
  COMMIT_TIMEOUT_MS = 11e4;
54180
54566
  PUSH_TIMEOUT_MS = 11e4;
54181
54567
  MAX_MESSAGE = 2e4;
54568
+ KILL_GRACE_MS2 = 2e3;
54182
54569
  MergeBody = external_exports.object({
54183
54570
  number: external_exports.number().int().positive(),
54184
54571
  method: external_exports.enum(["merge", "squash", "rebase"]).default("merge"),
@@ -54903,7 +55290,8 @@ var init_git_hosts = __esm({
54903
55290
  });
54904
55291
 
54905
55292
  // src/bridge/git.ts
54906
- import { createHash as createHash25 } from "node:crypto";
55293
+ import { createHash as createHash26 } from "node:crypto";
55294
+ import { readFileSync as readFileSync42, realpathSync as realpathSync3 } from "node:fs";
54907
55295
  import { lstat as lstat25, open as open17, readdir as readdir15, realpath as realpath12 } from "node:fs/promises";
54908
55296
  import path95 from "node:path";
54909
55297
  function statusLetter(code) {
@@ -55126,13 +55514,70 @@ async function gitBranches(cwd) {
55126
55514
  }
55127
55515
  return { current: current2, local, remote };
55128
55516
  }
55129
- async function gitPulls(cwd) {
55130
- const root = await repository2(cwd);
55131
- const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
55132
- const host = await detectHost(root, branch);
55517
+ function credentialIdentity(host, fresh = false) {
55518
+ const key4 = JSON.stringify([host.kind ?? null, (host.domain ?? "").toLowerCase()]);
55519
+ const hit = credentialReads.get(key4);
55520
+ if (host.kind !== "gitlab") return hostCredentialIdentity(host);
55521
+ if (!fresh && hit && Date.now() - hit.at < CREDENTIAL_TTL_MS) return hit.value;
55522
+ const value2 = hostCredentialIdentity(host).catch((error62) => {
55523
+ credentialReads.delete(key4);
55524
+ throw error62;
55525
+ });
55526
+ credentialReads.set(key4, { at: Date.now(), value: value2 });
55527
+ if (credentialReads.size > 64) credentialReads.delete(credentialReads.keys().next().value);
55528
+ return value2;
55529
+ }
55530
+ function repositoryId(root) {
55531
+ try {
55532
+ const dotGit = path95.join(root, ".git");
55533
+ let gitDir2 = dotGit;
55534
+ try {
55535
+ const link = /^gitdir:\s*(.+)$/m.exec(readFileSync42(dotGit, "utf8"));
55536
+ if (link) gitDir2 = path95.resolve(root, link[1].trim());
55537
+ } catch {
55538
+ }
55539
+ let common = gitDir2;
55540
+ try {
55541
+ common = path95.resolve(gitDir2, readFileSync42(path95.join(gitDir2, "commondir"), "utf8").trim());
55542
+ } catch {
55543
+ }
55544
+ return realpathSync3(common);
55545
+ } catch {
55546
+ return root;
55547
+ }
55548
+ }
55549
+ function invalidatePulls(root) {
55550
+ const prefix = repositoryId(root) + "\0";
55551
+ pullsCache.invalidate((key4) => key4.startsWith(prefix));
55552
+ }
55553
+ function invalidatePullsForDomain(domain2) {
55554
+ const normalized = domain2.trim().toLowerCase().replace(/\.$/, "");
55555
+ for (const key4 of credentialReads.keys()) if (JSON.parse(key4)[1] === normalized) credentialReads.delete(key4);
55556
+ pullsCache.invalidate((key4) => key4.split("\0")[1] === normalized);
55557
+ }
55558
+ async function gitPulls(cwd, retried = false) {
55559
+ const { root, branch, host } = await withIndependentGitReadDeadline(async () => {
55560
+ const root2 = await repository2(cwd);
55561
+ const branch2 = (await git(root2, "branch", "--show-current").catch(() => "")).trim();
55562
+ return { root: root2, branch: branch2, host: await detectHost(root2, branch2) };
55563
+ });
55133
55564
  const provider2 = providerFor(host);
55134
- const list = provider2 ? await provider2.list(root, branch, host) : unknownHost(host);
55135
- return { ...list, branch: branch || null, host };
55565
+ const credential = await credentialIdentity(host);
55566
+ const key4 = repositoryId(root) + "\0" + (host.domain ?? "").toLowerCase().replace(/\.$/, "") + "\0" + JSON.stringify([branch, host, credential]);
55567
+ try {
55568
+ return await pullsCache.get(key4, () => withoutGitReadDeadline(async () => {
55569
+ const list = provider2 ? await provider2.list(root, branch, host) : unknownHost(host);
55570
+ if (await credentialIdentity(host, true) !== credential) {
55571
+ pullsCache.invalidate((candidate) => candidate === key4);
55572
+ throw new CredentialsChanged();
55573
+ }
55574
+ return { ...list, branch: branch || null, host };
55575
+ }));
55576
+ } catch (error62) {
55577
+ if (!(error62 instanceof CredentialsChanged)) throw error62;
55578
+ if (!retried) return gitPulls(cwd, true);
55579
+ throw new BridgeError(409, "Forge credentials keep changing. Retry.");
55580
+ }
55136
55581
  }
55137
55582
  async function repositoryPath(root, raw, allowRoot = false) {
55138
55583
  if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path95.isAbsolute(raw) || path95.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
@@ -55163,13 +55608,14 @@ async function repositoryPath(root, raw, allowRoot = false) {
55163
55608
  }
55164
55609
  function invalidateTree(root) {
55165
55610
  treeCache.delete(root);
55611
+ invalidatePulls(root);
55166
55612
  }
55167
55613
  async function treeSnapshot(root, head) {
55168
55614
  const [tracked, porcelain] = await Promise.all([
55169
55615
  git(root, "ls-files", "-z"),
55170
55616
  git(root, "status", "--porcelain=v1", "-z", "--untracked-files=all")
55171
55617
  ]);
55172
- const changed2 = /* @__PURE__ */ new Map();
55618
+ const changed = /* @__PURE__ */ new Map();
55173
55619
  const files = new Set(tracked.split("\0").filter(Boolean));
55174
55620
  const tokens = porcelain.split("\0");
55175
55621
  for (let i = 0; i < tokens.length; i++) {
@@ -55177,7 +55623,7 @@ async function treeSnapshot(root, head) {
55177
55623
  if (!row) continue;
55178
55624
  const xy = row.slice(0, 2), file4 = row.slice(3);
55179
55625
  const letter = xy === "??" ? "?" : statusLetter(xy[1] !== " " ? xy[1] : xy[0]);
55180
- changed2.set(file4, letter);
55626
+ changed.set(file4, letter);
55181
55627
  files.add(file4);
55182
55628
  if (/[RC]/.test(xy)) i++;
55183
55629
  }
@@ -55202,12 +55648,12 @@ async function treeSnapshot(root, head) {
55202
55648
  }
55203
55649
  if (directory) {
55204
55650
  entry2.fileCount = (entry2.fileCount ?? 0) + 1;
55205
- if (changed2.has(file4)) entry2.status = "changed";
55206
- } else if (changed2.has(file4)) entry2.status = entry2.kind === "dir" ? "changed" : changed2.get(file4);
55651
+ if (changed.has(file4)) entry2.status = "changed";
55652
+ } else if (changed.has(file4)) entry2.status = entry2.kind === "dir" ? "changed" : changed.get(file4);
55207
55653
  parent = full2;
55208
55654
  }
55209
55655
  }
55210
- const version2 = createHash25("sha256").update(head).update(tracked).update(porcelain).digest("hex");
55656
+ const version2 = createHash26("sha256").update(head).update(tracked).update(porcelain).digest("hex");
55211
55657
  return { version: version2, levels: new Map([...levels].map(([directory, entries2]) => [
55212
55658
  directory,
55213
55659
  [...entries2.values()].sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "dir" ? -1 : 1)
@@ -55331,6 +55777,16 @@ async function gitDiscard(cwd, paths) {
55331
55777
  treeCache.delete(root);
55332
55778
  try {
55333
55779
  const files = await repositoryPaths(root, paths);
55780
+ for (const file4 of files) {
55781
+ const info = await lstat25(path95.join(root, file4)).catch((error62) => {
55782
+ if (error62.code === "ENOENT") return void 0;
55783
+ throw error62;
55784
+ });
55785
+ const indexed = info ? "" : await git(root, "ls-files", "-z", "--", `:(literal)${file4}`);
55786
+ if (info?.isDirectory() || indexed.split("\0").some((entry2) => entry2.startsWith(`${file4}/`))) {
55787
+ throw new BridgeError(409, "Discard the files in this directory one at a time.");
55788
+ }
55789
+ }
55334
55790
  const untracked = new Set((await git(root, "ls-files", "--others", "--exclude-standard", "-z")).split("\0").filter(Boolean));
55335
55791
  for (const file4 of files) {
55336
55792
  const literal2 = `:(literal)${file4}`;
@@ -55429,17 +55885,32 @@ async function readGitShow(cwd, sha) {
55429
55885
  truncated
55430
55886
  };
55431
55887
  }
55432
- var UNKNOWN_COUNTS, NO_DIFF2, MAX_STATUS_ROWS, treeCache, TREE_TTL_MS, MAX_IGNORED_ENTRIES, ignoredCache, MAX_SHOW_FILES, MAX_SHOW_PATCH, MAX_FILE_PATCH;
55888
+ var UNKNOWN_COUNTS, NO_DIFF2, MAX_STATUS_ROWS, REVOKING, pullsCache, credentialReads, CREDENTIAL_TTL_MS, CredentialsChanged, treeCache, TREE_TTL_MS, MAX_IGNORED_ENTRIES, ignoredCache, MAX_SHOW_FILES, MAX_SHOW_PATCH, MAX_FILE_PATCH;
55433
55889
  var init_git = __esm({
55434
55890
  "src/bridge/git.ts"() {
55435
55891
  "use strict";
55436
55892
  init_protocol();
55437
55893
  init_projects();
55438
55894
  init_git_hosts();
55895
+ init_git_host_auth();
55896
+ init_lookup_cache();
55439
55897
  init_git_hosts();
55440
55898
  UNKNOWN_COUNTS = { additions: 0, deletions: 0, countsComplete: false };
55441
55899
  NO_DIFF2 = ["diff", "--no-ext-diff", "--no-textconv", "--no-color"];
55442
55900
  MAX_STATUS_ROWS = 500;
55901
+ REVOKING = /* @__PURE__ */ new Set(["auth", "not-found"]);
55902
+ pullsCache = new LookupCache(
55903
+ 3e4,
55904
+ 3e5,
55905
+ 64,
55906
+ (value2) => value2.available === true,
55907
+ 45e3,
55908
+ (value2) => value2.available === false && REVOKING.has(String(value2.reason))
55909
+ );
55910
+ credentialReads = /* @__PURE__ */ new Map();
55911
+ CREDENTIAL_TTL_MS = 5e3;
55912
+ CredentialsChanged = class extends Error {
55913
+ };
55443
55914
  treeCache = /* @__PURE__ */ new Map();
55444
55915
  TREE_TTL_MS = 2e3;
55445
55916
  MAX_IGNORED_ENTRIES = 1e3;
@@ -55451,12 +55922,12 @@ var init_git = __esm({
55451
55922
  });
55452
55923
 
55453
55924
  // src/bridge/git-worktrees.ts
55454
- import { createHash as createHash26 } from "node:crypto";
55925
+ import { createHash as createHash27 } from "node:crypto";
55455
55926
  import { realpath as realpath13, stat as stat20 } from "node:fs/promises";
55456
55927
  import { homedir as homedir15 } from "node:os";
55457
55928
  import path96 from "node:path";
55458
55929
  function worktreeId(abs) {
55459
- return createHash26("sha256").update(`worktree\0${abs}`).digest("hex").slice(0, 32);
55930
+ return createHash27("sha256").update(`worktree\0${abs}`).digest("hex").slice(0, 32);
55460
55931
  }
55461
55932
  async function listed3(root) {
55462
55933
  const output2 = await git(root, "worktree", "list", "--porcelain", "-z");
@@ -55537,7 +56008,7 @@ async function readGitWorktrees(cwd, workers) {
55537
56008
  behind = Number(counts[0]);
55538
56009
  ahead = Number(counts[1]);
55539
56010
  }
55540
- const changed2 = uncommitted(await git(worktree.abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal"));
56011
+ const changed = uncommitted(await git(worktree.abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal"));
55541
56012
  const worker = await workerFor(worktree.abs, workers, worktrees.map((item) => item.abs));
55542
56013
  return {
55543
56014
  id: worktreeId(worktree.abs),
@@ -55546,7 +56017,7 @@ async function readGitWorktrees(cwd, workers) {
55546
56017
  head: worktree.head,
55547
56018
  ahead,
55548
56019
  behind,
55549
- changed: changed2,
56020
+ changed,
55550
56021
  ...worktree.abs === main2 ? { main: true } : {},
55551
56022
  ...worktree.locked ? { locked: true } : {},
55552
56023
  ...worker ? { worker: {
@@ -55695,7 +56166,7 @@ var init_git_sync = __esm({
55695
56166
  });
55696
56167
 
55697
56168
  // src/bridge/git-review.ts
55698
- import { mkdtemp as mkdtemp5, rm as rm12, writeFile as writeFile7 } from "node:fs/promises";
56169
+ import { mkdtemp as mkdtemp5, rm as rm11, writeFile as writeFile6 } from "node:fs/promises";
55699
56170
  import { tmpdir as tmpdir4 } from "node:os";
55700
56171
  import path97 from "node:path";
55701
56172
  async function repository4(cwd) {
@@ -55750,7 +56221,25 @@ function headerName(raw) {
55750
56221
  function patchFiles(patch) {
55751
56222
  const files = /* @__PURE__ */ new Set();
55752
56223
  let hunks = 0;
56224
+ let oldLeft = 0, newLeft = 0;
55753
56225
  for (const line of patch.split("\n")) {
56226
+ if (oldLeft > 0 || newLeft > 0) {
56227
+ if (line.startsWith("\\")) continue;
56228
+ if (line.startsWith("-")) oldLeft--;
56229
+ else if (line.startsWith("+")) newLeft--;
56230
+ else {
56231
+ oldLeft--;
56232
+ newLeft--;
56233
+ }
56234
+ continue;
56235
+ }
56236
+ const hunk = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line);
56237
+ if (hunk) {
56238
+ hunks++;
56239
+ oldLeft = hunk[1] === void 0 ? 1 : Number(hunk[1]);
56240
+ newLeft = hunk[2] === void 0 ? 1 : Number(hunk[2]);
56241
+ continue;
56242
+ }
55754
56243
  if (/^(?:rename|copy) (?:from|to) |^(?:old|new|deleted file|new file) mode |^GIT binary patch|^Binary files /.test(line)) {
55755
56244
  throw new BridgeError(400, "Only text hunks can be staged one at a time. Stage the whole file instead.");
55756
56245
  }
@@ -55758,7 +56247,6 @@ function patchFiles(patch) {
55758
56247
  const name = headerName(line.slice(4).replace(/\t.*$/, ""));
55759
56248
  if (name) files.add(name);
55760
56249
  }
55761
- if (line.startsWith("@@ ")) hunks++;
55762
56250
  }
55763
56251
  if (!files.size || !hunks) throw new BridgeError(400, "This patch has no hunks.");
55764
56252
  if (files.size > 1) throw new BridgeError(400, "Stage hunks of one file at a time.");
@@ -55773,7 +56261,7 @@ async function gitApply(cwd, rawPatch, reverse) {
55773
56261
  const scratch = await mkdtemp5(path97.join(tmpdir4(), "phren-apply-"));
55774
56262
  const patchFile = path97.join(scratch, "hunk.patch");
55775
56263
  try {
55776
- await writeFile7(patchFile, rawPatch.endsWith("\n") ? rawPatch : rawPatch + "\n", { mode: 384 });
56264
+ await writeFile6(patchFile, rawPatch.endsWith("\n") ? rawPatch : rawPatch + "\n", { mode: 384 });
55777
56265
  const args = ["apply", "--cached", "--whitespace=nowarn", ...reverse === true ? ["-R"] : [], "--", patchFile];
55778
56266
  invalidateTree(root);
55779
56267
  try {
@@ -55785,7 +56273,7 @@ async function gitApply(cwd, rawPatch, reverse) {
55785
56273
  return { ok: true, path: file4, staged: reverse !== true };
55786
56274
  } finally {
55787
56275
  invalidateTree(root);
55788
- await rm12(scratch, { recursive: true, force: true });
56276
+ await rm11(scratch, { recursive: true, force: true });
55789
56277
  }
55790
56278
  }
55791
56279
  function sessionChanges(root, history) {
@@ -55844,8 +56332,8 @@ var init_git_review = __esm({
55844
56332
  // src/bridge/approval-rules.ts
55845
56333
  import { execFile as execFile22 } from "node:child_process";
55846
56334
  import { promisify as promisify20 } from "node:util";
55847
- import { createHash as createHash27, createPublicKey, verify } from "node:crypto";
55848
- import { lstat as lstat26, mkdir as mkdir24, readFile as readFile41, realpath as realpath14 } from "node:fs/promises";
56335
+ import { createHash as createHash28, createPublicKey, verify } from "node:crypto";
56336
+ import { lstat as lstat26, mkdir as mkdir24, readFile as readFile40, realpath as realpath14 } from "node:fs/promises";
55849
56337
  import { hostname as hostname8 } from "node:os";
55850
56338
  import path98 from "node:path";
55851
56339
  async function git6(cwd, ...args) {
@@ -55856,7 +56344,7 @@ async function git6(cwd, ...args) {
55856
56344
  })).stdout;
55857
56345
  }
55858
56346
  async function ownerKeys() {
55859
- const keys2 = await readFile41(path98.join(homeDir(), ".ssh", "authorized_keys"), "utf8");
56347
+ const keys2 = await readFile40(path98.join(homeDir(), ".ssh", "authorized_keys"), "utf8");
55860
56348
  const result = /* @__PURE__ */ new Set();
55861
56349
  for (const line of keys2.split("\n")) {
55862
56350
  const match = /^restrict,pty,command="sh ~\/\.local\/share\/phren\/bridge\/dispatch" ssh-ed25519 ([A-Za-z0-9+/]+={0,2}) phren-iphone\s*$/.exec(line);
@@ -55872,7 +56360,7 @@ function verified(envelope, keys2) {
55872
56360
  const key4 = createPublicKey({ key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), raw]), format: "der", type: "spki" });
55873
56361
  if (!verify(null, payload, key4, signature)) throw forbidden();
55874
56362
  const operation = operationSchema.parse(JSON.parse(payload.toString("utf8")));
55875
- return { operation, owner: createHash27("sha256").update(raw).digest("hex") };
56363
+ return { operation, owner: createHash28("sha256").update(raw).digest("hex") };
55876
56364
  }
55877
56365
  async function privateJSON(file4, fallback2, max = 2097152) {
55878
56366
  const info = await lstat26(file4).catch((error62) => {
@@ -55881,7 +56369,7 @@ async function privateJSON(file4, fallback2, max = 2097152) {
55881
56369
  });
55882
56370
  if (!info) return fallback2;
55883
56371
  if (!info.isFile() || info.isSymbolicLink() || info.mode & 63 || info.size > max) throw new BridgeError(409, "Approval policy must be a private regular file.");
55884
- return JSON.parse(await readFile41(file4, "utf8"));
56372
+ return JSON.parse(await readFile40(file4, "utf8"));
55885
56373
  }
55886
56374
  async function readPolicy(root) {
55887
56375
  const policy = policySchema.parse(await privateJSON(policyPath(root), { operations: [] }));
@@ -55922,7 +56410,7 @@ async function locked(root, work) {
55922
56410
  }
55923
56411
  async function listApprovalRules(root = bridgeRoot(), pairedKey) {
55924
56412
  try {
55925
- const pairedOwner = pairedKey ? createHash27("sha256").update(Buffer.from(pairedKey, "base64")).digest("hex") : void 0;
56413
+ const pairedOwner = pairedKey ? createHash28("sha256").update(Buffer.from(pairedKey, "base64")).digest("hex") : void 0;
55926
56414
  return [...(await readPolicy(root)).rules.values()].map((rule2) => ({
55927
56415
  ...rule2,
55928
56416
  signerFingerprint: "SHA256:" + Buffer.from(rule2.owner, "hex").toString("base64").replace(/=+$/, ""),
@@ -56040,7 +56528,7 @@ var init_approval_rules = __esm({
56040
56528
  });
56041
56529
 
56042
56530
  // src/bridge/conductor-context.ts
56043
- import { readFile as readFile42 } from "node:fs/promises";
56531
+ import { readFile as readFile41 } from "node:fs/promises";
56044
56532
  import path99 from "node:path";
56045
56533
  async function conductorBrief() {
56046
56534
  let source;
@@ -56051,7 +56539,7 @@ async function conductorBrief() {
56051
56539
  path99.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
56052
56540
  path99.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
56053
56541
  ]) {
56054
- source = await readFile42(candidate, "utf8").catch(() => void 0);
56542
+ source = await readFile41(candidate, "utf8").catch(() => void 0);
56055
56543
  if (source !== void 0) break;
56056
56544
  }
56057
56545
  }
@@ -56064,7 +56552,7 @@ async function conductorBrief() {
56064
56552
  async function ensureConductorBrief(brief) {
56065
56553
  const file4 = path99.join(bridgeRoot(), "conductor", "brief.md");
56066
56554
  const content = (brief ?? await conductorBrief()) + "\n";
56067
- if (await readFile42(file4, "utf8").catch(() => void 0) !== content) await atomicInPrivateDir(file4, content);
56555
+ if (await readFile41(file4, "utf8").catch(() => void 0) !== content) await atomicInPrivateDir(file4, content);
56068
56556
  return file4;
56069
56557
  }
56070
56558
  async function conductorContext(target, snapshot2) {
@@ -56084,92 +56572,11 @@ var init_conductor_context = __esm({
56084
56572
  }
56085
56573
  });
56086
56574
 
56087
- // src/bridge/codex-review-mode.ts
56088
- import { open as open18 } from "node:fs/promises";
56089
- import path100 from "node:path";
56090
- async function codexAutoReview(transcriptPath2) {
56091
- if (typeof transcriptPath2 !== "string" || !path100.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path100.basename(transcriptPath2))) return false;
56092
- const file4 = await open18(transcriptPath2, "r").catch(() => void 0);
56093
- if (!file4) return false;
56094
- try {
56095
- const size = (await file4.stat()).size;
56096
- let end = size, carry = Buffer.alloc(0);
56097
- while (end > 0 && size - end < SCAN_LIMIT) {
56098
- const start = Math.max(0, end - CHUNK), buffer = Buffer.alloc(end - start);
56099
- await file4.read(buffer, 0, buffer.length, start);
56100
- const bytes = Buffer.concat([buffer, carry]);
56101
- let lineEnd = bytes.length;
56102
- for (let at2 = bytes.lastIndexOf(10, lineEnd - 1); at2 >= 0; at2 = bytes.lastIndexOf(10, lineEnd - 1)) {
56103
- const settings2 = reviewSettings(bytes.subarray(at2 + 1, lineEnd).toString("utf8"));
56104
- if (settings2) return autoReviewed(settings2);
56105
- lineEnd = at2;
56106
- if (at2 === 0) break;
56107
- }
56108
- carry = bytes.subarray(0, lineEnd);
56109
- end = start;
56110
- }
56111
- const settings = end === 0 ? reviewSettings(carry.toString("utf8")) : void 0;
56112
- return !!settings && autoReviewed(settings);
56113
- } catch {
56114
- return false;
56115
- } finally {
56116
- await file4.close().catch(() => {
56117
- });
56118
- }
56119
- }
56120
- function reviewSettings(line) {
56121
- if (!line.includes('"approvals_reviewer"') || !(line.includes('"type":"turn_context"') || line.includes('"type":"thread_settings_applied"'))) return void 0;
56122
- try {
56123
- const entry2 = JSON.parse(line);
56124
- const payload = entry2?.payload;
56125
- const settings = entry2?.type === "turn_context" ? payload : entry2?.type === "event_msg" && payload?.type === "thread_settings_applied" ? payload.thread_settings : void 0;
56126
- if (!settings || !("approvals_reviewer" in settings)) return void 0;
56127
- return { reviewer: settings.approvals_reviewer, policy: settings.approval_policy };
56128
- } catch {
56129
- return void 0;
56130
- }
56131
- }
56132
- function autoReviewed({ reviewer, policy }) {
56133
- return reviewer === "auto_review" && (policy === "on-request" || !!policy && typeof policy === "object" && "granular" in policy);
56134
- }
56135
- var SCAN_LIMIT, CHUNK;
56136
- var init_codex_review_mode = __esm({
56137
- "src/bridge/codex-review-mode.ts"() {
56138
- "use strict";
56139
- SCAN_LIMIT = 64 * 1048576;
56140
- CHUNK = 1048576;
56141
- }
56142
- });
56143
-
56144
- // src/bridge/codex-thread-origin.ts
56145
- import { open as open19 } from "node:fs/promises";
56146
- import path101 from "node:path";
56147
- async function codexForeignThread(transcriptPath2) {
56148
- if (typeof transcriptPath2 !== "string" || !path101.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path101.basename(transcriptPath2))) return false;
56149
- const file4 = await open19(transcriptPath2, "r").catch(() => void 0);
56150
- if (!file4) return false;
56151
- try {
56152
- const buffer = Buffer.alloc(4096), { bytesRead } = await file4.read(buffer, 0, buffer.length, 0);
56153
- return foreignMeta(buffer.subarray(0, bytesRead).toString("utf8"));
56154
- } finally {
56155
- await file4.close();
56156
- }
56157
- }
56158
- function foreignMeta(head) {
56159
- if (!head.includes('"session_meta"')) return false;
56160
- return /"originator"\s*:\s*"codex_exec"/.test(head) || /"source"\s*:\s*"exec"/.test(head) || /"source"\s*:\s*\{\s*"subagent"/.test(head);
56161
- }
56162
- var init_codex_thread_origin = __esm({
56163
- "src/bridge/codex-thread-origin.ts"() {
56164
- "use strict";
56165
- }
56166
- });
56167
-
56168
56575
  // src/bridge/push.ts
56169
56576
  import { createCipheriv, createHmac as createHmac3, createPrivateKey, randomBytes as randomBytes6, sign } from "node:crypto";
56170
- import { readFile as readFile43, stat as stat21 } from "node:fs/promises";
56577
+ import { readFile as readFile42, stat as stat21 } from "node:fs/promises";
56171
56578
  import { connect as connect3 } from "node:http2";
56172
- import path102 from "node:path";
56579
+ import path100 from "node:path";
56173
56580
  function scheduleCollapseId(kind, runId) {
56174
56581
  return `${runId.slice(0, 63 - kind.length)}-${kind}`;
56175
56582
  }
@@ -56238,7 +56645,7 @@ async function secureJSON(file4, schema) {
56238
56645
  try {
56239
56646
  const metadata = await stat21(file4);
56240
56647
  if ((metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
56241
- return schema.parse(JSON.parse(await readFile43(file4, "utf8")));
56648
+ return schema.parse(JSON.parse(await readFile42(file4, "utf8")));
56242
56649
  } catch {
56243
56650
  return void 0;
56244
56651
  }
@@ -56247,12 +56654,12 @@ async function secureFile(file4) {
56247
56654
  try {
56248
56655
  const metadata = await stat21(file4);
56249
56656
  if (!metadata.isFile() || (metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
56250
- return await readFile43(file4, "utf8");
56657
+ return await readFile42(file4, "utf8");
56251
56658
  } catch {
56252
56659
  return void 0;
56253
56660
  }
56254
56661
  }
56255
- function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path102.join(bridgeRoot(), "apns.json")) {
56662
+ function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path100.join(bridgeRoot(), "apns.json")) {
56256
56663
  return [
56257
56664
  "Approval push is not configured: the phone only alerts while Phren runs, and a registered phone gets nothing while suspended.",
56258
56665
  "1. In your Apple developer account, create an APNs key (Keys, Apple Push Notifications service) and download AuthKey_<KEYID>.p8.",
@@ -56405,13 +56812,13 @@ var init_push = __esm({
56405
56812
  ApprovalPushService = class {
56406
56813
  devices = [];
56407
56814
  sender;
56408
- devicesFile = path102.join(bridgeRoot(), "push-devices.json");
56815
+ devicesFile = path100.join(bridgeRoot(), "push-devices.json");
56409
56816
  async start() {
56410
56817
  this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
56411
- const configFile = process.env.PHREN_APNS_CONFIG || path102.join(bridgeRoot(), "apns.json");
56818
+ const configFile = process.env.PHREN_APNS_CONFIG || path100.join(bridgeRoot(), "apns.json");
56412
56819
  const config4 = await secureJSON(configFile, configSchema2);
56413
56820
  if (!config4) return;
56414
- const keyPath = path102.isAbsolute(config4.privateKeyPath) ? config4.privateKeyPath : path102.resolve(path102.dirname(configFile), config4.privateKeyPath);
56821
+ const keyPath = path100.isAbsolute(config4.privateKeyPath) ? config4.privateKeyPath : path100.resolve(path100.dirname(configFile), config4.privateKeyPath);
56415
56822
  const key4 = await secureFile(keyPath);
56416
56823
  if (key4) this.sender = new APNsSender(config4, key4);
56417
56824
  }
@@ -56739,10 +57146,18 @@ async function scopedDispatch(scope, command, io) {
56739
57146
  answered = true;
56740
57147
  io.output.write(httpResponse(503, "Phren Hook is not running on this computer."));
56741
57148
  });
56742
- socket.on("close", () => resolve17());
57149
+ socket.setTimeout(io.answerIdleMs ?? ANSWER_IDLE_MS, () => socket.destroy());
57150
+ const drop = () => socket.destroy();
57151
+ io.output.once("error", drop);
57152
+ io.output.once("close", drop);
57153
+ socket.on("close", () => {
57154
+ io.output.off("error", drop);
57155
+ io.output.off("close", drop);
57156
+ resolve17();
57157
+ });
56743
57158
  });
56744
57159
  }
56745
- var GATEWAY_SCOPES, SCOPE_KEY_COMMENT, SCOPED_COMMAND, MAX_HEAD, MAX_HEADER_LINE, MAX_HEADERS, READ_TIMEOUT_MS, PROJECT, one, only, RULES, DESCRIBE, refuse, REASONS;
57160
+ var GATEWAY_SCOPES, SCOPE_KEY_COMMENT, SCOPED_COMMAND, MAX_HEAD, MAX_HEADER_LINE, MAX_HEADERS, READ_TIMEOUT_MS, ANSWER_IDLE_MS, PROJECT, one, only, RULES, DESCRIBE, refuse, REASONS;
56746
57161
  var init_scoped_gateway = __esm({
56747
57162
  "src/bridge/scoped-gateway.ts"() {
56748
57163
  "use strict";
@@ -56755,6 +57170,7 @@ var init_scoped_gateway = __esm({
56755
57170
  MAX_HEADER_LINE = 8192;
56756
57171
  MAX_HEADERS = 32;
56757
57172
  READ_TIMEOUT_MS = 1e4;
57173
+ ANSWER_IDLE_MS = 6e4;
56758
57174
  PROJECT = PROJECT_NAME2.source.slice(1, -1);
56759
57175
  one = (query, key4) => query.get(key4)?.length === 1 ? query.get(key4)[0] : void 0;
56760
57176
  only = (query, keys2) => [...query.keys()].every((key4) => keys2.includes(key4));
@@ -56828,10 +57244,10 @@ var init_pair = __esm({
56828
57244
 
56829
57245
  // src/bridge/opencode-permissions.ts
56830
57246
  import { randomUUID as randomUUID23 } from "node:crypto";
56831
- import { lstat as lstat27, mkdir as mkdir25, readFile as readFile44, rename as rename7, unlink as unlink6, writeFile as writeFile8 } from "node:fs/promises";
56832
- import path103 from "node:path";
57247
+ import { lstat as lstat27, mkdir as mkdir25, readFile as readFile43, rename as rename6, unlink as unlink6, writeFile as writeFile7 } from "node:fs/promises";
57248
+ import path101 from "node:path";
56833
57249
  function opencodeConfigPath(env = process.env, home = homeDir(env)) {
56834
- return path103.join(env.XDG_CONFIG_HOME || path103.join(home, ".config"), "opencode", "opencode.json");
57250
+ return path101.join(env.XDG_CONFIG_HOME || path101.join(home, ".config"), "opencode", "opencode.json");
56835
57251
  }
56836
57252
  function opencodeToolName(value2) {
56837
57253
  if (typeof value2 !== "string") return void 0;
@@ -56841,7 +57257,7 @@ function opencodeToolName(value2) {
56841
57257
  async function readConfig2(file4) {
56842
57258
  let text5;
56843
57259
  try {
56844
- text5 = await readFile44(file4, "utf8");
57260
+ text5 = await readFile43(file4, "utf8");
56845
57261
  } catch (error62) {
56846
57262
  if (error62.code === "ENOENT") return {};
56847
57263
  throw new BridgeError(409, "Could not read ~/.config/opencode/opencode.json.");
@@ -56879,12 +57295,12 @@ async function allowOpencodeToolEverywhere(tool, file4 = opencodeConfigPath()) {
56879
57295
  try {
56880
57296
  const config4 = withAllowedTool(await readConfig2(file4), name);
56881
57297
  const mode = (await lstat27(file4).catch(() => void 0))?.mode;
56882
- await mkdir25(path103.dirname(file4), { recursive: true, mode: 448 });
57298
+ await mkdir25(path101.dirname(file4), { recursive: true, mode: 448 });
56883
57299
  const temporary = `${file4}.${randomUUID23()}.tmp`;
56884
- await writeFile8(temporary, `${JSON.stringify(config4, null, 2)}
57300
+ await writeFile7(temporary, `${JSON.stringify(config4, null, 2)}
56885
57301
  `, { mode: mode === void 0 ? 384 : mode & 511, flag: "wx" });
56886
57302
  try {
56887
- await rename7(temporary, file4);
57303
+ await rename6(temporary, file4);
56888
57304
  } finally {
56889
57305
  await unlink6(temporary).catch(() => {
56890
57306
  });
@@ -56904,29 +57320,37 @@ var init_opencode_permissions = __esm({
56904
57320
  });
56905
57321
 
56906
57322
  // src/bridge/prompt-deliveries.ts
56907
- import { createHash as createHash28 } from "node:crypto";
56908
- import { readFileSync as readFileSync41 } from "node:fs";
56909
- import { open as open20 } from "node:fs/promises";
57323
+ import { createHash as createHash29 } from "node:crypto";
57324
+ import { readFileSync as readFileSync43 } from "node:fs";
57325
+ import { open as open18 } from "node:fs/promises";
56910
57326
  function promptKey(text5) {
56911
57327
  return unwrapPastedContent(text5).split("\n").filter((line) => !PICTURE_PATH_LINE.test(line)).join("\n").replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
56912
57328
  }
56913
- async function transcriptHas(record4) {
56914
- const file4 = await open20(await transcriptPath(record4.source, record4.session), "r");
57329
+ function matchingOffsets(buffer, start, record4) {
57330
+ const entries2 = [];
57331
+ const lines = buffer.toString("utf8").split("\n");
57332
+ let offset = start + buffer.length;
57333
+ for (let index2 = lines.length - 1; index2 >= 0; index2--) {
57334
+ const line = lines[index2];
57335
+ offset -= Buffer.byteLength(line) + (index2 < lines.length - 1 ? 1 : 0);
57336
+ let row;
57337
+ try {
57338
+ row = object2(JSON.parse(line));
57339
+ } catch {
57340
+ continue;
57341
+ }
57342
+ const stamp2 = Date.parse(String(row.timestamp ?? ""));
57343
+ if (Number.isFinite(stamp2) && stamp2 < record4.at - 5e3) break;
57344
+ if (userTexts(row).some((text5) => promptHash(text5) === record4.hash)) entries2.push({ offset, hook: row.type === "user" });
57345
+ }
57346
+ return entries2;
57347
+ }
57348
+ async function transcriptEntries(record4) {
57349
+ const file4 = await open18(await transcriptPath(record4.source, record4.session), "r");
56915
57350
  try {
56916
57351
  const size = (await file4.stat()).size, start = Math.max(0, size - 524288), buffer = Buffer.alloc(size - start);
56917
57352
  await file4.read(buffer, 0, buffer.length, start);
56918
- for (const line of buffer.toString("utf8").split("\n").reverse()) {
56919
- let row;
56920
- try {
56921
- row = object2(JSON.parse(line));
56922
- } catch {
56923
- continue;
56924
- }
56925
- const stamp2 = Date.parse(String(row.timestamp ?? ""));
56926
- if (Number.isFinite(stamp2) && stamp2 < record4.at - 5e3) break;
56927
- for (const text5 of userTexts(row)) if (promptHash(text5) === record4.hash) return true;
56928
- }
56929
- return false;
57353
+ return matchingOffsets(buffer, start, record4);
56930
57354
  } finally {
56931
57355
  await file4.close();
56932
57356
  }
@@ -56938,12 +57362,13 @@ function userTexts(row) {
56938
57362
  else for (const block of objects(content)) if (typeof block.text === "string") texts.push(block.text);
56939
57363
  };
56940
57364
  if (row.type === "user" && !row.isMeta) blocks(object2(row.message).content);
57365
+ if (row.type === "queue-operation" && row.operation === "remove" && typeof row.content === "string" && (row.reason === "absorbed_mid_turn" || row.reason === "delivered_to_agent")) texts.push(row.content);
56941
57366
  const payload = object2(row.payload);
56942
57367
  if (payload.type === "user_message" && typeof payload.message === "string") texts.push(payload.message);
56943
57368
  if (payload.type === "message" && payload.role === "user") blocks(payload.content);
56944
57369
  return texts;
56945
57370
  }
56946
- var DELIVERY_RETENTION_MS, DELIVERY_GIVE_UP_MS, MAX_RECORDS, PICTURE_PATH_LINE, promptHash, recordSchema2, PromptDeliveries;
57371
+ var DELIVERY_RETENTION_MS, DELIVERY_GIVE_UP_MS, MAX_RECORDS, LANDED_CHECK_MS, ENTRY_SLACK_MS, PICTURE_PATH_LINE, promptHash, recordSchema2, PromptDeliveries;
56947
57372
  var init_prompt_deliveries = __esm({
56948
57373
  "src/bridge/prompt-deliveries.ts"() {
56949
57374
  "use strict";
@@ -56953,8 +57378,10 @@ var init_prompt_deliveries = __esm({
56953
57378
  DELIVERY_RETENTION_MS = 24 * 36e5;
56954
57379
  DELIVERY_GIVE_UP_MS = 3e4;
56955
57380
  MAX_RECORDS = 512;
57381
+ LANDED_CHECK_MS = 3e3;
57382
+ ENTRY_SLACK_MS = 5e3;
56956
57383
  PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
56957
- promptHash = (text5) => createHash28("sha256").update(promptKey(text5)).digest("hex");
57384
+ promptHash = (text5) => createHash29("sha256").update(promptKey(text5)).digest("hex");
56958
57385
  recordSchema2 = external_exports.object({
56959
57386
  id: external_exports.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional(),
56960
57387
  hash: external_exports.string().regex(/^[0-9a-f]{64}$/),
@@ -56967,16 +57394,18 @@ var init_prompt_deliveries = __esm({
56967
57394
  reason: external_exports.string().max(500).optional(),
56968
57395
  at: external_exports.number(),
56969
57396
  settledAt: external_exports.number().optional(),
56970
- stoppedAt: external_exports.number().optional()
57397
+ stoppedAt: external_exports.number().optional(),
57398
+ /** The transcript entry (byte offset) that settled it, so no other message claims the same one. */
57399
+ entry: external_exports.number().optional()
56971
57400
  }).strict();
56972
- PromptDeliveries = class {
56973
- constructor(file4, now = Date.now, landed = transcriptHas) {
57401
+ PromptDeliveries = class _PromptDeliveries {
57402
+ constructor(file4, now = Date.now, landed = transcriptEntries) {
56974
57403
  this.file = file4;
56975
57404
  this.now = now;
56976
57405
  this.landed = landed;
56977
57406
  if (!file4) return;
56978
57407
  try {
56979
- for (const row of objects(object2(JSON.parse(readFileSync41(file4, "utf8"))).records)) {
57408
+ for (const row of objects(object2(JSON.parse(readFileSync43(file4, "utf8"))).records)) {
56980
57409
  const parsed = recordSchema2.safeParse(row);
56981
57410
  if (parsed.success) this.records.push({ ...parsed.data, state: parsed.data.state === "typed" ? "queued" : parsed.data.state });
56982
57411
  }
@@ -56990,6 +57419,18 @@ var init_prompt_deliveries = __esm({
56990
57419
  records = [];
56991
57420
  waiters = /* @__PURE__ */ new Map();
56992
57421
  writing = Promise.resolve();
57422
+ /** Panes (server, pane, agent) that sent a UserPromptSubmit or Stop since the Hook started. */
57423
+ hookPanes = /* @__PURE__ */ new Set();
57424
+ paneKey(target) {
57425
+ return [target.server, target.pane, target.source].join("|");
57426
+ }
57427
+ static open(record4) {
57428
+ return record4.state === "typed" || record4.state === "queued";
57429
+ }
57430
+ /** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
57431
+ static claimable(record4) {
57432
+ return _PromptDeliveries.open(record4) || record4.state === "failed" && !!record4.hookClaim;
57433
+ }
56993
57434
  samePane(record4, target) {
56994
57435
  return record4.server === target.server && record4.pane === target.pane && record4.source === target.source;
56995
57436
  }
@@ -57003,7 +57444,7 @@ var init_prompt_deliveries = __esm({
57003
57444
  }
57004
57445
  save() {
57005
57446
  if (!this.file) return;
57006
- const rows2 = this.records.filter((record4) => record4.id).map(({ idleSince: _2, ...row }) => row);
57447
+ const rows2 = this.records.filter((record4) => record4.id || record4.entry !== void 0).map(({ idleSince: _2, checkedAt: __, hookClaim: ___, seenRow: ____, ...row }) => row);
57007
57448
  const file4 = this.file;
57008
57449
  this.writing = this.writing.then(() => atomicInPrivateDir(file4, { records: rows2 })).catch(() => void 0);
57009
57450
  }
@@ -57126,14 +57567,14 @@ var init_prompt_deliveries = __esm({
57126
57567
  * input still pending on the old one stays there, out of the pane's view.
57127
57568
  * Fails loudly; a late UserPromptSubmit from the old thread still settles it. */
57128
57569
  threadChanged(previous) {
57129
- let changed2 = false;
57570
+ let changed = false;
57130
57571
  for (const record4 of this.records) if ((record4.state === "typed" || record4.state === "queued") && this.samePane(record4, previous) && record4.session === previous.session) {
57131
57572
  record4.state = "failed";
57132
57573
  record4.settledAt = this.now();
57133
- changed2 = true;
57574
+ changed = true;
57134
57575
  record4.reason = "The pane moved to another Codex conversation before the agent took the message.";
57135
57576
  }
57136
- if (changed2) this.save();
57577
+ if (changed) this.save();
57137
57578
  }
57138
57579
  /** False when `id` names another message: other words or another pane. */
57139
57580
  sameMessage(id2, target, text5) {
@@ -57154,23 +57595,104 @@ var init_prompt_deliveries = __esm({
57154
57595
  /** Conversation `target` just submitted `prompt`. Its own record wins, then
57155
57596
  * the oldest open one in the same pane: the agent kept the text across a
57156
57597
  * conversation change, and the conversation now in the pane is where it
57157
- * went. A prompt nothing matches was typed locally. Never refused. */
57158
- submitted(target, prompt) {
57598
+ * went. A prompt nothing matches was typed locally. Never refused.
57599
+ * For Claude the transcript is consulted first and the submission claims
57600
+ * the earliest unclaimed user row with these words, through the same
57601
+ * `settle` and the same table of claimed entries the idle check uses: a
57602
+ * callback for a row already claimed (the idle check settled it, the hook
57603
+ * came late) settles nothing more. */
57604
+ async submitted(target, prompt) {
57159
57605
  const hash2 = promptHash(prompt);
57160
- const open30 = this.records.filter((record5) => record5.hash === hash2 && this.samePane(record5, target) && record5.state !== "delivered");
57161
- const record4 = open30.find((entry2) => entry2.session === target.session) ?? open30[0];
57606
+ this.hookPanes.add(this.paneKey(target));
57607
+ const pick3 = () => {
57608
+ const open30 = this.records.filter((record5) => record5.hash === hash2 && this.samePane(record5, target) && record5.state !== "delivered");
57609
+ return open30.find((entry3) => entry3.session === target.session) ?? open30[0];
57610
+ };
57611
+ let record4 = pick3();
57162
57612
  if (!record4) return;
57613
+ let entry2;
57614
+ if (target.source === "claude") {
57615
+ let rows2;
57616
+ try {
57617
+ rows2 = (await this.landed({ source: target.source, session: target.session, hash: hash2, at: record4.at })).filter((row) => row.hook);
57618
+ } catch {
57619
+ rows2 = void 0;
57620
+ }
57621
+ record4 = pick3();
57622
+ if (!record4) return;
57623
+ const claimed = new Set(this.records.filter((other) => other.hash === hash2 && this.samePane(other, target) && other.session === target.session && other.entry !== void 0).map((other) => other.entry));
57624
+ if (!rows2 && !claimed.size) {
57625
+ this.settle(record4, void 0, target.session);
57626
+ this.save();
57627
+ return;
57628
+ }
57629
+ if (!rows2?.length) {
57630
+ record4.hookClaim = true;
57631
+ record4.session = target.session;
57632
+ return;
57633
+ }
57634
+ const free = rows2.filter((row) => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
57635
+ if (!free) return;
57636
+ entry2 = free.offset;
57637
+ }
57638
+ this.settle(record4, entry2, target.session);
57639
+ this.save();
57640
+ }
57641
+ /** Marks `record` delivered, with the transcript entry that settled it when known. */
57642
+ settle(record4, entry2, session) {
57163
57643
  record4.state = "delivered";
57164
- record4.session = target.session;
57165
57644
  record4.settledAt = this.now();
57166
57645
  delete record4.reason;
57167
- this.save();
57646
+ delete record4.hookClaim;
57647
+ delete record4.seenRow;
57648
+ if (session) record4.session = session;
57649
+ if (entry2 !== void 0) record4.entry = entry2;
57168
57650
  this.release(record4, "delivered");
57169
57651
  }
57652
+ /** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
57653
+ * An entry settles one message: the table of records' `entry` offsets (per conversation) is the only
57654
+ * state, so neither this path nor the hook's can settle two messages with one turn. A user row is a
57655
+ * turn start whose UserPromptSubmit hook settles the message itself, so while the agent works only a
57656
+ * mid-turn queue removal (no hook fires for it) settles from the transcript; once the agent is idle
57657
+ * (`working` false) a user row settles too, for a hook that never came. Of several identical open
57658
+ * messages the oldest take the entries. `pass` carries the entries still unclaimed within one observe. */
57659
+ async taken(record4, pass, working = false) {
57660
+ if (record4.source !== "claude") return (await this.landed(record4).catch(() => [])).length > 0;
57661
+ const same2 = (other) => other.hash === record4.hash && other.server === record4.server && other.pane === record4.pane && other.session === record4.session;
57662
+ const open30 = this.records.filter((other) => same2(other) && _PromptDeliveries.claimable(other)).sort((a, b) => a.at - b.at);
57663
+ if (open30[0] !== record4) return false;
57664
+ const key4 = [record4.hash, record4.server, record4.pane, record4.session, working].join("|");
57665
+ let free = pass.get(key4);
57666
+ if (!free) {
57667
+ const found = (await this.landed(record4).catch(() => [])).sort((a, b) => a.offset - b.offset);
57668
+ const used = new Set(this.records.filter((other) => same2(other) && other.entry !== void 0).map((other) => other.entry));
57669
+ let hooked = this.records.filter((other) => same2(other) && other.state === "delivered" && other.entry === void 0 && (other.settledAt ?? 0) >= record4.at - ENTRY_SLACK_MS).length;
57670
+ const unclaimed = found.filter((entry3) => !used.has(entry3.offset)).filter((entry3) => !(entry3.hook && hooked-- > 0));
57671
+ if (working) {
57672
+ const row = unclaimed.find((entry3) => entry3.hook);
57673
+ const hookless = !this.hookPanes.has(this.paneKey(record4));
57674
+ const own2 = row && (record4.hookClaim || hookless && record4.seenRow === row.offset);
57675
+ if (row && hookless && !own2) record4.seenRow = row.offset;
57676
+ free = unclaimed.filter((entry3) => !entry3.hook || own2 && entry3 === row);
57677
+ } else free = unclaimed;
57678
+ }
57679
+ if (!_PromptDeliveries.claimable(record4)) return false;
57680
+ const entry2 = free.shift();
57681
+ pass.set(key4, free);
57682
+ if (entry2 === void 0) return false;
57683
+ record4.entry = entry2.offset;
57684
+ return true;
57685
+ }
57170
57686
  /** A turn in `target`'s pane ended: the agent now takes held input or never will. */
57171
57687
  stopped(target) {
57172
57688
  const at2 = this.now();
57173
- for (const record4 of this.records) if (this.samePane(record4, target) && (record4.state === "typed" || record4.state === "queued") && record4.at < at2) record4.stoppedAt = at2;
57689
+ this.hookPanes.add(this.paneKey(target));
57690
+ let marked = false;
57691
+ for (const record4 of this.records) if (this.samePane(record4, target) && (record4.state === "typed" || record4.state === "queued") && record4.at < at2) {
57692
+ record4.stoppedAt = at2;
57693
+ marked = true;
57694
+ }
57695
+ if (marked) this.save();
57174
57696
  }
57175
57697
  /** Called on the Hook's activity tick with a server's panes. A message
57176
57698
  * still held fails loudly when its pane closed, its agent restarted, or the
@@ -57178,53 +57700,126 @@ var init_prompt_deliveries = __esm({
57178
57700
  * transcript shows it after all). */
57179
57701
  async observe(server, panes2) {
57180
57702
  const now = this.now();
57181
- let changed2 = false;
57703
+ let changed = false;
57704
+ const pass = /* @__PURE__ */ new Map();
57182
57705
  for (const record4 of this.records) {
57183
- if (record4.server !== server || record4.state !== "typed" && record4.state !== "queued") continue;
57706
+ if (record4.server !== server) continue;
57707
+ if (record4.state === "failed" && record4.hookClaim) {
57708
+ if (record4.source === "claude" && (record4.checkedAt === void 0 || now - record4.checkedAt >= LANDED_CHECK_MS)) {
57709
+ record4.checkedAt = now;
57710
+ if (await this.taken(record4, pass, true)) {
57711
+ this.settle(record4);
57712
+ changed = true;
57713
+ }
57714
+ }
57715
+ continue;
57716
+ }
57717
+ if (record4.state !== "typed" && record4.state !== "queued") continue;
57184
57718
  const pane = panes2.find((entry2) => entry2.pane_id === record4.pane);
57185
57719
  if (!pane || record4.terminal && pane.terminal_id !== record4.terminal || pane.agent && pane.agent !== record4.source) {
57186
- if (await this.landed(record4).catch(() => false)) {
57187
- record4.state = "delivered";
57188
- record4.settledAt = now;
57189
- changed2 = true;
57190
- this.release(record4, "delivered");
57720
+ if (await this.taken(record4, pass)) {
57721
+ this.settle(record4);
57722
+ changed = true;
57191
57723
  continue;
57192
57724
  }
57725
+ if (!_PromptDeliveries.open(record4)) continue;
57193
57726
  record4.state = "failed";
57194
57727
  record4.settledAt = now;
57195
- changed2 = true;
57728
+ changed = true;
57196
57729
  record4.reason = pane ? "The agent in this pane restarted before it took the message." : "The agent's pane closed before it took the message.";
57197
57730
  continue;
57198
57731
  }
57199
57732
  if (!["idle", "done"].includes(String(pane.agent_status))) {
57200
57733
  record4.idleSince = void 0;
57734
+ if (record4.source === "claude" && (record4.checkedAt === void 0 || now - record4.checkedAt >= LANDED_CHECK_MS)) {
57735
+ record4.checkedAt = now;
57736
+ if (await this.taken(record4, pass, true)) {
57737
+ this.settle(record4);
57738
+ changed = true;
57739
+ }
57740
+ }
57201
57741
  continue;
57202
57742
  }
57203
57743
  record4.idleSince ??= now;
57204
57744
  if (record4.stoppedAt === void 0 || now - Math.max(record4.idleSince, record4.stoppedAt) < DELIVERY_GIVE_UP_MS) continue;
57205
- if (await this.landed(record4).catch(() => false)) {
57206
- record4.state = "delivered";
57207
- record4.settledAt = now;
57208
- changed2 = true;
57209
- this.release(record4, "delivered");
57745
+ if (await this.taken(record4, pass)) {
57746
+ this.settle(record4);
57747
+ changed = true;
57210
57748
  continue;
57211
57749
  }
57750
+ if (!_PromptDeliveries.open(record4)) continue;
57212
57751
  record4.state = "failed";
57213
57752
  record4.settledAt = now;
57214
- changed2 = true;
57753
+ changed = true;
57215
57754
  record4.reason = "The agent finished its turn without taking the message.";
57216
57755
  }
57217
- if (changed2) this.save();
57756
+ if (changed) this.save();
57218
57757
  }
57219
57758
  };
57220
57759
  }
57221
57760
  });
57222
57761
 
57762
+ // src/bridge/agent-hook-asks.ts
57763
+ function appServerApproval(request9) {
57764
+ const params = request9.params;
57765
+ const reason2 = typeof params.reason === "string" && params.reason ? { reason: params.reason } : {};
57766
+ if (request9.method === "item/commandExecution/requestApproval") {
57767
+ return { tool: "Bash", input: {
57768
+ ...typeof params.command === "string" ? { command: params.command } : {},
57769
+ ...typeof params.cwd === "string" ? { cwd: params.cwd } : {},
57770
+ ...reason2
57771
+ } };
57772
+ }
57773
+ if (request9.method === "item/fileChange/requestApproval") {
57774
+ const changes = objects(params.changes);
57775
+ const verb = (change) => object2(change.kind).type === "add" ? "Add" : object2(change.kind).type === "delete" ? "Delete" : "Update";
57776
+ const patch = changes.filter((change) => typeof change.path === "string").map((change) => `*** ${verb(change)} File: ${change.path}`).join("\n");
57777
+ return { tool: "apply_patch", input: { ...patch ? { patch } : {}, ...typeof params.grantRoot === "string" ? { grantRoot: params.grantRoot } : {}, ...reason2 } };
57778
+ }
57779
+ if (request9.method === "item/permissions/requestApproval") return { tool: "Permissions", input: { permissions: params.permissions ?? {}, ...reason2 } };
57780
+ return void 0;
57781
+ }
57782
+ function appServerDecision(request9, allow) {
57783
+ if (request9.method === "item/permissions/requestApproval") return { permissions: allow ? object2(request9.params.permissions) : {}, scope: "turn" };
57784
+ return { decision: allow ? "accept" : "decline" };
57785
+ }
57786
+ function conductorCall(tool, input2) {
57787
+ const tail2 = /(?:^|[.:/]|__)(dispatch|hand_off|phren_admin)$/.exec(tool.replace(/^mcp_phren_/, ""))?.[1];
57788
+ const fields2 = object2(input2);
57789
+ let action;
57790
+ if (tail2 === "dispatch") action = "dispatch";
57791
+ else if (tail2 === "hand_off") action = "hand_off";
57792
+ else if (tail2 === "phren_admin" && (fields2.action === "dispatch" || fields2.action === "hand_off")) action = fields2.action;
57793
+ if (!action) return void 0;
57794
+ const project = typeof fields2.project === "string" ? fields2.project : void 0;
57795
+ const computer = typeof fields2.computer === "string" ? fields2.computer : void 0;
57796
+ return { action, ...project ? { project } : {}, ...computer ? { computer } : {} };
57797
+ }
57798
+ function opencodePermissionReply(decision) {
57799
+ if (decision === "approve") return "once";
57800
+ if (decision === "deny") return "reject";
57801
+ if (decision === "allow-project" || decision === "allow-everywhere") return "always";
57802
+ return void 0;
57803
+ }
57804
+ var OPENCODE_APPROVAL_OPTIONS;
57805
+ var init_agent_hook_asks = __esm({
57806
+ "src/bridge/agent-hook-asks.ts"() {
57807
+ "use strict";
57808
+ init_protocol();
57809
+ OPENCODE_APPROVAL_OPTIONS = [
57810
+ { label: "Allow once", decision: "approve" },
57811
+ { label: "Allow for this project", decision: "allow-project" },
57812
+ { label: "Allow everywhere", decision: "allow-everywhere" },
57813
+ { label: "Deny", decision: "deny" }
57814
+ ];
57815
+ }
57816
+ });
57817
+
57223
57818
  // src/bridge/opencode-pane-server.ts
57224
57819
  import * as crypto12 from "node:crypto";
57225
57820
  import * as fs42 from "node:fs";
57226
57821
  import * as net from "node:net";
57227
- import * as path104 from "node:path";
57822
+ import * as path102 from "node:path";
57228
57823
  function safeSegment(value2) {
57229
57824
  return typeof value2 === "string" && value2.length > 0 && value2 !== "." && value2 !== ".." && !/[/\\\u0000-\u001f\u007f]/.test(value2);
57230
57825
  }
@@ -57242,7 +57837,7 @@ function alive(pid) {
57242
57837
  }
57243
57838
  }
57244
57839
  function paneServerFile(dir, server, pane) {
57245
- return path104.join(dir, `${encodeURIComponent(`${server}/${pane}`)}.json`);
57840
+ return path102.join(dir, `${encodeURIComponent(`${server}/${pane}`)}.json`);
57246
57841
  }
57247
57842
  function registerPaneServer(dir, entry2) {
57248
57843
  if (!validEntry(entry2)) throw new Error("Invalid OpenCode pane server entry.");
@@ -57280,7 +57875,7 @@ function listPaneServers(dir) {
57280
57875
  const entries2 = [];
57281
57876
  for (const name of names.slice(0, 1024)) {
57282
57877
  if (!name.endsWith(".json")) continue;
57283
- const file4 = path104.join(dir, name);
57878
+ const file4 = path102.join(dir, name);
57284
57879
  let parsed;
57285
57880
  try {
57286
57881
  const info = fs42.lstatSync(file4);
@@ -57492,10 +58087,10 @@ var init_opencode_pane_server = __esm({
57492
58087
 
57493
58088
  // src/bridge/opencode-panes.ts
57494
58089
  import { execFile as execFile24 } from "node:child_process";
57495
- import path105 from "node:path";
58090
+ import path103 from "node:path";
57496
58091
  import { promisify as promisify22 } from "node:util";
57497
58092
  function paneServersDir() {
57498
- return path105.join(bridgeRoot(), "opencode-panes");
58093
+ return path103.join(bridgeRoot(), "opencode-panes");
57499
58094
  }
57500
58095
  function servedPane(server, pane) {
57501
58096
  return readPaneServer(paneServersDir(), server, pane);
@@ -57729,69 +58324,99 @@ var init_opencode_panes = __esm({
57729
58324
  }
57730
58325
  });
57731
58326
 
57732
- // src/bridge/agent-hooks.ts
57733
- import { request as request6, createServer as createServer3 } from "node:http";
57734
- import { mkdir as mkdir26, readFile as readFile45, chmod as chmod4, unlink as unlink7, lstat as lstat28 } from "node:fs/promises";
57735
- import { watch } from "node:fs";
57736
- import path106 from "node:path";
57737
- import { randomUUID as randomUUID24 } from "node:crypto";
57738
- import { hostname as hostname10 } from "node:os";
57739
- function watchHangUp(res) {
57740
- let closed = res.destroyed || res.socket?.destroyed === true;
57741
- const onClose = () => {
57742
- if (!res.writableEnded) closed = true;
57743
- };
57744
- res.once("close", onClose);
57745
- return () => {
57746
- res.off("close", onClose);
57747
- return closed || res.destroyed;
57748
- };
58327
+ // src/bridge/codex-review-mode.ts
58328
+ import { open as open19 } from "node:fs/promises";
58329
+ import path104 from "node:path";
58330
+ async function codexAutoReview(transcriptPath2) {
58331
+ if (typeof transcriptPath2 !== "string" || !path104.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path104.basename(transcriptPath2))) return false;
58332
+ const file4 = await open19(transcriptPath2, "r").catch(() => void 0);
58333
+ if (!file4) return false;
58334
+ try {
58335
+ const size = (await file4.stat()).size;
58336
+ let end = size, carry = Buffer.alloc(0);
58337
+ while (end > 0 && size - end < SCAN_LIMIT) {
58338
+ const start = Math.max(0, end - CHUNK), buffer = Buffer.alloc(end - start);
58339
+ await file4.read(buffer, 0, buffer.length, start);
58340
+ const bytes = Buffer.concat([buffer, carry]);
58341
+ let lineEnd = bytes.length;
58342
+ for (let at2 = bytes.lastIndexOf(10, lineEnd - 1); at2 >= 0; at2 = bytes.lastIndexOf(10, lineEnd - 1)) {
58343
+ const settings2 = reviewSettings(bytes.subarray(at2 + 1, lineEnd).toString("utf8"));
58344
+ if (settings2) return autoReviewed(settings2);
58345
+ lineEnd = at2;
58346
+ if (at2 === 0) break;
58347
+ }
58348
+ carry = bytes.subarray(0, lineEnd);
58349
+ end = start;
58350
+ }
58351
+ const settings = end === 0 ? reviewSettings(carry.toString("utf8")) : void 0;
58352
+ return !!settings && autoReviewed(settings);
58353
+ } catch {
58354
+ return false;
58355
+ } finally {
58356
+ await file4.close().catch(() => {
58357
+ });
58358
+ }
57749
58359
  }
57750
- function appServerApproval(request9) {
57751
- const params = request9.params;
57752
- const reason2 = typeof params.reason === "string" && params.reason ? { reason: params.reason } : {};
57753
- if (request9.method === "item/commandExecution/requestApproval") {
57754
- return { tool: "Bash", input: {
57755
- ...typeof params.command === "string" ? { command: params.command } : {},
57756
- ...typeof params.cwd === "string" ? { cwd: params.cwd } : {},
57757
- ...reason2
57758
- } };
58360
+ function reviewSettings(line) {
58361
+ if (!line.includes('"approvals_reviewer"') || !(line.includes('"type":"turn_context"') || line.includes('"type":"thread_settings_applied"'))) return void 0;
58362
+ try {
58363
+ const entry2 = JSON.parse(line);
58364
+ const payload = entry2?.payload;
58365
+ const settings = entry2?.type === "turn_context" ? payload : entry2?.type === "event_msg" && payload?.type === "thread_settings_applied" ? payload.thread_settings : void 0;
58366
+ if (!settings || !("approvals_reviewer" in settings)) return void 0;
58367
+ return { reviewer: settings.approvals_reviewer, policy: settings.approval_policy };
58368
+ } catch {
58369
+ return void 0;
57759
58370
  }
57760
- if (request9.method === "item/fileChange/requestApproval") {
57761
- const changes = objects(params.changes);
57762
- const verb = (change) => object2(change.kind).type === "add" ? "Add" : object2(change.kind).type === "delete" ? "Delete" : "Update";
57763
- const patch = changes.filter((change) => typeof change.path === "string").map((change) => `*** ${verb(change)} File: ${change.path}`).join("\n");
57764
- return { tool: "apply_patch", input: { ...patch ? { patch } : {}, ...typeof params.grantRoot === "string" ? { grantRoot: params.grantRoot } : {}, ...reason2 } };
58371
+ }
58372
+ function autoReviewed({ reviewer, policy }) {
58373
+ return reviewer === "auto_review" && (policy === "on-request" || !!policy && typeof policy === "object" && "granular" in policy);
58374
+ }
58375
+ var SCAN_LIMIT, CHUNK;
58376
+ var init_codex_review_mode = __esm({
58377
+ "src/bridge/codex-review-mode.ts"() {
58378
+ "use strict";
58379
+ SCAN_LIMIT = 64 * 1048576;
58380
+ CHUNK = 1048576;
57765
58381
  }
57766
- if (request9.method === "item/permissions/requestApproval") return { tool: "Permissions", input: { permissions: params.permissions ?? {}, ...reason2 } };
57767
- return void 0;
58382
+ });
58383
+
58384
+ // src/bridge/thread-origin.ts
58385
+ import { open as open20 } from "node:fs/promises";
58386
+ import path105 from "node:path";
58387
+ async function codexForeignThread(transcriptPath2) {
58388
+ if (typeof transcriptPath2 !== "string" || !path105.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path105.basename(transcriptPath2))) return false;
58389
+ return foreignMeta(await readHead(transcriptPath2, 4096));
57768
58390
  }
57769
- function appServerDecision(request9, allow) {
57770
- if (request9.method === "item/permissions/requestApproval") return { permissions: allow ? object2(request9.params.permissions) : {}, scope: "turn" };
57771
- return { decision: allow ? "accept" : "decline" };
58391
+ async function readHead(file4, bytes) {
58392
+ const handle = await open20(file4, "r").catch(() => void 0);
58393
+ if (!handle) return "";
58394
+ try {
58395
+ const buffer = Buffer.alloc(bytes), { bytesRead } = await handle.read(buffer, 0, bytes, 0);
58396
+ return buffer.subarray(0, bytesRead).toString("utf8");
58397
+ } finally {
58398
+ await handle.close();
58399
+ }
57772
58400
  }
57773
- function conductorCall(tool, input2) {
57774
- const tail2 = /(?:^|[.:/]|__)(dispatch|hand_off|phren_admin)$/.exec(tool.replace(/^mcp_phren_/, ""))?.[1];
57775
- const fields2 = object2(input2);
57776
- let action;
57777
- if (tail2 === "dispatch") action = "dispatch";
57778
- else if (tail2 === "hand_off") action = "hand_off";
57779
- else if (tail2 === "phren_admin" && (fields2.action === "dispatch" || fields2.action === "hand_off")) action = fields2.action;
57780
- if (!action) return void 0;
57781
- const project = typeof fields2.project === "string" ? fields2.project : void 0;
57782
- const computer = typeof fields2.computer === "string" ? fields2.computer : void 0;
57783
- return { action, ...project ? { project } : {}, ...computer ? { computer } : {} };
58401
+ function foreignMeta(head) {
58402
+ if (!head.includes('"session_meta"')) return false;
58403
+ return /"originator"\s*:\s*"codex_exec"/.test(head) || /"source"\s*:\s*"exec"/.test(head) || /"source"\s*:\s*\{\s*"subagent"/.test(head);
57784
58404
  }
57785
- function opencodePermissionReply(decision) {
57786
- if (decision === "approve") return "once";
57787
- if (decision === "deny") return "reject";
57788
- if (decision === "allow-project" || decision === "allow-everywhere") return "always";
57789
- return void 0;
58405
+ async function claudeHeadlessThread(transcriptPath2) {
58406
+ if (typeof transcriptPath2 !== "string" || !path105.isAbsolute(transcriptPath2) || !transcriptPath2.endsWith(".jsonl")) return false;
58407
+ return headlessEntrypoint(await readHead(transcriptPath2, 32768));
57790
58408
  }
57791
- function projectField(cwd) {
57792
- const project = paneProject(cwd, phrenStoreRoot());
57793
- return project ? { project } : {};
58409
+ function headlessEntrypoint(head) {
58410
+ return /"entrypoint"\s*:\s*"sdk-[a-z]+"/.test(head);
57794
58411
  }
58412
+ var init_thread_origin = __esm({
58413
+ "src/bridge/thread-origin.ts"() {
58414
+ "use strict";
58415
+ }
58416
+ });
58417
+
58418
+ // src/bridge/agent-hook-callback.ts
58419
+ import { request as request6 } from "node:http";
57795
58420
  function stopFacts(value2) {
57796
58421
  const tasks = Array.isArray(value2.background_tasks) ? value2.background_tasks.filter((task2) => !["completed", "failed", "killed", "stopped"].includes(String(object2(task2).status))) : void 0;
57797
58422
  return {
@@ -57811,6 +58436,7 @@ async function agentHook(source, elapsed = () => performance.now()) {
57811
58436
  const value2 = object2(JSON.parse(input2));
57812
58437
  if (value2.agent_id || value2.agentId || value2.isSidechain || value2.is_sidechain) return;
57813
58438
  if (source === "codex" && await codexForeignThread(value2.transcript_path).catch(() => false)) return;
58439
+ if (source === "claude" && await claudeHeadlessThread(value2.transcript_path).catch(() => false)) return;
57814
58440
  const target = targetSchema.parse({
57815
58441
  server: place.server,
57816
58442
  workspace: place.workspace,
@@ -57884,23 +58510,56 @@ async function forwardHook(source, target, event, value2, left3) {
57884
58510
  req.end(data);
57885
58511
  });
57886
58512
  }
57887
- var APPROVAL_SWEEP_MS, OPENCODE_PANES_FRESH_MS, APPROVAL_DEBOUNCE_MS, APPROVAL_HOLD_MS, DIALOG_READ_MS2, DIALOG_PUSH_MS, FANOUT_SWEEP_MS, SERVED_ASK_MS, FANOUT_ARCHIVE_MS, DISPATCH_LEASE_MS, OPENCODE_APPROVAL_OPTIONS, AgentHooks;
58513
+ var init_agent_hook_callback = __esm({
58514
+ "src/bridge/agent-hook-callback.ts"() {
58515
+ "use strict";
58516
+ init_shared();
58517
+ init_runtime();
58518
+ init_protocol();
58519
+ init_hook_fast();
58520
+ init_codex_daemon();
58521
+ init_codex_review_mode();
58522
+ init_thread_origin();
58523
+ init_terminal();
58524
+ init_launch_brief();
58525
+ init_codex_servers();
58526
+ init_agent_hook_stores();
58527
+ }
58528
+ });
58529
+
58530
+ // src/bridge/agent-hooks.ts
58531
+ import { createServer as createServer3 } from "node:http";
58532
+ import { mkdir as mkdir26, readFile as readFile44, chmod as chmod4, unlink as unlink7, lstat as lstat28 } from "node:fs/promises";
58533
+ import { watch } from "node:fs";
58534
+ import path106 from "node:path";
58535
+ import { randomUUID as randomUUID24 } from "node:crypto";
58536
+ import { hostname as hostname10 } from "node:os";
58537
+ function watchHangUp(res) {
58538
+ let closed = res.destroyed || res.socket?.destroyed === true;
58539
+ const onClose = () => {
58540
+ if (!res.writableEnded) closed = true;
58541
+ };
58542
+ res.once("close", onClose);
58543
+ return () => {
58544
+ res.off("close", onClose);
58545
+ return closed || res.destroyed;
58546
+ };
58547
+ }
58548
+ function projectField(cwd) {
58549
+ const project = paneProject(cwd, phrenStoreRoot());
58550
+ return project ? { project } : {};
58551
+ }
58552
+ var APPROVAL_SWEEP_MS, OPENCODE_PANES_FRESH_MS, APPROVAL_DEBOUNCE_MS, APPROVAL_HOLD_MS, QUESTION_READ_LINES, DIALOG_READ_MS2, DIALOG_PUSH_MS, FANOUT_SWEEP_MS, SERVED_ASK_MS, FANOUT_ARCHIVE_MS, DISPATCH_LEASE_MS, AgentHooks;
57888
58553
  var init_agent_hooks = __esm({
57889
58554
  "src/bridge/agent-hooks.ts"() {
57890
58555
  "use strict";
57891
58556
  init_approval_rules();
57892
58557
  init_conductor_role();
57893
58558
  init_conductor_context();
57894
- init_shared();
57895
58559
  init_registry();
57896
- init_runtime();
57897
58560
  init_logger();
57898
58561
  init_protocol();
57899
58562
  init_herdr();
57900
- init_hook_fast();
57901
- init_codex_daemon();
57902
- init_codex_review_mode();
57903
- init_codex_thread_origin();
57904
58563
  init_terminal();
57905
58564
  init_pane_text();
57906
58565
  init_changes();
@@ -57922,10 +58581,13 @@ var init_agent_hooks = __esm({
57922
58581
  init_prompt_deliveries();
57923
58582
  init_metrics();
57924
58583
  init_launch_brief();
58584
+ init_agent_hook_asks();
57925
58585
  init_sudo();
57926
58586
  init_codex_servers();
57927
58587
  init_opencode_panes();
57928
58588
  init_terminal_choice();
58589
+ init_agent_hook_asks();
58590
+ init_agent_hook_callback();
57929
58591
  init_agent_hook_stores();
57930
58592
  APPROVAL_SWEEP_MS = 2e3;
57931
58593
  OPENCODE_PANES_FRESH_MS = 15e3;
@@ -57934,18 +58596,13 @@ var init_agent_hooks = __esm({
57934
58596
  const value2 = Number(process.env.PHREN_APPROVAL_HOLD_MS);
57935
58597
  return Number.isFinite(value2) && value2 >= 50 && value2 <= 6e4 ? Math.floor(value2) : 55e3;
57936
58598
  })();
58599
+ QUESTION_READ_LINES = 120;
57937
58600
  DIALOG_READ_MS2 = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3e3);
57938
58601
  DIALOG_PUSH_MS = 10 * 6e4;
57939
58602
  FANOUT_SWEEP_MS = 5e3;
57940
58603
  SERVED_ASK_MS = 60 * 6e4;
57941
58604
  FANOUT_ARCHIVE_MS = 60 * 60 * 1e3;
57942
58605
  DISPATCH_LEASE_MS = 45e3;
57943
- OPENCODE_APPROVAL_OPTIONS = [
57944
- { label: "Allow once", decision: "approve" },
57945
- { label: "Allow for this project", decision: "allow-project" },
57946
- { label: "Allow everywhere", decision: "allow-everywhere" },
57947
- { label: "Deny", decision: "deny" }
57948
- ];
57949
58606
  AgentHooks = class {
57950
58607
  constructor(push = new ApprovalPushService(), modules, deliveriesFile) {
57951
58608
  this.push = push;
@@ -58318,7 +58975,7 @@ var init_agent_hooks = __esm({
58318
58975
  try {
58319
58976
  const file4 = path106.join(root, folder, name), info = await lstat28(file4);
58320
58977
  if (!info.isFile() || info.size > 65536) continue;
58321
- value2 = object2(JSON.parse(await readFile45(file4, "utf8")));
58978
+ value2 = object2(JSON.parse(await readFile44(file4, "utf8")));
58322
58979
  } catch {
58323
58980
  continue;
58324
58981
  }
@@ -58508,9 +59165,11 @@ var init_agent_hooks = __esm({
58508
59165
  this.dialogReads.set(key4, now);
58509
59166
  while (this.dialogReads.size > 128) this.dialogReads.delete(this.dialogReads.keys().next().value);
58510
59167
  const text5 = await this.paneLines(target);
59168
+ const tall = target.source === "claude" && /Chat about this/.test(text5) && !claudeQuestionDialog(text5) ? await this.paneLines(target, true, QUESTION_READ_LINES).catch(() => "") : "";
59169
+ const asking = target.source === "claude" && !!(claudeQuestionDialog(text5) || tall && claudeQuestionDialog(tall));
58511
59170
  this.passwords.set(key4, passwordLine(text5));
58512
59171
  while (this.passwords.size > 128) this.passwords.delete(this.passwords.keys().next().value);
58513
- if (target.source === "claude" && claudeQuestionDialog(text5)) {
59172
+ if (asking) {
58514
59173
  if (entry2 && !question2) this.terminalPrompts.delete(key4);
58515
59174
  return;
58516
59175
  }
@@ -58618,7 +59277,8 @@ var init_agent_hooks = __esm({
58618
59277
  async answerClaudeQuestions(target, questions, answers, options = {}) {
58619
59278
  const key4 = JSON.stringify(target);
58620
59279
  await answerClaudeQuestionDialog({
58621
- read: () => this.paneLines(target),
59280
+ // A tall question (long text, many options) pushes its tab bar out of 40 lines.
59281
+ read: () => this.paneLines(target, true, QUESTION_READ_LINES),
58622
59282
  keys: async (keys2) => {
58623
59283
  if (!keys2.length) return;
58624
59284
  await validateTarget(target, false, true);
@@ -58684,8 +59344,8 @@ var init_agent_hooks = __esm({
58684
59344
  return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines: 40, stripAnsi: false, format: "ansi", timeoutMs: 2e3 });
58685
59345
  }
58686
59346
  /** Read what the pane draws, stripping ANSI unless placeholder styling is needed. */
58687
- paneLines(target, stripAnsi = true) {
58688
- return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines: 40, stripAnsi, timeoutMs: 2e3 });
59347
+ paneLines(target, stripAnsi = true, lines = 40) {
59348
+ return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines, stripAnsi, timeoutMs: 2e3 });
58689
59349
  }
58690
59350
  /** After the phone walks Codex's /permissions menu onto Full Access, the
58691
59351
  * agent draws a second "Enable full access?" confirmation. Watch the pane's
@@ -59384,7 +60044,7 @@ ${await conductorBrief()}` : context3 } : {}));
59384
60044
  }
59385
60045
  if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body2.event))) this.stopCompacting(target);
59386
60046
  if (body2.event === "UserPromptSubmit") {
59387
- if (typeof body2.prompt === "string") this.deliveries.submitted(target, body2.prompt.slice(0, 65536));
60047
+ if (typeof body2.prompt === "string") await this.deliveries.submitted(target, body2.prompt.slice(0, 65536));
59388
60048
  await this.recordTurn(target, pane, body2, dispatch2);
59389
60049
  const context3 = this.modules?.has("conductor") === false ? void 0 : await conductorContext(target, s).catch(() => void 0);
59390
60050
  res.end(JSON.stringify(context3 ? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context3 } } : {}));
@@ -59588,7 +60248,7 @@ ${await conductorBrief()}` : context3 } : {}));
59588
60248
 
59589
60249
  // src/bridge/models.ts
59590
60250
  import { spawn as spawn11 } from "node:child_process";
59591
- import { readdir as readdir16, readFile as readFile46, stat as stat22 } from "node:fs/promises";
60251
+ import { readdir as readdir16, readFile as readFile45, stat as stat22 } from "node:fs/promises";
59592
60252
  import { homedir as homedir17 } from "node:os";
59593
60253
  import path107 from "node:path";
59594
60254
  function readCodexModels(executable2 = codexExecutable()) {
@@ -59676,7 +60336,7 @@ async function readClaudeCatalog(configDir2 = claudeConfigDir(), installed) {
59676
60336
  if (!newest2) return [];
59677
60337
  let parsed;
59678
60338
  try {
59679
- parsed = JSON.parse(await readFile46(newest2.file, "utf8"));
60339
+ parsed = JSON.parse(await readFile45(newest2.file, "utf8"));
59680
60340
  } catch {
59681
60341
  return [];
59682
60342
  }
@@ -59775,7 +60435,7 @@ async function readOpenCodeModels(executable2 = "opencode", configDir2 = path107
59775
60435
  let configured;
59776
60436
  for (const file4 of ["opencode.json", "opencode.jsonc"]) {
59777
60437
  try {
59778
- const text5 = await readFile46(path107.join(configDir2, file4), "utf8");
60438
+ const text5 = await readFile45(path107.join(configDir2, file4), "utf8");
59779
60439
  const model = /"model"\s*:\s*"([^"]+)"/.exec(text5)?.[1];
59780
60440
  if (model) {
59781
60441
  configured = model.slice(0, 200);
@@ -60479,6 +61139,7 @@ function descendsFrom(pid, roots, parents) {
60479
61139
  function attributeServers(input2) {
60480
61140
  const result = [];
60481
61141
  for (const server of input2.servers) {
61142
+ if (server.unverified) continue;
60482
61143
  if (descendsFrom(server.pid, input2.ownRoots, input2.parents)) result.push({ ...server, source: "started" });
60483
61144
  else if (input2.mentioned.has(server.port) && !descendsFrom(server.pid, input2.otherRoots, input2.parents)) {
60484
61145
  result.push({ ...server, source: "mentioned" });
@@ -60565,7 +61226,7 @@ var init_session_servers = __esm({
60565
61226
  });
60566
61227
 
60567
61228
  // src/bridge/uploads.ts
60568
- import { mkdir as mkdir27, readdir as readdir17, lstat as lstat29, realpath as realpath15, readFile as readFile47, stat as stat24, unlink as unlink8, writeFile as writeFile9 } from "node:fs/promises";
61229
+ import { mkdir as mkdir27, readdir as readdir17, lstat as lstat29, realpath as realpath15, readFile as readFile46, stat as stat24, unlink as unlink8, writeFile as writeFile8 } from "node:fs/promises";
60569
61230
  import path108 from "node:path";
60570
61231
  import { randomUUID as randomUUID26 } from "node:crypto";
60571
61232
  function imageBytes(bytes) {
@@ -60595,7 +61256,7 @@ async function saveUpload(session, name, bytes) {
60595
61256
  const folder = path108.join(root, session);
60596
61257
  await mkdir27(folder, { recursive: true, mode: 448 });
60597
61258
  saved = path108.join(folder, `${randomUUID26()}-${name}`);
60598
- await writeFile9(saved, bytes, { flag: "wx", mode: 384 });
61259
+ await writeFile8(saved, bytes, { flag: "wx", mode: 384 });
60599
61260
  });
60600
61261
  uploadQueue = task2;
60601
61262
  await task2;
@@ -60630,7 +61291,7 @@ async function uploadImage(requested) {
60630
61291
  const metadata = await stat24(file4);
60631
61292
  if (!metadata.isFile()) throw missing;
60632
61293
  if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
60633
- const bytes = await readFile47(file4);
61294
+ const bytes = await readFile46(file4);
60634
61295
  if (bytes.length > 8388608) throw new BridgeError(413, "This image is too large.");
60635
61296
  if (!imageBytes(bytes)) throw missing;
60636
61297
  return bytes;
@@ -60769,7 +61430,7 @@ var init_file_range = __esm({
60769
61430
  // src/bridge/file-write.ts
60770
61431
  import { randomBytes as randomBytes8 } from "node:crypto";
60771
61432
  import { constants as constants4 } from "node:fs";
60772
- import { lstat as lstat31, open as open23, realpath as realpath17, rename as rename8, rm as rm13 } from "node:fs/promises";
61433
+ import { lstat as lstat31, open as open23, realpath as realpath17, rename as rename7, rm as rm12 } from "node:fs/promises";
60773
61434
  import path110 from "node:path";
60774
61435
  async function serialized3(key4, work) {
60775
61436
  const previous = fileLocks.get(key4) ?? Promise.resolve();
@@ -60782,7 +61443,8 @@ async function serialized3(key4, work) {
60782
61443
  }
60783
61444
  }
60784
61445
  async function writeRepoFile(root, requested, content, expectedVersion) {
60785
- const key4 = `${await realpath17(root).catch(() => root)}\0${requested}`;
61446
+ const name = typeof requested === "string" ? path110.posix.normalize(requested) : requested;
61447
+ const key4 = `${await realpath17(root).catch(() => root)}\0${name}`;
60786
61448
  return serialized3(key4, () => writeRepoFileNow(root, requested, content, expectedVersion));
60787
61449
  }
60788
61450
  async function writeRepoFileNow(root, requested, content, expectedVersion) {
@@ -60842,9 +61504,9 @@ async function writeRepoFileNow(root, requested, content, expectedVersion) {
60842
61504
  if (!current2 || current2.isSymbolicLink() || fileVersion(current2) !== expectedVersion) {
60843
61505
  throw new BridgeError(409, "The file changed since you opened it.", { code: "file-changed" });
60844
61506
  }
60845
- await rename8(temporary, file4);
61507
+ await rename7(temporary, file4);
60846
61508
  } finally {
60847
- await rm13(temporary, { force: true });
61509
+ await rm12(temporary, { force: true });
60848
61510
  }
60849
61511
  const saved = await lstat31(file4);
60850
61512
  return { path: requested, version: fileVersion(saved), size: saved.size, created: false };
@@ -62006,8 +62668,8 @@ async function launch(options, reservation = createJob(options)) {
62006
62668
  for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.off(signal, cancel);
62007
62669
  fs44.closeSync(out);
62008
62670
  fs44.closeSync(err);
62009
- const blockedFile = path114.join(job, "blocked.json"), refusal = refused2 ?? stderrRefusal(stderr);
62010
- if (refusal && !fs44.existsSync(blockedFile)) atomicWriteText(blockedFile, JSON.stringify({ ...refusal, at: (/* @__PURE__ */ new Date()).toISOString() }));
62671
+ const blockedFile = path114.join(job, "blocked.json"), refusal2 = refused2 ?? stderrRefusal(stderr);
62672
+ if (refusal2 && !fs44.existsSync(blockedFile)) atomicWriteText(blockedFile, JSON.stringify({ ...refusal2, at: (/* @__PURE__ */ new Date()).toISOString() }));
62011
62673
  const blocked = fs44.existsSync(blockedFile);
62012
62674
  if (blocked) console.error(`blocked: ${fs44.readFileSync(blockedFile, "utf8").slice(0, 4e3)}`);
62013
62675
  fs44.writeFileSync(path114.join(job, "exit.txt"), `${exitCode}
@@ -62038,7 +62700,7 @@ var init_launcher = __esm({
62038
62700
 
62039
62701
  // src/bridge/fanout-messages.ts
62040
62702
  import { randomUUID as randomUUID27 } from "node:crypto";
62041
- import { appendFile as appendFile2, lstat as lstat32, mkdir as mkdir28, readdir as readdir18, readFile as readFile48, realpath as realpath18, rename as rename9, rm as rm14, writeFile as writeFile10 } from "node:fs/promises";
62703
+ import { appendFile as appendFile2, lstat as lstat32, mkdir as mkdir28, readdir as readdir18, readFile as readFile47, realpath as realpath18, rename as rename8, rm as rm13, writeFile as writeFile9 } from "node:fs/promises";
62042
62704
  import path115 from "node:path";
62043
62705
  var fanoutMessageSchema, receiptSchema2, FanoutMessages;
62044
62706
  var init_fanout_messages = __esm({
@@ -62092,7 +62754,7 @@ var init_fanout_messages = __esm({
62092
62754
  if (!(await lstat32(directory)).isDirectory() || await realpath18(directory) !== directory) continue;
62093
62755
  const file4 = path115.join(directory, "manifest.json"), info = await lstat32(file4);
62094
62756
  if (!info.isFile() || info.isSymbolicLink() || info.size > 65536) continue;
62095
- const manifest = manifestSchema.parse(JSON.parse(await readFile48(file4, "utf8")));
62757
+ const manifest = manifestSchema.parse(JSON.parse(await readFile47(file4, "utf8")));
62096
62758
  if (manifest.id === name) jobs.push({ directory, manifest });
62097
62759
  } catch {
62098
62760
  }
@@ -62156,7 +62818,7 @@ var init_fanout_messages = __esm({
62156
62818
  const file4 = path115.join(directory, name), info2 = await lstat32(file4);
62157
62819
  if (!info2.isFile() || info2.isSymbolicLink() || info2.size > 262144) continue;
62158
62820
  try {
62159
- rows2.push({ file: file4, message: receiptSchema2.parse(JSON.parse(await readFile48(file4, "utf8"))) });
62821
+ rows2.push({ file: file4, message: receiptSchema2.parse(JSON.parse(await readFile47(file4, "utf8"))) });
62160
62822
  } catch {
62161
62823
  }
62162
62824
  }
@@ -62202,17 +62864,17 @@ var init_fanout_messages = __esm({
62202
62864
  if (await realpath18(round) !== round) throw new BridgeError(400, "Invalid worker round directory.");
62203
62865
  const roundDir = path115.join(round, next.message.id);
62204
62866
  await mkdir28(roundDir, { mode: 448 });
62205
- await writeFile10(path115.join(roundDir, "prompt.txt"), next.message.text, { mode: 384 });
62867
+ await writeFile9(path115.join(roundDir, "prompt.txt"), next.message.text, { mode: 384 });
62206
62868
  for (const name of ["stderr.log", "final.txt", "exit.txt", "blocked.json", "prompt.txt"]) {
62207
- await rename9(path115.join(fresh.directory, name), path115.join(roundDir, `previous-${name}`)).catch((error62) => {
62869
+ await rename8(path115.join(fresh.directory, name), path115.join(roundDir, `previous-${name}`)).catch((error62) => {
62208
62870
  if (error62.code !== "ENOENT") throw error62;
62209
62871
  });
62210
62872
  }
62211
- await writeFile10(path115.join(fresh.directory, "prompt.txt"), next.message.text, { mode: 384 });
62873
+ await writeFile9(path115.join(fresh.directory, "prompt.txt"), next.message.text, { mode: 384 });
62212
62874
  const sentFile = next.file.replace(/\.queued\.json$/, ".sent.json");
62213
62875
  const message = { ...next.message, status: "running" };
62214
62876
  await atomic(next.file, JSON.stringify(message));
62215
- await rename9(next.file, sentFile);
62877
+ await rename8(next.file, sentFile);
62216
62878
  pending = { file: sentFile, message };
62217
62879
  const now = (/* @__PURE__ */ new Date()).toISOString();
62218
62880
  const manifest = {
@@ -62252,20 +62914,20 @@ var init_fanout_messages = __esm({
62252
62914
  await atomic(sentFile, JSON.stringify({ ...message, status: "failed" }));
62253
62915
  await atomic(path115.join(fresh.directory, "manifest.json"), JSON.stringify({ ...manifest, status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString() }));
62254
62916
  }).finally(async () => {
62255
- await rm14(lock, { recursive: true, force: true });
62917
+ await rm13(lock, { recursive: true, force: true });
62256
62918
  }).catch(() => {
62257
62919
  });
62258
62920
  } catch (error62) {
62259
62921
  if (!pending) throw error62;
62260
62922
  await atomic(pending.file, JSON.stringify({ ...pending.message, status: "failed" }));
62261
- if (pending.file.endsWith(".queued.json")) await rename9(pending.file, pending.file.replace(/\.queued\.json$/, ".sent.json"));
62923
+ if (pending.file.endsWith(".queued.json")) await rename8(pending.file, pending.file.replace(/\.queued\.json$/, ".sent.json"));
62262
62924
  if (started) await atomic(path115.join(job.directory, "manifest.json"), JSON.stringify({
62263
62925
  ...started,
62264
62926
  status: "failed",
62265
62927
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
62266
62928
  }));
62267
62929
  } finally {
62268
- if (!launched) await rm14(lock, { recursive: true, force: true });
62930
+ if (!launched) await rm13(lock, { recursive: true, force: true });
62269
62931
  }
62270
62932
  }
62271
62933
  };
@@ -63053,7 +63715,7 @@ var init_speech_transcribe = __esm({
63053
63715
  });
63054
63716
 
63055
63717
  // src/bridge/activity.ts
63056
- import { appendFile as appendFile3, mkdir as mkdir29, readFile as readFile49, rename as rename10, stat as stat25 } from "node:fs/promises";
63718
+ import { appendFile as appendFile3, mkdir as mkdir29, readFile as readFile48, rename as rename9, stat as stat25 } from "node:fs/promises";
63057
63719
  import path116 from "node:path";
63058
63720
  var ActivityJournal;
63059
63721
  var init_activity2 = __esm({
@@ -63088,14 +63750,14 @@ var init_activity2 = __esm({
63088
63750
  if (!changes.length) return;
63089
63751
  const root = bridgeRoot(), file4 = path116.join(root, "activity.jsonl");
63090
63752
  await mkdir29(root, { recursive: true, mode: 448 });
63091
- if ((await stat25(file4).catch(() => null))?.size && (await stat25(file4)).size > 2097152) await rename10(file4, file4 + ".previous");
63753
+ if ((await stat25(file4).catch(() => null))?.size && (await stat25(file4)).size > 2097152) await rename9(file4, file4 + ".previous");
63092
63754
  await appendFile3(file4, changes.map((row) => JSON.stringify(row)).join("\n") + "\n", { mode: 384 });
63093
63755
  if (this.previous.size > 4096) this.previous.clear();
63094
63756
  });
63095
63757
  return this.pending;
63096
63758
  }
63097
63759
  async recent() {
63098
- const text5 = await readFile49(path116.join(bridgeRoot(), "activity.jsonl"), "utf8").catch(() => "");
63760
+ const text5 = await readFile48(path116.join(bridgeRoot(), "activity.jsonl"), "utf8").catch(() => "");
63099
63761
  return text5.trim().split("\n").slice(-500).flatMap((line) => {
63100
63762
  try {
63101
63763
  return [JSON.parse(line)];
@@ -63229,7 +63891,7 @@ var init_code_package = __esm({
63229
63891
  });
63230
63892
 
63231
63893
  // src/bridge/code-routes.ts
63232
- import { rm as rm15 } from "node:fs/promises";
63894
+ import { rm as rm14 } from "node:fs/promises";
63233
63895
  import * as fs46 from "node:fs";
63234
63896
  import * as path118 from "node:path";
63235
63897
  async function requireCodePackage(store) {
@@ -63254,7 +63916,7 @@ async function resolveCodeStore(base, value2, write = false) {
63254
63916
  function noIndex(project) {
63255
63917
  return new BridgeError(404, `No code index for "${project}" on this computer. Build one with: phren code index ${project}`);
63256
63918
  }
63257
- function readHead(root) {
63919
+ function readHead2(root) {
63258
63920
  try {
63259
63921
  const dotGit = path118.join(root, ".git");
63260
63922
  const gitDirectory2 = fs46.statSync(dotGit).isDirectory() ? dotGit : (() => {
@@ -63492,7 +64154,7 @@ var init_code_routes = __esm({
63492
64154
  const project = projectSchema.parse(projectValue ?? "");
63493
64155
  const { codeDatabasePath } = await requireCodePackage(this.store);
63494
64156
  const file4 = codeDatabasePath(this.store, project);
63495
- await Promise.all([file4, `${file4}-journal`, `${file4}-wal`, `${file4}-shm`].map((path145) => rm15(path145, { force: true })));
64157
+ await Promise.all([file4, `${file4}-journal`, `${file4}-wal`, `${file4}-shm`].map((path145) => rm14(path145, { force: true })));
63496
64158
  return { project, disabled: true };
63497
64159
  }
63498
64160
  async reindex(projectValue) {
@@ -63584,7 +64246,7 @@ var init_code_routes = __esm({
63584
64246
  for (const root of new Set(files.map((file4) => file4.root))) {
63585
64247
  const project = projects.find((entry2) => entry2.root === root);
63586
64248
  if (!project) continue;
63587
- const head = readHead(root);
64249
+ const head = readHead2(root);
63588
64250
  const previous = this.heads.get(root);
63589
64251
  if (head !== void 0) this.heads.set(root, head);
63590
64252
  this.schedule(project.project, previous !== void 0 && head !== void 0 && previous !== head);
@@ -63780,8 +64442,8 @@ var init_context2 = __esm({
63780
64442
 
63781
64443
  // src/bridge/questions.ts
63782
64444
  import { execFile as execFile26 } from "node:child_process";
63783
- import { createHash as createHash29 } from "node:crypto";
63784
- import { mkdir as mkdir30, open as open25, stat as stat26, readFile as readFile50, writeFile as writeFile11 } from "node:fs/promises";
64445
+ import { createHash as createHash30 } from "node:crypto";
64446
+ import { mkdir as mkdir30, open as open25, stat as stat26, readFile as readFile49, writeFile as writeFile10 } from "node:fs/promises";
63785
64447
  import path119 from "node:path";
63786
64448
  import { promisify as promisify24 } from "node:util";
63787
64449
  function asyncQuestion(raw, id2) {
@@ -64023,8 +64685,8 @@ ${attachedFiles(paths)}` : answer;
64023
64685
  this.snapshots.set(target.session, { at: Date.now(), stamp: stamp2, pending });
64024
64686
  }
64025
64687
  return Promise.all((pending ?? []).map(async (p) => {
64026
- const key4 = createHash29("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
64027
- const submitted = await readFile50(path119.join(bridgeRoot(), "question-replies", key4), "utf8").then((value2) => value2 === "submitted").catch(() => false);
64688
+ const key4 = createHash30("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
64689
+ const submitted = await readFile49(path119.join(bridgeRoot(), "question-replies", key4), "utf8").then((value2) => value2 === "submitted").catch(() => false);
64028
64690
  return { toolUseId: p.id, isAsync: true, submitted, questions: asPrompt(p.questions) };
64029
64691
  })).then((prompts) => prompts.filter((p) => !p.submitted));
64030
64692
  }
@@ -64059,7 +64721,7 @@ ${attachedFiles(paths)}` : answer;
64059
64721
  if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
64060
64722
  const directory = path119.join(bridgeRoot(), "question-replies");
64061
64723
  await mkdir30(directory, { recursive: true, mode: 448 });
64062
- const key4 = createHash29("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
64724
+ const key4 = createHash30("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
64063
64725
  const receiptPath = path119.join(directory, key4);
64064
64726
  const receipt = await open25(receiptPath, "wx", 384).catch((error62) => {
64065
64727
  if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
@@ -64069,7 +64731,7 @@ ${attachedFiles(paths)}` : answer;
64069
64731
  try {
64070
64732
  if (entry2) await this.served.steer(entry2, reply, extra);
64071
64733
  else await exec21(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8e3, maxBuffer: 65536 });
64072
- await writeFile11(receiptPath, "submitted", { mode: 384 });
64734
+ await writeFile10(receiptPath, "submitted", { mode: 384 });
64073
64735
  } catch {
64074
64736
  throw new BridgeError(409, "Codex did not confirm the answer. Check the conversation; Phren has not retried it.");
64075
64737
  }
@@ -64296,7 +64958,7 @@ var init_settings_switch = __esm({
64296
64958
  if (pane.agent_status === "working") throw new BridgeError(409, "The agent started working during the settings change. The result is unconfirmed; check the terminal.");
64297
64959
  };
64298
64960
  const screenMode = async () => claudeFooterMode(await this.hooks.paneLines(target));
64299
- const changed2 = async (from, wait) => {
64961
+ const changed = async (from, wait) => {
64300
64962
  const deadline = Date.now() + wait;
64301
64963
  do {
64302
64964
  await new Promise((resolve17) => setTimeout(resolve17, 150));
@@ -64348,7 +65010,7 @@ var init_settings_switch = __esm({
64348
65010
  if (change.plan === true) {
64349
65011
  if (started !== "plan") {
64350
65012
  await slash("/plan");
64351
- mode = await changed2(started, this.wait);
65013
+ mode = await changed(started, this.wait);
64352
65014
  if (mode !== "plan") throw new BridgeError(409, "Claude did not enter plan mode. Open terminal to check.");
64353
65015
  }
64354
65016
  } else if (change.permissionMode || change.plan === false) {
@@ -64358,7 +65020,7 @@ var init_settings_switch = __esm({
64358
65020
  if (presses >= MAX_PRESSES || presses > 0 && mode === started) throw new BridgeError(422, "Claude doesn't offer that mode in this session.");
64359
65021
  await validate2();
64360
65022
  await terminalProvider().sendKeys(target.server, target.pane, ["shift+tab"]);
64361
- mode = await changed2(mode, this.wait);
65023
+ mode = await changed(mode, this.wait);
64362
65024
  }
64363
65025
  }
64364
65026
  const phone = mode ? CLAUDE_MODES[mode] : void 0;
@@ -64374,7 +65036,7 @@ var init_settings_switch = __esm({
64374
65036
  });
64375
65037
 
64376
65038
  // src/bridge/job-registry.ts
64377
- import { readFileSync as readFileSync47 } from "node:fs";
65039
+ import { readFileSync as readFileSync49 } from "node:fs";
64378
65040
  import path120 from "node:path";
64379
65041
  function jobKey(job) {
64380
65042
  if (job.pane) return `pane:${paneKey3(job.pane)}`;
@@ -64515,7 +65177,7 @@ var init_job_registry = __esm({
64515
65177
  now;
64516
65178
  async list() {
64517
65179
  try {
64518
- const parsed = stateSchema2.safeParse(JSON.parse(readFileSync47(this.file, "utf8")));
65180
+ const parsed = stateSchema2.safeParse(JSON.parse(readFileSync49(this.file, "utf8")));
64519
65181
  return parsed.success ? parsed.data.jobs : [];
64520
65182
  } catch {
64521
65183
  return [];
@@ -64574,7 +65236,7 @@ var init_job_registry = __esm({
64574
65236
 
64575
65237
  // src/bridge/resources.ts
64576
65238
  import { execFile as execFile27 } from "node:child_process";
64577
- import { readdir as readdir19, readFile as readFile51, statfs } from "node:fs/promises";
65239
+ import { readdir as readdir19, readFile as readFile50, statfs } from "node:fs/promises";
64578
65240
  import { cpus, loadavg, totalmem, uptime } from "node:os";
64579
65241
  import path121 from "node:path";
64580
65242
  import { promisify as promisify25 } from "node:util";
@@ -64609,12 +65271,12 @@ function computerHardware(platform = process.platform) {
64609
65271
  return { ...found, ...base };
64610
65272
  }
64611
65273
  if (platform === "linux") {
64612
- const dmi = (name) => readFile51(`/sys/devices/virtual/dmi/id/${name}`, "utf8").catch(() => void 0);
65274
+ const dmi = (name) => readFile50(`/sys/devices/virtual/dmi/id/${name}`, "utf8").catch(() => void 0);
64613
65275
  const [vendor, product, version2, cpuinfo] = await Promise.all([
64614
65276
  dmi("sys_vendor"),
64615
65277
  dmi("product_name"),
64616
65278
  dmi("product_version"),
64617
- readFile51("/proc/cpuinfo", "utf8").catch(() => "")
65279
+ readFile50("/proc/cpuinfo", "utf8").catch(() => "")
64618
65280
  ]);
64619
65281
  const model = linuxModel(vendor, product, version2), chip = linuxChip(cpuinfo);
64620
65282
  return { ...model ? { model } : {}, ...chip ? { chip } : {}, ...base };
@@ -64833,7 +65495,7 @@ async function linuxBattery() {
64833
65495
  const names = await readdir19(root).catch(() => []);
64834
65496
  const battery = names.find((name) => /^BAT/.test(name));
64835
65497
  if (!battery) return void 0;
64836
- const read = (name, field) => readFile51(path121.join(root, name, field), "utf8").then((text5) => text5.trim()).catch(() => "");
65498
+ const read = (name, field) => readFile50(path121.join(root, name, field), "utf8").then((text5) => text5.trim()).catch(() => "");
64837
65499
  const [capacity2, status] = await Promise.all([read(battery, "capacity"), read(battery, "status")]);
64838
65500
  const online = await Promise.all(names.filter((name) => !/^BAT/.test(name)).map((name) => read(name, "online")));
64839
65501
  const percent = Number(capacity2);
@@ -64903,7 +65565,7 @@ async function collectResources(deps2) {
64903
65565
  const platform = deps2.platform;
64904
65566
  const registry2 = deps2.jobs ?? new JobRegistry();
64905
65567
  const [memory, disk, battery, rows2, registered, hardware] = await Promise.all([
64906
- platform === "darwin" ? darwinMemory() : platform === "linux" ? readFile51("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() })) : Promise.resolve({ totalBytes: totalmem() }),
65568
+ platform === "darwin" ? darwinMemory() : platform === "linux" ? readFile50("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() })) : Promise.resolve({ totalBytes: totalmem() }),
64907
65569
  statfs(deps2.home()).then((info) => ({ path: "~", totalBytes: info.blocks * info.bsize, freeBytes: info.bavail * info.bsize })).catch(() => void 0),
64908
65570
  platform === "darwin" ? run3("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => void 0) : platform === "linux" ? linuxBattery() : Promise.resolve(void 0),
64909
65571
  deps2.processes().catch(() => []),
@@ -64984,7 +65646,7 @@ var init_resources = __esm({
64984
65646
  });
64985
65647
 
64986
65648
  // src/bridge/canary.ts
64987
- import { lstat as lstat33, mkdtemp as mkdtemp6, realpath as realpath19, rm as rm16 } from "node:fs/promises";
65649
+ import { lstat as lstat33, mkdtemp as mkdtemp6, realpath as realpath19, rm as rm15 } from "node:fs/promises";
64988
65650
  import { hostname as hostname11, tmpdir as tmpdir5 } from "node:os";
64989
65651
  import path122 from "node:path";
64990
65652
  function reason(error62) {
@@ -65031,7 +65693,7 @@ async function conductorStep(options, server) {
65031
65693
  failure2 = reason(error62);
65032
65694
  } finally {
65033
65695
  const cleanup = await closeCanaryWorkspaces(server, before, created);
65034
- await rm16(folder, { recursive: true, force: true }).catch(() => {
65696
+ await rm15(folder, { recursive: true, force: true }).catch(() => {
65035
65697
  });
65036
65698
  if (cleanup) failure2 = failure2 ? `${failure2}; ${cleanup}` : cleanup;
65037
65699
  }
@@ -65143,7 +65805,7 @@ var init_canary = __esm({
65143
65805
 
65144
65806
  // src/bridge/launch-worktree.ts
65145
65807
  import { execFile as execFile28 } from "node:child_process";
65146
- import { mkdir as mkdir31, realpath as realpath20, rm as rm17, stat as stat28 } from "node:fs/promises";
65808
+ import { mkdir as mkdir31, realpath as realpath20, rm as rm16, stat as stat28 } from "node:fs/promises";
65147
65809
  import path123 from "node:path";
65148
65810
  import { promisify as promisify26 } from "node:util";
65149
65811
  async function git7(cwd, ...args) {
@@ -65189,7 +65851,7 @@ async function createLaunchWorktree(cwd, request9) {
65189
65851
  path: abs,
65190
65852
  branch,
65191
65853
  async discard() {
65192
- await git7(root, "worktree", "remove", "--force", abs).catch(() => rm17(abs, { recursive: true, force: true }));
65854
+ await git7(root, "worktree", "remove", "--force", abs).catch(() => rm16(abs, { recursive: true, force: true }));
65193
65855
  await git7(root, "worktree", "prune").catch(() => void 0);
65194
65856
  await git7(root, "branch", "-D", branch).catch(() => void 0);
65195
65857
  }
@@ -65211,7 +65873,7 @@ var init_launch_worktree = __esm({
65211
65873
  });
65212
65874
 
65213
65875
  // src/bridge/server-launch.ts
65214
- import { mkdir as mkdir32, mkdtemp as mkdtemp7, readFile as readFile52, realpath as realpath21, rmdir as rmdir2 } from "node:fs/promises";
65876
+ import { mkdir as mkdir32, mkdtemp as mkdtemp7, readFile as readFile51, realpath as realpath21, rmdir as rmdir2 } from "node:fs/promises";
65215
65877
  import path124 from "node:path";
65216
65878
  function effortArgs(kind, effort) {
65217
65879
  if (kind === "claude") return ["--effort", effort];
@@ -65231,7 +65893,7 @@ async function phrenLaunchArgs(kind, data, store = phrenStoreRoot()) {
65231
65893
  return [...mode === "chat" ? ["--mode", "chat"] : [], ...resume ? ["--session", resume] : []];
65232
65894
  }
65233
65895
  async function sessionUsedTools(session, store = phrenStoreRoot()) {
65234
- const raw = await readFile52(path124.join(store, ".sessions", `session-${session}.events.jsonl`), "utf8").catch(() => "");
65896
+ const raw = await readFile51(path124.join(store, ".sessions", `session-${session}.events.jsonl`), "utf8").catch(() => "");
65235
65897
  const withTools = (message) => {
65236
65898
  const content = message?.content;
65237
65899
  return Array.isArray(content) && content.some((block) => ["tool_use", "tool_result"].includes(String(block?.type)));
@@ -65273,7 +65935,7 @@ mode: primary
65273
65935
  ${brief}
65274
65936
  `;
65275
65937
  await mkdir32(directory, { recursive: true, mode: 448 });
65276
- if (await readFile52(file4, "utf8").catch(() => void 0) !== definition) await atomic(file4, definition, 420);
65938
+ if (await readFile51(file4, "utf8").catch(() => void 0) !== definition) await atomic(file4, definition, 420);
65277
65939
  return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
65278
65940
  }
65279
65941
  if (kind === "phren") return [...PHREN_AGENT_ARGS, ...model ? phrenModelArgs(model) : [], "--append-system-prompt-file", briefFile, ...effortArgs(kind, effort)];
@@ -65501,7 +66163,9 @@ async function startSession(server, data, options) {
65501
66163
  startThread: !!brief,
65502
66164
  ...permissionMode ? { remoteArgs: codexModeFlags(permissionMode) } : {}
65503
66165
  }).catch((error62) => {
65504
- logger.warn("launch", `Codex app-server unavailable, typing instead: ${error62 instanceof Error ? error62.message : String(error62)}`);
66166
+ const note = `Codex app-server unavailable, typing instead: ${error62 instanceof Error ? error62.message : String(error62)}`;
66167
+ if (error62 instanceof AppServerUnsupportedError) logger.debug("launch", note);
66168
+ else logger.warn("launch", note);
65505
66169
  return void 0;
65506
66170
  }) : void 0;
65507
66171
  const appServer = structuredLaunch?.entry;
@@ -66780,8 +67444,8 @@ var init_session_git = __esm({
66780
67444
  // src/bridge/enroll.ts
66781
67445
  import { execFile as execFile29 } from "node:child_process";
66782
67446
  import { promisify as promisify27 } from "node:util";
66783
- import { realpathSync as realpathSync5 } from "node:fs";
66784
- import { readdir as readdir20, readFile as readFile53, stat as stat30, mkdir as mkdir33 } from "node:fs/promises";
67447
+ import { realpathSync as realpathSync6 } from "node:fs";
67448
+ import { readdir as readdir20, readFile as readFile52, stat as stat30, mkdir as mkdir33 } from "node:fs/promises";
66785
67449
  import { homedir as homedir19 } from "node:os";
66786
67450
  import path130 from "node:path";
66787
67451
  function repoName(url2) {
@@ -66810,7 +67474,7 @@ async function registeredSources(env) {
66810
67474
  const source = readProjectConfig(store, project).sourcePath;
66811
67475
  if (typeof source === "string" && source) {
66812
67476
  try {
66813
- paths.add(realpathSync5.native(path130.resolve(source)));
67477
+ paths.add(realpathSync6.native(path130.resolve(source)));
66814
67478
  } catch {
66815
67479
  }
66816
67480
  }
@@ -66825,7 +67489,7 @@ async function candidateRepos(activity, env = process.env) {
66825
67489
  let dir = path130.resolve(directory);
66826
67490
  try {
66827
67491
  if (!(await stat30(dir)).isDirectory()) return;
66828
- dir = realpathSync5.native(dir);
67492
+ dir = realpathSync6.native(dir);
66829
67493
  } catch {
66830
67494
  return;
66831
67495
  }
@@ -66869,7 +67533,7 @@ async function candidateRepos(activity, env = process.env) {
66869
67533
  if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
66870
67534
  }
66871
67535
  try {
66872
- const session = JSON.parse(await readFile53(path130.join(herdrRoot(), "session.json"), "utf8"));
67536
+ const session = JSON.parse(await readFile52(path130.join(herdrRoot(), "session.json"), "utf8"));
66873
67537
  for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
66874
67538
  const directory = JSON.parse(`"${match[1]}"`);
66875
67539
  if (!path130.isAbsolute(directory)) continue;
@@ -66954,7 +67618,7 @@ async function enrollProject(input2, env = process.env) {
66954
67618
  const raw = input2.directory;
66955
67619
  if (raw.length > 4096 || raw.includes("\0") || !path130.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
66956
67620
  try {
66957
- directory = realpathSync5.native(raw);
67621
+ directory = realpathSync6.native(raw);
66958
67622
  if (!(await stat30(directory)).isDirectory()) throw new Error();
66959
67623
  } catch {
66960
67624
  throw new BridgeError(404, "That folder is not on this computer.");
@@ -72169,10 +72833,10 @@ var init_project_git = __esm({
72169
72833
 
72170
72834
  // src/bridge/simulators.ts
72171
72835
  import { execFile as execFile30 } from "node:child_process";
72172
- import { chmod as chmod5, mkdir as mkdir34, readFile as readFile54, rename as rename11, stat as stat31, unlink as unlink9, writeFile as writeFile12 } from "node:fs/promises";
72836
+ import { chmod as chmod5, mkdir as mkdir34, readFile as readFile53, rename as rename10, stat as stat31, unlink as unlink9, writeFile as writeFile11 } from "node:fs/promises";
72173
72837
  import { tmpdir as tmpdir6 } from "node:os";
72174
72838
  import path137 from "node:path";
72175
- import { createHash as createHash30, randomUUID as randomUUID29 } from "node:crypto";
72839
+ import { createHash as createHash31, randomUUID as randomUUID29 } from "node:crypto";
72176
72840
  import { promisify as promisify28 } from "node:util";
72177
72841
  async function bootedSimulators() {
72178
72842
  if (process.platform !== "darwin") return [];
@@ -72200,7 +72864,7 @@ async function simulatorScreenshot(udid) {
72200
72864
  const file4 = path137.join(tmpdir6(), `phren-sim-${randomUUID29()}.png`);
72201
72865
  try {
72202
72866
  await exec25("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file4], { timeout: 15e3 });
72203
- return await readFile54(file4);
72867
+ return await readFile53(file4);
72204
72868
  } catch (error62) {
72205
72869
  if (error62 instanceof BridgeError) throw error62;
72206
72870
  throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
@@ -72308,23 +72972,23 @@ case "type":
72308
72972
  }
72309
72973
  default: fail(2, "unknown command \\(command)")
72310
72974
  }
72311
- ` : await readFile54(new URL("./native/simtap.swift", import.meta.url), "utf8");
72312
- const digest2 = createHash30("sha256").update(code).digest("hex");
72313
- const saved = await readFile54(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
72975
+ ` : await readFile53(new URL("./native/simtap.swift", import.meta.url), "utf8");
72976
+ const digest2 = createHash31("sha256").update(code).digest("hex");
72977
+ const saved = await readFile53(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
72314
72978
  if (await stat31(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
72315
72979
  await mkdir34(dir, { recursive: true, mode: 448 });
72316
72980
  const temporary = path137.join(dir, `simtap.${randomUUID29()}`), source = temporary + ".swift";
72317
72981
  const sidecar = temporary + ".sha256";
72318
72982
  try {
72319
- await writeFile12(source, code, { mode: 384, flag: "wx" });
72983
+ await writeFile11(source, code, { mode: 384, flag: "wx" });
72320
72984
  await exec25("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
72321
72985
  throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
72322
72986
  });
72323
72987
  await chmod5(temporary, 448);
72324
- const binarySha = createHash30("sha256").update(await readFile54(temporary)).digest("hex");
72325
- await writeFile12(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
72326
- await rename11(temporary, binary);
72327
- await rename11(sidecar, binary + ".sha256");
72988
+ const binarySha = createHash31("sha256").update(await readFile53(temporary)).digest("hex");
72989
+ await writeFile11(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
72990
+ await rename10(temporary, binary);
72991
+ await rename10(sidecar, binary + ".sha256");
72328
72992
  } finally {
72329
72993
  await Promise.all([source, temporary, sidecar].map((file4) => unlink9(file4).catch(() => void 0)));
72330
72994
  }
@@ -72338,8 +73002,8 @@ function simtap(name, ...args) {
72338
73002
  }
72339
73003
  async function verifiedHelper() {
72340
73004
  const binary = await helper();
72341
- const saved = await readFile54(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
72342
- const binarySha = createHash30("sha256").update(await readFile54(binary)).digest("hex");
73005
+ const saved = await readFile53(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
73006
+ const binarySha = createHash31("sha256").update(await readFile53(binary)).digest("hex");
72343
73007
  if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
72344
73008
  return binary;
72345
73009
  }
@@ -72795,7 +73459,7 @@ var init_session_rename = __esm({
72795
73459
 
72796
73460
  // src/bridge/link.ts
72797
73461
  import { execFile as execFile31 } from "node:child_process";
72798
- import { readFile as readFile55 } from "node:fs/promises";
73462
+ import { readFile as readFile54 } from "node:fs/promises";
72799
73463
  import { homedir as homedir21, hostname as hostname12, userInfo as userInfo5 } from "node:os";
72800
73464
  import path140 from "node:path";
72801
73465
  import { promisify as promisify29 } from "node:util";
@@ -72840,11 +73504,11 @@ async function probe2(host) {
72840
73504
  return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
72841
73505
  }
72842
73506
  async function discoverComputers(options = {}) {
72843
- const config4 = options.sshConfig ?? await readFile55(path140.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
73507
+ const config4 = options.sshConfig ?? await readFile54(path140.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
72844
73508
  const store = options.store !== void 0 ? options.store : findPhrenPath();
72845
73509
  const machines = store ? listMachines(store) : void 0;
72846
73510
  const { peers } = await optionalHookPeers();
72847
- const own2 = (await readFile55(path140.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
73511
+ const own2 = (await readFile54(path140.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
72848
73512
  const known2 = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
72849
73513
  const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config4), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known2.has(computerLabel(host))).slice(0, 32);
72850
73514
  const [found, peerIds] = await Promise.all([
@@ -72866,7 +73530,7 @@ function slugName(value2) {
72866
73530
  async function linkComputer(host, options = {}) {
72867
73531
  const remote = await probe2(host);
72868
73532
  if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
72869
- const own2 = (await readFile55(path140.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
73533
+ const own2 = (await readFile54(path140.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
72870
73534
  if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
72871
73535
  const name = computerName.parse(options.name ?? slugName(host));
72872
73536
  const as2 = computerName.parse(options.as ?? slugName(hostname12()));
@@ -74753,11 +75417,11 @@ var init_server_overview = __esm({
74753
75417
  });
74754
75418
 
74755
75419
  // src/bridge/codex-auth-refresh.ts
74756
- import { readFile as readFile56 } from "node:fs/promises";
75420
+ import { readFile as readFile55 } from "node:fs/promises";
74757
75421
  import path142 from "node:path";
74758
75422
  async function lastCodexRefresh(file4 = path142.join(codexHome(), "auth.json")) {
74759
75423
  try {
74760
- const auth = object2(JSON.parse(await readFile56(file4, "utf8")));
75424
+ const auth = object2(JSON.parse(await readFile55(file4, "utf8")));
74761
75425
  if (!object2(auth.tokens).refresh_token) return void 0;
74762
75426
  const at2 = Date.parse(String(auth.last_refresh ?? ""));
74763
75427
  return Number.isFinite(at2) ? at2 : 0;
@@ -74774,6 +75438,7 @@ var init_codex_auth_refresh = __esm({
74774
75438
  "use strict";
74775
75439
  init_home_paths();
74776
75440
  init_logger();
75441
+ init_codex_app_server();
74777
75442
  init_protocol();
74778
75443
  REFRESH_AFTER_MS = 6 * 864e5;
74779
75444
  CodexAuthKeeper = class {
@@ -74798,6 +75463,10 @@ var init_codex_auth_refresh = __esm({
74798
75463
  try {
74799
75464
  await this.refresher.refreshAuth();
74800
75465
  } catch (error62) {
75466
+ if (error62 instanceof AppServerUnsupportedError) {
75467
+ logger.debug("codex-auth", `Sign-in refresh skipped: ${error62.message}`);
75468
+ return false;
75469
+ }
74801
75470
  logger.warn("codex-auth", `Could not refresh the Codex sign-in ahead of its workers: ${error62 instanceof Error ? error62.message : String(error62)}`);
74802
75471
  return false;
74803
75472
  }
@@ -74813,8 +75482,8 @@ var init_codex_auth_refresh = __esm({
74813
75482
 
74814
75483
  // src/bridge/server.ts
74815
75484
  import { randomUUID as randomUUID30 } from "node:crypto";
74816
- import { chmod as chmod6, lstat as lstat36, mkdir as mkdir35, readFile as readFile57, rm as rm18, unlink as unlink10, writeFile as writeFile13 } from "node:fs/promises";
74817
- import { readFileSync as readFileSync55 } from "node:fs";
75485
+ import { chmod as chmod6, lstat as lstat36, mkdir as mkdir35, readFile as readFile56, rm as rm17, unlink as unlink10, writeFile as writeFile12 } from "node:fs/promises";
75486
+ import { readFileSync as readFileSync57 } from "node:fs";
74818
75487
  import { createServer as createServer4 } from "node:http";
74819
75488
  import { cpus as cpus2, hostname as hostname13, loadavg as loadavg2 } from "node:os";
74820
75489
  import path143 from "node:path";
@@ -74829,10 +75498,10 @@ async function serve(version2, options = {}) {
74829
75498
  let computerID2;
74830
75499
  const identityFile = path143.join(root, "computer-id");
74831
75500
  try {
74832
- computerID2 = (await readFile57(identityFile, "utf8")).trim();
75501
+ computerID2 = (await readFile56(identityFile, "utf8")).trim();
74833
75502
  } catch {
74834
75503
  computerID2 = randomUUID30();
74835
- await writeFile13(identityFile, computerID2, { flag: "wx", mode: 384 });
75504
+ await writeFile12(identityFile, computerID2, { flag: "wx", mode: 384 });
74836
75505
  }
74837
75506
  const launches = new LaunchLimiter();
74838
75507
  const dispatches = modules.has("conductor") ? new DispatchService({
@@ -74954,7 +75623,7 @@ async function serve(version2, options = {}) {
74954
75623
  if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
74955
75624
  function gatewayTiming() {
74956
75625
  try {
74957
- const parsed = JSON.parse(readFileSync55(path143.join(root, "gateway.json"), "utf8"));
75626
+ const parsed = JSON.parse(readFileSync57(path143.join(root, "gateway.json"), "utf8"));
74958
75627
  if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
74959
75628
  } catch {
74960
75629
  }
@@ -75000,7 +75669,7 @@ async function serve(version2, options = {}) {
75000
75669
  }
75001
75670
  const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
75002
75671
  };
75003
- if (modules.has("git")) await rm18(path143.join(root, "changes-scratch"), { recursive: true, force: true });
75672
+ if (modules.has("git")) await rm17(path143.join(root, "changes-scratch"), { recursive: true, force: true });
75004
75673
  const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
75005
75674
  const { stream } = streams;
75006
75675
  const overview = overviewStream({
@@ -75266,7 +75935,7 @@ __export(device_enroll_exports, {
75266
75935
  enrollDevice: () => enrollDevice,
75267
75936
  runEnrollDevice: () => runEnrollDevice
75268
75937
  });
75269
- import { readFile as readFile58 } from "node:fs/promises";
75938
+ import { readFile as readFile57 } from "node:fs/promises";
75270
75939
  import { homedir as homedir22, userInfo as userInfo6 } from "node:os";
75271
75940
  import path144 from "node:path";
75272
75941
  async function enrollDevice(input2, options) {
@@ -75276,14 +75945,14 @@ async function enrollDevice(input2, options) {
75276
75945
  const line = `restrict,pty,${forcedCommand} ${publicKey} ${comment}`;
75277
75946
  const encoded = publicKey.split(" ")[1];
75278
75947
  const file4 = path144.join(options.sshDirectory ?? path144.join(homedir22(), ".ssh"), "authorized_keys");
75279
- const before = await readFile58(file4, "utf8").catch(() => "");
75948
+ const before = await readFile57(file4, "utf8").catch(() => "");
75280
75949
  await appendAuthorizedKey(
75281
75950
  line,
75282
75951
  (existing) => existing.split(/\s+/).includes(encoded),
75283
75952
  "This phone key is already authorized with different options.",
75284
75953
  options.sshDirectory
75285
75954
  );
75286
- const id2 = await readFile58(path144.join(options.root ?? bridgeRoot(), "computer-id"), "utf8").then((value2) => value2.trim() || null).catch(() => null);
75955
+ const id2 = await readFile57(path144.join(options.root ?? bridgeRoot(), "computer-id"), "utf8").then((value2) => value2.trim() || null).catch(() => null);
75287
75956
  return {
75288
75957
  v: 1,
75289
75958
  ok: true,
@@ -75334,13 +76003,13 @@ __export(command_exports, {
75334
76003
  approvalPushCheck: () => approvalPushCheck,
75335
76004
  runBridge: () => runBridge
75336
76005
  });
75337
- import { readFile as readFile59 } from "node:fs/promises";
76006
+ import { readFile as readFile58 } from "node:fs/promises";
75338
76007
  async function runBridge(args, version2) {
75339
76008
  switch (args[0]) {
75340
76009
  case "enroll-computer": {
75341
76010
  if (args.length === 2) console.log(await enrollComputer(args[1]));
75342
76011
  else if (args.length === 4 && args[2] === "--accept") {
75343
- await acceptComputer(args[1], await readFile59(args[3], "utf8"));
76012
+ await acceptComputer(args[1], await readFile58(args[3], "utf8"));
75344
76013
  console.log(`Enrolled ${args[1]} for Phren Hook.`);
75345
76014
  } else throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
75346
76015
  break;
@@ -75515,7 +76184,7 @@ async function runBridge(args, version2) {
75515
76184
  break;
75516
76185
  }
75517
76186
  const readModels = async (source) => {
75518
- const rows2 = JSON.parse(await readFile59(fixture, "utf8"));
76187
+ const rows2 = JSON.parse(await readFile58(fixture, "utf8"));
75519
76188
  return Array.isArray(rows2[source]) ? rows2[source] : [];
75520
76189
  };
75521
76190
  const emptyUsage = (source) => ({ source, windows: [] });
@@ -75672,7 +76341,7 @@ async function main() {
75672
76341
  return askpass2(args[1]);
75673
76342
  }
75674
76343
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
75675
- return runBridge2(args, "0.3.45");
76344
+ return runBridge2(args, "0.3.46");
75676
76345
  }
75677
76346
  main().then((code) => {
75678
76347
  process.exitCode = code;