nexus-agents 2.173.7 → 2.173.8

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 (116) hide show
  1. package/dist/{child-mcp-config-3IX4DFNS.js → child-mcp-config-RSM4VNFS.js} +2 -2
  2. package/dist/{chunk-TTGJDWIG.js → chunk-3PXN234X.js} +35 -35
  3. package/dist/{chunk-TE66HW3D.js → chunk-3ZLPS4XC.js} +3 -3
  4. package/dist/{chunk-CUJUNXKQ.js → chunk-4IDGRIWO.js} +4 -4
  5. package/dist/{chunk-MSINKE6X.js → chunk-66EE7Y2F.js} +2 -2
  6. package/dist/{chunk-GKLCBQCF.js → chunk-6N2WQBJU.js} +2 -2
  7. package/dist/{chunk-GACT2UFT.js → chunk-6VT7ODBT.js} +2 -2
  8. package/dist/{chunk-TJMQU4HJ.js → chunk-6WYBSYJ2.js} +3 -3
  9. package/dist/{chunk-LGD2HW6Q.js → chunk-6XMMFCL3.js} +3 -3
  10. package/dist/{chunk-DTPN2JVO.js → chunk-7IIVYNLK.js} +2 -2
  11. package/dist/{chunk-MHIBHQRQ.js → chunk-AEWJKZ5E.js} +2 -2
  12. package/dist/{chunk-PNLDFZHQ.js → chunk-ATQZERNG.js} +2 -2
  13. package/dist/{chunk-UC3N7GBQ.js → chunk-BGKDC7P5.js} +2 -2
  14. package/dist/{chunk-62MUTXDW.js → chunk-CHZF364E.js} +2 -2
  15. package/dist/{chunk-2XSDDIP5.js → chunk-D6MTIPFD.js} +2 -2
  16. package/dist/{chunk-PVZ6RBA3.js → chunk-FVSXYMVW.js} +3 -3
  17. package/dist/{chunk-6MSNCO7J.js → chunk-GWDGD7GY.js} +2 -2
  18. package/dist/{chunk-OBQ7DEIU.js → chunk-H7HMKGGB.js} +7 -7
  19. package/dist/{chunk-KRJMJB4J.js → chunk-HGHPZ2W3.js} +12 -8
  20. package/dist/chunk-HGHPZ2W3.js.map +1 -0
  21. package/dist/{chunk-P7YUHXF3.js → chunk-JYI63V47.js} +4 -4
  22. package/dist/{chunk-KQKLOOZ2.js → chunk-KLAVOOWV.js} +2 -2
  23. package/dist/{chunk-LEG43263.js → chunk-MREBZQA6.js} +5 -5
  24. package/dist/{chunk-NVD6E7ML.js → chunk-NBLCQBR5.js} +8 -8
  25. package/dist/{chunk-DO4JTAXE.js → chunk-PL57P5LU.js} +4 -4
  26. package/dist/{chunk-FAKU44NN.js → chunk-Q7L6CXIO.js} +5 -5
  27. package/dist/{chunk-AIQ7XUU5.js → chunk-SGQOW5SD.js} +4 -4
  28. package/dist/{chunk-USWXI6Y3.js → chunk-TOIBWK5Z.js} +2 -2
  29. package/dist/{chunk-XPEFH4LN.js → chunk-V34YWUSC.js} +2 -2
  30. package/dist/{chunk-XUYNONNG.js → chunk-VSDI6ASO.js} +8 -8
  31. package/dist/{chunk-YYHUDQ2C.js → chunk-XC37XDMH.js} +2 -2
  32. package/dist/{chunk-5KSQF4L2.js → chunk-XPZODTJ6.js} +12 -2
  33. package/dist/{chunk-5KSQF4L2.js.map → chunk-XPZODTJ6.js.map} +1 -1
  34. package/dist/{chunk-2SELLY6Y.js → chunk-YBTBVOVA.js} +4 -4
  35. package/dist/{chunk-ZAP6ACXW.js → chunk-YFTNNQMV.js} +5 -5
  36. package/dist/{cli-circuit-breaker-V5K3EFCL.js → cli-circuit-breaker-4HDWO5Z6.js} +3 -3
  37. package/dist/cli.js +39 -39
  38. package/dist/{composite-router-EVZ345UR.js → composite-router-W6GXLKWB.js} +2 -2
  39. package/dist/{consensus-vote-6MBJNJNI.js → consensus-vote-KTWHGAOH.js} +15 -15
  40. package/dist/{context-retriever-NX3XWPJH.js → context-retriever-67M3IABW.js} +8 -8
  41. package/dist/{doctor-deep-MRWSVCTT.js → doctor-deep-NPQZPZDO.js} +3 -3
  42. package/dist/{expert-bridge-4MMZ3IUZ.js → expert-bridge-3AW3OHAY.js} +4 -4
  43. package/dist/{factory-UX6P7AUY.js → factory-PIXCR3PF.js} +5 -5
  44. package/dist/{factory-IFJY73H2.js → factory-XSRDHJ34.js} +8 -8
  45. package/dist/{improvement-review-TB7MUZCZ.js → improvement-review-JQVHCWVU.js} +5 -5
  46. package/dist/index.js +29 -29
  47. package/dist/{init-opencode-XZS3T7O4.js → init-opencode-Q6XT7UTP.js} +5 -5
  48. package/dist/{issue-triage-BJXIOSDB.js → issue-triage-JCGAF2P3.js} +6 -6
  49. package/dist/{pr-reviewer-helpers-QIQI53HQ.js → pr-reviewer-helpers-QBETICKQ.js} +4 -4
  50. package/dist/{registry-command-C3366WTC.js → registry-command-3SKGILCO.js} +2 -2
  51. package/dist/{repo-security-plan-QN3QULHR.js → repo-security-plan-C5RDE3QO.js} +3 -3
  52. package/dist/{research-helpers-synthesize-4CM6ZODP.js → research-helpers-synthesize-J4Z7MY7X.js} +4 -4
  53. package/dist/{routing-memory-DCPIJPNX.js → routing-memory-ZZKVDP2K.js} +2 -2
  54. package/dist/{session-memory-GSWNIVYF.js → session-memory-2QINLWDR.js} +3 -3
  55. package/dist/{setup-command-YMLDQOSM.js → setup-command-UJ5VETUJ.js} +13 -13
  56. package/dist/{setup-config-PXXDTAFZ.js → setup-config-SUN272BA.js} +3 -3
  57. package/dist/{setup-custom-api-ODWGNSXY.js → setup-custom-api-AEUEX4IF.js} +3 -3
  58. package/dist/{tool-memory-NJRRSHDL.js → tool-memory-VS2GRBV3.js} +5 -5
  59. package/dist/{unified-registry-RCWX3FB3.js → unified-registry-O4FIGTBJ.js} +9 -9
  60. package/dist/{weather-report-LHUNTDCX.js → weather-report-3FB5MXHV.js} +2 -2
  61. package/package.json +1 -1
  62. package/dist/chunk-KRJMJB4J.js.map +0 -1
  63. /package/dist/{child-mcp-config-3IX4DFNS.js.map → child-mcp-config-RSM4VNFS.js.map} +0 -0
  64. /package/dist/{chunk-TTGJDWIG.js.map → chunk-3PXN234X.js.map} +0 -0
  65. /package/dist/{chunk-TE66HW3D.js.map → chunk-3ZLPS4XC.js.map} +0 -0
  66. /package/dist/{chunk-CUJUNXKQ.js.map → chunk-4IDGRIWO.js.map} +0 -0
  67. /package/dist/{chunk-MSINKE6X.js.map → chunk-66EE7Y2F.js.map} +0 -0
  68. /package/dist/{chunk-GKLCBQCF.js.map → chunk-6N2WQBJU.js.map} +0 -0
  69. /package/dist/{chunk-GACT2UFT.js.map → chunk-6VT7ODBT.js.map} +0 -0
  70. /package/dist/{chunk-TJMQU4HJ.js.map → chunk-6WYBSYJ2.js.map} +0 -0
  71. /package/dist/{chunk-LGD2HW6Q.js.map → chunk-6XMMFCL3.js.map} +0 -0
  72. /package/dist/{chunk-DTPN2JVO.js.map → chunk-7IIVYNLK.js.map} +0 -0
  73. /package/dist/{chunk-MHIBHQRQ.js.map → chunk-AEWJKZ5E.js.map} +0 -0
  74. /package/dist/{chunk-PNLDFZHQ.js.map → chunk-ATQZERNG.js.map} +0 -0
  75. /package/dist/{chunk-UC3N7GBQ.js.map → chunk-BGKDC7P5.js.map} +0 -0
  76. /package/dist/{chunk-62MUTXDW.js.map → chunk-CHZF364E.js.map} +0 -0
  77. /package/dist/{chunk-2XSDDIP5.js.map → chunk-D6MTIPFD.js.map} +0 -0
  78. /package/dist/{chunk-PVZ6RBA3.js.map → chunk-FVSXYMVW.js.map} +0 -0
  79. /package/dist/{chunk-6MSNCO7J.js.map → chunk-GWDGD7GY.js.map} +0 -0
  80. /package/dist/{chunk-OBQ7DEIU.js.map → chunk-H7HMKGGB.js.map} +0 -0
  81. /package/dist/{chunk-P7YUHXF3.js.map → chunk-JYI63V47.js.map} +0 -0
  82. /package/dist/{chunk-KQKLOOZ2.js.map → chunk-KLAVOOWV.js.map} +0 -0
  83. /package/dist/{chunk-LEG43263.js.map → chunk-MREBZQA6.js.map} +0 -0
  84. /package/dist/{chunk-NVD6E7ML.js.map → chunk-NBLCQBR5.js.map} +0 -0
  85. /package/dist/{chunk-DO4JTAXE.js.map → chunk-PL57P5LU.js.map} +0 -0
  86. /package/dist/{chunk-FAKU44NN.js.map → chunk-Q7L6CXIO.js.map} +0 -0
  87. /package/dist/{chunk-AIQ7XUU5.js.map → chunk-SGQOW5SD.js.map} +0 -0
  88. /package/dist/{chunk-USWXI6Y3.js.map → chunk-TOIBWK5Z.js.map} +0 -0
  89. /package/dist/{chunk-XPEFH4LN.js.map → chunk-V34YWUSC.js.map} +0 -0
  90. /package/dist/{chunk-XUYNONNG.js.map → chunk-VSDI6ASO.js.map} +0 -0
  91. /package/dist/{chunk-YYHUDQ2C.js.map → chunk-XC37XDMH.js.map} +0 -0
  92. /package/dist/{chunk-2SELLY6Y.js.map → chunk-YBTBVOVA.js.map} +0 -0
  93. /package/dist/{chunk-ZAP6ACXW.js.map → chunk-YFTNNQMV.js.map} +0 -0
  94. /package/dist/{cli-circuit-breaker-V5K3EFCL.js.map → cli-circuit-breaker-4HDWO5Z6.js.map} +0 -0
  95. /package/dist/{composite-router-EVZ345UR.js.map → composite-router-W6GXLKWB.js.map} +0 -0
  96. /package/dist/{consensus-vote-6MBJNJNI.js.map → consensus-vote-KTWHGAOH.js.map} +0 -0
  97. /package/dist/{context-retriever-NX3XWPJH.js.map → context-retriever-67M3IABW.js.map} +0 -0
  98. /package/dist/{doctor-deep-MRWSVCTT.js.map → doctor-deep-NPQZPZDO.js.map} +0 -0
  99. /package/dist/{expert-bridge-4MMZ3IUZ.js.map → expert-bridge-3AW3OHAY.js.map} +0 -0
  100. /package/dist/{factory-IFJY73H2.js.map → factory-PIXCR3PF.js.map} +0 -0
  101. /package/dist/{factory-UX6P7AUY.js.map → factory-XSRDHJ34.js.map} +0 -0
  102. /package/dist/{improvement-review-TB7MUZCZ.js.map → improvement-review-JQVHCWVU.js.map} +0 -0
  103. /package/dist/{init-opencode-XZS3T7O4.js.map → init-opencode-Q6XT7UTP.js.map} +0 -0
  104. /package/dist/{issue-triage-BJXIOSDB.js.map → issue-triage-JCGAF2P3.js.map} +0 -0
  105. /package/dist/{pr-reviewer-helpers-QIQI53HQ.js.map → pr-reviewer-helpers-QBETICKQ.js.map} +0 -0
  106. /package/dist/{registry-command-C3366WTC.js.map → registry-command-3SKGILCO.js.map} +0 -0
  107. /package/dist/{repo-security-plan-QN3QULHR.js.map → repo-security-plan-C5RDE3QO.js.map} +0 -0
  108. /package/dist/{research-helpers-synthesize-4CM6ZODP.js.map → research-helpers-synthesize-J4Z7MY7X.js.map} +0 -0
  109. /package/dist/{routing-memory-DCPIJPNX.js.map → routing-memory-ZZKVDP2K.js.map} +0 -0
  110. /package/dist/{session-memory-GSWNIVYF.js.map → session-memory-2QINLWDR.js.map} +0 -0
  111. /package/dist/{setup-command-YMLDQOSM.js.map → setup-command-UJ5VETUJ.js.map} +0 -0
  112. /package/dist/{setup-config-PXXDTAFZ.js.map → setup-config-SUN272BA.js.map} +0 -0
  113. /package/dist/{setup-custom-api-ODWGNSXY.js.map → setup-custom-api-AEUEX4IF.js.map} +0 -0
  114. /package/dist/{tool-memory-NJRRSHDL.js.map → tool-memory-VS2GRBV3.js.map} +0 -0
  115. /package/dist/{unified-registry-RCWX3FB3.js.map → unified-registry-O4FIGTBJ.js.map} +0 -0
  116. /package/dist/{weather-report-LHUNTDCX.js.map → weather-report-3FB5MXHV.js.map} +0 -0
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-6T3EPABN.js";
6
6
  import {
7
7
  SessionMemory
8
- } from "./chunk-GACT2UFT.js";
8
+ } from "./chunk-6VT7ODBT.js";
9
9
  import {
10
10
  StatsOnlyAdapter,
11
11
  ensureSharedMemoryRegistry
@@ -15,7 +15,7 @@ import {
15
15
  } from "./chunk-KSQSWEFH.js";
16
16
  import {
17
17
  generateId
18
- } from "./chunk-YYHUDQ2C.js";
18
+ } from "./chunk-XC37XDMH.js";
19
19
  import {
20
20
  ErrorCode,
21
21
  NexusError,
@@ -28,7 +28,7 @@ import {
28
28
  getTimeProvider,
29
29
  ok,
30
30
  setSharedMobiMemDbPathResolver
31
- } from "./chunk-CUJUNXKQ.js";
31
+ } from "./chunk-4IDGRIWO.js";
32
32
  import {
33
33
  nexusDataPath
34
34
  } from "./chunk-DHVMSIT5.js";
@@ -5552,4 +5552,4 @@ export {
5552
5552
  reinitializeMemoryBackends,
5553
5553
  ToolMemoryManager
5554
5554
  };
5555
- //# sourceMappingURL=chunk-P7YUHXF3.js.map
5555
+ //# sourceMappingURL=chunk-JYI63V47.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getTimeProvider
3
- } from "./chunk-CUJUNXKQ.js";
3
+ } from "./chunk-4IDGRIWO.js";
4
4
 
5
5
  // src/security/audit-trail.ts
6
6
  var MAX_EVENTS = 1e4;
@@ -205,4 +205,4 @@ export {
205
205
  createGraphAuditBridge,
206
206
  createAuditTrail
207
207
  };
208
- //# sourceMappingURL=chunk-KQKLOOZ2.js.map
208
+ //# sourceMappingURL=chunk-KLAVOOWV.js.map
@@ -1,19 +1,19 @@
1
1
  import {
2
2
  resolveToken
3
- } from "./chunk-USWXI6Y3.js";
3
+ } from "./chunk-TOIBWK5Z.js";
4
4
  import {
5
5
  REGISTRY_PATH,
6
6
  getProjectRoot,
7
7
  loadPapersRegistry,
8
8
  loadTechniquesRegistry,
9
9
  savePapersRegistry
10
- } from "./chunk-MHIBHQRQ.js";
10
+ } from "./chunk-AEWJKZ5E.js";
11
11
  import {
12
12
  resolveInsideRoot
13
13
  } from "./chunk-NUBSJGQZ.js";
14
14
  import {
15
15
  getToolMemory
16
- } from "./chunk-P7YUHXF3.js";
16
+ } from "./chunk-JYI63V47.js";
17
17
  import {
18
18
  capitalizeWords,
19
19
  truncateSentence
@@ -38,7 +38,7 @@ import {
38
38
  getTimeProvider,
39
39
  ok,
40
40
  registerPersistentDistillerFactory
41
- } from "./chunk-CUJUNXKQ.js";
41
+ } from "./chunk-4IDGRIWO.js";
42
42
  import {
43
43
  ensureLearningDir,
44
44
  getRulesFile
@@ -4090,4 +4090,4 @@ export {
4090
4090
  DEFAULT_CONTEXT_BUDGET_TOKENS,
4091
4091
  getContextPromptPrefix
4092
4092
  };
4093
- //# sourceMappingURL=chunk-LEG43263.js.map
4093
+ //# sourceMappingURL=chunk-MREBZQA6.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  readOpenAICompatEnv
3
- } from "./chunk-DO4JTAXE.js";
3
+ } from "./chunk-PL57P5LU.js";
4
4
  import {
5
5
  resolveInsideRoot
6
6
  } from "./chunk-NUBSJGQZ.js";
@@ -10,10 +10,10 @@ import {
10
10
  import {
11
11
  createAllAdapters,
12
12
  probeCli
13
- } from "./chunk-KRJMJB4J.js";
13
+ } from "./chunk-HGHPZ2W3.js";
14
14
  import {
15
15
  DEFAULTS
16
- } from "./chunk-6MSNCO7J.js";
16
+ } from "./chunk-GWDGD7GY.js";
17
17
  import {
18
18
  CliNameSchema,
19
19
  DEFAULT_CAPABILITIES,
@@ -30,7 +30,7 @@ import {
30
30
  ok,
31
31
  symbols,
32
32
  writeLine
33
- } from "./chunk-CUJUNXKQ.js";
33
+ } from "./chunk-4IDGRIWO.js";
34
34
  import {
35
35
  getLearningDir,
36
36
  getOutcomesFile,
@@ -46,7 +46,7 @@ import {
46
46
  } from "./chunk-DHVMSIT5.js";
47
47
 
48
48
  // src/version.ts
49
- var VERSION = true ? "2.173.7" : "dev";
49
+ var VERSION = true ? "2.173.8" : "dev";
50
50
 
51
51
  // src/config/schemas-core.ts
52
52
  import { z } from "zod";
@@ -2182,7 +2182,7 @@ async function runDoctorFix(result) {
2182
2182
  writeLine2("\u2500".repeat(40));
2183
2183
  let fixCount = 0;
2184
2184
  if (!result.dataDirectory.rootExists || result.dataDirectory.subdirectories.some((d) => !d.exists || !d.writable)) {
2185
- const { runSetup } = await import("./setup-command-YMLDQOSM.js");
2185
+ const { runSetup } = await import("./setup-command-UJ5VETUJ.js");
2186
2186
  const setupResult = runSetup({
2187
2187
  skipMcp: true,
2188
2188
  skipRules: true,
@@ -2196,7 +2196,7 @@ async function runDoctorFix(result) {
2196
2196
  }
2197
2197
  }
2198
2198
  if (!result.configFile.found) {
2199
- const { runConfigInitSync } = await import("./setup-config-PXXDTAFZ.js");
2199
+ const { runConfigInitSync } = await import("./setup-config-SUN272BA.js");
2200
2200
  const configResult = runConfigInitSync(process.cwd(), false, false);
2201
2201
  if (configResult.success && configResult.created) {
2202
2202
  writeLine2(`\u2713 Generated config: ${configResult.path}`);
@@ -2295,4 +2295,4 @@ export {
2295
2295
  startStdioServer,
2296
2296
  closeServer
2297
2297
  };
2298
- //# sourceMappingURL=chunk-NVD6E7ML.js.map
2298
+ //# sourceMappingURL=chunk-NBLCQBR5.js.map
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  computeCostDetail,
3
3
  recordUsageEvent
4
- } from "./chunk-MSINKE6X.js";
4
+ } from "./chunk-66EE7Y2F.js";
5
5
  import {
6
6
  BaseAdapter,
7
7
  createStream,
8
8
  planOptionalParams,
9
9
  requireApiKey,
10
10
  validateApiKeyPresence
11
- } from "./chunk-PNLDFZHQ.js";
11
+ } from "./chunk-ATQZERNG.js";
12
12
  import {
13
13
  ConfigError,
14
14
  ModelCapability,
@@ -19,7 +19,7 @@ import {
19
19
  getTimeProvider,
20
20
  getTokenEstimator,
21
21
  ok
22
- } from "./chunk-CUJUNXKQ.js";
22
+ } from "./chunk-4IDGRIWO.js";
23
23
 
24
24
  // src/adapters/openai-types.ts
25
25
  var OPENAI_MODELS = {
@@ -795,4 +795,4 @@ export {
795
795
  discoverModels,
796
796
  buildOpenAICompatAdapters
797
797
  };
798
- //# sourceMappingURL=chunk-DO4JTAXE.js.map
798
+ //# sourceMappingURL=chunk-PL57P5LU.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  GitHubProvider,
3
3
  ScmError
4
- } from "./chunk-DTPN2JVO.js";
4
+ } from "./chunk-7IIVYNLK.js";
5
5
  import {
6
6
  ROLE_DEFAULT_TRUST,
7
7
  ReputationCache,
@@ -11,17 +11,17 @@ import {
11
11
  gateWithReputation,
12
12
  resolveReputationGatingMode,
13
13
  sanitizeInput
14
- } from "./chunk-GKLCBQCF.js";
14
+ } from "./chunk-6N2WQBJU.js";
15
15
  import {
16
16
  emitPolicyEvent
17
- } from "./chunk-KQKLOOZ2.js";
17
+ } from "./chunk-KLAVOOWV.js";
18
18
  import {
19
19
  CLI_SUBPROCESS_TIMEOUTS,
20
20
  createLogger,
21
21
  err,
22
22
  getTimeProvider,
23
23
  ok
24
- } from "./chunk-CUJUNXKQ.js";
24
+ } from "./chunk-4IDGRIWO.js";
25
25
 
26
26
  // src/security/trust-classifier.ts
27
27
  function mapAuthorAssociation(association) {
@@ -1211,4 +1211,4 @@ export {
1211
1211
  IssueTriage,
1212
1212
  createIssueTriage
1213
1213
  };
1214
- //# sourceMappingURL=chunk-FAKU44NN.js.map
1214
+ //# sourceMappingURL=chunk-Q7L6CXIO.js.map
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  GitHubProvider,
3
3
  ScmError
4
- } from "./chunk-DTPN2JVO.js";
4
+ } from "./chunk-7IIVYNLK.js";
5
5
  import {
6
6
  resolveToken
7
- } from "./chunk-USWXI6Y3.js";
7
+ } from "./chunk-TOIBWK5Z.js";
8
8
  import {
9
9
  err,
10
10
  ok
11
- } from "./chunk-CUJUNXKQ.js";
11
+ } from "./chunk-4IDGRIWO.js";
12
12
 
13
13
  // src/scm/factory.ts
14
14
  async function createScmProvider(config) {
@@ -41,4 +41,4 @@ export {
41
41
  createScmProvider,
42
42
  createGitHubProvider
43
43
  };
44
- //# sourceMappingURL=chunk-AIQ7XUU5.js.map
44
+ //# sourceMappingURL=chunk-SGQOW5SD.js.map
@@ -2,7 +2,7 @@ import {
2
2
  createLogger,
3
3
  err,
4
4
  ok
5
- } from "./chunk-CUJUNXKQ.js";
5
+ } from "./chunk-4IDGRIWO.js";
6
6
 
7
7
  // src/scm/token-resolver.ts
8
8
  import { execFile } from "child_process";
@@ -87,4 +87,4 @@ export {
87
87
  hasToken,
88
88
  getTokenEnvVars
89
89
  };
90
- //# sourceMappingURL=chunk-USWXI6Y3.js.map
90
+ //# sourceMappingURL=chunk-TOIBWK5Z.js.map
@@ -3,7 +3,7 @@ import {
3
3
  MODEL_IDS,
4
4
  getTimeProvider,
5
5
  resolveModelIdentitySync
6
- } from "./chunk-CUJUNXKQ.js";
6
+ } from "./chunk-4IDGRIWO.js";
7
7
 
8
8
  // src/config/model-availability.ts
9
9
  var DEFAULT_TTL_MS = 6e4;
@@ -150,4 +150,4 @@ export {
150
150
  resetAvailabilityCache,
151
151
  filterAvailableModels
152
152
  };
153
- //# sourceMappingURL=chunk-XPEFH4LN.js.map
153
+ //# sourceMappingURL=chunk-V34YWUSC.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  computeCostDetail
3
- } from "./chunk-MSINKE6X.js";
3
+ } from "./chunk-66EE7Y2F.js";
4
4
  import {
5
5
  DEFAULT_CONSENSUS_CONFIG,
6
6
  DEFAULT_INCREMENTAL_QUORUM_CONFIG,
@@ -18,20 +18,20 @@ import {
18
18
  toolSuccess,
19
19
  withProgressHeartbeat,
20
20
  wrapToolWithTimeout
21
- } from "./chunk-PVZ6RBA3.js";
21
+ } from "./chunk-FVSXYMVW.js";
22
22
  import {
23
23
  createEvent,
24
24
  getGlobalRegistry
25
- } from "./chunk-2SELLY6Y.js";
25
+ } from "./chunk-YBTBVOVA.js";
26
26
  import {
27
27
  getToolMemory
28
- } from "./chunk-P7YUHXF3.js";
28
+ } from "./chunk-JYI63V47.js";
29
29
  import {
30
30
  authRemediation,
31
31
  delay,
32
32
  getAvailableClis,
33
33
  withTimeout
34
- } from "./chunk-KRJMJB4J.js";
34
+ } from "./chunk-HGHPZ2W3.js";
35
35
  import {
36
36
  AgentError,
37
37
  CLI_NAMES,
@@ -59,7 +59,7 @@ import {
59
59
  registerPersistentOutcomeStoreFactory,
60
60
  resolveClassGuardMs,
61
61
  resolveVoteTimeout
62
- } from "./chunk-CUJUNXKQ.js";
62
+ } from "./chunk-4IDGRIWO.js";
63
63
  import {
64
64
  ensureLearningDir,
65
65
  getOutcomesFile
@@ -5866,7 +5866,7 @@ async function processVotesWithCascade(engineVotes, opts) {
5866
5866
  var CONTRARIAN_ESCALATION_THRESHOLD = 0.8;
5867
5867
  async function runContrarianCheck(proposal, log) {
5868
5868
  try {
5869
- const { executeExpert } = await import("./expert-bridge-4MMZ3IUZ.js");
5869
+ const { executeExpert } = await import("./expert-bridge-3AW3OHAY.js");
5870
5870
  const prompt = [
5871
5871
  "You are a contrarian analyst. Your job is to find reasons this proposal should be REJECTED.",
5872
5872
  "Look for: YAGNI (not needed), MISALIGNED (wrong tech/architecture), SECURITY_RISK, SCOPE_CREEP.",
@@ -6393,4 +6393,4 @@ export {
6393
6393
  CONSENSUS_VOTE_OUTPUT_SCHEMA,
6394
6394
  registerConsensusVoteTool
6395
6395
  };
6396
- //# sourceMappingURL=chunk-XUYNONNG.js.map
6396
+ //# sourceMappingURL=chunk-VSDI6ASO.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  getRandomProvider,
3
3
  getTimeProvider
4
- } from "./chunk-CUJUNXKQ.js";
4
+ } from "./chunk-4IDGRIWO.js";
5
5
 
6
6
  // src/utils/id-utils.ts
7
7
  import { randomUUID } from "crypto";
@@ -24,4 +24,4 @@ export {
24
24
  generateHyphenId,
25
25
  generateUUID
26
26
  };
27
- //# sourceMappingURL=chunk-YYHUDQ2C.js.map
27
+ //# sourceMappingURL=chunk-XC37XDMH.js.map
@@ -8,7 +8,7 @@ import {
8
8
  getTimeProvider,
9
9
  isRateLimitText,
10
10
  ok
11
- } from "./chunk-CUJUNXKQ.js";
11
+ } from "./chunk-4IDGRIWO.js";
12
12
 
13
13
  // src/cli-adapters/circuit-breaker-types.ts
14
14
  var CircuitErrorCode = {
@@ -390,6 +390,16 @@ var DEFAULT_CONFIG = {
390
390
  maxFallbackAttempts: 2
391
391
  };
392
392
  var defaultCliCircuitBreakerRegistry = new CircuitBreakerRegistry();
393
+ var registryLogger = createLogger({ component: "cli-circuit-breaker" });
394
+ defaultCliCircuitBreakerRegistry.addGlobalStateChangeListener((event) => {
395
+ registryLogger.warn("CLI circuit state changed", {
396
+ cli: event.cliName,
397
+ previousState: event.previousState,
398
+ newState: event.newState,
399
+ failureCount: event.failureCount,
400
+ reason: event.reason
401
+ });
402
+ });
393
403
  function getDefaultCliCircuitBreakerRegistry() {
394
404
  return defaultCliCircuitBreakerRegistry;
395
405
  }
@@ -530,4 +540,4 @@ export {
530
540
  CliCircuitBreakerIntegration,
531
541
  createCliCircuitBreakerIntegration
532
542
  };
533
- //# sourceMappingURL=chunk-5KSQF4L2.js.map
543
+ //# sourceMappingURL=chunk-XPZODTJ6.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli-adapters/circuit-breaker-types.ts","../src/cli-adapters/circuit-breaker.ts","../src/cli-adapters/cli-circuit-breaker.ts"],"sourcesContent":["/**\n * nexus-agents/cli-adapters - Circuit Breaker Types\n *\n * Type definitions and error classes for the circuit breaker pattern.\n *\n * (Source: Issue #81 - Circuit breaker for CLI failures)\n */\n\nimport { NexusError, ErrorCode } from '../core/errors.js';\nimport { isRateLimitText } from '../adapters/rate-limit-detector.js';\nimport type { CliName } from './types.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Circuit breaker states.\n */\nexport type CircuitState = 'closed' | 'open' | 'half-open';\n\n/**\n * Categories of failures for circuit breaker decisions.\n */\nexport type FailureCategory =\n | 'timeout' // CLI didn't respond in time\n | 'crash' // Process crashed or exited unexpectedly\n | 'authentication' // OAuth/auth failure\n | 'rate_limit' // Rate limit exceeded\n | 'connection' // MCP connection failed\n | 'unknown'; // Uncategorized failure\n\n/**\n * Configuration options for circuit breaker.\n */\nexport interface CircuitBreakerConfig {\n /** Number of failures before opening circuit (default: 5) */\n readonly failureThreshold: number;\n /** Time in ms before attempting recovery (default: 30000) */\n readonly resetTimeoutMs: number;\n /** Successful calls needed in half-open to close (default: 2) */\n readonly halfOpenSuccessThreshold: number;\n /** Whether to count timeouts as failures (default: true) */\n readonly countTimeoutsAsFailures: boolean;\n /** Whether to count auth failures as failures (default: false) */\n readonly countAuthFailuresAsFailures: boolean;\n /** Whether to count rate limit errors as failures (default: false) */\n readonly countRateLimitsAsFailures: boolean;\n /** Maximum number of requests allowed in half-open state (default: 3) */\n readonly halfOpenMaxRequests: number;\n}\n\n/**\n * Circuit breaker state snapshot.\n */\nexport interface CircuitBreakerSnapshot {\n /** Current state */\n readonly state: CircuitState;\n /** Total failure count since last closed */\n readonly failureCount: number;\n /** Success count in half-open state */\n readonly successCount: number;\n /** Timestamp of last failure */\n readonly lastFailureTime: number | null;\n /** Timestamp of last state change */\n readonly lastStateChange: number;\n /** Requests in current half-open window */\n readonly halfOpenRequests: number;\n /** Configuration */\n readonly config: CircuitBreakerConfig;\n}\n\n/**\n * Event emitted on circuit state changes.\n */\nexport interface CircuitStateChangeEvent {\n /** CLI name */\n readonly cliName: CliName;\n /** Previous state */\n readonly previousState: CircuitState;\n /** New state */\n readonly newState: CircuitState;\n /** Timestamp of change */\n readonly timestamp: number;\n /** Failure count at time of change */\n readonly failureCount: number;\n /** Reason for state change */\n readonly reason: string;\n}\n\n/**\n * Event listener for circuit state changes.\n */\nexport type CircuitStateChangeListener = (event: CircuitStateChangeEvent) => void;\n\n/**\n * Interface for circuit breaker operations.\n */\nexport interface ICircuitBreaker {\n /**\n * Executes a function with circuit breaker protection.\n */\n execute<T>(fn: () => Promise<T>): Promise<import('../core/index.js').Result<T, CircuitError>>;\n\n /**\n * Gets the current circuit state.\n */\n getState(): CircuitState;\n\n /**\n * Gets a full snapshot of circuit breaker state.\n */\n getSnapshot(): CircuitBreakerSnapshot;\n\n /**\n * Manually resets the circuit breaker to closed state.\n */\n reset(): void;\n\n /**\n * Records a failure manually (for external failure detection).\n */\n recordFailure(category: FailureCategory): void;\n\n /**\n * Records a success manually (for external success detection).\n */\n recordSuccess(): void;\n}\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/**\n * Error codes specific to circuit breaker.\n */\nexport const CircuitErrorCode = {\n CIRCUIT_OPEN: 'CIRCUIT_OPEN',\n CIRCUIT_HALF_OPEN_REJECTED: 'CIRCUIT_HALF_OPEN_REJECTED',\n EXECUTION_FAILED: 'EXECUTION_FAILED',\n} as const;\n\nexport type CircuitErrorCode = (typeof CircuitErrorCode)[keyof typeof CircuitErrorCode];\n\n// ============================================================================\n// Error Class\n// ============================================================================\n\n/**\n * Error thrown when circuit breaker blocks a request.\n */\nexport class CircuitError extends NexusError {\n readonly circuitErrorCode: CircuitErrorCode;\n readonly cliName: CliName;\n readonly circuitState: CircuitState;\n readonly failureCategory?: FailureCategory;\n\n constructor(\n message: string,\n options: {\n circuitErrorCode: CircuitErrorCode;\n cliName: CliName;\n circuitState: CircuitState;\n failureCategory?: FailureCategory;\n cause?: Error;\n }\n ) {\n const baseOptions: { code: ErrorCode; cause?: Error; context: Record<string, unknown> } = {\n code: ErrorCode.INTERNAL_ERROR,\n context: {\n circuitErrorCode: options.circuitErrorCode,\n cliName: options.cliName,\n circuitState: options.circuitState,\n },\n };\n if (options.cause !== undefined) {\n baseOptions.cause = options.cause;\n }\n if (options.failureCategory !== undefined) {\n baseOptions.context['failureCategory'] = options.failureCategory;\n }\n super(message, baseOptions);\n this.name = 'CircuitError';\n this.circuitErrorCode = options.circuitErrorCode;\n this.cliName = options.cliName;\n this.circuitState = options.circuitState;\n if (options.failureCategory !== undefined) {\n this.failureCategory = options.failureCategory;\n }\n }\n}\n\n// ============================================================================\n// Default Configuration\n// ============================================================================\n\n/**\n * Default circuit breaker configuration.\n */\nexport const DEFAULT_CIRCUIT_BREAKER_CONFIG: CircuitBreakerConfig = {\n failureThreshold: 5,\n resetTimeoutMs: 30_000,\n halfOpenSuccessThreshold: 2,\n countTimeoutsAsFailures: true,\n countAuthFailuresAsFailures: false,\n countRateLimitsAsFailures: true,\n halfOpenMaxRequests: 3,\n} as const;\n\n// ============================================================================\n// Error Categorization Patterns\n// ============================================================================\n\n/**\n * Pattern matchers for categorizing errors.\n */\nconst TIMEOUT_PATTERNS = ['timeout', 'timed out'];\nconst AUTH_PATTERNS = ['auth', 'unauthorized', 'forbidden', 'oauth'];\nconst CONNECTION_PATTERNS = [\n 'connection',\n 'econnrefused',\n 'enotfound',\n 'mcp',\n 'eaddrinuse',\n 'address already in use',\n];\nconst CRASH_PATTERNS = ['crash', 'exited', 'killed', 'sigterm', 'sigkill'];\n\n/**\n * Checks if text contains any of the patterns.\n */\nfunction matchesPatterns(text: string, patterns: string[]): boolean {\n return patterns.some((pattern) => text.includes(pattern));\n}\n\n/**\n * Categorizes an error into a failure category.\n */\nexport function categorizeError(error: unknown): FailureCategory {\n if (!(error instanceof Error)) {\n return 'unknown';\n }\n\n const message = error.message.toLowerCase();\n const name = error.name.toLowerCase();\n const combined = `${message} ${name}`;\n\n if (matchesPatterns(combined, TIMEOUT_PATTERNS)) return 'timeout';\n if (matchesPatterns(combined, AUTH_PATTERNS)) return 'authentication';\n if (isRateLimitText(combined)) return 'rate_limit';\n if (matchesPatterns(combined, CONNECTION_PATTERNS)) return 'connection';\n if (matchesPatterns(combined, CRASH_PATTERNS)) return 'crash';\n\n return 'unknown';\n}\n","/**\n * nexus-agents/cli-adapters - Circuit Breaker Implementation\n *\n * Implements the circuit breaker pattern to handle CLI failures gracefully\n * and prevent cascade failures in the multi-CLI mesh.\n *\n * (Source: Issue #81 - Circuit breaker for CLI failures)\n * (Source: Martin Fowler's Circuit Breaker pattern)\n */\n\nimport type { Result } from '../core/index.js';\nimport { getErrorMessage, err, ok, getTimeProvider } from '../core/index.js';\n\nimport { ErrorCode, type ModelError } from '../core/errors.js';\n\nimport type { CliName, CliErrorCode } from './types.js';\nimport {\n CircuitError,\n CircuitErrorCode,\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n categorizeError,\n type CircuitState,\n type FailureCategory,\n type CircuitBreakerConfig,\n type CircuitBreakerSnapshot,\n type CircuitStateChangeEvent,\n type CircuitStateChangeListener,\n type ICircuitBreaker,\n} from './circuit-breaker-types.js';\n\n// Re-export all types for convenience\nexport {\n CircuitError,\n CircuitErrorCode,\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n categorizeError,\n type CircuitState,\n type FailureCategory,\n type CircuitBreakerConfig,\n type CircuitBreakerSnapshot,\n type CircuitStateChangeEvent,\n type CircuitStateChangeListener,\n type ICircuitBreaker,\n} from './circuit-breaker-types.js';\n\n// ============================================================================\n// Circuit Breaker Implementation\n// ============================================================================\n\n/**\n * Circuit breaker implementation for CLI adapters.\n *\n * Provides protection against cascading failures by:\n * 1. Tracking failure counts\n * 2. Opening circuit when threshold exceeded\n * 3. Allowing gradual recovery through half-open state\n */\nexport class CliCircuitBreaker implements ICircuitBreaker {\n private state: CircuitState = 'closed';\n private failureCount = 0;\n private successCount = 0;\n private lastFailureTime: number | null = null;\n private lastStateChange: number;\n private halfOpenRequests = 0;\n private readonly listeners: Set<CircuitStateChangeListener> = new Set();\n\n constructor(\n private readonly cliName: CliName,\n private readonly config: CircuitBreakerConfig = DEFAULT_CIRCUIT_BREAKER_CONFIG\n ) {\n this.lastStateChange = getTimeProvider().now();\n }\n\n /**\n * Executes a function with circuit breaker protection.\n */\n async execute<T>(fn: () => Promise<T>): Promise<Result<T, CircuitError>> {\n const canExecute = this.canExecute();\n if (!canExecute.ok) {\n return canExecute;\n }\n\n try {\n const result = await fn();\n this.onSuccess();\n return ok(result);\n } catch (error) {\n const category = categorizeError(error);\n if (this.shouldCountFailure(category)) {\n this.onFailure(category);\n }\n return err(this.createExecutionError(error, category));\n }\n }\n\n getState(): CircuitState {\n this.checkStateTransition();\n return this.state;\n }\n\n getSnapshot(): CircuitBreakerSnapshot {\n this.checkStateTransition();\n return {\n state: this.state,\n failureCount: this.failureCount,\n successCount: this.successCount,\n lastFailureTime: this.lastFailureTime,\n lastStateChange: this.lastStateChange,\n halfOpenRequests: this.halfOpenRequests,\n config: this.config,\n };\n }\n\n reset(): void {\n const previousState = this.state;\n this.state = 'closed';\n this.failureCount = 0;\n this.successCount = 0;\n this.lastFailureTime = null;\n this.halfOpenRequests = 0;\n this.lastStateChange = getTimeProvider().now();\n\n if (previousState !== 'closed') {\n this.emitStateChange(previousState, 'closed', 'Manual reset');\n }\n }\n\n recordFailure(category: FailureCategory): void {\n if (this.shouldCountFailure(category)) {\n this.onFailure(category);\n }\n }\n\n recordSuccess(): void {\n this.onSuccess();\n }\n\n addStateChangeListener(listener: CircuitStateChangeListener): void {\n this.listeners.add(listener);\n }\n\n removeStateChangeListener(listener: CircuitStateChangeListener): void {\n this.listeners.delete(listener);\n }\n\n // -------------------------------------------------------------------------\n // Private Methods\n // -------------------------------------------------------------------------\n\n private canExecute(): Result<true, CircuitError> {\n this.checkStateTransition();\n\n if (this.state === 'closed') {\n return ok(true);\n }\n\n if (this.state === 'open') {\n return err(\n new CircuitError(`Circuit is open for CLI: ${this.cliName}`, {\n circuitErrorCode: CircuitErrorCode.CIRCUIT_OPEN,\n cliName: this.cliName,\n circuitState: this.state,\n })\n );\n }\n\n // half-open state\n if (this.halfOpenRequests >= this.config.halfOpenMaxRequests) {\n return err(\n new CircuitError(`Circuit half-open request limit reached for CLI: ${this.cliName}`, {\n circuitErrorCode: CircuitErrorCode.CIRCUIT_HALF_OPEN_REJECTED,\n cliName: this.cliName,\n circuitState: this.state,\n })\n );\n }\n this.halfOpenRequests++;\n return ok(true);\n }\n\n private checkStateTransition(): void {\n if (this.state === 'open' && this.lastFailureTime !== null) {\n const elapsed = getTimeProvider().now() - this.lastFailureTime;\n if (elapsed >= this.config.resetTimeoutMs) {\n this.transitionTo('half-open', 'Reset timeout elapsed');\n }\n }\n }\n\n private onSuccess(): void {\n if (this.state === 'closed') {\n this.failureCount = 0;\n } else if (this.state === 'half-open') {\n this.successCount++;\n if (this.successCount >= this.config.halfOpenSuccessThreshold) {\n const reason = `${String(this.successCount)} consecutive successes in half-open state`;\n this.transitionTo('closed', reason);\n }\n }\n }\n\n private onFailure(category: FailureCategory): void {\n this.failureCount++;\n this.lastFailureTime = getTimeProvider().now();\n\n if (this.state === 'closed' && this.failureCount >= this.config.failureThreshold) {\n const reason = `Failure threshold (${String(this.config.failureThreshold)}) exceeded`;\n this.transitionTo('open', reason);\n } else if (this.state === 'half-open') {\n this.transitionTo('open', `Failure during half-open recovery (category: ${category})`);\n }\n }\n\n private transitionTo(newState: CircuitState, reason: string): void {\n const previousState = this.state;\n this.state = newState;\n this.lastStateChange = getTimeProvider().now();\n\n if (newState === 'closed') {\n this.failureCount = 0;\n this.successCount = 0;\n this.halfOpenRequests = 0;\n } else if (newState === 'half-open') {\n // #3026 finding 5: pre-fix `failureCount` carried over across\n // recovery cycles. transitionTo('open',…) only zeroes counts on\n // 'closed', so a half-open→open→half-open flaky pattern grew\n // `failureCount` monotonically across cycles. The count served\n // its threshold purpose when we opened the circuit; resetting on\n // 'half-open' restores the documented per-cycle semantic that\n // operator dashboards / alerts read from `getSnapshot()`.\n this.failureCount = 0;\n this.successCount = 0;\n this.halfOpenRequests = 0;\n }\n\n this.emitStateChange(previousState, newState, reason);\n }\n\n private emitStateChange(\n previousState: CircuitState,\n newState: CircuitState,\n reason: string\n ): void {\n const event: CircuitStateChangeEvent = {\n cliName: this.cliName,\n previousState,\n newState,\n timestamp: this.lastStateChange,\n failureCount: this.failureCount,\n reason,\n };\n\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch {\n // Ignore listener errors to prevent cascade\n }\n }\n }\n\n private shouldCountFailure(category: FailureCategory): boolean {\n if (category === 'timeout') return this.config.countTimeoutsAsFailures;\n if (category === 'authentication') return this.config.countAuthFailuresAsFailures;\n if (category === 'rate_limit') return this.config.countRateLimitsAsFailures;\n return true;\n }\n\n private createExecutionError(error: unknown, category: FailureCategory): CircuitError {\n const message = getErrorMessage(error);\n const cause = error instanceof Error ? error : new Error(String(error));\n return new CircuitError(`CLI execution failed: ${message}`, {\n circuitErrorCode: CircuitErrorCode.EXECUTION_FAILED,\n cliName: this.cliName,\n circuitState: this.state,\n failureCategory: category,\n cause,\n });\n }\n}\n\n// ============================================================================\n// Registry\n// ============================================================================\n\n/**\n * Registry for managing per-CLI circuit breakers.\n */\nexport class CircuitBreakerRegistry {\n private readonly breakers: Map<CliName, CliCircuitBreaker> = new Map();\n private readonly globalListeners: Set<CircuitStateChangeListener> = new Set();\n\n constructor(private readonly defaultConfig: Partial<CircuitBreakerConfig> = {}) {}\n\n getBreaker(cliName: CliName, config?: Partial<CircuitBreakerConfig>): CliCircuitBreaker {\n let breaker = this.breakers.get(cliName);\n\n if (!breaker) {\n const mergedConfig: CircuitBreakerConfig = {\n ...DEFAULT_CIRCUIT_BREAKER_CONFIG,\n ...this.defaultConfig,\n ...config,\n };\n breaker = new CliCircuitBreaker(cliName, mergedConfig);\n\n for (const listener of this.globalListeners) {\n breaker.addStateChangeListener(listener);\n }\n\n this.breakers.set(cliName, breaker);\n }\n\n return breaker;\n }\n\n isOpen(cliName: CliName): boolean {\n return this.breakers.get(cliName)?.getState() === 'open';\n }\n\n getAllSnapshots(): Map<CliName, CircuitBreakerSnapshot> {\n const snapshots = new Map<CliName, CircuitBreakerSnapshot>();\n for (const [name, breaker] of this.breakers) {\n snapshots.set(name, breaker.getSnapshot());\n }\n return snapshots;\n }\n\n resetAll(): void {\n for (const breaker of this.breakers.values()) {\n breaker.reset();\n }\n }\n\n reset(cliName: CliName): void {\n this.breakers.get(cliName)?.reset();\n }\n\n addGlobalStateChangeListener(listener: CircuitStateChangeListener): void {\n this.globalListeners.add(listener);\n for (const breaker of this.breakers.values()) {\n breaker.addStateChangeListener(listener);\n }\n }\n\n removeGlobalStateChangeListener(listener: CircuitStateChangeListener): void {\n this.globalListeners.delete(listener);\n for (const breaker of this.breakers.values()) {\n breaker.removeStateChangeListener(listener);\n }\n }\n\n getHealthyClis(): CliName[] {\n const healthy: CliName[] = [];\n for (const [name, breaker] of this.breakers) {\n if (breaker.getState() === 'closed') {\n healthy.push(name);\n }\n }\n return healthy;\n }\n\n getUnhealthyClis(): CliName[] {\n const unhealthy: CliName[] = [];\n for (const [name, breaker] of this.breakers) {\n const state = breaker.getState();\n if (state === 'open' || state === 'half-open') {\n unhealthy.push(name);\n }\n }\n return unhealthy;\n }\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Maps CLI error codes to failure categories.\n */\nexport function mapCliErrorToCategory(errorCode: CliErrorCode): FailureCategory {\n const mapping: Record<string, FailureCategory> = {\n TIMEOUT: 'timeout',\n NOT_AUTHENTICATED: 'authentication',\n RATE_LIMITED: 'rate_limit',\n CONNECTION_ERROR: 'connection',\n };\n return mapping[errorCode] ?? 'unknown';\n}\n\n/**\n * Maps a direct-API {@link ModelError} to a circuit-breaker failure category.\n *\n * Mirrors {@link mapCliErrorToCategory} for the IModelAdapter layer (#3423):\n * API failures must drive the same breaker degradation/failover learning that\n * CLI subprocess failures already get. Maps by the structured `error.code`\n * first, then falls back to message-pattern categorization via\n * {@link categorizeError} (which returns `'unknown'` if nothing matches).\n *\n * The fallback is what turns a generic `MODEL_ERROR` whose message reads\n * \"connection refused\" into a `connection` category instead of `unknown`.\n */\nexport function mapModelErrorToCategory(error: ModelError): FailureCategory {\n switch (error.code) {\n case ErrorCode.MODEL_TIMEOUT:\n case ErrorCode.TIMEOUT_ERROR:\n return 'timeout';\n case ErrorCode.UNAUTHORIZED:\n return 'authentication';\n case ErrorCode.MODEL_RATE_LIMITED:\n case ErrorCode.RATE_LIMIT_ERROR:\n return 'rate_limit';\n case ErrorCode.MODEL_UNAVAILABLE:\n case ErrorCode.MODEL_NOT_FOUND:\n // Intentional reuse of `connection`: there is no dedicated \"endpoint gone /\n // model retired\" category, and `connection` is a counted, failover-driving\n // category — the right behaviour for an unavailable/missing model.\n return 'connection';\n default:\n // MODEL_ERROR and any other code: fall back to message-pattern matching.\n return categorizeError(error);\n }\n}\n\n// `createCircuitBreakerRegistryWithMetrics` and the\n// `Capacity Monitor Integration` section\n// (`integrateCapacityMonitorWithCircuitBreaker` + the\n// `CapacityMonitorIntegrationConfig` interface and its default config)\n// were removed in #3018 — both had only test-file callers in the tree.\n// The `CircuitBreakerRegistry` above is what production adapters use;\n// if metrics-logging or capacity-monitor integration come back as real\n// requirements, reintroduce them alongside the consumer code in the\n// same PR (activation-or-delete YAGNI — same pattern as #2937–#2940).\n","/**\n * nexus-agents/cli-adapters - CLI Circuit Breaker Integration\n *\n * Wraps CLI adapter calls with circuit breaker pattern for resilient\n * multi-CLI execution with automatic fallback on failures.\n *\n * (Source: Issue #359 - Integrate circuit breaker with CLI adapters)\n */\n\nimport type { Result, ILogger } from '../core/index.js';\nimport { ok, err, createLogger, getTimeProvider } from '../core/index.js';\nimport type { TaskCategory } from '../config/task-specialization-types.js';\nimport type { FallbackTaskType } from './task-classifier.js';\nimport { getFallbackChainForCategory } from './fallback-chains.js';\nimport type { ICliAdapter, CliName, CliTask, CliResponse, CliError } from './types.js';\nimport {\n CircuitBreakerRegistry,\n CircuitError,\n mapCliErrorToCategory,\n type CircuitBreakerConfig,\n type CircuitBreakerSnapshot,\n type CircuitStateChangeListener,\n} from './circuit-breaker.js';\n\n/** Maps canonical TaskCategory (10 types) to FallbackTaskType (5 types). */\nconst CATEGORY_TO_FALLBACK: Record<TaskCategory, FallbackTaskType> = {\n code_generation: 'code',\n code_review: 'code',\n testing: 'code',\n research: 'research',\n exploration: 'research',\n documentation: 'documentation',\n architecture: 'analysis',\n security_review: 'analysis',\n planning: 'analysis',\n devops: 'general',\n};\n\n/** Configuration for CLI circuit breaker integration. */\nexport interface CliCircuitBreakerConfig {\n readonly perCliConfig?: Partial<Record<CliName, Partial<CircuitBreakerConfig>>>;\n readonly fallbackChain?: ReadonlyArray<CliName>;\n readonly enableFallback?: boolean;\n readonly maxFallbackAttempts?: number;\n}\n\n/** Result of a circuit-protected execution with fallback info. */\nexport interface CircuitProtectedResult {\n readonly response: CliResponse;\n readonly executedBy: CliName;\n readonly usedFallback: boolean;\n readonly fallbackAttempts?: ReadonlyArray<CliName>;\n}\n\n/** Health status for all CLIs with circuit state. */\nexport interface CliCircuitHealthStatus {\n readonly clis: ReadonlyArray<{\n readonly name: CliName;\n readonly healthy: boolean;\n readonly circuitState: 'closed' | 'open' | 'half-open';\n readonly failureCount: number;\n readonly lastFailureTime: number | null;\n }>;\n readonly systemHealthy: boolean;\n readonly healthyCount: number;\n readonly timestamp: number;\n}\n\n/** Interface for CLI circuit breaker integration. */\nexport interface ICliCircuitBreakerIntegration {\n execute(\n adapter: ICliAdapter,\n task: CliTask,\n taskCategory?: TaskCategory\n ): Promise<Result<CircuitProtectedResult, CircuitError | CliError>>;\n getHealthStatus(): CliCircuitHealthStatus;\n getCircuitSnapshots(): Map<CliName, CircuitBreakerSnapshot>;\n resetCircuit(cliName: CliName): void;\n resetAllCircuits(): void;\n addStateChangeListener(listener: CircuitStateChangeListener): void;\n}\n\nconst DEFAULT_FALLBACK_CHAIN: ReadonlyArray<CliName> = ['claude', 'gemini', 'codex', 'opencode'];\nconst DEFAULT_CONFIG: Required<CliCircuitBreakerConfig> = {\n perCliConfig: {},\n fallbackChain: DEFAULT_FALLBACK_CHAIN,\n enableFallback: true,\n maxFallbackAttempts: 2,\n};\nconst defaultCliCircuitBreakerRegistry = new CircuitBreakerRegistry();\n\n/** Returns the shared CLI circuit-breaker registry used by default integrations. */\nexport function getDefaultCliCircuitBreakerRegistry(): CircuitBreakerRegistry {\n return defaultCliCircuitBreakerRegistry;\n}\n\n/**\n * Reads the current snapshot for a CLI without creating a new breaker.\n *\n * `undefined` means no circuit state is known yet, so callers should fail open.\n */\nexport function getCliCircuitBreakerSnapshot(cliName: CliName): CircuitBreakerSnapshot | undefined {\n return defaultCliCircuitBreakerRegistry.getAllSnapshots().get(cliName);\n}\n\n/**\n * Integrates circuit breaker pattern with CLI adapters.\n * Provides automatic fallback when a CLI's circuit opens.\n */\nexport class CliCircuitBreakerIntegration implements ICliCircuitBreakerIntegration {\n private readonly registry: CircuitBreakerRegistry;\n private readonly adapters: Map<CliName, ICliAdapter> = new Map();\n private readonly config: Required<CliCircuitBreakerConfig>;\n private readonly logger: ILogger;\n\n constructor(\n adapters: ReadonlyArray<ICliAdapter>,\n config?: CliCircuitBreakerConfig,\n logger?: ILogger\n ) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.logger = logger ?? createLogger({ component: 'cli-circuit-breaker-integration' });\n this.registry =\n config === undefined ? defaultCliCircuitBreakerRegistry : new CircuitBreakerRegistry();\n for (const adapter of adapters) {\n this.adapters.set(adapter.name, adapter);\n this.registry.getBreaker(adapter.name, this.config.perCliConfig[adapter.name]);\n }\n }\n\n async execute(\n adapter: ICliAdapter,\n task: CliTask,\n taskCategory?: TaskCategory\n ): Promise<Result<CircuitProtectedResult, CircuitError | CliError>> {\n const primaryCli = adapter.name;\n const fallbackAttempts: CliName[] = [];\n let lastError: CircuitError | CliError | undefined;\n\n const primaryResult = await this.executeWithBreaker(adapter, task);\n if (primaryResult.ok) {\n return ok({ response: primaryResult.value, executedBy: primaryCli, usedFallback: false });\n }\n lastError = primaryResult.error;\n\n if (!this.config.enableFallback || !(lastError instanceof CircuitError)) {\n return err(lastError);\n }\n\n for (const cli of this.getFallbackClis(primaryCli, taskCategory).slice(\n 0,\n this.config.maxFallbackAttempts\n )) {\n const fallbackAdapter = this.adapters.get(cli);\n if (!fallbackAdapter) continue;\n fallbackAttempts.push(cli);\n this.logger.info('Attempting fallback', { from: primaryCli, to: cli });\n const result = await this.executeWithBreaker(fallbackAdapter, task);\n if (result.ok) {\n return ok({\n response: result.value,\n executedBy: cli,\n usedFallback: true,\n fallbackAttempts,\n });\n }\n lastError = result.error;\n }\n\n this.logger.warn('All fallback attempts failed', { primaryCli, fallbackAttempts });\n return err(lastError);\n }\n\n getHealthStatus(): CliCircuitHealthStatus {\n const snapshots = this.registry.getAllSnapshots();\n const clis: CliCircuitHealthStatus['clis'][number][] = [];\n let healthyCount = 0;\n for (const name of this.adapters.keys()) {\n const snapshot = snapshots.get(name);\n if (!snapshot) continue;\n const healthy = snapshot.state === 'closed';\n if (healthy) healthyCount++;\n clis.push({\n name,\n healthy,\n circuitState: snapshot.state,\n failureCount: snapshot.failureCount,\n lastFailureTime: snapshot.lastFailureTime,\n });\n }\n return {\n clis,\n systemHealthy: healthyCount > 0,\n healthyCount,\n timestamp: getTimeProvider().now(),\n };\n }\n\n getCircuitSnapshots(): Map<CliName, CircuitBreakerSnapshot> {\n const allSnapshots = this.registry.getAllSnapshots();\n const snapshots = new Map<CliName, CircuitBreakerSnapshot>();\n for (const name of this.adapters.keys()) {\n const snapshot = allSnapshots.get(name);\n if (snapshot !== undefined) {\n snapshots.set(name, snapshot);\n }\n }\n return snapshots;\n }\n\n resetCircuit(cliName: CliName): void {\n this.registry.reset(cliName);\n this.logger.info('Circuit reset', { cliName });\n }\n\n resetAllCircuits(): void {\n this.registry.resetAll();\n this.logger.info('All circuits reset');\n }\n\n addStateChangeListener(listener: CircuitStateChangeListener): void {\n this.registry.addGlobalStateChangeListener(listener);\n }\n\n private async executeWithBreaker(\n adapter: ICliAdapter,\n task: CliTask\n ): Promise<Result<CliResponse, CircuitError | CliError>> {\n const breaker = this.registry.getBreaker(adapter.name);\n const result = await breaker.execute(async () => {\n const execResult = await adapter.execute(task);\n if (!execResult.ok) {\n breaker.recordFailure(mapCliErrorToCategory(execResult.error.code));\n const wrappedError = new Error(execResult.error.message);\n (wrappedError as Error & { cliError: CliError }).cliError = execResult.error;\n throw wrappedError;\n }\n return execResult.value;\n });\n\n if (!result.ok) {\n if (result.error.circuitErrorCode === 'CIRCUIT_OPEN') return err(result.error);\n const wrapped = result.error.cause as (Error & { cliError?: CliError }) | undefined;\n if (wrapped?.cliError) return err(wrapped.cliError);\n return err(result.error);\n }\n return ok(result.value);\n }\n\n private getFallbackClis(excludeCli: CliName, taskCategory?: TaskCategory): CliName[] {\n const chain =\n taskCategory !== undefined\n ? getFallbackChainForCategory(taskCategory, CATEGORY_TO_FALLBACK[taskCategory])\n : this.config.fallbackChain;\n return [...chain].filter(\n (cli) => cli !== excludeCli && !this.registry.isOpen(cli) && this.adapters.has(cli)\n );\n }\n}\n\n/** Creates a CLI circuit breaker integration with the specified adapters. */\nexport function createCliCircuitBreakerIntegration(\n adapters: ReadonlyArray<ICliAdapter>,\n config?: CliCircuitBreakerConfig,\n logger?: ILogger\n): CliCircuitBreakerIntegration {\n return new CliCircuitBreakerIntegration(adapters, config, logger);\n}\n"],"mappings":";;;;;;;;;;;;;AAyIO,IAAM,mBAAmB;AAAA,EAC9B,cAAc;AAAA,EACd,4BAA4B;AAAA,EAC5B,kBAAkB;AACpB;AAWO,IAAM,eAAN,cAA2B,WAAW;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,SACA,SAOA;AACA,UAAM,cAAoF;AAAA,MACxF,MAAM,UAAU;AAAA,MAChB,SAAS;AAAA,QACP,kBAAkB,QAAQ;AAAA,QAC1B,SAAS,QAAQ;AAAA,QACjB,cAAc,QAAQ;AAAA,MACxB;AAAA,IACF;AACA,QAAI,QAAQ,UAAU,QAAW;AAC/B,kBAAY,QAAQ,QAAQ;AAAA,IAC9B;AACA,QAAI,QAAQ,oBAAoB,QAAW;AACzC,kBAAY,QAAQ,iBAAiB,IAAI,QAAQ;AAAA,IACnD;AACA,UAAM,SAAS,WAAW;AAC1B,SAAK,OAAO;AACZ,SAAK,mBAAmB,QAAQ;AAChC,SAAK,UAAU,QAAQ;AACvB,SAAK,eAAe,QAAQ;AAC5B,QAAI,QAAQ,oBAAoB,QAAW;AACzC,WAAK,kBAAkB,QAAQ;AAAA,IACjC;AAAA,EACF;AACF;AASO,IAAM,iCAAuD;AAAA,EAClE,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,0BAA0B;AAAA,EAC1B,yBAAyB;AAAA,EACzB,6BAA6B;AAAA,EAC7B,2BAA2B;AAAA,EAC3B,qBAAqB;AACvB;AASA,IAAM,mBAAmB,CAAC,WAAW,WAAW;AAChD,IAAM,gBAAgB,CAAC,QAAQ,gBAAgB,aAAa,OAAO;AACnE,IAAM,sBAAsB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,IAAM,iBAA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AM;AAClE;","names":[]}
1
+ {"version":3,"sources":["../src/cli-adapters/circuit-breaker-types.ts","../src/cli-adapters/circuit-breaker.ts","../src/cli-adapters/cli-circuit-breaker.ts"],"sourcesContent":["/**\n * nexus-agents/cli-adapters - Circuit Breaker Types\n *\n * Type definitions and error classes for the circuit breaker pattern.\n *\n * (Source: Issue #81 - Circuit breaker for CLI failures)\n */\n\nimport { NexusError, ErrorCode } from '../core/errors.js';\nimport { isRateLimitText } from '../adapters/rate-limit-detector.js';\nimport type { CliName } from './types.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Circuit breaker states.\n */\nexport type CircuitState = 'closed' | 'open' | 'half-open';\n\n/**\n * Categories of failures for circuit breaker decisions.\n */\nexport type FailureCategory =\n | 'timeout' // CLI didn't respond in time\n | 'crash' // Process crashed or exited unexpectedly\n | 'authentication' // OAuth/auth failure\n | 'rate_limit' // Rate limit exceeded\n | 'connection' // MCP connection failed\n | 'unknown'; // Uncategorized failure\n\n/**\n * Configuration options for circuit breaker.\n */\nexport interface CircuitBreakerConfig {\n /** Number of failures before opening circuit (default: 5) */\n readonly failureThreshold: number;\n /** Time in ms before attempting recovery (default: 30000) */\n readonly resetTimeoutMs: number;\n /** Successful calls needed in half-open to close (default: 2) */\n readonly halfOpenSuccessThreshold: number;\n /** Whether to count timeouts as failures (default: true) */\n readonly countTimeoutsAsFailures: boolean;\n /** Whether to count auth failures as failures (default: false) */\n readonly countAuthFailuresAsFailures: boolean;\n /** Whether to count rate limit errors as failures (default: false) */\n readonly countRateLimitsAsFailures: boolean;\n /** Maximum number of requests allowed in half-open state (default: 3) */\n readonly halfOpenMaxRequests: number;\n}\n\n/**\n * Circuit breaker state snapshot.\n */\nexport interface CircuitBreakerSnapshot {\n /** Current state */\n readonly state: CircuitState;\n /** Total failure count since last closed */\n readonly failureCount: number;\n /** Success count in half-open state */\n readonly successCount: number;\n /** Timestamp of last failure */\n readonly lastFailureTime: number | null;\n /** Timestamp of last state change */\n readonly lastStateChange: number;\n /** Requests in current half-open window */\n readonly halfOpenRequests: number;\n /** Configuration */\n readonly config: CircuitBreakerConfig;\n}\n\n/**\n * Event emitted on circuit state changes.\n */\nexport interface CircuitStateChangeEvent {\n /** CLI name */\n readonly cliName: CliName;\n /** Previous state */\n readonly previousState: CircuitState;\n /** New state */\n readonly newState: CircuitState;\n /** Timestamp of change */\n readonly timestamp: number;\n /** Failure count at time of change */\n readonly failureCount: number;\n /** Reason for state change */\n readonly reason: string;\n}\n\n/**\n * Event listener for circuit state changes.\n */\nexport type CircuitStateChangeListener = (event: CircuitStateChangeEvent) => void;\n\n/**\n * Interface for circuit breaker operations.\n */\nexport interface ICircuitBreaker {\n /**\n * Executes a function with circuit breaker protection.\n */\n execute<T>(fn: () => Promise<T>): Promise<import('../core/index.js').Result<T, CircuitError>>;\n\n /**\n * Gets the current circuit state.\n */\n getState(): CircuitState;\n\n /**\n * Gets a full snapshot of circuit breaker state.\n */\n getSnapshot(): CircuitBreakerSnapshot;\n\n /**\n * Manually resets the circuit breaker to closed state.\n */\n reset(): void;\n\n /**\n * Records a failure manually (for external failure detection).\n */\n recordFailure(category: FailureCategory): void;\n\n /**\n * Records a success manually (for external success detection).\n */\n recordSuccess(): void;\n}\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/**\n * Error codes specific to circuit breaker.\n */\nexport const CircuitErrorCode = {\n CIRCUIT_OPEN: 'CIRCUIT_OPEN',\n CIRCUIT_HALF_OPEN_REJECTED: 'CIRCUIT_HALF_OPEN_REJECTED',\n EXECUTION_FAILED: 'EXECUTION_FAILED',\n} as const;\n\nexport type CircuitErrorCode = (typeof CircuitErrorCode)[keyof typeof CircuitErrorCode];\n\n// ============================================================================\n// Error Class\n// ============================================================================\n\n/**\n * Error thrown when circuit breaker blocks a request.\n */\nexport class CircuitError extends NexusError {\n readonly circuitErrorCode: CircuitErrorCode;\n readonly cliName: CliName;\n readonly circuitState: CircuitState;\n readonly failureCategory?: FailureCategory;\n\n constructor(\n message: string,\n options: {\n circuitErrorCode: CircuitErrorCode;\n cliName: CliName;\n circuitState: CircuitState;\n failureCategory?: FailureCategory;\n cause?: Error;\n }\n ) {\n const baseOptions: { code: ErrorCode; cause?: Error; context: Record<string, unknown> } = {\n code: ErrorCode.INTERNAL_ERROR,\n context: {\n circuitErrorCode: options.circuitErrorCode,\n cliName: options.cliName,\n circuitState: options.circuitState,\n },\n };\n if (options.cause !== undefined) {\n baseOptions.cause = options.cause;\n }\n if (options.failureCategory !== undefined) {\n baseOptions.context['failureCategory'] = options.failureCategory;\n }\n super(message, baseOptions);\n this.name = 'CircuitError';\n this.circuitErrorCode = options.circuitErrorCode;\n this.cliName = options.cliName;\n this.circuitState = options.circuitState;\n if (options.failureCategory !== undefined) {\n this.failureCategory = options.failureCategory;\n }\n }\n}\n\n// ============================================================================\n// Default Configuration\n// ============================================================================\n\n/**\n * Default circuit breaker configuration.\n */\nexport const DEFAULT_CIRCUIT_BREAKER_CONFIG: CircuitBreakerConfig = {\n failureThreshold: 5,\n resetTimeoutMs: 30_000,\n halfOpenSuccessThreshold: 2,\n countTimeoutsAsFailures: true,\n countAuthFailuresAsFailures: false,\n countRateLimitsAsFailures: true,\n halfOpenMaxRequests: 3,\n} as const;\n\n// ============================================================================\n// Error Categorization Patterns\n// ============================================================================\n\n/**\n * Pattern matchers for categorizing errors.\n */\nconst TIMEOUT_PATTERNS = ['timeout', 'timed out'];\nconst AUTH_PATTERNS = ['auth', 'unauthorized', 'forbidden', 'oauth'];\nconst CONNECTION_PATTERNS = [\n 'connection',\n 'econnrefused',\n 'enotfound',\n 'mcp',\n 'eaddrinuse',\n 'address already in use',\n];\nconst CRASH_PATTERNS = ['crash', 'exited', 'killed', 'sigterm', 'sigkill'];\n\n/**\n * Checks if text contains any of the patterns.\n */\nfunction matchesPatterns(text: string, patterns: string[]): boolean {\n return patterns.some((pattern) => text.includes(pattern));\n}\n\n/**\n * Categorizes an error into a failure category.\n */\nexport function categorizeError(error: unknown): FailureCategory {\n if (!(error instanceof Error)) {\n return 'unknown';\n }\n\n const message = error.message.toLowerCase();\n const name = error.name.toLowerCase();\n const combined = `${message} ${name}`;\n\n if (matchesPatterns(combined, TIMEOUT_PATTERNS)) return 'timeout';\n if (matchesPatterns(combined, AUTH_PATTERNS)) return 'authentication';\n if (isRateLimitText(combined)) return 'rate_limit';\n if (matchesPatterns(combined, CONNECTION_PATTERNS)) return 'connection';\n if (matchesPatterns(combined, CRASH_PATTERNS)) return 'crash';\n\n return 'unknown';\n}\n","/**\n * nexus-agents/cli-adapters - Circuit Breaker Implementation\n *\n * Implements the circuit breaker pattern to handle CLI failures gracefully\n * and prevent cascade failures in the multi-CLI mesh.\n *\n * (Source: Issue #81 - Circuit breaker for CLI failures)\n * (Source: Martin Fowler's Circuit Breaker pattern)\n */\n\nimport type { Result } from '../core/index.js';\nimport { getErrorMessage, err, ok, getTimeProvider } from '../core/index.js';\n\nimport { ErrorCode, type ModelError } from '../core/errors.js';\n\nimport type { CliName, CliErrorCode } from './types.js';\nimport {\n CircuitError,\n CircuitErrorCode,\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n categorizeError,\n type CircuitState,\n type FailureCategory,\n type CircuitBreakerConfig,\n type CircuitBreakerSnapshot,\n type CircuitStateChangeEvent,\n type CircuitStateChangeListener,\n type ICircuitBreaker,\n} from './circuit-breaker-types.js';\n\n// Re-export all types for convenience\nexport {\n CircuitError,\n CircuitErrorCode,\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n categorizeError,\n type CircuitState,\n type FailureCategory,\n type CircuitBreakerConfig,\n type CircuitBreakerSnapshot,\n type CircuitStateChangeEvent,\n type CircuitStateChangeListener,\n type ICircuitBreaker,\n} from './circuit-breaker-types.js';\n\n// ============================================================================\n// Circuit Breaker Implementation\n// ============================================================================\n\n/**\n * Circuit breaker implementation for CLI adapters.\n *\n * Provides protection against cascading failures by:\n * 1. Tracking failure counts\n * 2. Opening circuit when threshold exceeded\n * 3. Allowing gradual recovery through half-open state\n */\nexport class CliCircuitBreaker implements ICircuitBreaker {\n private state: CircuitState = 'closed';\n private failureCount = 0;\n private successCount = 0;\n private lastFailureTime: number | null = null;\n private lastStateChange: number;\n private halfOpenRequests = 0;\n private readonly listeners: Set<CircuitStateChangeListener> = new Set();\n\n constructor(\n private readonly cliName: CliName,\n private readonly config: CircuitBreakerConfig = DEFAULT_CIRCUIT_BREAKER_CONFIG\n ) {\n this.lastStateChange = getTimeProvider().now();\n }\n\n /**\n * Executes a function with circuit breaker protection.\n */\n async execute<T>(fn: () => Promise<T>): Promise<Result<T, CircuitError>> {\n const canExecute = this.canExecute();\n if (!canExecute.ok) {\n return canExecute;\n }\n\n try {\n const result = await fn();\n this.onSuccess();\n return ok(result);\n } catch (error) {\n const category = categorizeError(error);\n if (this.shouldCountFailure(category)) {\n this.onFailure(category);\n }\n return err(this.createExecutionError(error, category));\n }\n }\n\n getState(): CircuitState {\n this.checkStateTransition();\n return this.state;\n }\n\n getSnapshot(): CircuitBreakerSnapshot {\n this.checkStateTransition();\n return {\n state: this.state,\n failureCount: this.failureCount,\n successCount: this.successCount,\n lastFailureTime: this.lastFailureTime,\n lastStateChange: this.lastStateChange,\n halfOpenRequests: this.halfOpenRequests,\n config: this.config,\n };\n }\n\n reset(): void {\n const previousState = this.state;\n this.state = 'closed';\n this.failureCount = 0;\n this.successCount = 0;\n this.lastFailureTime = null;\n this.halfOpenRequests = 0;\n this.lastStateChange = getTimeProvider().now();\n\n if (previousState !== 'closed') {\n this.emitStateChange(previousState, 'closed', 'Manual reset');\n }\n }\n\n recordFailure(category: FailureCategory): void {\n if (this.shouldCountFailure(category)) {\n this.onFailure(category);\n }\n }\n\n recordSuccess(): void {\n this.onSuccess();\n }\n\n addStateChangeListener(listener: CircuitStateChangeListener): void {\n this.listeners.add(listener);\n }\n\n removeStateChangeListener(listener: CircuitStateChangeListener): void {\n this.listeners.delete(listener);\n }\n\n // -------------------------------------------------------------------------\n // Private Methods\n // -------------------------------------------------------------------------\n\n private canExecute(): Result<true, CircuitError> {\n this.checkStateTransition();\n\n if (this.state === 'closed') {\n return ok(true);\n }\n\n if (this.state === 'open') {\n return err(\n new CircuitError(`Circuit is open for CLI: ${this.cliName}`, {\n circuitErrorCode: CircuitErrorCode.CIRCUIT_OPEN,\n cliName: this.cliName,\n circuitState: this.state,\n })\n );\n }\n\n // half-open state\n if (this.halfOpenRequests >= this.config.halfOpenMaxRequests) {\n return err(\n new CircuitError(`Circuit half-open request limit reached for CLI: ${this.cliName}`, {\n circuitErrorCode: CircuitErrorCode.CIRCUIT_HALF_OPEN_REJECTED,\n cliName: this.cliName,\n circuitState: this.state,\n })\n );\n }\n this.halfOpenRequests++;\n return ok(true);\n }\n\n private checkStateTransition(): void {\n if (this.state === 'open' && this.lastFailureTime !== null) {\n const elapsed = getTimeProvider().now() - this.lastFailureTime;\n if (elapsed >= this.config.resetTimeoutMs) {\n this.transitionTo('half-open', 'Reset timeout elapsed');\n }\n }\n }\n\n private onSuccess(): void {\n if (this.state === 'closed') {\n this.failureCount = 0;\n } else if (this.state === 'half-open') {\n this.successCount++;\n if (this.successCount >= this.config.halfOpenSuccessThreshold) {\n const reason = `${String(this.successCount)} consecutive successes in half-open state`;\n this.transitionTo('closed', reason);\n }\n }\n }\n\n private onFailure(category: FailureCategory): void {\n this.failureCount++;\n this.lastFailureTime = getTimeProvider().now();\n\n if (this.state === 'closed' && this.failureCount >= this.config.failureThreshold) {\n const reason = `Failure threshold (${String(this.config.failureThreshold)}) exceeded`;\n this.transitionTo('open', reason);\n } else if (this.state === 'half-open') {\n this.transitionTo('open', `Failure during half-open recovery (category: ${category})`);\n }\n }\n\n private transitionTo(newState: CircuitState, reason: string): void {\n const previousState = this.state;\n this.state = newState;\n this.lastStateChange = getTimeProvider().now();\n\n if (newState === 'closed') {\n this.failureCount = 0;\n this.successCount = 0;\n this.halfOpenRequests = 0;\n } else if (newState === 'half-open') {\n // #3026 finding 5: pre-fix `failureCount` carried over across\n // recovery cycles. transitionTo('open',…) only zeroes counts on\n // 'closed', so a half-open→open→half-open flaky pattern grew\n // `failureCount` monotonically across cycles. The count served\n // its threshold purpose when we opened the circuit; resetting on\n // 'half-open' restores the documented per-cycle semantic that\n // operator dashboards / alerts read from `getSnapshot()`.\n this.failureCount = 0;\n this.successCount = 0;\n this.halfOpenRequests = 0;\n }\n\n this.emitStateChange(previousState, newState, reason);\n }\n\n private emitStateChange(\n previousState: CircuitState,\n newState: CircuitState,\n reason: string\n ): void {\n const event: CircuitStateChangeEvent = {\n cliName: this.cliName,\n previousState,\n newState,\n timestamp: this.lastStateChange,\n failureCount: this.failureCount,\n reason,\n };\n\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch {\n // Ignore listener errors to prevent cascade\n }\n }\n }\n\n private shouldCountFailure(category: FailureCategory): boolean {\n if (category === 'timeout') return this.config.countTimeoutsAsFailures;\n if (category === 'authentication') return this.config.countAuthFailuresAsFailures;\n if (category === 'rate_limit') return this.config.countRateLimitsAsFailures;\n return true;\n }\n\n private createExecutionError(error: unknown, category: FailureCategory): CircuitError {\n const message = getErrorMessage(error);\n const cause = error instanceof Error ? error : new Error(String(error));\n return new CircuitError(`CLI execution failed: ${message}`, {\n circuitErrorCode: CircuitErrorCode.EXECUTION_FAILED,\n cliName: this.cliName,\n circuitState: this.state,\n failureCategory: category,\n cause,\n });\n }\n}\n\n// ============================================================================\n// Registry\n// ============================================================================\n\n/**\n * Registry for managing per-CLI circuit breakers.\n */\nexport class CircuitBreakerRegistry {\n private readonly breakers: Map<CliName, CliCircuitBreaker> = new Map();\n private readonly globalListeners: Set<CircuitStateChangeListener> = new Set();\n\n constructor(private readonly defaultConfig: Partial<CircuitBreakerConfig> = {}) {}\n\n getBreaker(cliName: CliName, config?: Partial<CircuitBreakerConfig>): CliCircuitBreaker {\n let breaker = this.breakers.get(cliName);\n\n if (!breaker) {\n const mergedConfig: CircuitBreakerConfig = {\n ...DEFAULT_CIRCUIT_BREAKER_CONFIG,\n ...this.defaultConfig,\n ...config,\n };\n breaker = new CliCircuitBreaker(cliName, mergedConfig);\n\n for (const listener of this.globalListeners) {\n breaker.addStateChangeListener(listener);\n }\n\n this.breakers.set(cliName, breaker);\n }\n\n return breaker;\n }\n\n isOpen(cliName: CliName): boolean {\n return this.breakers.get(cliName)?.getState() === 'open';\n }\n\n getAllSnapshots(): Map<CliName, CircuitBreakerSnapshot> {\n const snapshots = new Map<CliName, CircuitBreakerSnapshot>();\n for (const [name, breaker] of this.breakers) {\n snapshots.set(name, breaker.getSnapshot());\n }\n return snapshots;\n }\n\n resetAll(): void {\n for (const breaker of this.breakers.values()) {\n breaker.reset();\n }\n }\n\n reset(cliName: CliName): void {\n this.breakers.get(cliName)?.reset();\n }\n\n addGlobalStateChangeListener(listener: CircuitStateChangeListener): void {\n this.globalListeners.add(listener);\n for (const breaker of this.breakers.values()) {\n breaker.addStateChangeListener(listener);\n }\n }\n\n removeGlobalStateChangeListener(listener: CircuitStateChangeListener): void {\n this.globalListeners.delete(listener);\n for (const breaker of this.breakers.values()) {\n breaker.removeStateChangeListener(listener);\n }\n }\n\n getHealthyClis(): CliName[] {\n const healthy: CliName[] = [];\n for (const [name, breaker] of this.breakers) {\n if (breaker.getState() === 'closed') {\n healthy.push(name);\n }\n }\n return healthy;\n }\n\n getUnhealthyClis(): CliName[] {\n const unhealthy: CliName[] = [];\n for (const [name, breaker] of this.breakers) {\n const state = breaker.getState();\n if (state === 'open' || state === 'half-open') {\n unhealthy.push(name);\n }\n }\n return unhealthy;\n }\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Maps CLI error codes to failure categories.\n */\nexport function mapCliErrorToCategory(errorCode: CliErrorCode): FailureCategory {\n const mapping: Record<string, FailureCategory> = {\n TIMEOUT: 'timeout',\n NOT_AUTHENTICATED: 'authentication',\n RATE_LIMITED: 'rate_limit',\n CONNECTION_ERROR: 'connection',\n };\n return mapping[errorCode] ?? 'unknown';\n}\n\n/**\n * Maps a direct-API {@link ModelError} to a circuit-breaker failure category.\n *\n * Mirrors {@link mapCliErrorToCategory} for the IModelAdapter layer (#3423):\n * API failures must drive the same breaker degradation/failover learning that\n * CLI subprocess failures already get. Maps by the structured `error.code`\n * first, then falls back to message-pattern categorization via\n * {@link categorizeError} (which returns `'unknown'` if nothing matches).\n *\n * The fallback is what turns a generic `MODEL_ERROR` whose message reads\n * \"connection refused\" into a `connection` category instead of `unknown`.\n */\nexport function mapModelErrorToCategory(error: ModelError): FailureCategory {\n switch (error.code) {\n case ErrorCode.MODEL_TIMEOUT:\n case ErrorCode.TIMEOUT_ERROR:\n return 'timeout';\n case ErrorCode.UNAUTHORIZED:\n return 'authentication';\n case ErrorCode.MODEL_RATE_LIMITED:\n case ErrorCode.RATE_LIMIT_ERROR:\n return 'rate_limit';\n case ErrorCode.MODEL_UNAVAILABLE:\n case ErrorCode.MODEL_NOT_FOUND:\n // Intentional reuse of `connection`: there is no dedicated \"endpoint gone /\n // model retired\" category, and `connection` is a counted, failover-driving\n // category — the right behaviour for an unavailable/missing model.\n return 'connection';\n default:\n // MODEL_ERROR and any other code: fall back to message-pattern matching.\n return categorizeError(error);\n }\n}\n\n// `createCircuitBreakerRegistryWithMetrics` and the\n// `Capacity Monitor Integration` section\n// (`integrateCapacityMonitorWithCircuitBreaker` + the\n// `CapacityMonitorIntegrationConfig` interface and its default config)\n// were removed in #3018 — both had only test-file callers in the tree.\n// The `CircuitBreakerRegistry` above is what production adapters use;\n// if metrics-logging or capacity-monitor integration come back as real\n// requirements, reintroduce them alongside the consumer code in the\n// same PR (activation-or-delete YAGNI — same pattern as #2937–#2940).\n","/**\n * nexus-agents/cli-adapters - CLI Circuit Breaker Integration\n *\n * Wraps CLI adapter calls with circuit breaker pattern for resilient\n * multi-CLI execution with automatic fallback on failures.\n *\n * (Source: Issue #359 - Integrate circuit breaker with CLI adapters)\n */\n\nimport type { Result, ILogger } from '../core/index.js';\nimport { ok, err, createLogger, getTimeProvider } from '../core/index.js';\nimport type { TaskCategory } from '../config/task-specialization-types.js';\nimport type { FallbackTaskType } from './task-classifier.js';\nimport { getFallbackChainForCategory } from './fallback-chains.js';\nimport type { ICliAdapter, CliName, CliTask, CliResponse, CliError } from './types.js';\nimport {\n CircuitBreakerRegistry,\n CircuitError,\n mapCliErrorToCategory,\n type CircuitBreakerConfig,\n type CircuitBreakerSnapshot,\n type CircuitStateChangeListener,\n} from './circuit-breaker.js';\n\n/** Maps canonical TaskCategory (10 types) to FallbackTaskType (5 types). */\nconst CATEGORY_TO_FALLBACK: Record<TaskCategory, FallbackTaskType> = {\n code_generation: 'code',\n code_review: 'code',\n testing: 'code',\n research: 'research',\n exploration: 'research',\n documentation: 'documentation',\n architecture: 'analysis',\n security_review: 'analysis',\n planning: 'analysis',\n devops: 'general',\n};\n\n/** Configuration for CLI circuit breaker integration. */\nexport interface CliCircuitBreakerConfig {\n readonly perCliConfig?: Partial<Record<CliName, Partial<CircuitBreakerConfig>>>;\n readonly fallbackChain?: ReadonlyArray<CliName>;\n readonly enableFallback?: boolean;\n readonly maxFallbackAttempts?: number;\n}\n\n/** Result of a circuit-protected execution with fallback info. */\nexport interface CircuitProtectedResult {\n readonly response: CliResponse;\n readonly executedBy: CliName;\n readonly usedFallback: boolean;\n readonly fallbackAttempts?: ReadonlyArray<CliName>;\n}\n\n/** Health status for all CLIs with circuit state. */\nexport interface CliCircuitHealthStatus {\n readonly clis: ReadonlyArray<{\n readonly name: CliName;\n readonly healthy: boolean;\n readonly circuitState: 'closed' | 'open' | 'half-open';\n readonly failureCount: number;\n readonly lastFailureTime: number | null;\n }>;\n readonly systemHealthy: boolean;\n readonly healthyCount: number;\n readonly timestamp: number;\n}\n\n/** Interface for CLI circuit breaker integration. */\nexport interface ICliCircuitBreakerIntegration {\n execute(\n adapter: ICliAdapter,\n task: CliTask,\n taskCategory?: TaskCategory\n ): Promise<Result<CircuitProtectedResult, CircuitError | CliError>>;\n getHealthStatus(): CliCircuitHealthStatus;\n getCircuitSnapshots(): Map<CliName, CircuitBreakerSnapshot>;\n resetCircuit(cliName: CliName): void;\n resetAllCircuits(): void;\n addStateChangeListener(listener: CircuitStateChangeListener): void;\n}\n\nconst DEFAULT_FALLBACK_CHAIN: ReadonlyArray<CliName> = ['claude', 'gemini', 'codex', 'opencode'];\nconst DEFAULT_CONFIG: Required<CliCircuitBreakerConfig> = {\n perCliConfig: {},\n fallbackChain: DEFAULT_FALLBACK_CHAIN,\n enableFallback: true,\n maxFallbackAttempts: 2,\n};\nconst defaultCliCircuitBreakerRegistry = new CircuitBreakerRegistry();\n\n// #4330: the shared registry now gates voter-panel availability, so a CLI can\n// vanish from a panel roster because its circuit opened. Log every transition —\n// otherwise the next person debugging a \"missing voter\" has no trail, and a\n// misclassified transient error silently costs the panel its diversity.\nconst registryLogger = createLogger({ component: 'cli-circuit-breaker' });\ndefaultCliCircuitBreakerRegistry.addGlobalStateChangeListener((event) => {\n registryLogger.warn('CLI circuit state changed', {\n cli: event.cliName,\n previousState: event.previousState,\n newState: event.newState,\n failureCount: event.failureCount,\n reason: event.reason,\n });\n});\n\n/** Returns the shared CLI circuit-breaker registry used by default integrations. */\nexport function getDefaultCliCircuitBreakerRegistry(): CircuitBreakerRegistry {\n return defaultCliCircuitBreakerRegistry;\n}\n\n/**\n * Reads the current snapshot for a CLI without creating a new breaker.\n *\n * `undefined` means no circuit state is known yet, so callers should fail open.\n */\nexport function getCliCircuitBreakerSnapshot(cliName: CliName): CircuitBreakerSnapshot | undefined {\n return defaultCliCircuitBreakerRegistry.getAllSnapshots().get(cliName);\n}\n\n/**\n * Integrates circuit breaker pattern with CLI adapters.\n * Provides automatic fallback when a CLI's circuit opens.\n */\nexport class CliCircuitBreakerIntegration implements ICliCircuitBreakerIntegration {\n private readonly registry: CircuitBreakerRegistry;\n private readonly adapters: Map<CliName, ICliAdapter> = new Map();\n private readonly config: Required<CliCircuitBreakerConfig>;\n private readonly logger: ILogger;\n\n constructor(\n adapters: ReadonlyArray<ICliAdapter>,\n config?: CliCircuitBreakerConfig,\n logger?: ILogger\n ) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.logger = logger ?? createLogger({ component: 'cli-circuit-breaker-integration' });\n this.registry =\n config === undefined ? defaultCliCircuitBreakerRegistry : new CircuitBreakerRegistry();\n for (const adapter of adapters) {\n this.adapters.set(adapter.name, adapter);\n this.registry.getBreaker(adapter.name, this.config.perCliConfig[adapter.name]);\n }\n }\n\n async execute(\n adapter: ICliAdapter,\n task: CliTask,\n taskCategory?: TaskCategory\n ): Promise<Result<CircuitProtectedResult, CircuitError | CliError>> {\n const primaryCli = adapter.name;\n const fallbackAttempts: CliName[] = [];\n let lastError: CircuitError | CliError | undefined;\n\n const primaryResult = await this.executeWithBreaker(adapter, task);\n if (primaryResult.ok) {\n return ok({ response: primaryResult.value, executedBy: primaryCli, usedFallback: false });\n }\n lastError = primaryResult.error;\n\n if (!this.config.enableFallback || !(lastError instanceof CircuitError)) {\n return err(lastError);\n }\n\n for (const cli of this.getFallbackClis(primaryCli, taskCategory).slice(\n 0,\n this.config.maxFallbackAttempts\n )) {\n const fallbackAdapter = this.adapters.get(cli);\n if (!fallbackAdapter) continue;\n fallbackAttempts.push(cli);\n this.logger.info('Attempting fallback', { from: primaryCli, to: cli });\n const result = await this.executeWithBreaker(fallbackAdapter, task);\n if (result.ok) {\n return ok({\n response: result.value,\n executedBy: cli,\n usedFallback: true,\n fallbackAttempts,\n });\n }\n lastError = result.error;\n }\n\n this.logger.warn('All fallback attempts failed', { primaryCli, fallbackAttempts });\n return err(lastError);\n }\n\n getHealthStatus(): CliCircuitHealthStatus {\n const snapshots = this.registry.getAllSnapshots();\n const clis: CliCircuitHealthStatus['clis'][number][] = [];\n let healthyCount = 0;\n for (const name of this.adapters.keys()) {\n const snapshot = snapshots.get(name);\n if (!snapshot) continue;\n const healthy = snapshot.state === 'closed';\n if (healthy) healthyCount++;\n clis.push({\n name,\n healthy,\n circuitState: snapshot.state,\n failureCount: snapshot.failureCount,\n lastFailureTime: snapshot.lastFailureTime,\n });\n }\n return {\n clis,\n systemHealthy: healthyCount > 0,\n healthyCount,\n timestamp: getTimeProvider().now(),\n };\n }\n\n getCircuitSnapshots(): Map<CliName, CircuitBreakerSnapshot> {\n const allSnapshots = this.registry.getAllSnapshots();\n const snapshots = new Map<CliName, CircuitBreakerSnapshot>();\n for (const name of this.adapters.keys()) {\n const snapshot = allSnapshots.get(name);\n if (snapshot !== undefined) {\n snapshots.set(name, snapshot);\n }\n }\n return snapshots;\n }\n\n resetCircuit(cliName: CliName): void {\n this.registry.reset(cliName);\n this.logger.info('Circuit reset', { cliName });\n }\n\n resetAllCircuits(): void {\n this.registry.resetAll();\n this.logger.info('All circuits reset');\n }\n\n addStateChangeListener(listener: CircuitStateChangeListener): void {\n this.registry.addGlobalStateChangeListener(listener);\n }\n\n private async executeWithBreaker(\n adapter: ICliAdapter,\n task: CliTask\n ): Promise<Result<CliResponse, CircuitError | CliError>> {\n const breaker = this.registry.getBreaker(adapter.name);\n const result = await breaker.execute(async () => {\n const execResult = await adapter.execute(task);\n if (!execResult.ok) {\n breaker.recordFailure(mapCliErrorToCategory(execResult.error.code));\n const wrappedError = new Error(execResult.error.message);\n (wrappedError as Error & { cliError: CliError }).cliError = execResult.error;\n throw wrappedError;\n }\n return execResult.value;\n });\n\n if (!result.ok) {\n if (result.error.circuitErrorCode === 'CIRCUIT_OPEN') return err(result.error);\n const wrapped = result.error.cause as (Error & { cliError?: CliError }) | undefined;\n if (wrapped?.cliError) return err(wrapped.cliError);\n return err(result.error);\n }\n return ok(result.value);\n }\n\n private getFallbackClis(excludeCli: CliName, taskCategory?: TaskCategory): CliName[] {\n const chain =\n taskCategory !== undefined\n ? getFallbackChainForCategory(taskCategory, CATEGORY_TO_FALLBACK[taskCategory])\n : this.config.fallbackChain;\n return [...chain].filter(\n (cli) => cli !== excludeCli && !this.registry.isOpen(cli) && this.adapters.has(cli)\n );\n }\n}\n\n/** Creates a CLI circuit breaker integration with the specified adapters. */\nexport function createCliCircuitBreakerIntegration(\n adapters: ReadonlyArray<ICliAdapter>,\n config?: CliCircuitBreakerConfig,\n logger?: ILogger\n): CliCircuitBreakerIntegration {\n return new CliCircuitBreakerIntegration(adapters, config, logger);\n}\n"],"mappings":";;;;;;;;;;;;;AAyIO,IAAM,mBAAmB;AAAA,EAC9B,cAAc;AAAA,EACd,4BAA4B;AAAA,EAC5B,kBAAkB;AACpB;AAWO,IAAM,eAAN,cAA2B,WAAW;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,SACA,SAOA;AACA,UAAM,cAAoF;AAAA,MACxF,MAAM,UAAU;AAAA,MAChB,SAAS;AAAA,QACP,kBAAkB,QAAQ;AAAA,QAC1B,SAAS,QAAQ;AAAA,QACjB,cAAc,QAAQ;AAAA,MACxB;AAAA,IACF;AACA,QAAI,QAAQ,UAAU,QAAW;AAC/B,kBAAY,QAAQ,QAAQ;AAAA,IAC9B;AACA,QAAI,QAAQ,oBAAoB,QAAW;AACzC,kBAAY,QAAQ,iBAAiB,IAAI,QAAQ;AAAA,IACnD;AACA,UAAM,SAAS,WAAW;AAC1B,SAAK,OAAO;AACZ,SAAK,mBAAmB,QAAQ;AAChC,SAAK,UAAU,QAAQ;AACvB,SAAK,eAAe,QAAQ;AAC5B,QAAI,QAAQ,oBAAoB,QAAW;AACzC,WAAK,kBAAkB,QAAQ;AAAA,IACjC;AAAA,EACF;AACF;AASO,IAAM,iCAAuD;AAAA,EAClE,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,0BAA0B;AAAA,EAC1B,yBAAyB;AAAA,EACzB,6BAA6B;AAAA,EAC7B,2BAA2B;AAAA,EAC3B,qBAAqB;AACvB;AASA,IAAM,mBAAmB,CAAC,WAAW,WAAW;AAChD,IAAM,gBAAgB,CAAC,QAAQ,gBAAgB,aAAa,OAAO;AACnE,IAAM,sBAAsB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,IAAM,iBAAiB,CAA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AC5E,KAAK,OAAO;AAClB,WAAO,CAAC,GAAG,KAAK,EAAE;AAAA,MAChB,CAAC,QAAQ,QAAQ,cAAc,CAAC,KAAK,SAAS,OAAO,GAAG,KAAK,KAAK,SAAS,IAAI,GAAG;AAAA,IACpF;AAAA,EACF;AACF;AAGO,SAAS,mCACd,UACA,QACA,QAC8B;AAC9B,SAAO,IAAI,6BAA6B,UAAU,QAAQ,MAAM;AAClE;","names":[]}
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  createAutoAdapter
3
- } from "./chunk-KRJMJB4J.js";
3
+ } from "./chunk-HGHPZ2W3.js";
4
4
  import {
5
5
  mapModelErrorToCategory
6
- } from "./chunk-5KSQF4L2.js";
6
+ } from "./chunk-XPZODTJ6.js";
7
7
  import {
8
8
  CLI_NAMES,
9
9
  CircularBuffer,
@@ -24,7 +24,7 @@ import {
24
24
  ok,
25
25
  recordRateLimitEvent,
26
26
  toRateLimitError
27
- } from "./chunk-CUJUNXKQ.js";
27
+ } from "./chunk-4IDGRIWO.js";
28
28
 
29
29
  // src/agents/collaboration/event-bus-helpers.ts
30
30
  import { randomUUID } from "crypto";
@@ -1041,4 +1041,4 @@ export {
1041
1041
  getGlobalRegistry,
1042
1042
  resetGlobalRegistry
1043
1043
  };
1044
- //# sourceMappingURL=chunk-2SELLY6Y.js.map
1044
+ //# sourceMappingURL=chunk-YBTBVOVA.js.map