@phren/cli 0.3.0 → 0.3.1

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 (55) hide show
  1. package/dist/bridge/agent-hooks.d.ts +15 -6
  2. package/dist/bridge/agent-hooks.js +55 -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.js +92 -2
  6. package/dist/bridge/computers.d.ts +5 -0
  7. package/dist/bridge/computers.js +10 -4
  8. package/dist/bridge/conductor-group.d.ts +23 -0
  9. package/dist/bridge/conductor-group.js +25 -0
  10. package/dist/bridge/hand-off.js +5 -1
  11. package/dist/bridge/herdr.d.ts +7 -0
  12. package/dist/bridge/herdr.js +53 -2
  13. package/dist/bridge/link.d.ts +48 -0
  14. package/dist/bridge/link.js +136 -0
  15. package/dist/bridge/memory-store.d.ts +23 -0
  16. package/dist/bridge/memory-store.js +152 -0
  17. package/dist/bridge/pair.d.ts +46 -0
  18. package/dist/bridge/pair.js +240 -0
  19. package/dist/bridge/peers.d.ts +9 -0
  20. package/dist/bridge/peers.js +25 -2
  21. package/dist/bridge/server-launch.d.ts +9 -0
  22. package/dist/bridge/server-launch.js +34 -11
  23. package/dist/bridge/server-pane-routes.js +38 -7
  24. package/dist/bridge/server-routes.d.ts +1 -0
  25. package/dist/bridge/server-routes.js +11 -3
  26. package/dist/bridge/server-stream.js +4 -1
  27. package/dist/bridge/speech-key.d.ts +33 -0
  28. package/dist/bridge/speech-key.js +106 -0
  29. package/dist/bridge/speech-transcribe.js +1 -1
  30. package/dist/bridge/speech.d.ts +1 -3
  31. package/dist/bridge/speech.js +2 -16
  32. package/dist/bridge-hook.mjs +1198 -492
  33. package/dist/cli-handlers.js +6 -0
  34. package/dist/cli-registry.js +14 -2
  35. package/dist/content/learning.js +1 -1
  36. package/dist/data/tasks.d.ts +26 -0
  37. package/dist/data/tasks.js +72 -1
  38. package/dist/entrypoint.js +7 -0
  39. package/dist/governance/rbac.d.ts +1 -1
  40. package/dist/governance/rbac.js +1 -0
  41. package/dist/init/init-walkthrough.d.ts +10 -0
  42. package/dist/init/init-walkthrough.js +24 -1
  43. package/dist/init/init.d.ts +5 -0
  44. package/dist/init/init.js +54 -32
  45. package/dist/link/doctor.js +10 -0
  46. package/dist/mcp/profile.js +2 -1
  47. package/dist/modules/config.d.ts +7 -0
  48. package/dist/modules/config.js +17 -0
  49. package/dist/modules/registry.js +5 -4
  50. package/dist/sync/task-claim.d.ts +22 -0
  51. package/dist/sync/task-claim.js +45 -0
  52. package/dist/tools/dispatch.js +2 -2
  53. package/dist/tools/tasks.js +40 -1
  54. package/package.json +2 -1
  55. 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.1" : "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: randomBytes4, 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();
@@ -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) {
@@ -34473,7 +34507,7 @@ async function removeGrant(input2, root = bridgeRoot()) {
34473
34507
  init_zod();
34474
34508
  init_protocol();
34475
34509
  import { createPrivateKey, sign } from "node:crypto";
34476
- import { readFile as readFile12, stat as stat8 } from "node:fs/promises";
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";
34479
34513
  var deviceSchema = external_exports.object({
@@ -34536,7 +34570,7 @@ function schedulePushPayload(value2) {
34536
34570
  }
34537
34571
  async function secureJSON(file2, schema) {
34538
34572
  try {
34539
- const metadata = await stat8(file2);
34573
+ const metadata = await stat9(file2);
34540
34574
  if ((metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
34541
34575
  return schema.parse(JSON.parse(await readFile12(file2, "utf8")));
34542
34576
  } catch {
@@ -34545,7 +34579,7 @@ async function secureJSON(file2, schema) {
34545
34579
  }
34546
34580
  async function secureFile(file2) {
34547
34581
  try {
34548
- const metadata = await stat8(file2);
34582
+ const metadata = await stat9(file2);
34549
34583
  if (!metadata.isFile() || (metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
34550
34584
  return await readFile12(file2, "utf8");
34551
34585
  } catch {
@@ -34686,6 +34720,161 @@ var ApprovalPushService = class {
34686
34720
  // src/bridge/agent-hooks.ts
34687
34721
  init_limits();
34688
34722
 
34723
+ // src/bridge/claude-question-dialog.ts
34724
+ init_protocol();
34725
+ var TAB_BAR = /^\s*(?:←\s+)?((?:[☐☒]\s+\S[^☐☒✔→]*?\s*)+)(?:✔\s+Submit\s*)?(?:→\s*)?$/;
34726
+ var ROW = /^\s*(❯)?\s*(\d)\.\s+(?:\[([ ✔])\]\s+)?(.*?)\s*$/;
34727
+ var NEXT = /^\s*(❯)?\s+(?:Next|Submit)\s*$/;
34728
+ var normalize = (text3) => text3.replace(/\s+/g, " ").trim();
34729
+ function claudeQuestionDialog(text3) {
34730
+ const lines = text3.split(/\r?\n/);
34731
+ let bar = -1;
34732
+ for (let index2 = lines.length - 1; index2 >= 0; index2--) if (TAB_BAR.test(lines[index2]) && /[☐☒]/.test(lines[index2])) {
34733
+ bar = index2;
34734
+ break;
34735
+ }
34736
+ if (bar < 0) return void 0;
34737
+ const tabs = [...lines[bar].matchAll(/[☐☒]\s+([^☐☒✔→]+?)(?=\s{2,}|\s*[☐☒✔→]|\s*$)/g)].map((match) => match[1].trim());
34738
+ const body2 = lines.slice(bar + 1);
34739
+ const content = body2.map((line) => line.trim()).filter((line) => line && !/^─+$/.test(line));
34740
+ if (content[0] === "Review your answers") {
34741
+ if (!body2.some((line) => /^\s*❯?\s*1\.\s+Submit answers\s*$/.test(line))) return void 0;
34742
+ const answers = [];
34743
+ for (const line of content.slice(1)) {
34744
+ if (/^Ready to submit/.test(line)) break;
34745
+ const question2 = /^●\s+(.+)$/.exec(line), answer = /^→\s+(.+)$/.exec(line), last = answers[answers.length - 1];
34746
+ if (question2) answers.push({ question: question2[1], answer: "" });
34747
+ else if (answer && last) last.answer = answer[1];
34748
+ else if (last) {
34749
+ if (last.answer) last.answer += " " + line;
34750
+ else last.question += " " + line;
34751
+ }
34752
+ }
34753
+ return { kind: "review", tabs, answers };
34754
+ }
34755
+ if (!content.some((line) => /Esc to cancel/.test(line))) return void 0;
34756
+ const first = body2.findIndex((line) => ROW.test(line));
34757
+ if (first < 0) return void 0;
34758
+ const title = normalize(body2.slice(0, first).filter((line) => line.trim()).join(" "));
34759
+ const rows = [];
34760
+ let cursor, chat = false;
34761
+ for (const line of body2.slice(first)) {
34762
+ const next = NEXT.exec(line);
34763
+ if (next) {
34764
+ if (next[1]) cursor = "next";
34765
+ continue;
34766
+ }
34767
+ const match = ROW.exec(line);
34768
+ if (!match) continue;
34769
+ const number4 = Number(match[2]);
34770
+ if (match[1]) cursor = number4;
34771
+ if (/^Chat about this$/.test(match[4])) {
34772
+ chat = true;
34773
+ continue;
34774
+ }
34775
+ const answered = !match[3] && / ✔$/.test(match[4]);
34776
+ rows.push({
34777
+ number: number4,
34778
+ label: answered ? match[4].slice(0, -2).trim() : match[4],
34779
+ answered,
34780
+ cursor: !!match[1],
34781
+ ...match[3] ? { checked: match[3] === "\u2714" } : {}
34782
+ });
34783
+ }
34784
+ if (!title || !chat || rows.length < 2) return void 0;
34785
+ const other = rows.pop();
34786
+ return { kind: "question", tabs, title, multiSelect: rows.some((row) => row.checked !== void 0), options: rows, other, ...cursor !== void 0 ? { cursor } : {} };
34787
+ }
34788
+ var changed = (message) => new BridgeError(409, `${message} Nothing else was sent; check the question and answer again, or cancel it.`);
34789
+ var typedKeys = (text3) => [...text3].map((character) => character === " " ? "space" : character);
34790
+ async function answerClaudeQuestionDialog(io, questions, answers, options = {}) {
34791
+ const from = options.from ?? 0, submit = options.submit ?? true;
34792
+ const sleep3 = io.sleep ?? ((ms) => new Promise((resolve11) => setTimeout(resolve11, ms)));
34793
+ const matches = (screen, index2) => screen?.kind === "question" && screen.title === normalize(questions[index2].question);
34794
+ const settle2 = async (check2, ms = 2e3) => {
34795
+ for (let waited = 0; ; waited += 120) {
34796
+ const value2 = check2(claudeQuestionDialog(await io.read()));
34797
+ if (value2 !== void 0 || waited >= ms) return value2;
34798
+ await sleep3(120);
34799
+ }
34800
+ };
34801
+ const initial = await settle2((screen) => screen);
34802
+ if (!initial) throw changed("The terminal is not showing Claude's question.");
34803
+ if (initial.tabs.length !== questions.length) throw changed("The terminal is asking a different set of questions.");
34804
+ const reach = async (index2) => {
34805
+ const screen = await settle2((value2) => value2);
34806
+ if (screen?.kind === "question" && screen.title === normalize(questions[index2].question)) return screen;
34807
+ const at = screen?.kind === "review" ? questions.length : screen?.kind === "question" ? questions.findIndex((question2) => normalize(question2.question) === screen.title) : -1;
34808
+ if (at < 0) throw changed("The terminal is showing a different question.");
34809
+ if (screen?.kind === "question" && screen.other && screen.cursor === screen.other.number) await io.keys(["up"]);
34810
+ await io.keys(Array(Math.abs(index2 - at)).fill(index2 > at ? "right" : "left"));
34811
+ const moved = await settle2((value2) => matches(value2, index2) ? value2 : void 0);
34812
+ if (!moved) throw changed("Could not move the terminal to the question being answered.");
34813
+ return moved;
34814
+ };
34815
+ const leaves = (index2) => (value2) => value2 === void 0 ? "gone" : !matches(value2, index2) ? "moved" : void 0;
34816
+ for (const [offset, answer] of answers.entries()) {
34817
+ const index2 = from + offset, question2 = questions[index2];
34818
+ if (!question2) throw new BridgeError(400, "The answer names a question that was not asked.");
34819
+ const typed = answer.text?.trim() ?? "";
34820
+ let screen = await reach(index2);
34821
+ if (screen.multiSelect !== !!question2.multiSelect || screen.options.length !== question2.options.length || screen.options.some((row, position) => row.label !== question2.options[position].label.trim())) {
34822
+ throw changed("The terminal's options differ from the question being answered.");
34823
+ }
34824
+ if (!screen.multiSelect) {
34825
+ if (typed) {
34826
+ const other = screen.other;
34827
+ await io.keys([String(other.number)]);
34828
+ const focused = await settle2((value2) => matches(value2, index2) && value2.cursor === other.number ? value2 : void 0);
34829
+ if (!focused) throw changed("Could not open the typed answer.");
34830
+ await io.keys(typedKeys(typed));
34831
+ const shown = await settle2((value2) => matches(value2, index2) && value2.other && normalize(value2.other.label).startsWith(normalize(typed).slice(0, 20)) ? value2 : void 0);
34832
+ if (!shown) throw changed("The typed answer did not appear in the terminal.");
34833
+ await io.keys(["enter"]);
34834
+ } else {
34835
+ await io.keys([String(screen.options[answer.options[0]].number)]);
34836
+ }
34837
+ if (!await settle2(leaves(index2))) throw changed("The terminal did not take the answer.");
34838
+ continue;
34839
+ }
34840
+ const rows = [...screen.options, ...screen.other ? [screen.other] : []];
34841
+ for (const [position, row] of rows.entries()) {
34842
+ const wanted = position < screen.options.length ? answer.options.includes(position) : !!row.checked && !!typed;
34843
+ if (wanted === !!row.checked) continue;
34844
+ const box = (value2) => matches(value2, index2) ? !!(position < value2.options.length ? value2.options[position] : value2.other)?.checked : void 0;
34845
+ for (let attempt = 0; attempt < 2 && box(screen) !== wanted; attempt++) {
34846
+ await io.keys([String(row.number)]);
34847
+ screen = await settle2((value2) => box(value2) === wanted ? value2 : void 0, 1e3) ?? screen;
34848
+ }
34849
+ if (box(screen) !== wanted) throw changed("The terminal's checkboxes did not match the answer.");
34850
+ }
34851
+ if (typed) {
34852
+ const other = screen.other, cursor = typeof screen.cursor === "number" ? screen.cursor : 1;
34853
+ if (cursor !== other.number) await io.keys(Array(Math.abs(other.number - cursor)).fill(other.number > cursor ? "down" : "up"));
34854
+ if (!await settle2((value2) => matches(value2, index2) && value2.cursor === other.number ? value2 : void 0)) throw changed("Could not reach the typed answer row.");
34855
+ await io.keys(typedKeys(typed));
34856
+ const shown = await settle2((value2) => matches(value2, index2) && value2.other?.checked && normalize(value2.other.label).startsWith(normalize(typed).slice(0, 20)) ? value2 : void 0);
34857
+ if (!shown) throw changed("The typed answer did not appear in the terminal.");
34858
+ await io.keys(["tab"]);
34859
+ if (!await settle2((value2) => matches(value2, index2) && value2.cursor === "next" ? value2 : void 0)) throw changed("Could not reach the question's Next row.");
34860
+ await io.keys(["enter"]);
34861
+ } else {
34862
+ await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
34863
+ }
34864
+ if (!await settle2(leaves(index2))) throw changed("The terminal did not move past the question.");
34865
+ }
34866
+ if (!submit) return;
34867
+ const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0);
34868
+ if (review === "gone") return;
34869
+ if (!review) throw changed("The terminal did not reach the review of the answers.");
34870
+ const expected = questions.map((question2) => normalize(question2.question));
34871
+ if (review.answers.length !== questions.length || review.answers.some((row, position) => normalize(row.question) !== expected[position] || !row.answer)) {
34872
+ throw changed("Not every question has an answer in the terminal.");
34873
+ }
34874
+ await io.keys(["1"]);
34875
+ if (await settle2((value2) => value2 === void 0 ? "gone" : void 0) !== "gone") throw changed("The terminal did not submit the answers.");
34876
+ }
34877
+
34689
34878
  // src/bridge/terminal-choice.ts
34690
34879
  init_zod();
34691
34880
  init_protocol();
@@ -35284,14 +35473,13 @@ var AgentHooks = class {
35284
35473
  }
35285
35474
  return;
35286
35475
  }
35287
- if (entry?.questions?.length) {
35288
- if (!active) {
35289
- this.terminalPrompts.delete(key);
35290
- this.passwords.delete(key);
35291
- }
35476
+ const question2 = !!entry?.questions?.length;
35477
+ if (question2 && !active) {
35478
+ this.terminalPrompts.delete(key);
35479
+ this.passwords.delete(key);
35292
35480
  return;
35293
35481
  }
35294
- if (entry && !entry.dialog && entry.choice && !entry.released) return;
35482
+ if (!question2 && entry && !entry.dialog && entry.choice && !entry.released) return;
35295
35483
  if (!active) {
35296
35484
  if (entry) this.terminalPrompts.delete(key);
35297
35485
  this.passwords.delete(key);
@@ -35304,6 +35492,14 @@ var AgentHooks = class {
35304
35492
  const text3 = await this.paneLines(target);
35305
35493
  this.passwords.set(key, passwordLine(text3));
35306
35494
  while (this.passwords.size > 128) this.passwords.delete(this.passwords.keys().next().value);
35495
+ if (target.source === "claude" && claudeQuestionDialog(text3)) {
35496
+ if (entry && !question2) this.terminalPrompts.delete(key);
35497
+ return;
35498
+ }
35499
+ if (question2) {
35500
+ this.terminalPrompts.delete(key);
35501
+ return;
35502
+ }
35307
35503
  const dialog = target.source === "codex" ? visibleTerminalChoice(text3) : numberedDialog(text3);
35308
35504
  if (entry && !entry.dialog) {
35309
35505
  if (dialog?.title) {
@@ -35363,24 +35559,40 @@ var AgentHooks = class {
35363
35559
  }
35364
35560
  throw new BridgeError(409, "Could not move and verify the terminal selection. Open terminal to choose this option.");
35365
35561
  }
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) {
35562
+ /** Answer Claude's AskUserQuestion dialog in the pane: every question in
35563
+ * `answers` from `from` on, then the set's submission when `submit`. The
35564
+ * walk reads the pane before and after each key, so a dialog on another
35565
+ * tab, a changed question or a missed key stops it with nothing stray
35566
+ * typed. A finished set clears the remembered question. */
35567
+ async answerClaudeQuestions(target, questions, answers, options = {}) {
35568
+ const key = JSON.stringify(target);
35569
+ await answerClaudeQuestionDialog({
35570
+ read: () => this.paneLines(target),
35571
+ keys: async (keys) => {
35572
+ if (!keys.length) return;
35573
+ await validateTarget(target, false, true);
35574
+ await rpc(target.server, "agent.send_keys", { target: target.pane, keys });
35575
+ }
35576
+ }, questions, answers, options);
35577
+ this.dialogReads.delete(key);
35578
+ if (options.submit ?? true) this.terminalPrompts.delete(key);
35579
+ }
35580
+ /** An older phone answers a released AskUserQuestion one question at a
35581
+ * time with the chosen digits through `/v1/keys`. Walk that question with
35582
+ * the same verified steps and submit after the last. False when the
35583
+ * prompt is not a remembered question, so the keys take the usual path. */
35584
+ async answerReleasedQuestion(target, keys) {
35372
35585
  const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
35373
- if (!entry?.questions?.length) return void 0;
35586
+ if (target.source !== "claude" || !entry?.questions?.length) return false;
35374
35587
  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"];
35588
+ if (!digits.length) return false;
35589
+ const index2 = Math.min(entry.questionIndex ?? 0, entry.questions.length - 1), last = index2 + 1 >= entry.questions.length;
35590
+ await this.answerClaudeQuestions(target, entry.questions, [{ options: digits.map((digit) => Number(digit) - 1) }], { from: index2, submit: last });
35591
+ if (!last) {
35592
+ entry.questionIndex = index2 + 1;
35593
+ entry.choice = questionChoice(entry.questions, index2 + 1);
35380
35594
  }
35381
- entry.questionIndex = next;
35382
- entry.choice = questionChoice(entry.questions, next);
35383
- return [...digits, "Tab"];
35595
+ return true;
35384
35596
  }
35385
35597
  startCompacting(target) {
35386
35598
  this.compactingSince.set(JSON.stringify(target), Date.now());
@@ -35868,7 +36080,7 @@ var AgentHooks = class {
35868
36080
  this.server.listen(localSocket(), () => resolve11());
35869
36081
  });
35870
36082
  await chmod(localSocket(), 384);
35871
- await mkdir8(this.approvalsDirectory(), { recursive: true, mode: 448 }).catch(() => {
36083
+ await mkdir9(this.approvalsDirectory(), { recursive: true, mode: 448 }).catch(() => {
35872
36084
  });
35873
36085
  try {
35874
36086
  this.opencodeWatcher = watch(this.approvalsDirectory(), { persistent: false }, () => this.scheduleOpencodeSweep());
@@ -35999,13 +36211,13 @@ import { execFile as execFile4 } from "node:child_process";
35999
36211
  import { promisify as promisify4 } from "node:util";
36000
36212
  import { request as request2 } from "node:http";
36001
36213
  import { userInfo } from "node:os";
36002
- import { readFile as readFile15, realpath as realpath7, stat as stat10 } from "node:fs/promises";
36214
+ import { readFile as readFile15, realpath as realpath7, stat as stat11 } from "node:fs/promises";
36003
36215
  import path37 from "node:path";
36004
36216
 
36005
36217
  // src/bridge/locate.ts
36006
36218
  init_protocol();
36007
36219
  import { realpathSync as realpathSync3 } from "node:fs";
36008
- import { readFile as readFile14, stat as stat9 } from "node:fs/promises";
36220
+ import { readFile as readFile14, stat as stat10 } from "node:fs/promises";
36009
36221
  import { homedir as homedir8 } from "node:os";
36010
36222
  import path36 from "node:path";
36011
36223
  init_transcripts();
@@ -36018,7 +36230,7 @@ async function locateProject(project, activity, env = process.env) {
36018
36230
  const offer = async (directory, source, lastSeen) => {
36019
36231
  let dir = path36.resolve(directory);
36020
36232
  try {
36021
- if (!(await stat9(dir)).isDirectory()) return;
36233
+ if (!(await stat10(dir)).isDirectory()) return;
36022
36234
  dir = realpathSync3.native(dir);
36023
36235
  } catch {
36024
36236
  return;
@@ -36113,7 +36325,7 @@ async function resolveTouched(raw, cwd) {
36113
36325
  const home = homeDir();
36114
36326
  const absolute = raw === "~" || raw.startsWith("~/") ? path37.join(home, raw.slice(1)) : path37.resolve(cwd, raw);
36115
36327
  let existing = absolute, rest = [];
36116
- while (!await stat10(existing).catch(() => void 0)) {
36328
+ while (!await stat11(existing).catch(() => void 0)) {
36117
36329
  const parent = path37.dirname(existing);
36118
36330
  if (parent === existing) return void 0;
36119
36331
  rest.unshift(path37.basename(existing));
@@ -36136,7 +36348,7 @@ async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
36136
36348
  const files = await statusFiles(root);
36137
36349
  const byRoot = /* @__PURE__ */ new Map();
36138
36350
  for (const file2 of requested) {
36139
- const owner = await gitRoot((await stat10(file2).catch(() => void 0))?.isDirectory() ? file2 : path37.dirname(file2));
36351
+ const owner = await gitRoot((await stat11(file2).catch(() => void 0))?.isDirectory() ? file2 : path37.dirname(file2));
36140
36352
  if (!owner) continue;
36141
36353
  const rel = (path37.relative(owner, file2) || ".").split(path37.sep).join("/");
36142
36354
  if (rel.startsWith(":")) throw new BridgeError(400, "Invalid diff pathspec.");
@@ -36165,7 +36377,7 @@ async function headFile(cwd) {
36165
36377
  let directory = cwd;
36166
36378
  for (let depth = 0; depth < 64; depth++) {
36167
36379
  const dotGit = path37.join(directory, ".git");
36168
- const info = await stat10(dotGit).catch(() => void 0);
36380
+ const info = await stat11(dotGit).catch(() => void 0);
36169
36381
  if (info?.isDirectory()) return path37.join(dotGit, "HEAD");
36170
36382
  if (info?.isFile()) {
36171
36383
  const match = /^gitdir:\s*(.+)$/m.exec(await readFile15(dotGit, "utf8").catch(() => ""));
@@ -36314,7 +36526,7 @@ async function launchDirectory(raw, activity = [], located = []) {
36314
36526
  let dir;
36315
36527
  try {
36316
36528
  dir = await realpath7(raw);
36317
- if (!(await stat10(dir)).isDirectory()) throw new Error();
36529
+ if (!(await stat11(dir)).isDirectory()) throw new Error();
36318
36530
  } catch {
36319
36531
  throw new BridgeError(400, "Workspace directory does not exist.");
36320
36532
  }
@@ -36629,7 +36841,7 @@ var CodeRoutes = class {
36629
36841
  const project = projectSchema.parse(projectValue ?? "");
36630
36842
  const { codeDatabasePath } = await requireCodePackage(this.store);
36631
36843
  const file2 = codeDatabasePath(this.store, project);
36632
- await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path79) => rm4(path79, { force: true })));
36844
+ await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path81) => rm4(path81, { force: true })));
36633
36845
  return { project, disabled: true };
36634
36846
  }
36635
36847
  async reindex(projectValue) {
@@ -36793,7 +37005,7 @@ function readHead(root) {
36793
37005
  }
36794
37006
 
36795
37007
  // src/bridge/context.ts
36796
- import { open as open5 } from "node:fs/promises";
37008
+ import { open as open6 } from "node:fs/promises";
36797
37009
  import { constants } from "node:fs";
36798
37010
  init_protocol();
36799
37011
  init_transcripts();
@@ -36828,15 +37040,15 @@ function codexContext(tail, startsAtBeginning) {
36828
37040
  var ContextUsageReader = class {
36829
37041
  cache = /* @__PURE__ */ new Map();
36830
37042
  async read(file2, session) {
36831
- const handle = await open5(file2, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
37043
+ const handle = await open6(file2, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
36832
37044
  try {
36833
37045
  const metadata = await handle.stat();
36834
37046
  if (!metadata.isFile()) return void 0;
36835
37047
  const key = `codex:${session}:${file2}`;
36836
- const stat24 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
37048
+ const stat25 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
36837
37049
  const cached2 = this.cache.get(key);
36838
37050
  this.cache.delete(key);
36839
- if (cached2?.stat === stat24) {
37051
+ if (cached2?.stat === stat25) {
36840
37052
  this.cache.set(key, cached2);
36841
37053
  return cached2.percent;
36842
37054
  }
@@ -36847,7 +37059,7 @@ var ContextUsageReader = class {
36847
37059
  const after = await handle.stat();
36848
37060
  if (after.size !== metadata.size || after.mtimeMs !== metadata.mtimeMs || after.ctimeMs !== metadata.ctimeMs) return void 0;
36849
37061
  const percent = codexContext(tail, start === 0);
36850
- this.cache.set(key, { stat: stat24, percent });
37062
+ this.cache.set(key, { stat: stat25, percent });
36851
37063
  while (this.cache.size > MAX_SESSIONS) this.cache.delete(this.cache.keys().next().value);
36852
37064
  return percent;
36853
37065
  } finally {
@@ -36924,12 +37136,12 @@ init_zod();
36924
37136
  init_logger();
36925
37137
  init_project_config();
36926
37138
  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";
37139
+ import { lstat as lstat11, mkdir as mkdir12, readFile as readFile20, readdir as readdir8, realpath as realpath9, stat as stat13 } from "node:fs/promises";
36928
37140
  import path46 from "node:path";
36929
37141
 
36930
37142
  // src/bridge/computers.ts
36931
37143
  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";
37144
+ 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
37145
  import { homedir as homedir13 } from "node:os";
36934
37146
  import path44 from "node:path";
36935
37147
  import { promisify as promisify7 } from "node:util";
@@ -36944,7 +37156,7 @@ init_fanouts();
36944
37156
  init_protocol();
36945
37157
  import { execFile as execFile5, spawn as spawn2 } from "node:child_process";
36946
37158
  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";
37159
+ import { lstat as lstat7, open as open7, readFile as readFile16, readdir as readdir7, realpath as realpath8, stat as stat12 } from "node:fs/promises";
36948
37160
  import { homedir as homedir10 } from "node:os";
36949
37161
  import path41 from "node:path";
36950
37162
  import { promisify as promisify5 } from "node:util";
@@ -37022,10 +37234,10 @@ var openCodeAuthFile = () => path41.join(
37022
37234
  );
37023
37235
  async function readOpenRouterKey() {
37024
37236
  try {
37025
- const handle = await open6(openCodeAuthFile(), "r");
37237
+ const handle = await open7(openCodeAuthFile(), "r");
37026
37238
  try {
37027
- const stat24 = await handle.stat();
37028
- if (!stat24.isFile() || stat24.size > 65536) return void 0;
37239
+ const stat25 = await handle.stat();
37240
+ if (!stat25.isFile() || stat25.size > 65536) return void 0;
37029
37241
  const key = object2(object2(JSON.parse(await handle.readFile("utf8"))).openrouter).key;
37030
37242
  return typeof key === "string" && key.length >= 16 && key.length <= 4096 && !/[\x00-\x1f\x7f]/.test(key) ? key : void 0;
37031
37243
  } finally {
@@ -37037,7 +37249,7 @@ async function readOpenRouterKey() {
37037
37249
  }
37038
37250
  async function readOpenCodeGoKey() {
37039
37251
  try {
37040
- const handle = await open6(openCodeAuthFile(), "r");
37252
+ const handle = await open7(openCodeAuthFile(), "r");
37041
37253
  try {
37042
37254
  const metadata = await handle.stat();
37043
37255
  if (!metadata.isFile() || metadata.size > 65536) return void 0;
@@ -37212,7 +37424,7 @@ async function containedRegularFile(root, candidate, maximum) {
37212
37424
  if (!link.isFile() || link.isSymbolicLink() || link.size > maximum) return void 0;
37213
37425
  const resolved = await realpath8(candidate);
37214
37426
  if (!resolved.startsWith(root + path41.sep)) return void 0;
37215
- const metadata = await stat11(resolved);
37427
+ const metadata = await stat12(resolved);
37216
37428
  return metadata.isFile() && metadata.size <= maximum ? resolved : void 0;
37217
37429
  } catch {
37218
37430
  return void 0;
@@ -37647,10 +37859,10 @@ var AccountUsageReader = class {
37647
37859
  async snapshotClaude() {
37648
37860
  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
37861
  try {
37650
- const handle = await open6(claudeFile(), "r");
37862
+ const handle = await open7(claudeFile(), "r");
37651
37863
  try {
37652
- const stat24 = await handle.stat();
37653
- if (!stat24.isFile() || stat24.size > 16384) throw new Error("Invalid usage snapshot");
37864
+ const stat25 = await handle.stat();
37865
+ if (!stat25.isFile() || stat25.size > 16384) throw new Error("Invalid usage snapshot");
37654
37866
  const saved = object2(JSON.parse(await handle.readFile("utf8")));
37655
37867
  const date5 = new Date(String(saved.updatedAt));
37656
37868
  if (!Number.isFinite(date5.getTime()) || date5.getTime() > this.now() + 6e4) throw new Error("Invalid usage timestamp");
@@ -37661,10 +37873,10 @@ var AccountUsageReader = class {
37661
37873
  } catch {
37662
37874
  }
37663
37875
  try {
37664
- const handle = await open6(claudeConfigFile(), "r");
37876
+ const handle = await open7(claudeConfigFile(), "r");
37665
37877
  try {
37666
- const stat24 = await handle.stat();
37667
- if (!stat24.isFile() || stat24.size > 16777216) throw new Error("Invalid Claude config");
37878
+ const stat25 = await handle.stat();
37879
+ if (!stat25.isFile() || stat25.size > 16777216) throw new Error("Invalid Claude config");
37668
37880
  const scoped = claudeScopedWindows(JSON.parse(await handle.readFile("utf8")), new Date(this.now())).filter((entry) => !claude2.windows.some((existing) => existing.id === entry.id));
37669
37881
  if (scoped.length) claude2 = { ...claude2, windows: [...claude2.windows, ...scoped], message: void 0 };
37670
37882
  } finally {
@@ -37723,7 +37935,7 @@ async function captureClaudeUsage(original) {
37723
37935
  // src/bridge/install.ts
37724
37936
  init_home_paths();
37725
37937
  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";
37938
+ 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
37939
  import { homedir as homedir12 } from "node:os";
37728
37940
  import path43 from "node:path";
37729
37941
  import { fileURLToPath as fileURLToPath4 } from "node:url";
@@ -37878,7 +38090,7 @@ function keyOptions(line) {
37878
38090
  return void 0;
37879
38091
  }
37880
38092
  function upgradeKeys(text3) {
37881
- let changed = 0;
38093
+ let changed2 = 0;
37882
38094
  const result = text3.split(/(?<=\n)/).map((line) => {
37883
38095
  const parsed = keyOptions(line);
37884
38096
  if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest)) return line;
@@ -37887,10 +38099,10 @@ function upgradeKeys(text3) {
37887
38099
  const options = parsed.options.filter((option) => option.toLowerCase() !== "port-forwarding" && !option.toLowerCase().startsWith("permitopen=")).map((option) => old.test(option) ? forcedCommand : option);
37888
38100
  if (!options.includes("pty")) options.splice(1, 0, "pty");
37889
38101
  const next = options.join(",") + parsed.rest;
37890
- if (next !== line) changed++;
38102
+ if (next !== line) changed2++;
37891
38103
  return next;
37892
38104
  }).join("");
37893
- return { text: result, changed };
38105
+ return { text: result, changed: changed2 };
37894
38106
  }
37895
38107
  var quote2 = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
37896
38108
  var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -37983,10 +38195,10 @@ async function install(version3, noService = false) {
37983
38195
  const modules = activateModules(defaultPhrenPath(), void 0, true);
37984
38196
  if (!modules.has("hook")) throw new Error(disabledHint("hook"));
37985
38197
  const root = bridgeRoot(), herdr = herdrRoot(), versions = path43.join(root, "versions");
37986
- await mkdir9(versions, { recursive: true, mode: 448 });
38198
+ await mkdir10(versions, { recursive: true, mode: 448 });
37987
38199
  await chmod2(root, 448);
37988
38200
  const serviceLog = path43.join(root, "service.log");
37989
- const log2 = await open7(serviceLog, "a", 384);
38201
+ const log2 = await open8(serviceLog, "a", 384);
37990
38202
  try {
37991
38203
  await log2.chmod(384);
37992
38204
  } finally {
@@ -37996,7 +38208,7 @@ async function install(version3, noService = false) {
37996
38208
  const own2 = fileURLToPath4(import.meta.url);
37997
38209
  const bundle = own2.endsWith("bridge-hook.mjs") ? own2 : path43.join(path43.dirname(own2), "..", "bridge-hook.mjs");
37998
38210
  const destination2 = path43.join(versions, version3);
37999
- await mkdir9(destination2, { recursive: true, mode: 448 });
38211
+ await mkdir10(destination2, { recursive: true, mode: 448 });
38000
38212
  const installedBundle = path43.join(destination2, "bridge-hook.mjs");
38001
38213
  const previousBundle = await missingFile(readFile17(installedBundle));
38002
38214
  const stagedBundle = installedBundle + `.phren-${process.pid}`;
@@ -38019,14 +38231,14 @@ async function install(version3, noService = false) {
38019
38231
  if (!noService) {
38020
38232
  if (process.platform === "darwin") {
38021
38233
  const folder = path43.join(homedir12(), "Library/LaunchAgents");
38022
- await mkdir9(folder, { recursive: true });
38234
+ await mkdir10(folder, { recursive: true });
38023
38235
  await atomic(path43.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>
38024
38236
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
38025
38237
  <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
38238
  `);
38027
38239
  } else {
38028
38240
  const folder = path43.join(homedir12(), ".config/systemd/user");
38029
- await mkdir9(folder, { recursive: true });
38241
+ await mkdir10(folder, { recursive: true });
38030
38242
  await atomic(path43.join(folder, unit), `[Unit]
38031
38243
  Description=Phren Hook
38032
38244
  [Service]
@@ -38203,13 +38415,13 @@ async function applyOpencodePlugin(remove = false) {
38203
38415
  }
38204
38416
  if (source === void 0 || !opencodePluginNeedsWrite(existing, source)) return false;
38205
38417
  if (!(await lstat8(path43.dirname(dir)).catch(() => null))?.isDirectory()) return false;
38206
- await mkdir9(dir, { recursive: true });
38418
+ await mkdir10(dir, { recursive: true });
38207
38419
  await atomic(file2, source, 420);
38208
38420
  return true;
38209
38421
  }
38210
38422
  async function applyAgentHooks(edits) {
38211
38423
  for (const { file: file2, before, after } of edits) {
38212
- await mkdir9(path43.dirname(file2), { recursive: true, mode: 448 });
38424
+ await mkdir10(path43.dirname(file2), { recursive: true, mode: 448 });
38213
38425
  if (await missingFile(readFile17(file2, "utf8")) !== before) throw new Error("Agent settings changed during installation. Run install again.");
38214
38426
  if (before !== void 0) await copyFile2(file2, file2 + `.phren-hook-${Date.now()}.bak`);
38215
38427
  await atomic(file2, after);
@@ -38258,11 +38470,11 @@ async function regularFile(file2) {
38258
38470
  }
38259
38471
  async function enrollComputer(name, root = bridgeRoot()) {
38260
38472
  computerName.parse(name);
38261
- await mkdir10(root, { recursive: true, mode: 448 });
38473
+ await mkdir11(root, { recursive: true, mode: 448 });
38262
38474
  await chmod3(root, 448);
38263
38475
  const lock = path44.join(root, "enroll-computer.lock");
38264
38476
  try {
38265
- await mkdir10(lock, { mode: 448 });
38477
+ await mkdir11(lock, { mode: 448 });
38266
38478
  } catch {
38267
38479
  throw new BridgeError(409, "Computer enrollment is already running; inspect enroll-computer.lock if interrupted.");
38268
38480
  }
@@ -38291,13 +38503,22 @@ async function acceptComputer(name, input2, sshDirectory = path44.join(homedir13
38291
38503
  const raw = input2.trim();
38292
38504
  const publicKey = publicComputerKey(raw.startsWith(prefix) ? raw.slice(prefix.length) : raw);
38293
38505
  const line = computerKeyLine(name, publicKey);
38506
+ const encoded = publicKey.split(" ")[1];
38507
+ await appendAuthorizedKey(
38508
+ line,
38509
+ (existing) => existing.endsWith(` phren-computer:${name}`) || existing.split(/\s+/).includes(encoded),
38510
+ "This name or key is already enrolled differently. Revoke the old line explicitly first.",
38511
+ sshDirectory
38512
+ );
38513
+ }
38514
+ async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory = path44.join(homedir13(), ".ssh")) {
38294
38515
  const directory = await lstat9(sshDirectory).catch(() => void 0);
38295
38516
  if (directory && (!directory.isDirectory() || directory.isSymbolicLink())) throw new BridgeError(409, "Refusing an unexpected SSH directory.");
38296
- await mkdir10(sshDirectory, { recursive: true, mode: 448 });
38517
+ await mkdir11(sshDirectory, { recursive: true, mode: 448 });
38297
38518
  await chmod3(sshDirectory, 448);
38298
38519
  const lock = path44.join(sshDirectory, ".phren-enroll.lock");
38299
38520
  try {
38300
- await mkdir10(lock, { mode: 448 });
38521
+ await mkdir11(lock, { mode: 448 });
38301
38522
  } catch {
38302
38523
  throw new BridgeError(409, "SSH enrollment is already running; inspect .phren-enroll.lock if interrupted.");
38303
38524
  }
@@ -38310,10 +38531,7 @@ async function acceptComputer(name, input2, sshDirectory = path44.join(homedir13
38310
38531
  await chmod3(file2, 384);
38311
38532
  return;
38312
38533
  }
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
- }
38534
+ if (lines.some(conflicts)) throw new BridgeError(409, conflictMessage);
38317
38535
  await writeFile5(temporary, before + (before && !before.endsWith("\n") ? "\n" : "") + line + "\n", { mode: 384, flag: "wx" });
38318
38536
  const current = await regularFile(file2) ? await readFile18(file2, "utf8") : "";
38319
38537
  if (current !== before) throw new BridgeError(409, "authorized_keys changed during enrollment. Try again.");
@@ -38412,10 +38630,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
38412
38630
  for (const value2 of values.slice(0, 128)) {
38413
38631
  if (state.count >= 128) break;
38414
38632
  const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
38415
- const path79 = publicLabel(raw.path);
38633
+ const path81 = publicLabel(raw.path);
38416
38634
  const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
38417
38635
  const routed = destination(raw, fallbackComputer, fallbackTarget);
38418
- if (!id2.success || !source.success || !path79 || !callId || !routed) continue;
38636
+ if (!id2.success || !source.success || !path81 || !callId || !routed) continue;
38419
38637
  const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
38420
38638
  const nestedSession = sessionId.safeParse(raw.session);
38421
38639
  const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
@@ -38428,7 +38646,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
38428
38646
  projected.push({
38429
38647
  id: publicID(parent, routed.computer.id, receipt.id, descendant),
38430
38648
  provider: source.data,
38431
- path: path79,
38649
+ path: path81,
38432
38650
  callId,
38433
38651
  state: raw.failed === true ? "failed" : childState,
38434
38652
  ...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
@@ -38513,6 +38731,20 @@ async function hookPeers(root = bridgeRoot()) {
38513
38731
  if (new Set(computers.map((peer) => peer.name)).size !== computers.length) throw new BridgeError(409, "hooks.yaml has duplicate computer names.");
38514
38732
  return computers;
38515
38733
  }
38734
+ async function addHookPeer(input2, root = bridgeRoot()) {
38735
+ const peer = peerSchema.parse(input2);
38736
+ const existing = await hookPeers(root).catch((error62) => {
38737
+ if (error62 instanceof BridgeError && error62.details?.hooksYaml === "missing") return [];
38738
+ throw error62;
38739
+ });
38740
+ const same = (other) => JSON.stringify(peerSchema.parse(other)) === JSON.stringify(peer);
38741
+ if (existing.some(same)) return { added: false, peer };
38742
+ const clash = existing.find((other) => other.name === peer.name || other.address === peer.address && other.port === peer.port && other.server === peer.server);
38743
+ if (clash) throw new BridgeError(409, `hooks.yaml already has ${clash.name} at ${clash.address}; remove that entry first to link it differently.`);
38744
+ if (existing.length >= 32) throw new BridgeError(409, "hooks.yaml already has 32 computers.");
38745
+ await atomic(path45.join(root, "hooks.yaml"), dump({ version: 1, computers: [...existing, peer] }, { lineWidth: -1 }));
38746
+ return { added: true, peer };
38747
+ }
38516
38748
  async function optionalHookPeers(root = bridgeRoot()) {
38517
38749
  try {
38518
38750
  return { peers: await hookPeers(root) };
@@ -38597,34 +38829,34 @@ async function peerRequest(peer, route, data, timeout) {
38597
38829
  const knownHosts = path45.join(temporary, "known_hosts");
38598
38830
  await writeFile6(knownHosts, `phren-peer ${peer.hostKey}
38599
38831
  `, { mode: 384 });
38600
- const ssh = spawn4("ssh", peerSSHArgs(peer, knownHosts, key), { stdio: ["pipe", "pipe", "pipe"] });
38601
- child = ssh;
38832
+ const ssh2 = spawn4("ssh", peerSSHArgs(peer, knownHosts, key), { stdio: ["pipe", "pipe", "pipe"] });
38833
+ child = ssh2;
38602
38834
  stream = new Duplex({
38603
38835
  read() {
38604
- ssh.stdout.resume();
38836
+ ssh2.stdout.resume();
38605
38837
  },
38606
38838
  write(chunk, encoding, callback) {
38607
- ssh.stdin.write(chunk, encoding, callback);
38839
+ ssh2.stdin.write(chunk, encoding, callback);
38608
38840
  },
38609
38841
  final(callback) {
38610
- ssh.stdin.end(callback);
38842
+ ssh2.stdin.end(callback);
38611
38843
  },
38612
38844
  destroy(error62, callback) {
38613
- ssh.kill();
38845
+ ssh2.kill();
38614
38846
  callback(error62);
38615
38847
  }
38616
38848
  });
38617
- ssh.stdout.on("data", (chunk) => {
38618
- if (!stream.push(chunk)) ssh.stdout.pause();
38849
+ ssh2.stdout.on("data", (chunk) => {
38850
+ if (!stream.push(chunk)) ssh2.stdout.pause();
38619
38851
  });
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));
38852
+ ssh2.stdout.on("end", () => stream.push(null));
38853
+ ssh2.stdout.on("error", (error62) => stream?.destroy(error62));
38854
+ ssh2.stdin.on("error", (error62) => stream?.destroy(error62));
38623
38855
  let diagnostic = "";
38624
38856
  child.stderr.on("data", (bytes) => {
38625
38857
  diagnostic = (diagnostic + bytes.toString()).slice(-4096);
38626
38858
  });
38627
- const exited = new Promise((resolve11) => ssh.once("exit", (code) => resolve11(code)));
38859
+ const exited = new Promise((resolve11) => ssh2.once("exit", (code) => resolve11(code)));
38628
38860
  child.on("error", (error62) => stream?.destroy(new BridgeError(503, `SSH is unavailable (${error62.code ?? "spawn failed"}).`)));
38629
38861
  try {
38630
38862
  return await hookRequest(route, data, { createConnection: () => stream }, timeout ?? (data === void 0 ? 15e3 : 65e3));
@@ -38732,12 +38964,12 @@ async function dispatchProjectDirectory(project) {
38732
38964
  const source = readProjectConfig(phrenStoreRoot(), name).sourcePath;
38733
38965
  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
38966
  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.");
38967
+ if (!directory || !(await stat13(directory)).isDirectory()) throw new BridgeError(404, "Project is not on this computer.");
38736
38968
  return directory;
38737
38969
  }
38738
38970
  async function save(receipt) {
38739
38971
  const root = path46.join(bridgeRoot(), "dispatches");
38740
- await mkdir11(root, { recursive: true, mode: 448 });
38972
+ await mkdir12(root, { recursive: true, mode: 448 });
38741
38973
  await atomic(path46.join(root, `${receipt.id}.json`), receipt);
38742
38974
  }
38743
38975
  var MAX_RECEIPT_BYTES = 65536;
@@ -38991,6 +39223,8 @@ function sessionsFrom(overview, computer, local, now = Date.now()) {
38991
39223
  const sessions = [];
38992
39224
  for (const group of objects(overview.groups)) for (const tab of objects(group.children)) {
38993
39225
  if (typeof tab.agent !== "string") continue;
39226
+ const inConductorWorkspace = tab.role !== "conductor" && objects(group.children).some((other) => other.role === "conductor");
39227
+ const label2 = inConductorWorkspace ? typeof tab.label === "string" && !/^\d+$/.test(tab.label) ? tab.label : void 0 : group.label;
38994
39228
  const target = targetSchema.safeParse(tab.target);
38995
39229
  const cwd = typeof tab.cwd === "string" ? tab.cwd : "";
38996
39230
  const text3 = (value2) => typeof value2 === "string" && value2 ? value2 : void 0;
@@ -38999,7 +39233,7 @@ function sessionsFrom(overview, computer, local, now = Date.now()) {
38999
39233
  computer,
39000
39234
  local,
39001
39235
  project: tab.role === "conductor" ? void 0 : text3(cwd.split("/").filter(Boolean).at(-1)),
39002
- label: text3(group.label),
39236
+ label: text3(label2),
39003
39237
  title: text3(tab.title),
39004
39238
  agent: tab.agent,
39005
39239
  status: text3(tab.agentStatus),
@@ -39059,7 +39293,7 @@ async function listLiveSessions(options = {}) {
39059
39293
  init_protocol();
39060
39294
 
39061
39295
  // src/bridge/schedule-watch.ts
39062
- import { open as open8, stat as stat13 } from "node:fs/promises";
39296
+ import { open as open9, stat as stat14 } from "node:fs/promises";
39063
39297
  init_protocol();
39064
39298
  init_transcripts();
39065
39299
  var STARTUP_BLOCK_WINDOW_MS = 9e4;
@@ -39153,7 +39387,7 @@ async function readFinalTurn(source, sessionId2) {
39153
39387
  if (!sessionId2) return void 0;
39154
39388
  const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
39155
39389
  if (!file2) return void 0;
39156
- const handle = await open8(file2, "r").catch(() => void 0);
39390
+ const handle = await open9(file2, "r").catch(() => void 0);
39157
39391
  if (!handle) return void 0;
39158
39392
  try {
39159
39393
  const { size } = await handle.stat();
@@ -39193,7 +39427,7 @@ function ownerQuestion(text3) {
39193
39427
  async function realTranscriptStamp(source, sessionId2) {
39194
39428
  if (!sessionId2) return void 0;
39195
39429
  const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
39196
- const metadata = file2 ? await stat13(file2).catch(() => void 0) : void 0;
39430
+ const metadata = file2 ? await stat14(file2).catch(() => void 0) : void 0;
39197
39431
  return metadata ? { size: metadata.size, mtimeMs: metadata.mtimeMs } : void 0;
39198
39432
  }
39199
39433
  async function watchHerdrRun(server, target, signal, startup, env = {}) {
@@ -39328,7 +39562,7 @@ function observe(receipt, value2, now) {
39328
39562
  const parsed = observationSchema.safeParse(value2);
39329
39563
  if (!parsed.success || parsed.data.state === "unavailable" || parsed.data.state === "unknown") return false;
39330
39564
  const seen = parsed.data, at = new Date(now).toISOString();
39331
- let changed = false;
39565
+ let changed2 = false;
39332
39566
  if (seen.session && receipt.target && !("session" in receipt.target)) {
39333
39567
  const full2 = targetSchema.safeParse({
39334
39568
  server: receipt.target.server,
@@ -39340,7 +39574,7 @@ function observe(receipt, value2, now) {
39340
39574
  });
39341
39575
  if (full2.success) {
39342
39576
  receipt.target = full2.data;
39343
- changed = true;
39577
+ changed2 = true;
39344
39578
  }
39345
39579
  }
39346
39580
  const sawWorking = receipt.worker?.sawWorking === true || seen.state === "working" || seen.state === "blocked";
@@ -39359,9 +39593,9 @@ function observe(receipt, value2, now) {
39359
39593
  if (repeated) {
39360
39594
  if (receipt.worker && receipt.worker.sawWorking !== sawWorking) {
39361
39595
  receipt.worker.sawWorking = sawWorking;
39362
- changed = true;
39596
+ changed2 = true;
39363
39597
  }
39364
- return changed;
39598
+ return changed2;
39365
39599
  }
39366
39600
  receipt.worker = { state: next, since: at, checkedAt: at, sawWorking };
39367
39601
  if (next !== "working") {
@@ -39378,13 +39612,13 @@ function observe(receipt, value2, now) {
39378
39612
  return true;
39379
39613
  }
39380
39614
  function noticeLine(receipts) {
39381
- const clean = (value2, max) => value2.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
39615
+ const clean2 = (value2, max) => value2.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
39382
39616
  const word = { "done": "done", "needs-you": "needs you", "failed": "failed", "blocked": "blocked", "gone": "gone" };
39383
39617
  const describe4 = (receipt, room) => {
39384
39618
  const returned = receipt.returned;
39385
39619
  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}` : ""}`;
39620
+ const excerpt = detail ? clean2(detail.replace(/[*_`#>]+/g, ""), room) : "";
39621
+ return `${clean2(receipt.computer, 60)} ${clean2(receipt.label, 80)} ${word[returned.state]}${excerpt ? `, ${excerpt}` : ""}`;
39388
39622
  };
39389
39623
  if (receipts.length === 1) return `Return: ${describe4(receipts[0], 100)} (dispatch ${receipts[0].id}). Call dispatch_returns.`;
39390
39624
  const items = receipts.slice(0, 4).map((receipt) => describe4(receipt, 40)).join("; ");
@@ -39446,11 +39680,11 @@ var DispatchReturns = class {
39446
39680
  /** Ask each peer, once, about every open dispatch placed on it. */
39447
39681
  async poll() {
39448
39682
  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;
39683
+ 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);
39684
+ if (!open15.length) return;
39451
39685
  const peers = await this.peers().catch(() => []);
39452
39686
  const byComputer = /* @__PURE__ */ new Map();
39453
- for (const receipt of open14) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
39687
+ for (const receipt of open15) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
39454
39688
  await Promise.all([...byComputer].map(async ([computer, receipts]) => {
39455
39689
  const peer = peers.find((candidate) => candidate.name === computer);
39456
39690
  const local = !peer && this.isLocal(computer);
@@ -39520,7 +39754,7 @@ init_zod();
39520
39754
  init_protocol();
39521
39755
  import { execFile as execFile8 } from "node:child_process";
39522
39756
  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";
39757
+ import { mkdir as mkdir13, open as open10, stat as stat15, readFile as readFile21, writeFile as writeFile7 } from "node:fs/promises";
39524
39758
  import path47 from "node:path";
39525
39759
  import { promisify as promisify8 } from "node:util";
39526
39760
  init_transcripts();
@@ -39637,7 +39871,7 @@ var CodexQuestions = class {
39637
39871
  const cached2 = this.snapshots.get(target.session);
39638
39872
  let pending = cached2?.pending;
39639
39873
  if (!cached2 || Date.now() - cached2.at > 1e3) {
39640
- const metadata = await stat14(file2), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
39874
+ const metadata = await stat15(file2), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
39641
39875
  pending = cached2?.stamp === stamp ? cached2.pending : await pendingAsyncQuestions(file2).catch((error62) => {
39642
39876
  if (this.failedSnapshots.size >= 64) this.failedSnapshots.delete(this.failedSnapshots.keys().next().value);
39643
39877
  this.failedSnapshots.set(target.session, Date.now());
@@ -39666,10 +39900,10 @@ var CodexQuestions = class {
39666
39900
  const pane = await validateTarget(target);
39667
39901
  if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
39668
39902
  const directory = path47.join(bridgeRoot(), "question-replies");
39669
- await mkdir12(directory, { recursive: true, mode: 448 });
39903
+ await mkdir13(directory, { recursive: true, mode: 448 });
39670
39904
  const key = createHash12("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
39671
39905
  const receiptPath = path47.join(directory, key);
39672
- const receipt = await open9(receiptPath, "wx", 384).catch((error62) => {
39906
+ const receipt = await open10(receiptPath, "wx", 384).catch((error62) => {
39673
39907
  if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
39674
39908
  throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
39675
39909
  });
@@ -39690,7 +39924,7 @@ init_transcripts();
39690
39924
  init_home_paths();
39691
39925
  init_protocol();
39692
39926
  import { spawn as spawn5 } from "node:child_process";
39693
- import { readdir as readdir9, readFile as readFile22, stat as stat15 } from "node:fs/promises";
39927
+ import { readdir as readdir9, readFile as readFile22, stat as stat16 } from "node:fs/promises";
39694
39928
  import { homedir as homedir14 } from "node:os";
39695
39929
  import path48 from "node:path";
39696
39930
  function readCodexModels(executable = "codex") {
@@ -39776,7 +40010,7 @@ async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
39776
40010
  try {
39777
40011
  for (const name of await readdir9(directory)) {
39778
40012
  if (!name.endsWith("-cc.json")) continue;
39779
- const file2 = path48.join(directory, name), at = (await stat15(file2)).mtimeMs;
40013
+ const file2 = path48.join(directory, name), at = (await stat16(file2)).mtimeMs;
39780
40014
  if (!newest || at > newest.at) newest = { file: file2, at };
39781
40015
  }
39782
40016
  } catch {
@@ -40575,7 +40809,7 @@ init_home_paths();
40575
40809
  init_fanouts();
40576
40810
  import { spawn as spawn6 } from "node:child_process";
40577
40811
  import { createWriteStream } from "node:fs";
40578
- import { mkdir as mkdir13, readFile as readFile24, stat as stat16 } from "node:fs/promises";
40812
+ import { mkdir as mkdir14, readFile as readFile24, stat as stat17 } from "node:fs/promises";
40579
40813
  import path50 from "node:path";
40580
40814
  import { finished as streamFinished } from "node:stream/promises";
40581
40815
  init_protocol();
@@ -40640,7 +40874,7 @@ async function promptWhenReady(server, paneId, text3, signal, waitMs = 6e4) {
40640
40874
  }
40641
40875
  async function launchHeadless(context, store, started) {
40642
40876
  const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path50.join(root, context.runId);
40643
- await mkdir13(jobDir, { recursive: true, mode: 448 });
40877
+ await mkdir14(jobDir, { recursive: true, mode: 448 });
40644
40878
  const eventLog = "events.jsonl", now = (/* @__PURE__ */ new Date()).toISOString();
40645
40879
  const manifest = {
40646
40880
  schemaVersion: 1,
@@ -40756,8 +40990,8 @@ async function ensureCodexDirTrusted(cwd) {
40756
40990
  ${trustLine}
40757
40991
  `;
40758
40992
  }
40759
- await mkdir13(directory, { recursive: true, mode: 448 });
40760
- const metadata = await stat16(file2).catch(() => void 0);
40993
+ await mkdir14(directory, { recursive: true, mode: 448 });
40994
+ const metadata = await stat17(file2).catch(() => void 0);
40761
40995
  const mode = metadata ? metadata.mode & 511 : 384;
40762
40996
  await atomic(file2, next, mode);
40763
40997
  }
@@ -41337,7 +41571,7 @@ init_shared();
41337
41571
 
41338
41572
  // src/bridge/server-routes.ts
41339
41573
  init_zod();
41340
- import path77 from "node:path";
41574
+ import path78 from "node:path";
41341
41575
 
41342
41576
  // src/bridge/code-note.ts
41343
41577
  init_zod();
@@ -42033,8 +42267,8 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
42033
42267
  } catch (e) {
42034
42268
  if (e.code === "EEXIST") {
42035
42269
  try {
42036
- const stat24 = fs27.statSync(lockFile);
42037
- if (Date.now() - stat24.mtimeMs < STALE_LOCK_MS) {
42270
+ const stat25 = fs27.statSync(lockFile);
42271
+ if (Date.now() - stat25.mtimeMs < STALE_LOCK_MS) {
42038
42272
  return phrenErr("Consolidation already running", PhrenError.LOCK_TIMEOUT);
42039
42273
  }
42040
42274
  tryUnlink(lockFile);
@@ -42461,6 +42695,7 @@ function canonicalTaskFilePath(phrenPath, project) {
42461
42695
  function resolveTaskFilePath(phrenPath, project) {
42462
42696
  return canonicalTaskFilePath(phrenPath, project);
42463
42697
  }
42698
+ var STALE_CLAIM_MS = 24 * 60 * 60 * 1e3;
42464
42699
 
42465
42700
  // src/data/access.ts
42466
42701
  init_profile_store();
@@ -42689,16 +42924,16 @@ function jaccardSimilarity(a, b) {
42689
42924
  }
42690
42925
  var ENTITY_CACHE_TTL_MS = 60 * 60 * 1e3;
42691
42926
  function isDuplicateFinding(existingContent, newLearning, threshold = 0.6) {
42692
- const normalize = (text3) => {
42927
+ const normalize2 = (text3) => {
42693
42928
  return stripHtmlComments(text3).trim().toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((w) => w.length > 2 && !DEDUP_STOP_WORDS.has(w));
42694
42929
  };
42695
- const newWords = normalize(newLearning);
42930
+ const newWords = normalize2(newLearning);
42696
42931
  if (newWords.length === 0) return false;
42697
42932
  const newSet = new Set(newWords);
42698
42933
  const bullets = existingContent.split("\n").filter((l) => l.startsWith("- "));
42699
42934
  for (const bullet of bullets) {
42700
42935
  if (isInactiveFindingLine(bullet)) continue;
42701
- const existingWords = normalize(bullet);
42936
+ const existingWords = normalize2(bullet);
42702
42937
  if (existingWords.length === 0) continue;
42703
42938
  const existingSet = new Set(existingWords);
42704
42939
  let overlap = 0;
@@ -42837,14 +43072,14 @@ function parseTaskItems(taskPath) {
42837
43072
  counters[section] += 1;
42838
43073
  const itemId = `${section === "Active" ? "A" : section === "Queue" ? "Q" : "D"}${counters[section]}`;
42839
43074
  const stripped = stripBulletPrefix(line).body;
42840
- const { clean, bid } = stripBid(stripped);
43075
+ const { clean: clean2, bid } = stripBid(stripped);
42841
43076
  items.push({
42842
43077
  id: itemId,
42843
43078
  stableId: bid,
42844
43079
  section,
42845
- line: clean,
42846
- priority: normalizePriority(clean),
42847
- pinned: detectPinned(clean) || void 0
43080
+ line: clean2,
43081
+ priority: normalizePriority(clean2),
43082
+ pinned: detectPinned(clean2) || void 0
42848
43083
  });
42849
43084
  }
42850
43085
  return items;
@@ -43296,7 +43531,7 @@ init_protocol();
43296
43531
  import { execFile as execFile10 } from "node:child_process";
43297
43532
  import { promisify as promisify10 } from "node:util";
43298
43533
  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";
43534
+ import { readdir as readdir10, readFile as readFile26, stat as stat18, mkdir as mkdir15 } from "node:fs/promises";
43300
43535
  import { homedir as homedir16 } from "node:os";
43301
43536
  import path66 from "node:path";
43302
43537
  init_transcripts();
@@ -43508,8 +43743,8 @@ function addTermCount(terms, rawText, weight = 1) {
43508
43743
  }
43509
43744
  function maybeReadUtf8(filePath, maxBytes = 256e3) {
43510
43745
  try {
43511
- const stat24 = fs31.statSync(filePath);
43512
- if (!stat24.isFile() || stat24.size > maxBytes) return "";
43746
+ const stat25 = fs31.statSync(filePath);
43747
+ if (!stat25.isFile() || stat25.size > maxBytes) return "";
43513
43748
  return fs31.readFileSync(filePath, "utf8");
43514
43749
  } catch {
43515
43750
  return "";
@@ -44328,29 +44563,29 @@ function resolveStoreConflicts(cwd) {
44328
44563
  // src/sync/store-merge.ts
44329
44564
  init_machine_identity();
44330
44565
  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"]);
44566
+ async function commitLocalStoreWrites(cwd, git7, message) {
44567
+ const add = await git7(cwd, ["add", "--sparse", "-A"]);
44333
44568
  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"]);
44569
+ await git7(cwd, ["reset", "HEAD", "--", ...SENSITIVE_STORE_PATHSPECS]);
44570
+ const staged = await git7(cwd, ["diff", "--cached", "--name-only"]);
44336
44571
  if (!staged.ok) return { committed: false, error: staged.error || "git diff failed" };
44337
44572
  if (!staged.output) return { committed: false };
44338
- const commit = await git6(cwd, ["-c", "commit.gpgsign=false", "commit", "-m", storeCommitMessage(message)]);
44573
+ const commit = await git7(cwd, ["-c", "commit.gpgsign=false", "commit", "-m", storeCommitMessage(message)]);
44339
44574
  return commit.ok ? { committed: true } : { committed: false, error: commit.error || "git commit failed" };
44340
44575
  }
44341
- async function conflictedPaths(cwd, git6) {
44342
- const result = await git6(cwd, ["diff", "--name-only", "--diff-filter=U"]);
44576
+ async function conflictedPaths(cwd, git7) {
44577
+ const result = await git7(cwd, ["diff", "--name-only", "--diff-filter=U"]);
44343
44578
  return result.ok ? result.output.split("\n").map((entry) => entry.trim()).filter(Boolean) : [];
44344
44579
  }
44345
- async function abortMerge(cwd, git6) {
44580
+ async function abortMerge(cwd, git7) {
44346
44581
  if (inProgressGitOperation(cwd) !== "merge") return true;
44347
- const aborted2 = await git6(cwd, ["merge", "--abort"]);
44582
+ const aborted2 = await git7(cwd, ["merge", "--abort"]);
44348
44583
  if (aborted2.ok) return true;
44349
- const reset = await git6(cwd, ["reset", "--merge", "ORIG_HEAD"]);
44584
+ const reset = await git7(cwd, ["reset", "--merge", "ORIG_HEAD"]);
44350
44585
  return reset.ok && inProgressGitOperation(cwd) !== "merge";
44351
44586
  }
44352
44587
  async function mergeStoreUpstream(cwd, options) {
44353
- const { git: git6 } = options;
44588
+ const { git: git7 } = options;
44354
44589
  const operation = inProgressGitOperation(cwd);
44355
44590
  if (operation) {
44356
44591
  const recovery = gitOperationRecovery(operation);
@@ -44359,15 +44594,15 @@ async function mergeStoreUpstream(cwd, options) {
44359
44594
  detail: `The store already has a Git operation in progress (${operation}). Run '${recovery}' in the store before syncing again.`
44360
44595
  };
44361
44596
  }
44362
- const branch = await git6(cwd, ["symbolic-ref", "--quiet", "HEAD"]);
44597
+ const branch = await git7(cwd, ["symbolic-ref", "--quiet", "HEAD"]);
44363
44598
  if (!branch.ok) return { status: "error", detail: "No branch is checked out." };
44364
44599
  let committedLocalWrites = false;
44365
44600
  if (options.commitLocalWrites !== false) {
44366
- const saved = await commitLocalStoreWrites(cwd, git6, options.commitMessage ?? "auto-save phren (store sync)");
44601
+ const saved = await commitLocalStoreWrites(cwd, git7, options.commitMessage ?? "auto-save phren (store sync)");
44367
44602
  if (saved.error) return { status: "error", detail: `Cannot commit local store writes: ${saved.error}` };
44368
44603
  committedLocalWrites = saved.committed;
44369
44604
  }
44370
- const refs = await git6(cwd, ["for-each-ref", "--format=%(upstream:remotename)%09%(upstream:remoteref)%09%(upstream)", branch.output]);
44605
+ const refs = await git7(cwd, ["for-each-ref", "--format=%(upstream:remotename)%09%(upstream:remoteref)%09%(upstream)", branch.output]);
44371
44606
  const [remote, remoteRef, trackingRef] = refs.output.split(" ");
44372
44607
  if (!refs.ok || !remote || !remoteRef || !trackingRef) {
44373
44608
  return {
@@ -44376,22 +44611,22 @@ async function mergeStoreUpstream(cwd, options) {
44376
44611
  committedLocalWrites
44377
44612
  };
44378
44613
  }
44379
- const tracked = await git6(cwd, ["rev-parse", "--verify", trackingRef]);
44614
+ const tracked = await git7(cwd, ["rev-parse", "--verify", trackingRef]);
44380
44615
  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}`]);
44616
+ const fetched = await git7(cwd, ["fetch", "--quiet", "--no-tags", "--no-recurse-submodules", "--", remote, `${remoteRef}:${trackingRef}`]);
44382
44617
  if (!fetched.ok) return { status: "error", detail: `Fetch failed: ${fetched.error || "unknown Git error"}`, committedLocalWrites };
44383
44618
  }
44384
- const target = await git6(cwd, ["rev-parse", "--verify", trackingRef]);
44619
+ const target = await git7(cwd, ["rev-parse", "--verify", trackingRef]);
44385
44620
  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) {
44621
+ if ((await git7(cwd, ["merge-base", "--is-ancestor", target.output, "HEAD"])).ok) {
44387
44622
  return {
44388
44623
  status: "unchanged",
44389
44624
  detail: committedLocalWrites ? "Committed local store writes; the store already contains the remote changes." : "The store already contains the remote changes.",
44390
44625
  committedLocalWrites
44391
44626
  };
44392
44627
  }
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]);
44628
+ const canFastForward = (await git7(cwd, ["merge-base", "--is-ancestor", "HEAD", target.output])).ok;
44629
+ const merged = await git7(cwd, canFastForward ? ["merge", "--ff-only", target.output] : ["merge", "--no-edit", target.output]);
44395
44630
  if (merged.ok) {
44396
44631
  return {
44397
44632
  status: "updated",
@@ -44399,7 +44634,7 @@ async function mergeStoreUpstream(cwd, options) {
44399
44634
  committedLocalWrites
44400
44635
  };
44401
44636
  }
44402
- const initialConflicts = await conflictedPaths(cwd, git6);
44637
+ const initialConflicts = await conflictedPaths(cwd, git7);
44403
44638
  if (initialConflicts.length === 0 && inProgressGitOperation(cwd) !== "merge") {
44404
44639
  return {
44405
44640
  status: "error",
@@ -44408,7 +44643,7 @@ async function mergeStoreUpstream(cwd, options) {
44408
44643
  };
44409
44644
  }
44410
44645
  if (initialConflicts.length > 0 && resolveStoreConflicts(cwd).unresolved.length === 0) {
44411
- const commit = await git6(cwd, ["-c", "commit.gpgsign=false", "commit", "--no-edit"]);
44646
+ const commit = await git7(cwd, ["-c", "commit.gpgsign=false", "commit", "--no-edit"]);
44412
44647
  if (commit.ok) {
44413
44648
  return {
44414
44649
  status: "updated",
@@ -44418,9 +44653,9 @@ async function mergeStoreUpstream(cwd, options) {
44418
44653
  };
44419
44654
  }
44420
44655
  }
44421
- const unresolvedConflicts = await conflictedPaths(cwd, git6);
44656
+ const unresolvedConflicts = await conflictedPaths(cwd, git7);
44422
44657
  const conflicts = unresolvedConflicts.length > 0 ? unresolvedConflicts : initialConflicts;
44423
- const cleaned = await abortMerge(cwd, git6);
44658
+ const cleaned = await abortMerge(cwd, git7);
44424
44659
  if (!cleaned) {
44425
44660
  return {
44426
44661
  status: "error",
@@ -44477,12 +44712,12 @@ function clearStoreAuthFailure(cwd) {
44477
44712
  fs33.rmSync(runtimeFile(cwd, "sync-auth.json"), { force: true });
44478
44713
  }
44479
44714
  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";
44715
+ const git7 = (args) => runGit(cwd, args, 5e3);
44716
+ const branch = name ? null : git7(["symbolic-ref", "--quiet", "--short", "HEAD"]);
44717
+ const pushRemote = push && (branch && git7(["config", "--get", `branch.${branch}.pushRemote`]) || git7(["config", "--get", "remote.pushDefault"]));
44718
+ const remoteName = name || pushRemote || branch && git7(["config", "--get", `branch.${branch}.remote`]) || "origin";
44484
44719
  if (remoteName === ".") return;
44485
- const remote = git6(["remote", "get-url", ...push ? ["--push"] : [], "--", remoteName]);
44720
+ const remote = git7(["remote", "get-url", ...push ? ["--push"] : [], "--", remoteName]);
44486
44721
  return remote ? { remoteName, remote } : void 0;
44487
44722
  }
44488
44723
  function authBackoffActive(state, now = Date.now()) {
@@ -44508,12 +44743,12 @@ function recordStoreAuthFailure(cwd, remoteName, remote, now = Date.now()) {
44508
44743
  return state;
44509
44744
  });
44510
44745
  }
44511
- function withStoreAuthBackoff(git6, now = Date.now) {
44746
+ function withStoreAuthBackoff(git7, now = Date.now) {
44512
44747
  return async (cwd, args) => {
44513
- if (!["fetch", "pull", "push", "ls-remote"].includes(args[0])) return git6(cwd, args);
44748
+ if (!["fetch", "pull", "push", "ls-remote"].includes(args[0])) return git7(cwd, args);
44514
44749
  const separator = args.indexOf("--");
44515
44750
  const remote = storeSyncRemote(cwd, separator >= 0 ? args[separator + 1] : void 0, args[0] === "push");
44516
- if (!remote) return git6(cwd, args);
44751
+ if (!remote) return git7(cwd, args);
44517
44752
  const release = tryFileLock(runtimeFile(cwd, "sync-auth-probe"));
44518
44753
  if (!release) return { ok: false, output: "", error: "Store remote check deferred: another sync is running." };
44519
44754
  try {
@@ -44522,7 +44757,7 @@ function withStoreAuthBackoff(git6, now = Date.now) {
44522
44757
  if (sameRemote && authBackoffActive(previous, now())) {
44523
44758
  return { ok: false, output: "", error: storeAuthDetail(previous) };
44524
44759
  }
44525
- const result = await git6(cwd, args);
44760
+ const result = await git7(cwd, args);
44526
44761
  if (args[0] === "push") return result;
44527
44762
  if (result.ok) {
44528
44763
  if (sameRemote) clearStoreAuthFailure(cwd);
@@ -44592,7 +44827,7 @@ function repoName(url2) {
44592
44827
  }
44593
44828
  async function isRepository(directory) {
44594
44829
  try {
44595
- await stat17(path66.join(directory, ".git"));
44830
+ await stat18(path66.join(directory, ".git"));
44596
44831
  return true;
44597
44832
  } catch {
44598
44833
  return false;
@@ -44626,7 +44861,7 @@ async function candidateRepos(activity, env = process.env) {
44626
44861
  const offer = async (directory, source, lastSeen) => {
44627
44862
  let dir = path66.resolve(directory);
44628
44863
  try {
44629
- if (!(await stat17(dir)).isDirectory()) return;
44864
+ if (!(await stat18(dir)).isDirectory()) return;
44630
44865
  dir = realpathSync5.native(dir);
44631
44866
  } catch {
44632
44867
  return;
@@ -44638,7 +44873,7 @@ async function candidateRepos(activity, env = process.env) {
44638
44873
  };
44639
44874
  const toplevel = async (directory) => {
44640
44875
  let existing = directory;
44641
- while (!await stat17(existing).catch(() => void 0)) {
44876
+ while (!await stat18(existing).catch(() => void 0)) {
44642
44877
  const parent = path66.dirname(existing);
44643
44878
  if (parent === existing) return void 0;
44644
44879
  existing = parent;
@@ -44682,12 +44917,12 @@ async function cloneRoot(env) {
44682
44917
  const home = homedir16();
44683
44918
  for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path66.join(home, r))]) {
44684
44919
  try {
44685
- if ((await stat17(root)).isDirectory()) return root;
44920
+ if ((await stat18(root)).isDirectory()) return root;
44686
44921
  } catch {
44687
44922
  }
44688
44923
  }
44689
44924
  const fallback = path66.join(home, "Projects");
44690
- await mkdir14(fallback, { recursive: true });
44925
+ await mkdir15(fallback, { recursive: true });
44691
44926
  return fallback;
44692
44927
  }
44693
44928
  async function publishStore(store, project) {
@@ -44708,7 +44943,7 @@ async function publishStore(store, project) {
44708
44943
  async function enrollProject(input2, env = process.env) {
44709
44944
  const store = phrenStoreRoot(env);
44710
44945
  try {
44711
- if (!(await stat17(path66.join(store, ".config"))).isDirectory()) throw new Error();
44946
+ if (!(await stat18(path66.join(store, ".config"))).isDirectory()) throw new Error();
44712
44947
  } catch {
44713
44948
  throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
44714
44949
  }
@@ -44721,7 +44956,7 @@ async function enrollProject(input2, env = process.env) {
44721
44956
  if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
44722
44957
  directory = path66.join(await cloneRoot(env), name);
44723
44958
  try {
44724
- await stat17(directory);
44959
+ await stat18(directory);
44725
44960
  throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
44726
44961
  } catch (error62) {
44727
44962
  if (error62 instanceof BridgeError) throw error62;
@@ -44739,7 +44974,7 @@ async function enrollProject(input2, env = process.env) {
44739
44974
  if (raw.length > 4096 || raw.includes("\0") || !path66.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
44740
44975
  try {
44741
44976
  directory = realpathSync5.native(raw);
44742
- if (!(await stat17(directory)).isDirectory()) throw new Error();
44977
+ if (!(await stat18(directory)).isDirectory()) throw new Error();
44743
44978
  } catch {
44744
44979
  throw new BridgeError(404, "That folder is not on this computer.");
44745
44980
  }
@@ -44752,7 +44987,7 @@ async function enrollProject(input2, env = process.env) {
44752
44987
  // src/bridge/files.ts
44753
44988
  init_protocol();
44754
44989
  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";
44990
+ import { lstat as lstat14, open as open11, readdir as readdir11, realpath as realpath11 } from "node:fs/promises";
44756
44991
  import path67 from "node:path";
44757
44992
  var MAX_BYTES = 2097152;
44758
44993
  async function browseFiles(root, relative3) {
@@ -44778,7 +45013,7 @@ async function browseFiles(root, relative3) {
44778
45013
  };
44779
45014
  }
44780
45015
  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);
45016
+ const handle = await open11(resolved, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
44782
45017
  try {
44783
45018
  const current = await handle.stat();
44784
45019
  if (!current.isFile() || current.ino !== metadata.ino || current.dev !== metadata.dev) throw new BridgeError(409, "The file changed. Refresh and try again.");
@@ -44800,7 +45035,7 @@ async function browseFiles(root, relative3) {
44800
45035
  // src/bridge/file-range.ts
44801
45036
  init_protocol();
44802
45037
  import { constants as constants3 } from "node:fs";
44803
- import { lstat as lstat15, open as open11, realpath as realpath12 } from "node:fs/promises";
45038
+ import { lstat as lstat15, open as open12, realpath as realpath12 } from "node:fs/promises";
44804
45039
  import path68 from "node:path";
44805
45040
  var MAX_FILE_RANGE = 4 * 1024 * 1024;
44806
45041
  var types = {
@@ -44841,8 +45076,8 @@ function fileContentType(file2) {
44841
45076
  const ext = path68.extname(file2).slice(1).toLowerCase();
44842
45077
  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
45078
  }
44844
- function version2(stat24) {
44845
- return `${stat24.dev}:${stat24.ino}:${stat24.size}:${stat24.mtimeMs}:${stat24.ctimeMs}`;
45079
+ function version2(stat25) {
45080
+ return `${stat25.dev}:${stat25.ino}:${stat25.size}:${stat25.mtimeMs}:${stat25.ctimeMs}`;
44846
45081
  }
44847
45082
  function rangeInteger(value2, fallback) {
44848
45083
  if (value2 === null) return fallback;
@@ -44867,7 +45102,7 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
44867
45102
  if (!resolved.startsWith(base + path68.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
44868
45103
  const metadata = await lstat15(resolved);
44869
45104
  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);
45105
+ const handle = await open12(resolved, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
44871
45106
  try {
44872
45107
  const current = await handle.stat();
44873
45108
  if (!current.isFile() || version2(current) !== version2(metadata) || await realpath12(file2) !== resolved) {
@@ -44903,22 +45138,149 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
44903
45138
  }
44904
45139
  }
44905
45140
 
45141
+ // src/bridge/memory-store.ts
45142
+ init_zod();
45143
+ init_protocol();
45144
+ import { execFile as execFile11 } from "node:child_process";
45145
+ import { createHash as createHash15 } from "node:crypto";
45146
+ 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";
45147
+ import path69 from "node:path";
45148
+ import { promisify as promisify11 } from "node:util";
45149
+ var exec11 = promisify11(execFile11);
45150
+ var SHA = /^[0-9a-f]{40}$/;
45151
+ var MAX_FILE = 4 * 1024 * 1024;
45152
+ var queue = Promise.resolve();
45153
+ function serialized(work) {
45154
+ const next = queue.then(work, work);
45155
+ queue = next.catch(() => void 0);
45156
+ return next;
45157
+ }
45158
+ async function git5(store, args, env = {}) {
45159
+ try {
45160
+ const { stdout } = await exec11("git", ["-C", store, ...args], {
45161
+ env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" },
45162
+ maxBuffer: 64 * 1024 * 1024,
45163
+ timeout: 6e4
45164
+ });
45165
+ return stdout;
45166
+ } catch (error62) {
45167
+ const stderr = String(error62.stderr ?? "").trim();
45168
+ throw new BridgeError(500, `git ${args[0]} failed in the store${stderr ? `: ${stderr.split("\n")[0]}` : "."}`);
45169
+ }
45170
+ }
45171
+ function blobSha(content) {
45172
+ return createHash15("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
45173
+ }
45174
+ async function isRepository2(store) {
45175
+ return await lstat16(path69.join(store, ".git")).catch(() => void 0) !== void 0;
45176
+ }
45177
+ function storeHead(store, indexFile = path69.join(bridgeRoot(), "store-snapshot.index")) {
45178
+ return serialized(async () => {
45179
+ if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
45180
+ await mkdir16(path69.dirname(indexFile), { recursive: true, mode: 448 });
45181
+ const env = { GIT_INDEX_FILE: indexFile };
45182
+ if (!await lstat16(indexFile).catch(() => void 0)) {
45183
+ const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
45184
+ await git5(store, head.trim() ? ["read-tree", "HEAD"] : ["read-tree", "--empty"], env);
45185
+ }
45186
+ await git5(store, ["add", "--all", "--", "."], env);
45187
+ return { sha: (await git5(store, ["write-tree"], env)).trim() };
45188
+ });
45189
+ }
45190
+ async function storeTree(store, sha) {
45191
+ if (!SHA.test(sha)) throw new BridgeError(400, "Invalid tree sha.");
45192
+ if ((await git5(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "tree") throw new BridgeError(404, "Unknown tree.");
45193
+ const tree = (await git5(store, ["ls-tree", "-r", "-l", "-z", sha])).split("\0").filter(Boolean).flatMap((line) => {
45194
+ const match = /^(\d+) (\w+) ([0-9a-f]{40}) +(\d+|-)\t(.+)$/s.exec(line);
45195
+ if (!match || match[2] !== "blob" || match[1] === "120000") return [];
45196
+ return [{ path: match[5], type: "blob", sha: match[3], size: Number(match[4]) }];
45197
+ });
45198
+ return { sha, truncated: false, tree };
45199
+ }
45200
+ async function storeBlob(store, sha) {
45201
+ if (!SHA.test(sha)) throw new BridgeError(400, "Invalid blob sha.");
45202
+ if ((await git5(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "blob") throw new BridgeError(404, "Unknown blob.");
45203
+ const { stdout } = await exec11("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE * 4 });
45204
+ return { sha, encoding: "base64", content: stdout.toString("base64") };
45205
+ }
45206
+ async function storeFile(store, relative3) {
45207
+ const normalized = path69.posix.normalize(relative3);
45208
+ if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path69.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
45209
+ throw new BridgeError(400, "Invalid store path.");
45210
+ }
45211
+ const root = await realpath13(store);
45212
+ let parent = path69.dirname(path69.join(root, normalized));
45213
+ for (; ; ) {
45214
+ const real = await realpath13(parent).catch(() => void 0);
45215
+ if (real) {
45216
+ if (real !== root && !real.startsWith(root + path69.sep)) throw new BridgeError(400, "Invalid store path.");
45217
+ break;
45218
+ }
45219
+ parent = path69.dirname(parent);
45220
+ }
45221
+ const file2 = path69.join(root, normalized);
45222
+ const info = await lstat16(file2).catch(() => void 0);
45223
+ if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
45224
+ return file2;
45225
+ }
45226
+ async function currentSha(file2) {
45227
+ const content = await readFile27(file2).catch((error62) => {
45228
+ if (error62.code === "ENOENT") return null;
45229
+ throw error62;
45230
+ });
45231
+ return content === null ? null : blobSha(content);
45232
+ }
45233
+ var putSchema = external_exports.object({ path: external_exports.string().max(1024), content: external_exports.string(), sha: external_exports.string().regex(SHA).nullable().optional() });
45234
+ var deleteSchema = external_exports.object({ path: external_exports.string().max(1024), sha: external_exports.string().regex(SHA) });
45235
+ function putStoreFile(store, data) {
45236
+ const input2 = putSchema.parse(data);
45237
+ const content = Buffer.from(input2.content, "base64");
45238
+ if (content.length > MAX_FILE) throw new BridgeError(413, "This file is too large for the phone to write.");
45239
+ return serialized(async () => {
45240
+ const file2 = await storeFile(store, input2.path);
45241
+ if (await currentSha(file2) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
45242
+ await mkdir16(path69.dirname(file2), { recursive: true });
45243
+ const temporary = `${file2}.phren-${process.pid}-${Date.now()}`;
45244
+ await writeFile8(temporary, content, { flag: "wx" });
45245
+ await rename7(temporary, file2);
45246
+ return { content: { sha: blobSha(content), path: input2.path }, commit: { sha: blobSha(content) } };
45247
+ });
45248
+ }
45249
+ function deleteStoreFile(store, data) {
45250
+ const input2 = deleteSchema.parse(data);
45251
+ return serialized(async () => {
45252
+ const file2 = await storeFile(store, input2.path);
45253
+ if (await currentSha(file2) !== input2.sha) throw new BridgeError(409, `${input2.path} changed on this computer.`);
45254
+ await rm8(file2);
45255
+ return { ok: true };
45256
+ });
45257
+ }
45258
+ var STORE_ROUTES = { head: "/v1/store/head", tree: "/v1/store/tree", blob: "/v1/store/blob", file: "/v1/store/file", delete: "/v1/store/delete" };
45259
+ async function storeRoute(store, method, url2, data) {
45260
+ if (method === "GET" && url2.pathname === STORE_ROUTES.head) return storeHead(store);
45261
+ if (method === "GET" && url2.pathname === STORE_ROUTES.tree) return storeTree(store, url2.searchParams.get("sha") ?? "");
45262
+ if (method === "GET" && url2.pathname === STORE_ROUTES.blob) return storeBlob(store, url2.searchParams.get("sha") ?? "");
45263
+ if (method === "POST" && url2.pathname === STORE_ROUTES.file) return putStoreFile(store, data ?? {});
45264
+ if (method === "POST" && url2.pathname === STORE_ROUTES.delete) return deleteStoreFile(store, data ?? {});
45265
+ throw new BridgeError(404, "Unknown Phren Hook route.");
45266
+ }
45267
+
44906
45268
  // src/bridge/server-routes.ts
44907
45269
  init_protocol();
44908
45270
 
44909
45271
  // src/bridge/simulators.ts
44910
45272
  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";
45273
+ import { execFile as execFile12 } from "node:child_process";
45274
+ 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
45275
  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);
45276
+ import path70 from "node:path";
45277
+ import { createHash as createHash16, randomUUID as randomUUID17 } from "node:crypto";
45278
+ import { promisify as promisify12 } from "node:util";
45279
+ var exec12 = promisify12(execFile12);
44918
45280
  var UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
44919
45281
  async function bootedSimulators() {
44920
45282
  if (process.platform !== "darwin") return [];
44921
- const { stdout } = await exec11("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
45283
+ const { stdout } = await exec12("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
44922
45284
  let parsed = {};
44923
45285
  try {
44924
45286
  parsed = JSON.parse(stdout);
@@ -44939,10 +45301,10 @@ async function bootedSimulators() {
44939
45301
  async function simulatorScreenshot(udid) {
44940
45302
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
44941
45303
  if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
44942
- const file2 = path69.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
45304
+ const file2 = path70.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
44943
45305
  try {
44944
- await exec11("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
44945
- return await readFile27(file2);
45306
+ await exec12("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
45307
+ return await readFile28(file2);
44946
45308
  } catch (error62) {
44947
45309
  if (error62 instanceof BridgeError) throw error62;
44948
45310
  throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
@@ -44958,25 +45320,25 @@ function helper() {
44958
45320
  return building;
44959
45321
  }
44960
45322
  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";
45323
+ const dir = path70.join(bridgeRoot(), "native");
45324
+ const binary = path70.join(dir, "simtap");
45325
+ 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");
45326
+ const digest2 = createHash16("sha256").update(code).digest("hex");
45327
+ const saved = await readFile28(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
45328
+ if (await stat19(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
45329
+ await mkdir17(dir, { recursive: true, mode: 448 });
45330
+ const temporary = path70.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
44969
45331
  const sidecar = temporary + ".sha256";
44970
45332
  try {
44971
- await writeFile8(source, code, { mode: 384, flag: "wx" });
44972
- await exec11("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
45333
+ await writeFile9(source, code, { mode: 384, flag: "wx" });
45334
+ await exec12("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
44973
45335
  throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
44974
45336
  });
44975
45337
  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");
45338
+ const binarySha = createHash16("sha256").update(await readFile28(temporary)).digest("hex");
45339
+ await writeFile9(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
45340
+ await rename8(temporary, binary);
45341
+ await rename8(sidecar, binary + ".sha256");
44980
45342
  } finally {
44981
45343
  await Promise.all([source, temporary, sidecar].map((file2) => unlink5(file2).catch(() => void 0)));
44982
45344
  }
@@ -44991,11 +45353,11 @@ function simtap(name, ...args) {
44991
45353
  }
44992
45354
  async function executeSimtap(name, ...args) {
44993
45355
  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");
45356
+ const saved = await readFile28(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
45357
+ const binarySha = createHash16("sha256").update(await readFile28(binary)).digest("hex");
44996
45358
  if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
44997
45359
  try {
44998
- await exec11(binary, [name, ...args], { timeout: 6e4 });
45360
+ await exec12(binary, [name, ...args], { timeout: 6e4 });
44999
45361
  } catch (error62) {
45000
45362
  const failure2 = error62;
45001
45363
  const message = String(failure2?.stderr ?? failure2?.message ?? "");
@@ -45011,7 +45373,7 @@ async function simulatorAct(udid, request6) {
45011
45373
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
45012
45374
  if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready"].includes(request6.action)) throw new BridgeError(400, "Unknown simulator action.");
45013
45375
  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(() => {
45376
+ const simctl = (...args) => exec12("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
45015
45377
  throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`);
45016
45378
  });
45017
45379
  switch (request6.action) {
@@ -45060,7 +45422,7 @@ async function deviceName(udid) {
45060
45422
  async function simulatorApps(udid) {
45061
45423
  if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
45062
45424
  if (process.platform !== "darwin") return [];
45063
- const { stdout } = await exec11("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
45425
+ const { stdout } = await exec12("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
45064
45426
  const apps = [];
45065
45427
  const blocks = stdout.split(/\n(?=\s{4}"[^"]+" =\s+\{)/);
45066
45428
  for (const block of blocks) {
@@ -45076,8 +45438,8 @@ init_transcripts();
45076
45438
 
45077
45439
  // src/bridge/uploads.ts
45078
45440
  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";
45441
+ 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";
45442
+ import path71 from "node:path";
45081
45443
  import { randomUUID as randomUUID18 } from "node:crypto";
45082
45444
  function imageBytes(bytes) {
45083
45445
  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 +45452,51 @@ async function saveUpload(session, name, bytes) {
45090
45452
  let saved = "";
45091
45453
  const task = uploadQueue.catch(() => {
45092
45454
  }).then(async () => {
45093
- const root = path70.join(bridgeRoot(), "uploads");
45094
- await mkdir16(root, { recursive: true, mode: 448 });
45455
+ const root = path71.join(bridgeRoot(), "uploads");
45456
+ await mkdir18(root, { recursive: true, mode: 448 });
45095
45457
  let used = 0;
45096
45458
  const directories = await readdir12(root, { withFileTypes: true });
45097
45459
  for (const dir of directories) {
45098
45460
  if (!dir.isDirectory()) continue;
45099
- const folder2 = path70.join(root, dir.name);
45461
+ const folder2 = path71.join(root, dir.name);
45100
45462
  for (const entry of await readdir12(folder2, { withFileTypes: true })) {
45101
45463
  if (!entry.isFile()) continue;
45102
- const file2 = path70.join(folder2, entry.name), metadata = await lstat16(file2);
45464
+ const file2 = path71.join(folder2, entry.name), metadata = await lstat17(file2);
45103
45465
  if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink6(file2);
45104
45466
  else used += metadata.size;
45105
45467
  }
45106
45468
  }
45107
45469
  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 });
45470
+ const folder = path71.join(root, session);
45471
+ await mkdir18(folder, { recursive: true, mode: 448 });
45472
+ saved = path71.join(folder, `${randomUUID18()}-${name}`);
45473
+ await writeFile10(saved, bytes, { flag: "wx", mode: 384 });
45112
45474
  });
45113
45475
  uploadQueue = task;
45114
45476
  await task;
45115
45477
  return saved;
45116
45478
  }
45117
45479
  async function listUploads(session) {
45118
- const folder = path70.join(bridgeRoot(), "uploads", session);
45480
+ const folder = path71.join(bridgeRoot(), "uploads", session);
45119
45481
  const entries = await readdir12(folder, { withFileTypes: true }).catch(() => []);
45120
45482
  const files = [];
45121
45483
  for (const entry of entries) {
45122
45484
  if (!entry.isFile()) continue;
45123
- const file2 = path70.join(folder, entry.name), metadata = await stat19(file2);
45485
+ const file2 = path71.join(folder, entry.name), metadata = await stat20(file2);
45124
45486
  files.push({ name: entry.name.replace(/^[0-9a-f-]{36}-/, ""), path: file2, size: metadata.size, modified: metadata.mtime.toISOString() });
45125
45487
  }
45126
45488
  return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
45127
45489
  }
45128
45490
  async function uploadImage(requested) {
45129
45491
  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);
45492
+ if (!requested || requested.length > 4096 || !path71.isAbsolute(requested)) throw missing;
45493
+ const root = await realpath14(path71.join(bridgeRoot(), "uploads")).catch(() => void 0);
45494
+ const file2 = await realpath14(requested).catch(() => void 0);
45495
+ if (!root || !file2 || !file2.startsWith(root + path71.sep)) throw missing;
45496
+ const metadata = await stat20(file2);
45135
45497
  if (!metadata.isFile()) throw missing;
45136
45498
  if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
45137
- const bytes = await readFile28(file2);
45499
+ const bytes = await readFile29(file2);
45138
45500
  if (bytes.length > 8388608) throw new BridgeError(413, "This image is too large.");
45139
45501
  if (!imageBytes(bytes)) throw missing;
45140
45502
  return bytes;
@@ -45144,7 +45506,7 @@ async function uploadImage(requested) {
45144
45506
  init_transcript_index();
45145
45507
  init_transcripts();
45146
45508
  import { homedir as homedir17, tmpdir as tmpdir4 } from "node:os";
45147
- import path71 from "node:path";
45509
+ import path72 from "node:path";
45148
45510
  init_protocol();
45149
45511
  var cache = /* @__PURE__ */ new Map();
45150
45512
  var modelCache = /* @__PURE__ */ new Map();
@@ -45282,7 +45644,7 @@ function describe3(tool, args) {
45282
45644
  return "";
45283
45645
  };
45284
45646
  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";
45647
+ const base = (v) => path72.basename(v.split(" \xB7 ")[0].trim()) || "file";
45286
45648
  const name = tool.toLowerCase();
45287
45649
  let value2;
45288
45650
  if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
@@ -45317,17 +45679,17 @@ init_shared();
45317
45679
 
45318
45680
  // src/bridge/server-pane-routes.ts
45319
45681
  init_zod();
45320
- import path74 from "node:path";
45682
+ import path75 from "node:path";
45321
45683
  import { setTimeout as sleep2 } from "node:timers/promises";
45322
45684
 
45323
45685
  // src/bridge/git.ts
45324
45686
  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);
45687
+ import { createHash as createHash17 } from "node:crypto";
45688
+ import { execFile as execFile13 } from "node:child_process";
45689
+ import { lstat as lstat18, readdir as readdir13, readFile as readFile30, realpath as realpath15, stat as stat21 } from "node:fs/promises";
45690
+ import path73 from "node:path";
45691
+ import { promisify as promisify13 } from "node:util";
45692
+ var exec13 = promisify13(execFile13);
45331
45693
  function statusLetter(code) {
45332
45694
  const letter = code[0];
45333
45695
  return ["M", "A", "D", "R", "C", "U"].includes(letter) ? letter : "M";
@@ -45371,9 +45733,9 @@ function parseNumstat(out) {
45371
45733
  }
45372
45734
  async function countLines(root, rel) {
45373
45735
  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);
45736
+ const abs = path73.join(root, await repositoryPath(root, rel));
45737
+ if ((await stat21(abs)).size > 5e6) return 0;
45738
+ const bytes = await readFile30(abs);
45377
45739
  if (!bytes.length || bytes.includes(0)) return 0;
45378
45740
  let lines = 0;
45379
45741
  for (const byte of bytes) if (byte === 10) lines++;
@@ -45539,7 +45901,7 @@ function checkRollup(items) {
45539
45901
  }
45540
45902
  async function currentPull(root, branch) {
45541
45903
  try {
45542
- const { stdout } = await exec12("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
45904
+ const { stdout } = await exec13("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
45543
45905
  cwd: root,
45544
45906
  timeout: 15e3,
45545
45907
  maxBuffer: 4194304,
@@ -45566,7 +45928,7 @@ async function gitPulls(cwd) {
45566
45928
  const branch = (await git2(root, "branch", "--show-current").catch(() => "")).trim();
45567
45929
  try {
45568
45930
  const [{ stdout }, current] = await Promise.all([
45569
- exec12("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
45931
+ exec13("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
45570
45932
  cwd: root,
45571
45933
  timeout: 15e3,
45572
45934
  maxBuffer: 4194304,
@@ -45595,31 +45957,31 @@ async function gitPulls(cwd) {
45595
45957
  }
45596
45958
  }
45597
45959
  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.");
45960
+ 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
45961
  const segments = raw.split(/[\\/]/);
45600
45962
  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.");
45963
+ const clean2 = segments.filter((part) => part && part !== ".").join("/");
45964
+ if (!clean2 && !allowRoot || clean2.startsWith("-")) throw new BridgeError(400, "Invalid path.");
45965
+ const abs = path73.resolve(root, clean2);
45966
+ if (abs !== root && !abs.startsWith(root + path73.sep)) throw new BridgeError(403, "This path is outside the repository.");
45605
45967
  let existing = abs;
45606
45968
  while (true) {
45607
45969
  try {
45608
- await lstat17(existing);
45970
+ await lstat18(existing);
45609
45971
  break;
45610
45972
  } catch (error62) {
45611
45973
  if (error62.code !== "ENOENT" || existing === root) throw new BridgeError(400, "Invalid path.");
45612
- existing = path72.dirname(existing);
45974
+ existing = path73.dirname(existing);
45613
45975
  }
45614
45976
  }
45615
45977
  let resolved;
45616
45978
  try {
45617
- resolved = await realpath14(existing);
45979
+ resolved = await realpath15(existing);
45618
45980
  } catch {
45619
45981
  throw new BridgeError(403, "This path cannot be resolved inside the repository.");
45620
45982
  }
45621
- if (resolved !== root && !resolved.startsWith(root + path72.sep)) throw new BridgeError(403, "This path is outside the repository.");
45622
- return clean;
45983
+ if (resolved !== root && !resolved.startsWith(root + path73.sep)) throw new BridgeError(403, "This path is outside the repository.");
45984
+ return clean2;
45623
45985
  }
45624
45986
  var treeCache = /* @__PURE__ */ new Map();
45625
45987
  function invalidateTree(root) {
@@ -45631,7 +45993,7 @@ async function treeSnapshot(root, head) {
45631
45993
  git2(root, "ls-files", "-z"),
45632
45994
  git2(root, "status", "--porcelain=v1", "-z", "--untracked-files=all")
45633
45995
  ]);
45634
- const changed = /* @__PURE__ */ new Map();
45996
+ const changed2 = /* @__PURE__ */ new Map();
45635
45997
  const files = new Set(tracked.split("\0").filter(Boolean));
45636
45998
  const tokens = porcelain.split("\0");
45637
45999
  for (let i = 0; i < tokens.length; i++) {
@@ -45639,7 +46001,7 @@ async function treeSnapshot(root, head) {
45639
46001
  if (!row) continue;
45640
46002
  const xy = row.slice(0, 2), file2 = row.slice(3);
45641
46003
  const letter = xy === "??" ? "?" : statusLetter(xy[1] !== " " ? xy[1] : xy[0]);
45642
- changed.set(file2, letter);
46004
+ changed2.set(file2, letter);
45643
46005
  files.add(file2);
45644
46006
  if (/[RC]/.test(xy)) i++;
45645
46007
  }
@@ -45664,12 +46026,12 @@ async function treeSnapshot(root, head) {
45664
46026
  }
45665
46027
  if (directory) {
45666
46028
  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);
46029
+ if (changed2.has(file2)) entry.status = "changed";
46030
+ } else if (changed2.has(file2)) entry.status = entry.kind === "dir" ? "changed" : changed2.get(file2);
45669
46031
  parent = full2;
45670
46032
  }
45671
46033
  }
45672
- const version3 = createHash16("sha256").update(head).update(tracked).update(porcelain).digest("hex");
46034
+ const version3 = createHash17("sha256").update(head).update(tracked).update(porcelain).digest("hex");
45673
46035
  return { version: version3, levels: new Map([...levels].map(([directory, entries]) => [
45674
46036
  directory,
45675
46037
  [...entries.values()].sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "dir" ? -1 : 1)
@@ -45700,7 +46062,7 @@ async function ignoredEntries(root, prefix, shown) {
45700
46062
  const entries = /* @__PURE__ */ new Map();
45701
46063
  const inside = prefix && listing.some((item) => item.endsWith("/") && (prefix + "/").startsWith(item));
45702
46064
  if (inside) {
45703
- const dirents = await readdir13(path72.join(root, prefix), { withFileTypes: true }).catch(() => []);
46065
+ const dirents = await readdir13(path73.join(root, prefix), { withFileTypes: true }).catch(() => []);
45704
46066
  for (const dirent of dirents) {
45705
46067
  if (dirent.name === ".git" || taken.has(dirent.name) || entries.size >= MAX_IGNORED_ENTRIES) continue;
45706
46068
  entries.set(dirent.name, { name: dirent.name, path: `${prefix}/${dirent.name}`, kind: dirent.isDirectory() ? "dir" : "file", ignored: true });
@@ -45745,8 +46107,8 @@ async function repositoryPaths(root, raw) {
45745
46107
  if (!list.length || list.length > 64) throw new BridgeError(400, "Choose between 1 and 64 paths.");
45746
46108
  const paths = [];
45747
46109
  for (const entry of list) {
45748
- const clean = await repositoryPath(root, entry);
45749
- if (clean && !paths.includes(clean)) paths.push(clean);
46110
+ const clean2 = await repositoryPath(root, entry);
46111
+ if (clean2 && !paths.includes(clean2)) paths.push(clean2);
45750
46112
  }
45751
46113
  if (!paths.length) throw new BridgeError(400, "Choose between 1 and 64 paths.");
45752
46114
  return paths;
@@ -45796,14 +46158,14 @@ init_fanouts();
45796
46158
 
45797
46159
  // src/bridge/git-worktrees.ts
45798
46160
  init_protocol();
45799
- import { createHash as createHash17 } from "node:crypto";
45800
- import { realpath as realpath15, stat as stat21 } from "node:fs/promises";
46161
+ import { createHash as createHash18 } from "node:crypto";
46162
+ import { realpath as realpath16, stat as stat22 } from "node:fs/promises";
45801
46163
  import { homedir as homedir18 } from "node:os";
45802
- import path73 from "node:path";
46164
+ import path74 from "node:path";
45803
46165
  var MAX_WORKTREES = 64;
45804
46166
  var worktreeIdPattern = /^[a-f0-9]{32}$/;
45805
46167
  function worktreeId(abs) {
45806
- return createHash17("sha256").update(`worktree\0${abs}`).digest("hex").slice(0, 32);
46168
+ return createHash18("sha256").update(`worktree\0${abs}`).digest("hex").slice(0, 32);
45807
46169
  }
45808
46170
  async function listed(root) {
45809
46171
  const output2 = await git2(root, "worktree", "list", "--porcelain");
@@ -45827,8 +46189,8 @@ async function listed(root) {
45827
46189
  let main;
45828
46190
  for (const [index2, block] of blocks.entries()) {
45829
46191
  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;
46192
+ const abs = await realpath16(block.worktree).catch(() => void 0);
46193
+ if (!abs || !(await stat22(abs).catch(() => void 0))?.isDirectory()) continue;
45832
46194
  if (index2 === 0) main = abs;
45833
46195
  const branch = block.branch?.startsWith("refs/heads/") ? block.branch.slice("refs/heads/".length) : null;
45834
46196
  worktrees.push({ abs, head: block.HEAD ?? "", branch, locked: block.locked !== void 0 });
@@ -45838,11 +46200,11 @@ async function listed(root) {
45838
46200
  }
45839
46201
  function displayPath(abs, roots) {
45840
46202
  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("/");
46203
+ const rel = path74.relative(root, abs);
46204
+ if (rel && !rel.startsWith("..") && !path74.isAbsolute(rel)) return rel.split(path74.sep).join("/");
45843
46205
  }
45844
46206
  const home = homedir18();
45845
- return abs === home ? "~" : abs.startsWith(home + path73.sep) ? "~/" + path73.relative(home, abs).split(path73.sep).join("/") : abs;
46207
+ return abs === home ? "~" : abs.startsWith(home + path74.sep) ? "~/" + path74.relative(home, abs).split(path74.sep).join("/") : abs;
45846
46208
  }
45847
46209
  function uncommitted(status) {
45848
46210
  const tokens = status.split("\0");
@@ -45856,12 +46218,12 @@ function uncommitted(status) {
45856
46218
  return count2;
45857
46219
  }
45858
46220
  async function workerFor(abs, workers, all = []) {
45859
- const nested = all.filter((other) => other.startsWith(abs + path73.sep));
46221
+ const nested = all.filter((other) => other.startsWith(abs + path74.sep));
45860
46222
  let best;
45861
46223
  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;
46224
+ const cwd = await realpath16(worker.cwd).catch(() => path74.resolve(worker.cwd));
46225
+ if (cwd !== abs && !cwd.startsWith(abs + path74.sep)) continue;
46226
+ if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path74.sep))) continue;
45865
46227
  const score = (cwd === abs ? 2 : 0) + (worker.child ? 1 : 0);
45866
46228
  if (!best || score > best.score) best = { worker, score };
45867
46229
  }
@@ -45886,7 +46248,7 @@ async function gitWorktrees(cwd, workers = []) {
45886
46248
  behind = 0;
45887
46249
  }
45888
46250
  }
45889
- const changed = uncommitted(await git2(worktree.abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal").catch(() => ""));
46251
+ const changed2 = uncommitted(await git2(worktree.abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal").catch(() => ""));
45890
46252
  const worker = await workerFor(worktree.abs, workers, worktrees.map((item) => item.abs));
45891
46253
  return {
45892
46254
  id: worktreeId(worktree.abs),
@@ -45895,7 +46257,7 @@ async function gitWorktrees(cwd, workers = []) {
45895
46257
  head: worktree.head,
45896
46258
  ahead,
45897
46259
  behind,
45898
- changed,
46260
+ changed: changed2,
45899
46261
  ...worktree.abs === main ? { main: true } : {},
45900
46262
  ...worktree.locked ? { locked: true } : {},
45901
46263
  ...worker ? { worker: {
@@ -46048,11 +46410,11 @@ async function gitPullRequest(cwd, draft) {
46048
46410
 
46049
46411
  // src/bridge/session-servers.ts
46050
46412
  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";
46413
+ import { execFile as execFile14 } from "node:child_process";
46414
+ import { open as open13, stat as stat23 } from "node:fs/promises";
46415
+ import { promisify as promisify14 } from "node:util";
46054
46416
  init_transcripts();
46055
- var exec13 = promisify13(execFile13);
46417
+ var exec14 = promisify14(execFile14);
46056
46418
  var MAX_DEPTH = 64;
46057
46419
  var TRANSCRIPT_TAIL_BYTES = 1048576;
46058
46420
  var MAX_OTHER_PANES = 48;
@@ -46084,7 +46446,7 @@ function attributeServers(input2) {
46084
46446
  return result.sort((a, b) => Number(a.source === "mentioned") - Number(b.source === "mentioned") || a.port - b.port);
46085
46447
  }
46086
46448
  async function processTable(session) {
46087
- const { stdout } = await exec13("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4e3, maxBuffer: 16777216 });
46449
+ const { stdout } = await exec14("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4e3, maxBuffer: 16777216 });
46088
46450
  const parents = /* @__PURE__ */ new Map();
46089
46451
  const runners = [];
46090
46452
  const flag = `--session-id ${session}`;
@@ -46107,12 +46469,12 @@ async function paneRoots(server, paneId) {
46107
46469
  }
46108
46470
  async function transcriptHolders(file2) {
46109
46471
  const lsof = process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof";
46110
- const { stdout } = await exec13(lsof, ["-t", "--", file2], { timeout: 3e3 }).catch(() => ({ stdout: "" }));
46472
+ const { stdout } = await exec14(lsof, ["-t", "--", file2], { timeout: 3e3 }).catch(() => ({ stdout: "" }));
46111
46473
  return stdout.split("\n").map(Number).filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid);
46112
46474
  }
46113
46475
  async function transcriptTail(file2) {
46114
- const size = (await stat22(file2)).size;
46115
- const handle = await open12(file2, "r");
46476
+ const size = (await stat23(file2)).size;
46477
+ const handle = await open13(file2, "r");
46116
46478
  try {
46117
46479
  const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
46118
46480
  const buffer = Buffer.alloc(length);
@@ -46187,7 +46549,7 @@ function herdrWorktreeWorkers(s) {
46187
46549
  const workers = [];
46188
46550
  for (const pane of objects(s.panes)) {
46189
46551
  const cwd = pane.foreground_cwd || pane.cwd;
46190
- if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path74.isAbsolute(cwd)) continue;
46552
+ if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path75.isAbsolute(cwd)) continue;
46191
46553
  const name = paneAgentName(s, pane);
46192
46554
  workers.push({
46193
46555
  cwd,
@@ -46200,6 +46562,27 @@ function herdrWorktreeWorkers(s) {
46200
46562
  }
46201
46563
  var ANSWER_KEYS = ["Escape", "Enter", "Up", "Down", "Tab", "AltUp", "y", "n", "p", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
46202
46564
  var HERDR_KEYS = { Escape: "esc", Enter: "enter", Up: "up", Down: "down", Tab: "tab", AltUp: "alt+Up" };
46565
+ var questionText = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
46566
+ var claudeQuestionBody = external_exports.object({
46567
+ 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),
46568
+ answers: external_exports.array(external_exports.object({
46569
+ optionIndexes: external_exports.array(external_exports.number().int().nonnegative()).max(8),
46570
+ text: external_exports.string().max(1e3).refine((t) => !/[\x00-\x1f\x7f]/.test(t)).optional()
46571
+ })).min(1).max(8)
46572
+ });
46573
+ function claudeQuestionAnswer(data) {
46574
+ const body2 = claudeQuestionBody.parse(data);
46575
+ if (body2.answers.length !== body2.questions.length) throw new BridgeError(400, "Answer every question.");
46576
+ const answers = body2.answers.map((answer, index2) => {
46577
+ const question2 = body2.questions[index2], options = [...new Set(answer.optionIndexes)], text3 = answer.text?.trim() ?? "";
46578
+ if (options.some((option) => option >= question2.options.length)) throw new BridgeError(400, "Choose an available answer.");
46579
+ if (question2.multiSelect ? !options.length && !text3 : options.length + (text3 ? 1 : 0) !== 1) {
46580
+ throw new BridgeError(400, question2.multiSelect ? "Choose at least one answer." : "Choose one answer for each question.");
46581
+ }
46582
+ return { options, ...text3 ? { text: text3 } : {} };
46583
+ });
46584
+ return { questions: body2.questions.map((q) => ({ question: q.question, multiSelect: q.multiSelect, options: q.options.map((label2) => ({ label: label2 })) })), answers };
46585
+ }
46203
46586
  var secretText = external_exports.string().min(1).max(256).refine((t) => !/[\x00-\x1f\x7f]/.test(t));
46204
46587
  async function resubmitIfIdle(agentHooks, target, text3) {
46205
46588
  const status = async () => {
@@ -46382,9 +46765,7 @@ async function paneRoute(ctx, url2, data, response) {
46382
46765
  const status = String(pane.agent_status), menu = agentHooks.menuOpen(target);
46383
46766
  const holding = menu || !!agentHooks.terminalPrompt(target);
46384
46767
  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) });
46768
+ if (await agentHooks.answerReleasedQuestion(target, keys)) {
46388
46769
  result = { ok: true };
46389
46770
  } else {
46390
46771
  const answerKeys = await agentHooks.dialogAnswerKeys(target, keys);
@@ -46458,7 +46839,10 @@ async function paneRoute(ctx, url2, data, response) {
46458
46839
  await agentHooks.answer(target, actionId, data.decision, data.updatedInput);
46459
46840
  result = { ok: true };
46460
46841
  } else if (url2.pathname === "/v1/questions/answer") {
46461
- await codexQuestions.answer(target, data);
46842
+ if (target.source === "claude") {
46843
+ const { questions, answers } = claudeQuestionAnswer(data);
46844
+ await agentHooks.answerClaudeQuestions(target, questions, answers);
46845
+ } else await codexQuestions.answer(target, data);
46462
46846
  result = { ok: true };
46463
46847
  } else throw new BridgeError(404, "Unknown Phren Hook route.");
46464
46848
  }
@@ -46466,8 +46850,8 @@ async function paneRoute(ctx, url2, data, response) {
46466
46850
  }
46467
46851
 
46468
46852
  // src/bridge/server-launch.ts
46469
- import { mkdir as mkdir18, readFile as readFile30 } from "node:fs/promises";
46470
- import path76 from "node:path";
46853
+ import { mkdir as mkdir20, readFile as readFile31 } from "node:fs/promises";
46854
+ import path77 from "node:path";
46471
46855
  init_zod();
46472
46856
  init_home_paths();
46473
46857
 
@@ -46475,15 +46859,15 @@ init_home_paths();
46475
46859
  init_zod();
46476
46860
  init_utils_helpers();
46477
46861
  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";
46862
+ import { execFile as execFile15 } from "node:child_process";
46863
+ import { mkdir as mkdir19, realpath as realpath17, rm as rm9, stat as stat24 } from "node:fs/promises";
46864
+ import path76 from "node:path";
46865
+ import { promisify as promisify15 } from "node:util";
46482
46866
  init_protocol();
46483
- var exec14 = promisify14(execFile14);
46484
- async function git5(cwd, ...args) {
46867
+ var exec15 = promisify15(execFile15);
46868
+ async function git6(cwd, ...args) {
46485
46869
  countGit("launch-worktree");
46486
- return (await exec14("git", ["-C", cwd, "--no-pager", ...args], {
46870
+ return (await exec15("git", ["-C", cwd, "--no-pager", ...args], {
46487
46871
  timeout: 12e4,
46488
46872
  maxBuffer: 1048576,
46489
46873
  env: nonInteractiveGitEnv({ ...process.env, GIT_CONFIG_NOSYSTEM: "1" })
@@ -46498,55 +46882,75 @@ async function createLaunchWorktree(cwd, request6) {
46498
46882
  const branch = request6.branch;
46499
46883
  const root = await gitRoot(cwd);
46500
46884
  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();
46885
+ const head = (await git6(root, "rev-parse", "--verify", "--quiet", "HEAD^{commit}").catch(() => "")).trim();
46502
46886
  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)) {
46887
+ if (!await git6(root, "check-ref-format", "--branch", branch).then(() => true, () => false)) {
46504
46888
  throw new BridgeError(400, `"${branch}" is not a valid Git branch name.`);
46505
46889
  }
46506
- if (await git5(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
46890
+ if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
46507
46891
  throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
46508
46892
  }
46509
- const worktree = path75.join(root, ".claude", "worktrees", worktreeFolderName(branch));
46510
- if (await stat23(worktree).then(() => true, () => false)) {
46893
+ const worktree = path76.join(root, ".claude", "worktrees", worktreeFolderName(branch));
46894
+ if (await stat24(worktree).then(() => true, () => false)) {
46511
46895
  throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
46512
46896
  }
46513
- await mkdir17(path75.dirname(worktree), { recursive: true });
46897
+ await mkdir19(path76.dirname(worktree), { recursive: true });
46514
46898
  try {
46515
- await git5(root, "worktree", "add", "-b", branch, worktree, head);
46899
+ await git6(root, "worktree", "add", "-b", branch, worktree, head);
46516
46900
  } catch (error62) {
46517
46901
  const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").at(-1) : "";
46518
46902
  throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
46519
46903
  }
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;
46904
+ const abs = await realpath17(worktree);
46905
+ const inside = path76.relative(root, await realpath17(cwd));
46906
+ const start = inside && !inside.startsWith("..") ? path76.join(abs, inside) : abs;
46907
+ const startDir = await stat24(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
46524
46908
  return {
46525
46909
  cwd: startDir,
46526
46910
  path: abs,
46527
46911
  branch,
46528
46912
  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);
46913
+ await git6(root, "worktree", "remove", "--force", abs).catch(() => rm9(abs, { recursive: true, force: true }));
46914
+ await git6(root, "worktree", "prune").catch(() => void 0);
46915
+ await git6(root, "branch", "-D", branch).catch(() => void 0);
46532
46916
  }
46533
46917
  };
46534
46918
  }
46535
46919
 
46920
+ // src/bridge/conductor-group.ts
46921
+ init_protocol();
46922
+ async function groupConductor(peers, ask = peerRequest) {
46923
+ const answers = await Promise.all(peers.map(async (peer) => {
46924
+ try {
46925
+ const conductor = (await ask(peer, "/v1/conductor", void 0, 8e3)).conductor;
46926
+ return { peer, conductor: conductor && typeof conductor === "object" ? object2(conductor) : void 0 };
46927
+ } catch (error62) {
46928
+ if (error62 instanceof BridgeError && error62.status === 404 && error62.message === disabledHint("conductor")) return { peer };
46929
+ const message = error62 instanceof BridgeError && error62.status === 404 ? "Its Hook is too old to report a conductor." : error62 instanceof Error ? error62.message : "Unreachable.";
46930
+ return { peer, error: message };
46931
+ }
46932
+ }));
46933
+ const hit = answers.find((answer) => answer.conductor);
46934
+ return {
46935
+ ...hit ? { found: { computer: hit.peer.name, ...hit.conductor.target ? { target: object2(hit.conductor.target) } : {} } } : {},
46936
+ unchecked: answers.flatMap((answer) => "error" in answer && answer.error ? [{ computer: answer.peer.name, error: answer.error }] : [])
46937
+ };
46938
+ }
46939
+
46536
46940
  // src/bridge/server-launch.ts
46537
46941
  init_protocol();
46538
46942
  var launchKinds = ["codex", "claude", "copilot", "opencode"];
46539
46943
  var plainText = (max) => external_exports.string().min(1).max(max).refine((t) => !/[\x00-\x1f\x7f]/.test(t));
46540
46944
  async function conductorBrief() {
46541
46945
  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";
46946
+ 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
46947
  else {
46544
- const here = path76.dirname(fileURLToPath(import.meta.url));
46948
+ const here = path77.dirname(fileURLToPath(import.meta.url));
46545
46949
  for (const candidate of [
46546
- path76.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
46547
- path76.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
46950
+ path77.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
46951
+ path77.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
46548
46952
  ]) {
46549
- source = await readFile30(candidate, "utf8").catch(() => void 0);
46953
+ source = await readFile31(candidate, "utf8").catch(() => void 0);
46550
46954
  if (source !== void 0) break;
46551
46955
  }
46552
46956
  }
@@ -46565,15 +46969,15 @@ function effortArgs(kind, effort) {
46565
46969
  }
46566
46970
  async function prepareConductor(kind, effort, model) {
46567
46971
  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");
46972
+ const briefDirectory = path77.join(bridgeRoot(), "conductor");
46973
+ await mkdir20(briefDirectory, { recursive: true, mode: 448 });
46974
+ const briefFile = path77.join(briefDirectory, "brief.md");
46975
+ if (await readFile31(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
46572
46976
  if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
46573
46977
  if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
46574
46978
  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");
46979
+ const directory = path77.join(process.env.XDG_CONFIG_HOME || path77.join(homeDir(), ".config"), "opencode", "agents");
46980
+ const file2 = path77.join(directory, "conductor.md");
46577
46981
  const definition = `---
46578
46982
  description: Coordinate the owner's work across agent sessions.
46579
46983
  mode: primary
@@ -46581,8 +46985,8 @@ mode: primary
46581
46985
 
46582
46986
  ${brief}
46583
46987
  `;
46584
- await mkdir18(directory, { recursive: true, mode: 448 });
46585
- if (await readFile30(file2, "utf8").catch(() => void 0) !== definition) await atomic(file2, definition, 420);
46988
+ await mkdir20(directory, { recursive: true, mode: 448 });
46989
+ if (await readFile31(file2, "utf8").catch(() => void 0) !== definition) await atomic(file2, definition, 420);
46586
46990
  return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
46587
46991
  }
46588
46992
  throw new BridgeError(400, "The selected harness cannot run as a conductor.");
@@ -46595,13 +46999,22 @@ async function targetForPane(server, pane) {
46595
46999
  const chat = await paneChatState(server, pane).catch(() => ({}));
46596
47000
  return chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : void 0;
46597
47001
  }
47002
+ async function localConductor(known) {
47003
+ const names = [.../* @__PURE__ */ new Set([...known ? [known.server] : [], ...(await servers()).map((item) => String(item.session))])];
47004
+ for (const name of names) {
47005
+ const value2 = known && name === known.server ? known.snapshot : await snapshot(name);
47006
+ 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)));
47007
+ if (existing) return { server: name, target: await targetForPane(name, existing) };
47008
+ }
47009
+ return void 0;
47010
+ }
46598
47011
  function herdrAgentName(label2) {
46599
47012
  const slug = label2.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "").slice(0, 32).replace(/-+$/, "");
46600
47013
  return slug || "agent";
46601
47014
  }
46602
47015
  async function launchSession(server, data, options = {}) {
46603
47016
  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);
47017
+ const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path77.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
46605
47018
  const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
46606
47019
  if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
46607
47020
  const label2 = plainText(200).parse(data.label);
@@ -46609,23 +47022,28 @@ async function launchSession(server, data, options = {}) {
46609
47022
  const effort = external_exports.enum(launchEfforts).default("medium").parse(data.effort);
46610
47023
  if (role === "conductor" && kind === "copilot") throw new BridgeError(400, "Copilot cannot run as a conductor.");
46611
47024
  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;
47025
+ const wanted = options.canary ? "phren-canary" : role === "conductor" ? isConductorName(baseName) ? baseName : herdrAgentName(`conductor-${baseName}`) : isConductorName(baseName) ? herdrAgentName(`worker-${baseName}`) : baseName;
46613
47026
  const model = typeof data.model === "string" && data.model.trim() ? plainText(200).parse(data.model.trim()) : void 0;
46614
47027
  const modelFlag = { codex: "--model", claude: "--model", opencode: "--model" };
46615
- const workspace = data.workspaceId === void 0 ? void 0 : id.parse(data.workspaceId);
47028
+ let workspace = data.workspaceId === void 0 ? void 0 : id.parse(data.workspaceId);
46616
47029
  const timeout = Math.min(12e4, Math.max(3001, data.timeoutMs === void 0 ? 45e3 : external_exports.number().int().parse(data.timeoutMs)));
46617
47030
  const before = await snapshot(server);
46618
47031
  const taken = agentNames(before);
46619
47032
  let name = wanted;
46620
47033
  for (let n = 2; taken.has(name) && n < 100; n++) name = `${wanted.slice(0, 32 - String(n).length - 1)}-${n}`;
47034
+ let unchecked = [];
46621
47035
  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
- }
47036
+ const existing = await localConductor({ server, snapshot: before });
47037
+ if (existing) throw new BridgeError(409, "A conductor is already running on this computer.", { target: existing.target });
47038
+ const group = await groupConductor((await optionalHookPeers()).peers);
47039
+ if (group.found) throw new BridgeError(
47040
+ 409,
47041
+ `A conductor is already running on ${group.found.computer}, which is linked with this computer. A connected group shares one conductor.`,
47042
+ { computer: group.found.computer, target: group.found.target }
47043
+ );
47044
+ unchecked = group.unchecked;
46628
47045
  }
47046
+ if (role === "agent" && workspace && objects(before.panes).some((pane2) => pane2.workspace_id === workspace && isConductorName(paneAgentName(before, pane2)))) workspace = void 0;
46629
47047
  const args = role === "conductor" ? await prepareConductor(kind, effort, model) : [...model && modelFlag[kind] ? [modelFlag[kind], model] : [], ...data.effort === void 0 ? [] : effortArgs(kind, effort)];
46630
47048
  if (workspace && !objects(before.workspaces).some((w) => w.workspace_id === workspace)) throw new BridgeError(409, "The workspace changed.");
46631
47049
  const knownWorkspaces = new Set(objects(before.workspaces).map((w) => w.workspace_id));
@@ -46673,6 +47091,7 @@ async function launchSession(server, data, options = {}) {
46673
47091
  role,
46674
47092
  sessionId: sessionId2,
46675
47093
  target,
47094
+ ...unchecked.length ? { unchecked } : {},
46676
47095
  ...worktree ? { worktree: { path: worktree.path, branch: worktree.branch } } : {}
46677
47096
  };
46678
47097
  }
@@ -46686,7 +47105,7 @@ async function workspaceAction(server, operation, data) {
46686
47105
  if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
46687
47106
  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
47107
  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);
47108
+ 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
47109
  if (operation === "create") await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label: label2, cwd, focus: false, env: {} });
46691
47110
  else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
46692
47111
  else if (pane && operation === "focus") await rpc(server, "pane.focus", { pane_id: pane });
@@ -46697,6 +47116,79 @@ async function workspaceAction(server, operation, data) {
46697
47116
 
46698
47117
  // src/bridge/server-routes.ts
46699
47118
  init_metrics();
47119
+
47120
+ // src/bridge/speech.ts
47121
+ init_zod();
47122
+ init_protocol();
47123
+ import { once } from "node:events";
47124
+ var SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
47125
+ var OUTPUT_FORMAT = "pcm_24000";
47126
+ var SPEECH_MODEL = "eleven_flash_v2_5";
47127
+ var DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
47128
+ var MAX_TEXT = 2e3;
47129
+ var speechRequest = external_exports.object({ text: external_exports.string().trim().min(1).max(MAX_TEXT) });
47130
+ async function speechError(upstream) {
47131
+ let detail = "";
47132
+ try {
47133
+ detail = String((await upstream.json()).detail?.status ?? "");
47134
+ } catch {
47135
+ }
47136
+ if (detail === "quota_exceeded") return new BridgeError(402, "The ElevenLabs quota on this computer's account is used up.", { code: "speech-quota" });
47137
+ switch (upstream.status) {
47138
+ case 401:
47139
+ case 403:
47140
+ return new BridgeError(502, "ElevenLabs refused this computer's key.", { code: "speech-rejected" });
47141
+ case 404:
47142
+ return new BridgeError(502, "ElevenLabs doesn't know the configured voice.", { code: "speech-voice" });
47143
+ case 400:
47144
+ case 422:
47145
+ return new BridgeError(400, "ElevenLabs couldn't voice this text.", { code: "speech-invalid" });
47146
+ case 429:
47147
+ return new BridgeError(429, "ElevenLabs is busy. Try again shortly.", { code: "speech-busy" });
47148
+ default:
47149
+ return new BridgeError(502, `ElevenLabs failed (HTTP ${upstream.status}).`, { code: "speech-failed" });
47150
+ }
47151
+ }
47152
+ async function synthesizeSpeech(text3, signal, options = {}) {
47153
+ const key = await (options.key ?? readSpeechKey)();
47154
+ if (!key) throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
47155
+ const voice = options.voice ?? process.env.PHREN_SPEECH_VOICE ?? DEFAULT_SPEECH_VOICE;
47156
+ const url2 = `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice)}/stream?output_format=${OUTPUT_FORMAT}`;
47157
+ let upstream;
47158
+ try {
47159
+ upstream = await (options.fetch ?? fetch)(url2, {
47160
+ method: "POST",
47161
+ signal,
47162
+ headers: { "xi-api-key": key, "Content-Type": "application/json" },
47163
+ body: JSON.stringify({ text: text3, model_id: SPEECH_MODEL, voice_settings: { stability: 0.6, similarity_boost: 0.75 } })
47164
+ });
47165
+ } catch {
47166
+ throw new BridgeError(502, "Couldn't reach ElevenLabs from this computer.", { code: "speech-unreachable" });
47167
+ }
47168
+ if (!upstream.ok || !upstream.body) throw await speechError(upstream);
47169
+ return upstream.body;
47170
+ }
47171
+ async function streamSpeech(data, response, options = {}) {
47172
+ const { text: text3 } = speechRequest.parse(data);
47173
+ const abort = new AbortController();
47174
+ response.once("close", () => {
47175
+ if (!response.writableEnded) abort.abort();
47176
+ });
47177
+ const audio = await synthesizeSpeech(text3, abort.signal, options);
47178
+ response.statusCode = 200;
47179
+ response.setHeader("Content-Type", "application/octet-stream");
47180
+ response.setHeader("X-Phren-Audio", SPEECH_AUDIO);
47181
+ try {
47182
+ for await (const chunk of audio) {
47183
+ if (!response.write(chunk)) await once(response, "drain", { signal: abort.signal });
47184
+ }
47185
+ response.end();
47186
+ } catch {
47187
+ response.destroy();
47188
+ }
47189
+ }
47190
+
47191
+ // src/bridge/server-routes.ts
46700
47192
  var CHILD_ACTIVITY_CACHE_MS = 5e3;
46701
47193
  var OVERVIEW_ENRICH_BUDGET_MS = 5e3;
46702
47194
  var childActivityCache = /* @__PURE__ */ new Map();
@@ -46740,7 +47232,8 @@ var capabilities = {
46740
47232
  code: true,
46741
47233
  overviewStream: true,
46742
47234
  speech: true,
46743
- transcribe: true
47235
+ transcribe: true,
47236
+ memoryStore: true
46744
47237
  };
46745
47238
  function capabilitiesForModules(snapshot2) {
46746
47239
  const allowed = new Set(snapshot2.modules.flatMap((module) => module.capabilities));
@@ -46867,7 +47360,9 @@ function createRouteHandler(ctx) {
46867
47360
  if (url2.origin !== "http://phren.local") throw new BridgeError(400, "Invalid request origin.");
46868
47361
  requireRoute(modules, request6.method ?? "", url2.pathname);
46869
47362
  let result;
46870
- if (request6.method === "GET") {
47363
+ if (url2.pathname.startsWith("/v1/store/")) {
47364
+ result = await storeRoute(modules.store, request6.method ?? "", url2, request6.method === "POST" ? await body(request6) : void 0);
47365
+ } else if (request6.method === "GET") {
46871
47366
  switch (url2.pathname) {
46872
47367
  case "/v1/health":
46873
47368
  result = { ...info, codePackage: await codePackageStatus(scheduleStore, modules.has("code")) };
@@ -46895,6 +47390,10 @@ function createRouteHandler(ctx) {
46895
47390
  case "/v1/conductor/grants":
46896
47391
  result = { grants: await listGrants() };
46897
47392
  break;
47393
+ // Asked by linked peers before they start a conductor: one per connected group.
47394
+ case "/v1/conductor":
47395
+ result = { computer: info.computer, conductor: await localConductor() ?? null };
47396
+ break;
46898
47397
  case "/v1/dispatch/capacity": {
46899
47398
  const live = await servers();
46900
47399
  const snapshots = await Promise.all(live.map((server) => snapshot(String(server.session))));
@@ -46931,7 +47430,7 @@ function createRouteHandler(ctx) {
46931
47430
  case "/v1/files/range": {
46932
47431
  let root;
46933
47432
  if (url2.searchParams.get("scope") === "uploads") {
46934
- root = path77.join(bridgeRoot(), "uploads");
47433
+ root = path78.join(bridgeRoot(), "uploads");
46935
47434
  } else if (url2.searchParams.has("session")) {
46936
47435
  const target = targetFromURL(url2), pane = await validateTarget(target);
46937
47436
  const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
@@ -47236,7 +47735,7 @@ init_protocol();
47236
47735
  // src/bridge/transcript-preview.ts
47237
47736
  init_codex_threads();
47238
47737
  import { constants as constants4 } from "node:fs";
47239
- import { open as open13 } from "node:fs/promises";
47738
+ import { open as open14 } from "node:fs/promises";
47240
47739
  init_protocol();
47241
47740
  init_transcript_index();
47242
47741
  var PREVIEW_INTERVAL_MS = 500;
@@ -47289,9 +47788,9 @@ function claudePanePreview(rendered, prompt, previous = "") {
47289
47788
  }
47290
47789
  if (!writing) continue;
47291
47790
  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}/, ""));
47791
+ const clean2 = tidy(line);
47792
+ if (/^\s*(?:↳|⎿|ctrl\+|shift\+|\? for shortcuts)/i.test(clean2) || claudeChrome(clean2)) continue;
47793
+ reply.push(clean2.replace(/^ {2}/, ""));
47295
47794
  shown.push(tidy(markedBody[index2] ?? line).replace(/^ {2}/, ""));
47296
47795
  }
47297
47796
  const text3 = unwrapTerminalLines(reply, shown).trim().slice(0, MAX_TEXT2);
@@ -47450,11 +47949,11 @@ async function readDeltaPreview(target, file2, rollout) {
47450
47949
  if (target.source === "codex") return await codexThreadPreview(target.session) ?? (file2 && rollout ? await rollout.read(file2).catch(() => null) : null);
47451
47950
  if (target.source !== "opencode" || !file2) return null;
47452
47951
  try {
47453
- const handle = await open13(file2 + ".preview.json", constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
47952
+ const handle = await open14(file2 + ".preview.json", constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
47454
47953
  let bytes;
47455
47954
  try {
47456
- const stat24 = await handle.stat();
47457
- if (!stat24.isFile() || stat24.size > MAX_PREVIEW_BYTES) return null;
47955
+ const stat25 = await handle.stat();
47956
+ if (!stat25.isFile() || stat25.size > MAX_PREVIEW_BYTES) return null;
47458
47957
  const buffer = Buffer.alloc(MAX_PREVIEW_BYTES + 1);
47459
47958
  const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
47460
47959
  if (bytesRead > MAX_PREVIEW_BYTES) return null;
@@ -47701,7 +48200,13 @@ function transcriptStreams(ctx) {
47701
48200
  store: info.store,
47702
48201
  profile: info.profile,
47703
48202
  generation: info.generation,
47704
- capabilities: { ...activeCapabilities, asyncQuestions: target.source === "codex" && codexQuestions.available },
48203
+ capabilities: {
48204
+ ...activeCapabilities,
48205
+ asyncQuestions: target.source === "codex" && codexQuestions.available,
48206
+ // Claude's AskUserQuestion is answered in its terminal dialog
48207
+ // through /v1/questions/answer, whether or not a hold caught it.
48208
+ ...target.source === "claude" ? { questions: true } : {}
48209
+ },
47705
48210
  branch
47706
48211
  } });
47707
48212
  }
@@ -47854,15 +48359,15 @@ async function serve(version3) {
47854
48359
  if (!modules.has("hook")) throw new BridgeError(404, disabledHint("hook"));
47855
48360
  const activeCapabilities = capabilitiesForModules(modules);
47856
48361
  const root = bridgeRoot();
47857
- await mkdir19(root, { recursive: true, mode: 448 });
48362
+ await mkdir21(root, { recursive: true, mode: 448 });
47858
48363
  await chmod5(root, 448);
47859
48364
  let computerID2;
47860
- const identityFile = path78.join(root, "computer-id");
48365
+ const identityFile = path79.join(root, "computer-id");
47861
48366
  try {
47862
- computerID2 = (await readFile31(identityFile, "utf8")).trim();
48367
+ computerID2 = (await readFile32(identityFile, "utf8")).trim();
47863
48368
  } catch {
47864
48369
  computerID2 = randomUUID19();
47865
- await writeFile10(identityFile, computerID2, { flag: "wx", mode: 384 });
48370
+ await writeFile11(identityFile, computerID2, { flag: "wx", mode: 384 });
47866
48371
  }
47867
48372
  const launches = new LaunchLimiter();
47868
48373
  const dispatches = modules.has("conductor") ? new DispatchService({
@@ -47907,7 +48412,7 @@ async function serve(version3) {
47907
48412
  if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
47908
48413
  function gatewayTiming() {
47909
48414
  try {
47910
- const parsed = JSON.parse(readFileSync31(path78.join(root, "gateway.json"), "utf8"));
48415
+ const parsed = JSON.parse(readFileSync31(path79.join(root, "gateway.json"), "utf8"));
47911
48416
  if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
47912
48417
  } catch {
47913
48418
  }
@@ -47936,7 +48441,7 @@ async function serve(version3) {
47936
48441
  launch: (server, data) => launches.run(() => launchSession(server, data, { canary: true })),
47937
48442
  scheduler
47938
48443
  });
47939
- const old = await lstat18(socketPath()).catch(() => null);
48444
+ const old = await lstat19(socketPath()).catch(() => null);
47940
48445
  if (old) {
47941
48446
  if (!old.isSocket() || process.getuid && old.uid !== process.getuid()) throw new Error("Refusing to replace an unexpected hook socket.");
47942
48447
  const { connect: connect4 } = await import("node:net");
@@ -47953,7 +48458,7 @@ async function serve(version3) {
47953
48458
  }
47954
48459
  const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
47955
48460
  };
47956
- if (modules.has("git")) await rm9(path78.join(root, "changes-scratch"), { recursive: true, force: true });
48461
+ if (modules.has("git")) await rm10(path79.join(root, "changes-scratch"), { recursive: true, force: true });
47957
48462
  const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
47958
48463
  const { stream } = streams;
47959
48464
  const overview = overviewStream({
@@ -48095,17 +48600,171 @@ async function serve(version3) {
48095
48600
 
48096
48601
  // src/bridge/command.ts
48097
48602
  init_protocol();
48603
+
48604
+ // src/bridge/link.ts
48605
+ init_profile_store();
48606
+ init_phren_paths();
48607
+ import { execFile as execFile16 } from "node:child_process";
48608
+ import { readFile as readFile33 } from "node:fs/promises";
48609
+ import { homedir as homedir19, hostname as hostname9, userInfo as userInfo2 } from "node:os";
48610
+ import path80 from "node:path";
48611
+ import { promisify as promisify16 } from "node:util";
48612
+ init_protocol();
48613
+ var exec16 = promisify16(execFile16);
48614
+ var REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"';
48615
+ var GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
48616
+ function sshConfigHosts(text3) {
48617
+ const hosts = [];
48618
+ let block = [], skip = false;
48619
+ const flush = () => {
48620
+ if (!skip) hosts.push(...block);
48621
+ block = [];
48622
+ skip = false;
48623
+ };
48624
+ for (const raw of text3.split(/\r?\n/)) {
48625
+ const match = /^\s*([A-Za-z]+)(?:\s*=\s*|\s+)(.+?)\s*$/.exec(raw.replace(/\s#.*$|^\s*#.*$/, ""));
48626
+ if (!match) continue;
48627
+ const [key, value2] = [match[1].toLowerCase(), match[2]];
48628
+ if (key === "host" || key === "match") {
48629
+ flush();
48630
+ if (key === "host") block = value2.split(/\s+/).filter((alias) => !/[*?!]/.test(alias));
48631
+ } else if (key === "hostname" && GIT_HOSTS.test(value2)) skip = true;
48632
+ }
48633
+ flush();
48634
+ return [...new Set(hosts.filter((alias) => !GIT_HOSTS.test(alias)))];
48635
+ }
48636
+ async function ssh(host, command, input2, timeout = 2e4) {
48637
+ return new Promise((resolve11, reject) => {
48638
+ const child = execFile16(
48639
+ "ssh",
48640
+ ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", host, command],
48641
+ { timeout, maxBuffer: 1048576 },
48642
+ (error62, stdout, stderr) => {
48643
+ if (error62) reject(new BridgeError(503, `ssh ${host}: ${(stderr || error62.message).split("\n").find(Boolean)?.slice(0, 200) ?? "failed"}`));
48644
+ else resolve11(stdout);
48645
+ }
48646
+ );
48647
+ child.stdin?.end(input2 ?? "");
48648
+ });
48649
+ }
48650
+ async function probe2(host) {
48651
+ 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);
48652
+ const field = (name) => new RegExp(`^${name}=(.*)$`, "m").exec(out)?.[1]?.trim() || void 0;
48653
+ const computerId = field("id");
48654
+ return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
48655
+ }
48656
+ async function discoverComputers(options = {}) {
48657
+ const config3 = options.sshConfig ?? await readFile33(path80.join(homedir19(), ".ssh", "config"), "utf8").catch(() => "");
48658
+ const store = options.store !== void 0 ? options.store : findPhrenPath();
48659
+ const machines = store ? listMachines(store) : void 0;
48660
+ const { peers } = await optionalHookPeers();
48661
+ const own2 = (await readFile33(path80.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
48662
+ const known = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
48663
+ const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known.has(computerLabel(host))).slice(0, 32);
48664
+ const [found, peerIds] = await Promise.all([
48665
+ Promise.all(candidates.map((host) => probe2(host).catch(() => void 0))),
48666
+ Promise.all(peers.map((peer) => peerRequest(peer, "/v1/health").then((health2) => object2(health2.computer).id, () => void 0)))
48667
+ ]);
48668
+ const seen = /* @__PURE__ */ new Set([own2, ...peerIds.filter((id2) => typeof id2 === "string")]);
48669
+ const reachable = found.filter((item) => {
48670
+ if (!item || seen.has(item.computerId)) return false;
48671
+ seen.add(item.computerId);
48672
+ return true;
48673
+ });
48674
+ return { reachable, checked: candidates };
48675
+ }
48676
+ function slugName(value2) {
48677
+ const label2 = computerLabel(value2).replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^[^A-Za-z0-9_]+/, "") || "computer";
48678
+ return computerName.parse(label2.slice(0, 100));
48679
+ }
48680
+ async function linkComputer(host, options = {}) {
48681
+ const remote = await probe2(host);
48682
+ if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
48683
+ const own2 = (await readFile33(path80.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
48684
+ if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
48685
+ const name = computerName.parse(options.name ?? slugName(host));
48686
+ const as = computerName.parse(options.as ?? slugName(hostname9()));
48687
+ const backAddress = options.backAddress ?? remote.client;
48688
+ if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
48689
+ 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(" ")]));
48690
+ const remoteHostKey = publicComputerKey((await ssh(host, "cat /etc/ssh/ssh_host_ed25519_key.pub")).trim().split(/\s+/).slice(0, 2).join(" "));
48691
+ const localHostKey = publicComputerKey((await readFile33("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
48692
+ const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
48693
+ 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));
48694
+ await acceptComputer(name, remoteLine);
48695
+ const peer = { name, address: String(resolved.hostname || host), username: remote.user || String(resolved.user), port: Number(resolved.port) || 22, server: "default", hostKey: remoteHostKey };
48696
+ const local = await addHookPeer(peer);
48697
+ const back = { name: as, address: backAddress, username: userInfo2().username, port: 22, server: "default", hostKey: localHostKey };
48698
+ const answer = JSON.parse(await ssh(host, `${REMOTE_PATH} phren bridge add-peer`, JSON.stringify(back), 45e3).catch((error62) => {
48699
+ 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.`);
48700
+ throw error62;
48701
+ }));
48702
+ const reached = await peerRequest(peer, "/v1/health").then(() => void 0, (error62) => error62.message);
48703
+ return {
48704
+ name,
48705
+ as,
48706
+ local: { added: local.added },
48707
+ remote: { added: !!answer.added, reachable: !!answer.reachable, ...answer.error ? { error: String(answer.error) } : {} },
48708
+ reachable: !reached,
48709
+ ...reached ? { error: reached } : {}
48710
+ };
48711
+ }
48712
+ async function addPeerFromLink(input2) {
48713
+ const { added, peer } = await addHookPeer(JSON.parse(input2));
48714
+ const error62 = await peerRequest(peer, "/v1/health").then(() => void 0, (failure2) => failure2.message);
48715
+ return { added, reachable: !error62, ...error62 ? { error: error62 } : {} };
48716
+ }
48717
+
48718
+ // src/bridge/command.ts
48098
48719
  init_fanouts();
48720
+ 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
48721
  async function runBridge(args, version3) {
48100
48722
  switch (args[0]) {
48101
48723
  case "enroll-computer": {
48102
48724
  if (args.length === 2) console.log(await enrollComputer(args[1]));
48103
48725
  else if (args.length === 4 && args[2] === "--accept") {
48104
- await acceptComputer(args[1], await readFile32(args[3], "utf8"));
48726
+ await acceptComputer(args[1], await readFile34(args[3], "utf8"));
48105
48727
  console.log(`Enrolled ${args[1]} for Phren Hook.`);
48106
48728
  } else throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
48107
48729
  break;
48108
48730
  }
48731
+ case "discover": {
48732
+ const { reachable, checked } = await discoverComputers();
48733
+ if (!reachable.length) console.log(`No unlinked computers running Phren Hook answered over ssh (checked ${checked.length}: ${checked.join(", ") || "none"}).`);
48734
+ else {
48735
+ console.log("Reachable over ssh, running Phren Hook, and not linked:");
48736
+ for (const item of reachable) console.log(` ${item.host} (${item.user}) link with: phren bridge link ${item.host}`);
48737
+ }
48738
+ break;
48739
+ }
48740
+ case "link": {
48741
+ const host = args[1];
48742
+ const flag = (name) => {
48743
+ const index2 = args.indexOf(name);
48744
+ return index2 > 1 ? args[index2 + 1] : void 0;
48745
+ };
48746
+ if (!host || host.startsWith("-")) throw new Error(LINK_USAGE);
48747
+ if (!args.includes("--yes")) {
48748
+ if (!process.stdin.isTTY) throw new Error(`Linking ${host} lets each computer run agents on the other. Pass --yes to confirm.`);
48749
+ const { createInterface: createInterface2 } = await import("node:readline/promises");
48750
+ const prompt = createInterface2({ input: process.stdin, output: process.stdout });
48751
+ const answer = await prompt.question(`Link this computer and ${host} both ways, so each can list and start agents on the other? [y/N] `);
48752
+ prompt.close();
48753
+ if (!/^y(es)?$/i.test(answer.trim())) {
48754
+ console.log("Not linked.");
48755
+ return 1;
48756
+ }
48757
+ }
48758
+ const result = await linkComputer(host, { name: flag("--name"), as: flag("--as"), backAddress: flag("--back-address") });
48759
+ console.log(JSON.stringify(result, null, 2));
48760
+ return result.reachable && result.remote.reachable ? 0 : 1;
48761
+ }
48762
+ case "add-peer": {
48763
+ const chunks = [];
48764
+ for await (const chunk of process.stdin) chunks.push(chunk);
48765
+ console.log(JSON.stringify(await addPeerFromLink(Buffer.concat(chunks).toString("utf8"))));
48766
+ break;
48767
+ }
48109
48768
  case "fanouts": {
48110
48769
  if (args[1] !== "archive") throw new Error(FANOUTS_ARCHIVE_USAGE);
48111
48770
  const options = parseFanoutArchiveFlags(args.slice(2));
@@ -48116,6 +48775,12 @@ async function runBridge(args, version3) {
48116
48775
  console.log(`${doing} ${moved.length} fan-out job(s); ${removal} ${deleted} past the ${ARCHIVE_MAX_FOLDERS}-folder cap.`);
48117
48776
  break;
48118
48777
  }
48778
+ case "speech-key": {
48779
+ if (args[1] !== "set" || args.length !== 2) throw new Error(SPEECH_KEY_USAGE);
48780
+ await writeSpeechKey(await readSecret("ElevenLabs API key: "));
48781
+ console.log(`Stored the ElevenLabs key in ${speechKeyFile()} (mode 600).`);
48782
+ break;
48783
+ }
48119
48784
  case "usage-statusline":
48120
48785
  await captureClaudeUsage(args[1] || "");
48121
48786
  break;
@@ -48147,7 +48812,7 @@ async function runBridge(args, version3) {
48147
48812
  break;
48148
48813
  case "doctor": {
48149
48814
  const helper2 = await health(), muxes = await servers();
48150
- const push = approvalPushCheck(helper2);
48815
+ const push = approvalPushCheck(helper2), speech = await speechKeyStatus();
48151
48816
  console.log(JSON.stringify({ ok: true, helper: helper2, herdr: muxes, checks: {
48152
48817
  privateSocket: true,
48153
48818
  protocol: true,
@@ -48155,13 +48820,15 @@ async function runBridge(args, version3) {
48155
48820
  herdrRunning: muxes.length > 0,
48156
48821
  terminal: "SSH PTY; authorize the Phren device key with pty",
48157
48822
  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"
48823
+ approvalPush: push.configured ? "configured" : "not configured",
48824
+ speechKey: speech.configured ? "configured" : "not configured",
48825
+ speechKeyDetail: speech.detail
48159
48826
  }, ...push.warning ? { warnings: [push.warning] } : {} }, null, 2));
48160
48827
  if (push.warning) console.error(`warning: ${push.warning}`);
48161
48828
  break;
48162
48829
  }
48163
48830
  default:
48164
- throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|fanouts archive>");
48831
+ throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|discover|link|fanouts archive|speech-key set>");
48165
48832
  }
48166
48833
  return 0;
48167
48834
  }
@@ -48169,11 +48836,50 @@ function approvalPushCheck(helper2) {
48169
48836
  const configured = object2(helper2.capabilities).approvalPush === "direct-apns";
48170
48837
  return configured ? { configured } : { configured, warning: apnsSetupSteps() };
48171
48838
  }
48839
+ var SPEECH_KEY_USAGE = "Usage: phren bridge speech-key set (paste the key when asked, or pipe it on stdin)";
48840
+ async function readSecret(prompt) {
48841
+ const stdin = process.stdin;
48842
+ if (!stdin.isTTY) {
48843
+ let text3 = "";
48844
+ for await (const chunk of stdin) text3 += chunk;
48845
+ return text3;
48846
+ }
48847
+ process.stderr.write(prompt);
48848
+ stdin.setEncoding("utf8");
48849
+ stdin.setRawMode(true);
48850
+ stdin.resume();
48851
+ return new Promise((resolve11, reject) => {
48852
+ let value2 = "";
48853
+ const finish = () => {
48854
+ stdin.off("data", onData);
48855
+ stdin.setRawMode(false);
48856
+ stdin.pause();
48857
+ process.stderr.write("\n");
48858
+ };
48859
+ const onData = (chunk) => {
48860
+ for (const char of chunk) {
48861
+ if (char === "\r" || char === "\n") {
48862
+ finish();
48863
+ resolve11(value2);
48864
+ return;
48865
+ }
48866
+ if (char === "") {
48867
+ finish();
48868
+ reject(new Error("Cancelled."));
48869
+ return;
48870
+ }
48871
+ if (char === "\x7F" || char === "\b") value2 = value2.slice(0, -1);
48872
+ else value2 += char;
48873
+ }
48874
+ };
48875
+ stdin.on("data", onData);
48876
+ });
48877
+ }
48172
48878
 
48173
48879
  // src/bridge/hook-main.ts
48174
48880
  init_utils_helpers();
48175
48881
  Object.assign(process.env, nonInteractiveGitEnv());
48176
- runBridge(process.argv.slice(2), "0.3.0").then((code) => {
48882
+ runBridge(process.argv.slice(2), "0.3.1").then((code) => {
48177
48883
  process.exitCode = code;
48178
48884
  }).catch((error62) => {
48179
48885
  console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");