@phren/cli 0.3.0 → 0.3.2

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 (64) hide show
  1. package/dist/bridge/agent-hooks.d.ts +20 -6
  2. package/dist/bridge/agent-hooks.js +74 -24
  3. package/dist/bridge/claude-question-dialog.d.ts +65 -0
  4. package/dist/bridge/claude-question-dialog.js +210 -0
  5. package/dist/bridge/command.d.ts +3 -2
  6. package/dist/bridge/command.js +97 -5
  7. package/dist/bridge/computers.d.ts +5 -0
  8. package/dist/bridge/computers.js +10 -4
  9. package/dist/bridge/conductor-group.d.ts +23 -0
  10. package/dist/bridge/conductor-group.js +25 -0
  11. package/dist/bridge/hand-off.js +5 -1
  12. package/dist/bridge/herdr.d.ts +7 -0
  13. package/dist/bridge/herdr.js +53 -2
  14. package/dist/bridge/link.d.ts +48 -0
  15. package/dist/bridge/link.js +136 -0
  16. package/dist/bridge/memory-store.d.ts +23 -0
  17. package/dist/bridge/memory-store.js +152 -0
  18. package/dist/bridge/pair.d.ts +46 -0
  19. package/dist/bridge/pair.js +240 -0
  20. package/dist/bridge/peers.d.ts +9 -0
  21. package/dist/bridge/peers.js +25 -2
  22. package/dist/bridge/push.d.ts +42 -3
  23. package/dist/bridge/push.js +90 -20
  24. package/dist/bridge/server-launch.d.ts +9 -0
  25. package/dist/bridge/server-launch.js +34 -11
  26. package/dist/bridge/server-pane-routes.js +45 -8
  27. package/dist/bridge/server-routes.d.ts +1 -0
  28. package/dist/bridge/server-routes.js +11 -3
  29. package/dist/bridge/server-stream.js +4 -1
  30. package/dist/bridge/speech-key.d.ts +33 -0
  31. package/dist/bridge/speech-key.js +106 -0
  32. package/dist/bridge/speech-transcribe.js +1 -1
  33. package/dist/bridge/speech.d.ts +7 -3
  34. package/dist/bridge/speech.js +36 -17
  35. package/dist/bridge-hook.mjs +1356 -514
  36. package/dist/cli/namespaces-store.js +21 -0
  37. package/dist/cli-handlers.js +6 -0
  38. package/dist/cli-registry.js +14 -2
  39. package/dist/content/learning.js +1 -1
  40. package/dist/data/tasks.d.ts +26 -0
  41. package/dist/data/tasks.js +72 -1
  42. package/dist/entrypoint.js +7 -0
  43. package/dist/governance/rbac.d.ts +1 -1
  44. package/dist/governance/rbac.js +1 -0
  45. package/dist/init/init-walkthrough.d.ts +10 -0
  46. package/dist/init/init-walkthrough.js +25 -2
  47. package/dist/init/init.d.ts +5 -0
  48. package/dist/init/init.js +54 -32
  49. package/dist/link/doctor.js +10 -0
  50. package/dist/link/link.js +9 -3
  51. package/dist/link/refresh.js +11 -10
  52. package/dist/mcp/profile.js +2 -1
  53. package/dist/modules/config.d.ts +7 -0
  54. package/dist/modules/config.js +17 -0
  55. package/dist/modules/registry.js +5 -4
  56. package/dist/sync/conflict-resolve.d.ts +1 -1
  57. package/dist/sync/conflict-resolve.js +44 -7
  58. package/dist/sync/task-claim.d.ts +22 -0
  59. package/dist/sync/task-claim.js +45 -0
  60. package/dist/tools/dispatch.js +2 -2
  61. package/dist/tools/search.js +1 -1
  62. package/dist/tools/tasks.js +40 -1
  63. package/package.json +2 -1
  64. package/starter/global/skills/conductor/SKILL.md +41 -9
@@ -268,10 +268,10 @@ function mergeDefs(...defs) {
268
268
  function cloneDef(schema) {
269
269
  return mergeDefs(schema._zod.def);
270
270
  }
271
- function getElementAtPath(obj, path79) {
272
- if (!path79)
271
+ function getElementAtPath(obj, path81) {
272
+ if (!path81)
273
273
  return obj;
274
- return path79.reduce((acc, key) => acc?.[key], obj);
274
+ return path81.reduce((acc, key) => acc?.[key], obj);
275
275
  }
276
276
  function promiseAllObject(promisesObj) {
277
277
  const keys = Object.keys(promisesObj);
@@ -530,11 +530,11 @@ function explicitlyAborted(x, startIndex = 0) {
530
530
  }
531
531
  return false;
532
532
  }
533
- function prefixIssues(path79, issues) {
533
+ function prefixIssues(path81, issues) {
534
534
  return issues.map((iss) => {
535
535
  var _a3;
536
536
  (_a3 = iss).path ?? (_a3.path = []);
537
- iss.path.unshift(path79);
537
+ iss.path.unshift(path81);
538
538
  return iss;
539
539
  });
540
540
  }
@@ -1055,16 +1055,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
1055
1055
  }
1056
1056
  function formatError(error62, mapper = (issue2) => issue2.message) {
1057
1057
  const fieldErrors = { _errors: [] };
1058
- const processError = (error63, path79 = []) => {
1058
+ const processError = (error63, path81 = []) => {
1059
1059
  for (const issue2 of error63.issues) {
1060
1060
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1061
- issue2.errors.map((issues) => processError({ issues }, [...path79, ...issue2.path]));
1061
+ issue2.errors.map((issues) => processError({ issues }, [...path81, ...issue2.path]));
1062
1062
  } else if (issue2.code === "invalid_key") {
1063
- processError({ issues: issue2.issues }, [...path79, ...issue2.path]);
1063
+ processError({ issues: issue2.issues }, [...path81, ...issue2.path]);
1064
1064
  } else if (issue2.code === "invalid_element") {
1065
- processError({ issues: issue2.issues }, [...path79, ...issue2.path]);
1065
+ processError({ issues: issue2.issues }, [...path81, ...issue2.path]);
1066
1066
  } else {
1067
- const fullpath = [...path79, ...issue2.path];
1067
+ const fullpath = [...path81, ...issue2.path];
1068
1068
  if (fullpath.length === 0) {
1069
1069
  fieldErrors._errors.push(mapper(issue2));
1070
1070
  } else {
@@ -1103,17 +1103,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
1103
1103
  }
1104
1104
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
1105
1105
  const result = { errors: [] };
1106
- const processError = (error63, path79 = []) => {
1106
+ const processError = (error63, path81 = []) => {
1107
1107
  var _a3;
1108
1108
  for (const issue2 of error63.issues) {
1109
1109
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1110
- issue2.errors.map((issues) => processError({ issues }, [...path79, ...issue2.path]));
1110
+ issue2.errors.map((issues) => processError({ issues }, [...path81, ...issue2.path]));
1111
1111
  } else if (issue2.code === "invalid_key") {
1112
- processError({ issues: issue2.issues }, [...path79, ...issue2.path]);
1112
+ processError({ issues: issue2.issues }, [...path81, ...issue2.path]);
1113
1113
  } else if (issue2.code === "invalid_element") {
1114
- processError({ issues: issue2.issues }, [...path79, ...issue2.path]);
1114
+ processError({ issues: issue2.issues }, [...path81, ...issue2.path]);
1115
1115
  } else {
1116
- const fullpath = [...path79, ...issue2.path];
1116
+ const fullpath = [...path81, ...issue2.path];
1117
1117
  if (fullpath.length === 0) {
1118
1118
  result.errors.push(mapper(issue2));
1119
1119
  continue;
@@ -1152,8 +1152,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
1152
1152
  }
1153
1153
  function toDotPath(_path) {
1154
1154
  const segs = [];
1155
- const path79 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1156
- for (const seg of path79) {
1155
+ const path81 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1156
+ for (const seg of path81) {
1157
1157
  if (typeof seg === "number")
1158
1158
  segs.push(`[${seg}]`);
1159
1159
  else if (typeof seg === "symbol")
@@ -2164,9 +2164,9 @@ function parseURLObject(trimmed, def) {
2164
2164
  function stripTabAndNewline(value2) {
2165
2165
  return value2.replace(asciiTabOrNewline, "");
2166
2166
  }
2167
- function urlHostnameOk(url2, hostname9) {
2168
- hostname9.lastIndex = 0;
2169
- return hostname9.test(url2.hostname);
2167
+ function urlHostnameOk(url2, hostname10) {
2168
+ hostname10.lastIndex = 0;
2169
+ return hostname10.test(url2.hostname);
2170
2170
  }
2171
2171
  function urlProtocolOk(url2, protocol) {
2172
2172
  protocol.lastIndex = 0;
@@ -16203,14 +16203,14 @@ function rewriteKeyNames(ctx) {
16203
16203
  }
16204
16204
  function serializeDefaultValue(value2, schema, ctx, json2, params) {
16205
16205
  let unrepresentable = false;
16206
- const serialized = JSON.stringify(value2, (_, val) => {
16206
+ const serialized2 = JSON.stringify(value2, (_, val) => {
16207
16207
  if (typeof val !== "bigint")
16208
16208
  return val;
16209
16209
  unrepresentable = true;
16210
16210
  return null;
16211
16211
  });
16212
16212
  if (!unrepresentable)
16213
- return JSON.parse(serialized);
16213
+ return JSON.parse(serialized2);
16214
16214
  handleUnrepresentable(schema, ctx, json2, params, "BigInt defaults cannot be represented in JSON Schema");
16215
16215
  return UNREPRESENTABLE_DEFAULT;
16216
16216
  }
@@ -19149,13 +19149,13 @@ function resolveRef(ref, ctx) {
19149
19149
  if (!ref.startsWith("#")) {
19150
19150
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
19151
19151
  }
19152
- const path79 = ref.slice(1).split("/").filter(Boolean);
19153
- if (path79.length === 0) {
19152
+ const path81 = ref.slice(1).split("/").filter(Boolean);
19153
+ if (path81.length === 0) {
19154
19154
  return ctx.rootSchema;
19155
19155
  }
19156
19156
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
19157
- if (path79[0] === defsKey) {
19158
- const key = path79[1] === void 0 ? void 0 : decodeJSONPointerSegment(path79[1]);
19157
+ if (path81[0] === defsKey) {
19158
+ const key = path81[1] === void 0 ? void 0 : decodeJSONPointerSegment(path81[1]);
19159
19159
  if (!key || !ctx.defs[key]) {
19160
19160
  throw new Error(`Reference not found: ${ref}`);
19161
19161
  }
@@ -19898,21 +19898,21 @@ function visit(schema, fnOrHandlers) {
19898
19898
  case "object": {
19899
19899
  const oldShape = def.shape;
19900
19900
  const keys = Object.keys(oldShape);
19901
- let changed = false;
19901
+ let changed2 = false;
19902
19902
  const newShape = {};
19903
19903
  for (const k of keys) {
19904
19904
  const mapped = run(oldShape[k]);
19905
19905
  if (mapped !== oldShape[k])
19906
- changed = true;
19906
+ changed2 = true;
19907
19907
  newShape[k] = mapped;
19908
19908
  }
19909
19909
  let newCatchall = def.catchall;
19910
19910
  if (def.catchall) {
19911
19911
  newCatchall = run(def.catchall);
19912
19912
  if (newCatchall !== def.catchall)
19913
- changed = true;
19913
+ changed2 = true;
19914
19914
  }
19915
- return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s;
19915
+ return changed2 ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s;
19916
19916
  }
19917
19917
  case "array": {
19918
19918
  const mapped = run(def.element);
@@ -19920,21 +19920,21 @@ function visit(schema, fnOrHandlers) {
19920
19920
  }
19921
19921
  case "tuple": {
19922
19922
  const oldItems = def.items;
19923
- let changed = false;
19923
+ let changed2 = false;
19924
19924
  const newItems = [];
19925
19925
  for (const item of oldItems) {
19926
19926
  const mapped = run(item);
19927
19927
  if (mapped !== item)
19928
- changed = true;
19928
+ changed2 = true;
19929
19929
  newItems.push(mapped);
19930
19930
  }
19931
19931
  let newRest = def.rest;
19932
19932
  if (def.rest) {
19933
19933
  newRest = run(def.rest);
19934
19934
  if (newRest !== def.rest)
19935
- changed = true;
19935
+ changed2 = true;
19936
19936
  }
19937
- return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s;
19937
+ return changed2 ? clone(s, { ...def, items: newItems, rest: newRest }) : s;
19938
19938
  }
19939
19939
  case "record":
19940
19940
  case "map": {
@@ -19948,15 +19948,15 @@ function visit(schema, fnOrHandlers) {
19948
19948
  }
19949
19949
  case "union": {
19950
19950
  const oldOptions = def.options;
19951
- let changed = false;
19951
+ let changed2 = false;
19952
19952
  const newOptions = [];
19953
19953
  for (const opt of oldOptions) {
19954
19954
  const mapped = run(opt);
19955
19955
  if (mapped !== opt)
19956
- changed = true;
19956
+ changed2 = true;
19957
19957
  newOptions.push(mapped);
19958
19958
  }
19959
- return changed ? clone(s, { ...def, options: newOptions }) : s;
19959
+ return changed2 ? clone(s, { ...def, options: newOptions }) : s;
19960
19960
  }
19961
19961
  case "intersection": {
19962
19962
  const newLeft = run(def.left);
@@ -20615,7 +20615,7 @@ var init_metrics = __esm({
20615
20615
  };
20616
20616
  hookMetrics = new HookMetrics();
20617
20617
  countHerdr = (method) => hookMetrics.count("herdr", method);
20618
- countIdentity = (probe2) => hookMetrics.count("identity", probe2);
20618
+ countIdentity = (probe3) => hookMetrics.count("identity", probe3);
20619
20619
  countGit = (caller) => hookMetrics.count("git", caller);
20620
20620
  countTick = (timer) => hookMetrics.count("timer", timer);
20621
20621
  }
@@ -22107,9 +22107,9 @@ function resolveString(expression, source) {
22107
22107
  const declaration = new RegExp(`\\b(?:const|let|var)\\s+${identifier}\\s*=\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`)`).exec(source);
22108
22108
  return declaration ? unescapeJs(declaration[1].slice(1, -1)) : void 0;
22109
22109
  }
22110
- function callArguments(source, open14) {
22110
+ function callArguments(source, open15) {
22111
22111
  let depth = 0, quote3 = "";
22112
- for (let index2 = open14; index2 < source.length; index2++) {
22112
+ for (let index2 = open15; index2 < source.length; index2++) {
22113
22113
  const character = source[index2];
22114
22114
  if (quote3) {
22115
22115
  if (character === "\\") index2++;
@@ -22122,7 +22122,7 @@ function callArguments(source, open14) {
22122
22122
  }
22123
22123
  if (character === "(" || character === "{" || character === "[") depth++;
22124
22124
  else if (character === ")" || character === "}" || character === "]") {
22125
- if (--depth === 0) return source.slice(open14 + 1, index2);
22125
+ if (--depth === 0) return source.slice(open15 + 1, index2);
22126
22126
  }
22127
22127
  }
22128
22128
  return void 0;
@@ -26436,8 +26436,8 @@ function appendAuditLog(phrenPath, event, details) {
26436
26436
  fs3.mkdirSync(path11.dirname(logPath), { recursive: true });
26437
26437
  withFileLock(logPath, () => {
26438
26438
  fs3.appendFileSync(logPath, line);
26439
- const stat24 = fs3.statSync(logPath);
26440
- if (stat24.size > 1e6) {
26439
+ const stat25 = fs3.statSync(logPath);
26440
+ if (stat25.size > 1e6) {
26441
26441
  const content = fs3.readFileSync(logPath, "utf8");
26442
26442
  const lines = content.split("\n");
26443
26443
  fs3.writeFileSync(logPath, lines.slice(-MAX_LOG_LINES).join("\n") + "\n");
@@ -26526,8 +26526,8 @@ ${Date.now()}`, { flag: "wx" });
26526
26526
  } catch (err) {
26527
26527
  logger.debug("acquireFileLock", `lockWrite: ${errorMessage(err)}`);
26528
26528
  try {
26529
- const stat24 = fs5.statSync(lockPath);
26530
- if (Date.now() - stat24.mtimeMs > staleThreshold) {
26529
+ const stat25 = fs5.statSync(lockPath);
26530
+ if (Date.now() - stat25.mtimeMs > staleThreshold) {
26531
26531
  let ownerAlive = false;
26532
26532
  try {
26533
26533
  const content = fs5.readFileSync(lockPath, "utf-8");
@@ -28275,7 +28275,7 @@ var init_package_metadata = __esm({
28275
28275
  __dirname = path24.dirname(fileURLToPath2(import.meta.url));
28276
28276
  ROOT = path24.join(__dirname, "..");
28277
28277
  PACKAGE_JSON_PATH = path24.join(ROOT, "package.json");
28278
- BUNDLED_VERSION = true ? "0.3.0" : "0.0.0";
28278
+ BUNDLED_VERSION = true ? "0.3.2" : "0.0.0";
28279
28279
  PACKAGE_JSON = readPackageJson();
28280
28280
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
28281
28281
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -30522,7 +30522,7 @@ var require_websocket = __commonJS({
30522
30522
  var http = __require("http");
30523
30523
  var net = __require("net");
30524
30524
  var tls = __require("tls");
30525
- var { randomBytes: randomBytes4, createHash: createHash18 } = __require("crypto");
30525
+ var { randomBytes: randomBytes5, createHash: createHash19 } = __require("crypto");
30526
30526
  var { Duplex: Duplex2, Readable } = __require("stream");
30527
30527
  var { URL: URL2 } = __require("url");
30528
30528
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -31060,7 +31060,7 @@ var require_websocket = __commonJS({
31060
31060
  }
31061
31061
  }
31062
31062
  const defaultPort = isSecure ? 443 : 80;
31063
- const key = randomBytes4(16).toString("base64");
31063
+ const key = randomBytes5(16).toString("base64");
31064
31064
  const request6 = isSecure ? https.request : http.request;
31065
31065
  const protocolSet = /* @__PURE__ */ new Set();
31066
31066
  let perMessageDeflate;
@@ -31190,7 +31190,7 @@ var require_websocket = __commonJS({
31190
31190
  abortHandshake(websocket, socket, "Invalid Upgrade header");
31191
31191
  return;
31192
31192
  }
31193
- const digest2 = createHash18("sha1").update(key + GUID).digest("base64");
31193
+ const digest2 = createHash19("sha1").update(key + GUID).digest("base64");
31194
31194
  if (res.headers["sec-websocket-accept"] !== digest2) {
31195
31195
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
31196
31196
  return;
@@ -31471,7 +31471,7 @@ var require_stream = __commonJS({
31471
31471
  };
31472
31472
  duplex._final = function(callback) {
31473
31473
  if (ws.readyState === ws.CONNECTING) {
31474
- ws.once("open", function open14() {
31474
+ ws.once("open", function open15() {
31475
31475
  duplex._final(callback);
31476
31476
  });
31477
31477
  return;
@@ -31492,7 +31492,7 @@ var require_stream = __commonJS({
31492
31492
  };
31493
31493
  duplex._write = function(chunk, encoding, callback) {
31494
31494
  if (ws.readyState === ws.CONNECTING) {
31495
- ws.once("open", function open14() {
31495
+ ws.once("open", function open15() {
31496
31496
  duplex._write(chunk, encoding, callback);
31497
31497
  });
31498
31498
  return;
@@ -31559,7 +31559,7 @@ var require_websocket_server = __commonJS({
31559
31559
  var EventEmitter = __require("events");
31560
31560
  var http = __require("http");
31561
31561
  var { Duplex: Duplex2 } = __require("stream");
31562
- var { createHash: createHash18 } = __require("crypto");
31562
+ var { createHash: createHash19 } = __require("crypto");
31563
31563
  var extension2 = require_extension();
31564
31564
  var PerMessageDeflate2 = require_permessage_deflate();
31565
31565
  var subprotocol2 = require_subprotocol();
@@ -31866,7 +31866,7 @@ var require_websocket_server = __commonJS({
31866
31866
  );
31867
31867
  }
31868
31868
  if (this._state > RUNNING) return abortHandshake(socket, 503);
31869
- const digest2 = createHash18("sha1").update(key + GUID).digest("base64");
31869
+ const digest2 = createHash19("sha1").update(key + GUID).digest("base64");
31870
31870
  const headers = [
31871
31871
  "HTTP/1.1 101 Switching Protocols",
31872
31872
  "Upgrade: websocket",
@@ -32189,8 +32189,8 @@ function recordLookupEvents(phrenPath, events) {
32189
32189
  return;
32190
32190
  }
32191
32191
  try {
32192
- const stat24 = fs24.statSync(logPath);
32193
- if (stat24.size > ROTATE_BYTES) {
32192
+ const stat25 = fs24.statSync(logPath);
32193
+ if (stat25.size > ROTATE_BYTES) {
32194
32194
  const content = fs24.readFileSync(logPath, "utf8");
32195
32195
  const kept = content.split("\n").filter(Boolean).slice(-MAX_LOG_LINES2);
32196
32196
  fs24.writeFileSync(logPath, kept.join("\n") + "\n");
@@ -32722,7 +32722,7 @@ var init_policy = __esm({
32722
32722
  });
32723
32723
 
32724
32724
  // src/bridge/command.ts
32725
- import { readFile as readFile32 } from "node:fs/promises";
32725
+ import { readFile as readFile34 } from "node:fs/promises";
32726
32726
 
32727
32727
  // src/bridge/fanout-messages.ts
32728
32728
  init_zod();
@@ -32989,9 +32989,9 @@ import * as path23 from "node:path";
32989
32989
  function gitDirectory(store) {
32990
32990
  const dotGit = path23.join(store, ".git");
32991
32991
  try {
32992
- const stat24 = fs15.statSync(dotGit);
32993
- if (stat24.isDirectory()) return dotGit;
32994
- if (!stat24.isFile()) return void 0;
32992
+ const stat25 = fs15.statSync(dotGit);
32993
+ if (stat25.isDirectory()) return dotGit;
32994
+ if (!stat25.isFile()) return void 0;
32995
32995
  const match = /^gitdir:\s*(.+)\s*$/i.exec(fs15.readFileSync(dotGit, "utf8"));
32996
32996
  if (!match) return void 0;
32997
32997
  return path23.resolve(store, match[1]);
@@ -33026,7 +33026,7 @@ import * as fs17 from "node:fs";
33026
33026
  import * as path25 from "node:path";
33027
33027
  var core = (names) => names.map((name) => ({ name, profiles: ["core", "full"] }));
33028
33028
  var full = (names) => names.map((name) => ({ name, profiles: ["full"] }));
33029
- var routes = (method, paths) => paths.map((path79) => ({ method, path: path79 }));
33029
+ var routes = (method, paths) => paths.map((path81) => ({ method, path: path81 }));
33030
33030
  var BUILTIN_MODULES = [
33031
33031
  {
33032
33032
  schemaVersion: 1,
@@ -33156,8 +33156,8 @@ var BUILTIN_MODULES = [
33156
33156
  { agents: ["claude", "codex", "copilot", "cursor"], events: ["Stop"], handler: "phren hook-stop" },
33157
33157
  { agents: ["claude"], events: ["PostToolUse"], handler: "phren hook-tool" }
33158
33158
  ],
33159
- hookRoutes: [],
33160
- capabilities: ["memory"],
33159
+ hookRoutes: [...routes("GET", ["/v1/store/head", "/v1/store/tree", "/v1/store/blob"]), ...routes("POST", ["/v1/store/file", "/v1/store/delete"])],
33160
+ capabilities: ["memory", "memoryStore"],
33161
33161
  storeFiles: [
33162
33162
  "phren.root.yaml",
33163
33163
  "machines.yaml",
@@ -33189,7 +33189,7 @@ var BUILTIN_MODULES = [
33189
33189
  requires: ["memory"],
33190
33190
  tools: [
33191
33191
  ...core(["get_tasks", "add_task", "manage_task"]),
33192
- ...full(["complete_task", "remove_task", "update_task", "tidy_done_tasks", "pin_task"])
33192
+ ...full(["complete_task", "remove_task", "update_task", "tidy_done_tasks", "pin_task", "claim_task"])
33193
33193
  ],
33194
33194
  cliCommands: ["task", "tasks", "config task-mode", "config proactivity.tasks"],
33195
33195
  agentHooks: [],
@@ -33220,6 +33220,7 @@ var BUILTIN_MODULES = [
33220
33220
  "bridge hook",
33221
33221
  "bridge serve",
33222
33222
  "bridge ssh",
33223
+ "pair",
33223
33224
  "bridge fanouts archive",
33224
33225
  "canary"
33225
33226
  ],
@@ -33375,7 +33376,7 @@ var BUILTIN_MODULES = [
33375
33376
  cliCommands: ["dispatch", "dispatch status", "dispatch returns", "dispatch sessions", "hand-off", "conductor", "conductor grants", "bridge enroll-computer"],
33376
33377
  agentHooks: [],
33377
33378
  hookRoutes: [
33378
- ...routes("GET", ["/v1/dispatch", "/v1/dispatch/capacity", "/v1/conductor/grants"]),
33379
+ ...routes("GET", ["/v1/dispatch", "/v1/dispatch/capacity", "/v1/conductor", "/v1/conductor/grants"]),
33379
33380
  ...routes("POST", ["/v1/dispatch", "/v1/dispatch/workers", "/v1/dispatch/returns", "/v1/conductor/grants"]),
33380
33381
  ...routes("DELETE", ["/v1/conductor/grants"])
33381
33382
  ],
@@ -33541,11 +33542,11 @@ function activateModules(store, profile = snapshotProfile(store), legacyHook = f
33541
33542
 
33542
33543
  // src/bridge/server.ts
33543
33544
  import { randomUUID as randomUUID19 } from "node:crypto";
33544
- import { chmod as chmod5, lstat as lstat18, mkdir as mkdir19, readFile as readFile31, rm as rm9, unlink as unlink7, writeFile as writeFile10 } from "node:fs/promises";
33545
+ import { chmod as chmod5, lstat as lstat19, mkdir as mkdir21, readFile as readFile32, rm as rm10, unlink as unlink7, writeFile as writeFile11 } from "node:fs/promises";
33545
33546
  import { readFileSync as readFileSync31 } from "node:fs";
33546
33547
  import { createServer as createServer2 } from "node:http";
33547
33548
  import { cpus, hostname as hostname8, loadavg } from "node:os";
33548
- import path78 from "node:path";
33549
+ import path79 from "node:path";
33549
33550
 
33550
33551
  // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs
33551
33552
  var import_stream = __toESM(require_stream(), 1);
@@ -33557,89 +33558,90 @@ var import_subprotocol = __toESM(require_subprotocol(), 1);
33557
33558
  var import_websocket = __toESM(require_websocket(), 1);
33558
33559
  var import_websocket_server = __toESM(require_websocket_server(), 1);
33559
33560
 
33560
- // src/bridge/speech.ts
33561
- init_zod();
33561
+ // src/bridge/speech-key.ts
33562
33562
  init_home_paths();
33563
33563
  init_protocol();
33564
- import { once } from "node:events";
33565
- import { readFile as readFile7 } from "node:fs/promises";
33564
+ import { mkdir as mkdir6, readFile as readFile7, stat as stat6 } from "node:fs/promises";
33566
33565
  import path28 from "node:path";
33567
- var SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
33568
- var OUTPUT_FORMAT = "pcm_24000";
33569
- var SPEECH_MODEL = "eleven_flash_v2_5";
33570
- var DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
33571
- var MAX_TEXT = 2e3;
33572
- var speechRequest = external_exports.object({ text: external_exports.string().trim().min(1).max(MAX_TEXT) });
33573
- function speechKeyFile(env = process.env) {
33566
+ var SPEECH_KEY_ENV = "ELEVENLABS_API_KEY";
33567
+ function speechKeyFile() {
33568
+ return path28.join(bridgeRoot(), "elevenlabs.json");
33569
+ }
33570
+ function legacySpeechKeyFile(env = process.env) {
33574
33571
  return path28.join(homeDir(env), ".config", "mina-trailer.json");
33575
33572
  }
33576
- async function readSpeechKey(file2 = speechKeyFile()) {
33573
+ function clean(value2) {
33574
+ return typeof value2 === "string" && value2.trim() ? value2.trim() : void 0;
33575
+ }
33576
+ async function readStored(file2) {
33577
+ let info;
33577
33578
  try {
33578
- const key = JSON.parse(await readFile7(file2, "utf8")).elevenlabs_api_key;
33579
- return typeof key === "string" && key.trim() ? key.trim() : void 0;
33579
+ info = await stat6(file2);
33580
33580
  } catch {
33581
- return void 0;
33581
+ return { state: "missing" };
33582
33582
  }
33583
- }
33584
- async function speechError(upstream) {
33585
- let detail = "";
33583
+ if (!info.isFile()) return { state: "invalid" };
33584
+ if (process.platform !== "win32" && ((info.mode & 63) !== 0 || process.getuid && info.uid !== process.getuid())) return { state: "unsafe" };
33586
33585
  try {
33587
- detail = String((await upstream.json()).detail?.status ?? "");
33586
+ const key = clean(JSON.parse(await readFile7(file2, "utf8")).apiKey);
33587
+ return key ? { state: "ok", key } : { state: "invalid" };
33588
33588
  } catch {
33589
- }
33590
- if (detail === "quota_exceeded") return new BridgeError(402, "The ElevenLabs quota on this computer's account is used up.", { code: "speech-quota" });
33591
- switch (upstream.status) {
33592
- case 401:
33593
- case 403:
33594
- return new BridgeError(502, "ElevenLabs refused this computer's key.", { code: "speech-rejected" });
33595
- case 404:
33596
- return new BridgeError(502, "ElevenLabs doesn't know the configured voice.", { code: "speech-voice" });
33597
- case 400:
33598
- case 422:
33599
- return new BridgeError(400, "ElevenLabs couldn't voice this text.", { code: "speech-invalid" });
33600
- case 429:
33601
- return new BridgeError(429, "ElevenLabs is busy. Try again shortly.", { code: "speech-busy" });
33602
- default:
33603
- return new BridgeError(502, `ElevenLabs failed (HTTP ${upstream.status}).`, { code: "speech-failed" });
33589
+ return { state: "invalid" };
33604
33590
  }
33605
33591
  }
33606
- async function synthesizeSpeech(text3, signal, options = {}) {
33607
- const key = await (options.key ?? (() => readSpeechKey()))();
33608
- if (!key) throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
33609
- const voice = options.voice ?? process.env.PHREN_SPEECH_VOICE ?? DEFAULT_SPEECH_VOICE;
33610
- const url2 = `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice)}/stream?output_format=${OUTPUT_FORMAT}`;
33611
- let upstream;
33592
+ async function readLegacy(file2) {
33612
33593
  try {
33613
- upstream = await (options.fetch ?? fetch)(url2, {
33614
- method: "POST",
33615
- signal,
33616
- headers: { "xi-api-key": key, "Content-Type": "application/json" },
33617
- body: JSON.stringify({ text: text3, model_id: SPEECH_MODEL, voice_settings: { stability: 0.6, similarity_boost: 0.75 } })
33618
- });
33594
+ return clean(JSON.parse(await readFile7(file2, "utf8")).elevenlabs_api_key);
33619
33595
  } catch {
33620
- throw new BridgeError(502, "Couldn't reach ElevenLabs from this computer.", { code: "speech-unreachable" });
33596
+ return void 0;
33621
33597
  }
33622
- if (!upstream.ok || !upstream.body) throw await speechError(upstream);
33623
- return upstream.body;
33624
33598
  }
33625
- async function streamSpeech(data, response, options = {}) {
33626
- const { text: text3 } = speechRequest.parse(data);
33627
- const abort = new AbortController();
33628
- response.once("close", () => {
33629
- if (!response.writableEnded) abort.abort();
33630
- });
33631
- const audio = await synthesizeSpeech(text3, abort.signal, options);
33632
- response.statusCode = 200;
33633
- response.setHeader("Content-Type", "application/octet-stream");
33634
- response.setHeader("X-Phren-Audio", SPEECH_AUDIO);
33599
+ async function writeSpeechKey(key, file2 = speechKeyFile()) {
33600
+ const value2 = clean(key);
33601
+ if (!value2) throw new Error("The ElevenLabs key is empty.");
33602
+ await mkdir6(path28.dirname(file2), { recursive: true, mode: 448 });
33603
+ await atomic(file2, JSON.stringify({ apiKey: value2 }) + "\n", 384);
33604
+ }
33605
+ async function resolveSpeechKey(paths = {}) {
33606
+ const env = paths.env ?? process.env;
33607
+ const fromEnv = clean(env[SPEECH_KEY_ENV]);
33608
+ if (fromEnv) return { key: fromEnv, source: "environment" };
33609
+ const file2 = paths.file ?? speechKeyFile();
33610
+ const stored = await readStored(file2);
33611
+ if (stored.state === "ok") return { key: stored.key, source: "file" };
33612
+ if (stored.state !== "missing") return void 0;
33613
+ const legacy = await readLegacy(paths.legacy ?? legacySpeechKeyFile(env));
33614
+ if (!legacy) return void 0;
33635
33615
  try {
33636
- for await (const chunk of audio) {
33637
- if (!response.write(chunk)) await once(response, "drain", { signal: abort.signal });
33638
- }
33639
- response.end();
33616
+ await writeSpeechKey(legacy, file2);
33640
33617
  } catch {
33641
- response.destroy();
33642
33618
  }
33619
+ return { key: legacy, source: "file" };
33620
+ }
33621
+ async function readSpeechKey() {
33622
+ return (await resolveSpeechKey())?.key;
33623
+ }
33624
+ async function speechKeyStatus(paths = {}) {
33625
+ const env = paths.env ?? process.env;
33626
+ const file2 = paths.file ?? speechKeyFile();
33627
+ const stored = await readStored(file2);
33628
+ const setup = "run `phren bridge speech-key set` and paste the key";
33629
+ if (clean(env[SPEECH_KEY_ENV])) {
33630
+ return stored.state === "ok" ? { configured: true, detail: `${SPEECH_KEY_ENV} is set and a key is stored in ${file2}` } : { configured: true, detail: `${SPEECH_KEY_ENV} is set in this shell; the Hook service doesn't see shell env, so ${setup} to store it` };
33631
+ }
33632
+ switch (stored.state) {
33633
+ case "ok":
33634
+ return { configured: true, detail: `stored in ${file2}` };
33635
+ case "unsafe":
33636
+ return { configured: false, problem: true, detail: `${file2} is readable by other users; run chmod 600 on it` };
33637
+ case "invalid":
33638
+ return { configured: false, problem: true, detail: `${file2} has no apiKey; ${setup}` };
33639
+ }
33640
+ const legacy = paths.legacy ?? legacySpeechKeyFile(env);
33641
+ if (await readLegacy(legacy)) {
33642
+ return { configured: true, detail: `not stored yet; the Hook copies it from ${legacy} on first use` };
33643
+ }
33644
+ return { configured: false, detail: `no ElevenLabs key, so spoken replies and Scribe dictation are off; ${setup}` };
33643
33645
  }
33644
33646
 
33645
33647
  // src/bridge/speech-transcribe.ts
@@ -33754,7 +33756,7 @@ function relayTranscription(client, query, options = {}) {
33754
33756
 
33755
33757
  // src/bridge/activity.ts
33756
33758
  init_protocol();
33757
- import { appendFile as appendFile3, mkdir as mkdir6, readFile as readFile8, rename as rename4, stat as stat6 } from "node:fs/promises";
33759
+ import { appendFile as appendFile3, mkdir as mkdir7, readFile as readFile8, rename as rename4, stat as stat7 } from "node:fs/promises";
33758
33760
  import path29 from "node:path";
33759
33761
  var ActivityJournal = class {
33760
33762
  pending = Promise.resolve();
@@ -33783,8 +33785,8 @@ var ActivityJournal = class {
33783
33785
  }
33784
33786
  if (!changes.length) return;
33785
33787
  const root = bridgeRoot(), file2 = path29.join(root, "activity.jsonl");
33786
- await mkdir6(root, { recursive: true, mode: 448 });
33787
- if ((await stat6(file2).catch(() => null))?.size && (await stat6(file2)).size > 2097152) await rename4(file2, file2 + ".previous");
33788
+ await mkdir7(root, { recursive: true, mode: 448 });
33789
+ if ((await stat7(file2).catch(() => null))?.size && (await stat7(file2)).size > 2097152) await rename4(file2, file2 + ".previous");
33788
33790
  await appendFile3(file2, changes.map((row) => JSON.stringify(row)).join("\n") + "\n", { mode: 384 });
33789
33791
  if (this.previous.size > 4096) this.previous.clear();
33790
33792
  });
@@ -33810,7 +33812,7 @@ init_shared();
33810
33812
  init_logger();
33811
33813
  init_protocol();
33812
33814
  import { request, createServer } from "node:http";
33813
- import { mkdir as mkdir8, readFile as readFile13, chmod, unlink as unlink3, lstat as lstat6 } from "node:fs/promises";
33815
+ import { mkdir as mkdir9, readFile as readFile13, chmod, unlink as unlink3, lstat as lstat6 } from "node:fs/promises";
33814
33816
  import { watch } from "node:fs";
33815
33817
  import path35 from "node:path";
33816
33818
  import { randomUUID as randomUUID7 } from "node:crypto";
@@ -33822,7 +33824,7 @@ import { createHmac, randomBytes as randomBytes2 } from "node:crypto";
33822
33824
  import { execFile as execFile3 } from "node:child_process";
33823
33825
  import { connect } from "node:net";
33824
33826
  import { homedir as homedir7 } from "node:os";
33825
- import { readdir as readdir6, readlink, realpath as realpath6, stat as stat7 } from "node:fs/promises";
33827
+ import { open as open5, readdir as readdir6, readlink, realpath as realpath6, stat as stat8 } from "node:fs/promises";
33826
33828
  import path32 from "node:path";
33827
33829
  import { promisify as promisify3 } from "node:util";
33828
33830
 
@@ -33914,7 +33916,7 @@ var TabActivityStore = class {
33914
33916
  await this.load();
33915
33917
  const prefix = JSON.stringify(server) + ":";
33916
33918
  const seen = /* @__PURE__ */ new Set(), times = /* @__PURE__ */ new Map();
33917
- let changed = false;
33919
+ let changed2 = false;
33918
33920
  for (const tab of objects(snapshot2.tabs)) {
33919
33921
  const tabKey = tabActivityKey(tab.workspace_id, tab.tab_id), key = prefix + tabKey;
33920
33922
  seen.add(key);
@@ -33924,17 +33926,17 @@ var TabActivityStore = class {
33924
33926
  if (stamp?.signature !== signature) {
33925
33927
  stamp = { signature, lastChangedAt: at };
33926
33928
  this.entries.set(key, stamp);
33927
- changed = true;
33929
+ changed2 = true;
33928
33930
  }
33929
33931
  times.set(tabKey, stamp.lastChangedAt);
33930
33932
  }
33931
33933
  for (const key of this.entries.keys()) {
33932
33934
  if (key.startsWith(prefix) && !seen.has(key)) {
33933
33935
  this.entries.delete(key);
33934
- changed = true;
33936
+ changed2 = true;
33935
33937
  }
33936
33938
  }
33937
- this.dirty ||= changed;
33939
+ this.dirty ||= changed2;
33938
33940
  await this.persist();
33939
33941
  return times;
33940
33942
  });
@@ -34016,7 +34018,7 @@ function noteOptionalReadFailure(what, key, error62) {
34016
34018
  async function rpc(server, method, params = {}, signal, timeoutMs = 1e4) {
34017
34019
  const socket = herdrSocket(server);
34018
34020
  countHerdr(method);
34019
- const metadata = await stat7(socket).catch((error62) => {
34021
+ const metadata = await stat8(socket).catch((error62) => {
34020
34022
  throw herdrSocketError(error62);
34021
34023
  });
34022
34024
  if (!metadata.isSocket() || process.getuid && metadata.uid !== process.getuid()) throw new BridgeError(503, "The Herdr socket is unavailable.");
@@ -34147,7 +34149,7 @@ function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged) {
34147
34149
  children: objects(s.tabs).filter((t) => t.workspace_id === w.workspace_id).map((t) => {
34148
34150
  const panes2 = objects(s.panes).filter((p) => p.tab_id === t.tab_id && p.workspace_id === t.workspace_id);
34149
34151
  const agent = panes2.find((p) => p.agent);
34150
- const changed = Math.max(0, ...panes2.map((p) => Number.isSafeInteger(p.state_change_seq) ? Number(p.state_change_seq) : 0));
34152
+ const changed2 = Math.max(0, ...panes2.map((p) => Number.isSafeInteger(p.state_change_seq) ? Number(p.state_change_seq) : 0));
34151
34153
  return {
34152
34154
  id: t.tab_id,
34153
34155
  label: t.label,
@@ -34156,7 +34158,7 @@ function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged) {
34156
34158
  agentStatus: t.agent_status,
34157
34159
  cwd: agent?.foreground_cwd || agent?.cwd,
34158
34160
  role: isConductorName(paneAgentName(s, agent)) ? "conductor" : void 0,
34159
- changedSeq: changed || void 0,
34161
+ changedSeq: changed2 || void 0,
34160
34162
  lastChangedAt: lastChanged?.get(tabActivityKey(t.workspace_id, t.tab_id)),
34161
34163
  approvalPending: panes2.some((p) => approvalPanes?.has(String(p.pane_id))) || void 0,
34162
34164
  contextUsedPercent: agent && panes2.filter((p) => p.agent).length === 1 ? contextUsedPercent?.get(agent) : void 0,
@@ -34189,7 +34191,7 @@ var identities = /* @__PURE__ */ new Map();
34189
34191
  var identityKey = (server, pane, pids) => JSON.stringify([server, pane.pane_id, pane.terminal_id, pids, pane.agent]);
34190
34192
  async function resolveIdentity(server, pane, fresh) {
34191
34193
  const reported = object2(pane.agent_session);
34192
- if (reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) {
34194
+ if (pane.agent !== "copilot" && reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) {
34193
34195
  countIdentity("reported");
34194
34196
  return { sessionId: reported.value };
34195
34197
  }
@@ -34209,7 +34211,39 @@ async function resolveIdentity(server, pane, fresh) {
34209
34211
  async function paneIdentity(server, pane, fresh = false) {
34210
34212
  return (await resolveIdentity(server, pane, fresh)).sessionId;
34211
34213
  }
34214
+ var copilotHome = () => process.env.COPILOT_HOME || path32.join(homedir7(), ".copilot");
34215
+ async function copilotForegroundSession(pids, home = copilotHome()) {
34216
+ if (!pids.length) return void 0;
34217
+ const folder = path32.join(home, "logs");
34218
+ const names = await readdir6(folder).catch(() => []);
34219
+ const logs = names.filter((name) => pids.some((pid) => name.startsWith("process-") && name.endsWith(`-${pid}.log`)));
34220
+ let current, latest = -1;
34221
+ for (const name of logs) {
34222
+ const file2 = await open5(path32.join(folder, name), "r").catch(() => void 0);
34223
+ if (!file2) continue;
34224
+ try {
34225
+ const { size } = await file2.stat(), length = Math.min(size, 262144);
34226
+ const { buffer, bytesRead } = await file2.read(Buffer.alloc(length), 0, length, size - length);
34227
+ const lines = [...buffer.subarray(0, bytesRead).toString("utf8").matchAll(/^(\S+) \[INFO\] (Registering|Unregistering) foreground session: ([0-9a-f-]{36})\s*$/gim)];
34228
+ const last = lines.at(-1);
34229
+ if (!last) continue;
34230
+ const at = Date.parse(last[1]);
34231
+ if (at <= latest) continue;
34232
+ latest = at;
34233
+ current = last[2] === "Registering" && sessionId.safeParse(last[3]).success ? last[3] : void 0;
34234
+ } finally {
34235
+ await file2.close();
34236
+ }
34237
+ }
34238
+ return current;
34239
+ }
34212
34240
  async function identityFromProcesses(server, pane, pids) {
34241
+ if (pane.agent === "copilot") {
34242
+ const current = await copilotForegroundSession(pids).catch(() => void 0);
34243
+ if (current) return await stat8(path32.join(copilotHome(), "session-state", current, "events.jsonl")).then(() => ({ sessionId: current, noTranscriptLogs: false }), () => ({ noTranscriptLogs: true }));
34244
+ const reported = object2(pane.agent_session);
34245
+ if (reported.kind === "id" && reported.agent === "copilot" && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) return { sessionId: reported.value, noTranscriptLogs: false };
34246
+ }
34213
34247
  const files = await processLogs(pids);
34214
34248
  const candidates = files.flatMap((file2) => {
34215
34249
  const match = pane.agent === "codex" ? /rollout-.*-([a-f0-9-]{36})\.jsonl$/i.exec(file2) ?? /thread-writer-locks\/([a-f0-9-]{36})\.lock$/i.exec(file2) : pane.agent === "claude" ? /\/([a-f0-9-]{36})\.jsonl$/i.exec(file2) : pane.agent === "phren" ? /\/session-([a-f0-9-]{36})\.events\.jsonl$/i.exec(file2) : /\/session-state\/([a-f0-9-]{36})\/events\.jsonl$/i.exec(file2);
@@ -34320,7 +34354,7 @@ init_locks();
34320
34354
  init_js_yaml();
34321
34355
  init_zod();
34322
34356
  init_protocol();
34323
- import { lstat as lstat5, mkdir as mkdir7, readFile as readFile11 } from "node:fs/promises";
34357
+ import { lstat as lstat5, mkdir as mkdir8, readFile as readFile11 } from "node:fs/promises";
34324
34358
  import path33 from "node:path";
34325
34359
  var grantAction = external_exports.enum(["dispatch", "hand_off"]);
34326
34360
  var grantScope = external_exports.union([
@@ -34370,7 +34404,7 @@ async function listGrants(root = bridgeRoot()) {
34370
34404
  }
34371
34405
  async function writeGrants(root, grants) {
34372
34406
  const file2 = grantFile(root);
34373
- await mkdir7(root, { recursive: true, mode: 448 });
34407
+ await mkdir8(root, { recursive: true, mode: 448 });
34374
34408
  await atomic(file2, dump({ grants }, { lineWidth: 120 }));
34375
34409
  }
34376
34410
  function specificity(grant) {
@@ -34472,17 +34506,28 @@ async function removeGrant(input2, root = bridgeRoot()) {
34472
34506
  // src/bridge/push.ts
34473
34507
  init_zod();
34474
34508
  init_protocol();
34475
- import { createPrivateKey, sign } from "node:crypto";
34476
- import { readFile as readFile12, stat as stat8 } from "node:fs/promises";
34509
+ import { createCipheriv, createHmac as createHmac2, createPrivateKey, randomBytes as randomBytes3, sign } from "node:crypto";
34510
+ import { readFile as readFile12, stat as stat9 } from "node:fs/promises";
34477
34511
  import { connect as connect2 } from "node:http2";
34478
34512
  import path34 from "node:path";
34513
+ var relaySchema = external_exports.object({
34514
+ url: external_exports.string().url().refine(
34515
+ (value2) => /^https:\/\//.test(value2) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${value2}/`),
34516
+ "The relay must use https."
34517
+ ),
34518
+ relayId: external_exports.string().regex(/^[A-Za-z0-9_-]{40,400}$/),
34519
+ secret: external_exports.string().regex(/^[A-Za-z0-9_-]{20,100}$/),
34520
+ key: external_exports.string().regex(/^[A-Za-z0-9_-]{43}$/)
34521
+ });
34479
34522
  var deviceSchema = external_exports.object({
34480
34523
  deviceID: external_exports.string().uuid(),
34481
34524
  hostID: external_exports.string().uuid(),
34482
- token: external_exports.string().regex(/^[0-9a-f]{64}$/),
34525
+ /** The APNs token, for a Hook with its own key (apns.json). */
34526
+ token: external_exports.string().regex(/^[0-9a-f]{64}$/).optional(),
34527
+ relay: relaySchema.optional(),
34483
34528
  environment: external_exports.enum(["development", "production"]),
34484
34529
  kinds: external_exports.array(external_exports.enum(["approval", "scheduleStarted", "scheduleFinished", "scheduleFailed", "scheduleBlocked"])).max(5).default(["approval"])
34485
- });
34530
+ }).refine((device) => device.token !== void 0 || device.relay !== void 0, "A phone needs an APNs token or a relay registration.");
34486
34531
  var configSchema2 = external_exports.object({
34487
34532
  keyId: external_exports.string().regex(/^[A-Z0-9]{10}$/),
34488
34533
  teamId: external_exports.string().regex(/^[A-Z0-9]{10}$/),
@@ -34536,7 +34581,7 @@ function schedulePushPayload(value2) {
34536
34581
  }
34537
34582
  async function secureJSON(file2, schema) {
34538
34583
  try {
34539
- const metadata = await stat8(file2);
34584
+ const metadata = await stat9(file2);
34540
34585
  if ((metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
34541
34586
  return schema.parse(JSON.parse(await readFile12(file2, "utf8")));
34542
34587
  } catch {
@@ -34545,7 +34590,7 @@ async function secureJSON(file2, schema) {
34545
34590
  }
34546
34591
  async function secureFile(file2) {
34547
34592
  try {
34548
- const metadata = await stat8(file2);
34593
+ const metadata = await stat9(file2);
34549
34594
  if (!metadata.isFile() || (metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
34550
34595
  return await readFile12(file2, "utf8");
34551
34596
  } catch {
@@ -34562,13 +34607,62 @@ function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path34.joi
34562
34607
  ].join("\n");
34563
34608
  }
34564
34609
  function approvalPushCapability(status) {
34565
- return status.configured ? "direct-apns" : void 0;
34610
+ if (!status.configured) return void 0;
34611
+ return status.direct === false ? "relay" : "direct-apns";
34566
34612
  }
34567
34613
  function upsertPushDevice(devices, value2) {
34568
34614
  const device = deviceSchema.parse(value2);
34569
34615
  return [...devices.filter((item) => item.deviceID !== device.deviceID), device].slice(-16);
34570
34616
  }
34571
34617
  var base64url3 = (value2) => Buffer.from(value2).toString("base64url");
34618
+ var RELAY_MAX_CIPHERTEXT = 2800;
34619
+ function relayCiphertext(key, payload, nonce = randomBytes3(12)) {
34620
+ const aps = payload.aps ?? {};
34621
+ let body2 = aps.alert?.body ?? "";
34622
+ for (; ; ) {
34623
+ const content = JSON.stringify({
34624
+ t: aps.alert?.title ?? "phren",
34625
+ b: body2,
34626
+ ...aps.category ? { c: aps.category } : {},
34627
+ ...aps["interruption-level"] ? { i: aps["interruption-level"] } : {},
34628
+ ...payload.phren ? { p: payload.phren } : {}
34629
+ });
34630
+ const cipher = createCipheriv("chacha20-poly1305", Buffer.from(key, "base64url"), nonce, { authTagLength: 16 });
34631
+ const sealed = Buffer.concat([nonce, cipher.update(content, "utf8"), cipher.final(), cipher.getAuthTag()]).toString("base64url");
34632
+ if (sealed.length <= RELAY_MAX_CIPHERTEXT || !body2) return sealed;
34633
+ body2 = body2.length > 40 ? `${body2.slice(0, Math.floor(body2.length * 0.8))}\u2026` : "";
34634
+ }
34635
+ }
34636
+ function relaySignature(secret, timestamp4, body2) {
34637
+ return createHmac2("sha256", secret).update(`${timestamp4}.${body2}`).digest("base64url");
34638
+ }
34639
+ async function sendThroughRelay(relay2, payload, headers, fetcher = fetch, now = Date.now) {
34640
+ const aps = payload.aps ?? {};
34641
+ const body2 = JSON.stringify({
34642
+ kind: "alert",
34643
+ ciphertext: relayCiphertext(relay2.key, payload),
34644
+ collapseId: headers.collapseId.slice(0, 64),
34645
+ expiration: Number(headers.expiration) || 0,
34646
+ ...aps.category ? { category: aps.category } : {}
34647
+ });
34648
+ const timestamp4 = String(Math.floor(now() / 1e3));
34649
+ try {
34650
+ const response = await fetcher(`${relay2.url.replace(/\/+$/, "")}/v1/send`, {
34651
+ method: "POST",
34652
+ body: body2,
34653
+ signal: AbortSignal.timeout(1e4),
34654
+ headers: {
34655
+ "content-type": "application/json",
34656
+ "x-phren-relay": relay2.relayId,
34657
+ "x-phren-timestamp": timestamp4,
34658
+ "x-phren-signature": relaySignature(relay2.secret, timestamp4, body2)
34659
+ }
34660
+ });
34661
+ return response.status === 410 ? "gone" : response.ok ? "sent" : "failed";
34662
+ } catch {
34663
+ return "failed";
34664
+ }
34665
+ }
34572
34666
  var APNsSender = class {
34573
34667
  constructor(config3, key, now = Date.now) {
34574
34668
  this.config = config3;
@@ -34635,21 +34729,44 @@ var ApprovalPushService = class {
34635
34729
  const key = await secureFile(keyPath);
34636
34730
  if (key) this.sender = new APNsSender(config3, key);
34637
34731
  }
34732
+ /** Phones this Hook can reach: through the relay, or direct with its own key. */
34733
+ get reachable() {
34734
+ return this.devices.filter((device) => device.relay || this.sender && device.token);
34735
+ }
34638
34736
  get available() {
34639
- return this.sender !== void 0 && this.devices.length > 0;
34737
+ return this.reachable.length > 0;
34640
34738
  }
34641
34739
  get status() {
34642
- return { supported: true, configured: this.sender !== void 0, devices: this.devices.length };
34740
+ const relay2 = this.devices.filter((device) => device.relay).length;
34741
+ return {
34742
+ supported: true,
34743
+ configured: this.sender !== void 0 || relay2 > 0,
34744
+ direct: this.sender !== void 0,
34745
+ devices: this.devices.length,
34746
+ relay: relay2
34747
+ };
34643
34748
  }
34644
34749
  async register(value2) {
34645
34750
  this.devices = upsertPushDevice(this.devices, value2);
34646
34751
  await atomic(this.devicesFile, JSON.stringify(this.devices));
34647
34752
  }
34753
+ /** One phone: the relay when it registered through one, otherwise direct. */
34754
+ async send(device, payload, headers) {
34755
+ if (device.relay) {
34756
+ const result = await sendThroughRelay(device.relay, payload, headers);
34757
+ if (result === "gone") {
34758
+ this.devices = this.devices.filter((item) => item.deviceID !== device.deviceID);
34759
+ await atomic(this.devicesFile, JSON.stringify(this.devices)).catch(() => {
34760
+ });
34761
+ }
34762
+ return result === "sent";
34763
+ }
34764
+ return this.sender && device.token ? this.sender.send(device, payload, headers) : false;
34765
+ }
34648
34766
  async notify(value2) {
34649
- if (!this.sender || !this.devices.length) return false;
34650
- const devices = this.devices.filter((device) => device.kinds.includes("approval"));
34767
+ const devices = this.reachable.filter((device) => device.kinds.includes("approval"));
34651
34768
  if (!devices.length) return false;
34652
- return (await Promise.all(devices.map((device) => this.sender.send(device, approvalPushPayload(value2, device.hostID), {
34769
+ return (await Promise.all(devices.map((device) => this.send(device, approvalPushPayload(value2, device.hostID), {
34653
34770
  expiration: String(Math.floor(Date.parse(value2.expiresAt) / 1e3)),
34654
34771
  collapseId: value2.binding
34655
34772
  })))).some(Boolean);
@@ -34658,21 +34775,21 @@ var ApprovalPushService = class {
34658
34775
  * phones already accept agent alerts; the payload carries the reason so the
34659
34776
  * notification is actionable on its own. */
34660
34777
  async notifyFanoutBlocked(value2) {
34661
- if (!this.sender || !this.devices.length) return false;
34662
- const devices = this.devices.filter((device) => device.kinds.includes("approval"));
34778
+ const devices = this.reachable.filter((device) => device.kinds.includes("approval"));
34663
34779
  if (!devices.length) return false;
34664
- return (await Promise.all(devices.map((device) => this.sender.send(device, fanoutBlockedPushPayload(value2), {
34780
+ return (await Promise.all(devices.map((device) => this.send(device, fanoutBlockedPushPayload(value2), {
34665
34781
  expiration: "0",
34666
34782
  collapseId: `fanout-${value2.job}`
34667
34783
  })))).some(Boolean);
34668
34784
  }
34669
34785
  async notifySchedule(value2) {
34670
- if (!this.sender) return { notified: false, reason: "no push config" };
34671
- let devices = this.devices.filter((device) => device.kinds.includes(value2.kind));
34672
- if (!devices.length && value2.kind === "scheduleBlocked") devices = this.devices.filter((device) => device.kinds.includes("scheduleFailed"));
34786
+ const reachable = this.reachable;
34787
+ if (!reachable.length) return { notified: false, reason: this.sender || this.devices.length ? "no registered devices" : "no push config" };
34788
+ let devices = reachable.filter((device) => device.kinds.includes(value2.kind));
34789
+ if (!devices.length && value2.kind === "scheduleBlocked") devices = reachable.filter((device) => device.kinds.includes("scheduleFailed"));
34673
34790
  if (!devices.length) return { notified: false, reason: "no registered devices" };
34674
34791
  try {
34675
- const notified = (await Promise.all(devices.map((device) => this.sender.send(device, schedulePushPayload(value2), {
34792
+ const notified = (await Promise.all(devices.map((device) => this.send(device, schedulePushPayload(value2), {
34676
34793
  expiration: "0",
34677
34794
  collapseId: scheduleCollapseId(value2.kind, value2.runId)
34678
34795
  })))).some(Boolean);
@@ -34686,6 +34803,161 @@ var ApprovalPushService = class {
34686
34803
  // src/bridge/agent-hooks.ts
34687
34804
  init_limits();
34688
34805
 
34806
+ // src/bridge/claude-question-dialog.ts
34807
+ init_protocol();
34808
+ var TAB_BAR = /^\s*(?:←\s+)?((?:[☐☒]\s+\S[^☐☒✔→]*?\s*)+)(?:✔\s+Submit\s*)?(?:→\s*)?$/;
34809
+ var ROW = /^\s*(❯)?\s*(\d)\.\s+(?:\[([ ✔])\]\s+)?(.*?)\s*$/;
34810
+ var NEXT = /^\s*(❯)?\s+(?:Next|Submit)\s*$/;
34811
+ var normalize = (text3) => text3.replace(/\s+/g, " ").trim();
34812
+ function claudeQuestionDialog(text3) {
34813
+ const lines = text3.split(/\r?\n/);
34814
+ let bar = -1;
34815
+ for (let index2 = lines.length - 1; index2 >= 0; index2--) if (TAB_BAR.test(lines[index2]) && /[☐☒]/.test(lines[index2])) {
34816
+ bar = index2;
34817
+ break;
34818
+ }
34819
+ if (bar < 0) return void 0;
34820
+ const tabs = [...lines[bar].matchAll(/[☐☒]\s+([^☐☒✔→]+?)(?=\s{2,}|\s*[☐☒✔→]|\s*$)/g)].map((match) => match[1].trim());
34821
+ const body2 = lines.slice(bar + 1);
34822
+ const content = body2.map((line) => line.trim()).filter((line) => line && !/^─+$/.test(line));
34823
+ if (content[0] === "Review your answers") {
34824
+ if (!body2.some((line) => /^\s*❯?\s*1\.\s+Submit answers\s*$/.test(line))) return void 0;
34825
+ const answers = [];
34826
+ for (const line of content.slice(1)) {
34827
+ if (/^Ready to submit/.test(line)) break;
34828
+ const question2 = /^●\s+(.+)$/.exec(line), answer = /^→\s+(.+)$/.exec(line), last = answers[answers.length - 1];
34829
+ if (question2) answers.push({ question: question2[1], answer: "" });
34830
+ else if (answer && last) last.answer = answer[1];
34831
+ else if (last) {
34832
+ if (last.answer) last.answer += " " + line;
34833
+ else last.question += " " + line;
34834
+ }
34835
+ }
34836
+ return { kind: "review", tabs, answers };
34837
+ }
34838
+ if (!content.some((line) => /Esc to cancel/.test(line))) return void 0;
34839
+ const first = body2.findIndex((line) => ROW.test(line));
34840
+ if (first < 0) return void 0;
34841
+ const title = normalize(body2.slice(0, first).filter((line) => line.trim()).join(" "));
34842
+ const rows = [];
34843
+ let cursor, chat = false;
34844
+ for (const line of body2.slice(first)) {
34845
+ const next = NEXT.exec(line);
34846
+ if (next) {
34847
+ if (next[1]) cursor = "next";
34848
+ continue;
34849
+ }
34850
+ const match = ROW.exec(line);
34851
+ if (!match) continue;
34852
+ const number4 = Number(match[2]);
34853
+ if (match[1]) cursor = number4;
34854
+ if (/^Chat about this$/.test(match[4])) {
34855
+ chat = true;
34856
+ continue;
34857
+ }
34858
+ const answered = !match[3] && / ✔$/.test(match[4]);
34859
+ rows.push({
34860
+ number: number4,
34861
+ label: answered ? match[4].slice(0, -2).trim() : match[4],
34862
+ answered,
34863
+ cursor: !!match[1],
34864
+ ...match[3] ? { checked: match[3] === "\u2714" } : {}
34865
+ });
34866
+ }
34867
+ if (!title || !chat || rows.length < 2) return void 0;
34868
+ const other = rows.pop();
34869
+ return { kind: "question", tabs, title, multiSelect: rows.some((row) => row.checked !== void 0), options: rows, other, ...cursor !== void 0 ? { cursor } : {} };
34870
+ }
34871
+ var changed = (message) => new BridgeError(409, `${message} Nothing else was sent; check the question and answer again, or cancel it.`);
34872
+ var typedKeys = (text3) => [...text3].map((character) => character === " " ? "space" : character);
34873
+ async function answerClaudeQuestionDialog(io, questions, answers, options = {}) {
34874
+ const from = options.from ?? 0, submit = options.submit ?? true;
34875
+ const sleep3 = io.sleep ?? ((ms) => new Promise((resolve11) => setTimeout(resolve11, ms)));
34876
+ const matches = (screen, index2) => screen?.kind === "question" && screen.title === normalize(questions[index2].question);
34877
+ const settle2 = async (check2, ms = 2e3) => {
34878
+ for (let waited = 0; ; waited += 120) {
34879
+ const value2 = check2(claudeQuestionDialog(await io.read()));
34880
+ if (value2 !== void 0 || waited >= ms) return value2;
34881
+ await sleep3(120);
34882
+ }
34883
+ };
34884
+ const initial = await settle2((screen) => screen);
34885
+ if (!initial) throw changed("The terminal is not showing Claude's question.");
34886
+ if (initial.tabs.length !== questions.length) throw changed("The terminal is asking a different set of questions.");
34887
+ const reach = async (index2) => {
34888
+ const screen = await settle2((value2) => value2);
34889
+ if (screen?.kind === "question" && screen.title === normalize(questions[index2].question)) return screen;
34890
+ const at = screen?.kind === "review" ? questions.length : screen?.kind === "question" ? questions.findIndex((question2) => normalize(question2.question) === screen.title) : -1;
34891
+ if (at < 0) throw changed("The terminal is showing a different question.");
34892
+ if (screen?.kind === "question" && screen.other && screen.cursor === screen.other.number) await io.keys(["up"]);
34893
+ await io.keys(Array(Math.abs(index2 - at)).fill(index2 > at ? "right" : "left"));
34894
+ const moved = await settle2((value2) => matches(value2, index2) ? value2 : void 0);
34895
+ if (!moved) throw changed("Could not move the terminal to the question being answered.");
34896
+ return moved;
34897
+ };
34898
+ const leaves = (index2) => (value2) => value2 === void 0 ? "gone" : !matches(value2, index2) ? "moved" : void 0;
34899
+ for (const [offset, answer] of answers.entries()) {
34900
+ const index2 = from + offset, question2 = questions[index2];
34901
+ if (!question2) throw new BridgeError(400, "The answer names a question that was not asked.");
34902
+ const typed = answer.text?.trim() ?? "";
34903
+ let screen = await reach(index2);
34904
+ if (screen.multiSelect !== !!question2.multiSelect || screen.options.length !== question2.options.length || screen.options.some((row, position) => row.label !== question2.options[position].label.trim())) {
34905
+ throw changed("The terminal's options differ from the question being answered.");
34906
+ }
34907
+ if (!screen.multiSelect) {
34908
+ if (typed) {
34909
+ const other = screen.other;
34910
+ await io.keys([String(other.number)]);
34911
+ const focused = await settle2((value2) => matches(value2, index2) && value2.cursor === other.number ? value2 : void 0);
34912
+ if (!focused) throw changed("Could not open the typed answer.");
34913
+ await io.keys(typedKeys(typed));
34914
+ const shown = await settle2((value2) => matches(value2, index2) && value2.other && normalize(value2.other.label).startsWith(normalize(typed).slice(0, 20)) ? value2 : void 0);
34915
+ if (!shown) throw changed("The typed answer did not appear in the terminal.");
34916
+ await io.keys(["enter"]);
34917
+ } else {
34918
+ await io.keys([String(screen.options[answer.options[0]].number)]);
34919
+ }
34920
+ if (!await settle2(leaves(index2))) throw changed("The terminal did not take the answer.");
34921
+ continue;
34922
+ }
34923
+ const rows = [...screen.options, ...screen.other ? [screen.other] : []];
34924
+ for (const [position, row] of rows.entries()) {
34925
+ const wanted = position < screen.options.length ? answer.options.includes(position) : !!row.checked && !!typed;
34926
+ if (wanted === !!row.checked) continue;
34927
+ const box = (value2) => matches(value2, index2) ? !!(position < value2.options.length ? value2.options[position] : value2.other)?.checked : void 0;
34928
+ for (let attempt = 0; attempt < 2 && box(screen) !== wanted; attempt++) {
34929
+ await io.keys([String(row.number)]);
34930
+ screen = await settle2((value2) => box(value2) === wanted ? value2 : void 0, 1e3) ?? screen;
34931
+ }
34932
+ if (box(screen) !== wanted) throw changed("The terminal's checkboxes did not match the answer.");
34933
+ }
34934
+ if (typed) {
34935
+ const other = screen.other, cursor = typeof screen.cursor === "number" ? screen.cursor : 1;
34936
+ if (cursor !== other.number) await io.keys(Array(Math.abs(other.number - cursor)).fill(other.number > cursor ? "down" : "up"));
34937
+ if (!await settle2((value2) => matches(value2, index2) && value2.cursor === other.number ? value2 : void 0)) throw changed("Could not reach the typed answer row.");
34938
+ await io.keys(typedKeys(typed));
34939
+ const shown = await settle2((value2) => matches(value2, index2) && value2.other?.checked && normalize(value2.other.label).startsWith(normalize(typed).slice(0, 20)) ? value2 : void 0);
34940
+ if (!shown) throw changed("The typed answer did not appear in the terminal.");
34941
+ await io.keys(["tab"]);
34942
+ if (!await settle2((value2) => matches(value2, index2) && value2.cursor === "next" ? value2 : void 0)) throw changed("Could not reach the question's Next row.");
34943
+ await io.keys(["enter"]);
34944
+ } else {
34945
+ await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
34946
+ }
34947
+ if (!await settle2(leaves(index2))) throw changed("The terminal did not move past the question.");
34948
+ }
34949
+ if (!submit) return;
34950
+ const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0);
34951
+ if (review === "gone") return;
34952
+ if (!review) throw changed("The terminal did not reach the review of the answers.");
34953
+ const expected = questions.map((question2) => normalize(question2.question));
34954
+ if (review.answers.length !== questions.length || review.answers.some((row, position) => normalize(row.question) !== expected[position] || !row.answer)) {
34955
+ throw changed("Not every question has an answer in the terminal.");
34956
+ }
34957
+ await io.keys(["1"]);
34958
+ if (await settle2((value2) => value2 === void 0 ? "gone" : void 0) !== "gone") throw changed("The terminal did not submit the answers.");
34959
+ }
34960
+
34689
34961
  // src/bridge/terminal-choice.ts
34690
34962
  init_zod();
34691
34963
  init_protocol();
@@ -35284,14 +35556,13 @@ var AgentHooks = class {
35284
35556
  }
35285
35557
  return;
35286
35558
  }
35287
- if (entry?.questions?.length) {
35288
- if (!active) {
35289
- this.terminalPrompts.delete(key);
35290
- this.passwords.delete(key);
35291
- }
35559
+ const question2 = !!entry?.questions?.length;
35560
+ if (question2 && !active) {
35561
+ this.terminalPrompts.delete(key);
35562
+ this.passwords.delete(key);
35292
35563
  return;
35293
35564
  }
35294
- if (entry && !entry.dialog && entry.choice && !entry.released) return;
35565
+ if (!question2 && entry && !entry.dialog && entry.choice && !entry.released) return;
35295
35566
  if (!active) {
35296
35567
  if (entry) this.terminalPrompts.delete(key);
35297
35568
  this.passwords.delete(key);
@@ -35304,6 +35575,14 @@ var AgentHooks = class {
35304
35575
  const text3 = await this.paneLines(target);
35305
35576
  this.passwords.set(key, passwordLine(text3));
35306
35577
  while (this.passwords.size > 128) this.passwords.delete(this.passwords.keys().next().value);
35578
+ if (target.source === "claude" && claudeQuestionDialog(text3)) {
35579
+ if (entry && !question2) this.terminalPrompts.delete(key);
35580
+ return;
35581
+ }
35582
+ if (question2) {
35583
+ this.terminalPrompts.delete(key);
35584
+ return;
35585
+ }
35307
35586
  const dialog = target.source === "codex" ? visibleTerminalChoice(text3) : numberedDialog(text3);
35308
35587
  if (entry && !entry.dialog) {
35309
35588
  if (dialog?.title) {
@@ -35363,24 +35642,40 @@ var AgentHooks = class {
35363
35642
  }
35364
35643
  throw new BridgeError(409, "Could not move and verify the terminal selection. Open terminal to choose this option.");
35365
35644
  }
35366
- /** Answer one question of a released AskUserQuestion with the option's own
35367
- * digit: send the chosen digit(s), then Tab to advance to the next
35368
- * question or Enter after the last. The stored question index moves with
35369
- * them and a finished set is cleared. Undefined when the prompt is not a
35370
- * question, so an ordinary key falls through to the usual handling. */
35371
- questionAnswerKeys(target, keys) {
35645
+ /** Answer Claude's AskUserQuestion dialog in the pane: every question in
35646
+ * `answers` from `from` on, then the set's submission when `submit`. The
35647
+ * walk reads the pane before and after each key, so a dialog on another
35648
+ * tab, a changed question or a missed key stops it with nothing stray
35649
+ * typed. A finished set clears the remembered question. */
35650
+ async answerClaudeQuestions(target, questions, answers, options = {}) {
35651
+ const key = JSON.stringify(target);
35652
+ await answerClaudeQuestionDialog({
35653
+ read: () => this.paneLines(target),
35654
+ keys: async (keys) => {
35655
+ if (!keys.length) return;
35656
+ await validateTarget(target, false, true);
35657
+ await rpc(target.server, "agent.send_keys", { target: target.pane, keys });
35658
+ }
35659
+ }, questions, answers, options);
35660
+ this.dialogReads.delete(key);
35661
+ if (options.submit ?? true) this.terminalPrompts.delete(key);
35662
+ }
35663
+ /** An older phone answers a released AskUserQuestion one question at a
35664
+ * time with the chosen digits through `/v1/keys`. Walk that question with
35665
+ * the same verified steps and submit after the last. False when the
35666
+ * prompt is not a remembered question, so the keys take the usual path. */
35667
+ async answerReleasedQuestion(target, keys) {
35372
35668
  const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
35373
- if (!entry?.questions?.length) return void 0;
35669
+ if (target.source !== "claude" || !entry?.questions?.length) return false;
35374
35670
  const digits = keys.filter((value2) => /^[1-9]$/.test(value2));
35375
- if (!digits.length) return void 0;
35376
- const index2 = Math.min(entry.questionIndex ?? 0, entry.questions.length - 1), next = index2 + 1;
35377
- if (next >= entry.questions.length) {
35378
- this.terminalPrompts.delete(key);
35379
- return [...digits, "Enter"];
35671
+ if (!digits.length) return false;
35672
+ const index2 = Math.min(entry.questionIndex ?? 0, entry.questions.length - 1), last = index2 + 1 >= entry.questions.length;
35673
+ await this.answerClaudeQuestions(target, entry.questions, [{ options: digits.map((digit) => Number(digit) - 1) }], { from: index2, submit: last });
35674
+ if (!last) {
35675
+ entry.questionIndex = index2 + 1;
35676
+ entry.choice = questionChoice(entry.questions, index2 + 1);
35380
35677
  }
35381
- entry.questionIndex = next;
35382
- entry.choice = questionChoice(entry.questions, next);
35383
- return [...digits, "Tab"];
35678
+ return true;
35384
35679
  }
35385
35680
  startCompacting(target) {
35386
35681
  this.compactingSince.set(JSON.stringify(target), Date.now());
@@ -35586,6 +35881,25 @@ var AgentHooks = class {
35586
35881
  if (!entry.response.destroyed) entry.response.end("{}");
35587
35882
  }
35588
35883
  }
35884
+ /** The phone's Esc or Cancel on a question the Hook holds. A held
35885
+ * AskUserQuestion has no terminal choice, so `releaseChoice` never lets it
35886
+ * go and the terminal stays frozen until the hold timer; decline it now so
35887
+ * Claude moves on. True when a held question was cancelled. */
35888
+ cancelHeldQuestion(target) {
35889
+ let cancelled = false;
35890
+ for (const [id2, entry] of this.pending) {
35891
+ if (entry.tool !== "AskUserQuestion" || JSON.stringify(entry.target) !== JSON.stringify(target)) continue;
35892
+ this.pending.delete(id2);
35893
+ this.dropPushBindings(id2);
35894
+ clearTimeout(entry.timer);
35895
+ if (!entry.response.destroyed) entry.response.end(JSON.stringify({ hookSpecificOutput: {
35896
+ hookEventName: "PermissionRequest",
35897
+ decision: { behavior: "deny", message: "The user cancelled this question in Phren without answering." }
35898
+ } }));
35899
+ cancelled = true;
35900
+ }
35901
+ return cancelled;
35902
+ }
35589
35903
  async answerPush(binding, decision) {
35590
35904
  if (!["approve", "deny"].includes(String(decision))) throw new BridgeError(400, "The approval answer is not valid.");
35591
35905
  const linked = this.pushBindings.consume(binding);
@@ -35868,7 +36182,7 @@ var AgentHooks = class {
35868
36182
  this.server.listen(localSocket(), () => resolve11());
35869
36183
  });
35870
36184
  await chmod(localSocket(), 384);
35871
- await mkdir8(this.approvalsDirectory(), { recursive: true, mode: 448 }).catch(() => {
36185
+ await mkdir9(this.approvalsDirectory(), { recursive: true, mode: 448 }).catch(() => {
35872
36186
  });
35873
36187
  try {
35874
36188
  this.opencodeWatcher = watch(this.approvalsDirectory(), { persistent: false }, () => this.scheduleOpencodeSweep());
@@ -35999,13 +36313,13 @@ import { execFile as execFile4 } from "node:child_process";
35999
36313
  import { promisify as promisify4 } from "node:util";
36000
36314
  import { request as request2 } from "node:http";
36001
36315
  import { userInfo } from "node:os";
36002
- import { readFile as readFile15, realpath as realpath7, stat as stat10 } from "node:fs/promises";
36316
+ import { readFile as readFile15, realpath as realpath7, stat as stat11 } from "node:fs/promises";
36003
36317
  import path37 from "node:path";
36004
36318
 
36005
36319
  // src/bridge/locate.ts
36006
36320
  init_protocol();
36007
36321
  import { realpathSync as realpathSync3 } from "node:fs";
36008
- import { readFile as readFile14, stat as stat9 } from "node:fs/promises";
36322
+ import { readFile as readFile14, stat as stat10 } from "node:fs/promises";
36009
36323
  import { homedir as homedir8 } from "node:os";
36010
36324
  import path36 from "node:path";
36011
36325
  init_transcripts();
@@ -36018,7 +36332,7 @@ async function locateProject(project, activity, env = process.env) {
36018
36332
  const offer = async (directory, source, lastSeen) => {
36019
36333
  let dir = path36.resolve(directory);
36020
36334
  try {
36021
- if (!(await stat9(dir)).isDirectory()) return;
36335
+ if (!(await stat10(dir)).isDirectory()) return;
36022
36336
  dir = realpathSync3.native(dir);
36023
36337
  } catch {
36024
36338
  return;
@@ -36113,7 +36427,7 @@ async function resolveTouched(raw, cwd) {
36113
36427
  const home = homeDir();
36114
36428
  const absolute = raw === "~" || raw.startsWith("~/") ? path37.join(home, raw.slice(1)) : path37.resolve(cwd, raw);
36115
36429
  let existing = absolute, rest = [];
36116
- while (!await stat10(existing).catch(() => void 0)) {
36430
+ while (!await stat11(existing).catch(() => void 0)) {
36117
36431
  const parent = path37.dirname(existing);
36118
36432
  if (parent === existing) return void 0;
36119
36433
  rest.unshift(path37.basename(existing));
@@ -36136,7 +36450,7 @@ async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
36136
36450
  const files = await statusFiles(root);
36137
36451
  const byRoot = /* @__PURE__ */ new Map();
36138
36452
  for (const file2 of requested) {
36139
- const owner = await gitRoot((await stat10(file2).catch(() => void 0))?.isDirectory() ? file2 : path37.dirname(file2));
36453
+ const owner = await gitRoot((await stat11(file2).catch(() => void 0))?.isDirectory() ? file2 : path37.dirname(file2));
36140
36454
  if (!owner) continue;
36141
36455
  const rel = (path37.relative(owner, file2) || ".").split(path37.sep).join("/");
36142
36456
  if (rel.startsWith(":")) throw new BridgeError(400, "Invalid diff pathspec.");
@@ -36165,7 +36479,7 @@ async function headFile(cwd) {
36165
36479
  let directory = cwd;
36166
36480
  for (let depth = 0; depth < 64; depth++) {
36167
36481
  const dotGit = path37.join(directory, ".git");
36168
- const info = await stat10(dotGit).catch(() => void 0);
36482
+ const info = await stat11(dotGit).catch(() => void 0);
36169
36483
  if (info?.isDirectory()) return path37.join(dotGit, "HEAD");
36170
36484
  if (info?.isFile()) {
36171
36485
  const match = /^gitdir:\s*(.+)$/m.exec(await readFile15(dotGit, "utf8").catch(() => ""));
@@ -36314,7 +36628,7 @@ async function launchDirectory(raw, activity = [], located = []) {
36314
36628
  let dir;
36315
36629
  try {
36316
36630
  dir = await realpath7(raw);
36317
- if (!(await stat10(dir)).isDirectory()) throw new Error();
36631
+ if (!(await stat11(dir)).isDirectory()) throw new Error();
36318
36632
  } catch {
36319
36633
  throw new BridgeError(400, "Workspace directory does not exist.");
36320
36634
  }
@@ -36629,7 +36943,7 @@ var CodeRoutes = class {
36629
36943
  const project = projectSchema.parse(projectValue ?? "");
36630
36944
  const { codeDatabasePath } = await requireCodePackage(this.store);
36631
36945
  const file2 = codeDatabasePath(this.store, project);
36632
- await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path79) => rm4(path79, { force: true })));
36946
+ await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path81) => rm4(path81, { force: true })));
36633
36947
  return { project, disabled: true };
36634
36948
  }
36635
36949
  async reindex(projectValue) {
@@ -36793,7 +37107,7 @@ function readHead(root) {
36793
37107
  }
36794
37108
 
36795
37109
  // src/bridge/context.ts
36796
- import { open as open5 } from "node:fs/promises";
37110
+ import { open as open6 } from "node:fs/promises";
36797
37111
  import { constants } from "node:fs";
36798
37112
  init_protocol();
36799
37113
  init_transcripts();
@@ -36828,15 +37142,15 @@ function codexContext(tail, startsAtBeginning) {
36828
37142
  var ContextUsageReader = class {
36829
37143
  cache = /* @__PURE__ */ new Map();
36830
37144
  async read(file2, session) {
36831
- const handle = await open5(file2, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
37145
+ const handle = await open6(file2, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
36832
37146
  try {
36833
37147
  const metadata = await handle.stat();
36834
37148
  if (!metadata.isFile()) return void 0;
36835
37149
  const key = `codex:${session}:${file2}`;
36836
- const stat24 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
37150
+ const stat25 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
36837
37151
  const cached2 = this.cache.get(key);
36838
37152
  this.cache.delete(key);
36839
- if (cached2?.stat === stat24) {
37153
+ if (cached2?.stat === stat25) {
36840
37154
  this.cache.set(key, cached2);
36841
37155
  return cached2.percent;
36842
37156
  }
@@ -36847,7 +37161,7 @@ var ContextUsageReader = class {
36847
37161
  const after = await handle.stat();
36848
37162
  if (after.size !== metadata.size || after.mtimeMs !== metadata.mtimeMs || after.ctimeMs !== metadata.ctimeMs) return void 0;
36849
37163
  const percent = codexContext(tail, start === 0);
36850
- this.cache.set(key, { stat: stat24, percent });
37164
+ this.cache.set(key, { stat: stat25, percent });
36851
37165
  while (this.cache.size > MAX_SESSIONS) this.cache.delete(this.cache.keys().next().value);
36852
37166
  return percent;
36853
37167
  } finally {
@@ -36924,12 +37238,12 @@ init_zod();
36924
37238
  init_logger();
36925
37239
  init_project_config();
36926
37240
  import { randomUUID as randomUUID9 } from "node:crypto";
36927
- import { lstat as lstat11, mkdir as mkdir11, readFile as readFile20, readdir as readdir8, realpath as realpath9, stat as stat12 } from "node:fs/promises";
37241
+ import { lstat as lstat11, mkdir as mkdir12, readFile as readFile20, readdir as readdir8, realpath as realpath9, stat as stat13 } from "node:fs/promises";
36928
37242
  import path46 from "node:path";
36929
37243
 
36930
37244
  // src/bridge/computers.ts
36931
37245
  import { execFile as execFile7 } from "node:child_process";
36932
- import { chmod as chmod3, lstat as lstat9, mkdir as mkdir10, mkdtemp as mkdtemp2, readFile as readFile18, rename as rename6, rm as rm5, writeFile as writeFile5 } from "node:fs/promises";
37246
+ import { chmod as chmod3, lstat as lstat9, mkdir as mkdir11, mkdtemp as mkdtemp2, readFile as readFile18, rename as rename6, rm as rm5, writeFile as writeFile5 } from "node:fs/promises";
36933
37247
  import { homedir as homedir13 } from "node:os";
36934
37248
  import path44 from "node:path";
36935
37249
  import { promisify as promisify7 } from "node:util";
@@ -36944,7 +37258,7 @@ init_fanouts();
36944
37258
  init_protocol();
36945
37259
  import { execFile as execFile5, spawn as spawn2 } from "node:child_process";
36946
37260
  import { createHash as createHash9 } from "node:crypto";
36947
- import { lstat as lstat7, open as open6, readFile as readFile16, readdir as readdir7, realpath as realpath8, stat as stat11 } from "node:fs/promises";
37261
+ import { lstat as lstat7, open as open7, readFile as readFile16, readdir as readdir7, realpath as realpath8, stat as stat12 } from "node:fs/promises";
36948
37262
  import { homedir as homedir10 } from "node:os";
36949
37263
  import path41 from "node:path";
36950
37264
  import { promisify as promisify5 } from "node:util";
@@ -37022,10 +37336,10 @@ var openCodeAuthFile = () => path41.join(
37022
37336
  );
37023
37337
  async function readOpenRouterKey() {
37024
37338
  try {
37025
- const handle = await open6(openCodeAuthFile(), "r");
37339
+ const handle = await open7(openCodeAuthFile(), "r");
37026
37340
  try {
37027
- const stat24 = await handle.stat();
37028
- if (!stat24.isFile() || stat24.size > 65536) return void 0;
37341
+ const stat25 = await handle.stat();
37342
+ if (!stat25.isFile() || stat25.size > 65536) return void 0;
37029
37343
  const key = object2(object2(JSON.parse(await handle.readFile("utf8"))).openrouter).key;
37030
37344
  return typeof key === "string" && key.length >= 16 && key.length <= 4096 && !/[\x00-\x1f\x7f]/.test(key) ? key : void 0;
37031
37345
  } finally {
@@ -37037,7 +37351,7 @@ async function readOpenRouterKey() {
37037
37351
  }
37038
37352
  async function readOpenCodeGoKey() {
37039
37353
  try {
37040
- const handle = await open6(openCodeAuthFile(), "r");
37354
+ const handle = await open7(openCodeAuthFile(), "r");
37041
37355
  try {
37042
37356
  const metadata = await handle.stat();
37043
37357
  if (!metadata.isFile() || metadata.size > 65536) return void 0;
@@ -37212,7 +37526,7 @@ async function containedRegularFile(root, candidate, maximum) {
37212
37526
  if (!link.isFile() || link.isSymbolicLink() || link.size > maximum) return void 0;
37213
37527
  const resolved = await realpath8(candidate);
37214
37528
  if (!resolved.startsWith(root + path41.sep)) return void 0;
37215
- const metadata = await stat11(resolved);
37529
+ const metadata = await stat12(resolved);
37216
37530
  return metadata.isFile() && metadata.size <= maximum ? resolved : void 0;
37217
37531
  } catch {
37218
37532
  return void 0;
@@ -37647,10 +37961,10 @@ var AccountUsageReader = class {
37647
37961
  async snapshotClaude() {
37648
37962
  let claude2 = { source: "claude", windows: [], message: "Usage appears after Claude Code replies on this computer. Run phren bridge install if usage reporting is not set up yet." };
37649
37963
  try {
37650
- const handle = await open6(claudeFile(), "r");
37964
+ const handle = await open7(claudeFile(), "r");
37651
37965
  try {
37652
- const stat24 = await handle.stat();
37653
- if (!stat24.isFile() || stat24.size > 16384) throw new Error("Invalid usage snapshot");
37966
+ const stat25 = await handle.stat();
37967
+ if (!stat25.isFile() || stat25.size > 16384) throw new Error("Invalid usage snapshot");
37654
37968
  const saved = object2(JSON.parse(await handle.readFile("utf8")));
37655
37969
  const date5 = new Date(String(saved.updatedAt));
37656
37970
  if (!Number.isFinite(date5.getTime()) || date5.getTime() > this.now() + 6e4) throw new Error("Invalid usage timestamp");
@@ -37661,10 +37975,10 @@ var AccountUsageReader = class {
37661
37975
  } catch {
37662
37976
  }
37663
37977
  try {
37664
- const handle = await open6(claudeConfigFile(), "r");
37978
+ const handle = await open7(claudeConfigFile(), "r");
37665
37979
  try {
37666
- const stat24 = await handle.stat();
37667
- if (!stat24.isFile() || stat24.size > 16777216) throw new Error("Invalid Claude config");
37980
+ const stat25 = await handle.stat();
37981
+ if (!stat25.isFile() || stat25.size > 16777216) throw new Error("Invalid Claude config");
37668
37982
  const scoped = claudeScopedWindows(JSON.parse(await handle.readFile("utf8")), new Date(this.now())).filter((entry) => !claude2.windows.some((existing) => existing.id === entry.id));
37669
37983
  if (scoped.length) claude2 = { ...claude2, windows: [...claude2.windows, ...scoped], message: void 0 };
37670
37984
  } finally {
@@ -37723,7 +38037,7 @@ async function captureClaudeUsage(original) {
37723
38037
  // src/bridge/install.ts
37724
38038
  init_home_paths();
37725
38039
  init_protocol();
37726
- import { chmod as chmod2, copyFile as copyFile2, mkdir as mkdir9, open as open7, readFile as readFile17, rename as rename5, symlink, unlink as unlink4, lstat as lstat8, writeFile as writeFile4 } from "node:fs/promises";
38040
+ import { chmod as chmod2, copyFile as copyFile2, mkdir as mkdir10, open as open8, readFile as readFile17, rename as rename5, symlink, unlink as unlink4, lstat as lstat8, writeFile as writeFile4 } from "node:fs/promises";
37727
38041
  import { homedir as homedir12 } from "node:os";
37728
38042
  import path43 from "node:path";
37729
38043
  import { fileURLToPath as fileURLToPath4 } from "node:url";
@@ -37878,7 +38192,7 @@ function keyOptions(line) {
37878
38192
  return void 0;
37879
38193
  }
37880
38194
  function upgradeKeys(text3) {
37881
- let changed = 0;
38195
+ let changed2 = 0;
37882
38196
  const result = text3.split(/(?<=\n)/).map((line) => {
37883
38197
  const parsed = keyOptions(line);
37884
38198
  if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest)) return line;
@@ -37887,10 +38201,10 @@ function upgradeKeys(text3) {
37887
38201
  const options = parsed.options.filter((option) => option.toLowerCase() !== "port-forwarding" && !option.toLowerCase().startsWith("permitopen=")).map((option) => old.test(option) ? forcedCommand : option);
37888
38202
  if (!options.includes("pty")) options.splice(1, 0, "pty");
37889
38203
  const next = options.join(",") + parsed.rest;
37890
- if (next !== line) changed++;
38204
+ if (next !== line) changed2++;
37891
38205
  return next;
37892
38206
  }).join("");
37893
- return { text: result, changed };
38207
+ return { text: result, changed: changed2 };
37894
38208
  }
37895
38209
  var quote2 = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
37896
38210
  var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -37983,10 +38297,10 @@ async function install(version3, noService = false) {
37983
38297
  const modules = activateModules(defaultPhrenPath(), void 0, true);
37984
38298
  if (!modules.has("hook")) throw new Error(disabledHint("hook"));
37985
38299
  const root = bridgeRoot(), herdr = herdrRoot(), versions = path43.join(root, "versions");
37986
- await mkdir9(versions, { recursive: true, mode: 448 });
38300
+ await mkdir10(versions, { recursive: true, mode: 448 });
37987
38301
  await chmod2(root, 448);
37988
38302
  const serviceLog = path43.join(root, "service.log");
37989
- const log2 = await open7(serviceLog, "a", 384);
38303
+ const log2 = await open8(serviceLog, "a", 384);
37990
38304
  try {
37991
38305
  await log2.chmod(384);
37992
38306
  } finally {
@@ -37996,7 +38310,7 @@ async function install(version3, noService = false) {
37996
38310
  const own2 = fileURLToPath4(import.meta.url);
37997
38311
  const bundle = own2.endsWith("bridge-hook.mjs") ? own2 : path43.join(path43.dirname(own2), "..", "bridge-hook.mjs");
37998
38312
  const destination2 = path43.join(versions, version3);
37999
- await mkdir9(destination2, { recursive: true, mode: 448 });
38313
+ await mkdir10(destination2, { recursive: true, mode: 448 });
38000
38314
  const installedBundle = path43.join(destination2, "bridge-hook.mjs");
38001
38315
  const previousBundle = await missingFile(readFile17(installedBundle));
38002
38316
  const stagedBundle = installedBundle + `.phren-${process.pid}`;
@@ -38019,14 +38333,14 @@ async function install(version3, noService = false) {
38019
38333
  if (!noService) {
38020
38334
  if (process.platform === "darwin") {
38021
38335
  const folder = path43.join(homedir12(), "Library/LaunchAgents");
38022
- await mkdir9(folder, { recursive: true });
38336
+ await mkdir10(folder, { recursive: true });
38023
38337
  await atomic(path43.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>
38024
38338
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
38025
38339
  <plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(program)}</string><string>serve</string></array><key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string><key>PHREN_HERDR_HOME</key><string>${xml(herdr)}</string><key>PHREN_PATH</key><string>${xml(modules.store)}</string><key>PHREN_PROFILE</key><string>${xml(modules.profile)}</string></dict><key>StandardErrorPath</key><string>${xml(path43.join(root, "service.log"))}</string></dict></plist>
38026
38340
  `);
38027
38341
  } else {
38028
38342
  const folder = path43.join(homedir12(), ".config/systemd/user");
38029
- await mkdir9(folder, { recursive: true });
38343
+ await mkdir10(folder, { recursive: true });
38030
38344
  await atomic(path43.join(folder, unit), `[Unit]
38031
38345
  Description=Phren Hook
38032
38346
  [Service]
@@ -38203,13 +38517,13 @@ async function applyOpencodePlugin(remove = false) {
38203
38517
  }
38204
38518
  if (source === void 0 || !opencodePluginNeedsWrite(existing, source)) return false;
38205
38519
  if (!(await lstat8(path43.dirname(dir)).catch(() => null))?.isDirectory()) return false;
38206
- await mkdir9(dir, { recursive: true });
38520
+ await mkdir10(dir, { recursive: true });
38207
38521
  await atomic(file2, source, 420);
38208
38522
  return true;
38209
38523
  }
38210
38524
  async function applyAgentHooks(edits) {
38211
38525
  for (const { file: file2, before, after } of edits) {
38212
- await mkdir9(path43.dirname(file2), { recursive: true, mode: 448 });
38526
+ await mkdir10(path43.dirname(file2), { recursive: true, mode: 448 });
38213
38527
  if (await missingFile(readFile17(file2, "utf8")) !== before) throw new Error("Agent settings changed during installation. Run install again.");
38214
38528
  if (before !== void 0) await copyFile2(file2, file2 + `.phren-hook-${Date.now()}.bak`);
38215
38529
  await atomic(file2, after);
@@ -38258,11 +38572,11 @@ async function regularFile(file2) {
38258
38572
  }
38259
38573
  async function enrollComputer(name, root = bridgeRoot()) {
38260
38574
  computerName.parse(name);
38261
- await mkdir10(root, { recursive: true, mode: 448 });
38575
+ await mkdir11(root, { recursive: true, mode: 448 });
38262
38576
  await chmod3(root, 448);
38263
38577
  const lock = path44.join(root, "enroll-computer.lock");
38264
38578
  try {
38265
- await mkdir10(lock, { mode: 448 });
38579
+ await mkdir11(lock, { mode: 448 });
38266
38580
  } catch {
38267
38581
  throw new BridgeError(409, "Computer enrollment is already running; inspect enroll-computer.lock if interrupted.");
38268
38582
  }
@@ -38291,13 +38605,22 @@ async function acceptComputer(name, input2, sshDirectory = path44.join(homedir13
38291
38605
  const raw = input2.trim();
38292
38606
  const publicKey = publicComputerKey(raw.startsWith(prefix) ? raw.slice(prefix.length) : raw);
38293
38607
  const line = computerKeyLine(name, publicKey);
38608
+ const encoded = publicKey.split(" ")[1];
38609
+ await appendAuthorizedKey(
38610
+ line,
38611
+ (existing) => existing.endsWith(` phren-computer:${name}`) || existing.split(/\s+/).includes(encoded),
38612
+ "This name or key is already enrolled differently. Revoke the old line explicitly first.",
38613
+ sshDirectory
38614
+ );
38615
+ }
38616
+ async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory = path44.join(homedir13(), ".ssh")) {
38294
38617
  const directory = await lstat9(sshDirectory).catch(() => void 0);
38295
38618
  if (directory && (!directory.isDirectory() || directory.isSymbolicLink())) throw new BridgeError(409, "Refusing an unexpected SSH directory.");
38296
- await mkdir10(sshDirectory, { recursive: true, mode: 448 });
38619
+ await mkdir11(sshDirectory, { recursive: true, mode: 448 });
38297
38620
  await chmod3(sshDirectory, 448);
38298
38621
  const lock = path44.join(sshDirectory, ".phren-enroll.lock");
38299
38622
  try {
38300
- await mkdir10(lock, { mode: 448 });
38623
+ await mkdir11(lock, { mode: 448 });
38301
38624
  } catch {
38302
38625
  throw new BridgeError(409, "SSH enrollment is already running; inspect .phren-enroll.lock if interrupted.");
38303
38626
  }
@@ -38310,10 +38633,7 @@ async function acceptComputer(name, input2, sshDirectory = path44.join(homedir13
38310
38633
  await chmod3(file2, 384);
38311
38634
  return;
38312
38635
  }
38313
- const encoded = publicKey.split(" ")[1];
38314
- if (lines.some((existing) => existing.endsWith(` phren-computer:${name}`) || existing.split(/\s+/).includes(encoded))) {
38315
- throw new BridgeError(409, "This name or key is already enrolled differently. Revoke the old line explicitly first.");
38316
- }
38636
+ if (lines.some(conflicts)) throw new BridgeError(409, conflictMessage);
38317
38637
  await writeFile5(temporary, before + (before && !before.endsWith("\n") ? "\n" : "") + line + "\n", { mode: 384, flag: "wx" });
38318
38638
  const current = await regularFile(file2) ? await readFile18(file2, "utf8") : "";
38319
38639
  if (current !== before) throw new BridgeError(409, "authorized_keys changed during enrollment. Try again.");
@@ -38412,10 +38732,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
38412
38732
  for (const value2 of values.slice(0, 128)) {
38413
38733
  if (state.count >= 128) break;
38414
38734
  const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
38415
- const path79 = publicLabel(raw.path);
38735
+ const path81 = publicLabel(raw.path);
38416
38736
  const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
38417
38737
  const routed = destination(raw, fallbackComputer, fallbackTarget);
38418
- if (!id2.success || !source.success || !path79 || !callId || !routed) continue;
38738
+ if (!id2.success || !source.success || !path81 || !callId || !routed) continue;
38419
38739
  const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
38420
38740
  const nestedSession = sessionId.safeParse(raw.session);
38421
38741
  const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
@@ -38428,7 +38748,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
38428
38748
  projected.push({
38429
38749
  id: publicID(parent, routed.computer.id, receipt.id, descendant),
38430
38750
  provider: source.data,
38431
- path: path79,
38751
+ path: path81,
38432
38752
  callId,
38433
38753
  state: raw.failed === true ? "failed" : childState,
38434
38754
  ...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
@@ -38513,6 +38833,20 @@ async function hookPeers(root = bridgeRoot()) {
38513
38833
  if (new Set(computers.map((peer) => peer.name)).size !== computers.length) throw new BridgeError(409, "hooks.yaml has duplicate computer names.");
38514
38834
  return computers;
38515
38835
  }
38836
+ async function addHookPeer(input2, root = bridgeRoot()) {
38837
+ const peer = peerSchema.parse(input2);
38838
+ const existing = await hookPeers(root).catch((error62) => {
38839
+ if (error62 instanceof BridgeError && error62.details?.hooksYaml === "missing") return [];
38840
+ throw error62;
38841
+ });
38842
+ const same = (other) => JSON.stringify(peerSchema.parse(other)) === JSON.stringify(peer);
38843
+ if (existing.some(same)) return { added: false, peer };
38844
+ const clash = existing.find((other) => other.name === peer.name || other.address === peer.address && other.port === peer.port && other.server === peer.server);
38845
+ if (clash) throw new BridgeError(409, `hooks.yaml already has ${clash.name} at ${clash.address}; remove that entry first to link it differently.`);
38846
+ if (existing.length >= 32) throw new BridgeError(409, "hooks.yaml already has 32 computers.");
38847
+ await atomic(path45.join(root, "hooks.yaml"), dump({ version: 1, computers: [...existing, peer] }, { lineWidth: -1 }));
38848
+ return { added: true, peer };
38849
+ }
38516
38850
  async function optionalHookPeers(root = bridgeRoot()) {
38517
38851
  try {
38518
38852
  return { peers: await hookPeers(root) };
@@ -38597,34 +38931,34 @@ async function peerRequest(peer, route, data, timeout) {
38597
38931
  const knownHosts = path45.join(temporary, "known_hosts");
38598
38932
  await writeFile6(knownHosts, `phren-peer ${peer.hostKey}
38599
38933
  `, { mode: 384 });
38600
- const ssh = spawn4("ssh", peerSSHArgs(peer, knownHosts, key), { stdio: ["pipe", "pipe", "pipe"] });
38601
- child = ssh;
38934
+ const ssh2 = spawn4("ssh", peerSSHArgs(peer, knownHosts, key), { stdio: ["pipe", "pipe", "pipe"] });
38935
+ child = ssh2;
38602
38936
  stream = new Duplex({
38603
38937
  read() {
38604
- ssh.stdout.resume();
38938
+ ssh2.stdout.resume();
38605
38939
  },
38606
38940
  write(chunk, encoding, callback) {
38607
- ssh.stdin.write(chunk, encoding, callback);
38941
+ ssh2.stdin.write(chunk, encoding, callback);
38608
38942
  },
38609
38943
  final(callback) {
38610
- ssh.stdin.end(callback);
38944
+ ssh2.stdin.end(callback);
38611
38945
  },
38612
38946
  destroy(error62, callback) {
38613
- ssh.kill();
38947
+ ssh2.kill();
38614
38948
  callback(error62);
38615
38949
  }
38616
38950
  });
38617
- ssh.stdout.on("data", (chunk) => {
38618
- if (!stream.push(chunk)) ssh.stdout.pause();
38951
+ ssh2.stdout.on("data", (chunk) => {
38952
+ if (!stream.push(chunk)) ssh2.stdout.pause();
38619
38953
  });
38620
- ssh.stdout.on("end", () => stream.push(null));
38621
- ssh.stdout.on("error", (error62) => stream?.destroy(error62));
38622
- ssh.stdin.on("error", (error62) => stream?.destroy(error62));
38954
+ ssh2.stdout.on("end", () => stream.push(null));
38955
+ ssh2.stdout.on("error", (error62) => stream?.destroy(error62));
38956
+ ssh2.stdin.on("error", (error62) => stream?.destroy(error62));
38623
38957
  let diagnostic = "";
38624
38958
  child.stderr.on("data", (bytes) => {
38625
38959
  diagnostic = (diagnostic + bytes.toString()).slice(-4096);
38626
38960
  });
38627
- const exited = new Promise((resolve11) => ssh.once("exit", (code) => resolve11(code)));
38961
+ const exited = new Promise((resolve11) => ssh2.once("exit", (code) => resolve11(code)));
38628
38962
  child.on("error", (error62) => stream?.destroy(new BridgeError(503, `SSH is unavailable (${error62.code ?? "spawn failed"}).`)));
38629
38963
  try {
38630
38964
  return await hookRequest(route, data, { createConnection: () => stream }, timeout ?? (data === void 0 ? 15e3 : 65e3));
@@ -38732,12 +39066,12 @@ async function dispatchProjectDirectory(project) {
38732
39066
  const source = readProjectConfig(phrenStoreRoot(), name).sourcePath;
38733
39067
  if (typeof source !== "string" || !path46.isAbsolute(source) || /[\x00-\x1f\x7f]/.test(source)) throw new BridgeError(404, "Project has no absolute sourcePath on this computer.");
38734
39068
  const directory = await realpath9(source).catch(() => void 0);
38735
- if (!directory || !(await stat12(directory)).isDirectory()) throw new BridgeError(404, "Project is not on this computer.");
39069
+ if (!directory || !(await stat13(directory)).isDirectory()) throw new BridgeError(404, "Project is not on this computer.");
38736
39070
  return directory;
38737
39071
  }
38738
39072
  async function save(receipt) {
38739
39073
  const root = path46.join(bridgeRoot(), "dispatches");
38740
- await mkdir11(root, { recursive: true, mode: 448 });
39074
+ await mkdir12(root, { recursive: true, mode: 448 });
38741
39075
  await atomic(path46.join(root, `${receipt.id}.json`), receipt);
38742
39076
  }
38743
39077
  var MAX_RECEIPT_BYTES = 65536;
@@ -38991,6 +39325,8 @@ function sessionsFrom(overview, computer, local, now = Date.now()) {
38991
39325
  const sessions = [];
38992
39326
  for (const group of objects(overview.groups)) for (const tab of objects(group.children)) {
38993
39327
  if (typeof tab.agent !== "string") continue;
39328
+ const inConductorWorkspace = tab.role !== "conductor" && objects(group.children).some((other) => other.role === "conductor");
39329
+ const label2 = inConductorWorkspace ? typeof tab.label === "string" && !/^\d+$/.test(tab.label) ? tab.label : void 0 : group.label;
38994
39330
  const target = targetSchema.safeParse(tab.target);
38995
39331
  const cwd = typeof tab.cwd === "string" ? tab.cwd : "";
38996
39332
  const text3 = (value2) => typeof value2 === "string" && value2 ? value2 : void 0;
@@ -38999,7 +39335,7 @@ function sessionsFrom(overview, computer, local, now = Date.now()) {
38999
39335
  computer,
39000
39336
  local,
39001
39337
  project: tab.role === "conductor" ? void 0 : text3(cwd.split("/").filter(Boolean).at(-1)),
39002
- label: text3(group.label),
39338
+ label: text3(label2),
39003
39339
  title: text3(tab.title),
39004
39340
  agent: tab.agent,
39005
39341
  status: text3(tab.agentStatus),
@@ -39059,7 +39395,7 @@ async function listLiveSessions(options = {}) {
39059
39395
  init_protocol();
39060
39396
 
39061
39397
  // src/bridge/schedule-watch.ts
39062
- import { open as open8, stat as stat13 } from "node:fs/promises";
39398
+ import { open as open9, stat as stat14 } from "node:fs/promises";
39063
39399
  init_protocol();
39064
39400
  init_transcripts();
39065
39401
  var STARTUP_BLOCK_WINDOW_MS = 9e4;
@@ -39153,7 +39489,7 @@ async function readFinalTurn(source, sessionId2) {
39153
39489
  if (!sessionId2) return void 0;
39154
39490
  const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
39155
39491
  if (!file2) return void 0;
39156
- const handle = await open8(file2, "r").catch(() => void 0);
39492
+ const handle = await open9(file2, "r").catch(() => void 0);
39157
39493
  if (!handle) return void 0;
39158
39494
  try {
39159
39495
  const { size } = await handle.stat();
@@ -39193,7 +39529,7 @@ function ownerQuestion(text3) {
39193
39529
  async function realTranscriptStamp(source, sessionId2) {
39194
39530
  if (!sessionId2) return void 0;
39195
39531
  const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
39196
- const metadata = file2 ? await stat13(file2).catch(() => void 0) : void 0;
39532
+ const metadata = file2 ? await stat14(file2).catch(() => void 0) : void 0;
39197
39533
  return metadata ? { size: metadata.size, mtimeMs: metadata.mtimeMs } : void 0;
39198
39534
  }
39199
39535
  async function watchHerdrRun(server, target, signal, startup, env = {}) {
@@ -39328,7 +39664,7 @@ function observe(receipt, value2, now) {
39328
39664
  const parsed = observationSchema.safeParse(value2);
39329
39665
  if (!parsed.success || parsed.data.state === "unavailable" || parsed.data.state === "unknown") return false;
39330
39666
  const seen = parsed.data, at = new Date(now).toISOString();
39331
- let changed = false;
39667
+ let changed2 = false;
39332
39668
  if (seen.session && receipt.target && !("session" in receipt.target)) {
39333
39669
  const full2 = targetSchema.safeParse({
39334
39670
  server: receipt.target.server,
@@ -39340,7 +39676,7 @@ function observe(receipt, value2, now) {
39340
39676
  });
39341
39677
  if (full2.success) {
39342
39678
  receipt.target = full2.data;
39343
- changed = true;
39679
+ changed2 = true;
39344
39680
  }
39345
39681
  }
39346
39682
  const sawWorking = receipt.worker?.sawWorking === true || seen.state === "working" || seen.state === "blocked";
@@ -39359,9 +39695,9 @@ function observe(receipt, value2, now) {
39359
39695
  if (repeated) {
39360
39696
  if (receipt.worker && receipt.worker.sawWorking !== sawWorking) {
39361
39697
  receipt.worker.sawWorking = sawWorking;
39362
- changed = true;
39698
+ changed2 = true;
39363
39699
  }
39364
- return changed;
39700
+ return changed2;
39365
39701
  }
39366
39702
  receipt.worker = { state: next, since: at, checkedAt: at, sawWorking };
39367
39703
  if (next !== "working") {
@@ -39378,13 +39714,13 @@ function observe(receipt, value2, now) {
39378
39714
  return true;
39379
39715
  }
39380
39716
  function noticeLine(receipts) {
39381
- const clean = (value2, max) => value2.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
39717
+ const clean2 = (value2, max) => value2.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
39382
39718
  const word = { "done": "done", "needs-you": "needs you", "failed": "failed", "blocked": "blocked", "gone": "gone" };
39383
39719
  const describe4 = (receipt, room) => {
39384
39720
  const returned = receipt.returned;
39385
39721
  const detail = returned.state === "needs-you" ? returned.question : returned.state === "failed" ? returned.error : returned.state === "done" ? returned.reply?.split("\n").find((line) => line.trim()) : void 0;
39386
- const excerpt = detail ? clean(detail.replace(/[*_`#>]+/g, ""), room) : "";
39387
- return `${clean(receipt.computer, 60)} ${clean(receipt.label, 80)} ${word[returned.state]}${excerpt ? `, ${excerpt}` : ""}`;
39722
+ const excerpt = detail ? clean2(detail.replace(/[*_`#>]+/g, ""), room) : "";
39723
+ return `${clean2(receipt.computer, 60)} ${clean2(receipt.label, 80)} ${word[returned.state]}${excerpt ? `, ${excerpt}` : ""}`;
39388
39724
  };
39389
39725
  if (receipts.length === 1) return `Return: ${describe4(receipts[0], 100)} (dispatch ${receipts[0].id}). Call dispatch_returns.`;
39390
39726
  const items = receipts.slice(0, 4).map((receipt) => describe4(receipt, 40)).join("; ");
@@ -39446,11 +39782,11 @@ var DispatchReturns = class {
39446
39782
  /** Ask each peer, once, about every open dispatch placed on it. */
39447
39783
  async poll() {
39448
39784
  const now = this.now();
39449
- const open14 = (await dispatchStatus()).filter((receipt) => (receipt.state === "accepted" || receipt.state === "uncertain") && receipt.target && receipt.worker?.state !== "gone" && now - Date.parse(receipt.createdAt) < WATCH_MS);
39450
- if (!open14.length) return;
39785
+ const open15 = (await dispatchStatus()).filter((receipt) => (receipt.state === "accepted" || receipt.state === "uncertain") && receipt.target && receipt.worker?.state !== "gone" && now - Date.parse(receipt.createdAt) < WATCH_MS);
39786
+ if (!open15.length) return;
39451
39787
  const peers = await this.peers().catch(() => []);
39452
39788
  const byComputer = /* @__PURE__ */ new Map();
39453
- for (const receipt of open14) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
39789
+ for (const receipt of open15) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
39454
39790
  await Promise.all([...byComputer].map(async ([computer, receipts]) => {
39455
39791
  const peer = peers.find((candidate) => candidate.name === computer);
39456
39792
  const local = !peer && this.isLocal(computer);
@@ -39520,7 +39856,7 @@ init_zod();
39520
39856
  init_protocol();
39521
39857
  import { execFile as execFile8 } from "node:child_process";
39522
39858
  import { createHash as createHash12 } from "node:crypto";
39523
- import { mkdir as mkdir12, open as open9, stat as stat14, readFile as readFile21, writeFile as writeFile7 } from "node:fs/promises";
39859
+ import { mkdir as mkdir13, open as open10, stat as stat15, readFile as readFile21, writeFile as writeFile7 } from "node:fs/promises";
39524
39860
  import path47 from "node:path";
39525
39861
  import { promisify as promisify8 } from "node:util";
39526
39862
  init_transcripts();
@@ -39637,7 +39973,7 @@ var CodexQuestions = class {
39637
39973
  const cached2 = this.snapshots.get(target.session);
39638
39974
  let pending = cached2?.pending;
39639
39975
  if (!cached2 || Date.now() - cached2.at > 1e3) {
39640
- const metadata = await stat14(file2), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
39976
+ const metadata = await stat15(file2), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
39641
39977
  pending = cached2?.stamp === stamp ? cached2.pending : await pendingAsyncQuestions(file2).catch((error62) => {
39642
39978
  if (this.failedSnapshots.size >= 64) this.failedSnapshots.delete(this.failedSnapshots.keys().next().value);
39643
39979
  this.failedSnapshots.set(target.session, Date.now());
@@ -39666,10 +40002,10 @@ var CodexQuestions = class {
39666
40002
  const pane = await validateTarget(target);
39667
40003
  if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
39668
40004
  const directory = path47.join(bridgeRoot(), "question-replies");
39669
- await mkdir12(directory, { recursive: true, mode: 448 });
40005
+ await mkdir13(directory, { recursive: true, mode: 448 });
39670
40006
  const key = createHash12("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
39671
40007
  const receiptPath = path47.join(directory, key);
39672
- const receipt = await open9(receiptPath, "wx", 384).catch((error62) => {
40008
+ const receipt = await open10(receiptPath, "wx", 384).catch((error62) => {
39673
40009
  if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
39674
40010
  throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
39675
40011
  });
@@ -39690,7 +40026,7 @@ init_transcripts();
39690
40026
  init_home_paths();
39691
40027
  init_protocol();
39692
40028
  import { spawn as spawn5 } from "node:child_process";
39693
- import { readdir as readdir9, readFile as readFile22, stat as stat15 } from "node:fs/promises";
40029
+ import { readdir as readdir9, readFile as readFile22, stat as stat16 } from "node:fs/promises";
39694
40030
  import { homedir as homedir14 } from "node:os";
39695
40031
  import path48 from "node:path";
39696
40032
  function readCodexModels(executable = "codex") {
@@ -39776,7 +40112,7 @@ async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
39776
40112
  try {
39777
40113
  for (const name of await readdir9(directory)) {
39778
40114
  if (!name.endsWith("-cc.json")) continue;
39779
- const file2 = path48.join(directory, name), at = (await stat15(file2)).mtimeMs;
40115
+ const file2 = path48.join(directory, name), at = (await stat16(file2)).mtimeMs;
39780
40116
  if (!newest || at > newest.at) newest = { file: file2, at };
39781
40117
  }
39782
40118
  } catch {
@@ -40575,7 +40911,7 @@ init_home_paths();
40575
40911
  init_fanouts();
40576
40912
  import { spawn as spawn6 } from "node:child_process";
40577
40913
  import { createWriteStream } from "node:fs";
40578
- import { mkdir as mkdir13, readFile as readFile24, stat as stat16 } from "node:fs/promises";
40914
+ import { mkdir as mkdir14, readFile as readFile24, stat as stat17 } from "node:fs/promises";
40579
40915
  import path50 from "node:path";
40580
40916
  import { finished as streamFinished } from "node:stream/promises";
40581
40917
  init_protocol();
@@ -40640,7 +40976,7 @@ async function promptWhenReady(server, paneId, text3, signal, waitMs = 6e4) {
40640
40976
  }
40641
40977
  async function launchHeadless(context, store, started) {
40642
40978
  const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path50.join(root, context.runId);
40643
- await mkdir13(jobDir, { recursive: true, mode: 448 });
40979
+ await mkdir14(jobDir, { recursive: true, mode: 448 });
40644
40980
  const eventLog = "events.jsonl", now = (/* @__PURE__ */ new Date()).toISOString();
40645
40981
  const manifest = {
40646
40982
  schemaVersion: 1,
@@ -40756,8 +41092,8 @@ async function ensureCodexDirTrusted(cwd) {
40756
41092
  ${trustLine}
40757
41093
  `;
40758
41094
  }
40759
- await mkdir13(directory, { recursive: true, mode: 448 });
40760
- const metadata = await stat16(file2).catch(() => void 0);
41095
+ await mkdir14(directory, { recursive: true, mode: 448 });
41096
+ const metadata = await stat17(file2).catch(() => void 0);
40761
41097
  const mode = metadata ? metadata.mode & 511 : 384;
40762
41098
  await atomic(file2, next, mode);
40763
41099
  }
@@ -41337,7 +41673,7 @@ init_shared();
41337
41673
 
41338
41674
  // src/bridge/server-routes.ts
41339
41675
  init_zod();
41340
- import path77 from "node:path";
41676
+ import path78 from "node:path";
41341
41677
 
41342
41678
  // src/bridge/code-note.ts
41343
41679
  init_zod();
@@ -42033,8 +42369,8 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
42033
42369
  } catch (e) {
42034
42370
  if (e.code === "EEXIST") {
42035
42371
  try {
42036
- const stat24 = fs27.statSync(lockFile);
42037
- if (Date.now() - stat24.mtimeMs < STALE_LOCK_MS) {
42372
+ const stat25 = fs27.statSync(lockFile);
42373
+ if (Date.now() - stat25.mtimeMs < STALE_LOCK_MS) {
42038
42374
  return phrenErr("Consolidation already running", PhrenError.LOCK_TIMEOUT);
42039
42375
  }
42040
42376
  tryUnlink(lockFile);
@@ -42461,6 +42797,7 @@ function canonicalTaskFilePath(phrenPath, project) {
42461
42797
  function resolveTaskFilePath(phrenPath, project) {
42462
42798
  return canonicalTaskFilePath(phrenPath, project);
42463
42799
  }
42800
+ var STALE_CLAIM_MS = 24 * 60 * 60 * 1e3;
42464
42801
 
42465
42802
  // src/data/access.ts
42466
42803
  init_profile_store();
@@ -42689,16 +43026,16 @@ function jaccardSimilarity(a, b) {
42689
43026
  }
42690
43027
  var ENTITY_CACHE_TTL_MS = 60 * 60 * 1e3;
42691
43028
  function isDuplicateFinding(existingContent, newLearning, threshold = 0.6) {
42692
- const normalize = (text3) => {
43029
+ const normalize2 = (text3) => {
42693
43030
  return stripHtmlComments(text3).trim().toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((w) => w.length > 2 && !DEDUP_STOP_WORDS.has(w));
42694
43031
  };
42695
- const newWords = normalize(newLearning);
43032
+ const newWords = normalize2(newLearning);
42696
43033
  if (newWords.length === 0) return false;
42697
43034
  const newSet = new Set(newWords);
42698
43035
  const bullets = existingContent.split("\n").filter((l) => l.startsWith("- "));
42699
43036
  for (const bullet of bullets) {
42700
43037
  if (isInactiveFindingLine(bullet)) continue;
42701
- const existingWords = normalize(bullet);
43038
+ const existingWords = normalize2(bullet);
42702
43039
  if (existingWords.length === 0) continue;
42703
43040
  const existingSet = new Set(existingWords);
42704
43041
  let overlap = 0;
@@ -42837,14 +43174,14 @@ function parseTaskItems(taskPath) {
42837
43174
  counters[section] += 1;
42838
43175
  const itemId = `${section === "Active" ? "A" : section === "Queue" ? "Q" : "D"}${counters[section]}`;
42839
43176
  const stripped = stripBulletPrefix(line).body;
42840
- const { clean, bid } = stripBid(stripped);
43177
+ const { clean: clean2, bid } = stripBid(stripped);
42841
43178
  items.push({
42842
43179
  id: itemId,
42843
43180
  stableId: bid,
42844
43181
  section,
42845
- line: clean,
42846
- priority: normalizePriority(clean),
42847
- pinned: detectPinned(clean) || void 0
43182
+ line: clean2,
43183
+ priority: normalizePriority(clean2),
43184
+ pinned: detectPinned(clean2) || void 0
42848
43185
  });
42849
43186
  }
42850
43187
  return items;
@@ -43296,7 +43633,7 @@ init_protocol();
43296
43633
  import { execFile as execFile10 } from "node:child_process";
43297
43634
  import { promisify as promisify10 } from "node:util";
43298
43635
  import { realpathSync as realpathSync5 } from "node:fs";
43299
- import { readdir as readdir10, readFile as readFile26, stat as stat17, mkdir as mkdir14 } from "node:fs/promises";
43636
+ import { readdir as readdir10, readFile as readFile26, stat as stat18, mkdir as mkdir15 } from "node:fs/promises";
43300
43637
  import { homedir as homedir16 } from "node:os";
43301
43638
  import path66 from "node:path";
43302
43639
  init_transcripts();
@@ -43508,8 +43845,8 @@ function addTermCount(terms, rawText, weight = 1) {
43508
43845
  }
43509
43846
  function maybeReadUtf8(filePath, maxBytes = 256e3) {
43510
43847
  try {
43511
- const stat24 = fs31.statSync(filePath);
43512
- if (!stat24.isFile() || stat24.size > maxBytes) return "";
43848
+ const stat25 = fs31.statSync(filePath);
43849
+ if (!stat25.isFile() || stat25.size > maxBytes) return "";
43513
43850
  return fs31.readFileSync(filePath, "utf8");
43514
43851
  } catch {
43515
43852
  return "";
@@ -44217,6 +44554,8 @@ function conflictStrategy(relFile) {
44217
44554
  if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file2)) return "archive";
44218
44555
  if (/(^|\/)reference\/topics\/[^/]+\.md$/i.test(file2)) return "topic";
44219
44556
  if (name === "summary.md") return "summary";
44557
+ if (name === "review.md") return "union";
44558
+ if (/(^|\/)(notes|journal)\/[^/]+\.md$/i.test(file2)) return "union";
44220
44559
  return null;
44221
44560
  }
44222
44561
  function git4(cwd, args) {
@@ -44256,11 +44595,26 @@ function mergeText(base, ours, theirs) {
44256
44595
  fs32.rmSync(dir, { recursive: true, force: true });
44257
44596
  }
44258
44597
  }
44259
- function mergeWithGeneratedBlock(base, ours, theirs, start, end, where) {
44598
+ function unionText(base, ours, theirs) {
44599
+ const clean2 = mergeText(base, ours, theirs);
44600
+ if (clean2 !== null) return clean2;
44601
+ const dir = fs32.mkdtempSync(path65.join(os3.tmpdir(), "phren-merge-"));
44602
+ try {
44603
+ const [o, b, t] = ["ours", "base", "theirs"].map((name) => path65.join(dir, name));
44604
+ fs32.writeFileSync(o, ours);
44605
+ fs32.writeFileSync(b, base);
44606
+ fs32.writeFileSync(t, theirs);
44607
+ const result = spawnSync2("git", ["merge-file", "--union", "-p", o, b, t], { encoding: "utf8", env: nonInteractiveGitEnv(), timeout: EXEC_TIMEOUT_MS });
44608
+ return result.status === 0 ? result.stdout : null;
44609
+ } finally {
44610
+ fs32.rmSync(dir, { recursive: true, force: true });
44611
+ }
44612
+ }
44613
+ function mergeWithGeneratedBlock(base, ours, theirs, start, end, where, merge2 = unionText) {
44260
44614
  const b = splitBlock(base, start, end);
44261
44615
  const o = splitBlock(ours, start, end);
44262
44616
  const t = splitBlock(theirs, start, end);
44263
- const rest = mergeText(b.rest, o.rest, t.rest);
44617
+ const rest = merge2(b.rest, o.rest, t.rest);
44264
44618
  if (rest === null) return null;
44265
44619
  const block = t.block ?? o.block;
44266
44620
  if (!block) return rest;
@@ -44277,8 +44631,13 @@ function resolveContent(strategy, base, ours, theirs) {
44277
44631
  return mergeTask(theirs, ours);
44278
44632
  case "topic":
44279
44633
  return mergeWithGeneratedBlock(base, ours, theirs, NOW_START, NOW_END, "top");
44634
+ // Summaries are regenerated from the store: when the hand-written part
44635
+ // doesn't merge cleanly, take the incoming file whole and let the next
44636
+ // summarize pass fold in anything only this machine had.
44280
44637
  case "summary":
44281
- return mergeWithGeneratedBlock(base, ours, theirs, KNOWS_START, KNOWS_END, "bottom");
44638
+ return mergeWithGeneratedBlock(base, ours, theirs, KNOWS_START, KNOWS_END, "bottom", mergeText) ?? theirs;
44639
+ case "union":
44640
+ return unionText(base, ours, theirs);
44282
44641
  }
44283
44642
  }
44284
44643
  function resolveStoreConflicts(cwd) {
@@ -44328,29 +44687,29 @@ function resolveStoreConflicts(cwd) {
44328
44687
  // src/sync/store-merge.ts
44329
44688
  init_machine_identity();
44330
44689
  var SENSITIVE_STORE_PATHSPECS = [".env", "**/.env", "*.pem", "*.key", ".config/auth-profiles.json"];
44331
- async function commitLocalStoreWrites(cwd, git6, message) {
44332
- const add = await git6(cwd, ["add", "--sparse", "-A"]);
44690
+ async function commitLocalStoreWrites(cwd, git7, message) {
44691
+ const add = await git7(cwd, ["add", "--sparse", "-A"]);
44333
44692
  if (!add.ok) return { committed: false, error: add.error || "git add failed" };
44334
- await git6(cwd, ["reset", "HEAD", "--", ...SENSITIVE_STORE_PATHSPECS]);
44335
- const staged = await git6(cwd, ["diff", "--cached", "--name-only"]);
44693
+ await git7(cwd, ["reset", "HEAD", "--", ...SENSITIVE_STORE_PATHSPECS]);
44694
+ const staged = await git7(cwd, ["diff", "--cached", "--name-only"]);
44336
44695
  if (!staged.ok) return { committed: false, error: staged.error || "git diff failed" };
44337
44696
  if (!staged.output) return { committed: false };
44338
- const commit = await git6(cwd, ["-c", "commit.gpgsign=false", "commit", "-m", storeCommitMessage(message)]);
44697
+ const commit = await git7(cwd, ["-c", "commit.gpgsign=false", "commit", "-m", storeCommitMessage(message)]);
44339
44698
  return commit.ok ? { committed: true } : { committed: false, error: commit.error || "git commit failed" };
44340
44699
  }
44341
- async function conflictedPaths(cwd, git6) {
44342
- const result = await git6(cwd, ["diff", "--name-only", "--diff-filter=U"]);
44700
+ async function conflictedPaths(cwd, git7) {
44701
+ const result = await git7(cwd, ["diff", "--name-only", "--diff-filter=U"]);
44343
44702
  return result.ok ? result.output.split("\n").map((entry) => entry.trim()).filter(Boolean) : [];
44344
44703
  }
44345
- async function abortMerge(cwd, git6) {
44704
+ async function abortMerge(cwd, git7) {
44346
44705
  if (inProgressGitOperation(cwd) !== "merge") return true;
44347
- const aborted2 = await git6(cwd, ["merge", "--abort"]);
44706
+ const aborted2 = await git7(cwd, ["merge", "--abort"]);
44348
44707
  if (aborted2.ok) return true;
44349
- const reset = await git6(cwd, ["reset", "--merge", "ORIG_HEAD"]);
44708
+ const reset = await git7(cwd, ["reset", "--merge", "ORIG_HEAD"]);
44350
44709
  return reset.ok && inProgressGitOperation(cwd) !== "merge";
44351
44710
  }
44352
44711
  async function mergeStoreUpstream(cwd, options) {
44353
- const { git: git6 } = options;
44712
+ const { git: git7 } = options;
44354
44713
  const operation = inProgressGitOperation(cwd);
44355
44714
  if (operation) {
44356
44715
  const recovery = gitOperationRecovery(operation);
@@ -44359,15 +44718,15 @@ async function mergeStoreUpstream(cwd, options) {
44359
44718
  detail: `The store already has a Git operation in progress (${operation}). Run '${recovery}' in the store before syncing again.`
44360
44719
  };
44361
44720
  }
44362
- const branch = await git6(cwd, ["symbolic-ref", "--quiet", "HEAD"]);
44721
+ const branch = await git7(cwd, ["symbolic-ref", "--quiet", "HEAD"]);
44363
44722
  if (!branch.ok) return { status: "error", detail: "No branch is checked out." };
44364
44723
  let committedLocalWrites = false;
44365
44724
  if (options.commitLocalWrites !== false) {
44366
- const saved = await commitLocalStoreWrites(cwd, git6, options.commitMessage ?? "auto-save phren (store sync)");
44725
+ const saved = await commitLocalStoreWrites(cwd, git7, options.commitMessage ?? "auto-save phren (store sync)");
44367
44726
  if (saved.error) return { status: "error", detail: `Cannot commit local store writes: ${saved.error}` };
44368
44727
  committedLocalWrites = saved.committed;
44369
44728
  }
44370
- const refs = await git6(cwd, ["for-each-ref", "--format=%(upstream:remotename)%09%(upstream:remoteref)%09%(upstream)", branch.output]);
44729
+ const refs = await git7(cwd, ["for-each-ref", "--format=%(upstream:remotename)%09%(upstream:remoteref)%09%(upstream)", branch.output]);
44371
44730
  const [remote, remoteRef, trackingRef] = refs.output.split(" ");
44372
44731
  if (!refs.ok || !remote || !remoteRef || !trackingRef) {
44373
44732
  return {
@@ -44376,22 +44735,22 @@ async function mergeStoreUpstream(cwd, options) {
44376
44735
  committedLocalWrites
44377
44736
  };
44378
44737
  }
44379
- const tracked = await git6(cwd, ["rev-parse", "--verify", trackingRef]);
44738
+ const tracked = await git7(cwd, ["rev-parse", "--verify", trackingRef]);
44380
44739
  if (!options.advertisedHead || !tracked.ok || tracked.output !== options.advertisedHead) {
44381
- const fetched = await git6(cwd, ["fetch", "--quiet", "--no-tags", "--no-recurse-submodules", "--", remote, `${remoteRef}:${trackingRef}`]);
44740
+ const fetched = await git7(cwd, ["fetch", "--quiet", "--no-tags", "--no-recurse-submodules", "--", remote, `${remoteRef}:${trackingRef}`]);
44382
44741
  if (!fetched.ok) return { status: "error", detail: `Fetch failed: ${fetched.error || "unknown Git error"}`, committedLocalWrites };
44383
44742
  }
44384
- const target = await git6(cwd, ["rev-parse", "--verify", trackingRef]);
44743
+ const target = await git7(cwd, ["rev-parse", "--verify", trackingRef]);
44385
44744
  if (!target.ok || !target.output) return { status: "error", detail: "Cannot read the fetched tracking branch.", committedLocalWrites };
44386
- if ((await git6(cwd, ["merge-base", "--is-ancestor", target.output, "HEAD"])).ok) {
44745
+ if ((await git7(cwd, ["merge-base", "--is-ancestor", target.output, "HEAD"])).ok) {
44387
44746
  return {
44388
44747
  status: "unchanged",
44389
44748
  detail: committedLocalWrites ? "Committed local store writes; the store already contains the remote changes." : "The store already contains the remote changes.",
44390
44749
  committedLocalWrites
44391
44750
  };
44392
44751
  }
44393
- const canFastForward = (await git6(cwd, ["merge-base", "--is-ancestor", "HEAD", target.output])).ok;
44394
- const merged = await git6(cwd, canFastForward ? ["merge", "--ff-only", target.output] : ["merge", "--no-edit", target.output]);
44752
+ const canFastForward = (await git7(cwd, ["merge-base", "--is-ancestor", "HEAD", target.output])).ok;
44753
+ const merged = await git7(cwd, canFastForward ? ["merge", "--ff-only", target.output] : ["merge", "--no-edit", target.output]);
44395
44754
  if (merged.ok) {
44396
44755
  return {
44397
44756
  status: "updated",
@@ -44399,7 +44758,7 @@ async function mergeStoreUpstream(cwd, options) {
44399
44758
  committedLocalWrites
44400
44759
  };
44401
44760
  }
44402
- const initialConflicts = await conflictedPaths(cwd, git6);
44761
+ const initialConflicts = await conflictedPaths(cwd, git7);
44403
44762
  if (initialConflicts.length === 0 && inProgressGitOperation(cwd) !== "merge") {
44404
44763
  return {
44405
44764
  status: "error",
@@ -44408,7 +44767,7 @@ async function mergeStoreUpstream(cwd, options) {
44408
44767
  };
44409
44768
  }
44410
44769
  if (initialConflicts.length > 0 && resolveStoreConflicts(cwd).unresolved.length === 0) {
44411
- const commit = await git6(cwd, ["-c", "commit.gpgsign=false", "commit", "--no-edit"]);
44770
+ const commit = await git7(cwd, ["-c", "commit.gpgsign=false", "commit", "--no-edit"]);
44412
44771
  if (commit.ok) {
44413
44772
  return {
44414
44773
  status: "updated",
@@ -44418,9 +44777,9 @@ async function mergeStoreUpstream(cwd, options) {
44418
44777
  };
44419
44778
  }
44420
44779
  }
44421
- const unresolvedConflicts = await conflictedPaths(cwd, git6);
44780
+ const unresolvedConflicts = await conflictedPaths(cwd, git7);
44422
44781
  const conflicts = unresolvedConflicts.length > 0 ? unresolvedConflicts : initialConflicts;
44423
- const cleaned = await abortMerge(cwd, git6);
44782
+ const cleaned = await abortMerge(cwd, git7);
44424
44783
  if (!cleaned) {
44425
44784
  return {
44426
44785
  status: "error",
@@ -44477,12 +44836,12 @@ function clearStoreAuthFailure(cwd) {
44477
44836
  fs33.rmSync(runtimeFile(cwd, "sync-auth.json"), { force: true });
44478
44837
  }
44479
44838
  function storeSyncRemote(cwd, name, push = false) {
44480
- const git6 = (args) => runGit(cwd, args, 5e3);
44481
- const branch = name ? null : git6(["symbolic-ref", "--quiet", "--short", "HEAD"]);
44482
- const pushRemote = push && (branch && git6(["config", "--get", `branch.${branch}.pushRemote`]) || git6(["config", "--get", "remote.pushDefault"]));
44483
- const remoteName = name || pushRemote || branch && git6(["config", "--get", `branch.${branch}.remote`]) || "origin";
44839
+ const git7 = (args) => runGit(cwd, args, 5e3);
44840
+ const branch = name ? null : git7(["symbolic-ref", "--quiet", "--short", "HEAD"]);
44841
+ const pushRemote = push && (branch && git7(["config", "--get", `branch.${branch}.pushRemote`]) || git7(["config", "--get", "remote.pushDefault"]));
44842
+ const remoteName = name || pushRemote || branch && git7(["config", "--get", `branch.${branch}.remote`]) || "origin";
44484
44843
  if (remoteName === ".") return;
44485
- const remote = git6(["remote", "get-url", ...push ? ["--push"] : [], "--", remoteName]);
44844
+ const remote = git7(["remote", "get-url", ...push ? ["--push"] : [], "--", remoteName]);
44486
44845
  return remote ? { remoteName, remote } : void 0;
44487
44846
  }
44488
44847
  function authBackoffActive(state, now = Date.now()) {
@@ -44508,12 +44867,12 @@ function recordStoreAuthFailure(cwd, remoteName, remote, now = Date.now()) {
44508
44867
  return state;
44509
44868
  });
44510
44869
  }
44511
- function withStoreAuthBackoff(git6, now = Date.now) {
44870
+ function withStoreAuthBackoff(git7, now = Date.now) {
44512
44871
  return async (cwd, args) => {
44513
- if (!["fetch", "pull", "push", "ls-remote"].includes(args[0])) return git6(cwd, args);
44872
+ if (!["fetch", "pull", "push", "ls-remote"].includes(args[0])) return git7(cwd, args);
44514
44873
  const separator = args.indexOf("--");
44515
44874
  const remote = storeSyncRemote(cwd, separator >= 0 ? args[separator + 1] : void 0, args[0] === "push");
44516
- if (!remote) return git6(cwd, args);
44875
+ if (!remote) return git7(cwd, args);
44517
44876
  const release = tryFileLock(runtimeFile(cwd, "sync-auth-probe"));
44518
44877
  if (!release) return { ok: false, output: "", error: "Store remote check deferred: another sync is running." };
44519
44878
  try {
@@ -44522,7 +44881,7 @@ function withStoreAuthBackoff(git6, now = Date.now) {
44522
44881
  if (sameRemote && authBackoffActive(previous, now())) {
44523
44882
  return { ok: false, output: "", error: storeAuthDetail(previous) };
44524
44883
  }
44525
- const result = await git6(cwd, args);
44884
+ const result = await git7(cwd, args);
44526
44885
  if (args[0] === "push") return result;
44527
44886
  if (result.ok) {
44528
44887
  if (sameRemote) clearStoreAuthFailure(cwd);
@@ -44592,7 +44951,7 @@ function repoName(url2) {
44592
44951
  }
44593
44952
  async function isRepository(directory) {
44594
44953
  try {
44595
- await stat17(path66.join(directory, ".git"));
44954
+ await stat18(path66.join(directory, ".git"));
44596
44955
  return true;
44597
44956
  } catch {
44598
44957
  return false;
@@ -44626,7 +44985,7 @@ async function candidateRepos(activity, env = process.env) {
44626
44985
  const offer = async (directory, source, lastSeen) => {
44627
44986
  let dir = path66.resolve(directory);
44628
44987
  try {
44629
- if (!(await stat17(dir)).isDirectory()) return;
44988
+ if (!(await stat18(dir)).isDirectory()) return;
44630
44989
  dir = realpathSync5.native(dir);
44631
44990
  } catch {
44632
44991
  return;
@@ -44638,7 +44997,7 @@ async function candidateRepos(activity, env = process.env) {
44638
44997
  };
44639
44998
  const toplevel = async (directory) => {
44640
44999
  let existing = directory;
44641
- while (!await stat17(existing).catch(() => void 0)) {
45000
+ while (!await stat18(existing).catch(() => void 0)) {
44642
45001
  const parent = path66.dirname(existing);
44643
45002
  if (parent === existing) return void 0;
44644
45003
  existing = parent;
@@ -44682,12 +45041,12 @@ async function cloneRoot(env) {
44682
45041
  const home = homedir16();
44683
45042
  for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path66.join(home, r))]) {
44684
45043
  try {
44685
- if ((await stat17(root)).isDirectory()) return root;
45044
+ if ((await stat18(root)).isDirectory()) return root;
44686
45045
  } catch {
44687
45046
  }
44688
45047
  }
44689
45048
  const fallback = path66.join(home, "Projects");
44690
- await mkdir14(fallback, { recursive: true });
45049
+ await mkdir15(fallback, { recursive: true });
44691
45050
  return fallback;
44692
45051
  }
44693
45052
  async function publishStore(store, project) {
@@ -44708,7 +45067,7 @@ async function publishStore(store, project) {
44708
45067
  async function enrollProject(input2, env = process.env) {
44709
45068
  const store = phrenStoreRoot(env);
44710
45069
  try {
44711
- if (!(await stat17(path66.join(store, ".config"))).isDirectory()) throw new Error();
45070
+ if (!(await stat18(path66.join(store, ".config"))).isDirectory()) throw new Error();
44712
45071
  } catch {
44713
45072
  throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
44714
45073
  }
@@ -44721,7 +45080,7 @@ async function enrollProject(input2, env = process.env) {
44721
45080
  if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
44722
45081
  directory = path66.join(await cloneRoot(env), name);
44723
45082
  try {
44724
- await stat17(directory);
45083
+ await stat18(directory);
44725
45084
  throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
44726
45085
  } catch (error62) {
44727
45086
  if (error62 instanceof BridgeError) throw error62;
@@ -44739,7 +45098,7 @@ async function enrollProject(input2, env = process.env) {
44739
45098
  if (raw.length > 4096 || raw.includes("\0") || !path66.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
44740
45099
  try {
44741
45100
  directory = realpathSync5.native(raw);
44742
- if (!(await stat17(directory)).isDirectory()) throw new Error();
45101
+ if (!(await stat18(directory)).isDirectory()) throw new Error();
44743
45102
  } catch {
44744
45103
  throw new BridgeError(404, "That folder is not on this computer.");
44745
45104
  }
@@ -44752,7 +45111,7 @@ async function enrollProject(input2, env = process.env) {
44752
45111
  // src/bridge/files.ts
44753
45112
  init_protocol();
44754
45113
  import { constants as constants2 } from "node:fs";
44755
- import { lstat as lstat14, open as open10, readdir as readdir11, realpath as realpath11 } from "node:fs/promises";
45114
+ import { lstat as lstat14, open as open11, readdir as readdir11, realpath as realpath11 } from "node:fs/promises";
44756
45115
  import path67 from "node:path";
44757
45116
  var MAX_BYTES = 2097152;
44758
45117
  async function browseFiles(root, relative3) {
@@ -44778,7 +45137,7 @@ async function browseFiles(root, relative3) {
44778
45137
  };
44779
45138
  }
44780
45139
  if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
44781
- const handle = await open10(resolved, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
45140
+ const handle = await open11(resolved, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
44782
45141
  try {
44783
45142
  const current = await handle.stat();
44784
45143
  if (!current.isFile() || current.ino !== metadata.ino || current.dev !== metadata.dev) throw new BridgeError(409, "The file changed. Refresh and try again.");
@@ -44800,7 +45159,7 @@ async function browseFiles(root, relative3) {
44800
45159
  // src/bridge/file-range.ts
44801
45160
  init_protocol();
44802
45161
  import { constants as constants3 } from "node:fs";
44803
- import { lstat as lstat15, open as open11, realpath as realpath12 } from "node:fs/promises";
45162
+ import { lstat as lstat15, open as open12, realpath as realpath12 } from "node:fs/promises";
44804
45163
  import path68 from "node:path";
44805
45164
  var MAX_FILE_RANGE = 4 * 1024 * 1024;
44806
45165
  var types = {
@@ -44841,8 +45200,8 @@ function fileContentType(file2) {
44841
45200
  const ext = path68.extname(file2).slice(1).toLowerCase();
44842
45201
  return types[ext] ?? (/^(ts|tsx|js|jsx|swift|py|rs|go|rb|sh|bash|zsh|c|h|cpp|hpp|cs|java|kt|html|css|scss|sql|toml|ini)$/.test(ext) ? "text/plain" : "application/octet-stream");
44843
45202
  }
44844
- function version2(stat24) {
44845
- return `${stat24.dev}:${stat24.ino}:${stat24.size}:${stat24.mtimeMs}:${stat24.ctimeMs}`;
45203
+ function version2(stat25) {
45204
+ return `${stat25.dev}:${stat25.ino}:${stat25.size}:${stat25.mtimeMs}:${stat25.ctimeMs}`;
44846
45205
  }
44847
45206
  function rangeInteger(value2, fallback) {
44848
45207
  if (value2 === null) return fallback;
@@ -44867,7 +45226,7 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
44867
45226
  if (!resolved.startsWith(base + path68.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
44868
45227
  const metadata = await lstat15(resolved);
44869
45228
  if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be opened.");
44870
- const handle = await open11(resolved, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
45229
+ const handle = await open12(resolved, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
44871
45230
  try {
44872
45231
  const current = await handle.stat();
44873
45232
  if (!current.isFile() || version2(current) !== version2(metadata) || await realpath12(file2) !== resolved) {
@@ -44903,22 +45262,149 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
44903
45262
  }
44904
45263
  }
44905
45264
 
45265
+ // src/bridge/memory-store.ts
45266
+ init_zod();
45267
+ init_protocol();
45268
+ import { execFile as execFile11 } from "node:child_process";
45269
+ import { createHash as createHash15 } from "node:crypto";
45270
+ import { lstat as lstat16, mkdir as mkdir16, readFile as readFile27, realpath as realpath13, rename as rename7, rm as rm8, writeFile as writeFile8 } from "node:fs/promises";
45271
+ import path69 from "node:path";
45272
+ import { promisify as promisify11 } from "node:util";
45273
+ var exec11 = promisify11(execFile11);
45274
+ var SHA = /^[0-9a-f]{40}$/;
45275
+ var MAX_FILE = 4 * 1024 * 1024;
45276
+ var queue = Promise.resolve();
45277
+ function serialized(work) {
45278
+ const next = queue.then(work, work);
45279
+ queue = next.catch(() => void 0);
45280
+ return next;
45281
+ }
45282
+ async function git5(store, args, env = {}) {
45283
+ try {
45284
+ const { stdout } = await exec11("git", ["-C", store, ...args], {
45285
+ env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" },
45286
+ maxBuffer: 64 * 1024 * 1024,
45287
+ timeout: 6e4
45288
+ });
45289
+ return stdout;
45290
+ } catch (error62) {
45291
+ const stderr = String(error62.stderr ?? "").trim();
45292
+ throw new BridgeError(500, `git ${args[0]} failed in the store${stderr ? `: ${stderr.split("\n")[0]}` : "."}`);
45293
+ }
45294
+ }
45295
+ function blobSha(content) {
45296
+ return createHash15("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
45297
+ }
45298
+ async function isRepository2(store) {
45299
+ return await lstat16(path69.join(store, ".git")).catch(() => void 0) !== void 0;
45300
+ }
45301
+ function storeHead(store, indexFile = path69.join(bridgeRoot(), "store-snapshot.index")) {
45302
+ return serialized(async () => {
45303
+ if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
45304
+ await mkdir16(path69.dirname(indexFile), { recursive: true, mode: 448 });
45305
+ const env = { GIT_INDEX_FILE: indexFile };
45306
+ if (!await lstat16(indexFile).catch(() => void 0)) {
45307
+ const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
45308
+ await git5(store, head.trim() ? ["read-tree", "HEAD"] : ["read-tree", "--empty"], env);
45309
+ }
45310
+ await git5(store, ["add", "--all", "--", "."], env);
45311
+ return { sha: (await git5(store, ["write-tree"], env)).trim() };
45312
+ });
45313
+ }
45314
+ async function storeTree(store, sha) {
45315
+ if (!SHA.test(sha)) throw new BridgeError(400, "Invalid tree sha.");
45316
+ if ((await git5(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "tree") throw new BridgeError(404, "Unknown tree.");
45317
+ const tree = (await git5(store, ["ls-tree", "-r", "-l", "-z", sha])).split("\0").filter(Boolean).flatMap((line) => {
45318
+ const match = /^(\d+) (\w+) ([0-9a-f]{40}) +(\d+|-)\t(.+)$/s.exec(line);
45319
+ if (!match || match[2] !== "blob" || match[1] === "120000") return [];
45320
+ return [{ path: match[5], type: "blob", sha: match[3], size: Number(match[4]) }];
45321
+ });
45322
+ return { sha, truncated: false, tree };
45323
+ }
45324
+ async function storeBlob(store, sha) {
45325
+ if (!SHA.test(sha)) throw new BridgeError(400, "Invalid blob sha.");
45326
+ if ((await git5(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "blob") throw new BridgeError(404, "Unknown blob.");
45327
+ const { stdout } = await exec11("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE * 4 });
45328
+ return { sha, encoding: "base64", content: stdout.toString("base64") };
45329
+ }
45330
+ async function storeFile(store, relative3) {
45331
+ const normalized = path69.posix.normalize(relative3);
45332
+ if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path69.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
45333
+ throw new BridgeError(400, "Invalid store path.");
45334
+ }
45335
+ const root = await realpath13(store);
45336
+ let parent = path69.dirname(path69.join(root, normalized));
45337
+ for (; ; ) {
45338
+ const real = await realpath13(parent).catch(() => void 0);
45339
+ if (real) {
45340
+ if (real !== root && !real.startsWith(root + path69.sep)) throw new BridgeError(400, "Invalid store path.");
45341
+ break;
45342
+ }
45343
+ parent = path69.dirname(parent);
45344
+ }
45345
+ const file2 = path69.join(root, normalized);
45346
+ const info = await lstat16(file2).catch(() => void 0);
45347
+ if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
45348
+ return file2;
45349
+ }
45350
+ async function currentSha(file2) {
45351
+ const content = await readFile27(file2).catch((error62) => {
45352
+ if (error62.code === "ENOENT") return null;
45353
+ throw error62;
45354
+ });
45355
+ return content === null ? null : blobSha(content);
45356
+ }
45357
+ var putSchema = external_exports.object({ path: external_exports.string().max(1024), content: external_exports.string(), sha: external_exports.string().regex(SHA).nullable().optional() });
45358
+ var deleteSchema = external_exports.object({ path: external_exports.string().max(1024), sha: external_exports.string().regex(SHA) });
45359
+ function putStoreFile(store, data) {
45360
+ const input2 = putSchema.parse(data);
45361
+ const content = Buffer.from(input2.content, "base64");
45362
+ if (content.length > MAX_FILE) throw new BridgeError(413, "This file is too large for the phone to write.");
45363
+ return serialized(async () => {
45364
+ const file2 = await storeFile(store, input2.path);
45365
+ if (await currentSha(file2) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
45366
+ await mkdir16(path69.dirname(file2), { recursive: true });
45367
+ const temporary = `${file2}.phren-${process.pid}-${Date.now()}`;
45368
+ await writeFile8(temporary, content, { flag: "wx" });
45369
+ await rename7(temporary, file2);
45370
+ return { content: { sha: blobSha(content), path: input2.path }, commit: { sha: blobSha(content) } };
45371
+ });
45372
+ }
45373
+ function deleteStoreFile(store, data) {
45374
+ const input2 = deleteSchema.parse(data);
45375
+ return serialized(async () => {
45376
+ const file2 = await storeFile(store, input2.path);
45377
+ if (await currentSha(file2) !== input2.sha) throw new BridgeError(409, `${input2.path} changed on this computer.`);
45378
+ await rm8(file2);
45379
+ return { ok: true };
45380
+ });
45381
+ }
45382
+ var STORE_ROUTES = { head: "/v1/store/head", tree: "/v1/store/tree", blob: "/v1/store/blob", file: "/v1/store/file", delete: "/v1/store/delete" };
45383
+ async function storeRoute(store, method, url2, data) {
45384
+ if (method === "GET" && url2.pathname === STORE_ROUTES.head) return storeHead(store);
45385
+ if (method === "GET" && url2.pathname === STORE_ROUTES.tree) return storeTree(store, url2.searchParams.get("sha") ?? "");
45386
+ if (method === "GET" && url2.pathname === STORE_ROUTES.blob) return storeBlob(store, url2.searchParams.get("sha") ?? "");
45387
+ if (method === "POST" && url2.pathname === STORE_ROUTES.file) return putStoreFile(store, data ?? {});
45388
+ if (method === "POST" && url2.pathname === STORE_ROUTES.delete) return deleteStoreFile(store, data ?? {});
45389
+ throw new BridgeError(404, "Unknown Phren Hook route.");
45390
+ }
45391
+
44906
45392
  // src/bridge/server-routes.ts
44907
45393
  init_protocol();
44908
45394
 
44909
45395
  // src/bridge/simulators.ts
44910
45396
  init_protocol();
44911
- import { execFile as execFile11 } from "node:child_process";
44912
- import { chmod as chmod4, mkdir as mkdir15, readFile as readFile27, rename as rename7, stat as stat18, unlink as unlink5, writeFile as writeFile8 } from "node:fs/promises";
45397
+ import { execFile as execFile12 } from "node:child_process";
45398
+ import { chmod as chmod4, mkdir as mkdir17, readFile as readFile28, rename as rename8, stat as stat19, unlink as unlink5, writeFile as writeFile9 } from "node:fs/promises";
44913
45399
  import { tmpdir as tmpdir3 } from "node:os";
44914
- import path69 from "node:path";
44915
- import { createHash as createHash15, randomUUID as randomUUID17 } from "node:crypto";
44916
- import { promisify as promisify11 } from "node:util";
44917
- var exec11 = promisify11(execFile11);
45400
+ import path70 from "node:path";
45401
+ import { createHash as createHash16, randomUUID as randomUUID17 } from "node:crypto";
45402
+ import { promisify as promisify12 } from "node:util";
45403
+ var exec12 = promisify12(execFile12);
44918
45404
  var UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
44919
45405
  async function bootedSimulators() {
44920
45406
  if (process.platform !== "darwin") return [];
44921
- const { stdout } = await exec11("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
45407
+ const { stdout } = await exec12("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
44922
45408
  let parsed = {};
44923
45409
  try {
44924
45410
  parsed = JSON.parse(stdout);
@@ -44939,10 +45425,10 @@ async function bootedSimulators() {
44939
45425
  async function simulatorScreenshot(udid) {
44940
45426
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
44941
45427
  if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
44942
- const file2 = path69.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
45428
+ const file2 = path70.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
44943
45429
  try {
44944
- await exec11("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
44945
- return await readFile27(file2);
45430
+ await exec12("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
45431
+ return await readFile28(file2);
44946
45432
  } catch (error62) {
44947
45433
  if (error62 instanceof BridgeError) throw error62;
44948
45434
  throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
@@ -44958,25 +45444,25 @@ function helper() {
44958
45444
  return building;
44959
45445
  }
44960
45446
  async function buildHelper() {
44961
- const dir = path69.join(bridgeRoot(), "native");
44962
- const binary = path69.join(dir, "simtap");
44963
- const code = true ? '// Touches and keys for the iOS Simulator, without AppleScript: the window\n// is found through the Accessibility API and events are posted with CGEvent,\n// so one Accessibility grant for this helper is all macOS asks for.\n// Built on demand by Phren Hook with swiftc; see simulators.ts.\nimport ApplicationServices\nimport Cocoa\n\nfunc fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }\n\nlet args = CommandLine.arguments\nguard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise") }\nlet prefix = args[1], command = args[2]\n\nguard AXIsProcessTrusted() else { fail(3, "accessibility") }\nguard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }\nlet element = AXUIElementCreateApplication(app.processIdentifier)\nvar windowsRef: CFTypeRef?\nAXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)\nlet windows = (windowsRef as? [AXUIElement]) ?? []\nvar target: AXUIElement?\nfor window in windows {\n var titleRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)\n if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }\n}\nguard let window = target else { fail(5, "no window for \\(prefix)") }\n\nfunc frame(_ window: AXUIElement) -> CGRect {\n var posRef: CFTypeRef?, sizeRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)\n AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)\n var pos = CGPoint.zero, size = CGSize.zero\n if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }\n if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }\n return CGRect(origin: pos, size: size)\n}\nfunc raise() {\n app.activate(options: [])\n AXUIElementPerformAction(window, kAXRaiseAction as CFString)\n usleep(120_000)\n}\nfunc post(_ event: CGEvent?) {\n guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }\n event?.postToPid(app.processIdentifier)\n usleep(40_000)\n}\n\nswitch command {\ncase "raise": raise()\ncase "tap":\n guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }\n raise()\n let f = frame(window)\n // The device screen fills the window below its title bar.\n let titleBar: CGFloat = 28\n let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))\n post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))\ncase "key":\n guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }\n raise()\n var flags: CGEventFlags = []\n if args.contains("cmd") { flags.insert(.maskCommand) }\n if args.contains("shift") { flags.insert(.maskShift) }\n let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)\n down?.flags = flags; up?.flags = flags\n post(down); post(up)\ncase "type":\n guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }\n let submit = args.count == 5 && args[4] == "submit"\n guard args[3].unicodeScalars.allSatisfy({ scalar in\n (scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)\n }) else { fail(2, "invalid type controls; newline needs submit") }\n raise()\n for scalar in args[3].unicodeScalars {\n var chars = Array(String(scalar).utf16)\n let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)\n down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n post(down); post(up)\n }\ndefault: fail(2, "unknown command \\(command)")\n}\n' : await readFile27(new URL("./native/simtap.swift", import.meta.url), "utf8");
44964
- const digest2 = createHash15("sha256").update(code).digest("hex");
44965
- const saved = await readFile27(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
44966
- if (await stat18(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
44967
- await mkdir15(dir, { recursive: true, mode: 448 });
44968
- const temporary = path69.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
45447
+ const dir = path70.join(bridgeRoot(), "native");
45448
+ const binary = path70.join(dir, "simtap");
45449
+ const code = true ? '// Touches and keys for the iOS Simulator, without AppleScript: the window\n// is found through the Accessibility API and events are posted with CGEvent,\n// so one Accessibility grant for this helper is all macOS asks for.\n// Built on demand by Phren Hook with swiftc; see simulators.ts.\nimport ApplicationServices\nimport Cocoa\n\nfunc fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }\n\nlet args = CommandLine.arguments\nguard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise") }\nlet prefix = args[1], command = args[2]\n\nguard AXIsProcessTrusted() else { fail(3, "accessibility") }\nguard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }\nlet element = AXUIElementCreateApplication(app.processIdentifier)\nvar windowsRef: CFTypeRef?\nAXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)\nlet windows = (windowsRef as? [AXUIElement]) ?? []\nvar target: AXUIElement?\nfor window in windows {\n var titleRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)\n if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }\n}\nguard let window = target else { fail(5, "no window for \\(prefix)") }\n\nfunc frame(_ window: AXUIElement) -> CGRect {\n var posRef: CFTypeRef?, sizeRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)\n AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)\n var pos = CGPoint.zero, size = CGSize.zero\n if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }\n if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }\n return CGRect(origin: pos, size: size)\n}\nfunc raise() {\n app.activate(options: [])\n AXUIElementPerformAction(window, kAXRaiseAction as CFString)\n usleep(120_000)\n}\nfunc post(_ event: CGEvent?) {\n guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }\n event?.postToPid(app.processIdentifier)\n usleep(40_000)\n}\n\nswitch command {\ncase "raise": raise()\ncase "tap":\n guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }\n raise()\n let f = frame(window)\n // The device screen fills the window below its title bar.\n let titleBar: CGFloat = 28\n let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))\n post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))\ncase "key":\n guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }\n raise()\n var flags: CGEventFlags = []\n if args.contains("cmd") { flags.insert(.maskCommand) }\n if args.contains("shift") { flags.insert(.maskShift) }\n let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)\n down?.flags = flags; up?.flags = flags\n post(down); post(up)\ncase "type":\n guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }\n let submit = args.count == 5 && args[4] == "submit"\n guard args[3].unicodeScalars.allSatisfy({ scalar in\n (scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)\n }) else { fail(2, "invalid type controls; newline needs submit") }\n raise()\n for scalar in args[3].unicodeScalars {\n var chars = Array(String(scalar).utf16)\n let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)\n down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n post(down); post(up)\n }\ndefault: fail(2, "unknown command \\(command)")\n}\n' : await readFile28(new URL("./native/simtap.swift", import.meta.url), "utf8");
45450
+ const digest2 = createHash16("sha256").update(code).digest("hex");
45451
+ const saved = await readFile28(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
45452
+ if (await stat19(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
45453
+ await mkdir17(dir, { recursive: true, mode: 448 });
45454
+ const temporary = path70.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
44969
45455
  const sidecar = temporary + ".sha256";
44970
45456
  try {
44971
- await writeFile8(source, code, { mode: 384, flag: "wx" });
44972
- await exec11("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
45457
+ await writeFile9(source, code, { mode: 384, flag: "wx" });
45458
+ await exec12("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
44973
45459
  throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
44974
45460
  });
44975
45461
  await chmod4(temporary, 448);
44976
- const binarySha = createHash15("sha256").update(await readFile27(temporary)).digest("hex");
44977
- await writeFile8(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
44978
- await rename7(temporary, binary);
44979
- await rename7(sidecar, binary + ".sha256");
45462
+ const binarySha = createHash16("sha256").update(await readFile28(temporary)).digest("hex");
45463
+ await writeFile9(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
45464
+ await rename8(temporary, binary);
45465
+ await rename8(sidecar, binary + ".sha256");
44980
45466
  } finally {
44981
45467
  await Promise.all([source, temporary, sidecar].map((file2) => unlink5(file2).catch(() => void 0)));
44982
45468
  }
@@ -44991,11 +45477,11 @@ function simtap(name, ...args) {
44991
45477
  }
44992
45478
  async function executeSimtap(name, ...args) {
44993
45479
  const binary = await helper();
44994
- const saved = await readFile27(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
44995
- const binarySha = createHash15("sha256").update(await readFile27(binary)).digest("hex");
45480
+ const saved = await readFile28(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
45481
+ const binarySha = createHash16("sha256").update(await readFile28(binary)).digest("hex");
44996
45482
  if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
44997
45483
  try {
44998
- await exec11(binary, [name, ...args], { timeout: 6e4 });
45484
+ await exec12(binary, [name, ...args], { timeout: 6e4 });
44999
45485
  } catch (error62) {
45000
45486
  const failure2 = error62;
45001
45487
  const message = String(failure2?.stderr ?? failure2?.message ?? "");
@@ -45011,7 +45497,7 @@ async function simulatorAct(udid, request6) {
45011
45497
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
45012
45498
  if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready"].includes(request6.action)) throw new BridgeError(400, "Unknown simulator action.");
45013
45499
  if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
45014
- const simctl = (...args) => exec11("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
45500
+ const simctl = (...args) => exec12("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
45015
45501
  throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`);
45016
45502
  });
45017
45503
  switch (request6.action) {
@@ -45060,7 +45546,7 @@ async function deviceName(udid) {
45060
45546
  async function simulatorApps(udid) {
45061
45547
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
45062
45548
  if (process.platform !== "darwin") return [];
45063
- const { stdout } = await exec11("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
45549
+ const { stdout } = await exec12("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
45064
45550
  const apps = [];
45065
45551
  const blocks = stdout.split(/\n(?=\s{4}"[^"]+" =\s+\{)/);
45066
45552
  for (const block of blocks) {
@@ -45076,8 +45562,8 @@ init_transcripts();
45076
45562
 
45077
45563
  // src/bridge/uploads.ts
45078
45564
  init_protocol();
45079
- import { mkdir as mkdir16, readdir as readdir12, lstat as lstat16, realpath as realpath13, readFile as readFile28, stat as stat19, unlink as unlink6, writeFile as writeFile9 } from "node:fs/promises";
45080
- import path70 from "node:path";
45565
+ import { mkdir as mkdir18, readdir as readdir12, lstat as lstat17, realpath as realpath14, readFile as readFile29, stat as stat20, unlink as unlink6, writeFile as writeFile10 } from "node:fs/promises";
45566
+ import path71 from "node:path";
45081
45567
  import { randomUUID as randomUUID18 } from "node:crypto";
45082
45568
  function imageBytes(bytes) {
45083
45569
  return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255])) || /^GIF8[79]a/.test(bytes.subarray(0, 6).toString()) || bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP";
@@ -45090,51 +45576,51 @@ async function saveUpload(session, name, bytes) {
45090
45576
  let saved = "";
45091
45577
  const task = uploadQueue.catch(() => {
45092
45578
  }).then(async () => {
45093
- const root = path70.join(bridgeRoot(), "uploads");
45094
- await mkdir16(root, { recursive: true, mode: 448 });
45579
+ const root = path71.join(bridgeRoot(), "uploads");
45580
+ await mkdir18(root, { recursive: true, mode: 448 });
45095
45581
  let used = 0;
45096
45582
  const directories = await readdir12(root, { withFileTypes: true });
45097
45583
  for (const dir of directories) {
45098
45584
  if (!dir.isDirectory()) continue;
45099
- const folder2 = path70.join(root, dir.name);
45585
+ const folder2 = path71.join(root, dir.name);
45100
45586
  for (const entry of await readdir12(folder2, { withFileTypes: true })) {
45101
45587
  if (!entry.isFile()) continue;
45102
- const file2 = path70.join(folder2, entry.name), metadata = await lstat16(file2);
45588
+ const file2 = path71.join(folder2, entry.name), metadata = await lstat17(file2);
45103
45589
  if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink6(file2);
45104
45590
  else used += metadata.size;
45105
45591
  }
45106
45592
  }
45107
45593
  if (used + bytes.length > 268435456) throw new BridgeError(413, "Phren's image storage is full. Remove older uploads on the computer.");
45108
- const folder = path70.join(root, session);
45109
- await mkdir16(folder, { recursive: true, mode: 448 });
45110
- saved = path70.join(folder, `${randomUUID18()}-${name}`);
45111
- await writeFile9(saved, bytes, { flag: "wx", mode: 384 });
45594
+ const folder = path71.join(root, session);
45595
+ await mkdir18(folder, { recursive: true, mode: 448 });
45596
+ saved = path71.join(folder, `${randomUUID18()}-${name}`);
45597
+ await writeFile10(saved, bytes, { flag: "wx", mode: 384 });
45112
45598
  });
45113
45599
  uploadQueue = task;
45114
45600
  await task;
45115
45601
  return saved;
45116
45602
  }
45117
45603
  async function listUploads(session) {
45118
- const folder = path70.join(bridgeRoot(), "uploads", session);
45604
+ const folder = path71.join(bridgeRoot(), "uploads", session);
45119
45605
  const entries = await readdir12(folder, { withFileTypes: true }).catch(() => []);
45120
45606
  const files = [];
45121
45607
  for (const entry of entries) {
45122
45608
  if (!entry.isFile()) continue;
45123
- const file2 = path70.join(folder, entry.name), metadata = await stat19(file2);
45609
+ const file2 = path71.join(folder, entry.name), metadata = await stat20(file2);
45124
45610
  files.push({ name: entry.name.replace(/^[0-9a-f-]{36}-/, ""), path: file2, size: metadata.size, modified: metadata.mtime.toISOString() });
45125
45611
  }
45126
45612
  return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
45127
45613
  }
45128
45614
  async function uploadImage(requested) {
45129
45615
  const missing = new BridgeError(404, "This image is not one of the phone's uploads.");
45130
- if (!requested || requested.length > 4096 || !path70.isAbsolute(requested)) throw missing;
45131
- const root = await realpath13(path70.join(bridgeRoot(), "uploads")).catch(() => void 0);
45132
- const file2 = await realpath13(requested).catch(() => void 0);
45133
- if (!root || !file2 || !file2.startsWith(root + path70.sep)) throw missing;
45134
- const metadata = await stat19(file2);
45616
+ if (!requested || requested.length > 4096 || !path71.isAbsolute(requested)) throw missing;
45617
+ const root = await realpath14(path71.join(bridgeRoot(), "uploads")).catch(() => void 0);
45618
+ const file2 = await realpath14(requested).catch(() => void 0);
45619
+ if (!root || !file2 || !file2.startsWith(root + path71.sep)) throw missing;
45620
+ const metadata = await stat20(file2);
45135
45621
  if (!metadata.isFile()) throw missing;
45136
45622
  if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
45137
- const bytes = await readFile28(file2);
45623
+ const bytes = await readFile29(file2);
45138
45624
  if (bytes.length > 8388608) throw new BridgeError(413, "This image is too large.");
45139
45625
  if (!imageBytes(bytes)) throw missing;
45140
45626
  return bytes;
@@ -45144,7 +45630,7 @@ async function uploadImage(requested) {
45144
45630
  init_transcript_index();
45145
45631
  init_transcripts();
45146
45632
  import { homedir as homedir17, tmpdir as tmpdir4 } from "node:os";
45147
- import path71 from "node:path";
45633
+ import path72 from "node:path";
45148
45634
  init_protocol();
45149
45635
  var cache = /* @__PURE__ */ new Map();
45150
45636
  var modelCache = /* @__PURE__ */ new Map();
@@ -45282,7 +45768,7 @@ function describe3(tool, args) {
45282
45768
  return "";
45283
45769
  };
45284
45770
  const firstLine = (v) => v.split(/\r?\n/).map((l) => l.trim()).find((l) => l) ?? "";
45285
- const base = (v) => path71.basename(v.split(" \xB7 ")[0].trim()) || "file";
45771
+ const base = (v) => path72.basename(v.split(" \xB7 ")[0].trim()) || "file";
45286
45772
  const name = tool.toLowerCase();
45287
45773
  let value2;
45288
45774
  if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
@@ -45317,17 +45803,17 @@ init_shared();
45317
45803
 
45318
45804
  // src/bridge/server-pane-routes.ts
45319
45805
  init_zod();
45320
- import path74 from "node:path";
45806
+ import path75 from "node:path";
45321
45807
  import { setTimeout as sleep2 } from "node:timers/promises";
45322
45808
 
45323
45809
  // src/bridge/git.ts
45324
45810
  init_protocol();
45325
- import { createHash as createHash16 } from "node:crypto";
45326
- import { execFile as execFile12 } from "node:child_process";
45327
- import { lstat as lstat17, readdir as readdir13, readFile as readFile29, realpath as realpath14, stat as stat20 } from "node:fs/promises";
45328
- import path72 from "node:path";
45329
- import { promisify as promisify12 } from "node:util";
45330
- var exec12 = promisify12(execFile12);
45811
+ import { createHash as createHash17 } from "node:crypto";
45812
+ import { execFile as execFile13 } from "node:child_process";
45813
+ import { lstat as lstat18, readdir as readdir13, readFile as readFile30, realpath as realpath15, stat as stat21 } from "node:fs/promises";
45814
+ import path73 from "node:path";
45815
+ import { promisify as promisify13 } from "node:util";
45816
+ var exec13 = promisify13(execFile13);
45331
45817
  function statusLetter(code) {
45332
45818
  const letter = code[0];
45333
45819
  return ["M", "A", "D", "R", "C", "U"].includes(letter) ? letter : "M";
@@ -45371,9 +45857,9 @@ function parseNumstat(out) {
45371
45857
  }
45372
45858
  async function countLines(root, rel) {
45373
45859
  try {
45374
- const abs = path72.join(root, await repositoryPath(root, rel));
45375
- if ((await stat20(abs)).size > 5e6) return 0;
45376
- const bytes = await readFile29(abs);
45860
+ const abs = path73.join(root, await repositoryPath(root, rel));
45861
+ if ((await stat21(abs)).size > 5e6) return 0;
45862
+ const bytes = await readFile30(abs);
45377
45863
  if (!bytes.length || bytes.includes(0)) return 0;
45378
45864
  let lines = 0;
45379
45865
  for (const byte of bytes) if (byte === 10) lines++;
@@ -45539,7 +46025,7 @@ function checkRollup(items) {
45539
46025
  }
45540
46026
  async function currentPull(root, branch) {
45541
46027
  try {
45542
- const { stdout } = await exec12("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
46028
+ const { stdout } = await exec13("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
45543
46029
  cwd: root,
45544
46030
  timeout: 15e3,
45545
46031
  maxBuffer: 4194304,
@@ -45566,7 +46052,7 @@ async function gitPulls(cwd) {
45566
46052
  const branch = (await git2(root, "branch", "--show-current").catch(() => "")).trim();
45567
46053
  try {
45568
46054
  const [{ stdout }, current] = await Promise.all([
45569
- exec12("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
46055
+ exec13("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
45570
46056
  cwd: root,
45571
46057
  timeout: 15e3,
45572
46058
  maxBuffer: 4194304,
@@ -45595,31 +46081,31 @@ async function gitPulls(cwd) {
45595
46081
  }
45596
46082
  }
45597
46083
  async function repositoryPath(root, raw, allowRoot = false) {
45598
- if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path72.isAbsolute(raw) || path72.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
46084
+ if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path73.isAbsolute(raw) || path73.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
45599
46085
  const segments = raw.split(/[\\/]/);
45600
46086
  if (segments.includes("..")) throw new BridgeError(400, "Invalid path.");
45601
- const clean = segments.filter((part) => part && part !== ".").join("/");
45602
- if (!clean && !allowRoot || clean.startsWith("-")) throw new BridgeError(400, "Invalid path.");
45603
- const abs = path72.resolve(root, clean);
45604
- if (abs !== root && !abs.startsWith(root + path72.sep)) throw new BridgeError(403, "This path is outside the repository.");
46087
+ const clean2 = segments.filter((part) => part && part !== ".").join("/");
46088
+ if (!clean2 && !allowRoot || clean2.startsWith("-")) throw new BridgeError(400, "Invalid path.");
46089
+ const abs = path73.resolve(root, clean2);
46090
+ if (abs !== root && !abs.startsWith(root + path73.sep)) throw new BridgeError(403, "This path is outside the repository.");
45605
46091
  let existing = abs;
45606
46092
  while (true) {
45607
46093
  try {
45608
- await lstat17(existing);
46094
+ await lstat18(existing);
45609
46095
  break;
45610
46096
  } catch (error62) {
45611
46097
  if (error62.code !== "ENOENT" || existing === root) throw new BridgeError(400, "Invalid path.");
45612
- existing = path72.dirname(existing);
46098
+ existing = path73.dirname(existing);
45613
46099
  }
45614
46100
  }
45615
46101
  let resolved;
45616
46102
  try {
45617
- resolved = await realpath14(existing);
46103
+ resolved = await realpath15(existing);
45618
46104
  } catch {
45619
46105
  throw new BridgeError(403, "This path cannot be resolved inside the repository.");
45620
46106
  }
45621
- if (resolved !== root && !resolved.startsWith(root + path72.sep)) throw new BridgeError(403, "This path is outside the repository.");
45622
- return clean;
46107
+ if (resolved !== root && !resolved.startsWith(root + path73.sep)) throw new BridgeError(403, "This path is outside the repository.");
46108
+ return clean2;
45623
46109
  }
45624
46110
  var treeCache = /* @__PURE__ */ new Map();
45625
46111
  function invalidateTree(root) {
@@ -45631,7 +46117,7 @@ async function treeSnapshot(root, head) {
45631
46117
  git2(root, "ls-files", "-z"),
45632
46118
  git2(root, "status", "--porcelain=v1", "-z", "--untracked-files=all")
45633
46119
  ]);
45634
- const changed = /* @__PURE__ */ new Map();
46120
+ const changed2 = /* @__PURE__ */ new Map();
45635
46121
  const files = new Set(tracked.split("\0").filter(Boolean));
45636
46122
  const tokens = porcelain.split("\0");
45637
46123
  for (let i = 0; i < tokens.length; i++) {
@@ -45639,7 +46125,7 @@ async function treeSnapshot(root, head) {
45639
46125
  if (!row) continue;
45640
46126
  const xy = row.slice(0, 2), file2 = row.slice(3);
45641
46127
  const letter = xy === "??" ? "?" : statusLetter(xy[1] !== " " ? xy[1] : xy[0]);
45642
- changed.set(file2, letter);
46128
+ changed2.set(file2, letter);
45643
46129
  files.add(file2);
45644
46130
  if (/[RC]/.test(xy)) i++;
45645
46131
  }
@@ -45664,12 +46150,12 @@ async function treeSnapshot(root, head) {
45664
46150
  }
45665
46151
  if (directory) {
45666
46152
  entry.fileCount = (entry.fileCount ?? 0) + 1;
45667
- if (changed.has(file2)) entry.status = "changed";
45668
- } else if (changed.has(file2)) entry.status = entry.kind === "dir" ? "changed" : changed.get(file2);
46153
+ if (changed2.has(file2)) entry.status = "changed";
46154
+ } else if (changed2.has(file2)) entry.status = entry.kind === "dir" ? "changed" : changed2.get(file2);
45669
46155
  parent = full2;
45670
46156
  }
45671
46157
  }
45672
- const version3 = createHash16("sha256").update(head).update(tracked).update(porcelain).digest("hex");
46158
+ const version3 = createHash17("sha256").update(head).update(tracked).update(porcelain).digest("hex");
45673
46159
  return { version: version3, levels: new Map([...levels].map(([directory, entries]) => [
45674
46160
  directory,
45675
46161
  [...entries.values()].sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "dir" ? -1 : 1)
@@ -45700,7 +46186,7 @@ async function ignoredEntries(root, prefix, shown) {
45700
46186
  const entries = /* @__PURE__ */ new Map();
45701
46187
  const inside = prefix && listing.some((item) => item.endsWith("/") && (prefix + "/").startsWith(item));
45702
46188
  if (inside) {
45703
- const dirents = await readdir13(path72.join(root, prefix), { withFileTypes: true }).catch(() => []);
46189
+ const dirents = await readdir13(path73.join(root, prefix), { withFileTypes: true }).catch(() => []);
45704
46190
  for (const dirent of dirents) {
45705
46191
  if (dirent.name === ".git" || taken.has(dirent.name) || entries.size >= MAX_IGNORED_ENTRIES) continue;
45706
46192
  entries.set(dirent.name, { name: dirent.name, path: `${prefix}/${dirent.name}`, kind: dirent.isDirectory() ? "dir" : "file", ignored: true });
@@ -45745,8 +46231,8 @@ async function repositoryPaths(root, raw) {
45745
46231
  if (!list.length || list.length > 64) throw new BridgeError(400, "Choose between 1 and 64 paths.");
45746
46232
  const paths = [];
45747
46233
  for (const entry of list) {
45748
- const clean = await repositoryPath(root, entry);
45749
- if (clean && !paths.includes(clean)) paths.push(clean);
46234
+ const clean2 = await repositoryPath(root, entry);
46235
+ if (clean2 && !paths.includes(clean2)) paths.push(clean2);
45750
46236
  }
45751
46237
  if (!paths.length) throw new BridgeError(400, "Choose between 1 and 64 paths.");
45752
46238
  return paths;
@@ -45796,14 +46282,14 @@ init_fanouts();
45796
46282
 
45797
46283
  // src/bridge/git-worktrees.ts
45798
46284
  init_protocol();
45799
- import { createHash as createHash17 } from "node:crypto";
45800
- import { realpath as realpath15, stat as stat21 } from "node:fs/promises";
46285
+ import { createHash as createHash18 } from "node:crypto";
46286
+ import { realpath as realpath16, stat as stat22 } from "node:fs/promises";
45801
46287
  import { homedir as homedir18 } from "node:os";
45802
- import path73 from "node:path";
46288
+ import path74 from "node:path";
45803
46289
  var MAX_WORKTREES = 64;
45804
46290
  var worktreeIdPattern = /^[a-f0-9]{32}$/;
45805
46291
  function worktreeId(abs) {
45806
- return createHash17("sha256").update(`worktree\0${abs}`).digest("hex").slice(0, 32);
46292
+ return createHash18("sha256").update(`worktree\0${abs}`).digest("hex").slice(0, 32);
45807
46293
  }
45808
46294
  async function listed(root) {
45809
46295
  const output2 = await git2(root, "worktree", "list", "--porcelain");
@@ -45827,8 +46313,8 @@ async function listed(root) {
45827
46313
  let main;
45828
46314
  for (const [index2, block] of blocks.entries()) {
45829
46315
  if (block.bare !== void 0 || block.prunable !== void 0) continue;
45830
- const abs = await realpath15(block.worktree).catch(() => void 0);
45831
- if (!abs || !(await stat21(abs).catch(() => void 0))?.isDirectory()) continue;
46316
+ const abs = await realpath16(block.worktree).catch(() => void 0);
46317
+ if (!abs || !(await stat22(abs).catch(() => void 0))?.isDirectory()) continue;
45832
46318
  if (index2 === 0) main = abs;
45833
46319
  const branch = block.branch?.startsWith("refs/heads/") ? block.branch.slice("refs/heads/".length) : null;
45834
46320
  worktrees.push({ abs, head: block.HEAD ?? "", branch, locked: block.locked !== void 0 });
@@ -45838,11 +46324,11 @@ async function listed(root) {
45838
46324
  }
45839
46325
  function displayPath(abs, roots) {
45840
46326
  for (const root of roots) {
45841
- const rel = path73.relative(root, abs);
45842
- if (rel && !rel.startsWith("..") && !path73.isAbsolute(rel)) return rel.split(path73.sep).join("/");
46327
+ const rel = path74.relative(root, abs);
46328
+ if (rel && !rel.startsWith("..") && !path74.isAbsolute(rel)) return rel.split(path74.sep).join("/");
45843
46329
  }
45844
46330
  const home = homedir18();
45845
- return abs === home ? "~" : abs.startsWith(home + path73.sep) ? "~/" + path73.relative(home, abs).split(path73.sep).join("/") : abs;
46331
+ return abs === home ? "~" : abs.startsWith(home + path74.sep) ? "~/" + path74.relative(home, abs).split(path74.sep).join("/") : abs;
45846
46332
  }
45847
46333
  function uncommitted(status) {
45848
46334
  const tokens = status.split("\0");
@@ -45856,12 +46342,12 @@ function uncommitted(status) {
45856
46342
  return count2;
45857
46343
  }
45858
46344
  async function workerFor(abs, workers, all = []) {
45859
- const nested = all.filter((other) => other.startsWith(abs + path73.sep));
46345
+ const nested = all.filter((other) => other.startsWith(abs + path74.sep));
45860
46346
  let best;
45861
46347
  for (const worker of workers) {
45862
- const cwd = await realpath15(worker.cwd).catch(() => path73.resolve(worker.cwd));
45863
- if (cwd !== abs && !cwd.startsWith(abs + path73.sep)) continue;
45864
- if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path73.sep))) continue;
46348
+ const cwd = await realpath16(worker.cwd).catch(() => path74.resolve(worker.cwd));
46349
+ if (cwd !== abs && !cwd.startsWith(abs + path74.sep)) continue;
46350
+ if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path74.sep))) continue;
45865
46351
  const score = (cwd === abs ? 2 : 0) + (worker.child ? 1 : 0);
45866
46352
  if (!best || score > best.score) best = { worker, score };
45867
46353
  }
@@ -45886,7 +46372,7 @@ async function gitWorktrees(cwd, workers = []) {
45886
46372
  behind = 0;
45887
46373
  }
45888
46374
  }
45889
- const changed = uncommitted(await git2(worktree.abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal").catch(() => ""));
46375
+ const changed2 = uncommitted(await git2(worktree.abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal").catch(() => ""));
45890
46376
  const worker = await workerFor(worktree.abs, workers, worktrees.map((item) => item.abs));
45891
46377
  return {
45892
46378
  id: worktreeId(worktree.abs),
@@ -45895,7 +46381,7 @@ async function gitWorktrees(cwd, workers = []) {
45895
46381
  head: worktree.head,
45896
46382
  ahead,
45897
46383
  behind,
45898
- changed,
46384
+ changed: changed2,
45899
46385
  ...worktree.abs === main ? { main: true } : {},
45900
46386
  ...worktree.locked ? { locked: true } : {},
45901
46387
  ...worker ? { worker: {
@@ -46048,11 +46534,11 @@ async function gitPullRequest(cwd, draft) {
46048
46534
 
46049
46535
  // src/bridge/session-servers.ts
46050
46536
  init_protocol();
46051
- import { execFile as execFile13 } from "node:child_process";
46052
- import { open as open12, stat as stat22 } from "node:fs/promises";
46053
- import { promisify as promisify13 } from "node:util";
46537
+ import { execFile as execFile14 } from "node:child_process";
46538
+ import { open as open13, stat as stat23 } from "node:fs/promises";
46539
+ import { promisify as promisify14 } from "node:util";
46054
46540
  init_transcripts();
46055
- var exec13 = promisify13(execFile13);
46541
+ var exec14 = promisify14(execFile14);
46056
46542
  var MAX_DEPTH = 64;
46057
46543
  var TRANSCRIPT_TAIL_BYTES = 1048576;
46058
46544
  var MAX_OTHER_PANES = 48;
@@ -46084,7 +46570,7 @@ function attributeServers(input2) {
46084
46570
  return result.sort((a, b) => Number(a.source === "mentioned") - Number(b.source === "mentioned") || a.port - b.port);
46085
46571
  }
46086
46572
  async function processTable(session) {
46087
- const { stdout } = await exec13("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4e3, maxBuffer: 16777216 });
46573
+ const { stdout } = await exec14("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4e3, maxBuffer: 16777216 });
46088
46574
  const parents = /* @__PURE__ */ new Map();
46089
46575
  const runners = [];
46090
46576
  const flag = `--session-id ${session}`;
@@ -46107,12 +46593,12 @@ async function paneRoots(server, paneId) {
46107
46593
  }
46108
46594
  async function transcriptHolders(file2) {
46109
46595
  const lsof = process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof";
46110
- const { stdout } = await exec13(lsof, ["-t", "--", file2], { timeout: 3e3 }).catch(() => ({ stdout: "" }));
46596
+ const { stdout } = await exec14(lsof, ["-t", "--", file2], { timeout: 3e3 }).catch(() => ({ stdout: "" }));
46111
46597
  return stdout.split("\n").map(Number).filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid);
46112
46598
  }
46113
46599
  async function transcriptTail(file2) {
46114
- const size = (await stat22(file2)).size;
46115
- const handle = await open12(file2, "r");
46600
+ const size = (await stat23(file2)).size;
46601
+ const handle = await open13(file2, "r");
46116
46602
  try {
46117
46603
  const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
46118
46604
  const buffer = Buffer.alloc(length);
@@ -46187,7 +46673,7 @@ function herdrWorktreeWorkers(s) {
46187
46673
  const workers = [];
46188
46674
  for (const pane of objects(s.panes)) {
46189
46675
  const cwd = pane.foreground_cwd || pane.cwd;
46190
- if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path74.isAbsolute(cwd)) continue;
46676
+ if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path75.isAbsolute(cwd)) continue;
46191
46677
  const name = paneAgentName(s, pane);
46192
46678
  workers.push({
46193
46679
  cwd,
@@ -46200,6 +46686,27 @@ function herdrWorktreeWorkers(s) {
46200
46686
  }
46201
46687
  var ANSWER_KEYS = ["Escape", "Enter", "Up", "Down", "Tab", "AltUp", "y", "n", "p", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
46202
46688
  var HERDR_KEYS = { Escape: "esc", Enter: "enter", Up: "up", Down: "down", Tab: "tab", AltUp: "alt+Up" };
46689
+ var questionText = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
46690
+ var claudeQuestionBody = external_exports.object({
46691
+ questions: external_exports.array(external_exports.object({ question: questionText, multiSelect: external_exports.boolean().optional(), options: external_exports.array(questionText).min(1).max(8) })).min(1).max(8),
46692
+ answers: external_exports.array(external_exports.object({
46693
+ optionIndexes: external_exports.array(external_exports.number().int().nonnegative()).max(8),
46694
+ text: external_exports.string().max(1e3).refine((t) => !/[\x00-\x1f\x7f]/.test(t)).optional()
46695
+ })).min(1).max(8)
46696
+ });
46697
+ function claudeQuestionAnswer(data) {
46698
+ const body2 = claudeQuestionBody.parse(data);
46699
+ if (body2.answers.length !== body2.questions.length) throw new BridgeError(400, "Answer every question.");
46700
+ const answers = body2.answers.map((answer, index2) => {
46701
+ const question2 = body2.questions[index2], options = [...new Set(answer.optionIndexes)], text3 = answer.text?.trim() ?? "";
46702
+ if (options.some((option) => option >= question2.options.length)) throw new BridgeError(400, "Choose an available answer.");
46703
+ if (question2.multiSelect ? !options.length && !text3 : options.length + (text3 ? 1 : 0) !== 1) {
46704
+ throw new BridgeError(400, question2.multiSelect ? "Choose at least one answer." : "Choose one answer for each question.");
46705
+ }
46706
+ return { options, ...text3 ? { text: text3 } : {} };
46707
+ });
46708
+ return { questions: body2.questions.map((q) => ({ question: q.question, multiSelect: q.multiSelect, options: q.options.map((label2) => ({ label: label2 })) })), answers };
46709
+ }
46203
46710
  var secretText = external_exports.string().min(1).max(256).refine((t) => !/[\x00-\x1f\x7f]/.test(t));
46204
46711
  async function resubmitIfIdle(agentHooks, target, text3) {
46205
46712
  const status = async () => {
@@ -46381,10 +46888,11 @@ async function paneRoute(ctx, url2, data, response) {
46381
46888
  const keys = external_exports.array(external_exports.enum(ANSWER_KEYS)).min(1).max(4).parse(data.keys);
46382
46889
  const status = String(pane.agent_status), menu = agentHooks.menuOpen(target);
46383
46890
  const holding = menu || !!agentHooks.terminalPrompt(target);
46384
- if (!holding && (keys.every((key) => key === "Escape") ? !["working", "blocked", "waiting", "unknown"].includes(status) : !["blocked", "waiting", "unknown"].includes(status))) throw new BridgeError(409, keys.every((key) => key === "Escape") ? "This agent is no longer working." : "This agent is not waiting for an answer.");
46385
- const question2 = agentHooks.questionAnswerKeys(target, keys);
46386
- if (question2) {
46387
- await rpc(target.server, "agent.send_keys", { target: target.pane, keys: question2.map((key) => HERDR_KEYS[key] ?? key) });
46891
+ const cancelled = keys.every((key) => key === "Escape") && agentHooks.cancelHeldQuestion(target);
46892
+ if (!cancelled && !holding && (keys.every((key) => key === "Escape") ? !["working", "blocked", "waiting", "unknown"].includes(status) : !["blocked", "waiting", "unknown"].includes(status))) throw new BridgeError(409, keys.every((key) => key === "Escape") ? "This agent is no longer working." : "This agent is not waiting for an answer.");
46893
+ if (cancelled) {
46894
+ result = { ok: true };
46895
+ } else if (await agentHooks.answerReleasedQuestion(target, keys)) {
46388
46896
  result = { ok: true };
46389
46897
  } else {
46390
46898
  const answerKeys = await agentHooks.dialogAnswerKeys(target, keys);
@@ -46458,7 +46966,10 @@ async function paneRoute(ctx, url2, data, response) {
46458
46966
  await agentHooks.answer(target, actionId, data.decision, data.updatedInput);
46459
46967
  result = { ok: true };
46460
46968
  } else if (url2.pathname === "/v1/questions/answer") {
46461
- await codexQuestions.answer(target, data);
46969
+ if (target.source === "claude") {
46970
+ const { questions, answers } = claudeQuestionAnswer(data);
46971
+ await agentHooks.answerClaudeQuestions(target, questions, answers);
46972
+ } else await codexQuestions.answer(target, data);
46462
46973
  result = { ok: true };
46463
46974
  } else throw new BridgeError(404, "Unknown Phren Hook route.");
46464
46975
  }
@@ -46466,8 +46977,8 @@ async function paneRoute(ctx, url2, data, response) {
46466
46977
  }
46467
46978
 
46468
46979
  // src/bridge/server-launch.ts
46469
- import { mkdir as mkdir18, readFile as readFile30 } from "node:fs/promises";
46470
- import path76 from "node:path";
46980
+ import { mkdir as mkdir20, readFile as readFile31 } from "node:fs/promises";
46981
+ import path77 from "node:path";
46471
46982
  init_zod();
46472
46983
  init_home_paths();
46473
46984
 
@@ -46475,15 +46986,15 @@ init_home_paths();
46475
46986
  init_zod();
46476
46987
  init_utils_helpers();
46477
46988
  init_metrics();
46478
- import { execFile as execFile14 } from "node:child_process";
46479
- import { mkdir as mkdir17, realpath as realpath16, rm as rm8, stat as stat23 } from "node:fs/promises";
46480
- import path75 from "node:path";
46481
- import { promisify as promisify14 } from "node:util";
46989
+ import { execFile as execFile15 } from "node:child_process";
46990
+ import { mkdir as mkdir19, realpath as realpath17, rm as rm9, stat as stat24 } from "node:fs/promises";
46991
+ import path76 from "node:path";
46992
+ import { promisify as promisify15 } from "node:util";
46482
46993
  init_protocol();
46483
- var exec14 = promisify14(execFile14);
46484
- async function git5(cwd, ...args) {
46994
+ var exec15 = promisify15(execFile15);
46995
+ async function git6(cwd, ...args) {
46485
46996
  countGit("launch-worktree");
46486
- return (await exec14("git", ["-C", cwd, "--no-pager", ...args], {
46997
+ return (await exec15("git", ["-C", cwd, "--no-pager", ...args], {
46487
46998
  timeout: 12e4,
46488
46999
  maxBuffer: 1048576,
46489
47000
  env: nonInteractiveGitEnv({ ...process.env, GIT_CONFIG_NOSYSTEM: "1" })
@@ -46498,38 +47009,58 @@ async function createLaunchWorktree(cwd, request6) {
46498
47009
  const branch = request6.branch;
46499
47010
  const root = await gitRoot(cwd);
46500
47011
  if (!root) throw new BridgeError(409, "This folder is not a Git repository, so it cannot have a worktree. Turn off Work in a new worktree or choose a repository.");
46501
- const head = (await git5(root, "rev-parse", "--verify", "--quiet", "HEAD^{commit}").catch(() => "")).trim();
47012
+ const head = (await git6(root, "rev-parse", "--verify", "--quiet", "HEAD^{commit}").catch(() => "")).trim();
46502
47013
  if (!head) throw new BridgeError(409, "This repository has no commits yet, so there is no HEAD to start a worktree from.");
46503
- if (!await git5(root, "check-ref-format", "--branch", branch).then(() => true, () => false)) {
47014
+ if (!await git6(root, "check-ref-format", "--branch", branch).then(() => true, () => false)) {
46504
47015
  throw new BridgeError(400, `"${branch}" is not a valid Git branch name.`);
46505
47016
  }
46506
- if (await git5(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
47017
+ if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
46507
47018
  throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
46508
47019
  }
46509
- const worktree = path75.join(root, ".claude", "worktrees", worktreeFolderName(branch));
46510
- if (await stat23(worktree).then(() => true, () => false)) {
47020
+ const worktree = path76.join(root, ".claude", "worktrees", worktreeFolderName(branch));
47021
+ if (await stat24(worktree).then(() => true, () => false)) {
46511
47022
  throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
46512
47023
  }
46513
- await mkdir17(path75.dirname(worktree), { recursive: true });
47024
+ await mkdir19(path76.dirname(worktree), { recursive: true });
46514
47025
  try {
46515
- await git5(root, "worktree", "add", "-b", branch, worktree, head);
47026
+ await git6(root, "worktree", "add", "-b", branch, worktree, head);
46516
47027
  } catch (error62) {
46517
47028
  const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").at(-1) : "";
46518
47029
  throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
46519
47030
  }
46520
- const abs = await realpath16(worktree);
46521
- const inside = path75.relative(root, await realpath16(cwd));
46522
- const start = inside && !inside.startsWith("..") ? path75.join(abs, inside) : abs;
46523
- const startDir = await stat23(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
47031
+ const abs = await realpath17(worktree);
47032
+ const inside = path76.relative(root, await realpath17(cwd));
47033
+ const start = inside && !inside.startsWith("..") ? path76.join(abs, inside) : abs;
47034
+ const startDir = await stat24(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
46524
47035
  return {
46525
47036
  cwd: startDir,
46526
47037
  path: abs,
46527
47038
  branch,
46528
47039
  async discard() {
46529
- await git5(root, "worktree", "remove", "--force", abs).catch(() => rm8(abs, { recursive: true, force: true }));
46530
- await git5(root, "worktree", "prune").catch(() => void 0);
46531
- await git5(root, "branch", "-D", branch).catch(() => void 0);
47040
+ await git6(root, "worktree", "remove", "--force", abs).catch(() => rm9(abs, { recursive: true, force: true }));
47041
+ await git6(root, "worktree", "prune").catch(() => void 0);
47042
+ await git6(root, "branch", "-D", branch).catch(() => void 0);
47043
+ }
47044
+ };
47045
+ }
47046
+
47047
+ // src/bridge/conductor-group.ts
47048
+ init_protocol();
47049
+ async function groupConductor(peers, ask = peerRequest) {
47050
+ const answers = await Promise.all(peers.map(async (peer) => {
47051
+ try {
47052
+ const conductor = (await ask(peer, "/v1/conductor", void 0, 8e3)).conductor;
47053
+ return { peer, conductor: conductor && typeof conductor === "object" ? object2(conductor) : void 0 };
47054
+ } catch (error62) {
47055
+ if (error62 instanceof BridgeError && error62.status === 404 && error62.message === disabledHint("conductor")) return { peer };
47056
+ const message = error62 instanceof BridgeError && error62.status === 404 ? "Its Hook is too old to report a conductor." : error62 instanceof Error ? error62.message : "Unreachable.";
47057
+ return { peer, error: message };
46532
47058
  }
47059
+ }));
47060
+ const hit = answers.find((answer) => answer.conductor);
47061
+ return {
47062
+ ...hit ? { found: { computer: hit.peer.name, ...hit.conductor.target ? { target: object2(hit.conductor.target) } : {} } } : {},
47063
+ unchecked: answers.flatMap((answer) => "error" in answer && answer.error ? [{ computer: answer.peer.name, error: answer.error }] : [])
46533
47064
  };
46534
47065
  }
46535
47066
 
@@ -46539,14 +47070,14 @@ var launchKinds = ["codex", "claude", "copilot", "opencode"];
46539
47070
  var plainText = (max) => external_exports.string().min(1).max(max).refine((t) => !/[\x00-\x1f\x7f]/.test(t));
46540
47071
  async function conductorBrief() {
46541
47072
  let source;
46542
- if (true) source = "---\nname: conductor\ndescription: Coordinate independent Phren tasks across every project in the store and every enrolled computer, supervise their local agent fanout, and integrate verified returns in a concise dispatcher voice.\n---\n\n# Conductor\n\nYou are the owner's dispatcher for the whole store, not one project. You start\nin the phren store itself; that folder is not a project and not your work.\n\nFirst, before trusting your tools, check which phren you are running:\n`phren --version` and `command -v phren`. If the version is older than the one\nthe store or the owner expects, or the path is not the install you expect (a\nstale global package, an old checkout), tell the owner in one line and say\nwhich tools may be missing or behave differently.\n\nThen read the relevant projects' summaries and Phren tasks\n(`get_project_summary`, `get_tasks`) before selecting work.\n\nYour tools, use these instead of exploring the CLI or the Hook's files:\n\n- `live_sessions` (CLI `phren dispatch sessions`): every live agent on this\n computer and each enrolled one, with project, harness, status, `idleFor`\n (seconds since it last changed) and the target `hand_off` takes. Start here\n when asked what is running. Computers it could not reach are listed; say so\n rather than guessing. Computers in `notLinked` are registered in the store\n but have no Hook link here: say they were not checked, never that nothing is\n running there.\n- `hand_off`: send a prompt to one of those sessions.\n- `dispatch`: start a new worker on a computer (or `anywhere`).\n- `dispatch_returns` (CLI `phren dispatch returns`): what your workers sent\n back since you last asked: done with the final reply, needs-you with the\n question, failed with the error (a usage limit), blocked, or gone. Reading them marks them read. In core use\n `phren_admin(action: \"dispatch_returns\")`.\n- `phren dispatch status`: receipts of what you dispatched.\n- `get_tasks`, `get_project_summary`, `search_knowledge`: the store's memory.\n\nKeep\nengineering detail in worker briefs and review artifacts. In the owner's chat,\nwrite one short line per dispatch and one per return:\n\n```text\nLinuxbox: parser checks sent to Codex (configured default); report due 14:20 PT.\nDesk: navigation checks returned; tests passed; not merged.\n```\n\nInclude computer, brief, harness/model, and the next expected report time on a\ndispatch. Include who finished what, test result and merged/not merged on a\nreturn. If a result or deadline is unknown, say so. Surface questions in the same\nshort voice with the worker's choices; do not turn the chat into code commentary.\n\nPick five to ten independent tasks when that many are available and capacity\npermits. Do not manufacture tasks to fill the batch. Separate dependencies and\nfile ownership; give each remote lead a base revision, acceptance checks, local\nfanout limit, report time and integration instructions. Every brief repeats the\nowner's repository constraints, including any prohibition on commits, pushes,\nbranches or particular tests. Dispatch never expands the owner's authorization.\n\nPrefer Codex. Use OpenCode Go when its account and harness are connected. Use\nOpenRouter only when the owner explicitly requests it; an unavailable account\ndoes not authorize another paid provider. Name an explicit model when instructed,\notherwise use and report the remote configured default. Each remote lead owns\nits local checkouts, fanout and provider rate limits. Where installed, local\nworkers use the fanout wrapper's `scripts/run.sh --provider codex|opencode\n--label --worktree [--model] [--mode]` contract and parent-bound manifests.\n\nPrefer handing work to a session that already owns the project and is idle or\ndoing related work; call `hand_off` in full or `phren_admin(action: \"hand_off\",\ncomputer?, target|session, text)` in core. Otherwise dispatch a new worker.\nWrite one short line either way. Call `dispatch` in full or\n`phren_admin(action: \"dispatch\", computer, project, harness, model?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>]`.\n`anywhere` chooses the connected computer with the fewest working agents. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\n`accepted` on a receipt is prompt acceptance, not worker completion. Returns\narrive on their own: the Hook follows every worker you dispatch, and when you\nare idle it types one line into this session, such as `Return: Linuxbox parser\nchecks done, tests passed (dispatch <id>). Call dispatch_returns.` When you see\none, call `dispatch_returns` and report each return in one short line. You may\nalso call it whenever you want the current state; do not poll it in a loop, and\ndo not read remote transcripts by hand to learn whether a worker finished. Tell\nthe owner a return time as an expectation, not a promise.\n\nFor a `needs-you` return, surface the worker's question in the owner's chat\nwith its choices as the worker wrote them; do not rewrite or answer it for the\nowner unless the owner already decided. Send the answer back with `hand_off`\nto the row's `target`. A `blocked` worker waits on terminal input, such as a\npermission prompt: say so and point the owner to the phone or the terminal. A\n`gone` worker's pane closed or was taken over: say so, and decide with the\nowner before giving its work to another agent. A `done` reply is the worker's\nown account; check its evidence before saying tests passed or work merged.\n\nAn uncertain delivery is never retried automatically. Inspect its known target\nor status before deciding with the owner whether a replacement is needed. Keep\nunavailable workers visible instead of giving their work to another agent\nwhile the original may still be running.\n\nIntegrate returned changes in dependency order within the owner's allowed\nworkflow. Run a cleanup pass across the combined result and the affected checks.\nRequire evidence before saying tests passed or merged. Ship only within existing\nauthorization; if publication is not authorized, return the reviewable result.\nUpdate Phren tasks when verified complete and save durable decisions. A worker's\nfinished turn alone does not complete the owner's task.\n";
47073
+ if (true) source = "---\nname: conductor\ndescription: Coordinate independent Phren tasks across every project in the store and every enrolled computer, supervise their local agent fanout, and integrate verified returns in a concise dispatcher voice.\n---\n\n# Conductor\n\nYou are the owner's dispatcher for the whole store, not one project. You start\nin the phren store itself; that folder is not a project and not your work.\n\nFirst, before trusting your tools, check which phren you are running:\n`phren --version` and `command -v phren`. If the version is older than the one\nthe store or the owner expects, or the path is not the install you expect (a\nstale global package, an old checkout), tell the owner in one line and say\nwhich tools may be missing or behave differently.\n\nThen read the relevant projects' summaries and Phren tasks\n(`get_project_summary`, `get_tasks`) before selecting work.\n\nYour tools, use these instead of exploring the CLI or the Hook's files:\n\n- `live_sessions` (CLI `phren dispatch sessions`): every live agent on this\n computer and each enrolled one, with project, harness, status, `idleFor`\n (seconds since it last changed) and the target `hand_off` takes. Start here\n when asked what is running. Computers it could not reach are listed; say so\n rather than guessing. Computers in `notLinked` are registered in the store\n but have no Hook link here: say they were not checked, never that nothing is\n running there.\n- `hand_off`: send a prompt to one of those sessions.\n- `dispatch`: start a new worker on a computer (or `anywhere`).\n- `dispatch_returns` (CLI `phren dispatch returns`): what your workers sent\n back since you last asked: done with the final reply, needs-you with the\n question, failed with the error (a usage limit), blocked, or gone. Reading them marks them read. In core use\n `phren_admin(action: \"dispatch_returns\")`.\n- `phren dispatch status`: receipts of what you dispatched.\n- `get_tasks`, `get_project_summary`, `search_knowledge`: the store's memory.\n\nKeep engineering detail in worker briefs, Phren tasks and findings, and review\nartifacts, not in the owner's chat.\n\n## Voice and pace\n\nThe owner talks to you from the phone, often in talk mode, where your replies\nare read aloud in their voice. Sound like a good dispatcher: short, quick and\nconversational.\n\n- Lead with the outcome in one sentence. Keep the whole reply to one to four\n short sentences unless the owner asks for detail.\n- No tables, file paths, SHAs, PR numbers or run IDs in a reply unless the\n owner asks for them. Record them in Phren tasks and findings instead.\n- One short line per dispatch or return: who, what, result. A routine watcher\n or monitor event where nothing changed gets silence or a single line.\n- When the owner gives you a task, dispatch an engineer for it right away and\n say so in one line. That is the owner's standing rule; do not ask first.\n- Ask at most one question at a time, and name the options.\n- Delegate reading and analysis to workers instead of running long\n investigations yourself, so your own turns stay fast.\n- A message that begins with `[voice]` was spoken in talk mode, and your reply\n will be read aloud. Answer in one or two spoken sentences with no markdown,\n lists, symbols or code, written to sound natural read aloud: \"back in about\n twenty minutes\", not \"ETA ~20m\".\n\n```text\nLinuxbox has the parser checks on Codex, back around two twenty.\nDesk finished the navigation checks: tests passed, not merged yet.\n```\n\nIf a result or return time is unknown, say so. Surface a worker's question in\nthe same short voice, with the worker's own choices.\n\n## Dispatching\n\nPick five to ten independent tasks when that many are available and capacity\npermits. Do not manufacture tasks to fill the batch. Separate dependencies and\nfile ownership; give each remote lead a base revision, acceptance checks, local\nfanout limit, report time and integration instructions. Every brief repeats the\nowner's repository constraints, including any prohibition on commits, pushes,\nbranches or particular tests. Dispatch never expands the owner's authorization.\n\nYou are the one conductor for this computer and every computer linked with\nit; a second conductor in the group is refused at launch. Conductors on\ncomputers that are not linked share only the store, so claim a task before you\ndispatch it: `claim_task` (in core, `manage_task` with `action: \"claim\"`).\nSkip tasks marked `[claimed: <computer>]` by another computer. A claim that\ncomes back not claimed, with `heldBy`, means another conductor got there first:\nmove on. Completing a task clears its claim; release one you will not do. Start\nworkers with `dispatch` or `hand_off`, never as tabs in your own Herdr\nworkspace. When a computer shows up in `notLinked`, tell the owner that\n`phren bridge link <host>` can link it; never link a computer yourself.\n\nPrefer Codex. Use OpenCode Go when its account and harness are connected. Use\nOpenRouter only when the owner explicitly requests it; an unavailable account\ndoes not authorize another paid provider. Name an explicit model when instructed,\notherwise use and report the remote configured default. Each remote lead owns\nits local checkouts, fanout and provider rate limits. Where installed, local\nworkers use the fanout wrapper's `scripts/run.sh --provider codex|opencode\n--label --worktree [--model] [--mode]` contract and parent-bound manifests.\n\nPrefer handing work to a session that already owns the project and is idle or\ndoing related work; call `hand_off` in full or `phren_admin(action: \"hand_off\",\ncomputer?, target|session, text)` in core. Otherwise dispatch a new worker.\nWrite one short line either way. Call `dispatch` in full or\n`phren_admin(action: \"dispatch\", computer, project, harness, model?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>]`.\n`anywhere` chooses the connected computer with the fewest working agents. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\n`accepted` on a receipt is prompt acceptance, not worker completion. Returns\narrive on their own: the Hook follows every worker you dispatch, and when you\nare idle it types one line into this session, such as `Return: Linuxbox parser\nchecks done, tests passed (dispatch <id>). Call dispatch_returns.` When you see\none, call `dispatch_returns` and report each return in one short line. You may\nalso call it whenever you want the current state; do not poll it in a loop, and\ndo not read remote transcripts by hand to learn whether a worker finished. Tell\nthe owner a return time as an expectation, not a promise.\n\nFor a `needs-you` return, surface the worker's question in the owner's chat\nwith its choices as the worker wrote them; do not rewrite or answer it for the\nowner unless the owner already decided. Send the answer back with `hand_off`\nto the row's `target`. A `blocked` worker waits on terminal input, such as a\npermission prompt: say so and point the owner to the phone or the terminal. A\n`gone` worker's pane closed or was taken over: say so, and decide with the\nowner before giving its work to another agent. A `done` reply is the worker's\nown account; check its evidence before saying tests passed or work merged.\n\nAn uncertain delivery is never retried automatically. Inspect its known target\nor status before deciding with the owner whether a replacement is needed. Keep\nunavailable workers visible instead of giving their work to another agent\nwhile the original may still be running.\n\nIntegrate returned changes in dependency order within the owner's allowed\nworkflow. Run a cleanup pass across the combined result and the affected checks.\nRequire evidence before saying tests passed or merged. Ship only within existing\nauthorization; if publication is not authorized, return the reviewable result.\nUpdate Phren tasks when verified complete and save durable decisions. A worker's\nfinished turn alone does not complete the owner's task.\n";
46543
47074
  else {
46544
- const here = path76.dirname(fileURLToPath(import.meta.url));
47075
+ const here = path77.dirname(fileURLToPath(import.meta.url));
46545
47076
  for (const candidate of [
46546
- path76.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
46547
- path76.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
47077
+ path77.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
47078
+ path77.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
46548
47079
  ]) {
46549
- source = await readFile30(candidate, "utf8").catch(() => void 0);
47080
+ source = await readFile31(candidate, "utf8").catch(() => void 0);
46550
47081
  if (source !== void 0) break;
46551
47082
  }
46552
47083
  }
@@ -46565,15 +47096,15 @@ function effortArgs(kind, effort) {
46565
47096
  }
46566
47097
  async function prepareConductor(kind, effort, model) {
46567
47098
  const brief = await conductorBrief();
46568
- const briefDirectory = path76.join(bridgeRoot(), "conductor");
46569
- await mkdir18(briefDirectory, { recursive: true, mode: 448 });
46570
- const briefFile = path76.join(briefDirectory, "brief.md");
46571
- if (await readFile30(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
47099
+ const briefDirectory = path77.join(bridgeRoot(), "conductor");
47100
+ await mkdir20(briefDirectory, { recursive: true, mode: 448 });
47101
+ const briefFile = path77.join(briefDirectory, "brief.md");
47102
+ if (await readFile31(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
46572
47103
  if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
46573
47104
  if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
46574
47105
  if (kind === "opencode") {
46575
- const directory = path76.join(process.env.XDG_CONFIG_HOME || path76.join(homeDir(), ".config"), "opencode", "agents");
46576
- const file2 = path76.join(directory, "conductor.md");
47106
+ const directory = path77.join(process.env.XDG_CONFIG_HOME || path77.join(homeDir(), ".config"), "opencode", "agents");
47107
+ const file2 = path77.join(directory, "conductor.md");
46577
47108
  const definition = `---
46578
47109
  description: Coordinate the owner's work across agent sessions.
46579
47110
  mode: primary
@@ -46581,8 +47112,8 @@ mode: primary
46581
47112
 
46582
47113
  ${brief}
46583
47114
  `;
46584
- await mkdir18(directory, { recursive: true, mode: 448 });
46585
- if (await readFile30(file2, "utf8").catch(() => void 0) !== definition) await atomic(file2, definition, 420);
47115
+ await mkdir20(directory, { recursive: true, mode: 448 });
47116
+ if (await readFile31(file2, "utf8").catch(() => void 0) !== definition) await atomic(file2, definition, 420);
46586
47117
  return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
46587
47118
  }
46588
47119
  throw new BridgeError(400, "The selected harness cannot run as a conductor.");
@@ -46595,13 +47126,22 @@ async function targetForPane(server, pane) {
46595
47126
  const chat = await paneChatState(server, pane).catch(() => ({}));
46596
47127
  return chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : void 0;
46597
47128
  }
47129
+ async function localConductor(known) {
47130
+ const names = [.../* @__PURE__ */ new Set([...known ? [known.server] : [], ...(await servers()).map((item) => String(item.session))])];
47131
+ for (const name of names) {
47132
+ const value2 = known && name === known.server ? known.snapshot : await snapshot(name);
47133
+ const existing = objects(value2.panes).find((pane) => isConductorName(paneAgentName(value2, pane)) && provider.safeParse(pane.agent).success && !["completed", "exited", "failed", "stopped"].includes(String(pane.agent_status)));
47134
+ if (existing) return { server: name, target: await targetForPane(name, existing) };
47135
+ }
47136
+ return void 0;
47137
+ }
46598
47138
  function herdrAgentName(label2) {
46599
47139
  const slug = label2.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "").slice(0, 32).replace(/-+$/, "");
46600
47140
  return slug || "agent";
46601
47141
  }
46602
47142
  async function launchSession(server, data, options = {}) {
46603
47143
  const role = external_exports.enum(["agent", "conductor"]).default("agent").parse(data.role);
46604
- const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path76.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
47144
+ const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path77.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
46605
47145
  const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
46606
47146
  if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
46607
47147
  const label2 = plainText(200).parse(data.label);
@@ -46609,23 +47149,28 @@ async function launchSession(server, data, options = {}) {
46609
47149
  const effort = external_exports.enum(launchEfforts).default("medium").parse(data.effort);
46610
47150
  if (role === "conductor" && kind === "copilot") throw new BridgeError(400, "Copilot cannot run as a conductor.");
46611
47151
  const baseName = herdrAgentName(data.name === void 0 ? label2 : plainText(200).parse(data.name));
46612
- const wanted = options.canary ? "phren-canary" : role === "conductor" ? baseName === "conductor" || baseName.startsWith("conductor-") ? baseName : herdrAgentName(`conductor-${baseName}`) : baseName;
47152
+ const wanted = options.canary ? "phren-canary" : role === "conductor" ? isConductorName(baseName) ? baseName : herdrAgentName(`conductor-${baseName}`) : isConductorName(baseName) ? herdrAgentName(`worker-${baseName}`) : baseName;
46613
47153
  const model = typeof data.model === "string" && data.model.trim() ? plainText(200).parse(data.model.trim()) : void 0;
46614
47154
  const modelFlag = { codex: "--model", claude: "--model", opencode: "--model" };
46615
- const workspace = data.workspaceId === void 0 ? void 0 : id.parse(data.workspaceId);
47155
+ let workspace = data.workspaceId === void 0 ? void 0 : id.parse(data.workspaceId);
46616
47156
  const timeout = Math.min(12e4, Math.max(3001, data.timeoutMs === void 0 ? 45e3 : external_exports.number().int().parse(data.timeoutMs)));
46617
47157
  const before = await snapshot(server);
46618
47158
  const taken = agentNames(before);
46619
47159
  let name = wanted;
46620
47160
  for (let n = 2; taken.has(name) && n < 100; n++) name = `${wanted.slice(0, 32 - String(n).length - 1)}-${n}`;
47161
+ let unchecked = [];
46621
47162
  if (role === "conductor" && !options.canary) {
46622
- const otherServers = (await servers()).map((item) => String(item.session)).filter((name2) => name2 !== server);
46623
- const overviews = [{ name: server, value: before }, ...await Promise.all(otherServers.map(async (name2) => ({ name: name2, value: await snapshot(name2) })))];
46624
- for (const overview of overviews) {
46625
- const existing = objects(overview.value.panes).find((pane2) => isConductorName(paneAgentName(overview.value, pane2)) && provider.safeParse(pane2.agent).success && !["completed", "exited", "failed", "stopped"].includes(String(pane2.agent_status)));
46626
- if (existing) throw new BridgeError(409, "A conductor is already running for this store.", { target: await targetForPane(overview.name, existing) });
46627
- }
47163
+ const existing = await localConductor({ server, snapshot: before });
47164
+ if (existing) throw new BridgeError(409, "A conductor is already running on this computer.", { target: existing.target });
47165
+ const group = await groupConductor((await optionalHookPeers()).peers);
47166
+ if (group.found) throw new BridgeError(
47167
+ 409,
47168
+ `A conductor is already running on ${group.found.computer}, which is linked with this computer. A connected group shares one conductor.`,
47169
+ { computer: group.found.computer, target: group.found.target }
47170
+ );
47171
+ unchecked = group.unchecked;
46628
47172
  }
47173
+ if (role === "agent" && workspace && objects(before.panes).some((pane2) => pane2.workspace_id === workspace && isConductorName(paneAgentName(before, pane2)))) workspace = void 0;
46629
47174
  const args = role === "conductor" ? await prepareConductor(kind, effort, model) : [...model && modelFlag[kind] ? [modelFlag[kind], model] : [], ...data.effort === void 0 ? [] : effortArgs(kind, effort)];
46630
47175
  if (workspace && !objects(before.workspaces).some((w) => w.workspace_id === workspace)) throw new BridgeError(409, "The workspace changed.");
46631
47176
  const knownWorkspaces = new Set(objects(before.workspaces).map((w) => w.workspace_id));
@@ -46673,6 +47218,7 @@ async function launchSession(server, data, options = {}) {
46673
47218
  role,
46674
47219
  sessionId: sessionId2,
46675
47220
  target,
47221
+ ...unchecked.length ? { unchecked } : {},
46676
47222
  ...worktree ? { worktree: { path: worktree.path, branch: worktree.branch } } : {}
46677
47223
  };
46678
47224
  }
@@ -46686,7 +47232,7 @@ async function workspaceAction(server, operation, data) {
46686
47232
  if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
46687
47233
  if (pane && !objects(s.panes).some((p) => p.pane_id === pane && (!tab || p.tab_id === tab) && (!workspace || p.workspace_id === workspace))) throw new BridgeError(409, "The pane changed.");
46688
47234
  const label2 = data.label === void 0 ? void 0 : external_exports.string().min(1).max(200).refine((t) => !/[\x00-\x1f\x7f]/.test(t)).parse(data.label);
46689
- const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path76.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
47235
+ const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path77.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
46690
47236
  if (operation === "create") await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label: label2, cwd, focus: false, env: {} });
46691
47237
  else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
46692
47238
  else if (pane && operation === "focus") await rpc(server, "pane.focus", { pane_id: pane });
@@ -46697,6 +47243,87 @@ async function workspaceAction(server, operation, data) {
46697
47243
 
46698
47244
  // src/bridge/server-routes.ts
46699
47245
  init_metrics();
47246
+
47247
+ // src/bridge/speech.ts
47248
+ init_zod();
47249
+ init_protocol();
47250
+ import { once } from "node:events";
47251
+ var SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
47252
+ var OUTPUT_FORMAT = "pcm_24000";
47253
+ var SPEECH_MODEL = "eleven_flash_v2_5";
47254
+ var DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
47255
+ var MAX_TEXT = 2e3;
47256
+ var speechRequest = external_exports.object({ text: external_exports.string().trim().min(1).max(MAX_TEXT) });
47257
+ async function speechError(upstream) {
47258
+ let detail = "";
47259
+ try {
47260
+ detail = String((await upstream.json()).detail?.status ?? "");
47261
+ } catch {
47262
+ }
47263
+ if (detail === "quota_exceeded") return new BridgeError(402, "The ElevenLabs quota on this computer's account is used up.", { code: "speech-quota" });
47264
+ switch (upstream.status) {
47265
+ case 401:
47266
+ case 403:
47267
+ return new BridgeError(502, "ElevenLabs refused this computer's key.", { code: "speech-rejected" });
47268
+ case 404:
47269
+ return new BridgeError(502, "ElevenLabs doesn't know the configured voice.", { code: "speech-voice" });
47270
+ case 400:
47271
+ case 422:
47272
+ return new BridgeError(400, "ElevenLabs couldn't voice this text.", { code: "speech-invalid" });
47273
+ case 429:
47274
+ return new BridgeError(429, "ElevenLabs is busy. Try again shortly.", { code: "speech-busy" });
47275
+ default:
47276
+ return new BridgeError(502, `ElevenLabs failed (HTTP ${upstream.status}).`, { code: "speech-failed" });
47277
+ }
47278
+ }
47279
+ function speakableText(text3) {
47280
+ return text3.replace(/```[\s\S]*?(?:```|$)/g, " ").replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/https?:\/\/\S+/g, "a link").replace(/`([^`]*)`/g, "$1").split(/\r?\n/).map((line) => {
47281
+ const block = /^\s{0,3}(?:#{1,6}\s|[-*+]\s|\d+[.)]\s|\|)/.test(line);
47282
+ const words = line.replace(/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/, "").replace(/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+(?:\[[ xX]\]\s+)?)/, "").replace(/\s*\|\s*/g, (bar, offset, whole) => offset === 0 || offset + bar.length === whole.length ? "" : ", ").replace(/(\*\*|__|~~)(.+?)\1/g, "$2").replace(/(^|[^\w*])[*_](\S(?:.*?\S)?)[*_](?![\w*])/g, "$1$2").trim();
47283
+ return block && words && !/[.!?:;,]$/.test(words) ? `${words}.` : words;
47284
+ }).filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
47285
+ }
47286
+ async function synthesizeSpeech(text3, signal, options = {}) {
47287
+ const key = await (options.key ?? readSpeechKey)();
47288
+ if (!key) throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
47289
+ const voice = options.voice ?? process.env.PHREN_SPEECH_VOICE ?? DEFAULT_SPEECH_VOICE;
47290
+ const url2 = `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice)}/stream?output_format=${OUTPUT_FORMAT}`;
47291
+ let upstream;
47292
+ try {
47293
+ upstream = await (options.fetch ?? fetch)(url2, {
47294
+ method: "POST",
47295
+ signal,
47296
+ headers: { "xi-api-key": key, "Content-Type": "application/json" },
47297
+ body: JSON.stringify({ text: text3, model_id: SPEECH_MODEL, voice_settings: { stability: 0.6, similarity_boost: 0.75 } })
47298
+ });
47299
+ } catch {
47300
+ throw new BridgeError(502, "Couldn't reach ElevenLabs from this computer.", { code: "speech-unreachable" });
47301
+ }
47302
+ if (!upstream.ok || !upstream.body) throw await speechError(upstream);
47303
+ return upstream.body;
47304
+ }
47305
+ async function streamSpeech(data, response, options = {}) {
47306
+ const text3 = speakableText(speechRequest.parse(data).text);
47307
+ if (!text3) throw new BridgeError(400, "There is nothing to say in this reply.", { code: "speech-invalid" });
47308
+ const abort = new AbortController();
47309
+ response.once("close", () => {
47310
+ if (!response.writableEnded) abort.abort();
47311
+ });
47312
+ const audio = await synthesizeSpeech(text3, abort.signal, options);
47313
+ response.statusCode = 200;
47314
+ response.setHeader("Content-Type", "application/octet-stream");
47315
+ response.setHeader("X-Phren-Audio", SPEECH_AUDIO);
47316
+ try {
47317
+ for await (const chunk of audio) {
47318
+ if (!response.write(chunk)) await once(response, "drain", { signal: abort.signal });
47319
+ }
47320
+ response.end();
47321
+ } catch {
47322
+ response.destroy();
47323
+ }
47324
+ }
47325
+
47326
+ // src/bridge/server-routes.ts
46700
47327
  var CHILD_ACTIVITY_CACHE_MS = 5e3;
46701
47328
  var OVERVIEW_ENRICH_BUDGET_MS = 5e3;
46702
47329
  var childActivityCache = /* @__PURE__ */ new Map();
@@ -46740,7 +47367,8 @@ var capabilities = {
46740
47367
  code: true,
46741
47368
  overviewStream: true,
46742
47369
  speech: true,
46743
- transcribe: true
47370
+ transcribe: true,
47371
+ memoryStore: true
46744
47372
  };
46745
47373
  function capabilitiesForModules(snapshot2) {
46746
47374
  const allowed = new Set(snapshot2.modules.flatMap((module) => module.capabilities));
@@ -46867,7 +47495,9 @@ function createRouteHandler(ctx) {
46867
47495
  if (url2.origin !== "http://phren.local") throw new BridgeError(400, "Invalid request origin.");
46868
47496
  requireRoute(modules, request6.method ?? "", url2.pathname);
46869
47497
  let result;
46870
- if (request6.method === "GET") {
47498
+ if (url2.pathname.startsWith("/v1/store/")) {
47499
+ result = await storeRoute(modules.store, request6.method ?? "", url2, request6.method === "POST" ? await body(request6) : void 0);
47500
+ } else if (request6.method === "GET") {
46871
47501
  switch (url2.pathname) {
46872
47502
  case "/v1/health":
46873
47503
  result = { ...info, codePackage: await codePackageStatus(scheduleStore, modules.has("code")) };
@@ -46895,6 +47525,10 @@ function createRouteHandler(ctx) {
46895
47525
  case "/v1/conductor/grants":
46896
47526
  result = { grants: await listGrants() };
46897
47527
  break;
47528
+ // Asked by linked peers before they start a conductor: one per connected group.
47529
+ case "/v1/conductor":
47530
+ result = { computer: info.computer, conductor: await localConductor() ?? null };
47531
+ break;
46898
47532
  case "/v1/dispatch/capacity": {
46899
47533
  const live = await servers();
46900
47534
  const snapshots = await Promise.all(live.map((server) => snapshot(String(server.session))));
@@ -46931,7 +47565,7 @@ function createRouteHandler(ctx) {
46931
47565
  case "/v1/files/range": {
46932
47566
  let root;
46933
47567
  if (url2.searchParams.get("scope") === "uploads") {
46934
- root = path77.join(bridgeRoot(), "uploads");
47568
+ root = path78.join(bridgeRoot(), "uploads");
46935
47569
  } else if (url2.searchParams.has("session")) {
46936
47570
  const target = targetFromURL(url2), pane = await validateTarget(target);
46937
47571
  const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
@@ -47236,7 +47870,7 @@ init_protocol();
47236
47870
  // src/bridge/transcript-preview.ts
47237
47871
  init_codex_threads();
47238
47872
  import { constants as constants4 } from "node:fs";
47239
- import { open as open13 } from "node:fs/promises";
47873
+ import { open as open14 } from "node:fs/promises";
47240
47874
  init_protocol();
47241
47875
  init_transcript_index();
47242
47876
  var PREVIEW_INTERVAL_MS = 500;
@@ -47289,9 +47923,9 @@ function claudePanePreview(rendered, prompt, previous = "") {
47289
47923
  }
47290
47924
  if (!writing) continue;
47291
47925
  const tidy = (value2) => value2.replace(/^\s*[⏺●]\s?/, "").replace(/[⠁-⣿✻✽✶✢✳]/gu, "");
47292
- const clean = tidy(line);
47293
- if (/^\s*(?:↳|⎿|ctrl\+|shift\+|\? for shortcuts)/i.test(clean) || claudeChrome(clean)) continue;
47294
- reply.push(clean.replace(/^ {2}/, ""));
47926
+ const clean2 = tidy(line);
47927
+ if (/^\s*(?:↳|⎿|ctrl\+|shift\+|\? for shortcuts)/i.test(clean2) || claudeChrome(clean2)) continue;
47928
+ reply.push(clean2.replace(/^ {2}/, ""));
47295
47929
  shown.push(tidy(markedBody[index2] ?? line).replace(/^ {2}/, ""));
47296
47930
  }
47297
47931
  const text3 = unwrapTerminalLines(reply, shown).trim().slice(0, MAX_TEXT2);
@@ -47450,11 +48084,11 @@ async function readDeltaPreview(target, file2, rollout) {
47450
48084
  if (target.source === "codex") return await codexThreadPreview(target.session) ?? (file2 && rollout ? await rollout.read(file2).catch(() => null) : null);
47451
48085
  if (target.source !== "opencode" || !file2) return null;
47452
48086
  try {
47453
- const handle = await open13(file2 + ".preview.json", constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
48087
+ const handle = await open14(file2 + ".preview.json", constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
47454
48088
  let bytes;
47455
48089
  try {
47456
- const stat24 = await handle.stat();
47457
- if (!stat24.isFile() || stat24.size > MAX_PREVIEW_BYTES) return null;
48090
+ const stat25 = await handle.stat();
48091
+ if (!stat25.isFile() || stat25.size > MAX_PREVIEW_BYTES) return null;
47458
48092
  const buffer = Buffer.alloc(MAX_PREVIEW_BYTES + 1);
47459
48093
  const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
47460
48094
  if (bytesRead > MAX_PREVIEW_BYTES) return null;
@@ -47701,7 +48335,13 @@ function transcriptStreams(ctx) {
47701
48335
  store: info.store,
47702
48336
  profile: info.profile,
47703
48337
  generation: info.generation,
47704
- capabilities: { ...activeCapabilities, asyncQuestions: target.source === "codex" && codexQuestions.available },
48338
+ capabilities: {
48339
+ ...activeCapabilities,
48340
+ asyncQuestions: target.source === "codex" && codexQuestions.available,
48341
+ // Claude's AskUserQuestion is answered in its terminal dialog
48342
+ // through /v1/questions/answer, whether or not a hold caught it.
48343
+ ...target.source === "claude" ? { questions: true } : {}
48344
+ },
47705
48345
  branch
47706
48346
  } });
47707
48347
  }
@@ -47854,15 +48494,15 @@ async function serve(version3) {
47854
48494
  if (!modules.has("hook")) throw new BridgeError(404, disabledHint("hook"));
47855
48495
  const activeCapabilities = capabilitiesForModules(modules);
47856
48496
  const root = bridgeRoot();
47857
- await mkdir19(root, { recursive: true, mode: 448 });
48497
+ await mkdir21(root, { recursive: true, mode: 448 });
47858
48498
  await chmod5(root, 448);
47859
48499
  let computerID2;
47860
- const identityFile = path78.join(root, "computer-id");
48500
+ const identityFile = path79.join(root, "computer-id");
47861
48501
  try {
47862
- computerID2 = (await readFile31(identityFile, "utf8")).trim();
48502
+ computerID2 = (await readFile32(identityFile, "utf8")).trim();
47863
48503
  } catch {
47864
48504
  computerID2 = randomUUID19();
47865
- await writeFile10(identityFile, computerID2, { flag: "wx", mode: 384 });
48505
+ await writeFile11(identityFile, computerID2, { flag: "wx", mode: 384 });
47866
48506
  }
47867
48507
  const launches = new LaunchLimiter();
47868
48508
  const dispatches = modules.has("conductor") ? new DispatchService({
@@ -47907,7 +48547,7 @@ async function serve(version3) {
47907
48547
  if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
47908
48548
  function gatewayTiming() {
47909
48549
  try {
47910
- const parsed = JSON.parse(readFileSync31(path78.join(root, "gateway.json"), "utf8"));
48550
+ const parsed = JSON.parse(readFileSync31(path79.join(root, "gateway.json"), "utf8"));
47911
48551
  if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
47912
48552
  } catch {
47913
48553
  }
@@ -47936,7 +48576,7 @@ async function serve(version3) {
47936
48576
  launch: (server, data) => launches.run(() => launchSession(server, data, { canary: true })),
47937
48577
  scheduler
47938
48578
  });
47939
- const old = await lstat18(socketPath()).catch(() => null);
48579
+ const old = await lstat19(socketPath()).catch(() => null);
47940
48580
  if (old) {
47941
48581
  if (!old.isSocket() || process.getuid && old.uid !== process.getuid()) throw new Error("Refusing to replace an unexpected hook socket.");
47942
48582
  const { connect: connect4 } = await import("node:net");
@@ -47953,7 +48593,7 @@ async function serve(version3) {
47953
48593
  }
47954
48594
  const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
47955
48595
  };
47956
- if (modules.has("git")) await rm9(path78.join(root, "changes-scratch"), { recursive: true, force: true });
48596
+ if (modules.has("git")) await rm10(path79.join(root, "changes-scratch"), { recursive: true, force: true });
47957
48597
  const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
47958
48598
  const { stream } = streams;
47959
48599
  const overview = overviewStream({
@@ -48095,17 +48735,171 @@ async function serve(version3) {
48095
48735
 
48096
48736
  // src/bridge/command.ts
48097
48737
  init_protocol();
48738
+
48739
+ // src/bridge/link.ts
48740
+ init_profile_store();
48741
+ init_phren_paths();
48742
+ import { execFile as execFile16 } from "node:child_process";
48743
+ import { readFile as readFile33 } from "node:fs/promises";
48744
+ import { homedir as homedir19, hostname as hostname9, userInfo as userInfo2 } from "node:os";
48745
+ import path80 from "node:path";
48746
+ import { promisify as promisify16 } from "node:util";
48747
+ init_protocol();
48748
+ var exec16 = promisify16(execFile16);
48749
+ var REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"';
48750
+ var GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
48751
+ function sshConfigHosts(text3) {
48752
+ const hosts = [];
48753
+ let block = [], skip = false;
48754
+ const flush = () => {
48755
+ if (!skip) hosts.push(...block);
48756
+ block = [];
48757
+ skip = false;
48758
+ };
48759
+ for (const raw of text3.split(/\r?\n/)) {
48760
+ const match = /^\s*([A-Za-z]+)(?:\s*=\s*|\s+)(.+?)\s*$/.exec(raw.replace(/\s#.*$|^\s*#.*$/, ""));
48761
+ if (!match) continue;
48762
+ const [key, value2] = [match[1].toLowerCase(), match[2]];
48763
+ if (key === "host" || key === "match") {
48764
+ flush();
48765
+ if (key === "host") block = value2.split(/\s+/).filter((alias) => !/[*?!]/.test(alias));
48766
+ } else if (key === "hostname" && GIT_HOSTS.test(value2)) skip = true;
48767
+ }
48768
+ flush();
48769
+ return [...new Set(hosts.filter((alias) => !GIT_HOSTS.test(alias)))];
48770
+ }
48771
+ async function ssh(host, command, input2, timeout = 2e4) {
48772
+ return new Promise((resolve11, reject) => {
48773
+ const child = execFile16(
48774
+ "ssh",
48775
+ ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", host, command],
48776
+ { timeout, maxBuffer: 1048576 },
48777
+ (error62, stdout, stderr) => {
48778
+ if (error62) reject(new BridgeError(503, `ssh ${host}: ${(stderr || error62.message).split("\n").find(Boolean)?.slice(0, 200) ?? "failed"}`));
48779
+ else resolve11(stdout);
48780
+ }
48781
+ );
48782
+ child.stdin?.end(input2 ?? "");
48783
+ });
48784
+ }
48785
+ async function probe2(host) {
48786
+ const out = await ssh(host, `printf 'id=%s\\nuser=%s\\nclient=%s\\n' "$(cat ~/.local/share/phren/bridge/computer-id 2>/dev/null)" "$(id -un)" "\${SSH_CONNECTION%% *}"`, void 0, 12e3);
48787
+ const field = (name) => new RegExp(`^${name}=(.*)$`, "m").exec(out)?.[1]?.trim() || void 0;
48788
+ const computerId = field("id");
48789
+ return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
48790
+ }
48791
+ async function discoverComputers(options = {}) {
48792
+ const config3 = options.sshConfig ?? await readFile33(path80.join(homedir19(), ".ssh", "config"), "utf8").catch(() => "");
48793
+ const store = options.store !== void 0 ? options.store : findPhrenPath();
48794
+ const machines = store ? listMachines(store) : void 0;
48795
+ const { peers } = await optionalHookPeers();
48796
+ const own2 = (await readFile33(path80.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
48797
+ const known = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
48798
+ const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known.has(computerLabel(host))).slice(0, 32);
48799
+ const [found, peerIds] = await Promise.all([
48800
+ Promise.all(candidates.map((host) => probe2(host).catch(() => void 0))),
48801
+ Promise.all(peers.map((peer) => peerRequest(peer, "/v1/health").then((health2) => object2(health2.computer).id, () => void 0)))
48802
+ ]);
48803
+ const seen = /* @__PURE__ */ new Set([own2, ...peerIds.filter((id2) => typeof id2 === "string")]);
48804
+ const reachable = found.filter((item) => {
48805
+ if (!item || seen.has(item.computerId)) return false;
48806
+ seen.add(item.computerId);
48807
+ return true;
48808
+ });
48809
+ return { reachable, checked: candidates };
48810
+ }
48811
+ function slugName(value2) {
48812
+ const label2 = computerLabel(value2).replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^[^A-Za-z0-9_]+/, "") || "computer";
48813
+ return computerName.parse(label2.slice(0, 100));
48814
+ }
48815
+ async function linkComputer(host, options = {}) {
48816
+ const remote = await probe2(host);
48817
+ if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
48818
+ const own2 = (await readFile33(path80.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
48819
+ if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
48820
+ const name = computerName.parse(options.name ?? slugName(host));
48821
+ const as = computerName.parse(options.as ?? slugName(hostname9()));
48822
+ const backAddress = options.backAddress ?? remote.client;
48823
+ if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
48824
+ const resolved = Object.fromEntries((await exec16("ssh", ["-G", "--", host], { timeout: 5e3 })).stdout.split("\n").map((line) => line.split(" ")).filter((parts) => parts.length >= 2).map(([key, ...rest]) => [key, rest.join(" ")]));
48825
+ const remoteHostKey = publicComputerKey((await ssh(host, "cat /etc/ssh/ssh_host_ed25519_key.pub")).trim().split(/\s+/).slice(0, 2).join(" "));
48826
+ const localHostKey = publicComputerKey((await readFile33("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
48827
+ const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
48828
+ await ssh(host, `f=$(mktemp) && cat > "$f" && ${REMOTE_PATH} phren bridge enroll-computer ${as} --accept "$f"; s=$?; rm -f "$f"; exit $s`, await enrollComputer(as));
48829
+ await acceptComputer(name, remoteLine);
48830
+ const peer = { name, address: String(resolved.hostname || host), username: remote.user || String(resolved.user), port: Number(resolved.port) || 22, server: "default", hostKey: remoteHostKey };
48831
+ const local = await addHookPeer(peer);
48832
+ const back = { name: as, address: backAddress, username: userInfo2().username, port: 22, server: "default", hostKey: localHostKey };
48833
+ const answer = JSON.parse(await ssh(host, `${REMOTE_PATH} phren bridge add-peer`, JSON.stringify(back), 45e3).catch((error62) => {
48834
+ if (/Usage: phren bridge/.test(error62.message)) throw new BridgeError(409, `phren on ${host} is too old to finish linking. Update it there and run this again; the keys already exchanged are reused.`);
48835
+ throw error62;
48836
+ }));
48837
+ const reached = await peerRequest(peer, "/v1/health").then(() => void 0, (error62) => error62.message);
48838
+ return {
48839
+ name,
48840
+ as,
48841
+ local: { added: local.added },
48842
+ remote: { added: !!answer.added, reachable: !!answer.reachable, ...answer.error ? { error: String(answer.error) } : {} },
48843
+ reachable: !reached,
48844
+ ...reached ? { error: reached } : {}
48845
+ };
48846
+ }
48847
+ async function addPeerFromLink(input2) {
48848
+ const { added, peer } = await addHookPeer(JSON.parse(input2));
48849
+ const error62 = await peerRequest(peer, "/v1/health").then(() => void 0, (failure2) => failure2.message);
48850
+ return { added, reachable: !error62, ...error62 ? { error: error62 } : {} };
48851
+ }
48852
+
48853
+ // src/bridge/command.ts
48098
48854
  init_fanouts();
48855
+ var LINK_USAGE = "Usage: phren bridge link <ssh-host> [--name <its name here>] [--as <this computer's name there>] [--back-address <address it dials>] [--yes]";
48099
48856
  async function runBridge(args, version3) {
48100
48857
  switch (args[0]) {
48101
48858
  case "enroll-computer": {
48102
48859
  if (args.length === 2) console.log(await enrollComputer(args[1]));
48103
48860
  else if (args.length === 4 && args[2] === "--accept") {
48104
- await acceptComputer(args[1], await readFile32(args[3], "utf8"));
48861
+ await acceptComputer(args[1], await readFile34(args[3], "utf8"));
48105
48862
  console.log(`Enrolled ${args[1]} for Phren Hook.`);
48106
48863
  } else throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
48107
48864
  break;
48108
48865
  }
48866
+ case "discover": {
48867
+ const { reachable, checked } = await discoverComputers();
48868
+ if (!reachable.length) console.log(`No unlinked computers running Phren Hook answered over ssh (checked ${checked.length}: ${checked.join(", ") || "none"}).`);
48869
+ else {
48870
+ console.log("Reachable over ssh, running Phren Hook, and not linked:");
48871
+ for (const item of reachable) console.log(` ${item.host} (${item.user}) link with: phren bridge link ${item.host}`);
48872
+ }
48873
+ break;
48874
+ }
48875
+ case "link": {
48876
+ const host = args[1];
48877
+ const flag = (name) => {
48878
+ const index2 = args.indexOf(name);
48879
+ return index2 > 1 ? args[index2 + 1] : void 0;
48880
+ };
48881
+ if (!host || host.startsWith("-")) throw new Error(LINK_USAGE);
48882
+ if (!args.includes("--yes")) {
48883
+ if (!process.stdin.isTTY) throw new Error(`Linking ${host} lets each computer run agents on the other. Pass --yes to confirm.`);
48884
+ const { createInterface: createInterface2 } = await import("node:readline/promises");
48885
+ const prompt = createInterface2({ input: process.stdin, output: process.stdout });
48886
+ const answer = await prompt.question(`Link this computer and ${host} both ways, so each can list and start agents on the other? [y/N] `);
48887
+ prompt.close();
48888
+ if (!/^y(es)?$/i.test(answer.trim())) {
48889
+ console.log("Not linked.");
48890
+ return 1;
48891
+ }
48892
+ }
48893
+ const result = await linkComputer(host, { name: flag("--name"), as: flag("--as"), backAddress: flag("--back-address") });
48894
+ console.log(JSON.stringify(result, null, 2));
48895
+ return result.reachable && result.remote.reachable ? 0 : 1;
48896
+ }
48897
+ case "add-peer": {
48898
+ const chunks = [];
48899
+ for await (const chunk of process.stdin) chunks.push(chunk);
48900
+ console.log(JSON.stringify(await addPeerFromLink(Buffer.concat(chunks).toString("utf8"))));
48901
+ break;
48902
+ }
48109
48903
  case "fanouts": {
48110
48904
  if (args[1] !== "archive") throw new Error(FANOUTS_ARCHIVE_USAGE);
48111
48905
  const options = parseFanoutArchiveFlags(args.slice(2));
@@ -48116,6 +48910,12 @@ async function runBridge(args, version3) {
48116
48910
  console.log(`${doing} ${moved.length} fan-out job(s); ${removal} ${deleted} past the ${ARCHIVE_MAX_FOLDERS}-folder cap.`);
48117
48911
  break;
48118
48912
  }
48913
+ case "speech-key": {
48914
+ if (args[1] !== "set" || args.length !== 2) throw new Error(SPEECH_KEY_USAGE);
48915
+ await writeSpeechKey(await readSecret("ElevenLabs API key: "));
48916
+ console.log(`Stored the ElevenLabs key in ${speechKeyFile()} (mode 600).`);
48917
+ break;
48918
+ }
48119
48919
  case "usage-statusline":
48120
48920
  await captureClaudeUsage(args[1] || "");
48121
48921
  break;
@@ -48147,7 +48947,7 @@ async function runBridge(args, version3) {
48147
48947
  break;
48148
48948
  case "doctor": {
48149
48949
  const helper2 = await health(), muxes = await servers();
48150
- const push = approvalPushCheck(helper2);
48950
+ const push = approvalPushCheck(helper2), speech = await speechKeyStatus();
48151
48951
  console.log(JSON.stringify({ ok: true, helper: helper2, herdr: muxes, checks: {
48152
48952
  privateSocket: true,
48153
48953
  protocol: true,
@@ -48155,25 +48955,67 @@ async function runBridge(args, version3) {
48155
48955
  herdrRunning: muxes.length > 0,
48156
48956
  terminal: "SSH PTY; authorize the Phren device key with pty",
48157
48957
  shell: muxes.length > 0 ? "available" : "Herdr is not running: chat is unavailable, project shells and agents still open over SSH",
48158
- approvalPush: push.configured ? "configured" : "not configured"
48958
+ approvalPush: push.configured ? "configured" : "not configured",
48959
+ speechKey: speech.configured ? "configured" : "not configured",
48960
+ speechKeyDetail: speech.detail
48159
48961
  }, ...push.warning ? { warnings: [push.warning] } : {} }, null, 2));
48160
48962
  if (push.warning) console.error(`warning: ${push.warning}`);
48161
48963
  break;
48162
48964
  }
48163
48965
  default:
48164
- throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|fanouts archive>");
48966
+ throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|discover|link|fanouts archive|speech-key set>");
48165
48967
  }
48166
48968
  return 0;
48167
48969
  }
48168
48970
  function approvalPushCheck(helper2) {
48169
- const configured = object2(helper2.capabilities).approvalPush === "direct-apns";
48971
+ const capability = object2(helper2.capabilities).approvalPush;
48972
+ const configured = capability === "direct-apns" || capability === "relay";
48170
48973
  return configured ? { configured } : { configured, warning: apnsSetupSteps() };
48171
48974
  }
48975
+ var SPEECH_KEY_USAGE = "Usage: phren bridge speech-key set (paste the key when asked, or pipe it on stdin)";
48976
+ async function readSecret(prompt) {
48977
+ const stdin = process.stdin;
48978
+ if (!stdin.isTTY) {
48979
+ let text3 = "";
48980
+ for await (const chunk of stdin) text3 += chunk;
48981
+ return text3;
48982
+ }
48983
+ process.stderr.write(prompt);
48984
+ stdin.setEncoding("utf8");
48985
+ stdin.setRawMode(true);
48986
+ stdin.resume();
48987
+ return new Promise((resolve11, reject) => {
48988
+ let value2 = "";
48989
+ const finish = () => {
48990
+ stdin.off("data", onData);
48991
+ stdin.setRawMode(false);
48992
+ stdin.pause();
48993
+ process.stderr.write("\n");
48994
+ };
48995
+ const onData = (chunk) => {
48996
+ for (const char of chunk) {
48997
+ if (char === "\r" || char === "\n") {
48998
+ finish();
48999
+ resolve11(value2);
49000
+ return;
49001
+ }
49002
+ if (char === "") {
49003
+ finish();
49004
+ reject(new Error("Cancelled."));
49005
+ return;
49006
+ }
49007
+ if (char === "\x7F" || char === "\b") value2 = value2.slice(0, -1);
49008
+ else value2 += char;
49009
+ }
49010
+ };
49011
+ stdin.on("data", onData);
49012
+ });
49013
+ }
48172
49014
 
48173
49015
  // src/bridge/hook-main.ts
48174
49016
  init_utils_helpers();
48175
49017
  Object.assign(process.env, nonInteractiveGitEnv());
48176
- runBridge(process.argv.slice(2), "0.3.0").then((code) => {
49018
+ runBridge(process.argv.slice(2), "0.3.2").then((code) => {
48177
49019
  process.exitCode = code;
48178
49020
  }).catch((error62) => {
48179
49021
  console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");