@wrongstack/core 0.268.0 → 0.269.0

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 (75) hide show
  1. package/dist/{agent-bridge-UhojbpWx.d.ts → agent-bridge-PcHQl_UQ.d.ts} +1 -1
  2. package/dist/{agent-subagent-runner-Bvtf1o9K.d.ts → agent-subagent-runner-SHJW7t8q.d.ts} +8 -8
  3. package/dist/{brain-69wzMKp1.d.ts → brain-BYcK__Ym.d.ts} +1 -1
  4. package/dist/{compactor-CBQAJoDc.d.ts → compactor-C2RKEBtC.d.ts} +1 -1
  5. package/dist/{config-VKfOZ-6X.d.ts → config-C_ae2k86.d.ts} +11 -2
  6. package/dist/{context-C0U8B9NF.d.ts → context-Dp87Bcaq.d.ts} +24 -1
  7. package/dist/coordination/index.d.ts +22 -16
  8. package/dist/coordination/index.js +233 -86
  9. package/dist/coordination/index.js.map +1 -1
  10. package/dist/defaults/index.d.ts +25 -25
  11. package/dist/defaults/index.js +272 -69
  12. package/dist/defaults/index.js.map +1 -1
  13. package/dist/execution/index.d.ts +15 -15
  14. package/dist/execution/index.js +116 -19
  15. package/dist/execution/index.js.map +1 -1
  16. package/dist/execution/prompt-enhancer.d.ts +1 -1
  17. package/dist/extension/index.d.ts +6 -6
  18. package/dist/{global-mailbox-KByEFFBa.d.ts → global-mailbox-Bvrz1P3f.d.ts} +2 -1
  19. package/dist/{goal-preamble-CrYjmdw4.d.ts → goal-preamble-CA_4yiGQ.d.ts} +9 -9
  20. package/dist/{goal-store-Y_zdLZ3q.d.ts → goal-store-DhuJoUNG.d.ts} +1 -1
  21. package/dist/hq/index.d.ts +15 -6
  22. package/dist/hq/index.js +55 -8
  23. package/dist/hq/index.js.map +1 -1
  24. package/dist/{index-CtQnmkaS.d.ts → index-CZQ6Pwbs.d.ts} +8 -8
  25. package/dist/{index-gCv830d7.d.ts → index-W4VJCzHa.d.ts} +5 -5
  26. package/dist/{index-BfaS-f_m.d.ts → index-whDfTANu.d.ts} +2 -2
  27. package/dist/index.d.ts +41 -41
  28. package/dist/index.js +531 -167
  29. package/dist/index.js.map +1 -1
  30. package/dist/infrastructure/index.d.ts +6 -6
  31. package/dist/infrastructure/index.js +3 -3
  32. package/dist/infrastructure/index.js.map +1 -1
  33. package/dist/kernel/index.d.ts +9 -9
  34. package/dist/{mcp-servers-HT3Fi7Bl.d.ts → mcp-servers-DJdZiRcv.d.ts} +3 -3
  35. package/dist/models/index.d.ts +5 -5
  36. package/dist/models/index.js +1 -1
  37. package/dist/models/index.js.map +1 -1
  38. package/dist/{models-registry-Bvcl3Vaa.d.ts → models-registry-C3a-2-Yd.d.ts} +1 -1
  39. package/dist/{multi-agent-coordinator-BACjsmkC.d.ts → multi-agent-coordinator-CJSpTe5O.d.ts} +1 -1
  40. package/dist/{null-fleet-bus-DA7fvhUg.d.ts → null-fleet-bus-QVshIsDx.d.ts} +6 -6
  41. package/dist/observability/index.d.ts +2 -2
  42. package/dist/{parallel-eternal-engine-Ci71gYu_.d.ts → parallel-eternal-engine-D9y5Pkcc.d.ts} +9 -9
  43. package/dist/{path-resolver-O1IJnmKE.d.ts → path-resolver-CnQ8SIfh.d.ts} +3 -3
  44. package/dist/{permission-Bd-57Lbl.d.ts → permission-CvYQNUqZ.d.ts} +1 -1
  45. package/dist/{permission-policy-uNXC6Kge.d.ts → permission-policy-D5Ss8j4B.d.ts} +2 -2
  46. package/dist/{pipeline-BDNvENyV.d.ts → pipeline-l_zzFRh3.d.ts} +2 -2
  47. package/dist/{plan-templates-EMsalEtN.d.ts → plan-templates-NtPgyeJA.d.ts} +6 -5
  48. package/dist/{provider-model-resolve-CEb9x886.d.ts → provider-model-resolve-d5poT5y0.d.ts} +3 -3
  49. package/dist/{provider-runner-DWJbpo70.d.ts → provider-runner-gkctlQV_.d.ts} +3 -3
  50. package/dist/{retry-policy-C3s_lvdK.d.ts → retry-policy-CtFhfwa8.d.ts} +1 -1
  51. package/dist/sdd/index.d.ts +8 -8
  52. package/dist/sdd/index.js +1 -1
  53. package/dist/sdd/index.js.map +1 -1
  54. package/dist/{secret-vault-Cgduf5xL.d.ts → secret-vault-BLsVmTIK.d.ts} +1 -1
  55. package/dist/security/index.d.ts +5 -5
  56. package/dist/security/index.js.map +1 -1
  57. package/dist/{selector-47LBnBVk.d.ts → selector-CXl2_y9W.d.ts} +1 -1
  58. package/dist/{session-event-bridge-Cw7oqmW2.d.ts → session-event-bridge-Ccud20CC.d.ts} +1 -1
  59. package/dist/{session-reader-DD4v2Obw.d.ts → session-reader-ZeXQmsmE.d.ts} +1 -1
  60. package/dist/skills/index.js.map +1 -1
  61. package/dist/storage/index.d.ts +13 -11
  62. package/dist/storage/index.js +210 -64
  63. package/dist/storage/index.js.map +1 -1
  64. package/dist/tools/index.d.ts +2 -2
  65. package/dist/tools/index.js.map +1 -1
  66. package/dist/types/index.d.ts +21 -21
  67. package/dist/types/index.js +110 -19
  68. package/dist/types/index.js.map +1 -1
  69. package/dist/utils/index.d.ts +2 -2
  70. package/dist/utils/index.js +58 -24
  71. package/dist/utils/index.js.map +1 -1
  72. package/package.json +1 -1
  73. package/skills/chimera/SKILL.md +1 -1
  74. package/skills/typescript-strict/SKILL.md +3 -3
  75. package/skills/typescript-strict/SKILL.save.md +1 -1
package/dist/index.js CHANGED
@@ -59,8 +59,8 @@ async function atomicWrite(targetPath, content, opts = {}) {
59
59
  }
60
60
  let mode;
61
61
  try {
62
- const stat14 = await fsp3.stat(targetPath);
63
- mode = stat14.mode & 511;
62
+ const stat15 = await fsp3.stat(targetPath);
63
+ mode = stat15.mode & 511;
64
64
  } catch {
65
65
  mode = opts.mode;
66
66
  }
@@ -100,8 +100,8 @@ async function withFileLock(targetPath, fn, opts = {}) {
100
100
  }
101
101
  if (code !== "EEXIST") throw err;
102
102
  try {
103
- const stat14 = await fsp3.stat(lockPath);
104
- if (Date.now() - stat14.mtimeMs > staleMs) {
103
+ const stat15 = await fsp3.stat(lockPath);
104
+ if (Date.now() - stat15.mtimeMs > staleMs) {
105
105
  await fsp3.unlink(lockPath);
106
106
  continue;
107
107
  }
@@ -183,7 +183,7 @@ function getSessionRegistry(globalRoot) {
183
183
  function hasSessionRegistry() {
184
184
  return _instance !== null;
185
185
  }
186
- var REGISTRY_FILE, HEARTBEAT_INTERVAL_MS, STALE_TIMEOUT_MS, CLOSING_GRACE_MS, STALE_LOCK_MS, SessionRegistry, _instance;
186
+ var REGISTRY_FILE, HEARTBEAT_INTERVAL_MS, STALE_TIMEOUT_MS, CLOSING_GRACE_MS, STALE_LOCK_MS, STALE_TMP_MS, MAX_STALE_TMP_FILES, SessionRegistry, _instance;
187
187
  var init_session_registry = __esm({
188
188
  "src/session-registry.ts"() {
189
189
  REGISTRY_FILE = "session-registry.json";
@@ -191,6 +191,8 @@ var init_session_registry = __esm({
191
191
  STALE_TIMEOUT_MS = 3e4;
192
192
  CLOSING_GRACE_MS = 15e3;
193
193
  STALE_LOCK_MS = 1e4;
194
+ STALE_TMP_MS = 6e4;
195
+ MAX_STALE_TMP_FILES = 20;
194
196
  SessionRegistry = class {
195
197
  filePath;
196
198
  heartbeatTimer = null;
@@ -428,11 +430,11 @@ var init_session_registry = __esm({
428
430
  */
429
431
  async breakStaleLock(lockPath) {
430
432
  try {
431
- const [stat14, content] = await Promise.all([
433
+ const [stat15, content] = await Promise.all([
432
434
  fsp3.stat(lockPath),
433
435
  fsp3.readFile(lockPath, "utf8").catch(() => "")
434
436
  ]);
435
- const ageMs = Date.now() - stat14.mtimeMs;
437
+ const ageMs = Date.now() - stat15.mtimeMs;
436
438
  const ownerPid = Number.parseInt(content.trim(), 10);
437
439
  const ownerDead = Number.isInteger(ownerPid) && ownerPid > 0 && ownerPid !== process.pid && !pidAlive(ownerPid);
438
440
  if (ownerDead || ageMs > STALE_LOCK_MS) {
@@ -445,15 +447,48 @@ var init_session_registry = __esm({
445
447
  }
446
448
  }
447
449
  async writeAtomicLocked(registry) {
448
- const tmp = `${this.filePath}.${randomUUID().slice(0, 8)}.tmp`;
449
- await fsp3.writeFile(tmp, JSON.stringify(registry, null, 2), "utf8");
450
- await fsp3.rename(tmp, this.filePath);
450
+ await this.pruneStaleTempFiles();
451
+ await this.writeAtomicFile(registry);
451
452
  }
452
453
  /** Legacy write without lock — used by heartbeat for performance. */
453
454
  async writeAtomic(registry) {
454
- const tmp = `${this.filePath}.${randomUUID().slice(0, 8)}.tmp`;
455
- await fsp3.writeFile(tmp, JSON.stringify(registry, null, 2), "utf8");
456
- await fsp3.rename(tmp, this.filePath);
455
+ await this.pruneStaleTempFiles();
456
+ await this.writeAtomicFile(registry);
457
+ }
458
+ async writeAtomicFile(registry) {
459
+ const tmp = path3.join(
460
+ path3.dirname(this.filePath),
461
+ `.${path3.basename(this.filePath)}.${randomUUID().slice(0, 8)}.tmp`
462
+ );
463
+ try {
464
+ await fsp3.writeFile(tmp, JSON.stringify(registry, null, 2), "utf8");
465
+ await fsp3.rename(tmp, this.filePath);
466
+ } catch (err) {
467
+ await fsp3.unlink(tmp).catch(() => void 0);
468
+ throw err;
469
+ }
470
+ }
471
+ async pruneStaleTempFiles() {
472
+ try {
473
+ const dir = path3.dirname(this.filePath);
474
+ const base = path3.basename(this.filePath);
475
+ const now = Date.now();
476
+ const stale = [];
477
+ for (const name of await fsp3.readdir(dir)) {
478
+ const isTemp = (name.startsWith(`${base}.`) || name.startsWith(`.${base}.`)) && name.endsWith(".tmp");
479
+ if (!isTemp) continue;
480
+ const stat15 = await fsp3.stat(path3.join(dir, name)).catch(() => null);
481
+ if (!stat15) continue;
482
+ if (now - stat15.mtimeMs > STALE_TMP_MS) stale.push({ name, mtimeMs: stat15.mtimeMs });
483
+ }
484
+ stale.sort((a, b) => b.mtimeMs - a.mtimeMs);
485
+ await Promise.all(
486
+ stale.slice(MAX_STALE_TMP_FILES).map(async ({ name }) => {
487
+ await fsp3.unlink(path3.join(dir, name)).catch(() => void 0);
488
+ })
489
+ );
490
+ } catch {
491
+ }
457
492
  }
458
493
  };
459
494
  _instance = null;
@@ -601,7 +636,7 @@ function onResize(cb, stream = process.stdout) {
601
636
  };
602
637
  }
603
638
  function setRawMode(input, mode) {
604
- if (!input || input.isTTY !== true) return false;
639
+ if (input?.isTTY !== true) return false;
605
640
  if (typeof input.setRawMode !== "function") return false;
606
641
  input.setRawMode(mode);
607
642
  return true;
@@ -661,11 +696,7 @@ var color = {
661
696
  bgGreen: wrap("42", "49")
662
697
  };
663
698
  function stripAnsi(s) {
664
- return s.replace(
665
- // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape regex
666
- /\x1b\[[0-9;]*[A-Za-z]/g,
667
- ""
668
- );
699
+ return s.replace(/\x1b\[[0-9;]*[A-Za-z]/g, "");
669
700
  }
670
701
 
671
702
  // src/utils/config-json.ts
@@ -1410,8 +1441,8 @@ async function expandGlob(pattern) {
1410
1441
  for (const e of entries) {
1411
1442
  const full = `${dir}${SEP}${e}`;
1412
1443
  try {
1413
- const stat14 = await fsp3.stat(full);
1414
- if (stat14.isDirectory()) await walk3(full, rest);
1444
+ const stat15 = await fsp3.stat(full);
1445
+ if (stat15.isDirectory()) await walk3(full, rest);
1415
1446
  } catch {
1416
1447
  }
1417
1448
  }
@@ -1428,8 +1459,8 @@ async function expandGlob(pattern) {
1428
1459
  if (entries.includes(seg)) {
1429
1460
  const full = `${dir}${SEP}${seg}`;
1430
1461
  try {
1431
- const stat14 = await fsp3.stat(full);
1432
- if (stat14.isDirectory()) await walk3(full, rest);
1462
+ const stat15 = await fsp3.stat(full);
1463
+ if (stat15.isDirectory()) await walk3(full, rest);
1433
1464
  } catch {
1434
1465
  }
1435
1466
  }
@@ -1565,7 +1596,7 @@ function expandIPv6(addr) {
1565
1596
  };
1566
1597
  if (parts.length === 1) {
1567
1598
  const groups = parseGroups(parts[0] ?? "");
1568
- if (!groups || groups.length !== 8) return null;
1599
+ if (groups?.length !== 8) return null;
1569
1600
  return groups;
1570
1601
  }
1571
1602
  const head = parseGroups(parts[0] ?? "");
@@ -1934,7 +1965,7 @@ function hasToolResult(msg) {
1934
1965
  }
1935
1966
  function toolUseIds(msg) {
1936
1967
  const ids = /* @__PURE__ */ new Set();
1937
- if (!msg || msg.role !== "assistant") return ids;
1968
+ if (msg?.role !== "assistant") return ids;
1938
1969
  for (const block of contentBlocks(msg)) {
1939
1970
  if (block.type === "tool_use") ids.add(block.id);
1940
1971
  }
@@ -1942,7 +1973,7 @@ function toolUseIds(msg) {
1942
1973
  }
1943
1974
  function toolResultIds(msg) {
1944
1975
  const ids = /* @__PURE__ */ new Set();
1945
- if (!msg || msg.role !== "user") return ids;
1976
+ if (msg?.role !== "user") return ids;
1946
1977
  for (const block of contentBlocks(msg)) {
1947
1978
  if (block.type === "tool_result") ids.add(block.tool_use_id);
1948
1979
  }
@@ -2388,8 +2419,19 @@ function calState(key) {
2388
2419
  return state;
2389
2420
  }
2390
2421
  var MIN_SAMPLES_FOR_CALIBRATION = 3;
2422
+ var MODEL_FAMILY_RATIO = {
2423
+ // Anthropic: ~3.8-4.0 chars/token depending on model
2424
+ claude: 3.8,
2425
+ // OpenAI: ~4.0 chars/token
2426
+ "gpt-4": 4,
2427
+ "gpt-3.5": 4,
2428
+ // Google: ~3.5 chars/token
2429
+ gemini: 3.5,
2430
+ // DeepSeek: ~3.5 chars/token
2431
+ deepseek: 3.5
2432
+ };
2391
2433
  var ESTIMATE_CACHE = /* @__PURE__ */ new Map();
2392
- var ESTIMATE_CACHE_MAX_SIZE = 1e4;
2434
+ var ESTIMATE_CACHE_MAX_SIZE = 5e4;
2393
2435
  function getCachedEstimate(key, compute) {
2394
2436
  const existing = ESTIMATE_CACHE.get(key);
2395
2437
  if (existing !== void 0) return existing;
@@ -2531,8 +2573,24 @@ function estimateRequestTokensCalibrated(messages, systemPrompt, tools, calibrat
2531
2573
  total: Math.round(result.total * safeRatio)
2532
2574
  };
2533
2575
  }
2576
+ const fallbackRatio = getModelFamilyRatio(calibrationKey);
2577
+ if (fallbackRatio !== null) {
2578
+ return {
2579
+ messages: Math.round(result.messages * fallbackRatio),
2580
+ systemPrompt: Math.round(result.systemPrompt * fallbackRatio),
2581
+ tools: Math.round(result.tools * fallbackRatio),
2582
+ total: Math.round(result.total * fallbackRatio)
2583
+ };
2584
+ }
2534
2585
  return result;
2535
2586
  }
2587
+ function getModelFamilyRatio(calibrationKey) {
2588
+ const lower = calibrationKey.toLowerCase();
2589
+ for (const [family, ratio] of Object.entries(MODEL_FAMILY_RATIO)) {
2590
+ if (lower.includes(family)) return ratio / 3.5;
2591
+ }
2592
+ return null;
2593
+ }
2536
2594
  function resetCalibration(calibrationKey) {
2537
2595
  if (calibrationKey === void 0) {
2538
2596
  _cals.clear();
@@ -2550,6 +2608,7 @@ var GREP_MATCHES_PER_FILE = 3;
2550
2608
  var DIFF_INLINE_LINE_LIMIT = 260;
2551
2609
  var DIFF_HUNK_LIMIT = 8;
2552
2610
  var DIFF_HUNK_CONTEXT = 14;
2611
+ var GREP_LINE_RE = /^(.+?):(\d+):(.*)$/;
2553
2612
  function createToolOutputSerializer(opts = {}) {
2554
2613
  const capBytes = opts.perIterationOutputCapBytes ?? 1e5;
2555
2614
  function serialize(value, context = {}) {
@@ -2935,7 +2994,7 @@ ${renderStringList(passthrough, "", 50)}`);
2935
2994
  return sections.join("\n");
2936
2995
  }
2937
2996
  function parseGrepContentLine(line) {
2938
- const match = /^(.+?):(\d+):(.*)$/.exec(line);
2997
+ const match = GREP_LINE_RE.exec(line);
2939
2998
  if (!match?.[1] || !match[2]) return void 0;
2940
2999
  return { file: match[1], line: match[2], text: match[3] ?? "" };
2941
3000
  }
@@ -2953,22 +3012,20 @@ function compactDiff(diff) {
2953
3012
  const hunks = lines.filter((line) => line.startsWith("@@")).length;
2954
3013
  const added = lines.filter((line) => line.startsWith("+") && !line.startsWith("+++")).length;
2955
3014
  const removed = lines.filter((line) => line.startsWith("-") && !line.startsWith("---")).length;
2956
- const selected = /* @__PURE__ */ new Set();
3015
+ const intervals = [];
2957
3016
  let hunkCount = 0;
2958
3017
  for (let i = 0; i < lines.length; i++) {
2959
3018
  const line = lines[i] ?? "";
2960
3019
  if (line.startsWith("diff --git") || line.startsWith("--- ") || line.startsWith("+++ ")) {
2961
- selected.add(i);
3020
+ intervals.push([i, i]);
2962
3021
  continue;
2963
3022
  }
2964
3023
  if (!line.startsWith("@@")) continue;
2965
3024
  if (hunkCount >= DIFF_HUNK_LIMIT) continue;
2966
3025
  hunkCount++;
2967
- for (let j = i; j <= Math.min(lines.length - 1, i + DIFF_HUNK_CONTEXT); j++) {
2968
- selected.add(j);
2969
- }
3026
+ intervals.push([i, Math.min(lines.length - 1, i + DIFF_HUNK_CONTEXT)]);
2970
3027
  }
2971
- if (selected.size === 0) {
3028
+ if (intervals.length === 0) {
2972
3029
  return joinSections([
2973
3030
  renderHeader("diff_summary", {
2974
3031
  files: fileCount,
@@ -2981,17 +3038,29 @@ function compactDiff(diff) {
2981
3038
  `[serializer omitted ${Math.max(0, lines.length - DIFF_INLINE_LINE_LIMIT)} diff line(s)]`
2982
3039
  ]);
2983
3040
  }
3041
+ const merged = [intervals[0]];
3042
+ for (let i = 1; i < intervals.length; i++) {
3043
+ const last = merged[merged.length - 1];
3044
+ const current = intervals[i];
3045
+ if (current[0] <= last[1] + 1) {
3046
+ last[1] = Math.max(last[1], current[1]);
3047
+ } else {
3048
+ merged.push(current);
3049
+ }
3050
+ }
2984
3051
  const excerpt = [];
2985
- let previous = -1;
2986
- for (const index of [...selected].sort((a, b) => a - b)) {
2987
- if (index > previous + 1) {
2988
- const omitted = previous === -1 ? index : index - previous - 1;
3052
+ let prevLine = -1;
3053
+ for (const [start, end] of merged) {
3054
+ if (start > prevLine + 1) {
3055
+ const omitted = prevLine === -1 ? start : start - prevLine - 1;
2989
3056
  excerpt.push(`[serializer omitted ${omitted} diff line(s)]`);
2990
3057
  }
2991
- excerpt.push(lines[index] ?? "");
2992
- previous = index;
3058
+ for (let j = start; j <= end; j++) {
3059
+ excerpt.push(lines[j] ?? "");
3060
+ }
3061
+ prevLine = end;
2993
3062
  }
2994
- const trailing = lines.length - previous - 1;
3063
+ const trailing = lines.length - prevLine - 1;
2995
3064
  if (trailing > 0) excerpt.push(`[serializer omitted ${trailing} trailing diff line(s)]`);
2996
3065
  return joinSections([
2997
3066
  renderHeader("diff_summary", {
@@ -3185,6 +3254,7 @@ function truncateForEvent(content, max = 400) {
3185
3254
  if (!content) return "";
3186
3255
  return content.length <= max ? content : `${content.slice(0, max - 1)}\u2026`;
3187
3256
  }
3257
+ var READ_LINE_PREFIX_RE = /^\s*\d+→/gm;
3188
3258
  function sizeSignals(toolName, content) {
3189
3259
  if (!content || content.length === 0) {
3190
3260
  return { outputBytes: 0, outputTokens: 0, outputLines: void 0 };
@@ -3193,9 +3263,9 @@ function sizeSignals(toolName, content) {
3193
3263
  const outputTokens = Math.max(1, Math.round(outputBytes / 3.5));
3194
3264
  let outputLines;
3195
3265
  if (toolName === "read") {
3196
- const lineRe = /^\s*\d+→/gm;
3266
+ READ_LINE_PREFIX_RE.lastIndex = 0;
3197
3267
  let count = 0;
3198
- while (lineRe.exec(content) !== null) count++;
3268
+ while (READ_LINE_PREFIX_RE.exec(content) !== null) count++;
3199
3269
  if (count > 0) outputLines = count;
3200
3270
  } else if (toolName === "bash" || toolName === "shell" || toolName === "grep" || toolName === "logs") {
3201
3271
  let nl = 0;
@@ -4200,6 +4270,16 @@ function asText(content) {
4200
4270
  return content.filter((b) => b.type === "text").map((b) => b.text).join("");
4201
4271
  }
4202
4272
 
4273
+ // src/types/tool.ts
4274
+ var ToolErrorCategory = /* @__PURE__ */ ((ToolErrorCategory2) => {
4275
+ ToolErrorCategory2["TRANSIENT"] = "transient";
4276
+ ToolErrorCategory2["NOT_FOUND"] = "not_found";
4277
+ ToolErrorCategory2["PERMISSION"] = "permission";
4278
+ ToolErrorCategory2["VALIDATION"] = "validation";
4279
+ ToolErrorCategory2["FATAL"] = "fatal";
4280
+ return ToolErrorCategory2;
4281
+ })(ToolErrorCategory || {});
4282
+
4203
4283
  // src/types/provider.ts
4204
4284
  var ProviderError = class extends WrongStackError {
4205
4285
  status;
@@ -4315,6 +4395,17 @@ function normalizeTokenSavingTier(val) {
4315
4395
  ]);
4316
4396
  return validTiers.has(val) ? val : "off";
4317
4397
  }
4398
+ var DEFAULT_TUI_THINKING_WORD = "thinking";
4399
+ var MAX_TUI_THINKING_WORD_LENGTH = 16;
4400
+ function normalizeTuiThinkingWord(value) {
4401
+ if (typeof value !== "string") return DEFAULT_TUI_THINKING_WORD;
4402
+ const word = value.trim();
4403
+ if (word.length === 0 || word.length > MAX_TUI_THINKING_WORD_LENGTH) {
4404
+ return DEFAULT_TUI_THINKING_WORD;
4405
+ }
4406
+ if (!/^[\p{L}\p{N}_-]+$/u.test(word)) return DEFAULT_TUI_THINKING_WORD;
4407
+ return word;
4408
+ }
4318
4409
 
4319
4410
  // src/types/default-config.ts
4320
4411
  var DEFAULT_TOOLS_CONFIG = Object.freeze({
@@ -4375,8 +4466,8 @@ var VERSIONED_KEY_FILE_SIZE = KEY_FILE_MAGIC.length + 1 + KEY_BYTES;
4375
4466
  function checkKeyFilePermissions(keyFile) {
4376
4467
  if (process.platform === "win32") return;
4377
4468
  try {
4378
- const stat14 = fs3.statSync(keyFile);
4379
- const actualMode = stat14.mode & 511;
4469
+ const stat15 = fs3.statSync(keyFile);
4470
+ const actualMode = stat15.mode & 511;
4380
4471
  if (actualMode !== KEY_FILE_MODE) {
4381
4472
  console.warn(JSON.stringify({
4382
4473
  level: "warn",
@@ -7169,6 +7260,7 @@ ${post.additionalContext}`;
7169
7260
  } catch (err) {
7170
7261
  const msg = toErrorMessage(err);
7171
7262
  const scrubbed = this.opts.secretScrubber.scrub(msg);
7263
+ const { category, retryable, detail } = classifyToolError(err);
7172
7264
  this.opts.renderer?.writeToolResult(tool.name, scrubbed, true);
7173
7265
  const result = {
7174
7266
  type: "tool_result",
@@ -7179,6 +7271,9 @@ ${post.additionalContext}`;
7179
7271
  budget = this.budgetForString(result.content, budget);
7180
7272
  if (err instanceof Error) span?.recordError(err);
7181
7273
  span?.setAttribute("tool.is_error", true);
7274
+ span?.setAttribute("tool.error_category", category);
7275
+ span?.setAttribute("tool.error_retryable", retryable);
7276
+ if (detail) span?.setAttribute("tool.error_detail", detail);
7182
7277
  return { result, tool, durationMs: Date.now() - start };
7183
7278
  } finally {
7184
7279
  span?.end();
@@ -7190,6 +7285,9 @@ ${post.additionalContext}`;
7190
7285
  } catch (err) {
7191
7286
  const msg = toErrorMessage(err);
7192
7287
  const scrubbed = this.opts.secretScrubber.scrub(msg);
7288
+ const { category, retryable, detail } = classifyToolError(err);
7289
+ const tool = this.registry.get(use.name);
7290
+ this.opts.renderer?.writeToolResult(tool?.name ?? use.name, scrubbed, true);
7193
7291
  const result = {
7194
7292
  type: "tool_result",
7195
7293
  tool_use_id: use.id,
@@ -7197,7 +7295,7 @@ ${post.additionalContext}`;
7197
7295
  is_error: true
7198
7296
  };
7199
7297
  budget = this.budgetForString(result.content, budget);
7200
- return { result, tool: this.registry.get(use.name), durationMs: 0 };
7298
+ return { result, tool, durationMs: 0 };
7201
7299
  }
7202
7300
  };
7203
7301
  if (strategy === "sequential") {
@@ -7429,6 +7527,58 @@ function extractMalformedRaw(input) {
7429
7527
  }
7430
7528
  }
7431
7529
  var TOOL_OUTPUT_ARTIFACT_THRESHOLD_BYTES = 64 * 1024;
7530
+ function classifyToolError(err) {
7531
+ if (err instanceof Error && err.name === "AbortError") {
7532
+ return { category: "fatal" /* FATAL */, retryable: false, detail: "aborted" };
7533
+ }
7534
+ if (err instanceof Error && "code" in err) {
7535
+ const code = err.code;
7536
+ switch (code) {
7537
+ case "ETIMEDOUT":
7538
+ case "ECONNRESET":
7539
+ case "ECONNREFUSED":
7540
+ case "ENETUNREACH":
7541
+ case "EHOSTUNREACH":
7542
+ return { category: "transient" /* TRANSIENT */, retryable: true, detail: code };
7543
+ case "ENOENT":
7544
+ case "ENOTDIR":
7545
+ return { category: "not_found" /* NOT_FOUND */, retryable: false, detail: code };
7546
+ case "EACCES":
7547
+ case "EPERM":
7548
+ return { category: "permission" /* PERMISSION */, retryable: false, detail: code };
7549
+ case "EBUSY":
7550
+ case "EMFILE":
7551
+ case "ENFILE":
7552
+ return { category: "transient" /* TRANSIENT */, retryable: true, detail: code };
7553
+ }
7554
+ }
7555
+ if (err instanceof Error && "response" in err) {
7556
+ const response = err.response;
7557
+ const status = response?.status;
7558
+ if (status !== void 0) {
7559
+ if (status === 429 || status === 503 || status === 502 || status === 504) {
7560
+ return { category: "transient" /* TRANSIENT */, retryable: true, detail: `HTTP ${status}` };
7561
+ }
7562
+ if (status === 404 || status === 410) {
7563
+ return { category: "not_found" /* NOT_FOUND */, retryable: false, detail: `HTTP ${status}` };
7564
+ }
7565
+ if (status === 401 || status === 403) {
7566
+ return { category: "permission" /* PERMISSION */, retryable: false, detail: `HTTP ${status}` };
7567
+ }
7568
+ if (status === 400) {
7569
+ return { category: "validation" /* VALIDATION */, retryable: false, detail: `HTTP ${status}` };
7570
+ }
7571
+ }
7572
+ }
7573
+ if (err instanceof Error && err.message.includes("validation")) {
7574
+ return { category: "validation" /* VALIDATION */, retryable: false, detail: "validation" };
7575
+ }
7576
+ return {
7577
+ category: "fatal" /* FATAL */,
7578
+ retryable: false,
7579
+ detail: err instanceof Error ? err.message.slice(0, 100) : String(err).slice(0, 100)
7580
+ };
7581
+ }
7432
7582
  async function maybePersistLargeToolOutput(toolName, content, budget) {
7433
7583
  const bytes = Buffer.byteLength(content, "utf8");
7434
7584
  if (bytes <= Math.min(TOOL_OUTPUT_ARTIFACT_THRESHOLD_BYTES, Math.max(0, budget))) {
@@ -8041,6 +8191,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8041
8191
  * processes. When the limit is reached, the oldest entry is evicted.
8042
8192
  */
8043
8193
  _loadCache = /* @__PURE__ */ new Map();
8194
+ _indexCache = null;
8044
8195
  static LOAD_CACHE_MAX_ENTRIES = 50;
8045
8196
  constructor(opts) {
8046
8197
  this.dir = opts.dir;
@@ -8202,15 +8353,10 @@ var DefaultSessionStore = class _DefaultSessionStore {
8202
8353
  let errorMsg;
8203
8354
  let cacheHit = false;
8204
8355
  try {
8205
- let stat14;
8206
- try {
8207
- const s = await fsp3.stat(file);
8208
- stat14 = { mtimeMs: s.mtimeMs, size: s.size };
8209
- } catch (err) {
8210
- throw err;
8211
- }
8356
+ const s = await fsp3.stat(file);
8357
+ const stat15 = { mtimeMs: s.mtimeMs, size: s.size };
8212
8358
  const cached = this._loadCache.get(id);
8213
- if (cached && cached.mtimeMs === stat14.mtimeMs && cached.size === stat14.size) {
8359
+ if (cached && cached.mtimeMs === stat15.mtimeMs && cached.size === stat15.size) {
8214
8360
  cacheHit = true;
8215
8361
  this._loadCache.delete(id);
8216
8362
  this._loadCache.set(id, cached);
@@ -8238,7 +8384,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8238
8384
  this._loadCache.delete(oldest);
8239
8385
  }
8240
8386
  }
8241
- this._loadCache.set(id, { mtimeMs: stat14.mtimeMs, size: stat14.size, data });
8387
+ this._loadCache.set(id, { mtimeMs: stat15.mtimeMs, size: stat15.size, data });
8242
8388
  return data;
8243
8389
  } catch (err) {
8244
8390
  outcome = "failure";
@@ -8299,6 +8445,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8299
8445
  await ensureDir(this.dir);
8300
8446
  const line = JSON.stringify(summary) + "\n";
8301
8447
  await fsp3.appendFile(this.indexFile, line, "utf8");
8448
+ this._indexCache = null;
8302
8449
  this.indexAppendCount++;
8303
8450
  if (this.indexAppendCount >= _DefaultSessionStore.COMPACT_EVERY) {
8304
8451
  await this.compactIndex();
@@ -8313,6 +8460,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8313
8460
  await ensureDir(this.dir);
8314
8461
  const line = JSON.stringify({ action: "delete", id }) + "\n";
8315
8462
  await fsp3.appendFile(this.indexFile, line, "utf8");
8463
+ this._indexCache = null;
8316
8464
  this.indexAppendCount++;
8317
8465
  } catch {
8318
8466
  }
@@ -8332,6 +8480,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8332
8480
  const lines = entries.map((s) => JSON.stringify(s)).join("\n") + "\n";
8333
8481
  await fsp3.writeFile(tmp, lines, "utf8");
8334
8482
  await fsp3.rename(tmp, this.indexFile);
8483
+ this._indexCache = null;
8335
8484
  } catch (err) {
8336
8485
  outcome = "failure";
8337
8486
  errorMsg = toErrorMessage(err);
@@ -8345,10 +8494,22 @@ var DefaultSessionStore = class _DefaultSessionStore {
8345
8494
  * Returns empty array when the index doesn't exist or is corrupt.
8346
8495
  */
8347
8496
  async readIndex() {
8497
+ let stat15;
8498
+ try {
8499
+ const s = await fsp3.stat(this.indexFile);
8500
+ stat15 = { mtimeMs: s.mtimeMs, size: s.size };
8501
+ } catch {
8502
+ this._indexCache = null;
8503
+ return [];
8504
+ }
8505
+ if (this._indexCache !== null && this._indexCache.mtimeMs === stat15.mtimeMs && this._indexCache.size === stat15.size) {
8506
+ return [...this._indexCache.summaries];
8507
+ }
8348
8508
  let raw;
8349
8509
  try {
8350
8510
  raw = await fsp3.readFile(this.indexFile, "utf8");
8351
8511
  } catch {
8512
+ this._indexCache = null;
8352
8513
  return [];
8353
8514
  }
8354
8515
  const deleted = /* @__PURE__ */ new Set();
@@ -8368,7 +8529,9 @@ var DefaultSessionStore = class _DefaultSessionStore {
8368
8529
  } catch {
8369
8530
  }
8370
8531
  }
8371
- return Array.from(seen.values());
8532
+ const summaries = Array.from(seen.values());
8533
+ this._indexCache = { ...stat15, summaries };
8534
+ return [...summaries];
8372
8535
  }
8373
8536
  /**
8374
8537
  * Rebuild the index from disk by scanning all sessions and writing a
@@ -8382,6 +8545,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8382
8545
  const lines = valid.map((s) => JSON.stringify(s)).join("\n") + "\n";
8383
8546
  await fsp3.writeFile(tmp, lines, "utf8");
8384
8547
  await fsp3.rename(tmp, this.indexFile);
8548
+ this._indexCache = null;
8385
8549
  return valid.length;
8386
8550
  }
8387
8551
  /** Recursively collect session IDs from date-shard subdirectories.
@@ -8422,8 +8586,8 @@ var DefaultSessionStore = class _DefaultSessionStore {
8422
8586
  return JSON.parse(raw);
8423
8587
  } catch {
8424
8588
  const full = this.sessionPath(id, ".jsonl");
8425
- const stat14 = await fsp3.stat(full);
8426
- const summary = await this.summarize(id, stat14.mtime.toISOString());
8589
+ const stat15 = await fsp3.stat(full);
8590
+ const summary = await this.summarize(id, stat15.mtime.toISOString());
8427
8591
  await atomicWrite(manifest, JSON.stringify(summary), { mode: 384 }).catch((err) => {
8428
8592
  const msg = toErrorMessage(err);
8429
8593
  this.emitError(id, manifest, "summary_fallback", msg, true);
@@ -8505,8 +8669,8 @@ var DefaultSessionStore = class _DefaultSessionStore {
8505
8669
  const pruneFile = async (dir, name, prefix) => {
8506
8670
  const jsonlPath = path3.join(dir, name);
8507
8671
  try {
8508
- const stat14 = await fsp3.stat(jsonlPath);
8509
- if (stat14.mtimeMs >= cutoff) return;
8672
+ const stat15 = await fsp3.stat(jsonlPath);
8673
+ if (stat15.mtimeMs >= cutoff) return;
8510
8674
  } catch {
8511
8675
  return;
8512
8676
  }
@@ -9081,6 +9245,12 @@ var FileSessionWriter = class _FileSessionWriter {
9081
9245
  files
9082
9246
  });
9083
9247
  }
9248
+ /**
9249
+ * Truncate the session file to the checkpoint with the given promptIndex,
9250
+ * removing all events that follow it. Uses a single-pass byte-offset scan
9251
+ * so post-checkpoint content is never read or parsed — O(1) memory instead
9252
+ * of O(N) JSON.parse calls over the full file.
9253
+ */
9084
9254
  async truncateToCheckpoint(targetPromptIndex) {
9085
9255
  if (!this.filePath) return 0;
9086
9256
  if (this.flushTimer) {
@@ -9089,51 +9259,118 @@ var FileSessionWriter = class _FileSessionWriter {
9089
9259
  }
9090
9260
  await this.flushBuffer();
9091
9261
  await this.writeChain;
9092
- const raw = await fsp3.readFile(this.filePath, "utf8");
9093
- const lines = raw.split("\n");
9094
- const kept = [];
9262
+ const CHUNK_SIZE = 65536;
9263
+ let fd;
9264
+ let fileOffset = 0;
9265
+ let lineStartOffset = 0;
9266
+ let checkpointByteOffset = -1;
9095
9267
  let removedCount = 0;
9096
- let targetCheckpointLine = -1;
9097
- let afterTarget = false;
9098
- for (let i = 0; i < lines.length; i++) {
9099
- const line = expectDefined(lines[i]);
9100
- if (!line.trim()) continue;
9101
- let event;
9102
- try {
9103
- event = JSON.parse(line);
9104
- } catch {
9105
- kept.push(line);
9106
- continue;
9107
- }
9108
- if (event.type === "checkpoint") {
9109
- if (event.promptIndex === targetPromptIndex) {
9110
- targetCheckpointLine = kept.length;
9111
- afterTarget = true;
9112
- } else if (event.promptIndex > targetPromptIndex) {
9113
- afterTarget = true;
9114
- }
9115
- }
9116
- if (event.promptIndex !== void 0 && event.promptIndex > targetPromptIndex) {
9117
- removedCount++;
9118
- } else if (event.promptIndex === void 0) {
9119
- if (!afterTarget || targetCheckpointLine === -1) {
9120
- kept.push(line);
9121
- } else {
9122
- removedCount++;
9268
+ let targetCheckpointSeen = false;
9269
+ try {
9270
+ fd = await fsp3.open(this.filePath, "r", 384);
9271
+ while (true) {
9272
+ const buf = Buffer.alloc(CHUNK_SIZE);
9273
+ const { bytesRead } = await fd.read(buf, 0, CHUNK_SIZE, fileOffset);
9274
+ if (bytesRead === 0) break;
9275
+ let chunkPos = 0;
9276
+ while (chunkPos < bytesRead) {
9277
+ const idx = buf.indexOf("\n", chunkPos);
9278
+ if (idx === -1) {
9279
+ lineStartOffset = fileOffset + chunkPos;
9280
+ break;
9281
+ }
9282
+ if (checkpointByteOffset !== -1) {
9283
+ removedCount++;
9284
+ } else {
9285
+ const lineBytes = buf.subarray(chunkPos, idx);
9286
+ const line = new TextDecoder("utf-8", { fatal: false }).decode(lineBytes);
9287
+ if (line.trim()) {
9288
+ try {
9289
+ const event = JSON.parse(line);
9290
+ if (event.type === "checkpoint") {
9291
+ if (event.promptIndex === targetPromptIndex) {
9292
+ checkpointByteOffset = lineStartOffset;
9293
+ targetCheckpointSeen = true;
9294
+ } else if (event.promptIndex !== void 0 && event.promptIndex > targetPromptIndex) {
9295
+ checkpointByteOffset = lineStartOffset;
9296
+ }
9297
+ } else if (targetCheckpointSeen && event.promptIndex !== void 0 && event.promptIndex > targetPromptIndex) {
9298
+ removedCount++;
9299
+ } else if (targetCheckpointSeen && event.promptIndex === void 0) {
9300
+ removedCount++;
9301
+ } else if (!targetCheckpointSeen && event.promptIndex === void 0) {
9302
+ removedCount++;
9303
+ } else if (!targetCheckpointSeen && event.promptIndex !== void 0 && event.promptIndex > targetPromptIndex) {
9304
+ removedCount++;
9305
+ }
9306
+ } catch {
9307
+ }
9308
+ }
9309
+ }
9310
+ chunkPos = idx + 1;
9311
+ lineStartOffset = fileOffset + chunkPos;
9312
+ }
9313
+ fileOffset += bytesRead;
9314
+ if (chunkPos >= bytesRead) {
9315
+ lineStartOffset = fileOffset;
9123
9316
  }
9124
- } else {
9125
- kept.push(line);
9126
9317
  }
9318
+ } finally {
9319
+ await fd?.close();
9127
9320
  }
9128
- const truncated = kept.join("\n");
9321
+ if (checkpointByteOffset === -1) return 0;
9322
+ await this.writeChain;
9323
+ await this.handle.close();
9129
9324
  const tmpPath = `${this.filePath}.rewind.tmp`;
9130
- await fsp3.writeFile(tmpPath, truncated + "\n", "utf8");
9325
+ const src = await fsp3.open(this.filePath, "r", 384);
9131
9326
  try {
9132
- await this.handle.close();
9327
+ const statResult = await src.stat();
9328
+ const totalSize = statResult.size;
9329
+ const prefixBytes = checkpointByteOffset;
9330
+ let newlineAfterCheckpoint = prefixBytes;
9331
+ if (prefixBytes < totalSize) {
9332
+ const probeBuf = Buffer.alloc(Math.min(CHUNK_SIZE, totalSize - prefixBytes));
9333
+ const { bytesRead: probeRead } = await src.read(probeBuf, 0, probeBuf.length, prefixBytes);
9334
+ if (probeRead > 0) {
9335
+ const nl = probeBuf.indexOf("\n");
9336
+ newlineAfterCheckpoint = nl !== -1 ? prefixBytes + nl + 1 : totalSize;
9337
+ }
9338
+ } else {
9339
+ newlineAfterCheckpoint = totalSize;
9340
+ }
9341
+ const writeFd = await fsp3.open(tmpPath, "w", 384);
9342
+ try {
9343
+ let copied = 0;
9344
+ let readOffset = 0;
9345
+ while (readOffset < newlineAfterCheckpoint) {
9346
+ const toCopy = Math.min(CHUNK_SIZE, newlineAfterCheckpoint - readOffset);
9347
+ const copyBuf = Buffer.alloc(toCopy);
9348
+ const { bytesRead: r } = await src.read(copyBuf, 0, toCopy, readOffset);
9349
+ if (r === 0) break;
9350
+ await writeFd.write(copyBuf, 0, r);
9351
+ readOffset += r;
9352
+ copied += r;
9353
+ }
9354
+ const raw = await fsp3.readFile(this.filePath);
9355
+ const tail = raw.subarray(newlineAfterCheckpoint).toString("utf8");
9356
+ for (const line of tail.split("\n")) {
9357
+ if (!line.trim()) continue;
9358
+ try {
9359
+ JSON.parse(line);
9360
+ } catch {
9361
+ await writeFd.write(`${line}
9362
+ `, void 0, "utf8");
9363
+ }
9364
+ }
9365
+ } finally {
9366
+ await writeFd.close();
9367
+ }
9368
+ await src.close();
9133
9369
  await fsp3.rename(tmpPath, this.filePath);
9134
9370
  this.handle = await fsp3.open(this.filePath, "a", 384);
9135
9371
  } catch (err) {
9136
9372
  await fsp3.unlink(tmpPath).catch(() => void 0);
9373
+ this.handle = await fsp3.open(this.filePath, "a", 384).catch(() => this.handle);
9137
9374
  throw err;
9138
9375
  }
9139
9376
  await this.append({
@@ -9521,6 +9758,7 @@ function mergeAdjacentText(blocks) {
9521
9758
  init_atomic_write();
9522
9759
  var TYPE_PRIORITY_RE = /^\[(\w+)\|(\w+)\]\s+/;
9523
9760
  var TAG_RE = /#([\w-]+)/g;
9761
+ var MAX_MEMORY_CONSOLIDATE_BACKUPS = 5;
9524
9762
  function formatMetadata(entry) {
9525
9763
  const parts = [];
9526
9764
  if (entry.type && entry.priority) {
@@ -9713,6 +9951,7 @@ ${line}`;
9713
9951
  const backup = `${file}.bak.${Date.now()}`;
9714
9952
  try {
9715
9953
  await fsp3.copyFile(file, backup);
9954
+ await pruneConsolidateBackups(file);
9716
9955
  } catch {
9717
9956
  }
9718
9957
  try {
@@ -9723,6 +9962,20 @@ ${line}`;
9723
9962
  return removed;
9724
9963
  }
9725
9964
  };
9965
+ async function pruneConsolidateBackups(file) {
9966
+ const dir = path3.dirname(file);
9967
+ const base = path3.basename(file);
9968
+ const prefix = `${base}.bak.`;
9969
+ const backups = (await fsp3.readdir(dir)).filter((name) => name.startsWith(prefix)).sort().reverse();
9970
+ await Promise.all(
9971
+ backups.slice(MAX_MEMORY_CONSOLIDATE_BACKUPS).map(async (name) => {
9972
+ try {
9973
+ await fsp3.unlink(path3.join(dir, name));
9974
+ } catch {
9975
+ }
9976
+ })
9977
+ );
9978
+ }
9726
9979
  function parseEntries(raw, scope = "project-memory") {
9727
9980
  const entries = [];
9728
9981
  for (const line of raw.split("\n")) {
@@ -10339,7 +10592,9 @@ var BEHAVIOR_DEFAULTS = {
10339
10592
  plugins: true,
10340
10593
  memory: true,
10341
10594
  modelsRegistry: true,
10342
- skills: true
10595
+ skills: true,
10596
+ tokenSavingMode: "off",
10597
+ allowOutsideProjectRoot: true
10343
10598
  },
10344
10599
  mcpServers: {},
10345
10600
  indexing: {
@@ -10348,7 +10603,8 @@ var BEHAVIOR_DEFAULTS = {
10348
10603
  watchExternal: true,
10349
10604
  debounceMs: 400
10350
10605
  },
10351
- session: { ...DEFAULT_SESSION_LOGGING_CONFIG }
10606
+ session: { ...DEFAULT_SESSION_LOGGING_CONFIG },
10607
+ autonomy: { autoProceedDelayMs: DEFAULT_AUTONOMY_CONFIG.autoProceedDelayMs }
10352
10608
  };
10353
10609
  function envBool(v) {
10354
10610
  return !/^(0|false|no|off)$/i.test(v.trim());
@@ -11079,7 +11335,7 @@ function createSessionEventBridge(writer, level = "standard", options = {}) {
11079
11335
  if (!shouldSample(event)) return;
11080
11336
  try {
11081
11337
  await target.append(event);
11082
- } catch (err) {
11338
+ } catch (_err) {
11083
11339
  }
11084
11340
  },
11085
11341
  async appendBatch(events) {
@@ -14849,8 +15105,8 @@ ${recentJournal}` : "No prior iterations.",
14849
15105
  await saveGoal(this.goalPath, abandoned, this.opts.events);
14850
15106
  }
14851
15107
  try {
14852
- const { unlink: unlink16 } = await import('fs/promises');
14853
- await unlink16(this.goalPath);
15108
+ const { unlink: unlink17 } = await import('fs/promises');
15109
+ await unlink17(this.goalPath);
14854
15110
  } catch {
14855
15111
  }
14856
15112
  this.opts.onEternalStop?.();
@@ -15233,7 +15489,7 @@ var SubagentBudget = class _SubagentBudget {
15233
15489
  */
15234
15490
  _busRequestDecision(entry) {
15235
15491
  const bus = this._events;
15236
- if (!bus || !bus.hasListenerFor("budget.threshold_reached")) {
15492
+ if (!bus?.hasListenerFor("budget.threshold_reached")) {
15237
15493
  return Promise.resolve("stop");
15238
15494
  }
15239
15495
  return new Promise((resolve18) => {
@@ -20264,7 +20520,7 @@ var CollabSession = class extends EventEmitter {
20264
20520
  }
20265
20521
  for (const filePath of allFiles) {
20266
20522
  try {
20267
- const [content, stat14] = await Promise.all([
20523
+ const [content, stat15] = await Promise.all([
20268
20524
  fsp3.readFile(filePath, "utf8"),
20269
20525
  fsp3.stat(filePath)
20270
20526
  ]);
@@ -20274,8 +20530,8 @@ var CollabSession = class extends EventEmitter {
20274
20530
  path: filePath,
20275
20531
  content,
20276
20532
  language,
20277
- snapshotMtimeMs: stat14.mtimeMs,
20278
- snapshotSizeBytes: stat14.size
20533
+ snapshotMtimeMs: stat15.mtimeMs,
20534
+ snapshotSizeBytes: stat15.size
20279
20535
  });
20280
20536
  } catch {
20281
20537
  this.snapshot.files.push({ path: filePath, content: "", language: void 0 });
@@ -20688,9 +20944,9 @@ Emit each evaluation immediately. Do not wait until you have read all reports.`;
20688
20944
  for (const file of this.snapshot.files) {
20689
20945
  if (file.snapshotMtimeMs === void 0 && file.snapshotSizeBytes === void 0) continue;
20690
20946
  try {
20691
- const stat14 = await fsp3.stat(file.path);
20692
- const mtimeChanged = file.snapshotMtimeMs !== void 0 && stat14.mtimeMs > file.snapshotMtimeMs + 1;
20693
- const sizeChanged = file.snapshotSizeBytes !== void 0 && stat14.size !== file.snapshotSizeBytes;
20947
+ const stat15 = await fsp3.stat(file.path);
20948
+ const mtimeChanged = file.snapshotMtimeMs !== void 0 && stat15.mtimeMs > file.snapshotMtimeMs + 1;
20949
+ const sizeChanged = file.snapshotSizeBytes !== void 0 && stat15.size !== file.snapshotSizeBytes;
20694
20950
  if (mtimeChanged || sizeChanged) {
20695
20951
  warnings.push(`${file.path} changed after the collab snapshot was captured.`);
20696
20952
  }
@@ -23451,8 +23707,8 @@ async function loadProjectModes(modesDir) {
23451
23707
  for (const entry of entries) {
23452
23708
  if (!entry.endsWith(".md") && !entry.endsWith(".txt")) continue;
23453
23709
  const filePath = path3.join(modesDir, entry);
23454
- const stat14 = await fsp3.stat(filePath);
23455
- if (!stat14.isFile()) continue;
23710
+ const stat15 = await fsp3.stat(filePath);
23711
+ if (!stat15.isFile()) continue;
23456
23712
  const content = await fsp3.readFile(filePath, "utf8");
23457
23713
  const id = path3.basename(entry, path3.extname(entry));
23458
23714
  modes.push({
@@ -26582,9 +26838,9 @@ async function startMetricsServer(opts) {
26582
26838
  let server;
26583
26839
  if (useHttps && tls) {
26584
26840
  const { createServer } = await import('https');
26585
- const { readFileSync: readFileSync3 } = await import('fs');
26841
+ const { readFileSync: readFileSync4 } = await import('fs');
26586
26842
  server = createServer(
26587
- { cert: readFileSync3(tls.cert), key: readFileSync3(tls.key) },
26843
+ { cert: readFileSync4(tls.cert), key: readFileSync4(tls.key) },
26588
26844
  listener
26589
26845
  );
26590
26846
  } else {
@@ -27548,13 +27804,13 @@ var SkillInstaller = class {
27548
27804
  context: { reason: "path_traversal", skillName: skill.name }
27549
27805
  });
27550
27806
  }
27551
- const stat14 = await fsp3.stat(srcPath);
27552
- if (stat14.size > MAX_SKILL_FILE_SIZE) {
27807
+ const stat15 = await fsp3.stat(srcPath);
27808
+ if (stat15.size > MAX_SKILL_FILE_SIZE) {
27553
27809
  throw new FsError({
27554
- message: `Skill file "${file}" is too large (${(stat14.size / 1024).toFixed(1)}KB). Max: ${MAX_SKILL_FILE_SIZE / 1024}KB`,
27810
+ message: `Skill file "${file}" is too large (${(stat15.size / 1024).toFixed(1)}KB). Max: ${MAX_SKILL_FILE_SIZE / 1024}KB`,
27555
27811
  code: ERROR_CODES.FS_WRITE_FAILED,
27556
27812
  path: srcPath,
27557
- context: { skillName: skill.name, fileSize: stat14.size, maxSize: MAX_SKILL_FILE_SIZE }
27813
+ context: { skillName: skill.name, fileSize: stat15.size, maxSize: MAX_SKILL_FILE_SIZE }
27558
27814
  });
27559
27815
  }
27560
27816
  await fsp3.mkdir(path3.dirname(destPath), { recursive: true });
@@ -28104,7 +28360,7 @@ var SessionMemoryConsolidator = class {
28104
28360
  if (!result.finalText || result.finalText.trim().length < 20) return;
28105
28361
  if (result.iterations < this.minIterations) return;
28106
28362
  const provider = this.provider ?? ctx.provider;
28107
- if (!provider || !provider.complete) return;
28363
+ if (!provider?.complete) return;
28108
28364
  try {
28109
28365
  const existingEntries = await this.memoryStore.list("project-memory", this.maxExistingEntries);
28110
28366
  const prompt = buildConsolidationPrompt(
@@ -28147,7 +28403,7 @@ var SessionMemoryConsolidator = class {
28147
28403
  break;
28148
28404
  }
28149
28405
  case "edit": {
28150
- if (op.query && op.text && op.text.trim()) {
28406
+ if (op.query && op.text?.trim()) {
28151
28407
  await this.memoryStore.forget(op.query);
28152
28408
  await this.memoryStore.remember(op.text.trim(), void 0, {
28153
28409
  type: op.type,
@@ -28803,15 +29059,15 @@ var SessionRecovery = class {
28803
29059
  async detectStale(sessionId) {
28804
29060
  const fp = this.filePath(sessionId);
28805
29061
  const TAIL_SIZE = 8192;
28806
- let stat14;
29062
+ let stat15;
28807
29063
  try {
28808
- stat14 = await fsp3.stat(fp);
29064
+ stat15 = await fsp3.stat(fp);
28809
29065
  } catch (err) {
28810
29066
  if (err.code === "ENOENT") return null;
28811
29067
  return null;
28812
29068
  }
28813
- if (stat14.size === 0) return null;
28814
- const position = Math.max(0, stat14.size - TAIL_SIZE);
29069
+ if (stat15.size === 0) return null;
29070
+ const position = Math.max(0, stat15.size - TAIL_SIZE);
28815
29071
  const buf = Buffer.alloc(TAIL_SIZE);
28816
29072
  let fh;
28817
29073
  try {
@@ -30210,8 +30466,8 @@ var CloudSync = class {
30210
30466
  const localPath = this.categoryToPath(cat);
30211
30467
  if (!localPath) continue;
30212
30468
  try {
30213
- const stat14 = await fsp3.stat(localPath);
30214
- if (stat14.isDirectory()) {
30469
+ const stat15 = await fsp3.stat(localPath);
30470
+ if (stat15.isDirectory()) {
30215
30471
  const files = await this.walkDir(localPath, localPath);
30216
30472
  for (const file of files) {
30217
30473
  const content = await fsp3.readFile(file, "utf8");
@@ -30236,8 +30492,8 @@ var CloudSync = class {
30236
30492
  const localPath = this.categoryToPath(cat);
30237
30493
  if (!localPath) continue;
30238
30494
  try {
30239
- const stat14 = await fsp3.stat(localPath);
30240
- if (stat14.isDirectory()) {
30495
+ const stat15 = await fsp3.stat(localPath);
30496
+ if (stat15.isDirectory()) {
30241
30497
  const files = await this.walkDir(localPath, localPath);
30242
30498
  for (const file of files) {
30243
30499
  const content = await fsp3.readFile(file);
@@ -30716,6 +30972,8 @@ function mapMailboxMessageToHqSummary(message, options = {}) {
30716
30972
  const outcomePreview = previewText(message.outcome, previewLength, options.redactionPolicy);
30717
30973
  const task = taskSummary(message);
30718
30974
  return {
30975
+ mailId: message.id,
30976
+ // unique UUID per message record, used for deduplication
30719
30977
  messageId: message.id,
30720
30978
  from: message.from,
30721
30979
  to: message.to,
@@ -30859,9 +31117,15 @@ var HqPublisher = class {
30859
31117
  lastCommandId;
30860
31118
  connect() {
30861
31119
  if (this.socket !== null || this.stopped) return;
30862
- const socket = this.socketFactory(toClientUrl(this.options.url, this.options.token), {
30863
- ...this.options.token !== void 0 ? { token: this.options.token } : {}
30864
- });
31120
+ let socket;
31121
+ try {
31122
+ socket = this.socketFactory(toClientUrl(this.options.url, this.options.token), {
31123
+ ...this.options.token !== void 0 ? { token: this.options.token } : {}
31124
+ });
31125
+ } catch {
31126
+ this.scheduleReconnect();
31127
+ return;
31128
+ }
30865
31129
  this.socket = socket;
30866
31130
  const onOpen = () => {
30867
31131
  this.reconnectAttempt = 0;
@@ -31000,6 +31264,7 @@ var HqPublisher = class {
31000
31264
  startCommandPolling() {
31001
31265
  if (this.options.onCommand === void 0 || this.commandPollTimer !== null) return;
31002
31266
  this.commandPollTimer = setInterval(() => this.pollCommands(), this.options.commandPollIntervalMs ?? DEFAULT_COMMAND_POLL_INTERVAL_MS);
31267
+ this.commandPollTimer.unref?.();
31003
31268
  }
31004
31269
  stopCommandPolling() {
31005
31270
  if (this.commandPollTimer === null) return;
@@ -31058,6 +31323,7 @@ var HqPublisher = class {
31058
31323
  this.reconnectTimer = null;
31059
31324
  this.connect();
31060
31325
  }, delay);
31326
+ this.reconnectTimer.unref?.();
31061
31327
  }
31062
31328
  };
31063
31329
 
@@ -31409,6 +31675,7 @@ var GlobalMailbox = class {
31409
31675
  name: input.name,
31410
31676
  source: input.source
31411
31677
  });
31678
+ this.publishHqMailboxSnapshot();
31412
31679
  }
31413
31680
  async clientHeartbeat(input) {
31414
31681
  const last = this._lastClientHeartbeat.get(input.clientId) ?? 0;
@@ -31430,6 +31697,7 @@ var GlobalMailbox = class {
31430
31697
  this._events?.emitCustom("mailbox.client_heartbeat", {
31431
31698
  clientId: input.clientId
31432
31699
  });
31700
+ this.publishHqMailboxSnapshot();
31433
31701
  }
31434
31702
  async getClientStatuses() {
31435
31703
  await this._ensureClientRegistry();
@@ -31651,7 +31919,7 @@ var GlobalMailbox = class {
31651
31919
  obj[id] = agent;
31652
31920
  }
31653
31921
  const tmp = `${this.registryPath}.${randomUUID().slice(0, 8)}.tmp`;
31654
- await fsp3.writeFile(tmp, JSON.stringify(obj, null, 2), "utf8");
31922
+ await fsp3.writeFile(tmp, JSON.stringify(obj), "utf8");
31655
31923
  await fsp3.rename(tmp, this.registryPath);
31656
31924
  }
31657
31925
  // ── Client registry internals ───────────────────────────────────────────
@@ -31696,7 +31964,7 @@ var GlobalMailbox = class {
31696
31964
  obj[id] = client;
31697
31965
  }
31698
31966
  const tmp = `${this.clientRegistryPath}.${randomUUID().slice(0, 8)}.tmp`;
31699
- await fsp3.writeFile(tmp, JSON.stringify(obj, null, 2), "utf8");
31967
+ await fsp3.writeFile(tmp, JSON.stringify(obj), "utf8");
31700
31968
  await fsp3.rename(tmp, this.clientRegistryPath);
31701
31969
  }
31702
31970
  };
@@ -31721,6 +31989,40 @@ function emptyHqAuthFile() {
31721
31989
  function hqAuthFilePath(dataDir) {
31722
31990
  return path3.join(dataDir, "auth.json");
31723
31991
  }
31992
+ function hqRuntimeFilePath(dataDir) {
31993
+ return path3.join(dataDir, "runtime.json");
31994
+ }
31995
+ async function writeHqRuntimeFile(dataDir, file) {
31996
+ const payload = {
31997
+ ...file,
31998
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
31999
+ };
32000
+ await atomicWrite(hqRuntimeFilePath(dataDir), `${JSON.stringify(payload, null, 2)}
32001
+ `, { mode: 384 });
32002
+ }
32003
+ function isProcessAlive(pid) {
32004
+ if (!Number.isInteger(pid) || pid <= 0) return false;
32005
+ try {
32006
+ process.kill(pid, 0);
32007
+ return true;
32008
+ } catch {
32009
+ return false;
32010
+ }
32011
+ }
32012
+ function readHqRuntimeFileSync(dataDir) {
32013
+ try {
32014
+ const parsed = JSON.parse(fs3.readFileSync(hqRuntimeFilePath(dataDir), "utf8"));
32015
+ if (typeof parsed.url !== "string" || parsed.url.trim().length === 0) return void 0;
32016
+ if (typeof parsed.pid === "number" && !isProcessAlive(parsed.pid)) return void 0;
32017
+ return {
32018
+ url: parsed.url,
32019
+ updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : "",
32020
+ ...typeof parsed.pid === "number" ? { pid: parsed.pid } : {}
32021
+ };
32022
+ } catch {
32023
+ return void 0;
32024
+ }
32025
+ }
31724
32026
  async function readHqAuthFile(dataDir, opts = {}) {
31725
32027
  const file = hqAuthFilePath(dataDir);
31726
32028
  let raw;
@@ -31865,12 +32167,13 @@ function resolveHqConfig(options = {}) {
31865
32167
  const enabled = envEnabledRaw !== void 0 && envEnabledRaw.length > 0 ? envEnabledRaw !== "0" : fileConfig?.enabled;
31866
32168
  const dataDir = resolveHqDataDir(fileConfig?.dataDir, env);
31867
32169
  const token = envToken || configToken || readFirstClientTokenFromAuthFile(dataDir);
32170
+ const runtimeUrl = readHqRuntimeFileSync(dataDir)?.url.trim();
31868
32171
  const url = envUrl || configUrl;
31869
32172
  if (!url) {
31870
32173
  if (enabled === false) return void 0;
31871
- if (enabled === true || token) {
32174
+ if (enabled === true || token || runtimeUrl) {
31872
32175
  return {
31873
- url: "http://localhost:3499",
32176
+ url: runtimeUrl || "http://127.0.0.1:3499",
31874
32177
  enabled: true,
31875
32178
  ...token ? { token } : {}
31876
32179
  };
@@ -33784,7 +34087,7 @@ function parseArgs(args) {
33784
34087
  const parts = args.split(/\s+/);
33785
34088
  for (let i = 0; i < parts.length; i++) {
33786
34089
  const part = parts[i];
33787
- if (!part || !part.startsWith("--")) continue;
34090
+ if (!part?.startsWith("--")) continue;
33788
34091
  const key = part.slice(2);
33789
34092
  const next = parts[i + 1];
33790
34093
  if (next && !next.startsWith("--")) {
@@ -34330,8 +34633,12 @@ function formatHumanPrompt(request) {
34330
34633
  init_atomic_write();
34331
34634
  var MAILBOX_FILE2 = "_mailbox.jsonl";
34332
34635
  var LINE_SEPARATOR2 = "\n";
34636
+ var MESSAGE_CACHE_MAX_ENTRIES2 = 1e4;
34333
34637
  var DefaultMailbox = class {
34334
34638
  filePath;
34639
+ _messageCache = null;
34640
+ _messageCacheMtime = -1;
34641
+ _messageCacheSize = -1;
34335
34642
  constructor(sessionDir) {
34336
34643
  this.filePath = path3.join(sessionDir, MAILBOX_FILE2);
34337
34644
  }
@@ -34361,12 +34668,13 @@ var DefaultMailbox = class {
34361
34668
  await fsp3.mkdir(path3.dirname(this.filePath), { recursive: true });
34362
34669
  await withFileLock(this.filePath, async () => {
34363
34670
  await fsp3.appendFile(this.filePath, line, "utf8");
34671
+ this._pushToCache(msg);
34364
34672
  });
34365
34673
  return msg;
34366
34674
  }
34367
34675
  // ── Query ─────────────────────────────────────────────────────────────
34368
34676
  async query(q) {
34369
- const all = await this._readAll();
34677
+ const all = await this._readAllCached();
34370
34678
  const limit = q.limit ?? 50;
34371
34679
  const order = q.minPriority !== void 0 ? { low: 0, normal: 1, high: 2 } : null;
34372
34680
  const minPriorityRank = order && q.minPriority !== void 0 ? order[q.minPriority] : 0;
@@ -34421,12 +34729,13 @@ var DefaultMailbox = class {
34421
34729
  const serialized = all.map((m) => JSON.stringify(m)).join(LINE_SEPARATOR2) + LINE_SEPARATOR2;
34422
34730
  await fsp3.writeFile(this.filePath, serialized, "utf8");
34423
34731
  }
34732
+ this._setMessageCache(all);
34424
34733
  });
34425
34734
  return updated;
34426
34735
  }
34427
34736
  // ── Agent statuses ────────────────────────────────────────────────────
34428
34737
  async getAgentStatuses() {
34429
- const all = await this._readAll();
34738
+ const all = await this._readAllCached();
34430
34739
  const latest = /* @__PURE__ */ new Map();
34431
34740
  for (const m of all) {
34432
34741
  if (m.type !== "status") continue;
@@ -34462,16 +34771,20 @@ var DefaultMailbox = class {
34462
34771
  async heartbeat(_input) {
34463
34772
  }
34464
34773
  async unreadCount(forAgentId) {
34465
- const all = await this._readAll();
34774
+ const all = await this._readAllCached();
34466
34775
  return all.filter(
34467
34776
  (m) => (m.to === forAgentId || m.to === "*") && !(forAgentId in m.readBy) && !m.completed
34468
34777
  ).length;
34469
34778
  }
34470
34779
  async close() {
34780
+ this._messageCache = null;
34781
+ this._messageCacheMtime = -1;
34782
+ this._messageCacheSize = -1;
34471
34783
  }
34472
34784
  async clearAll() {
34473
34785
  await withFileLock(this.filePath, async () => {
34474
34786
  await fsp3.writeFile(this.filePath, "", "utf8");
34787
+ this._setMessageCache([]);
34475
34788
  });
34476
34789
  }
34477
34790
  async purgeStale(opts) {
@@ -34479,13 +34792,14 @@ var DefaultMailbox = class {
34479
34792
  const INCOMPLETE_MAX_AGE_MS = opts?.incompleteMaxAgeMs ?? 6048e5;
34480
34793
  let completedPurged = 0;
34481
34794
  let incompletePurged = 0;
34795
+ let remaining = 0;
34482
34796
  await withFileLock(this.filePath, async () => {
34483
- const all2 = await this._readAll();
34797
+ const all = await this._readAll();
34484
34798
  const now = Date.now();
34485
34799
  const cutoffCompleted = now - COMPLETED_MAX_AGE_MS;
34486
34800
  const cutoffIncomplete = now - INCOMPLETE_MAX_AGE_MS;
34487
34801
  const kept = [];
34488
- for (const msg of all2) {
34802
+ for (const msg of all) {
34489
34803
  const msgTime = new Date(msg.timestamp).getTime();
34490
34804
  const completedTime = msg.completedAt ? new Date(msg.completedAt).getTime() : 0;
34491
34805
  if (msg.completed && completedTime < cutoffCompleted) {
@@ -34498,17 +34812,18 @@ var DefaultMailbox = class {
34498
34812
  }
34499
34813
  kept.push(msg);
34500
34814
  }
34501
- if (kept.length < all2.length) {
34815
+ remaining = kept.length;
34816
+ if (kept.length < all.length) {
34502
34817
  const content = kept.map((m) => JSON.stringify(m)).join(LINE_SEPARATOR2) + LINE_SEPARATOR2;
34503
34818
  await fsp3.writeFile(this.filePath, content, "utf8");
34504
34819
  }
34820
+ this._setMessageCache(kept);
34505
34821
  });
34506
- const all = await this._readAll();
34507
34822
  return {
34508
34823
  completedPurged,
34509
34824
  incompletePurged,
34510
34825
  totalPurged: completedPurged + incompletePurged,
34511
- remaining: all.length
34826
+ remaining
34512
34827
  };
34513
34828
  }
34514
34829
  // ── Client registry stubs (not applicable per-session) ─────────────────
@@ -34547,6 +34862,52 @@ var DefaultMailbox = class {
34547
34862
  throw err;
34548
34863
  }
34549
34864
  }
34865
+ async _readAllCached() {
34866
+ try {
34867
+ const st = await fsp3.stat(this.filePath);
34868
+ if (this._messageCache !== null && this._messageCacheMtime === st.mtimeMs && this._messageCacheSize === st.size) {
34869
+ return this._messageCache;
34870
+ }
34871
+ const all = await this._readAll();
34872
+ this._setMessageCache(all, st.mtimeMs, st.size);
34873
+ return all;
34874
+ } catch (err) {
34875
+ if (err.code === "ENOENT") {
34876
+ this._setMessageCache([], -1, -1);
34877
+ return [];
34878
+ }
34879
+ throw err;
34880
+ }
34881
+ }
34882
+ _setMessageCache(messages, mtime, size) {
34883
+ if (messages.length > MESSAGE_CACHE_MAX_ENTRIES2) {
34884
+ this._messageCache = null;
34885
+ this._messageCacheMtime = -1;
34886
+ this._messageCacheSize = -1;
34887
+ return;
34888
+ }
34889
+ this._messageCache = messages;
34890
+ if (mtime !== void 0 && size !== void 0) {
34891
+ this._messageCacheMtime = mtime;
34892
+ this._messageCacheSize = size;
34893
+ return;
34894
+ }
34895
+ void fsp3.stat(this.filePath).then((st) => {
34896
+ this._messageCacheMtime = st.mtimeMs;
34897
+ this._messageCacheSize = st.size;
34898
+ }).catch(() => {
34899
+ });
34900
+ }
34901
+ _pushToCache(msg) {
34902
+ if (this._messageCache === null) return;
34903
+ if (this._messageCache.length >= MESSAGE_CACHE_MAX_ENTRIES2) {
34904
+ this._messageCache = null;
34905
+ this._messageCacheMtime = -1;
34906
+ this._messageCacheSize = -1;
34907
+ return;
34908
+ }
34909
+ this._messageCache.push(msg);
34910
+ }
34550
34911
  };
34551
34912
  var BrainMonitor = class {
34552
34913
  constructor(opts) {
@@ -35147,13 +35508,13 @@ function makeDependencyWatcherConfig(opts) {
35147
35508
  const globPatterns = patterns.filter((p) => p.includes("*"));
35148
35509
  const plainPatterns = patterns.filter((p) => !p.includes("*"));
35149
35510
  function matchesPattern(filePath) {
35150
- const basename12 = filePath.split("/").pop()?.split("\\").pop() ?? "";
35151
- if (plainPatterns.includes(basename12)) return true;
35511
+ const basename14 = filePath.split("/").pop()?.split("\\").pop() ?? "";
35512
+ if (plainPatterns.includes(basename14)) return true;
35152
35513
  for (const gp of globPatterns) {
35153
35514
  const regex = new RegExp(
35154
35515
  "^" + gp.replace(/\./g, "\\.").replace(/\*/g, ".*") + "$"
35155
35516
  );
35156
- if (regex.test(basename12)) return true;
35517
+ if (regex.test(basename14)) return true;
35157
35518
  }
35158
35519
  return false;
35159
35520
  }
@@ -35872,7 +36233,7 @@ var TaskDAG = class {
35872
36233
  }
35873
36234
  for (const depId of node.dependents) {
35874
36235
  const dep = this.nodes.get(depId);
35875
- if (dep && dep.deps.every((d) => !this.nodes.has(d) || this.nodes.get(d).status === "done")) {
36236
+ if (dep?.deps.every((d) => !this.nodes.has(d) || this.nodes.get(d).status === "done")) {
35876
36237
  this._transition(depId, "pending", "ready");
35877
36238
  }
35878
36239
  }
@@ -36134,7 +36495,7 @@ var ConsensusProtocol = class {
36134
36495
  */
36135
36496
  async initiateVote(changeId) {
36136
36497
  const change = this.graph.get(changeId);
36137
- if (!change || change.type !== "change") {
36498
+ if (change?.type !== "change") {
36138
36499
  throw new Error(`ConsensusProtocol: no change found with id "${changeId}"`);
36139
36500
  }
36140
36501
  await this.graph.update(changeId, { status: "proposed", votes: [] });
@@ -36147,7 +36508,7 @@ var ConsensusProtocol = class {
36147
36508
  */
36148
36509
  async castVote(changeId, voterId, value, rationale) {
36149
36510
  const change = this.graph.get(changeId);
36150
- if (!change || change.type !== "change") {
36511
+ if (change?.type !== "change") {
36151
36512
  throw new Error(`ConsensusProtocol: no change found for "${changeId}"`);
36152
36513
  }
36153
36514
  const voter = this.voters.get(voterId);
@@ -36201,7 +36562,7 @@ var ConsensusProtocol = class {
36201
36562
  */
36202
36563
  getStatus(changeId) {
36203
36564
  const change = this.graph.get(changeId);
36204
- if (!change || change.type !== "change") return null;
36565
+ if (change?.type !== "change") return null;
36205
36566
  const eligible = this._eligibleVoters(change);
36206
36567
  return this._resolve(changeId, change.votes, eligible);
36207
36568
  }
@@ -36404,7 +36765,7 @@ var ChangeManager = class {
36404
36765
  */
36405
36766
  async submitForReview(changeId) {
36406
36767
  const change = this.graph.get(changeId);
36407
- if (!change || change.type !== "change") {
36768
+ if (change?.type !== "change") {
36408
36769
  throw new Error(`ChangeManager: no change found "${changeId}"`);
36409
36770
  }
36410
36771
  if (change.status !== "proposed") {
@@ -36466,7 +36827,7 @@ var ChangeManager = class {
36466
36827
  */
36467
36828
  async proposeRollback(appliedChangeId, reason) {
36468
36829
  const original = this.graph.get(appliedChangeId);
36469
- if (!original || original.type !== "change") return null;
36830
+ if (original?.type !== "change") return null;
36470
36831
  const rollbackFiles = original.files.map((f) => ({
36471
36832
  path: f.path,
36472
36833
  action: f.action === "create" ? "delete" : f.action === "delete" ? "create" : "modify"
@@ -37020,7 +37381,7 @@ var TaskAuctioneer = class {
37020
37381
  */
37021
37382
  async bid(taskId, agent, rationale) {
37022
37383
  const goal = this.graph.get(taskId);
37023
- if (!goal || goal.type !== "goal") return false;
37384
+ if (goal?.type !== "goal") return false;
37024
37385
  if (goal.status !== "pending") return false;
37025
37386
  const currentCount = this._getAgentTaskCount(agent.agentId);
37026
37387
  if (currentCount >= this.maxTasksPerAgent) return false;
@@ -37069,7 +37430,7 @@ Score: ${score.toFixed(2)}`
37069
37430
  */
37070
37431
  async claim(taskId, agentId, agentName) {
37071
37432
  const goal = this.graph.get(taskId);
37072
- if (!goal || goal.type !== "goal") return false;
37433
+ if (goal?.type !== "goal") return false;
37073
37434
  if (goal.status !== "pending") return false;
37074
37435
  this._cancelBidWindow(taskId);
37075
37436
  await this.graph.update(taskId, {
@@ -39322,9 +39683,11 @@ function createAgentLoopHandler(a, handlers) {
39322
39683
  checkMailbox,
39323
39684
  foldBlockIntoConversation,
39324
39685
  {
39325
- // Cast to the broad parameter type — injectPendingMailboxMessages only
39326
- // calls emit('mailbox.received', ...) and uses logger.debug optionally.
39327
- events: a.events,
39686
+ events: {
39687
+ emit: (type, payload) => {
39688
+ a.events.emit(type, payload);
39689
+ }
39690
+ },
39328
39691
  logger: a.logger
39329
39692
  }
39330
39693
  );
@@ -39871,7 +40234,7 @@ async function runShellHook(spec, input, logger) {
39871
40234
  }
39872
40235
  function parseOutcome(stdout) {
39873
40236
  const trimmed = stdout.trim();
39874
- if (!trimmed || trimmed[0] !== "{") return null;
40237
+ if (trimmed?.[0] !== "{") return null;
39875
40238
  try {
39876
40239
  const obj = JSON.parse(trimmed);
39877
40240
  const outcome = {};
@@ -39990,10 +40353,12 @@ var HookRunner = class {
39990
40353
  async collectContext(event, toolName, payload) {
39991
40354
  const entries = this.matching(event, toolName);
39992
40355
  if (entries.length === 0) return void 0;
40356
+ const results = await Promise.allSettled(entries.map((entry) => this.invoke(entry, payload)));
39993
40357
  const parts = [];
39994
- for (const entry of entries) {
39995
- const outcome = await this.invoke(entry, payload);
39996
- if (outcome?.additionalContext) parts.push(outcome.additionalContext);
40358
+ for (const result of results) {
40359
+ if (result.status === "fulfilled" && result.value?.additionalContext) {
40360
+ parts.push(result.value.additionalContext);
40361
+ }
39997
40362
  }
39998
40363
  return parts.length ? parts.join("\n") : void 0;
39999
40364
  }
@@ -40586,7 +40951,6 @@ var DefaultSystemPromptBuilder = class {
40586
40951
  return 60;
40587
40952
  case "aggressive":
40588
40953
  return 70;
40589
- case "off":
40590
40954
  default:
40591
40955
  return 80;
40592
40956
  }
@@ -40689,13 +41053,13 @@ var DefaultSystemPromptBuilder = class {
40689
41053
  if (!planPath) return "";
40690
41054
  let raw;
40691
41055
  try {
40692
- const stat14 = await fsp3.stat(planPath);
40693
- if (this._planCache && this._planCache.path === planPath && this._planCache.mtimeMs === stat14.mtimeMs) {
41056
+ const stat15 = await fsp3.stat(planPath);
41057
+ if (this._planCache && this._planCache.path === planPath && this._planCache.mtimeMs === stat15.mtimeMs) {
40694
41058
  return this._planCache.text;
40695
41059
  }
40696
41060
  raw = await fsp3.readFile(planPath, "utf8");
40697
41061
  const text = this._formatPlan(raw);
40698
- this._planCache = { path: planPath, mtimeMs: stat14.mtimeMs, text };
41062
+ this._planCache = { path: planPath, mtimeMs: stat15.mtimeMs, text };
40699
41063
  return text;
40700
41064
  } catch {
40701
41065
  this._planCache = void 0;
@@ -41257,8 +41621,8 @@ ${clean.trim()}`);
41257
41621
  }
41258
41622
  async dirExists(p) {
41259
41623
  try {
41260
- const stat14 = await fsp3.stat(p);
41261
- return stat14.isDirectory();
41624
+ const stat15 = await fsp3.stat(p);
41625
+ return stat15.isDirectory();
41262
41626
  } catch {
41263
41627
  return false;
41264
41628
  }
@@ -44965,7 +45329,7 @@ function buildSyncCommand(cloud, configStore, vault, syncConfigPath) {
44965
45329
  };
44966
45330
  }
44967
45331
  const [repo, token, ...cats] = parts;
44968
- if (!repo || !repo.includes("/")) {
45332
+ if (!repo?.includes("/")) {
44969
45333
  return { message: 'Invalid repo format. Expected "owner/repo".' };
44970
45334
  }
44971
45335
  const storedToken = vault ? vault.encrypt(expectDefined(token)) : expectDefined(token);
@@ -46107,6 +46471,6 @@ function createChimeraPlugin() {
46107
46471
  };
46108
46472
  }
46109
46473
 
46110
- export { ACP_AGENTS, AGENTS_BY_PHASE, AGENT_CATALOG, TOOLS as AGENT_TOOL_PRESETS, AISpecBuilder, ALL_AGENT_DEFINITIONS, ALL_FLEET_AGENTS, ALL_SYNC_CATEGORIES, AUDIT_LOG_AGENT, Agent, AgentError, AgentStatusTracker, AnnotationsStore, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutoPhasePlanner, AutoPhaseRunner, AutonomousBrain, AutonomousCoordinator, AutonomousRunner, BUG_HUNTER_AGENT, BUILD_AGENTS, BrainDecisionQueue, BrainMonitor, BudgetExceededError, BudgetThresholdSignal, CHIMERA_REVIEW_PROMPT, CONTEXT_WINDOW_MODES, CORE_RECONSTRUCT_EVENTS, ChangeManager, CheckpointManager, CloudSync, CollabSession, CollaborationBus, ConfigError, ConfigMigrationError, ConsensusProtocol, Container, Context, ConversationState, DANGEROUS_FOR_SUBAGENTS, DECISION_TIMEOUT_MS, DEFAULT_AUTONOMY_CONFIG, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_CONFIG, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_DISPATCH_ROLE, DEFAULT_HQ_REDACTION_POLICY, DEFAULT_MAX_ITERATIONS, DEFAULT_MODES, DEFAULT_QUALITY_CHECKS, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SESSION_LOGGING_CONFIG, DEFAULT_SESSION_PRUNE_DAYS, DEFAULT_SPEC_TEMPLATE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DELIVERY_AGENTS, DEPENDENCY_FILE_PATTERNS, DISCOVERY_AGENTS, DOMAIN_AGENTS, DefaultAttachmentStore, DefaultBrainArbiter, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMailbox, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultPluginAPI, DefaultPromptStore, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionRewinder, DefaultSessionStore, DefaultSkillLoader, DefaultSystemPromptBuilder, DefaultTaskStore, DefaultTokenCounter, Director, DirectorAlertLevel, DirectorStateCheckpoint, DoneConditionChecker, ENHANCER_SYSTEM_PROMPT, ERROR_CODES, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FORBIDDEN_PROTO_KEYS, FileMemoryBackend, FleetBus, FleetCostCapError, FleetManager, FleetNotifier, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, GlobalMailbox, GraphMemoryBackend, HEAVY_BUDGET, HQ_AUTH_FILE_VERSION, HQ_PROTOCOL_VERSION, HookRegistry, HookRunner, HqPublisher, HumanEscalatingBrainArbiter, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, KNOWLEDGE_AGENTS, KnowledgeGraph, LAYER_1_IDENTITY, LIGHT_BUDGET, LLMSelector, LargeAnswerStore, MATRIX_PHASE_KEYS, MAX_JOURNAL_ENTRIES, MAX_PROGRESS_HISTORY, MEDIUM_BUDGET, MEMORY_TYPE_LABELS, META_AGENTS, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, ObservableBrainArbiter, PLANNING_AGENTS, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, PhaseGraphBuilder, PhaseOrchestrator, PhaseStore, Pipeline, PluginError, ProviderError, ProviderRegistry, QueueStore, REFACTOR_PLANNER_AGENT, REVIEW_AGENTS, RecoveryLock, ReplayLogStore, ReplayProviderRunner, ReportGenerator, RunController, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, STANDARD_AUDIT_EVENTS, ScopedEventBus, SddError, SddParallelRun, SddTaskDecomposer, SecurityScanner, SecurityScannerOrchestrator, SelectiveCompactor, SessionAnalyzer, SessionError, SessionMemoryConsolidator, SessionRecovery, SessionRegistry, SkillGenerator, SkillInstaller, SkillManifestStore, SlashCommandRegistry, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, StreamHangError, SubagentBudget, TIMEOUT_PREEMPT_FRACTION, TOKENS, TaskAuctioneer, TaskDAG, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, TechStackDetector, ToolAuditLog, ToolCapabilities, ToolError, ToolExecutor, ToolRegistry, VERIFY_AGENTS, WIDE_SUBAGENT_CAPABILITIES, WorktreeManager, WrongStackError, addPlanItem, allServers, analyzeCriticalPath, appendJournal, applyModelRuntime, applyRosterBudget, asBlocks, asText, assertNever, assertNotPrivateHost, assertSafePath, assessCommitSafety, atomicWrite, attachAutoExtend, attachDepWatcherBridge, attachMailboxChecker, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, bootConfig, braveSearchServer, buildBtwBlock, buildChildEnv, buildContextEvidenceDigest, buildGoalPreamble, buildLosslessDigest, buildMailboxBlock, buildOtlpMetricsRequest, buildOtlpTracesRequest, buildQueuedMessagesBlock, buildRecoveryStrategies, buildSmartDigest, classifyFamily, clearPlan, collabInjectMiddleware, collabPauseMiddleware, color, compactLog, compactSchemaDescriptions, compactToolDefinitionForWire, compileGlob, compileUserRegex, completePartialObject, composeDirectorPrompt, composeSubagentPrompt, computeMessageTokens, computeTaskItemProgress, computeTaskProgress, consumeBtwNotes, consumeQueuedMessagesUpdate, context7Server, contextManagerTool, createAutoExecutor, createAutoPhaseFromTaskGraph, createAutonomyBrain, createChimeraPlugin, createContextEvidenceState, createContextManagerTool, createDefaultPipelines, createDelegateTool, createGitPlugin, createGlobalMailbox, createHqEventEnvelope, createHqPublisherFromEnv, createMailboxChecker, createMailboxEventPayload, createMailboxHooks, createMailboxSnapshotPayload, createMailboxSnapshotPayloadFromMailbox, createMcpControlTool, createMcpUseTool, createMessage, createObservabilityPlugin, createPlanPlugin, createPromptsPlugin, createSecurityPlugin, createSecuritySlashCommand, createSessionEventBridge, createSkillsPlugin, createStrategyCompactor, createSyncPlugin, createTieredBrainArbiter, createToolOutputSerializer, decryptConfigSecrets, deepMerge, defaultGitignoreUpdater, defaultHqDataDir, defaultOrchestrator, defaultReportGenerator, defaultSecurityScanner, defaultSkillGenerator, defaultTechStackDetector, definePlugin, deriveTodosFromPlanItem, describeCatalogModel, detectEcosystem, detectNewlineStyle, detectEcosystem as detectPackageEcosystem, dispatchAgent, downloadGitHubTarball, eliseOldToolResults, emptyGoal, emptyHqAuthFile, emptyPlan, emptyTaskFile, encryptConfigSecrets, encryptedPrefixForVersion, enhanceUserPrompt, ensureDir, ensureHqFirstRunAuthFile, escapeGlobSubject, estimateMessageTokens, estimateMessages, estimateRequestTokens, estimateRequestTokensCalibrated, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, expandGlob, expandIPv6, expectDefined, extractRunEnv, extractText, filesystemServer, findCriticalPath, findPreserveStart, flagsToConfigPatch, formatContextWindowModeList, formatDecisionSummary, formatGoal, formatHumanPrompt, formatPlan, formatPlanTemplates, formatTaskList, formatTaskProgress, formatTodosList, getAgentDefinition, getCalibrationState, getContextWindowMode, getDangerousCapabilities, getFileHistory, getFilesByAgent, getFullLog, getFullPackageLog, getJsonPath, getLastAuthor, getManifestPackages, getPackageAuthor, getPackagesByAgent, getPlanTemplate, getSessionRegistry, getTemplate, getTermSize, githubServer, goalFilePath, googleMapsServer, hasCapability, hasDangerousCapabilityForSubagents, hasSessionRegistry, hasTextContent, hashRequest, hookMatcherMatches, hqAuthFilePath, injectPendingMailboxMessages, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isInteractive, isJsonObject, isPathSubjectKey, isPluginError, isPrimitiveArray, isPrivateIPv4, isPrivateIPv6, isSddError, isSecretField, isSessionError, isStdinTTY, isStdoutTTY, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isValidMatrixKey, isWrongStackError, jsonObjectFileExists, listContextWindowModes, listPlanTemplates, listTemplates, loadDirectorState, loadGoal, loadPlan, loadPlugins, loadProjectModes, loadTasks, loadTodosCheckpoint, loadUserModes, mailboxSessionTag, makeAgentSubagentRunner, makeAskResultTool, makeAskTool, makeAssignTool, makeAutonomyPromptContributor, makeAwaitTasksTool, makeCollabDebugTool, makeContinueToNextIterationTool, makeDependencyWatcherConfig, makeDirectorSessionFactory, makeFleetEmitTool, makeFleetHealthTool, makeFleetSessionTool, makeFleetStatusTool, makeFleetUsageTool, makeLLMClassifier, makeMailInboxTool, makeMailSendTool, makeMailboxTool, makeRollUpTool, makeSpawnTool, makeTerminateTool, makeWorkCompleteTool, mapMailboxAgentToHqSummary, mapMailboxMessageToHqSummary, markAssistantReferencedEvidence, matchAny, matchGlob, matrixKeyKind, mergeCustomModelDefs, mergeModelsPayload, migratePlaintextSecrets, miniMaxVisionServer, mintHqBrowserToken, mintHqToken, mutateHqAuthFile, mutatePlan, mutateTasks, noOpLogger, noOpVault, normalizePathSubject, normalizeRecipient, normalizeToLf, normalizeTokenSavingTier, normalizedEqual, onResize, parseContinueDirective, parseEncryptedVersion, parseEntries, parseHqEventPayload, parseHqFrame, parseProgressFromText, parseSkillRef, peekQueuedMessages, pendingBtwCount, phaseForRole, playwrightServer, projectHash, projectSlug, readHqAuthFile, readJsonObjectFile, recentTextTurns, recordActualUsage, recordFileAction, recordPackageAction, recordProgress, recordToolOutputEvidence, recordUserIntentEvidence, redactHqEvent, redactHqValue, removeJsonPath, removeJsonPathInFile, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, repeatedReadPressure, resetCalibration, resolveAuditLevel, resolveCacheForRequest, resolveChimeraConfig, resolveContextWindowPolicy, resolveHqConfig, resolveHqConfigFromEnv, resolveHqDataDir, resolveMailboxIdentity, resolveModelMatrix, resolveModelRuntime, resolveProjectDir, resolveProviderModelList, resolveReasoningForRequest, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, rotateConfigKeys, runConfigMigrations, runProviderWithRetry, runShellHook, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTasks, saveTodosCheckpoint, scoreAgents, scoreMessage, scrubAndTruncateHqPreview, securitySlashCommand, sentinelServer, setBtwNote, setJsonPath, setJsonPathInFile, setOutputLineGuard, setPlanItemStatus, setProgress, setQueuedMessagesSnapshot, setRawMode, shouldEnhance, slackServer, sleep, sshManagerServer, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, startPackageOutdatedWatcher, startTechStackConsumer, stripAnsi, subjectForToolInput, summarizeHqToolArgs, summarizeUsage, templateToMarkdown, toErrorMessage, toStyle, toWrongStackError, topologicalSort, truncate, unifiedDiff, unloadPlugins, updateJsonObjectFile, updatePackageOutdatedStatus, validateAgainstSchema, watchHqAuthFile, wireMetricsToEvents, withDisabledToolFiltering, withFileLock, wrapAsState, writeErr, writeHqAuthFile, writeJsonObjectFile, writeOut, wstackGlobalRoot, zaiVisionServer };
46474
+ export { ACP_AGENTS, AGENTS_BY_PHASE, AGENT_CATALOG, TOOLS as AGENT_TOOL_PRESETS, AISpecBuilder, ALL_AGENT_DEFINITIONS, ALL_FLEET_AGENTS, ALL_SYNC_CATEGORIES, AUDIT_LOG_AGENT, Agent, AgentError, AgentStatusTracker, AnnotationsStore, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutoPhasePlanner, AutoPhaseRunner, AutonomousBrain, AutonomousCoordinator, AutonomousRunner, BUG_HUNTER_AGENT, BUILD_AGENTS, BrainDecisionQueue, BrainMonitor, BudgetExceededError, BudgetThresholdSignal, CHIMERA_REVIEW_PROMPT, CONTEXT_WINDOW_MODES, CORE_RECONSTRUCT_EVENTS, ChangeManager, CheckpointManager, CloudSync, CollabSession, CollaborationBus, ConfigError, ConfigMigrationError, ConsensusProtocol, Container, Context, ConversationState, DANGEROUS_FOR_SUBAGENTS, DECISION_TIMEOUT_MS, DEFAULT_AUTONOMY_CONFIG, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_CONFIG, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_DISPATCH_ROLE, DEFAULT_HQ_REDACTION_POLICY, DEFAULT_MAX_ITERATIONS, DEFAULT_MODES, DEFAULT_QUALITY_CHECKS, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SESSION_LOGGING_CONFIG, DEFAULT_SESSION_PRUNE_DAYS, DEFAULT_SPEC_TEMPLATE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DEFAULT_TUI_THINKING_WORD, DELIVERY_AGENTS, DEPENDENCY_FILE_PATTERNS, DISCOVERY_AGENTS, DOMAIN_AGENTS, DefaultAttachmentStore, DefaultBrainArbiter, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMailbox, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPathResolver, DefaultPermissionPolicy, DefaultPluginAPI, DefaultPromptStore, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionRewinder, DefaultSessionStore, DefaultSkillLoader, DefaultSystemPromptBuilder, DefaultTaskStore, DefaultTokenCounter, Director, DirectorAlertLevel, DirectorStateCheckpoint, DoneConditionChecker, ENHANCER_SYSTEM_PROMPT, ERROR_CODES, EternalAutonomyEngine, EventBus, ExtensionRegistry, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FORBIDDEN_PROTO_KEYS, FileMemoryBackend, FleetBus, FleetCostCapError, FleetManager, FleetNotifier, FleetSpawnBudgetError, FleetUsageAggregator, FsError, GitignoreUpdater, GlobalMailbox, GraphMemoryBackend, HEAVY_BUDGET, HQ_AUTH_FILE_VERSION, HQ_PROTOCOL_VERSION, HookRegistry, HookRunner, HqPublisher, HumanEscalatingBrainArbiter, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, InputBuilder, IntelligentCompactor, KERNEL_API_VERSION, KNOWLEDGE_AGENTS, KnowledgeGraph, LAYER_1_IDENTITY, LIGHT_BUDGET, LLMSelector, LargeAnswerStore, MATRIX_PHASE_KEYS, MAX_JOURNAL_ENTRIES, MAX_PROGRESS_HISTORY, MAX_TUI_THINKING_WORD_LENGTH, MEDIUM_BUDGET, MEMORY_TYPE_LABELS, META_AGENTS, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, ObservableBrainArbiter, PLANNING_AGENTS, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, PhaseGraphBuilder, PhaseOrchestrator, PhaseStore, Pipeline, PluginError, ProviderError, ProviderRegistry, QueueStore, REFACTOR_PLANNER_AGENT, REVIEW_AGENTS, RecoveryLock, ReplayLogStore, ReplayProviderRunner, ReportGenerator, RunController, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, STANDARD_AUDIT_EVENTS, ScopedEventBus, SddError, SddParallelRun, SddTaskDecomposer, SecurityScanner, SecurityScannerOrchestrator, SelectiveCompactor, SessionAnalyzer, SessionError, SessionMemoryConsolidator, SessionRecovery, SessionRegistry, SkillGenerator, SkillInstaller, SkillManifestStore, SlashCommandRegistry, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, StreamHangError, SubagentBudget, TIMEOUT_PREEMPT_FRACTION, TOKENS, TaskAuctioneer, TaskDAG, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, TechStackDetector, ToolAuditLog, ToolCapabilities, ToolError, ToolErrorCategory, ToolExecutor, ToolRegistry, VERIFY_AGENTS, WIDE_SUBAGENT_CAPABILITIES, WorktreeManager, WrongStackError, addPlanItem, allServers, analyzeCriticalPath, appendJournal, applyModelRuntime, applyRosterBudget, asBlocks, asText, assertNever, assertNotPrivateHost, assertSafePath, assessCommitSafety, atomicWrite, attachAutoExtend, attachDepWatcherBridge, attachMailboxChecker, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, bootConfig, braveSearchServer, buildBtwBlock, buildChildEnv, buildContextEvidenceDigest, buildGoalPreamble, buildLosslessDigest, buildMailboxBlock, buildOtlpMetricsRequest, buildOtlpTracesRequest, buildQueuedMessagesBlock, buildRecoveryStrategies, buildSmartDigest, classifyFamily, clearPlan, collabInjectMiddleware, collabPauseMiddleware, color, compactLog, compactSchemaDescriptions, compactToolDefinitionForWire, compileGlob, compileUserRegex, completePartialObject, composeDirectorPrompt, composeSubagentPrompt, computeMessageTokens, computeTaskItemProgress, computeTaskProgress, consumeBtwNotes, consumeQueuedMessagesUpdate, context7Server, contextManagerTool, createAutoExecutor, createAutoPhaseFromTaskGraph, createAutonomyBrain, createChimeraPlugin, createContextEvidenceState, createContextManagerTool, createDefaultPipelines, createDelegateTool, createGitPlugin, createGlobalMailbox, createHqEventEnvelope, createHqPublisherFromEnv, createMailboxChecker, createMailboxEventPayload, createMailboxHooks, createMailboxSnapshotPayload, createMailboxSnapshotPayloadFromMailbox, createMcpControlTool, createMcpUseTool, createMessage, createObservabilityPlugin, createPlanPlugin, createPromptsPlugin, createSecurityPlugin, createSecuritySlashCommand, createSessionEventBridge, createSkillsPlugin, createStrategyCompactor, createSyncPlugin, createTieredBrainArbiter, createToolOutputSerializer, decryptConfigSecrets, deepMerge, defaultGitignoreUpdater, defaultHqDataDir, defaultOrchestrator, defaultReportGenerator, defaultSecurityScanner, defaultSkillGenerator, defaultTechStackDetector, definePlugin, deriveTodosFromPlanItem, describeCatalogModel, detectEcosystem, detectNewlineStyle, detectEcosystem as detectPackageEcosystem, dispatchAgent, downloadGitHubTarball, eliseOldToolResults, emptyGoal, emptyHqAuthFile, emptyPlan, emptyTaskFile, encryptConfigSecrets, encryptedPrefixForVersion, enhanceUserPrompt, ensureDir, ensureHqFirstRunAuthFile, escapeGlobSubject, estimateMessageTokens, estimateMessages, estimateRequestTokens, estimateRequestTokensCalibrated, estimateTextTokens, estimateToolDefTokens, estimateToolInputTokens, estimateToolResultTokens, everArtServer, expandGlob, expandIPv6, expectDefined, extractRunEnv, extractText, filesystemServer, findCriticalPath, findPreserveStart, flagsToConfigPatch, formatContextWindowModeList, formatDecisionSummary, formatGoal, formatHumanPrompt, formatPlan, formatPlanTemplates, formatTaskList, formatTaskProgress, formatTodosList, getAgentDefinition, getCalibrationState, getContextWindowMode, getDangerousCapabilities, getFileHistory, getFilesByAgent, getFullLog, getFullPackageLog, getJsonPath, getLastAuthor, getManifestPackages, getPackageAuthor, getPackagesByAgent, getPlanTemplate, getSessionRegistry, getTemplate, getTermSize, githubServer, goalFilePath, googleMapsServer, hasCapability, hasDangerousCapabilityForSubagents, hasSessionRegistry, hasTextContent, hashRequest, hookMatcherMatches, hqAuthFilePath, hqRuntimeFilePath, injectPendingMailboxMessages, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isInteractive, isJsonObject, isPathSubjectKey, isPluginError, isPrimitiveArray, isPrivateIPv4, isPrivateIPv6, isSddError, isSecretField, isSessionError, isStdinTTY, isStdoutTTY, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isValidMatrixKey, isWrongStackError, jsonObjectFileExists, listContextWindowModes, listPlanTemplates, listTemplates, loadDirectorState, loadGoal, loadPlan, loadPlugins, loadProjectModes, loadTasks, loadTodosCheckpoint, loadUserModes, mailboxSessionTag, makeAgentSubagentRunner, makeAskResultTool, makeAskTool, makeAssignTool, makeAutonomyPromptContributor, makeAwaitTasksTool, makeCollabDebugTool, makeContinueToNextIterationTool, makeDependencyWatcherConfig, makeDirectorSessionFactory, makeFleetEmitTool, makeFleetHealthTool, makeFleetSessionTool, makeFleetStatusTool, makeFleetUsageTool, makeLLMClassifier, makeMailInboxTool, makeMailSendTool, makeMailboxTool, makeRollUpTool, makeSpawnTool, makeTerminateTool, makeWorkCompleteTool, mapMailboxAgentToHqSummary, mapMailboxMessageToHqSummary, markAssistantReferencedEvidence, matchAny, matchGlob, matrixKeyKind, mergeCustomModelDefs, mergeModelsPayload, migratePlaintextSecrets, miniMaxVisionServer, mintHqBrowserToken, mintHqToken, mutateHqAuthFile, mutatePlan, mutateTasks, noOpLogger, noOpVault, normalizePathSubject, normalizeRecipient, normalizeToLf, normalizeTokenSavingTier, normalizeTuiThinkingWord, normalizedEqual, onResize, parseContinueDirective, parseEncryptedVersion, parseEntries, parseHqEventPayload, parseHqFrame, parseProgressFromText, parseSkillRef, peekQueuedMessages, pendingBtwCount, phaseForRole, playwrightServer, projectHash, projectSlug, readHqAuthFile, readHqRuntimeFileSync, readJsonObjectFile, recentTextTurns, recordActualUsage, recordFileAction, recordPackageAction, recordProgress, recordToolOutputEvidence, recordUserIntentEvidence, redactHqEvent, redactHqValue, removeJsonPath, removeJsonPathInFile, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, repairToolUseAdjacency, repeatedReadPressure, resetCalibration, resolveAuditLevel, resolveCacheForRequest, resolveChimeraConfig, resolveContextWindowPolicy, resolveHqConfig, resolveHqConfigFromEnv, resolveHqDataDir, resolveMailboxIdentity, resolveModelMatrix, resolveModelRuntime, resolveProjectDir, resolveProviderModelList, resolveReasoningForRequest, resolveSessionLoggingConfig, resolveWstackPaths, rewriteConfigEncrypted, rosterSummaryFromConfigs, rotateConfigKeys, runConfigMigrations, runProviderWithRetry, runShellHook, safeParse, safeStringify, sanitizeJsonString, saveGoal, savePlan, saveTasks, saveTodosCheckpoint, scoreAgents, scoreMessage, scrubAndTruncateHqPreview, securitySlashCommand, sentinelServer, setBtwNote, setJsonPath, setJsonPathInFile, setOutputLineGuard, setPlanItemStatus, setProgress, setQueuedMessagesSnapshot, setRawMode, shouldEnhance, slackServer, sleep, sshManagerServer, stableStringify, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, startPackageOutdatedWatcher, startTechStackConsumer, stripAnsi, subjectForToolInput, summarizeHqToolArgs, summarizeUsage, templateToMarkdown, toErrorMessage, toStyle, toWrongStackError, topologicalSort, truncate, unifiedDiff, unloadPlugins, updateJsonObjectFile, updatePackageOutdatedStatus, validateAgainstSchema, watchHqAuthFile, wireMetricsToEvents, withDisabledToolFiltering, withFileLock, wrapAsState, writeErr, writeHqAuthFile, writeHqRuntimeFile, writeJsonObjectFile, writeOut, wstackGlobalRoot, zaiVisionServer };
46111
46475
  //# sourceMappingURL=index.js.map
46112
46476
  //# sourceMappingURL=index.js.map