@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
@@ -8851,7 +8851,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8851
8851
  this._loadCache.clear();
8852
8852
  }
8853
8853
  }
8854
- // ── Storage event helpers ───────────────────────────────────────────────────
8854
+ // ── Storage event helpers ───────────────────────────────────────────────────
8855
8855
  emitRead(sessionId, filePath, operation, outcome, durationMs, error) {
8856
8856
  this.events?.emit("storage.read", {
8857
8857
  sessionId,
@@ -8966,7 +8966,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
8966
8966
  this.events,
8967
8967
  {
8968
8968
  resumed: true,
8969
- // Shard directory (sessions/<date>/) must match create() so the
8969
+ // Shard directory (sessions/<date>/) — must match create() so the
8970
8970
  // .summary.json sidecar lands next to the JSONL instead of the
8971
8971
  // sessions root (where summaryFor() would never find it).
8972
8972
  dir: path5.dirname(file),
@@ -9007,19 +9007,93 @@ var DefaultSessionStore = class _DefaultSessionStore {
9007
9007
  const raw = await fsp6.readFile(file, "utf8");
9008
9008
  const lines = raw.split("\n").filter((l) => l.trim());
9009
9009
  const events = [];
9010
+ let sessionStartEvent;
9011
+ let sessionEndEvent;
9012
+ let sessionModel;
9013
+ let sessionProvider;
9014
+ let sessionPendingToolUses;
9015
+ const messages = [];
9016
+ const openToolUses = /* @__PURE__ */ new Set();
9017
+ let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
9010
9018
  for (const line of lines) {
9011
9019
  try {
9012
9020
  const parsed = JSON.parse(line);
9013
9021
  if (parsed !== null && typeof parsed === "object" && typeof parsed.type === "string" && typeof parsed.ts === "string") {
9014
- events.push(parsed);
9022
+ const ev = parsed;
9023
+ events.push(ev);
9024
+ if (ev.type === "session_start" && !sessionStartEvent) {
9025
+ sessionStartEvent = ev;
9026
+ sessionModel = ev.model;
9027
+ sessionProvider = ev.provider;
9028
+ }
9029
+ if (ev.type === "session_end") {
9030
+ sessionEndEvent = ev;
9031
+ sessionPendingToolUses = ev.pendingToolUses;
9032
+ }
9033
+ if (ev.type === "user_input") {
9034
+ openToolUses.clear();
9035
+ messages.push({ role: "user", content: ev.content, ts: ev.ts });
9036
+ } else if (ev.type === "llm_response") {
9037
+ messages.push({ role: "assistant", content: ev.content, ts: ev.ts });
9038
+ for (const b of ev.content) {
9039
+ if (b.type === "tool_use") openToolUses.add(b.id);
9040
+ }
9041
+ usage = {
9042
+ input: usage.input + (ev.usage.input ?? 0),
9043
+ output: usage.output + (ev.usage.output ?? 0),
9044
+ cacheRead: (usage.cacheRead ?? 0) + (ev.usage.cacheRead ?? 0),
9045
+ cacheWrite: (usage.cacheWrite ?? 0) + (ev.usage.cacheWrite ?? 0)
9046
+ };
9047
+ } else if (ev.type === "tool_result") {
9048
+ if (!openToolUses.has(ev.id)) {
9049
+ this.events?.emit("session.damaged", {
9050
+ sessionId: id,
9051
+ detail: `Orphan tool_result "${ev.id}" has no matching tool_use`
9052
+ });
9053
+ continue;
9054
+ }
9055
+ openToolUses.delete(ev.id);
9056
+ const resultBlock = {
9057
+ type: "tool_result",
9058
+ tool_use_id: ev.id,
9059
+ content: typeof ev.content === "string" ? ev.content : JSON.stringify(ev.content),
9060
+ is_error: ev.isError
9061
+ };
9062
+ const last = messages[messages.length - 1];
9063
+ const lastIsToolResultUser = last?.role === "user" && Array.isArray(last.content) && last.content.every((b) => b.type === "tool_result");
9064
+ if (lastIsToolResultUser && Array.isArray(last.content)) {
9065
+ last.content.push(resultBlock);
9066
+ } else {
9067
+ messages.push({ role: "user", content: [resultBlock], ts: ev.ts });
9068
+ }
9069
+ }
9015
9070
  }
9016
9071
  } catch {
9017
9072
  }
9018
9073
  }
9019
- const meta = this.metaFromEvents(id, events);
9020
- const { messages, usage } = this.replay(events, id);
9074
+ if (openToolUses.size > 0) {
9075
+ this.events?.emit("session.damaged", {
9076
+ sessionId: id,
9077
+ detail: `${openToolUses.size} tool_use blocks without matching results - replay repaired`
9078
+ });
9079
+ }
9080
+ const repaired = repairToolUseAdjacency(messages);
9081
+ if (repaired.report.changed) {
9082
+ this.events?.emit("session.damaged", {
9083
+ sessionId: id,
9084
+ detail: `Repaired replay adjacency: removed ${repaired.report.removedToolUses.length} tool_use, ${repaired.report.removedToolResults.length} tool_result, ${repaired.report.removedMessages} empty messages`
9085
+ });
9086
+ }
9087
+ const meta = {
9088
+ id,
9089
+ startedAt: sessionStartEvent?.ts ?? (/* @__PURE__ */ new Date(0)).toISOString(),
9090
+ endedAt: sessionEndEvent?.ts,
9091
+ model: sessionModel,
9092
+ provider: sessionProvider,
9093
+ pendingToolUses: sessionPendingToolUses
9094
+ };
9021
9095
  const toolCallEnds = extractToolCallEnds(events);
9022
- const data = { metadata: meta, events, messages, usage, toolCallEnds };
9096
+ const data = { metadata: meta, events, messages: repaired.messages, usage, toolCallEnds };
9023
9097
  if (this._loadCache.size >= _DefaultSessionStore.LOAD_CACHE_MAX_ENTRIES) {
9024
9098
  const oldest = this._loadCache.keys().next().value;
9025
9099
  if (oldest !== void 0) {
@@ -9062,7 +9136,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
9062
9136
  return [];
9063
9137
  }
9064
9138
  }
9065
- // ── Session index (_index.jsonl) ─────────────────────────────────────────
9139
+ // ── Session index (_index.jsonl) ─────────────────────────────────────────
9066
9140
  //
9067
9141
  // One JSON line per closed session, appended atomically on close().
9068
9142
  // When a session is deleted, a tombstone {action:"delete",id:"..."} is
@@ -9238,7 +9312,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
9238
9312
  return [...childFileArrays.flat(), ...files];
9239
9313
  }
9240
9314
  /** Recursively collect session IDs from date-shard subdirectories.
9241
- * IDs include the date-prefix path (e.g. "2026-06-06/17-46-57Z_").
9315
+ * IDs include the date-prefix path (e.g. "2026-06-06/17-46-57Z_…").
9242
9316
  * Skips `.jsonl`/`.summary.json` root files, dot-files, and
9243
9317
  * sub-directories that belong to fleet/subagent sessions. */
9244
9318
  async collectSessionIds(dir, prefix = "", depth = 0) {
@@ -9293,7 +9367,7 @@ var DefaultSessionStore = class _DefaultSessionStore {
9293
9367
  }));
9294
9368
  });
9295
9369
  outcome = "failure";
9296
- errorMsg = "summary fallback \u2014 manifest rebuilt";
9370
+ errorMsg = "summary fallback \xE2\u20AC\u201D manifest rebuilt";
9297
9371
  this.emitRead(id, manifest, "summary", outcome, Date.now() - t0, errorMsg);
9298
9372
  return summary;
9299
9373
  } catch (err) {
@@ -9585,76 +9659,6 @@ var DefaultSessionStore = class _DefaultSessionStore {
9585
9659
  stream.destroy();
9586
9660
  }
9587
9661
  }
9588
- metaFromEvents(id, events) {
9589
- const start = events.find((e) => e.type === "session_start");
9590
- const end = events.findLast((e) => e.type === "session_end");
9591
- return {
9592
- id,
9593
- startedAt: start?.ts ?? (/* @__PURE__ */ new Date(0)).toISOString(),
9594
- endedAt: end?.ts,
9595
- model: start?.model,
9596
- provider: start?.provider,
9597
- pendingToolUses: end?.pendingToolUses
9598
- };
9599
- }
9600
- replay(events, sessionId = "unknown") {
9601
- const messages = [];
9602
- let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
9603
- const openToolUses = /* @__PURE__ */ new Set();
9604
- for (const e of events) {
9605
- if (e.type === "user_input") {
9606
- openToolUses.clear();
9607
- messages.push({ role: "user", content: e.content, ts: e.ts });
9608
- } else if (e.type === "llm_response") {
9609
- messages.push({ role: "assistant", content: e.content, ts: e.ts });
9610
- for (const b of e.content) {
9611
- if (b.type === "tool_use") openToolUses.add(b.id);
9612
- }
9613
- usage = {
9614
- input: usage.input + (e.usage.input ?? 0),
9615
- output: usage.output + (e.usage.output ?? 0),
9616
- cacheRead: (usage.cacheRead ?? 0) + (e.usage.cacheRead ?? 0),
9617
- cacheWrite: (usage.cacheWrite ?? 0) + (e.usage.cacheWrite ?? 0)
9618
- };
9619
- } else if (e.type === "tool_result") {
9620
- if (!openToolUses.has(e.id)) {
9621
- this.events?.emit("session.damaged", {
9622
- sessionId,
9623
- detail: `Orphan tool_result "${e.id}" has no matching tool_use`
9624
- });
9625
- continue;
9626
- }
9627
- openToolUses.delete(e.id);
9628
- const resultBlock = {
9629
- type: "tool_result",
9630
- tool_use_id: e.id,
9631
- content: typeof e.content === "string" ? e.content : JSON.stringify(e.content),
9632
- is_error: e.isError
9633
- };
9634
- const last = messages[messages.length - 1];
9635
- const lastIsToolResultUser = last?.role === "user" && Array.isArray(last.content) && last.content.every((b) => b.type === "tool_result");
9636
- if (lastIsToolResultUser && Array.isArray(last.content)) {
9637
- last.content.push(resultBlock);
9638
- } else {
9639
- messages.push({ role: "user", content: [resultBlock], ts: e.ts });
9640
- }
9641
- }
9642
- }
9643
- if (openToolUses.size > 0) {
9644
- this.events?.emit("session.damaged", {
9645
- sessionId,
9646
- detail: `${openToolUses.size} tool_use blocks without matching results - replay repaired`
9647
- });
9648
- }
9649
- const repaired = repairToolUseAdjacency(messages);
9650
- if (repaired.report.changed) {
9651
- this.events?.emit("session.damaged", {
9652
- sessionId,
9653
- detail: `Repaired replay adjacency: removed ${repaired.report.removedToolUses.length} tool_use, ${repaired.report.removedToolResults.length} tool_result, ${repaired.report.removedMessages} empty messages`
9654
- });
9655
- }
9656
- return { messages: repaired.messages, usage };
9657
- }
9658
9662
  };
9659
9663
  function extractToolCallEnds(events) {
9660
9664
  const result = [];
@@ -9713,7 +9717,7 @@ var FileSessionWriter = class _FileSessionWriter {
9713
9717
  /**
9714
9718
  * Lazy session_start/session_resumed init, shared by all appenders.
9715
9719
  * A single promise (not a boolean) so a second append racing the first
9716
- * can't push its event into the buffer BEFORE the first append's event
9720
+ * can't push its event into the buffer BEFORE the first append's event —
9717
9721
  * every appender awaits the same init and resumes in FIFO call order.
9718
9722
  */
9719
9723
  initPromise = null;
@@ -9726,24 +9730,24 @@ var FileSessionWriter = class _FileSessionWriter {
9726
9730
  lastAppendWarnAt = 0;
9727
9731
  secretScrubber;
9728
9732
  onCloseCb;
9729
- /** Implements SessionWriter.traceId propagated from ContextInit.traceId. */
9733
+ /** Implements SessionWriter.traceId — propagated from ContextInit.traceId. */
9730
9734
  traceId;
9731
- // ── Write buffer batches events to reduce per-event disk I/O ─────────
9735
+ // ── Write buffer — batches events to reduce per-event disk I/O ─────────
9732
9736
  //
9733
9737
  // Every append() pushes the scrubbed event into an in-memory buffer instead
9734
9738
  // of calling handle.appendFile() synchronously. The buffer flushes to disk
9735
9739
  // when it reaches FLUSH_SIZE events OR after FLUSH_INTERVAL_MS of inactivity.
9736
9740
  // This cuts the number of disk writes by ~95% without changing the on-disk
9737
- // format the JSONL is still one JSON object per line.
9741
+ // format — the JSONL is still one JSON object per line.
9738
9742
  writeBuffer = [];
9739
9743
  flushTimer = null;
9740
9744
  static FLUSH_INTERVAL_MS = 500;
9741
9745
  static FLUSH_SIZE = 50;
9742
- // ── Write serialization ─────────────────────────────────────────────────
9746
+ // ── Write serialization ─────────────────────────────────────────────────
9743
9747
  //
9744
9748
  // All disk writes are funneled through a FIFO promise chain. Without it,
9745
9749
  // a timer-driven flush racing an explicit flush()/close() issues two
9746
- // concurrent appendFile() calls on the shared O_APPEND handle the kernel
9750
+ // concurrent appendFile() calls on the shared O_APPEND handle — the kernel
9747
9751
  // may complete them out of order (chronology breaks) or, for large
9748
9752
  // batches, interleave partial writes (torn JSONL lines). The chain keeps
9749
9753
  // exactly one write in flight; failures don't break the chain.
@@ -9757,7 +9761,7 @@ var FileSessionWriter = class _FileSessionWriter {
9757
9761
  );
9758
9762
  return write;
9759
9763
  }
9760
- // ── Enriched summary tracking ──────────────────────────────────────────
9764
+ // ── Enriched summary tracking ──────────────────────────────────────────
9761
9765
  iterationCount = 0;
9762
9766
  toolCallCount = 0;
9763
9767
  toolErrorCount = 0;
@@ -9849,7 +9853,7 @@ var FileSessionWriter = class _FileSessionWriter {
9849
9853
  * (user_input, llm_response) call this so they survive SIGKILL/crash
9850
9854
  * instead of sitting in the in-memory buffer for up to 500ms.
9851
9855
  *
9852
- * Idempotent cancels any pending timer and writes whatever has
9856
+ * Idempotent — cancels any pending timer and writes whatever has
9853
9857
  * accumulated in the buffer. Safe to call even when the buffer
9854
9858
  * is empty (no-op).
9855
9859
  */
@@ -9872,7 +9876,7 @@ var FileSessionWriter = class _FileSessionWriter {
9872
9876
  /**
9873
9877
  * Flush all buffered events to disk as a single appendFile call.
9874
9878
  * Errors use the same throttled-warning pattern the old per-event
9875
- * append path used one warning every 5s with a suppressed count.
9879
+ * append path used — one warning every 5s with a suppressed count.
9876
9880
  * On failure the buffer is cleared (events are best-effort, same as
9877
9881
  * the old per-event path where a failed write was silently dropped).
9878
9882
  */
@@ -10055,7 +10059,7 @@ var FileSessionWriter = class _FileSessionWriter {
10055
10059
  /**
10056
10060
  * Truncate the session file to the checkpoint with the given promptIndex,
10057
10061
  * removing all events that follow it. Uses a single-pass byte-offset scan
10058
- * so post-checkpoint content is never read or parsed O(1) memory instead
10062
+ * so post-checkpoint content is never read or parsed — O(1) memory instead
10059
10063
  * of O(N) JSON.parse calls over the full file.
10060
10064
  */
10061
10065
  async truncateToCheckpoint(targetPromptIndex) {
@@ -10212,7 +10216,7 @@ var FileSessionWriter = class _FileSessionWriter {
10212
10216
  await fsp6.writeFile(this.filePath, record, "utf8");
10213
10217
  }
10214
10218
  /**
10215
- * Idea #1 write an in-flight marker. The agent loop should call
10219
+ * Idea #1 — write an in-flight marker. The agent loop should call
10216
10220
  * this at the start of each long-running operation; a matching
10217
10221
  * `clearInFlightMarker` follows on clean exit. A stale marker
10218
10222
  * (no end) is what `SessionRecovery.detectStale` looks for.
@@ -10229,9 +10233,9 @@ var FileSessionWriter = class _FileSessionWriter {
10229
10233
  this.events?.emit("in_flight.started", { context, ts: (/* @__PURE__ */ new Date()).toISOString() });
10230
10234
  }
10231
10235
  /**
10232
- * Idea #1 close the in-flight marker. Idempotent in spirit
10236
+ * Idea #1 — close the in-flight marker. Idempotent in spirit
10233
10237
  * (you can call it after a successful iteration even if you
10234
- * didn't open one this round) but the session log records
10238
+ * didn't open one this round) — but the session log records
10235
10239
  * every call so postmortem tooling can see "the agent finished
10236
10240
  * cleanly X times, then died without finishing Y".
10237
10241
  */
@@ -11302,7 +11306,7 @@ var GlobalMailbox = class {
11302
11306
  /**
11303
11307
  * @param projectDir — `~/.wrongstack/projects/<slug>/`
11304
11308
  * @param events — optional EventBus for real-time TUI/WebUI notifications
11305
- * @param hqPublisher — optional HQ publisher for cross-project telemetry
11309
+ * @param hqPublisher — optional HQ publisher, or getter, for cross-project telemetry
11306
11310
  */
11307
11311
  constructor(projectDir, events, hqPublisher) {
11308
11312
  this.messagePath = path5.join(projectDir, MAILBOX_FILE2);
@@ -11314,15 +11318,19 @@ var GlobalMailbox = class {
11314
11318
  get hqMailboxId() {
11315
11319
  return `${path5.basename(path5.dirname(this.messagePath))}:mailbox`;
11316
11320
  }
11321
+ get hqPublisher() {
11322
+ return typeof this._hqPublisher === "function" ? this._hqPublisher() : this._hqPublisher;
11323
+ }
11317
11324
  publishHqMailboxEvent(input) {
11318
11325
  try {
11319
- this._hqPublisher?.publishMailboxEvent(input);
11326
+ this.hqPublisher?.publishMailboxEvent(input);
11320
11327
  } catch {
11321
11328
  }
11322
11329
  }
11323
11330
  publishHqMailboxSnapshot() {
11324
- if (this._hqPublisher === void 0) return;
11325
- void this._hqPublisher.publishMailboxSnapshot(this, { mailboxId: this.hqMailboxId }).catch(() => {
11331
+ const publisher = this.hqPublisher;
11332
+ if (publisher === void 0) return;
11333
+ void publisher.publishMailboxSnapshot(this, { mailboxId: this.hqMailboxId }).catch(() => {
11326
11334
  });
11327
11335
  }
11328
11336
  // ── Messages ────────────────────────────────────────────────────────────
@@ -15479,6 +15487,186 @@ function createAgentMonitorService(opts) {
15479
15487
  return new AgentMonitorService(opts);
15480
15488
  }
15481
15489
 
15482
- export { ACP_AGENTS, AGENTS_BY_PHASE, AGENT_CATALOG, TOOLS as AGENT_TOOL_PRESETS, ALL_AGENT_DEFINITIONS, ALL_FLEET_AGENTS, AUDIT_LOG_AGENT, AgentMonitorService, AutonomousBrain, AutonomousCoordinator, BUG_HUNTER_AGENT, BUILD_AGENTS, BrainDecisionQueue, BrainMonitor, BudgetExceededError, BudgetThresholdSignal, ChangeManager, CollabSession, ConsensusProtocol, DECISION_TIMEOUT_MS, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_DISPATCH_ROLE, DEFAULT_QUALITY_CHECKS, DEFAULT_SUBAGENT_BASELINE, DELIVERY_AGENTS, DEPENDENCY_FILE_PATTERNS, DISCOVERY_AGENTS, DOMAIN_AGENTS, DefaultBrainArbiter, DefaultMailbox, DefaultMultiAgentCoordinator, Director, DirectorAlertLevel, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, GlobalMailbox, HEAVY_BUDGET, HumanEscalatingBrainArbiter, InMemoryAgentBridge, InMemoryBridgeTransport, KNOWLEDGE_AGENTS, KnowledgeGraph, LIGHT_BUDGET, LargeAnswerStore, MEDIUM_BUDGET, META_AGENTS, NULL_FLEET_BUS, ObservableBrainArbiter, PLANNING_AGENTS, REFACTOR_PLANNER_AGENT, REVIEW_AGENTS, SECURITY_SCANNER_AGENT, SubagentBudget, TIMEOUT_PREEMPT_FRACTION, TaskAuctioneer, TaskDAG, VERIFY_AGENTS, applyRosterBudget, attachAutoExtend, attachDepWatcherBridge, composeDirectorPrompt, composeSubagentPrompt, createAgentMonitorService, createDelegateTool, createMailboxHooks, createMessage, detectEcosystem, dispatchAgent, formatHumanPrompt, getAgentDefinition, getFullPackageLog, getManifestPackages, getPackageAuthor, getPackagesByAgent, mailboxSessionTag, makeAgentSubagentRunner, makeAskResultTool, makeAskTool, makeAssignTool, makeAwaitTasksTool, makeCollabDebugTool, makeDependencyWatcherConfig, makeDirectorSessionFactory, makeFleetEmitTool, makeFleetHealthTool, makeFleetSessionTool, makeFleetStatusTool, makeFleetUsageTool, makeLLMClassifier, makeMailInboxTool, makeMailSendTool, makeMailboxTool, makeRollUpTool, makeSpawnTool, makeTerminateTool, makeWorkCompleteTool, normalizeRecipient, recordPackageAction, resolveMailboxIdentity, resolveProjectDir, rosterSummaryFromConfigs, scoreAgents, startPackageOutdatedWatcher, updatePackageOutdatedStatus, withDisabledToolFiltering };
15490
+ // src/coordination/adaptive-concurrency.ts
15491
+ var DEFAULT_CONFIG = Object.freeze({
15492
+ enabled: false,
15493
+ minConcurrent: 1,
15494
+ maxConcurrent: 16,
15495
+ decreaseFactor: 0.5,
15496
+ successThreshold: 10,
15497
+ recoveryIntervalMs: 3e4
15498
+ });
15499
+ var AdaptiveConcurrencyController = class {
15500
+ config;
15501
+ state;
15502
+ disposers = [];
15503
+ stateChangeHandlers = [];
15504
+ constructor(fleetBus, setMaxConcurrent, config = {}, onStateChange) {
15505
+ this.config = {
15506
+ enabled: config.enabled ?? DEFAULT_CONFIG.enabled,
15507
+ minConcurrent: config.minConcurrent ?? DEFAULT_CONFIG.minConcurrent,
15508
+ maxConcurrent: config.maxConcurrent ?? DEFAULT_CONFIG.maxConcurrent,
15509
+ decreaseFactor: config.decreaseFactor ?? DEFAULT_CONFIG.decreaseFactor,
15510
+ successThreshold: config.successThreshold ?? DEFAULT_CONFIG.successThreshold,
15511
+ recoveryIntervalMs: config.recoveryIntervalMs ?? DEFAULT_CONFIG.recoveryIntervalMs
15512
+ };
15513
+ this.state = {
15514
+ current: this.config.maxConcurrent,
15515
+ min: this.config.minConcurrent,
15516
+ max: this.config.maxConcurrent,
15517
+ consecutiveSuccesses: 0,
15518
+ consecutiveFailures: 0,
15519
+ totalDecreases: 0,
15520
+ totalIncreases: 0,
15521
+ enabled: this.config.enabled
15522
+ };
15523
+ if (onStateChange) {
15524
+ this.stateChangeHandlers.push(onStateChange);
15525
+ }
15526
+ if (this.config.enabled) {
15527
+ setMaxConcurrent(this.state.current);
15528
+ }
15529
+ this.setupEventHandlers(fleetBus, setMaxConcurrent);
15530
+ }
15531
+ setupEventHandlers(fleetBus, setMaxConcurrent) {
15532
+ if (!this.config.enabled) return;
15533
+ const off = fleetBus.onAny((event) => {
15534
+ if (!this.config.enabled) return;
15535
+ if (event.type === "error" || event.type === "provider_error") {
15536
+ const payload = event.payload;
15537
+ if (payload?.status === 429 || payload?.code === "rate_limit_error" || payload?.kind === "rate_limit") {
15538
+ this.handleRateLimit(setMaxConcurrent);
15539
+ }
15540
+ }
15541
+ });
15542
+ this.disposers.push(off);
15543
+ }
15544
+ /**
15545
+ * Handle a rate limit (429) error - decrease concurrency
15546
+ */
15547
+ handleRateLimit(setMaxConcurrent) {
15548
+ if (this.state.current <= this.config.minConcurrent) {
15549
+ this.state.consecutiveFailures++;
15550
+ this.state.consecutiveSuccesses = 0;
15551
+ this.notifyStateChange();
15552
+ return;
15553
+ }
15554
+ const newConcurrent = Math.max(
15555
+ this.config.minConcurrent,
15556
+ Math.floor(this.state.current * this.config.decreaseFactor)
15557
+ );
15558
+ if (newConcurrent < this.state.current) {
15559
+ const previousConcurrent = this.state.current;
15560
+ this.state.current = newConcurrent;
15561
+ this.state.consecutiveFailures++;
15562
+ this.state.consecutiveSuccesses = 0;
15563
+ this.state.totalDecreases++;
15564
+ setMaxConcurrent(this.state.current);
15565
+ this.notifyStateChange();
15566
+ console.log(
15567
+ JSON.stringify({
15568
+ level: "warn",
15569
+ event: "adaptive_concurrency.decreased",
15570
+ reason: "rate_limit",
15571
+ previousConcurrent,
15572
+ newConcurrent: this.state.current,
15573
+ decreaseFactor: this.config.decreaseFactor,
15574
+ totalDecreases: this.state.totalDecreases
15575
+ })
15576
+ );
15577
+ }
15578
+ }
15579
+ /**
15580
+ * Force a decrease (e.g., manual trigger or other error types)
15581
+ */
15582
+ decrease(target) {
15583
+ if (!this.config.enabled) return;
15584
+ const newConcurrent = target ?? Math.max(
15585
+ this.config.minConcurrent,
15586
+ Math.floor(this.state.current * this.config.decreaseFactor)
15587
+ );
15588
+ if (newConcurrent < this.state.current) {
15589
+ const previousConcurrent = this.state.current;
15590
+ this.state.current = newConcurrent;
15591
+ this.state.consecutiveSuccesses = 0;
15592
+ this.state.totalDecreases++;
15593
+ this.notifyStateChange();
15594
+ console.log(
15595
+ JSON.stringify({
15596
+ level: "warn",
15597
+ event: "adaptive_concurrency.decreased",
15598
+ reason: "manual",
15599
+ previousConcurrent,
15600
+ newConcurrent: this.state.current,
15601
+ totalDecreases: this.state.totalDecreases
15602
+ })
15603
+ );
15604
+ }
15605
+ }
15606
+ /**
15607
+ * Get the current state
15608
+ */
15609
+ getState() {
15610
+ return { ...this.state };
15611
+ }
15612
+ /**
15613
+ * Update configuration at runtime
15614
+ */
15615
+ updateConfig(config) {
15616
+ if (config.enabled !== void 0) {
15617
+ this.config.enabled = config.enabled;
15618
+ }
15619
+ if (config.minConcurrent !== void 0) {
15620
+ this.config.minConcurrent = config.minConcurrent;
15621
+ }
15622
+ if (config.maxConcurrent !== void 0) {
15623
+ this.config.maxConcurrent = config.maxConcurrent;
15624
+ }
15625
+ if (config.decreaseFactor !== void 0) {
15626
+ this.config.decreaseFactor = config.decreaseFactor;
15627
+ }
15628
+ if (config.successThreshold !== void 0) {
15629
+ this.config.successThreshold = config.successThreshold;
15630
+ }
15631
+ if (config.recoveryIntervalMs !== void 0) {
15632
+ this.config.recoveryIntervalMs = config.recoveryIntervalMs;
15633
+ }
15634
+ this.state.current = Math.max(this.config.minConcurrent, Math.min(this.state.current, this.config.maxConcurrent));
15635
+ this.state.enabled = this.config.enabled;
15636
+ this.state.min = this.config.minConcurrent;
15637
+ this.state.max = this.config.maxConcurrent;
15638
+ this.notifyStateChange();
15639
+ }
15640
+ /**
15641
+ * Dispose of the controller and clean up event listeners
15642
+ */
15643
+ dispose() {
15644
+ for (const dispose of this.disposers) {
15645
+ dispose();
15646
+ }
15647
+ this.disposers.length = 0;
15648
+ this.stateChangeHandlers = [];
15649
+ }
15650
+ notifyStateChange() {
15651
+ const state = this.getState();
15652
+ for (const handler of this.stateChangeHandlers) {
15653
+ handler(state);
15654
+ }
15655
+ }
15656
+ /**
15657
+ * Register a state change handler
15658
+ */
15659
+ onStateChange(handler) {
15660
+ this.stateChangeHandlers.push(handler);
15661
+ return () => {
15662
+ const index = this.stateChangeHandlers.indexOf(handler);
15663
+ if (index !== -1) {
15664
+ this.stateChangeHandlers.splice(index, 1);
15665
+ }
15666
+ };
15667
+ }
15668
+ };
15669
+
15670
+ export { ACP_AGENTS, AGENTS_BY_PHASE, AGENT_CATALOG, TOOLS as AGENT_TOOL_PRESETS, ALL_AGENT_DEFINITIONS, ALL_FLEET_AGENTS, AUDIT_LOG_AGENT, AdaptiveConcurrencyController, AgentMonitorService, AutonomousBrain, AutonomousCoordinator, BUG_HUNTER_AGENT, BUILD_AGENTS, BrainDecisionQueue, BrainMonitor, BudgetExceededError, BudgetThresholdSignal, ChangeManager, CollabSession, ConsensusProtocol, DECISION_TIMEOUT_MS, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_DISPATCH_ROLE, DEFAULT_QUALITY_CHECKS, DEFAULT_SUBAGENT_BASELINE, DELIVERY_AGENTS, DEPENDENCY_FILE_PATTERNS, DISCOVERY_AGENTS, DOMAIN_AGENTS, DefaultBrainArbiter, DefaultMailbox, DefaultMultiAgentCoordinator, Director, DirectorAlertLevel, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FLEET_ROSTER_WITHACP, FleetBus, FleetCostCapError, FleetManager, FleetSpawnBudgetError, FleetUsageAggregator, GlobalMailbox, HEAVY_BUDGET, HumanEscalatingBrainArbiter, InMemoryAgentBridge, InMemoryBridgeTransport, KNOWLEDGE_AGENTS, KnowledgeGraph, LIGHT_BUDGET, LargeAnswerStore, MEDIUM_BUDGET, META_AGENTS, NULL_FLEET_BUS, ObservableBrainArbiter, PLANNING_AGENTS, REFACTOR_PLANNER_AGENT, REVIEW_AGENTS, SECURITY_SCANNER_AGENT, SubagentBudget, TIMEOUT_PREEMPT_FRACTION, TaskAuctioneer, TaskDAG, VERIFY_AGENTS, applyRosterBudget, attachAutoExtend, attachDepWatcherBridge, composeDirectorPrompt, composeSubagentPrompt, createAgentMonitorService, createDelegateTool, createMailboxHooks, createMessage, detectEcosystem, dispatchAgent, formatHumanPrompt, getAgentDefinition, getFullPackageLog, getManifestPackages, getPackageAuthor, getPackagesByAgent, mailboxSessionTag, makeAgentSubagentRunner, makeAskResultTool, makeAskTool, makeAssignTool, makeAwaitTasksTool, makeCollabDebugTool, makeDependencyWatcherConfig, makeDirectorSessionFactory, makeFleetEmitTool, makeFleetHealthTool, makeFleetSessionTool, makeFleetStatusTool, makeFleetUsageTool, makeLLMClassifier, makeMailInboxTool, makeMailSendTool, makeMailboxTool, makeRollUpTool, makeSpawnTool, makeTerminateTool, makeWorkCompleteTool, normalizeRecipient, recordPackageAction, resolveMailboxIdentity, resolveProjectDir, rosterSummaryFromConfigs, scoreAgents, startPackageOutdatedWatcher, updatePackageOutdatedStatus, withDisabledToolFiltering };
15483
15671
  //# sourceMappingURL=index.js.map
15484
15672
  //# sourceMappingURL=index.js.map