nexus-agents 4.13.0 → 4.14.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 (120) hide show
  1. package/dist/{child-mcp-config-OULJI7VH.js → child-mcp-config-E5YGOYIM.js} +2 -2
  2. package/dist/{chunk-P45XNRHB.js → chunk-3U3AAMAU.js} +2 -2
  3. package/dist/{chunk-HBF7O6CN.js → chunk-45X7AGDF.js} +6 -6
  4. package/dist/{chunk-V253VL7S.js → chunk-6IDZUUC5.js} +3 -3
  5. package/dist/{chunk-J6JEW4QZ.js → chunk-6MSKPFFM.js} +7 -7
  6. package/dist/{chunk-6454KSCM.js → chunk-7ERIPG4P.js} +2 -2
  7. package/dist/{chunk-KUGBMQAP.js → chunk-CEHYUQTT.js} +3 -3
  8. package/dist/{chunk-PWSW5Z4L.js → chunk-DJ2NGRHS.js} +2 -2
  9. package/dist/{chunk-C7EXWOXQ.js → chunk-GLYII4EO.js} +5 -5
  10. package/dist/{chunk-VPTDFOAK.js → chunk-GRJC2F3P.js} +3 -3
  11. package/dist/{chunk-VENIFAMX.js → chunk-HGO7LVRL.js} +4 -4
  12. package/dist/{chunk-B6C3JCQB.js → chunk-HW3BCQKG.js} +2 -2
  13. package/dist/{chunk-F6MUN523.js → chunk-IMI6LRZ2.js} +2 -2
  14. package/dist/{chunk-EHMMTCCS.js → chunk-IOAG43ER.js} +5 -5
  15. package/dist/{chunk-WATNLQS7.js → chunk-KNDUA6HH.js} +2 -2
  16. package/dist/{chunk-LUBCO6ZN.js → chunk-KQU3HO7T.js} +2 -2
  17. package/dist/{chunk-232RDSCM.js → chunk-LRUPAIVW.js} +2 -2
  18. package/dist/{chunk-I6JMAM4J.js → chunk-LVA53Q4Y.js} +2 -2
  19. package/dist/{chunk-TANMACVQ.js → chunk-M5KWBRUY.js} +2 -2
  20. package/dist/{chunk-YHY5AZL2.js → chunk-OC5EBGLD.js} +2 -2
  21. package/dist/{chunk-W6IZVEIM.js → chunk-PWUPYWJE.js} +2 -2
  22. package/dist/{chunk-5PCTGUMF.js → chunk-Q2LABBI5.js} +3 -3
  23. package/dist/{chunk-7STKQ3IH.js → chunk-R4TX27OZ.js} +2 -2
  24. package/dist/{chunk-IZUT5OHH.js → chunk-RGX43IEW.js} +2 -2
  25. package/dist/{chunk-IZUT5OHH.js.map → chunk-RGX43IEW.js.map} +1 -1
  26. package/dist/{chunk-F6SRPGDK.js → chunk-SJMQFZCV.js} +8 -8
  27. package/dist/{chunk-NMNTYAV2.js → chunk-SMPLE7KA.js} +2 -2
  28. package/dist/{chunk-ARTQO7XZ.js → chunk-T25FZOJ3.js} +4 -4
  29. package/dist/{chunk-4WVGF3SL.js → chunk-TYNKSYWN.js} +3 -3
  30. package/dist/{chunk-XGCYJLTP.js → chunk-ULAF5ULM.js} +8 -8
  31. package/dist/{chunk-2OAOW7E2.js → chunk-UZTRCADY.js} +48 -39
  32. package/dist/{chunk-2OAOW7E2.js.map → chunk-UZTRCADY.js.map} +1 -1
  33. package/dist/{chunk-XWIFBBBH.js → chunk-XHDAHIAJ.js} +2 -2
  34. package/dist/{chunk-56LJJOBN.js → chunk-XSOMMTPM.js} +4 -4
  35. package/dist/{chunk-VZWNGPUH.js → chunk-Y24TNAK5.js} +8 -8
  36. package/dist/{chunk-VZVGT4MN.js → chunk-ZMFD77AY.js} +5 -5
  37. package/dist/{cli-circuit-breaker-4AVWA333.js → cli-circuit-breaker-D4LO2S5C.js} +3 -3
  38. package/dist/cli.js +41 -41
  39. package/dist/{composite-router-7OTZN7NS.js → composite-router-JFRT5WIU.js} +2 -2
  40. package/dist/{consensus-vote-KFLDRUJJ.js → consensus-vote-2WUR2MN5.js} +16 -16
  41. package/dist/{context-retriever-2NZWXF6Z.js → context-retriever-5S6NTZRG.js} +8 -8
  42. package/dist/{doctor-deep-MC2FGSAF.js → doctor-deep-FXQN3UQZ.js} +3 -3
  43. package/dist/{doctor-live-25LRXKBO.js → doctor-live-HE5WX4IJ.js} +9 -9
  44. package/dist/{expert-bridge-2YLK3E6Q.js → expert-bridge-46OBG3SJ.js} +4 -4
  45. package/dist/{factory-G57M6CD4.js → factory-S67EX46S.js} +5 -5
  46. package/dist/{factory-T7KN4CKD.js → factory-ZXDSU5MF.js} +9 -9
  47. package/dist/{improvement-review-FFADRM4I.js → improvement-review-CWQCW4QJ.js} +5 -5
  48. package/dist/index.js +30 -30
  49. package/dist/{init-opencode-OSZF74AL.js → init-opencode-UNWGZXLG.js} +6 -6
  50. package/dist/issue-triage-FA3I6DFO.js +17 -0
  51. package/dist/{pr-reviewer-helpers-E3QXOVMT.js → pr-reviewer-helpers-PFPZQCPY.js} +4 -4
  52. package/dist/{registry-command-ZMKZ5CRZ.js → registry-command-YANXNMSO.js} +2 -2
  53. package/dist/{repo-security-plan-BPET6KTP.js → repo-security-plan-EWNWYF3Y.js} +3 -3
  54. package/dist/{research-helpers-synthesize-M4SONOWL.js → research-helpers-synthesize-TMXQFCDY.js} +4 -4
  55. package/dist/{routing-memory-3UWP6NOX.js → routing-memory-OZVM7DA3.js} +2 -2
  56. package/dist/{session-memory-N2ABITF7.js → session-memory-KD5Y7TVD.js} +3 -3
  57. package/dist/{setup-command-BXIJOFRP.js → setup-command-FRMKDYMA.js} +14 -14
  58. package/dist/{setup-config-PJNXP57G.js → setup-config-X2UWR7X2.js} +3 -3
  59. package/dist/{setup-custom-api-PE2M5HWL.js → setup-custom-api-PEP4D5KN.js} +4 -4
  60. package/dist/{tool-memory-CARCDHTN.js → tool-memory-JRZFQ3PX.js} +5 -5
  61. package/dist/{unified-registry-HVALHHPY.js → unified-registry-H44QDVXY.js} +10 -10
  62. package/dist/{weather-report-ZA7DBOC3.js → weather-report-4TP5YCFG.js} +2 -2
  63. package/package.json +1 -1
  64. package/dist/issue-triage-KVYM5FQ5.js +0 -17
  65. /package/dist/{child-mcp-config-OULJI7VH.js.map → child-mcp-config-E5YGOYIM.js.map} +0 -0
  66. /package/dist/{chunk-P45XNRHB.js.map → chunk-3U3AAMAU.js.map} +0 -0
  67. /package/dist/{chunk-HBF7O6CN.js.map → chunk-45X7AGDF.js.map} +0 -0
  68. /package/dist/{chunk-V253VL7S.js.map → chunk-6IDZUUC5.js.map} +0 -0
  69. /package/dist/{chunk-J6JEW4QZ.js.map → chunk-6MSKPFFM.js.map} +0 -0
  70. /package/dist/{chunk-6454KSCM.js.map → chunk-7ERIPG4P.js.map} +0 -0
  71. /package/dist/{chunk-KUGBMQAP.js.map → chunk-CEHYUQTT.js.map} +0 -0
  72. /package/dist/{chunk-PWSW5Z4L.js.map → chunk-DJ2NGRHS.js.map} +0 -0
  73. /package/dist/{chunk-C7EXWOXQ.js.map → chunk-GLYII4EO.js.map} +0 -0
  74. /package/dist/{chunk-VPTDFOAK.js.map → chunk-GRJC2F3P.js.map} +0 -0
  75. /package/dist/{chunk-VENIFAMX.js.map → chunk-HGO7LVRL.js.map} +0 -0
  76. /package/dist/{chunk-B6C3JCQB.js.map → chunk-HW3BCQKG.js.map} +0 -0
  77. /package/dist/{chunk-F6MUN523.js.map → chunk-IMI6LRZ2.js.map} +0 -0
  78. /package/dist/{chunk-EHMMTCCS.js.map → chunk-IOAG43ER.js.map} +0 -0
  79. /package/dist/{chunk-WATNLQS7.js.map → chunk-KNDUA6HH.js.map} +0 -0
  80. /package/dist/{chunk-LUBCO6ZN.js.map → chunk-KQU3HO7T.js.map} +0 -0
  81. /package/dist/{chunk-232RDSCM.js.map → chunk-LRUPAIVW.js.map} +0 -0
  82. /package/dist/{chunk-I6JMAM4J.js.map → chunk-LVA53Q4Y.js.map} +0 -0
  83. /package/dist/{chunk-TANMACVQ.js.map → chunk-M5KWBRUY.js.map} +0 -0
  84. /package/dist/{chunk-YHY5AZL2.js.map → chunk-OC5EBGLD.js.map} +0 -0
  85. /package/dist/{chunk-W6IZVEIM.js.map → chunk-PWUPYWJE.js.map} +0 -0
  86. /package/dist/{chunk-5PCTGUMF.js.map → chunk-Q2LABBI5.js.map} +0 -0
  87. /package/dist/{chunk-7STKQ3IH.js.map → chunk-R4TX27OZ.js.map} +0 -0
  88. /package/dist/{chunk-F6SRPGDK.js.map → chunk-SJMQFZCV.js.map} +0 -0
  89. /package/dist/{chunk-NMNTYAV2.js.map → chunk-SMPLE7KA.js.map} +0 -0
  90. /package/dist/{chunk-ARTQO7XZ.js.map → chunk-T25FZOJ3.js.map} +0 -0
  91. /package/dist/{chunk-4WVGF3SL.js.map → chunk-TYNKSYWN.js.map} +0 -0
  92. /package/dist/{chunk-XGCYJLTP.js.map → chunk-ULAF5ULM.js.map} +0 -0
  93. /package/dist/{chunk-XWIFBBBH.js.map → chunk-XHDAHIAJ.js.map} +0 -0
  94. /package/dist/{chunk-56LJJOBN.js.map → chunk-XSOMMTPM.js.map} +0 -0
  95. /package/dist/{chunk-VZWNGPUH.js.map → chunk-Y24TNAK5.js.map} +0 -0
  96. /package/dist/{chunk-VZVGT4MN.js.map → chunk-ZMFD77AY.js.map} +0 -0
  97. /package/dist/{cli-circuit-breaker-4AVWA333.js.map → cli-circuit-breaker-D4LO2S5C.js.map} +0 -0
  98. /package/dist/{composite-router-7OTZN7NS.js.map → composite-router-JFRT5WIU.js.map} +0 -0
  99. /package/dist/{consensus-vote-KFLDRUJJ.js.map → consensus-vote-2WUR2MN5.js.map} +0 -0
  100. /package/dist/{context-retriever-2NZWXF6Z.js.map → context-retriever-5S6NTZRG.js.map} +0 -0
  101. /package/dist/{doctor-deep-MC2FGSAF.js.map → doctor-deep-FXQN3UQZ.js.map} +0 -0
  102. /package/dist/{doctor-live-25LRXKBO.js.map → doctor-live-HE5WX4IJ.js.map} +0 -0
  103. /package/dist/{expert-bridge-2YLK3E6Q.js.map → expert-bridge-46OBG3SJ.js.map} +0 -0
  104. /package/dist/{factory-G57M6CD4.js.map → factory-S67EX46S.js.map} +0 -0
  105. /package/dist/{factory-T7KN4CKD.js.map → factory-ZXDSU5MF.js.map} +0 -0
  106. /package/dist/{improvement-review-FFADRM4I.js.map → improvement-review-CWQCW4QJ.js.map} +0 -0
  107. /package/dist/{init-opencode-OSZF74AL.js.map → init-opencode-UNWGZXLG.js.map} +0 -0
  108. /package/dist/{issue-triage-KVYM5FQ5.js.map → issue-triage-FA3I6DFO.js.map} +0 -0
  109. /package/dist/{pr-reviewer-helpers-E3QXOVMT.js.map → pr-reviewer-helpers-PFPZQCPY.js.map} +0 -0
  110. /package/dist/{registry-command-ZMKZ5CRZ.js.map → registry-command-YANXNMSO.js.map} +0 -0
  111. /package/dist/{repo-security-plan-BPET6KTP.js.map → repo-security-plan-EWNWYF3Y.js.map} +0 -0
  112. /package/dist/{research-helpers-synthesize-M4SONOWL.js.map → research-helpers-synthesize-TMXQFCDY.js.map} +0 -0
  113. /package/dist/{routing-memory-3UWP6NOX.js.map → routing-memory-OZVM7DA3.js.map} +0 -0
  114. /package/dist/{session-memory-N2ABITF7.js.map → session-memory-KD5Y7TVD.js.map} +0 -0
  115. /package/dist/{setup-command-BXIJOFRP.js.map → setup-command-FRMKDYMA.js.map} +0 -0
  116. /package/dist/{setup-config-PJNXP57G.js.map → setup-config-X2UWR7X2.js.map} +0 -0
  117. /package/dist/{setup-custom-api-PE2M5HWL.js.map → setup-custom-api-PEP4D5KN.js.map} +0 -0
  118. /package/dist/{tool-memory-CARCDHTN.js.map → tool-memory-JRZFQ3PX.js.map} +0 -0
  119. /package/dist/{unified-registry-HVALHHPY.js.map → unified-registry-H44QDVXY.js.map} +0 -0
  120. /package/dist/{weather-report-ZA7DBOC3.js.map → weather-report-4TP5YCFG.js.map} +0 -0
@@ -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// #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;AAA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li-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 integration comes back as a real requirement,\n// reintroduce it alongside the consumer code in the same PR\n// (activation-or-delete YAGNI — same pattern as #2937–#2940).\n//\n// The capacity-monitor half of that sentence is gone: the provider-header\n// monitor it referred to was removed in #4532 after 7 months unwired, so\n// there is nothing to \"come back\". Header parsing is now a BUILD.\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,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ACJ,iBAAiB,SACb,4BAA4B,cAAc,qBAAqB,YAAY,CAAC,IAC5E,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":[]}
@@ -5,34 +5,34 @@ import {
5
5
  planOptionalParams,
6
6
  requireApiKey,
7
7
  validateApiKeyPresence
8
- } from "./chunk-6454KSCM.js";
8
+ } from "./chunk-7ERIPG4P.js";
9
9
  import {
10
10
  CUSTOM_API_DEFAULT_MODEL
11
- } from "./chunk-B6C3JCQB.js";
11
+ } from "./chunk-HW3BCQKG.js";
12
12
  import {
13
13
  CUSTOM_API_BASE_URL_ENV,
14
14
  PROVIDER_ENV_KEYS,
15
15
  assertCustomApiHostResolvesPublic,
16
16
  validateCustomApiBaseUrl
17
- } from "./chunk-7STKQ3IH.js";
17
+ } from "./chunk-R4TX27OZ.js";
18
18
  import {
19
19
  nexusMkdtempSync
20
20
  } from "./chunk-SNJNRDKZ.js";
21
21
  import {
22
22
  getAvailabilityCache
23
- } from "./chunk-W6IZVEIM.js";
23
+ } from "./chunk-PWUPYWJE.js";
24
24
  import {
25
25
  extractSystemPrompt
26
26
  } from "./chunk-QZUG667L.js";
27
27
  import {
28
28
  generateHyphenId
29
- } from "./chunk-I6JMAM4J.js";
29
+ } from "./chunk-LVA53Q4Y.js";
30
30
  import {
31
31
  CliCircuitBreaker,
32
32
  DEFAULT_CIRCUIT_BREAKER_CONFIG,
33
33
  getCliCircuitBreakerSnapshot,
34
34
  getDefaultCliCircuitBreakerRegistry
35
- } from "./chunk-IZUT5OHH.js";
35
+ } from "./chunk-RGX43IEW.js";
36
36
  import {
37
37
  CLI_SUBPROCESS_TIMEOUTS,
38
38
  CLI_TIMEOUTS,
@@ -72,7 +72,7 @@ import {
72
72
  resolveCliAlias,
73
73
  resolveRetryAfterMs,
74
74
  retryAfterMsFromContext
75
- } from "./chunk-4WVGF3SL.js";
75
+ } from "./chunk-TYNKSYWN.js";
76
76
 
77
77
  // src/cli-adapters/cli-to-model-adapter.ts
78
78
  var CliToModelAdapter = class {
@@ -4885,4 +4885,4 @@ export {
4885
4885
  SdkAdapter,
4886
4886
  createAutoAdapter
4887
4887
  };
4888
- //# sourceMappingURL=chunk-F6SRPGDK.js.map
4888
+ //# sourceMappingURL=chunk-SJMQFZCV.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getDefaultRegistry
3
- } from "./chunk-4WVGF3SL.js";
3
+ } from "./chunk-TYNKSYWN.js";
4
4
  import {
5
5
  getNexusDataDir
6
6
  } from "./chunk-OQLFRJCW.js";
@@ -128,4 +128,4 @@ export {
128
128
  loadUsageEvents,
129
129
  rollupByModel
130
130
  };
131
- //# sourceMappingURL=chunk-NMNTYAV2.js.map
131
+ //# sourceMappingURL=chunk-SMPLE7KA.js.map
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-6T3EPABN.js";
6
6
  import {
7
7
  SessionMemory
8
- } from "./chunk-TANMACVQ.js";
8
+ } from "./chunk-M5KWBRUY.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-I6JMAM4J.js";
18
+ } from "./chunk-LVA53Q4Y.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-4WVGF3SL.js";
31
+ } from "./chunk-TYNKSYWN.js";
32
32
  import {
33
33
  nexusDataPath
34
34
  } from "./chunk-OQLFRJCW.js";
@@ -5550,4 +5550,4 @@ export {
5550
5550
  reinitializeMemoryBackends,
5551
5551
  ToolMemoryManager
5552
5552
  };
5553
- //# sourceMappingURL=chunk-ARTQO7XZ.js.map
5553
+ //# sourceMappingURL=chunk-T25FZOJ3.js.map
@@ -2623,7 +2623,7 @@ function setDefaultRegistry(registry) {
2623
2623
  }
2624
2624
  async function reloadDefaultRegistry() {
2625
2625
  globalRegistry = buildDefaultRegistry();
2626
- const { resetGlobalRegistry } = await import("./unified-registry-HVALHHPY.js");
2626
+ const { resetGlobalRegistry } = await import("./unified-registry-H44QDVXY.js");
2627
2627
  resetGlobalRegistry();
2628
2628
  return globalRegistry;
2629
2629
  }
@@ -15079,7 +15079,7 @@ var CompositeRouter = class _CompositeRouter {
15079
15079
  */
15080
15080
  async consultUnifiedContext(task) {
15081
15081
  try {
15082
- const { getContextForTask, inferTaskCategory } = await import("./context-retriever-2NZWXF6Z.js");
15082
+ const { getContextForTask, inferTaskCategory } = await import("./context-retriever-5S6NTZRG.js");
15083
15083
  const ctx = await getContextForTask({
15084
15084
  task: task.content,
15085
15085
  category: inferTaskCategory(task.content),
@@ -16670,4 +16670,4 @@ export {
16670
16670
  AgentCapability,
16671
16671
  OrchestratorError
16672
16672
  };
16673
- //# sourceMappingURL=chunk-4WVGF3SL.js.map
16673
+ //# sourceMappingURL=chunk-TYNKSYWN.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  computeCostDetail,
3
3
  priceBasisOf
4
- } from "./chunk-NMNTYAV2.js";
4
+ } from "./chunk-SMPLE7KA.js";
5
5
  import {
6
6
  allOf
7
7
  } from "./chunk-OQB3XC5O.js";
@@ -22,20 +22,20 @@ import {
22
22
  toolSuccess,
23
23
  withProgressHeartbeat,
24
24
  wrapToolWithTimeout
25
- } from "./chunk-V253VL7S.js";
25
+ } from "./chunk-6IDZUUC5.js";
26
26
  import {
27
27
  createEvent,
28
28
  getGlobalRegistry
29
- } from "./chunk-56LJJOBN.js";
29
+ } from "./chunk-XSOMMTPM.js";
30
30
  import {
31
31
  getToolMemory
32
- } from "./chunk-ARTQO7XZ.js";
32
+ } from "./chunk-T25FZOJ3.js";
33
33
  import {
34
34
  authRemediation,
35
35
  delay,
36
36
  getAvailableClis,
37
37
  withTimeout
38
- } from "./chunk-F6SRPGDK.js";
38
+ } from "./chunk-SJMQFZCV.js";
39
39
  import {
40
40
  AgentError,
41
41
  CLI_NAMES,
@@ -64,7 +64,7 @@ import {
64
64
  resolveClassGuardMs,
65
65
  resolveModelIdentitySync,
66
66
  resolveVoteTimeout
67
- } from "./chunk-4WVGF3SL.js";
67
+ } from "./chunk-TYNKSYWN.js";
68
68
  import {
69
69
  ensureLearningDir,
70
70
  getOutcomesFile
@@ -6162,7 +6162,7 @@ async function processVotesWithCascade(engineVotes, opts) {
6162
6162
  var CONTRARIAN_ESCALATION_THRESHOLD = 0.8;
6163
6163
  async function runContrarianCheck(proposal, log) {
6164
6164
  try {
6165
- const { executeExpert } = await import("./expert-bridge-2YLK3E6Q.js");
6165
+ const { executeExpert } = await import("./expert-bridge-46OBG3SJ.js");
6166
6166
  const prompt = [
6167
6167
  "You are a contrarian analyst. Your job is to find reasons this proposal should be REJECTED.",
6168
6168
  "Look for: YAGNI (not needed), MISALIGNED (wrong tech/architecture), SECURITY_RISK, SCOPE_CREEP.",
@@ -6728,4 +6728,4 @@ export {
6728
6728
  CONSENSUS_VOTE_TOOL_SCHEMA,
6729
6729
  registerConsensusVoteTool
6730
6730
  };
6731
- //# sourceMappingURL=chunk-XGCYJLTP.js.map
6731
+ //# sourceMappingURL=chunk-ULAF5ULM.js.map