@wrongstack/core 0.272.0 → 0.272.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 (47) hide show
  1. package/dist/{agent-bridge-jVSZiygR.d.ts → agent-bridge-DFQYEeXf.d.ts} +1 -1
  2. package/dist/{agent-subagent-runner-DOLIwBRo.d.ts → agent-subagent-runner-BZa_IEcd.d.ts} +4 -4
  3. package/dist/{brain-CdbbJWi3.d.ts → brain-etbcbRwV.d.ts} +24 -1
  4. package/dist/{config-D2DGoGSQ.d.ts → config-rRS8yorV.d.ts} +43 -1
  5. package/dist/coordination/index.d.ts +74 -14
  6. package/dist/coordination/index.js +285 -97
  7. package/dist/coordination/index.js.map +1 -1
  8. package/dist/defaults/index.d.ts +16 -16
  9. package/dist/defaults/index.js +209 -140
  10. package/dist/defaults/index.js.map +1 -1
  11. package/dist/execution/index.d.ts +9 -9
  12. package/dist/extension/index.d.ts +4 -4
  13. package/dist/{global-mailbox-CQj_C9Dp.d.ts → global-mailbox-DJ4EoRr0.d.ts} +7 -3
  14. package/dist/{goal-preamble-ZXDjjR1y.d.ts → goal-preamble-hM8BH7TK.d.ts} +5 -5
  15. package/dist/{goal-store-CcJBd-g1.d.ts → goal-store-CWlbT0TO.d.ts} +1 -1
  16. package/dist/hq/index.d.ts +6 -4
  17. package/dist/hq/index.js +14 -6
  18. package/dist/hq/index.js.map +1 -1
  19. package/dist/{index-Qo4kTzgw.d.ts → index-DWm_PE9L.d.ts} +3 -3
  20. package/dist/{index-BL7BAx0p.d.ts → index-DqW4o62H.d.ts} +4 -4
  21. package/dist/index.d.ts +27 -27
  22. package/dist/index.js +571 -215
  23. package/dist/index.js.map +1 -1
  24. package/dist/infrastructure/index.d.ts +4 -4
  25. package/dist/kernel/index.d.ts +5 -5
  26. package/dist/kernel/index.js.map +1 -1
  27. package/dist/{mcp-servers-DS-YUXvF.d.ts → mcp-servers-BpWHTKlE.d.ts} +1 -1
  28. package/dist/models/index.d.ts +3 -3
  29. package/dist/{models-registry-DP6pGHet.d.ts → models-registry-CXQFUn5t.d.ts} +1 -1
  30. package/dist/{multi-agent-coordinator-BvbdNQ14.d.ts → multi-agent-coordinator-jyimfo7D.d.ts} +1 -1
  31. package/dist/{null-fleet-bus-BxTfXBKo.d.ts → null-fleet-bus-DOGQcvrY.d.ts} +5 -5
  32. package/dist/observability/index.d.ts +1 -1
  33. package/dist/{parallel-eternal-engine-Cf-GTegR.d.ts → parallel-eternal-engine-rItJBYp9.d.ts} +6 -6
  34. package/dist/{path-resolver-DztfnFcv.d.ts → path-resolver-DrpF5MGK.d.ts} +2 -2
  35. package/dist/{pipeline-sNIkhXeB.d.ts → pipeline-Ckkn3AOA.d.ts} +1 -1
  36. package/dist/{plan-templates-DYiKFmEb.d.ts → plan-templates-BvHw5Znw.d.ts} +24 -6
  37. package/dist/{provider-model-resolve-dYAbTs_i.d.ts → provider-model-resolve-nZqnCeaR.d.ts} +1 -1
  38. package/dist/{provider-runner-Dw8x0F7u.d.ts → provider-runner-zVOn1p67.d.ts} +1 -1
  39. package/dist/sdd/index.d.ts +5 -5
  40. package/dist/storage/index.d.ts +12 -7
  41. package/dist/storage/index.js +250 -111
  42. package/dist/storage/index.js.map +1 -1
  43. package/dist/tools/index.d.ts +1 -1
  44. package/dist/types/index.d.ts +13 -13
  45. package/dist/types/index.js.map +1 -1
  46. package/dist/utils/index.d.ts +1 -1
  47. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -113,7 +113,7 @@ async function withFileLock(targetPath, fn, opts = {}) {
113
113
  if (Date.now() - started >= timeoutMs) {
114
114
  throw new Error(`Timed out waiting for file lock: ${targetPath}`);
115
115
  }
116
- await new Promise((resolve18) => setTimeout(resolve18, 25));
116
+ await new Promise((resolve19) => setTimeout(resolve19, 25));
117
117
  }
118
118
  }
119
119
  try {
@@ -146,7 +146,7 @@ async function renameWithRetry(from, to) {
146
146
  if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {
147
147
  throw err;
148
148
  }
149
- await new Promise((resolve18) => setTimeout(resolve18, delays[i]));
149
+ await new Promise((resolve19) => setTimeout(resolve19, delays[i]));
150
150
  }
151
151
  }
152
152
  throw lastErr;
@@ -754,9 +754,9 @@ async function updateJsonObjectFile(filePath, mutator) {
754
754
  await writeJsonObjectFile(filePath, next);
755
755
  return next;
756
756
  }
757
- function getJsonPath(root, path50) {
757
+ function getJsonPath(root, path51) {
758
758
  let current = root;
759
- for (const segment of path50) {
759
+ for (const segment of path51) {
760
760
  if (typeof segment === "number") {
761
761
  if (!Array.isArray(current)) return void 0;
762
762
  current = current[segment];
@@ -767,13 +767,13 @@ function getJsonPath(root, path50) {
767
767
  }
768
768
  return current;
769
769
  }
770
- function setJsonPath(root, path50, value) {
771
- if (path50.length === 0) {
770
+ function setJsonPath(root, path51, value) {
771
+ if (path51.length === 0) {
772
772
  if (!isJsonObject(value)) throw new Error("Root config value must be an object");
773
773
  return value;
774
774
  }
775
- const parent = ensureJsonParent(root, path50);
776
- const leaf = lastPathSegment(path50);
775
+ const parent = ensureJsonParent(root, path51);
776
+ const leaf = lastPathSegment(path51);
777
777
  if (typeof leaf === "number") {
778
778
  if (!Array.isArray(parent)) throw new Error(`Cannot set numeric segment ${leaf} on non-array parent`);
779
779
  parent[leaf] = value;
@@ -783,10 +783,10 @@ function setJsonPath(root, path50, value) {
783
783
  }
784
784
  return root;
785
785
  }
786
- function removeJsonPath(root, path50) {
787
- if (path50.length === 0) return false;
788
- const parent = getJsonPath(root, path50.slice(0, -1));
789
- const leaf = lastPathSegment(path50);
786
+ function removeJsonPath(root, path51) {
787
+ if (path51.length === 0) return false;
788
+ const parent = getJsonPath(root, path51.slice(0, -1));
789
+ const leaf = lastPathSegment(path51);
790
790
  if (typeof leaf === "number") {
791
791
  if (!Array.isArray(parent) || leaf < 0 || leaf >= parent.length) return false;
792
792
  parent.splice(leaf, 1);
@@ -796,27 +796,27 @@ function removeJsonPath(root, path50) {
796
796
  delete parent[leaf];
797
797
  return true;
798
798
  }
799
- async function setJsonPathInFile(filePath, path50, value) {
800
- return updateJsonObjectFile(filePath, (config) => setJsonPath(config, path50, value));
799
+ async function setJsonPathInFile(filePath, path51, value) {
800
+ return updateJsonObjectFile(filePath, (config) => setJsonPath(config, path51, value));
801
801
  }
802
- async function removeJsonPathInFile(filePath, path50) {
802
+ async function removeJsonPathInFile(filePath, path51) {
803
803
  return updateJsonObjectFile(filePath, (config) => {
804
- removeJsonPath(config, path50);
804
+ removeJsonPath(config, path51);
805
805
  });
806
806
  }
807
807
  function isJsonObject(value) {
808
808
  return typeof value === "object" && value !== null && !Array.isArray(value);
809
809
  }
810
- function lastPathSegment(path50) {
811
- const segment = path50[path50.length - 1];
810
+ function lastPathSegment(path51) {
811
+ const segment = path51[path51.length - 1];
812
812
  if (segment === void 0) throw new Error("Invalid empty JSON path");
813
813
  return segment;
814
814
  }
815
- function ensureJsonParent(root, path50) {
815
+ function ensureJsonParent(root, path51) {
816
816
  let current = root;
817
- for (let i = 0; i < path50.length - 1; i += 1) {
818
- const segment = path50[i];
819
- const nextSegment = path50[i + 1];
817
+ for (let i = 0; i < path51.length - 1; i += 1) {
818
+ const segment = path51[i];
819
+ const nextSegment = path51[i + 1];
820
820
  if (segment === void 0) throw new Error("Invalid empty JSON path segment");
821
821
  const nextContainer = typeof nextSegment === "number" ? [] : {};
822
822
  if (typeof segment === "number") {
@@ -1772,11 +1772,11 @@ function validateAgainstSchema(value, schema) {
1772
1772
  walk(value, schema, "", errors);
1773
1773
  return { ok: errors.length === 0, errors };
1774
1774
  }
1775
- function walk(value, schema, path50, errors) {
1775
+ function walk(value, schema, path51, errors) {
1776
1776
  if (schema.enum !== void 0) {
1777
1777
  if (!schema.enum.some((e) => deepEqual(e, value))) {
1778
1778
  errors.push({
1779
- path: path50 || "<root>",
1779
+ path: path51 || "<root>",
1780
1780
  message: `expected one of ${JSON.stringify(schema.enum)}, got ${JSON.stringify(value)}`
1781
1781
  });
1782
1782
  return;
@@ -1785,7 +1785,7 @@ function walk(value, schema, path50, errors) {
1785
1785
  if (typeof schema.type === "string") {
1786
1786
  if (!checkType(value, schema.type)) {
1787
1787
  errors.push({
1788
- path: path50 || "<root>",
1788
+ path: path51 || "<root>",
1789
1789
  message: `expected ${schema.type}, got ${describeType(value)}`
1790
1790
  });
1791
1791
  return;
@@ -1795,20 +1795,20 @@ function walk(value, schema, path50, errors) {
1795
1795
  const obj = value;
1796
1796
  for (const req of schema.required ?? []) {
1797
1797
  if (!(req in obj)) {
1798
- errors.push({ path: joinPath(path50, req), message: "required property missing" });
1798
+ errors.push({ path: joinPath(path51, req), message: "required property missing" });
1799
1799
  }
1800
1800
  }
1801
1801
  if (schema.properties) {
1802
1802
  for (const [key, subSchema] of Object.entries(schema.properties)) {
1803
1803
  if (key in obj) {
1804
- walk(obj[key], subSchema, joinPath(path50, key), errors);
1804
+ walk(obj[key], subSchema, joinPath(path51, key), errors);
1805
1805
  }
1806
1806
  }
1807
1807
  }
1808
1808
  }
1809
1809
  if (schema.type === "array" && Array.isArray(value) && schema.items) {
1810
1810
  for (let i = 0; i < value.length; i++) {
1811
- walk(value[i], schema.items, `${path50}[${i}]`, errors);
1811
+ walk(value[i], schema.items, `${path51}[${i}]`, errors);
1812
1812
  }
1813
1813
  }
1814
1814
  }
@@ -2207,7 +2207,7 @@ function stripSingleLineComments(s) {
2207
2207
 
2208
2208
  // src/utils/sleep.ts
2209
2209
  function sleep(ms) {
2210
- return new Promise((resolve18) => setTimeout(resolve18, ms));
2210
+ return new Promise((resolve19) => setTimeout(resolve19, ms));
2211
2211
  }
2212
2212
 
2213
2213
  // src/utils/string.ts
@@ -7063,7 +7063,7 @@ var InMemoryAgentBridge = class {
7063
7063
  });
7064
7064
  }
7065
7065
  this.inflightGuards.add(correlationId);
7066
- return new Promise((resolve18, reject) => {
7066
+ return new Promise((resolve19, reject) => {
7067
7067
  const timer = setTimeout(() => {
7068
7068
  this.inflightGuards.delete(correlationId);
7069
7069
  this.pendingRequests.delete(correlationId);
@@ -7082,7 +7082,7 @@ var InMemoryAgentBridge = class {
7082
7082
  return;
7083
7083
  }
7084
7084
  this.pendingRequests.set(correlationId, {
7085
- resolve: resolve18,
7085
+ resolve: resolve19,
7086
7086
  reject,
7087
7087
  timer
7088
7088
  });
@@ -8412,7 +8412,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8412
8412
  this._loadCache.clear();
8413
8413
  }
8414
8414
  }
8415
- // ── Storage event helpers ───────────────────────────────────────────────────
8415
+ // ── Storage event helpers ───────────────────────────────────────────────────
8416
8416
  emitRead(sessionId, filePath, operation, outcome, durationMs, error) {
8417
8417
  this.events?.emit("storage.read", {
8418
8418
  sessionId,
@@ -8527,7 +8527,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8527
8527
  this.events,
8528
8528
  {
8529
8529
  resumed: true,
8530
- // Shard directory (sessions/<date>/) must match create() so the
8530
+ // Shard directory (sessions/<date>/) — must match create() so the
8531
8531
  // .summary.json sidecar lands next to the JSONL instead of the
8532
8532
  // sessions root (where summaryFor() would never find it).
8533
8533
  dir: path3.dirname(file),
@@ -8568,19 +8568,93 @@ var DefaultSessionStore = class _DefaultSessionStore {
8568
8568
  const raw = await fsp3.readFile(file, "utf8");
8569
8569
  const lines = raw.split("\n").filter((l) => l.trim());
8570
8570
  const events = [];
8571
+ let sessionStartEvent;
8572
+ let sessionEndEvent;
8573
+ let sessionModel;
8574
+ let sessionProvider;
8575
+ let sessionPendingToolUses;
8576
+ const messages = [];
8577
+ const openToolUses = /* @__PURE__ */ new Set();
8578
+ let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
8571
8579
  for (const line of lines) {
8572
8580
  try {
8573
8581
  const parsed = JSON.parse(line);
8574
8582
  if (parsed !== null && typeof parsed === "object" && typeof parsed.type === "string" && typeof parsed.ts === "string") {
8575
- events.push(parsed);
8583
+ const ev = parsed;
8584
+ events.push(ev);
8585
+ if (ev.type === "session_start" && !sessionStartEvent) {
8586
+ sessionStartEvent = ev;
8587
+ sessionModel = ev.model;
8588
+ sessionProvider = ev.provider;
8589
+ }
8590
+ if (ev.type === "session_end") {
8591
+ sessionEndEvent = ev;
8592
+ sessionPendingToolUses = ev.pendingToolUses;
8593
+ }
8594
+ if (ev.type === "user_input") {
8595
+ openToolUses.clear();
8596
+ messages.push({ role: "user", content: ev.content, ts: ev.ts });
8597
+ } else if (ev.type === "llm_response") {
8598
+ messages.push({ role: "assistant", content: ev.content, ts: ev.ts });
8599
+ for (const b of ev.content) {
8600
+ if (b.type === "tool_use") openToolUses.add(b.id);
8601
+ }
8602
+ usage = {
8603
+ input: usage.input + (ev.usage.input ?? 0),
8604
+ output: usage.output + (ev.usage.output ?? 0),
8605
+ cacheRead: (usage.cacheRead ?? 0) + (ev.usage.cacheRead ?? 0),
8606
+ cacheWrite: (usage.cacheWrite ?? 0) + (ev.usage.cacheWrite ?? 0)
8607
+ };
8608
+ } else if (ev.type === "tool_result") {
8609
+ if (!openToolUses.has(ev.id)) {
8610
+ this.events?.emit("session.damaged", {
8611
+ sessionId: id,
8612
+ detail: `Orphan tool_result "${ev.id}" has no matching tool_use`
8613
+ });
8614
+ continue;
8615
+ }
8616
+ openToolUses.delete(ev.id);
8617
+ const resultBlock = {
8618
+ type: "tool_result",
8619
+ tool_use_id: ev.id,
8620
+ content: typeof ev.content === "string" ? ev.content : JSON.stringify(ev.content),
8621
+ is_error: ev.isError
8622
+ };
8623
+ const last = messages[messages.length - 1];
8624
+ const lastIsToolResultUser = last?.role === "user" && Array.isArray(last.content) && last.content.every((b) => b.type === "tool_result");
8625
+ if (lastIsToolResultUser && Array.isArray(last.content)) {
8626
+ last.content.push(resultBlock);
8627
+ } else {
8628
+ messages.push({ role: "user", content: [resultBlock], ts: ev.ts });
8629
+ }
8630
+ }
8576
8631
  }
8577
8632
  } catch {
8578
8633
  }
8579
8634
  }
8580
- const meta = this.metaFromEvents(id, events);
8581
- const { messages, usage } = this.replay(events, id);
8635
+ if (openToolUses.size > 0) {
8636
+ this.events?.emit("session.damaged", {
8637
+ sessionId: id,
8638
+ detail: `${openToolUses.size} tool_use blocks without matching results - replay repaired`
8639
+ });
8640
+ }
8641
+ const repaired = repairToolUseAdjacency(messages);
8642
+ if (repaired.report.changed) {
8643
+ this.events?.emit("session.damaged", {
8644
+ sessionId: id,
8645
+ detail: `Repaired replay adjacency: removed ${repaired.report.removedToolUses.length} tool_use, ${repaired.report.removedToolResults.length} tool_result, ${repaired.report.removedMessages} empty messages`
8646
+ });
8647
+ }
8648
+ const meta = {
8649
+ id,
8650
+ startedAt: sessionStartEvent?.ts ?? (/* @__PURE__ */ new Date(0)).toISOString(),
8651
+ endedAt: sessionEndEvent?.ts,
8652
+ model: sessionModel,
8653
+ provider: sessionProvider,
8654
+ pendingToolUses: sessionPendingToolUses
8655
+ };
8582
8656
  const toolCallEnds = extractToolCallEnds(events);
8583
- const data = { metadata: meta, events, messages, usage, toolCallEnds };
8657
+ const data = { metadata: meta, events, messages: repaired.messages, usage, toolCallEnds };
8584
8658
  if (this._loadCache.size >= _DefaultSessionStore.LOAD_CACHE_MAX_ENTRIES) {
8585
8659
  const oldest = this._loadCache.keys().next().value;
8586
8660
  if (oldest !== void 0) {
@@ -8623,7 +8697,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8623
8697
  return [];
8624
8698
  }
8625
8699
  }
8626
- // ── Session index (_index.jsonl) ─────────────────────────────────────────
8700
+ // ── Session index (_index.jsonl) ─────────────────────────────────────────
8627
8701
  //
8628
8702
  // One JSON line per closed session, appended atomically on close().
8629
8703
  // When a session is deleted, a tombstone {action:"delete",id:"..."} is
@@ -8799,7 +8873,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8799
8873
  return [...childFileArrays.flat(), ...files];
8800
8874
  }
8801
8875
  /** Recursively collect session IDs from date-shard subdirectories.
8802
- * IDs include the date-prefix path (e.g. "2026-06-06/17-46-57Z_").
8876
+ * IDs include the date-prefix path (e.g. "2026-06-06/17-46-57Z_…").
8803
8877
  * Skips `.jsonl`/`.summary.json` root files, dot-files, and
8804
8878
  * sub-directories that belong to fleet/subagent sessions. */
8805
8879
  async collectSessionIds(dir, prefix = "", depth = 0) {
@@ -8854,7 +8928,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8854
8928
  }));
8855
8929
  });
8856
8930
  outcome = "failure";
8857
- errorMsg = "summary fallback \u2014 manifest rebuilt";
8931
+ errorMsg = "summary fallback \xE2\u20AC\u201D manifest rebuilt";
8858
8932
  this.emitRead(id, manifest, "summary", outcome, Date.now() - t0, errorMsg);
8859
8933
  return summary;
8860
8934
  } catch (err) {
@@ -9146,76 +9220,6 @@ var DefaultSessionStore = class _DefaultSessionStore {
9146
9220
  stream.destroy();
9147
9221
  }
9148
9222
  }
9149
- metaFromEvents(id, events) {
9150
- const start = events.find((e) => e.type === "session_start");
9151
- const end = events.findLast((e) => e.type === "session_end");
9152
- return {
9153
- id,
9154
- startedAt: start?.ts ?? (/* @__PURE__ */ new Date(0)).toISOString(),
9155
- endedAt: end?.ts,
9156
- model: start?.model,
9157
- provider: start?.provider,
9158
- pendingToolUses: end?.pendingToolUses
9159
- };
9160
- }
9161
- replay(events, sessionId = "unknown") {
9162
- const messages = [];
9163
- let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
9164
- const openToolUses = /* @__PURE__ */ new Set();
9165
- for (const e of events) {
9166
- if (e.type === "user_input") {
9167
- openToolUses.clear();
9168
- messages.push({ role: "user", content: e.content, ts: e.ts });
9169
- } else if (e.type === "llm_response") {
9170
- messages.push({ role: "assistant", content: e.content, ts: e.ts });
9171
- for (const b of e.content) {
9172
- if (b.type === "tool_use") openToolUses.add(b.id);
9173
- }
9174
- usage = {
9175
- input: usage.input + (e.usage.input ?? 0),
9176
- output: usage.output + (e.usage.output ?? 0),
9177
- cacheRead: (usage.cacheRead ?? 0) + (e.usage.cacheRead ?? 0),
9178
- cacheWrite: (usage.cacheWrite ?? 0) + (e.usage.cacheWrite ?? 0)
9179
- };
9180
- } else if (e.type === "tool_result") {
9181
- if (!openToolUses.has(e.id)) {
9182
- this.events?.emit("session.damaged", {
9183
- sessionId,
9184
- detail: `Orphan tool_result "${e.id}" has no matching tool_use`
9185
- });
9186
- continue;
9187
- }
9188
- openToolUses.delete(e.id);
9189
- const resultBlock = {
9190
- type: "tool_result",
9191
- tool_use_id: e.id,
9192
- content: typeof e.content === "string" ? e.content : JSON.stringify(e.content),
9193
- is_error: e.isError
9194
- };
9195
- const last = messages[messages.length - 1];
9196
- const lastIsToolResultUser = last?.role === "user" && Array.isArray(last.content) && last.content.every((b) => b.type === "tool_result");
9197
- if (lastIsToolResultUser && Array.isArray(last.content)) {
9198
- last.content.push(resultBlock);
9199
- } else {
9200
- messages.push({ role: "user", content: [resultBlock], ts: e.ts });
9201
- }
9202
- }
9203
- }
9204
- if (openToolUses.size > 0) {
9205
- this.events?.emit("session.damaged", {
9206
- sessionId,
9207
- detail: `${openToolUses.size} tool_use blocks without matching results - replay repaired`
9208
- });
9209
- }
9210
- const repaired = repairToolUseAdjacency(messages);
9211
- if (repaired.report.changed) {
9212
- this.events?.emit("session.damaged", {
9213
- sessionId,
9214
- detail: `Repaired replay adjacency: removed ${repaired.report.removedToolUses.length} tool_use, ${repaired.report.removedToolResults.length} tool_result, ${repaired.report.removedMessages} empty messages`
9215
- });
9216
- }
9217
- return { messages: repaired.messages, usage };
9218
- }
9219
9223
  };
9220
9224
  function extractToolCallEnds(events) {
9221
9225
  const result = [];
@@ -9274,7 +9278,7 @@ var FileSessionWriter = class _FileSessionWriter {
9274
9278
  /**
9275
9279
  * Lazy session_start/session_resumed init, shared by all appenders.
9276
9280
  * A single promise (not a boolean) so a second append racing the first
9277
- * can't push its event into the buffer BEFORE the first append's event
9281
+ * can't push its event into the buffer BEFORE the first append's event —
9278
9282
  * every appender awaits the same init and resumes in FIFO call order.
9279
9283
  */
9280
9284
  initPromise = null;
@@ -9287,24 +9291,24 @@ var FileSessionWriter = class _FileSessionWriter {
9287
9291
  lastAppendWarnAt = 0;
9288
9292
  secretScrubber;
9289
9293
  onCloseCb;
9290
- /** Implements SessionWriter.traceId propagated from ContextInit.traceId. */
9294
+ /** Implements SessionWriter.traceId — propagated from ContextInit.traceId. */
9291
9295
  traceId;
9292
- // ── Write buffer batches events to reduce per-event disk I/O ─────────
9296
+ // ── Write buffer — batches events to reduce per-event disk I/O ─────────
9293
9297
  //
9294
9298
  // Every append() pushes the scrubbed event into an in-memory buffer instead
9295
9299
  // of calling handle.appendFile() synchronously. The buffer flushes to disk
9296
9300
  // when it reaches FLUSH_SIZE events OR after FLUSH_INTERVAL_MS of inactivity.
9297
9301
  // This cuts the number of disk writes by ~95% without changing the on-disk
9298
- // format the JSONL is still one JSON object per line.
9302
+ // format — the JSONL is still one JSON object per line.
9299
9303
  writeBuffer = [];
9300
9304
  flushTimer = null;
9301
9305
  static FLUSH_INTERVAL_MS = 500;
9302
9306
  static FLUSH_SIZE = 50;
9303
- // ── Write serialization ─────────────────────────────────────────────────
9307
+ // ── Write serialization ─────────────────────────────────────────────────
9304
9308
  //
9305
9309
  // All disk writes are funneled through a FIFO promise chain. Without it,
9306
9310
  // a timer-driven flush racing an explicit flush()/close() issues two
9307
- // concurrent appendFile() calls on the shared O_APPEND handle the kernel
9311
+ // concurrent appendFile() calls on the shared O_APPEND handle — the kernel
9308
9312
  // may complete them out of order (chronology breaks) or, for large
9309
9313
  // batches, interleave partial writes (torn JSONL lines). The chain keeps
9310
9314
  // exactly one write in flight; failures don't break the chain.
@@ -9318,7 +9322,7 @@ var FileSessionWriter = class _FileSessionWriter {
9318
9322
  );
9319
9323
  return write;
9320
9324
  }
9321
- // ── Enriched summary tracking ──────────────────────────────────────────
9325
+ // ── Enriched summary tracking ──────────────────────────────────────────
9322
9326
  iterationCount = 0;
9323
9327
  toolCallCount = 0;
9324
9328
  toolErrorCount = 0;
@@ -9410,7 +9414,7 @@ var FileSessionWriter = class _FileSessionWriter {
9410
9414
  * (user_input, llm_response) call this so they survive SIGKILL/crash
9411
9415
  * instead of sitting in the in-memory buffer for up to 500ms.
9412
9416
  *
9413
- * Idempotent cancels any pending timer and writes whatever has
9417
+ * Idempotent — cancels any pending timer and writes whatever has
9414
9418
  * accumulated in the buffer. Safe to call even when the buffer
9415
9419
  * is empty (no-op).
9416
9420
  */
@@ -9433,7 +9437,7 @@ var FileSessionWriter = class _FileSessionWriter {
9433
9437
  /**
9434
9438
  * Flush all buffered events to disk as a single appendFile call.
9435
9439
  * Errors use the same throttled-warning pattern the old per-event
9436
- * append path used one warning every 5s with a suppressed count.
9440
+ * append path used — one warning every 5s with a suppressed count.
9437
9441
  * On failure the buffer is cleared (events are best-effort, same as
9438
9442
  * the old per-event path where a failed write was silently dropped).
9439
9443
  */
@@ -9616,7 +9620,7 @@ var FileSessionWriter = class _FileSessionWriter {
9616
9620
  /**
9617
9621
  * Truncate the session file to the checkpoint with the given promptIndex,
9618
9622
  * removing all events that follow it. Uses a single-pass byte-offset scan
9619
- * so post-checkpoint content is never read or parsed O(1) memory instead
9623
+ * so post-checkpoint content is never read or parsed — O(1) memory instead
9620
9624
  * of O(N) JSON.parse calls over the full file.
9621
9625
  */
9622
9626
  async truncateToCheckpoint(targetPromptIndex) {
@@ -9773,7 +9777,7 @@ var FileSessionWriter = class _FileSessionWriter {
9773
9777
  await fsp3.writeFile(this.filePath, record, "utf8");
9774
9778
  }
9775
9779
  /**
9776
- * Idea #1 write an in-flight marker. The agent loop should call
9780
+ * Idea #1 — write an in-flight marker. The agent loop should call
9777
9781
  * this at the start of each long-running operation; a matching
9778
9782
  * `clearInFlightMarker` follows on clean exit. A stale marker
9779
9783
  * (no end) is what `SessionRecovery.detectStale` looks for.
@@ -9790,9 +9794,9 @@ var FileSessionWriter = class _FileSessionWriter {
9790
9794
  this.events?.emit("in_flight.started", { context, ts: (/* @__PURE__ */ new Date()).toISOString() });
9791
9795
  }
9792
9796
  /**
9793
- * Idea #1 close the in-flight marker. Idempotent in spirit
9797
+ * Idea #1 — close the in-flight marker. Idempotent in spirit
9794
9798
  * (you can call it after a successful iteration even if you
9795
- * didn't open one this round) but the session log records
9799
+ * didn't open one this round) — but the session log records
9796
9800
  * every call so postmortem tooling can see "the agent finished
9797
9801
  * cleanly X times, then died without finishing Y".
9798
9802
  */
@@ -10405,6 +10409,20 @@ var DefaultMemoryStore = class {
10405
10409
  */
10406
10410
  persistBackup;
10407
10411
  backupDir;
10412
+ /**
10413
+ * Per-scope tracked byte sizes — incremented on `remember()`, decremented on
10414
+ * `forget()`, recalculated after `consolidate()`. Eliminates the redundant
10415
+ * readAll() call that previously checked the file size after every write.
10416
+ */
10417
+ _trackedByteSizes = {};
10418
+ /** Result cache for scoreRelevant() — keyed by scope + context hash, TTL 30s. */
10419
+ _scoreCache = /* @__PURE__ */ new Map();
10420
+ /**
10421
+ * Per-entry cached lowercase strings — computed once per scoreRelevant() call,
10422
+ * stored here so repeated scoring of the same entries avoids re-computation.
10423
+ * Cleared on every mutation (remember/forget/consolidate/clear).
10424
+ */
10425
+ _cachedLower = null;
10408
10426
  constructor(opts) {
10409
10427
  this.files = {
10410
10428
  "project-agents": opts.paths.inProjectAgentsFile,
@@ -10438,6 +10456,20 @@ var DefaultMemoryStore = class {
10438
10456
  }
10439
10457
  }
10440
10458
  }
10459
+ /**
10460
+ * Recalculate the tracked byte size for a scope by re-reading the file and
10461
+ * summing the serialized byte length of each line. Called after consolidate()
10462
+ * (which modifies the file) to keep the tracker accurate.
10463
+ */
10464
+ async _recalcTrackedByteSize(scope) {
10465
+ const raw = await this.backend.readAll(scope, this.files[scope]);
10466
+ let total = 0;
10467
+ for (const line of raw.split("\n")) {
10468
+ if (line.trim()) total += Buffer.byteLength(line, "utf8");
10469
+ }
10470
+ this._trackedByteSizes[scope] = total;
10471
+ return total;
10472
+ }
10441
10473
  async readAll() {
10442
10474
  const parts = [];
10443
10475
  for (const scope of ["project-agents", "project-memory", "user-memory"]) {
@@ -10538,6 +10570,7 @@ ${body.trim()}`);
10538
10570
  const t0 = Date.now();
10539
10571
  try {
10540
10572
  await this.backend.remember(scope, entry, filePath);
10573
+ this._scoreCache.clear();
10541
10574
  const dur = Date.now() - t0;
10542
10575
  this.events?.emit("storage.write", {
10543
10576
  sessionId: "~memory~",
@@ -10562,16 +10595,21 @@ ${body.trim()}`);
10562
10595
  });
10563
10596
  throw err;
10564
10597
  }
10565
- const raw = await this.backend.readAll(scope, this.files[scope]);
10566
- if (Buffer.byteLength(raw, "utf8") > MAX_BYTES_TOTAL) {
10598
+ let trackedSize = this._trackedByteSizes[scope];
10599
+ if (trackedSize === void 0) {
10600
+ trackedSize = await this._recalcTrackedByteSize(scope);
10601
+ }
10602
+ if (trackedSize > MAX_BYTES_TOTAL) {
10567
10603
  const removed = await this.backend.consolidate(scope, this.files[scope]);
10568
10604
  if (removed > 0) {
10569
10605
  this.events?.emit("memory.consolidated", {
10570
10606
  scope,
10571
10607
  removed
10572
10608
  });
10609
+ await this._recalcTrackedByteSize(scope);
10573
10610
  }
10574
10611
  }
10612
+ this._trackedByteSizes[scope] = (this._trackedByteSizes[scope] ?? 0) + Buffer.byteLength(JSON.stringify(entry), "utf8");
10575
10613
  await this.mirrorBackup(scope);
10576
10614
  this.events?.emit("memory.remembered", {
10577
10615
  scope,
@@ -10590,16 +10628,30 @@ ${body.trim()}`);
10590
10628
  async scoreRelevant(ctx, scope = "project-memory", limit = 8) {
10591
10629
  const all = await this.list(scope);
10592
10630
  if (all.length === 0) return [];
10631
+ const ctxHash = `${scope}|${ctx.currentTask}|${(ctx.activeSkills ?? []).join(",")}|${(ctx.toolNames ?? []).join(",")}`;
10632
+ const now = Date.now();
10633
+ const TTL_MS = 3e4;
10634
+ const cached = this._scoreCache.get(ctxHash);
10635
+ if (cached && cached.expiresAt > now && cached.entries === all) {
10636
+ return cached.scored.slice(0, Math.min(limit, 15));
10637
+ }
10593
10638
  const taskWords = ctx.currentTask.toLowerCase().split(/\s+/).filter((w) => w.length > 2);
10594
10639
  const skillWords = (ctx.activeSkills ?? []).flatMap((s) => s.split("-"));
10595
10640
  const toolWords = (ctx.toolNames ?? []).flatMap((t2) => t2.toLowerCase().split("_"));
10596
- const now = Date.now();
10641
+ this._cachedLower = /* @__PURE__ */ new WeakMap();
10597
10642
  const scored = [];
10598
10643
  for (const entry of all) {
10599
10644
  let score = 0;
10600
10645
  const reasons = [];
10601
- const textLower = entry.text.toLowerCase();
10602
- const tagsLower = (entry.tags ?? []).map((t2) => t2.toLowerCase());
10646
+ let cachedLower = this._cachedLower.get(entry);
10647
+ if (!cachedLower) {
10648
+ cachedLower = {
10649
+ textLower: entry.text.toLowerCase(),
10650
+ tagsLower: (entry.tags ?? []).map((t2) => t2.toLowerCase())
10651
+ };
10652
+ this._cachedLower.set(entry, cachedLower);
10653
+ }
10654
+ const { textLower, tagsLower } = cachedLower;
10603
10655
  let taskHits = 0;
10604
10656
  for (const w of taskWords) {
10605
10657
  if (textLower.includes(w)) {
@@ -10685,6 +10737,7 @@ ${body.trim()}`);
10685
10737
  const relevant = scored.filter(
10686
10738
  (s) => s.score >= threshold || s.priority === "critical" || s.priority === "high"
10687
10739
  );
10740
+ this._scoreCache.set(ctxHash, { entries: all, scored: relevant, expiresAt: now + TTL_MS });
10688
10741
  return relevant.slice(0, Math.min(limit, 15));
10689
10742
  }
10690
10743
  async forget(query, scope = "project-memory") {
@@ -10694,6 +10747,7 @@ ${body.trim()}`);
10694
10747
  let removed = 0;
10695
10748
  try {
10696
10749
  removed = await this.backend.forget(scope, query, filePath);
10750
+ this._scoreCache.clear();
10697
10751
  const dur = Date.now() - t0;
10698
10752
  this.events?.emit("storage.write", {
10699
10753
  sessionId: "~memory~",
@@ -10725,6 +10779,7 @@ ${body.trim()}`);
10725
10779
  removed
10726
10780
  });
10727
10781
  await this.mirrorBackup(scope);
10782
+ await this._recalcTrackedByteSize(scope);
10728
10783
  }
10729
10784
  return removed;
10730
10785
  });
@@ -10736,6 +10791,7 @@ ${body.trim()}`);
10736
10791
  let removed = 0;
10737
10792
  try {
10738
10793
  removed = await this.backend.consolidate(scope, filePath);
10794
+ this._scoreCache.clear();
10739
10795
  const dur = Date.now() - t0;
10740
10796
  this.events?.emit("storage.write", {
10741
10797
  sessionId: "~memory~",
@@ -10766,6 +10822,7 @@ ${body.trim()}`);
10766
10822
  removed
10767
10823
  });
10768
10824
  await this.mirrorBackup(scope);
10825
+ await this._recalcTrackedByteSize(scope);
10769
10826
  }
10770
10827
  });
10771
10828
  }
@@ -10776,6 +10833,7 @@ ${body.trim()}`);
10776
10833
  const t0 = Date.now();
10777
10834
  try {
10778
10835
  await this.backend.clear(scope, filePath);
10836
+ this._scoreCache.clear();
10779
10837
  const dur = Date.now() - t0;
10780
10838
  this.events?.emit("storage.write", {
10781
10839
  sessionId: "~memory~",
@@ -10802,6 +10860,7 @@ ${body.trim()}`);
10802
10860
  }
10803
10861
  this.events?.emit("memory.cleared", { scope });
10804
10862
  await this.mirrorBackup(scope);
10863
+ this._trackedByteSizes[scope] = 0;
10805
10864
  });
10806
10865
  return;
10807
10866
  }
@@ -11082,6 +11141,15 @@ function stripUnsafeInProjectFields(inProject, sourcePath, warn = (msg) => conso
11082
11141
  }
11083
11142
  return out;
11084
11143
  }
11144
+ function samePath(a, b) {
11145
+ let ra = path3.resolve(a);
11146
+ let rb = path3.resolve(b);
11147
+ if (process.platform === "win32" || process.platform === "darwin") {
11148
+ ra = ra.toLowerCase();
11149
+ rb = rb.toLowerCase();
11150
+ }
11151
+ return ra === rb;
11152
+ }
11085
11153
  function deepMerge2(base, patch) {
11086
11154
  const opts = { arrayMode: "concat-primitives" };
11087
11155
  if (envBoolOptional(process.env.WRONGSTACK_DEBUG_CONFIG)) {
@@ -11110,10 +11178,11 @@ var DefaultConfigLoader = class {
11110
11178
  }
11111
11179
  async load(opts = {}) {
11112
11180
  let cfg = { ...BEHAVIOR_DEFAULTS };
11181
+ const inProjectCollides = samePath(this.paths.inProjectConfig, this.paths.globalConfig) || samePath(this.paths.inProjectConfig, this.paths.projectLocalConfig);
11113
11182
  const [global, local, inProject] = await Promise.all([
11114
11183
  this.readJson(this.paths.globalConfig),
11115
11184
  this.readJson(this.paths.projectLocalConfig),
11116
- this.readJson(this.paths.inProjectConfig)
11185
+ inProjectCollides ? Promise.resolve({}) : this.readJson(this.paths.inProjectConfig)
11117
11186
  ]);
11118
11187
  cfg = deepMerge2(cfg, global);
11119
11188
  cfg = deepMerge2(cfg, local);
@@ -13313,8 +13382,8 @@ async function streamProviderToResponse(provider, req, signal, ctx, events, logg
13313
13382
  });
13314
13383
  await Promise.race([
13315
13384
  drainPromise,
13316
- new Promise((resolve18) => {
13317
- drainTimer = setTimeout(resolve18, STREAM_DRAIN_TIMEOUT_MS);
13385
+ new Promise((resolve19) => {
13386
+ drainTimer = setTimeout(resolve19, STREAM_DRAIN_TIMEOUT_MS);
13318
13387
  })
13319
13388
  ]);
13320
13389
  } finally {
@@ -13421,7 +13490,7 @@ async function runProviderWithRetry(opts) {
13421
13490
  description
13422
13491
  });
13423
13492
  }
13424
- await new Promise((resolve18, reject) => {
13493
+ await new Promise((resolve19, reject) => {
13425
13494
  let settled = false;
13426
13495
  const cleanup = () => {
13427
13496
  clearTimeout(t2);
@@ -13437,7 +13506,7 @@ async function runProviderWithRetry(opts) {
13437
13506
  if (settled) return;
13438
13507
  settled = true;
13439
13508
  cleanup();
13440
- resolve18();
13509
+ resolve19();
13441
13510
  }, delay);
13442
13511
  if (signal.aborted) {
13443
13512
  onAbort();
@@ -15952,13 +16021,13 @@ var SubagentBudget = class _SubagentBudget {
15952
16021
  if (!bus?.hasListenerFor("budget.threshold_reached")) {
15953
16022
  return Promise.resolve("stop");
15954
16023
  }
15955
- return new Promise((resolve18) => {
16024
+ return new Promise((resolve19) => {
15956
16025
  let resolved = false;
15957
16026
  const respond = (d) => {
15958
16027
  if (resolved) return;
15959
16028
  resolved = true;
15960
16029
  clearTimeout(fallback);
15961
- resolve18(d);
16030
+ resolve19(d);
15962
16031
  };
15963
16032
  const fallback = setTimeout(() => respond("stop"), _SubagentBudget.DECISION_TIMEOUT_MS);
15964
16033
  bus.emit("budget.threshold_reached", {
@@ -19863,7 +19932,7 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
19863
19932
  taskIds.map((id) => {
19864
19933
  const cached = this.completedResults.find((r) => r.taskId === id);
19865
19934
  if (cached) return cached;
19866
- return new Promise((resolve18, reject) => {
19935
+ return new Promise((resolve19, reject) => {
19867
19936
  const timeout = setTimeout(() => {
19868
19937
  this.off("task.completed", handler);
19869
19938
  reject(new Error(`awaitTasks timed out waiting for task "${id}"`));
@@ -19872,7 +19941,7 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
19872
19941
  if (result.taskId === id) {
19873
19942
  clearTimeout(timeout);
19874
19943
  this.off("task.completed", handler);
19875
- resolve18(result);
19944
+ resolve19(result);
19876
19945
  }
19877
19946
  };
19878
19947
  this.on("task.completed", handler);
@@ -20140,12 +20209,12 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
20140
20209
  }
20141
20210
  return new Promise((resolveDecision) => {
20142
20211
  let settled = false;
20143
- const resolve18 = (d) => {
20212
+ const resolve19 = (d) => {
20144
20213
  if (settled) return;
20145
20214
  settled = true;
20146
20215
  resolveDecision(d);
20147
20216
  };
20148
- const fallback = setTimeout(() => resolve18("stop"), DECISION_TIMEOUT_MS);
20217
+ const fallback = setTimeout(() => resolve19("stop"), DECISION_TIMEOUT_MS);
20149
20218
  budget._events?.emit("budget.threshold_reached", {
20150
20219
  kind: "timeout",
20151
20220
  used,
@@ -20161,11 +20230,11 @@ var DefaultMultiAgentCoordinator = class _DefaultMultiAgentCoordinator extends E
20161
20230
  // disagreeing, resolves as a stop). Async grants still resolve.
20162
20231
  extend: (extra) => {
20163
20232
  clearTimeout(fallback);
20164
- queueMicrotask(() => resolve18({ extend: extra }));
20233
+ queueMicrotask(() => resolve19({ extend: extra }));
20165
20234
  },
20166
20235
  deny: () => {
20167
20236
  clearTimeout(fallback);
20168
- resolve18("stop");
20237
+ resolve19("stop");
20169
20238
  }
20170
20239
  });
20171
20240
  });
@@ -23411,11 +23480,11 @@ var Director = class _Director {
23411
23480
  if (cached) return cached;
23412
23481
  const existing = this.taskWaiters.get(id);
23413
23482
  if (existing) return existing.promise;
23414
- let resolve18;
23483
+ let resolve19;
23415
23484
  const promise = new Promise((res) => {
23416
- resolve18 = res;
23485
+ resolve19 = res;
23417
23486
  });
23418
- this.taskWaiters.set(id, { promise, resolve: resolve18 });
23487
+ this.taskWaiters.set(id, { promise, resolve: resolve19 });
23419
23488
  return promise;
23420
23489
  })
23421
23490
  );
@@ -23811,7 +23880,7 @@ function createDelegateTool(opts) {
23811
23880
  subagentId
23812
23881
  });
23813
23882
  const dir = director;
23814
- const result = await new Promise((resolve18) => {
23883
+ const result = await new Promise((resolve19) => {
23815
23884
  let settled = false;
23816
23885
  let timer;
23817
23886
  const finish = (value) => {
@@ -23821,7 +23890,7 @@ function createDelegateTool(opts) {
23821
23890
  offTool();
23822
23891
  offIter();
23823
23892
  offProgress();
23824
- resolve18(value);
23893
+ resolve19(value);
23825
23894
  };
23826
23895
  const arm = () => {
23827
23896
  if (timer) clearTimeout(timer);
@@ -25592,9 +25661,9 @@ var AISpecBuilder = class {
25592
25661
  if (!this.sessionPath) return;
25593
25662
  try {
25594
25663
  const fsp26 = await import('fs/promises');
25595
- const path50 = await import('path');
25664
+ const path51 = await import('path');
25596
25665
  const { atomicWrite: atomicWrite2 } = await Promise.resolve().then(() => (init_atomic_write(), atomic_write_exports));
25597
- await fsp26.mkdir(path50.dirname(this.sessionPath), { recursive: true });
25666
+ await fsp26.mkdir(path51.dirname(this.sessionPath), { recursive: true });
25598
25667
  await atomicWrite2(this.sessionPath, JSON.stringify(this.session, null, 2));
25599
25668
  } catch {
25600
25669
  }
@@ -26321,15 +26390,15 @@ function computeCriticalPath(graph, _topoOrder, blockedByMap) {
26321
26390
  maxId = id;
26322
26391
  }
26323
26392
  }
26324
- const path50 = [];
26393
+ const path51 = [];
26325
26394
  let current = maxId;
26326
26395
  const visited = /* @__PURE__ */ new Set();
26327
26396
  while (current && !visited.has(current)) {
26328
26397
  visited.add(current);
26329
- path50.unshift(current);
26398
+ path51.unshift(current);
26330
26399
  current = prev.get(current) ?? null;
26331
26400
  }
26332
- return path50;
26401
+ return path51;
26333
26402
  }
26334
26403
  function computeParallelGroups(graph, blockedByMap) {
26335
26404
  const groups = [];
@@ -27152,9 +27221,9 @@ var DefaultHealthRegistry = class {
27152
27221
  }
27153
27222
  async runOne(check) {
27154
27223
  let timer = null;
27155
- const timeout = new Promise((resolve18) => {
27224
+ const timeout = new Promise((resolve19) => {
27156
27225
  timer = setTimeout(
27157
- () => resolve18({ status: "unhealthy", detail: `timeout after ${this.timeoutMs}ms` }),
27226
+ () => resolve19({ status: "unhealthy", detail: `timeout after ${this.timeoutMs}ms` }),
27158
27227
  this.timeoutMs
27159
27228
  );
27160
27229
  });
@@ -27337,7 +27406,7 @@ async function startMetricsServer(opts) {
27337
27406
  const tls = opts.tls;
27338
27407
  const useHttps = !!(tls?.cert && tls?.key);
27339
27408
  const host = opts.host ?? "127.0.0.1";
27340
- const path50 = opts.path ?? "/metrics";
27409
+ const path51 = opts.path ?? "/metrics";
27341
27410
  const healthPath = opts.healthPath ?? "/healthz";
27342
27411
  const healthRegistry = opts.healthRegistry;
27343
27412
  const listener = (req, res) => {
@@ -27347,7 +27416,7 @@ async function startMetricsServer(opts) {
27347
27416
  return;
27348
27417
  }
27349
27418
  const url = req.url.split("?")[0];
27350
- if (url === path50) {
27419
+ if (url === path51) {
27351
27420
  let body;
27352
27421
  try {
27353
27422
  body = renderPrometheus(opts.sink.snapshot());
@@ -27393,14 +27462,14 @@ async function startMetricsServer(opts) {
27393
27462
  const { createServer } = await import('http');
27394
27463
  server = createServer(listener);
27395
27464
  }
27396
- await new Promise((resolve18, reject) => {
27465
+ await new Promise((resolve19, reject) => {
27397
27466
  const onError = (err) => {
27398
27467
  server.off("listening", onListening);
27399
27468
  reject(err);
27400
27469
  };
27401
27470
  const onListening = () => {
27402
27471
  server.off("error", onError);
27403
- resolve18();
27472
+ resolve19();
27404
27473
  };
27405
27474
  server.once("error", onError);
27406
27475
  server.once("listening", onListening);
@@ -27411,9 +27480,9 @@ async function startMetricsServer(opts) {
27411
27480
  const protocol = useHttps ? "https" : "http";
27412
27481
  return {
27413
27482
  port: boundPort,
27414
- url: `${protocol}://${host}:${boundPort}${path50}`,
27415
- close: () => new Promise((resolve18, reject) => {
27416
- server.close((err) => err ? reject(err) : resolve18());
27483
+ url: `${protocol}://${host}:${boundPort}${path51}`,
27484
+ close: () => new Promise((resolve19, reject) => {
27485
+ server.close((err) => err ? reject(err) : resolve19());
27417
27486
  })
27418
27487
  };
27419
27488
  }
@@ -30125,6 +30194,7 @@ var AgentStatusTracker = class {
30125
30194
  leaderCtxPct;
30126
30195
  leaderModel;
30127
30196
  leaderPartialText = "";
30197
+ leaderStartedAt;
30128
30198
  unsubscribers = [];
30129
30199
  onUpdate;
30130
30200
  sweepTimer = null;
@@ -30141,7 +30211,11 @@ var AgentStatusTracker = class {
30141
30211
  }
30142
30212
  start() {
30143
30213
  this.unsubscribers.push(
30144
- this.events.onPattern("agent.run.started", () => {
30214
+ this.events.onPattern("agent.run.started", (_event, payload) => {
30215
+ const p = payload;
30216
+ this.markLeaderStarted(p?.at);
30217
+ this.captureLeaderContext(p?.ctx);
30218
+ if (p?.model) this.leaderModel = p.model;
30145
30219
  this.leaderStatus = "running";
30146
30220
  this.leaderIterations++;
30147
30221
  this.flush();
@@ -30149,25 +30223,36 @@ var AgentStatusTracker = class {
30149
30223
  );
30150
30224
  this.unsubscribers.push(
30151
30225
  this.events.onPattern("iteration.started", (_e, payload) => {
30152
- const ctx = payload?.ctx;
30153
- if (!ctx) return;
30154
- if (ctx.model) this.leaderModel = ctx.model;
30155
- if (typeof ctx.tokenCount === "number" && typeof ctx.maxContext === "number" && ctx.maxContext > 0) {
30156
- this.leaderCtxPct = Math.round(ctx.tokenCount / ctx.maxContext * 100);
30226
+ const p = payload;
30227
+ const ctx = p?.ctx;
30228
+ this.markLeaderStarted();
30229
+ this.leaderStatus = "running";
30230
+ if (typeof p?.index === "number") {
30231
+ this.leaderIterations = Math.max(this.leaderIterations, p.index + 1);
30232
+ }
30233
+ if (!ctx) {
30234
+ this.flush();
30235
+ return;
30157
30236
  }
30237
+ this.captureLeaderContext(ctx);
30158
30238
  this.flush();
30159
30239
  })
30160
30240
  );
30161
30241
  this.unsubscribers.push(
30162
- this.events.onPattern("agent.run.completed", () => {
30163
- this.leaderStatus = "idle";
30242
+ this.events.onPattern("agent.run.completed", (_event, payload) => {
30243
+ const p = payload;
30244
+ this.captureLeaderContext(p?.ctx);
30245
+ this.leaderStatus = p?.status === "failed" ? "error" : "idle";
30164
30246
  this.leaderCurrentTool = void 0;
30165
30247
  this.leaderPartialText = "";
30248
+ if (this.leaderStatus === "idle") this.leaderStartedAt = void 0;
30166
30249
  this.flush();
30167
30250
  })
30168
30251
  );
30169
30252
  this.unsubscribers.push(
30170
- this.events.onPattern("agent.run.error", () => {
30253
+ this.events.onPattern("agent.run.error", (_event, payload) => {
30254
+ const p = payload;
30255
+ this.captureLeaderContext(p?.ctx);
30171
30256
  this.leaderStatus = "error";
30172
30257
  this.leaderCurrentTool = void 0;
30173
30258
  this.leaderPartialText = "";
@@ -30178,6 +30263,7 @@ var AgentStatusTracker = class {
30178
30263
  this.events.onPattern("tool.started", (_event, payload) => {
30179
30264
  const p = payload;
30180
30265
  if (p?.name) {
30266
+ this.markLeaderStarted();
30181
30267
  this.leaderCurrentTool = p.name;
30182
30268
  this.leaderToolCalls++;
30183
30269
  }
@@ -30193,12 +30279,14 @@ var AgentStatusTracker = class {
30193
30279
  );
30194
30280
  this.unsubscribers.push(
30195
30281
  this.events.onPattern("brain.ask_human", () => {
30282
+ this.markLeaderStarted();
30196
30283
  this.leaderStatus = "waiting_user";
30197
30284
  this.flush();
30198
30285
  })
30199
30286
  );
30200
30287
  this.unsubscribers.push(
30201
30288
  this.events.onPattern("llm.stream_started", () => {
30289
+ this.markLeaderStarted();
30202
30290
  this.leaderStatus = "streaming";
30203
30291
  this.leaderPartialText = "";
30204
30292
  this.flush();
@@ -30206,14 +30294,42 @@ var AgentStatusTracker = class {
30206
30294
  );
30207
30295
  this.unsubscribers.push(
30208
30296
  this.events.onPattern("provider.text_delta", (_e, payload) => {
30209
- const text = payload?.text;
30297
+ const p = payload;
30298
+ const text = p?.text;
30210
30299
  if (!text) return;
30300
+ this.markLeaderStarted();
30301
+ this.captureLeaderContext(p?.ctx);
30211
30302
  this.leaderStatus = "streaming";
30212
30303
  const next = this.leaderPartialText + text;
30213
30304
  this.leaderPartialText = next.length > PARTIAL_TEXT_CAP ? next.slice(next.length - PARTIAL_TEXT_CAP) : next;
30214
30305
  this.schedulePartialFlush();
30215
30306
  })
30216
30307
  );
30308
+ this.unsubscribers.push(
30309
+ this.events.onPattern("provider.response", (_e, payload) => {
30310
+ const p = payload;
30311
+ this.captureLeaderContext(p?.ctx);
30312
+ this.flush();
30313
+ })
30314
+ );
30315
+ this.unsubscribers.push(
30316
+ this.events.onPattern("provider.fallback", (_e, payload) => {
30317
+ const p = payload;
30318
+ if (p?.to?.model) {
30319
+ this.leaderModel = p.to.providerId ? `${p.to.providerId}/${p.to.model}` : p.to.model;
30320
+ this.flush();
30321
+ }
30322
+ })
30323
+ );
30324
+ this.unsubscribers.push(
30325
+ this.events.onPattern("ctx.pct", (_e, payload) => {
30326
+ const p = payload;
30327
+ if (typeof p?.load === "number" && Number.isFinite(p.load)) {
30328
+ this.leaderCtxPct = Math.round(p.load * 100);
30329
+ this.flush();
30330
+ }
30331
+ })
30332
+ );
30217
30333
  this.unsubscribers.push(
30218
30334
  this.events.onPattern("token.accounted", (_e, payload) => {
30219
30335
  const p = payload;
@@ -30227,7 +30343,8 @@ var AgentStatusTracker = class {
30227
30343
  const touch = (id) => {
30228
30344
  let entry = this.agents.get(id);
30229
30345
  if (!entry) {
30230
- entry = { id, name: id, status: "idle", iterations: 0, toolCalls: 0, lastActivityAt: (/* @__PURE__ */ new Date()).toISOString() };
30346
+ const now = (/* @__PURE__ */ new Date()).toISOString();
30347
+ entry = { id, name: id, status: "idle", iterations: 0, toolCalls: 0, startedAt: now, lastActivityAt: now };
30231
30348
  this.agents.set(id, entry);
30232
30349
  }
30233
30350
  entry.lastActivityAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -30240,6 +30357,7 @@ var AgentStatusTracker = class {
30240
30357
  const entry = touch(p.subagentId);
30241
30358
  entry.name = p.name?.trim() || entry.name;
30242
30359
  if (p.model) entry.model = p.model;
30360
+ if (!entry.startedAt) entry.startedAt = (/* @__PURE__ */ new Date()).toISOString();
30243
30361
  entry.status = "running";
30244
30362
  this.flush();
30245
30363
  })
@@ -30259,6 +30377,7 @@ var AgentStatusTracker = class {
30259
30377
  if (!p?.subagentId) return;
30260
30378
  const entry = touch(p.subagentId);
30261
30379
  entry.status = "running";
30380
+ if (!entry.startedAt) entry.startedAt = (/* @__PURE__ */ new Date()).toISOString();
30262
30381
  entry.iterations++;
30263
30382
  this.flush();
30264
30383
  })
@@ -30269,6 +30388,7 @@ var AgentStatusTracker = class {
30269
30388
  if (!p?.subagentId) return;
30270
30389
  const entry = touch(p.subagentId);
30271
30390
  entry.status = "running";
30391
+ if (!entry.startedAt) entry.startedAt = (/* @__PURE__ */ new Date()).toISOString();
30272
30392
  entry.currentTool = p.name;
30273
30393
  entry.toolCalls++;
30274
30394
  this.flush();
@@ -30280,6 +30400,7 @@ var AgentStatusTracker = class {
30280
30400
  if (!p?.subagentId) return;
30281
30401
  const entry = touch(p.subagentId);
30282
30402
  entry.status = "running";
30403
+ if (!entry.startedAt) entry.startedAt = (/* @__PURE__ */ new Date()).toISOString();
30283
30404
  if (typeof p.iteration === "number") entry.iterations = p.iteration;
30284
30405
  if (typeof p.toolCalls === "number") entry.toolCalls = p.toolCalls;
30285
30406
  if (typeof p.costUsd === "number") entry.costUsd = p.costUsd;
@@ -30367,6 +30488,7 @@ var AgentStatusTracker = class {
30367
30488
  const leaderEntry = {
30368
30489
  id: "leader",
30369
30490
  name: this.leaderName,
30491
+ startedAt: this.leaderStartedAt,
30370
30492
  status: this.leaderStatus,
30371
30493
  currentTool: this.leaderCurrentTool,
30372
30494
  iterations: this.leaderIterations,
@@ -30392,6 +30514,23 @@ var AgentStatusTracker = class {
30392
30514
  }
30393
30515
  }).catch(() => void 0);
30394
30516
  }
30517
+ markLeaderStarted(startedAt) {
30518
+ if (this.leaderStartedAt && (this.leaderStatus === "running" || this.leaderStatus === "streaming" || this.leaderStatus === "waiting_user")) {
30519
+ return;
30520
+ }
30521
+ this.leaderStartedAt = startedAt ?? (/* @__PURE__ */ new Date()).toISOString();
30522
+ }
30523
+ captureLeaderContext(ctx) {
30524
+ if (typeof ctx !== "object" || ctx === null) return;
30525
+ const c = ctx;
30526
+ if (typeof c.model === "string" && c.model.length > 0) this.leaderModel = c.model;
30527
+ const metaLimit = c.meta?.["effectiveMaxContext"];
30528
+ const providerMax = c.provider?.capabilities?.maxContext;
30529
+ const maxContext = typeof metaLimit === "number" && metaLimit > 0 ? metaLimit : typeof providerMax === "number" && providerMax > 0 ? providerMax : void 0;
30530
+ if (typeof c.lastRequestTokens === "number" && c.lastRequestTokens > 0 && maxContext !== void 0) {
30531
+ this.leaderCtxPct = Math.round(c.lastRequestTokens / maxContext * 100);
30532
+ }
30533
+ }
30395
30534
  };
30396
30535
  var INSTANCES_FILE = "webui-instances.json";
30397
30536
  var DISCOVERY_TTL_MS = 2500;
@@ -32066,7 +32205,7 @@ var GlobalMailbox = class {
32066
32205
  /**
32067
32206
  * @param projectDir — `~/.wrongstack/projects/<slug>/`
32068
32207
  * @param events — optional EventBus for real-time TUI/WebUI notifications
32069
- * @param hqPublisher — optional HQ publisher for cross-project telemetry
32208
+ * @param hqPublisher — optional HQ publisher, or getter, for cross-project telemetry
32070
32209
  */
32071
32210
  constructor(projectDir, events, hqPublisher) {
32072
32211
  this.messagePath = path3.join(projectDir, MAILBOX_FILE);
@@ -32078,15 +32217,19 @@ var GlobalMailbox = class {
32078
32217
  get hqMailboxId() {
32079
32218
  return `${path3.basename(path3.dirname(this.messagePath))}:mailbox`;
32080
32219
  }
32220
+ get hqPublisher() {
32221
+ return typeof this._hqPublisher === "function" ? this._hqPublisher() : this._hqPublisher;
32222
+ }
32081
32223
  publishHqMailboxEvent(input) {
32082
32224
  try {
32083
- this._hqPublisher?.publishMailboxEvent(input);
32225
+ this.hqPublisher?.publishMailboxEvent(input);
32084
32226
  } catch {
32085
32227
  }
32086
32228
  }
32087
32229
  publishHqMailboxSnapshot() {
32088
- if (this._hqPublisher === void 0) return;
32089
- void this._hqPublisher.publishMailboxSnapshot(this, { mailboxId: this.hqMailboxId }).catch(() => {
32230
+ const publisher = this.hqPublisher;
32231
+ if (publisher === void 0) return;
32232
+ void publisher.publishMailboxSnapshot(this, { mailboxId: this.hqMailboxId }).catch(() => {
32090
32233
  });
32091
32234
  }
32092
32235
  // ── Messages ────────────────────────────────────────────────────────────
@@ -33161,6 +33304,7 @@ function toAgentSummary(a) {
33161
33304
  iterations: a.iterations,
33162
33305
  toolCalls: a.toolCalls,
33163
33306
  lastActivityAt: a.lastActivityAt,
33307
+ ...a.startedAt !== void 0 ? { startedAt: a.startedAt } : {},
33164
33308
  ...a.currentTool !== void 0 ? { currentTool: a.currentTool } : {},
33165
33309
  ...a.costUsd !== void 0 ? { costUsd: a.costUsd } : {},
33166
33310
  ...a.tokensIn !== void 0 ? { tokensIn: a.tokensIn } : {},
@@ -33186,8 +33330,11 @@ function startSessionTelemetryBridge(opts) {
33186
33330
  ...opts.globalRoot !== void 0 ? { globalRoot: opts.globalRoot } : {}
33187
33331
  });
33188
33332
  const sessionFile = path3.join(wpaths.projectSessions, `${opts.sessionId}.jsonl`);
33189
- let agents = [];
33190
- let lastActivityAt = startedAt;
33333
+ let agents = (opts.initialAgents ?? []).map(toAgentSummary);
33334
+ let lastActivityAt = agents.reduce(
33335
+ (latest, agent) => agent.lastActivityAt > latest ? agent.lastActivityAt : latest,
33336
+ startedAt
33337
+ );
33191
33338
  let lastSnapshotHash = "";
33192
33339
  let disposed = false;
33193
33340
  function buildSnapshot() {
@@ -34495,7 +34642,7 @@ var SecurityScannerOrchestrator = class {
34495
34642
  message: errAsErr.message,
34496
34643
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
34497
34644
  }));
34498
- await new Promise((resolve18) => setTimeout(resolve18, delay));
34645
+ await new Promise((resolve19) => setTimeout(resolve19, delay));
34499
34646
  return this.completeWithRetry(provider, request, abortController, attempt + 1);
34500
34647
  }
34501
34648
  }
@@ -35628,12 +35775,12 @@ var BrainDecisionQueue = class {
35628
35775
  options: request.options,
35629
35776
  rationale: "Decision escalated to human authority."
35630
35777
  };
35631
- const pending = new Promise((resolve18) => {
35632
- const entry = { request, resolve: resolve18 };
35778
+ const pending = new Promise((resolve19) => {
35779
+ const entry = { request, resolve: resolve19 };
35633
35780
  if (this.opts.timeoutMs && this.opts.timeoutMs > 0) {
35634
35781
  entry.timer = setTimeout(() => {
35635
35782
  this.pending.delete(request.id);
35636
- resolve18({ type: "deny", reason: "Brain human decision timed out." });
35783
+ resolve19({ type: "deny", reason: "Brain human decision timed out." });
35637
35784
  }, this.opts.timeoutMs);
35638
35785
  }
35639
35786
  this.pending.set(request.id, entry);
@@ -39247,17 +39394,17 @@ ${input.detail}`
39247
39394
  _waitForDagProgress(timeoutMs) {
39248
39395
  const before = this._dagProgressKey();
39249
39396
  if (this.dag.isDone()) return Promise.resolve();
39250
- return new Promise((resolve18) => {
39397
+ return new Promise((resolve19) => {
39251
39398
  let off;
39252
39399
  const timer = setTimeout(() => {
39253
39400
  off?.();
39254
- resolve18();
39401
+ resolve19();
39255
39402
  }, timeoutMs);
39256
39403
  off = this.dag.onEvent(() => {
39257
39404
  if (this._dagProgressKey() === before) return;
39258
39405
  clearTimeout(timer);
39259
39406
  off?.();
39260
- resolve18();
39407
+ resolve19();
39261
39408
  });
39262
39409
  });
39263
39410
  }
@@ -39788,6 +39935,186 @@ function createAgentMonitorService(opts) {
39788
39935
  return new AgentMonitorService(opts);
39789
39936
  }
39790
39937
 
39938
+ // src/coordination/adaptive-concurrency.ts
39939
+ var DEFAULT_CONFIG = Object.freeze({
39940
+ enabled: false,
39941
+ minConcurrent: 1,
39942
+ maxConcurrent: 16,
39943
+ decreaseFactor: 0.5,
39944
+ successThreshold: 10,
39945
+ recoveryIntervalMs: 3e4
39946
+ });
39947
+ var AdaptiveConcurrencyController = class {
39948
+ config;
39949
+ state;
39950
+ disposers = [];
39951
+ stateChangeHandlers = [];
39952
+ constructor(fleetBus, setMaxConcurrent, config = {}, onStateChange) {
39953
+ this.config = {
39954
+ enabled: config.enabled ?? DEFAULT_CONFIG.enabled,
39955
+ minConcurrent: config.minConcurrent ?? DEFAULT_CONFIG.minConcurrent,
39956
+ maxConcurrent: config.maxConcurrent ?? DEFAULT_CONFIG.maxConcurrent,
39957
+ decreaseFactor: config.decreaseFactor ?? DEFAULT_CONFIG.decreaseFactor,
39958
+ successThreshold: config.successThreshold ?? DEFAULT_CONFIG.successThreshold,
39959
+ recoveryIntervalMs: config.recoveryIntervalMs ?? DEFAULT_CONFIG.recoveryIntervalMs
39960
+ };
39961
+ this.state = {
39962
+ current: this.config.maxConcurrent,
39963
+ min: this.config.minConcurrent,
39964
+ max: this.config.maxConcurrent,
39965
+ consecutiveSuccesses: 0,
39966
+ consecutiveFailures: 0,
39967
+ totalDecreases: 0,
39968
+ totalIncreases: 0,
39969
+ enabled: this.config.enabled
39970
+ };
39971
+ if (onStateChange) {
39972
+ this.stateChangeHandlers.push(onStateChange);
39973
+ }
39974
+ if (this.config.enabled) {
39975
+ setMaxConcurrent(this.state.current);
39976
+ }
39977
+ this.setupEventHandlers(fleetBus, setMaxConcurrent);
39978
+ }
39979
+ setupEventHandlers(fleetBus, setMaxConcurrent) {
39980
+ if (!this.config.enabled) return;
39981
+ const off = fleetBus.onAny((event) => {
39982
+ if (!this.config.enabled) return;
39983
+ if (event.type === "error" || event.type === "provider_error") {
39984
+ const payload = event.payload;
39985
+ if (payload?.status === 429 || payload?.code === "rate_limit_error" || payload?.kind === "rate_limit") {
39986
+ this.handleRateLimit(setMaxConcurrent);
39987
+ }
39988
+ }
39989
+ });
39990
+ this.disposers.push(off);
39991
+ }
39992
+ /**
39993
+ * Handle a rate limit (429) error - decrease concurrency
39994
+ */
39995
+ handleRateLimit(setMaxConcurrent) {
39996
+ if (this.state.current <= this.config.minConcurrent) {
39997
+ this.state.consecutiveFailures++;
39998
+ this.state.consecutiveSuccesses = 0;
39999
+ this.notifyStateChange();
40000
+ return;
40001
+ }
40002
+ const newConcurrent = Math.max(
40003
+ this.config.minConcurrent,
40004
+ Math.floor(this.state.current * this.config.decreaseFactor)
40005
+ );
40006
+ if (newConcurrent < this.state.current) {
40007
+ const previousConcurrent = this.state.current;
40008
+ this.state.current = newConcurrent;
40009
+ this.state.consecutiveFailures++;
40010
+ this.state.consecutiveSuccesses = 0;
40011
+ this.state.totalDecreases++;
40012
+ setMaxConcurrent(this.state.current);
40013
+ this.notifyStateChange();
40014
+ console.log(
40015
+ JSON.stringify({
40016
+ level: "warn",
40017
+ event: "adaptive_concurrency.decreased",
40018
+ reason: "rate_limit",
40019
+ previousConcurrent,
40020
+ newConcurrent: this.state.current,
40021
+ decreaseFactor: this.config.decreaseFactor,
40022
+ totalDecreases: this.state.totalDecreases
40023
+ })
40024
+ );
40025
+ }
40026
+ }
40027
+ /**
40028
+ * Force a decrease (e.g., manual trigger or other error types)
40029
+ */
40030
+ decrease(target) {
40031
+ if (!this.config.enabled) return;
40032
+ const newConcurrent = target ?? Math.max(
40033
+ this.config.minConcurrent,
40034
+ Math.floor(this.state.current * this.config.decreaseFactor)
40035
+ );
40036
+ if (newConcurrent < this.state.current) {
40037
+ const previousConcurrent = this.state.current;
40038
+ this.state.current = newConcurrent;
40039
+ this.state.consecutiveSuccesses = 0;
40040
+ this.state.totalDecreases++;
40041
+ this.notifyStateChange();
40042
+ console.log(
40043
+ JSON.stringify({
40044
+ level: "warn",
40045
+ event: "adaptive_concurrency.decreased",
40046
+ reason: "manual",
40047
+ previousConcurrent,
40048
+ newConcurrent: this.state.current,
40049
+ totalDecreases: this.state.totalDecreases
40050
+ })
40051
+ );
40052
+ }
40053
+ }
40054
+ /**
40055
+ * Get the current state
40056
+ */
40057
+ getState() {
40058
+ return { ...this.state };
40059
+ }
40060
+ /**
40061
+ * Update configuration at runtime
40062
+ */
40063
+ updateConfig(config) {
40064
+ if (config.enabled !== void 0) {
40065
+ this.config.enabled = config.enabled;
40066
+ }
40067
+ if (config.minConcurrent !== void 0) {
40068
+ this.config.minConcurrent = config.minConcurrent;
40069
+ }
40070
+ if (config.maxConcurrent !== void 0) {
40071
+ this.config.maxConcurrent = config.maxConcurrent;
40072
+ }
40073
+ if (config.decreaseFactor !== void 0) {
40074
+ this.config.decreaseFactor = config.decreaseFactor;
40075
+ }
40076
+ if (config.successThreshold !== void 0) {
40077
+ this.config.successThreshold = config.successThreshold;
40078
+ }
40079
+ if (config.recoveryIntervalMs !== void 0) {
40080
+ this.config.recoveryIntervalMs = config.recoveryIntervalMs;
40081
+ }
40082
+ this.state.current = Math.max(this.config.minConcurrent, Math.min(this.state.current, this.config.maxConcurrent));
40083
+ this.state.enabled = this.config.enabled;
40084
+ this.state.min = this.config.minConcurrent;
40085
+ this.state.max = this.config.maxConcurrent;
40086
+ this.notifyStateChange();
40087
+ }
40088
+ /**
40089
+ * Dispose of the controller and clean up event listeners
40090
+ */
40091
+ dispose() {
40092
+ for (const dispose of this.disposers) {
40093
+ dispose();
40094
+ }
40095
+ this.disposers.length = 0;
40096
+ this.stateChangeHandlers = [];
40097
+ }
40098
+ notifyStateChange() {
40099
+ const state = this.getState();
40100
+ for (const handler of this.stateChangeHandlers) {
40101
+ handler(state);
40102
+ }
40103
+ }
40104
+ /**
40105
+ * Register a state change handler
40106
+ */
40107
+ onStateChange(handler) {
40108
+ this.stateChangeHandlers.push(handler);
40109
+ return () => {
40110
+ const index = this.stateChangeHandlers.indexOf(handler);
40111
+ if (index !== -1) {
40112
+ this.stateChangeHandlers.splice(index, 1);
40113
+ }
40114
+ };
40115
+ }
40116
+ };
40117
+
39791
40118
  // src/tools/mcp-control.ts
39792
40119
  function createMcpControlTool(opts) {
39793
40120
  const { getConfig, configPath, registry } = opts;
@@ -40347,13 +40674,13 @@ function createAgentToolHandler(a) {
40347
40674
  }
40348
40675
  }
40349
40676
  function waitForConfirm(info) {
40350
- return new Promise((resolve18) => {
40677
+ return new Promise((resolve19) => {
40351
40678
  a.events.emit("tool.confirm_needed", {
40352
40679
  tool: info.tool,
40353
40680
  input: info.input,
40354
40681
  toolUseId: info.toolUseId,
40355
40682
  suggestedPattern: info.suggestedPattern,
40356
- resolve: resolve18
40683
+ resolve: resolve19
40357
40684
  });
40358
40685
  });
40359
40686
  }
@@ -40890,12 +41217,12 @@ function attachMailboxCheckerInner(a, source) {
40890
41217
  // src/core/iteration-limit.ts
40891
41218
  function requestLimitExtension(opts) {
40892
41219
  const { events, currentIterations, currentLimit, autoExtend, timeoutMs = 3e4 } = opts;
40893
- return new Promise((resolve18) => {
41220
+ return new Promise((resolve19) => {
40894
41221
  let resolved = false;
40895
41222
  const timerFired = () => {
40896
41223
  if (!resolved) {
40897
41224
  resolved = true;
40898
- resolve18(0);
41225
+ resolve19(0);
40899
41226
  }
40900
41227
  };
40901
41228
  const timer = setTimeout(timerFired, timeoutMs);
@@ -40904,14 +41231,14 @@ function requestLimitExtension(opts) {
40904
41231
  if (!resolved) {
40905
41232
  resolved = true;
40906
41233
  clearTimeout(timer);
40907
- resolve18(0);
41234
+ resolve19(0);
40908
41235
  }
40909
41236
  };
40910
41237
  const grant = (extra) => {
40911
41238
  if (!resolved) {
40912
41239
  resolved = true;
40913
41240
  clearTimeout(timer);
40914
- resolve18(Math.max(0, extra));
41241
+ resolve19(Math.max(0, extra));
40915
41242
  }
40916
41243
  };
40917
41244
  events.emit("iteration.limit_reached", {
@@ -40925,7 +41252,7 @@ function requestLimitExtension(opts) {
40925
41252
  if (!resolved) {
40926
41253
  resolved = true;
40927
41254
  clearTimeout(timer);
40928
- resolve18(100);
41255
+ resolve19(100);
40929
41256
  }
40930
41257
  });
40931
41258
  }
@@ -41456,12 +41783,26 @@ var Agent = class {
41456
41783
  const { blocks, text } = normalizeInput(userInput);
41457
41784
  const inputPayload = { content: blocks, text, ctx: this.ctx };
41458
41785
  await this.extensions.runBeforeRun(this.ctx, inputPayload);
41786
+ const runStartedAt = Date.now();
41787
+ const runStartedIso = new Date(runStartedAt).toISOString();
41459
41788
  try {
41789
+ this.events.emit("agent.run.started", {
41790
+ ctx: this.ctx,
41791
+ model: opts.model ?? this.ctx.model,
41792
+ at: runStartedIso
41793
+ });
41460
41794
  const autonomousContinue = opts.autonomousContinue ?? this.autonomousContinue;
41461
41795
  const result = await this._loopHandler.runInner(inputPayload, opts, controller, autonomousContinue);
41462
41796
  span?.setAttribute("agent.status", result.status);
41463
41797
  span?.setAttribute("agent.iterations", result.iterations);
41464
41798
  await this.extensions.runAfterRun(this.ctx, result);
41799
+ this.events.emit("agent.run.completed", {
41800
+ ctx: this.ctx,
41801
+ status: result.status,
41802
+ iterations: result.iterations,
41803
+ at: (/* @__PURE__ */ new Date()).toISOString(),
41804
+ durationMs: Date.now() - runStartedAt
41805
+ });
41465
41806
  return result;
41466
41807
  } catch (err) {
41467
41808
  const wse = err instanceof AgentError ? err : toWrongStackError(err);
@@ -41476,6 +41817,21 @@ var Agent = class {
41476
41817
  abortReason: signal.aborted ? signalAbortReason(signal) : void 0
41477
41818
  };
41478
41819
  await this.extensions.runAfterRun(this.ctx, result);
41820
+ if (result.status === "failed") {
41821
+ this.events.emit("agent.run.error", {
41822
+ ctx: this.ctx,
41823
+ err: safeError,
41824
+ at: (/* @__PURE__ */ new Date()).toISOString(),
41825
+ durationMs: Date.now() - runStartedAt
41826
+ });
41827
+ }
41828
+ this.events.emit("agent.run.completed", {
41829
+ ctx: this.ctx,
41830
+ status: result.status,
41831
+ iterations: result.iterations,
41832
+ at: (/* @__PURE__ */ new Date()).toISOString(),
41833
+ durationMs: Date.now() - runStartedAt
41834
+ });
41479
41835
  return result;
41480
41836
  } finally {
41481
41837
  span?.end();
@@ -41633,13 +41989,13 @@ async function runShellHook(spec, input, logger) {
41633
41989
  logger?.warn?.(`hook rejected: command not in allowlist: ${spec.command}`);
41634
41990
  return null;
41635
41991
  }
41636
- return await new Promise((resolve18) => {
41992
+ return await new Promise((resolve19) => {
41637
41993
  let settled = false;
41638
41994
  const done = (v) => {
41639
41995
  if (settled) return;
41640
41996
  settled = true;
41641
41997
  clearTimeout(timer);
41642
- resolve18(v);
41998
+ resolve19(v);
41643
41999
  };
41644
42000
  let child;
41645
42001
  try {
@@ -41652,7 +42008,7 @@ async function runShellHook(spec, input, logger) {
41652
42008
  });
41653
42009
  } catch (err2) {
41654
42010
  logger?.warn?.(`hook spawn failed: ${toErrorMessage(err2)}`);
41655
- return resolve18(null);
42011
+ return resolve19(null);
41656
42012
  }
41657
42013
  const timer = setTimeout(() => {
41658
42014
  logger?.warn?.(`hook command timed out after ${timeoutMs}ms: ${spec.command}`);
@@ -42264,8 +42620,8 @@ var InputBuilder = class {
42264
42620
  async registerFile(input) {
42265
42621
  const ref = await this.store.add({ ...input, kind: "file" });
42266
42622
  this.refs.push(ref);
42267
- const path50 = ref.meta.filename ?? ref.meta.label ?? String(ref.seq);
42268
- return `[file:${path50}]`;
42623
+ const path51 = ref.meta.filename ?? ref.meta.label ?? String(ref.seq);
42624
+ return `[file:${path51}]`;
42269
42625
  }
42270
42626
  /**
42271
42627
  * Whether `appendPaste(text)` would collapse the text to a placeholder
@@ -43166,12 +43522,12 @@ ${clean.trim()}`);
43166
43522
  }
43167
43523
  }
43168
43524
  async gitStatus(root) {
43169
- return new Promise((resolve18) => {
43525
+ return new Promise((resolve19) => {
43170
43526
  let settled = false;
43171
43527
  const finish = (s) => {
43172
43528
  if (settled) return;
43173
43529
  settled = true;
43174
- resolve18(s);
43530
+ resolve19(s);
43175
43531
  };
43176
43532
  let proc;
43177
43533
  const timer = setTimeout(() => {
@@ -44654,7 +45010,7 @@ var PhaseOrchestrator = class {
44654
45010
  async mergeOne(phase, handle) {
44655
45011
  if (!this.worktrees) return;
44656
45012
  try {
44657
- const resolve18 = this.ctx.resolveConflict ? async (info) => {
45013
+ const resolve19 = this.ctx.resolveConflict ? async (info) => {
44658
45014
  const shouldResolve = await this.shouldAttemptConflictResolution(phase, info);
44659
45015
  if (!shouldResolve) return false;
44660
45016
  this.emit("phase.conflictResolving", {
@@ -44668,7 +45024,7 @@ var PhaseOrchestrator = class {
44668
45024
  const mergeOpts = {
44669
45025
  squash: true
44670
45026
  };
44671
- if (resolve18 !== void 0) mergeOpts.resolve = resolve18;
45027
+ if (resolve19 !== void 0) mergeOpts.resolve = resolve19;
44672
45028
  const result = await this.worktrees.merge(handle, mergeOpts);
44673
45029
  if (result.resolved) {
44674
45030
  this.emit("phase.conflictResolved", { phaseId: phase.id, name: phase.name });
@@ -45019,7 +45375,7 @@ var PhaseOrchestrator = class {
45019
45375
  }
45020
45376
  }
45021
45377
  delay(ms) {
45022
- return new Promise((resolve18) => setTimeout(resolve18, ms));
45378
+ return new Promise((resolve19) => setTimeout(resolve19, ms));
45023
45379
  }
45024
45380
  };
45025
45381
 
@@ -46080,8 +46436,8 @@ var CollaborationBus = class {
46080
46436
  if (this.isPaused()) return false;
46081
46437
  this.pausedAtMs = Date.now();
46082
46438
  this.pausedBy = byParticipant;
46083
- this.pausePromise = new Promise((resolve18) => {
46084
- this.pauseResolve = resolve18;
46439
+ this.pausePromise = new Promise((resolve19) => {
46440
+ this.pauseResolve = resolve19;
46085
46441
  });
46086
46442
  return true;
46087
46443
  }
@@ -46117,8 +46473,8 @@ var CollaborationBus = class {
46117
46473
  return true;
46118
46474
  }
46119
46475
  let timer;
46120
- const timeoutPromise = new Promise((resolve18) => {
46121
- timer = setTimeout(() => resolve18("timeout"), timeoutMs);
46476
+ const timeoutPromise = new Promise((resolve19) => {
46477
+ timer = setTimeout(() => resolve19("timeout"), timeoutMs);
46122
46478
  });
46123
46479
  const resumedPromise = this.pausePromise.then(() => "resumed").catch(() => "resumed");
46124
46480
  const winner = await Promise.race([resumedPromise, timeoutPromise]);
@@ -46417,7 +46773,7 @@ async function gitOtherWorktrees(cwd, signal) {
46417
46773
  return branches.slice(1);
46418
46774
  }
46419
46775
  function runGit(args, cwd, signal) {
46420
- return new Promise((resolve18, reject) => {
46776
+ return new Promise((resolve19, reject) => {
46421
46777
  let stdout = "";
46422
46778
  let stderr = "";
46423
46779
  const child = spawn("git", args, {
@@ -46436,7 +46792,7 @@ function runGit(args, cwd, signal) {
46436
46792
  });
46437
46793
  child.on("error", (err) => reject(err));
46438
46794
  child.on("close", (code) => {
46439
- if (code === 0) resolve18(stdout);
46795
+ if (code === 0) resolve19(stdout);
46440
46796
  else reject(new Error(stderr || `git ${args[0]} exited ${code}`));
46441
46797
  });
46442
46798
  });
@@ -46549,8 +46905,8 @@ function extractManifestPath(msg) {
46549
46905
  }
46550
46906
  return void 0;
46551
46907
  }
46552
- function isManifestFile(path50) {
46553
- const name = pathBasename(path50).toLowerCase();
46908
+ function isManifestFile(path51) {
46909
+ const name = pathBasename(path51).toLowerCase();
46554
46910
  const manifests = [
46555
46911
  "package.json",
46556
46912
  "package-lock.json",
@@ -47061,7 +47417,7 @@ function createGitPlugin() {
47061
47417
  }
47062
47418
  async function runGit2(args, cwd) {
47063
47419
  try {
47064
- return await new Promise((resolve18, reject) => {
47420
+ return await new Promise((resolve19, reject) => {
47065
47421
  const child = spawn("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"], signal: AbortSignal.timeout(3e4), windowsHide: true });
47066
47422
  let stdout = "";
47067
47423
  let stderr = "";
@@ -47082,7 +47438,7 @@ async function runGit2(args, cwd) {
47082
47438
  })
47083
47439
  );
47084
47440
  });
47085
- child.on("close", (code) => resolve18({ stdout, stderr, code: code ?? 0 }));
47441
+ child.on("close", (code) => resolve19({ stdout, stderr, code: code ?? 0 }));
47086
47442
  });
47087
47443
  } catch (err) {
47088
47444
  if (err instanceof WrongStackError) throw err;
@@ -47884,7 +48240,7 @@ If NOTHING worth flagging:
47884
48240
  ## \u{1F982} Chimera Review \u2014 all clear \u2705
47885
48241
  No issues found in N changed files.`;
47886
48242
  async function runGit3(args, cwd) {
47887
- return new Promise((resolve18, reject) => {
48243
+ return new Promise((resolve19, reject) => {
47888
48244
  let child;
47889
48245
  try {
47890
48246
  child = spawn("git", args, {
@@ -47905,8 +48261,8 @@ async function runGit3(args, cwd) {
47905
48261
  child.stderr?.on("data", (d) => {
47906
48262
  stderr += d;
47907
48263
  });
47908
- child.on("error", () => resolve18({ stdout, stderr, code: 1 }));
47909
- child.on("close", (code) => resolve18({ stdout, stderr, code: code ?? 0 }));
48264
+ child.on("error", () => resolve19({ stdout, stderr, code: 1 }));
48265
+ child.on("close", (code) => resolve19({ stdout, stderr, code: code ?? 0 }));
47910
48266
  });
47911
48267
  }
47912
48268
  async function isGitRepo2(cwd) {
@@ -48060,6 +48416,6 @@ function createChimeraPlugin() {
48060
48416
  };
48061
48417
  }
48062
48418
 
48063
- 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, AgentMonitorService, 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, buildTranscriptFromEvents, classifyFamily, clearPlan, collabInjectMiddleware, collabPauseMiddleware, color, compactLog, compactSchemaDescriptions, compactToolDefinitionForWire, compileGlob, compileUserRegex, completePartialObject, composeDirectorPrompt, composeSubagentPrompt, computeMessageTokens, computeTaskItemProgress, computeTaskProgress, consumeBtwNotes, consumeQueuedMessagesUpdate, context7Server, contextManagerTool, createAgentMonitorService, 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, gatedEnhancerReasoning, generateSessionId, 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, mapSessionEventToEntries, markAssistantReferencedEvidence, matchAny, matchGlob, matrixKeyKind, mergeCustomModelDefs, mergeModelsPayload, mergeToolResults, 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, sanitizeModel, sanitizeNodeOptions, saveGoal, savePlan, saveTasks, saveTodosCheckpoint, scoreAgents, scoreMessage, scrubAndTruncateHqPreview, securitySlashCommand, sentinelServer, setBtwNote, setJsonPath, setJsonPathInFile, setOutputLineGuard, setPlanItemStatus, setProgress, setQueuedMessagesSnapshot, setRawMode, shouldEnhance, slackServer, sleep, sshManagerServer, stableStringify, startAgentMonitorEventBridge, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, startPackageOutdatedWatcher, startSessionTelemetryBridge, 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 };
48419
+ 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, AdaptiveConcurrencyController, Agent, AgentError, AgentMonitorService, 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, buildTranscriptFromEvents, classifyFamily, clearPlan, collabInjectMiddleware, collabPauseMiddleware, color, compactLog, compactSchemaDescriptions, compactToolDefinitionForWire, compileGlob, compileUserRegex, completePartialObject, composeDirectorPrompt, composeSubagentPrompt, computeMessageTokens, computeTaskItemProgress, computeTaskProgress, consumeBtwNotes, consumeQueuedMessagesUpdate, context7Server, contextManagerTool, createAgentMonitorService, 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, gatedEnhancerReasoning, generateSessionId, 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, mapSessionEventToEntries, markAssistantReferencedEvidence, matchAny, matchGlob, matrixKeyKind, mergeCustomModelDefs, mergeModelsPayload, mergeToolResults, 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, sanitizeModel, sanitizeNodeOptions, saveGoal, savePlan, saveTasks, saveTodosCheckpoint, scoreAgents, scoreMessage, scrubAndTruncateHqPreview, securitySlashCommand, sentinelServer, setBtwNote, setJsonPath, setJsonPathInFile, setOutputLineGuard, setPlanItemStatus, setProgress, setQueuedMessagesSnapshot, setRawMode, shouldEnhance, slackServer, sleep, sshManagerServer, stableStringify, startAgentMonitorEventBridge, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, startPackageOutdatedWatcher, startSessionTelemetryBridge, 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 };
48064
48420
  //# sourceMappingURL=index.js.map
48065
48421
  //# sourceMappingURL=index.js.map