claude-mycelium 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/.claude/settings.local.json +14 -0
  2. package/README.md +304 -0
  3. package/dist/coordination/gradient-cache.d.ts +48 -0
  4. package/dist/coordination/gradient-cache.d.ts.map +1 -0
  5. package/dist/coordination/gradient-cache.js +145 -0
  6. package/dist/coordination/gradient-cache.js.map +1 -0
  7. package/dist/coordination/index.d.ts +10 -0
  8. package/dist/coordination/index.d.ts.map +1 -0
  9. package/dist/coordination/index.js +10 -0
  10. package/dist/coordination/index.js.map +1 -0
  11. package/dist/core/agent-executor.d.ts +31 -0
  12. package/dist/core/agent-executor.d.ts.map +1 -0
  13. package/dist/core/agent-executor.js +257 -0
  14. package/dist/core/agent-executor.js.map +1 -0
  15. package/dist/core/change-applier.d.ts +10 -0
  16. package/dist/core/change-applier.d.ts.map +1 -0
  17. package/dist/core/change-applier.js +32 -0
  18. package/dist/core/change-applier.js.map +1 -0
  19. package/dist/core/gradient.d.ts +60 -0
  20. package/dist/core/gradient.d.ts.map +1 -0
  21. package/dist/core/gradient.js +191 -0
  22. package/dist/core/gradient.js.map +1 -0
  23. package/dist/core/index.d.ts +24 -0
  24. package/dist/core/index.d.ts.map +1 -0
  25. package/dist/core/index.js +24 -0
  26. package/dist/core/index.js.map +1 -0
  27. package/dist/core/mode-selector.d.ts +44 -0
  28. package/dist/core/mode-selector.d.ts.map +1 -0
  29. package/dist/core/mode-selector.js +208 -0
  30. package/dist/core/mode-selector.js.map +1 -0
  31. package/dist/core/signals/centrality.d.ts +44 -0
  32. package/dist/core/signals/centrality.d.ts.map +1 -0
  33. package/dist/core/signals/centrality.js +264 -0
  34. package/dist/core/signals/centrality.js.map +1 -0
  35. package/dist/core/signals/churn.d.ts +41 -0
  36. package/dist/core/signals/churn.d.ts.map +1 -0
  37. package/dist/core/signals/churn.js +188 -0
  38. package/dist/core/signals/churn.js.map +1 -0
  39. package/dist/core/signals/complexity.d.ts +29 -0
  40. package/dist/core/signals/complexity.d.ts.map +1 -0
  41. package/dist/core/signals/complexity.js +169 -0
  42. package/dist/core/signals/complexity.js.map +1 -0
  43. package/dist/core/signals/debt.d.ts +27 -0
  44. package/dist/core/signals/debt.d.ts.map +1 -0
  45. package/dist/core/signals/debt.js +80 -0
  46. package/dist/core/signals/debt.js.map +1 -0
  47. package/dist/core/signals/errors.d.ts +32 -0
  48. package/dist/core/signals/errors.d.ts.map +1 -0
  49. package/dist/core/signals/errors.js +73 -0
  50. package/dist/core/signals/errors.js.map +1 -0
  51. package/dist/core/signals/index.d.ts +19 -0
  52. package/dist/core/signals/index.d.ts.map +1 -0
  53. package/dist/core/signals/index.js +19 -0
  54. package/dist/core/signals/index.js.map +1 -0
  55. package/dist/cost/cost-tracker.d.ts +90 -0
  56. package/dist/cost/cost-tracker.d.ts.map +1 -0
  57. package/dist/cost/cost-tracker.js +305 -0
  58. package/dist/cost/cost-tracker.js.map +1 -0
  59. package/dist/cost/index.d.ts +56 -0
  60. package/dist/cost/index.d.ts.map +1 -0
  61. package/dist/cost/index.js +111 -0
  62. package/dist/cost/index.js.map +1 -0
  63. package/dist/index.d.ts +35 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +40 -0
  66. package/dist/index.js.map +1 -0
  67. package/dist/llm/anthropic-client.d.ts +52 -0
  68. package/dist/llm/anthropic-client.d.ts.map +1 -0
  69. package/dist/llm/anthropic-client.js +310 -0
  70. package/dist/llm/anthropic-client.js.map +1 -0
  71. package/dist/llm/index.d.ts +27 -0
  72. package/dist/llm/index.d.ts.map +1 -0
  73. package/dist/llm/index.js +34 -0
  74. package/dist/llm/index.js.map +1 -0
  75. package/dist/prompts/complexity-reducer.d.ts +7 -0
  76. package/dist/prompts/complexity-reducer.d.ts.map +1 -0
  77. package/dist/prompts/complexity-reducer.js +55 -0
  78. package/dist/prompts/complexity-reducer.js.map +1 -0
  79. package/dist/prompts/debt-payer.d.ts +7 -0
  80. package/dist/prompts/debt-payer.d.ts.map +1 -0
  81. package/dist/prompts/debt-payer.js +55 -0
  82. package/dist/prompts/debt-payer.js.map +1 -0
  83. package/dist/prompts/error-reducer.d.ts +7 -0
  84. package/dist/prompts/error-reducer.d.ts.map +1 -0
  85. package/dist/prompts/error-reducer.js +54 -0
  86. package/dist/prompts/error-reducer.js.map +1 -0
  87. package/dist/prompts/index.d.ts +22 -0
  88. package/dist/prompts/index.d.ts.map +1 -0
  89. package/dist/prompts/index.js +112 -0
  90. package/dist/prompts/index.js.map +1 -0
  91. package/dist/prompts/stabilizer.d.ts +7 -0
  92. package/dist/prompts/stabilizer.d.ts.map +1 -0
  93. package/dist/prompts/stabilizer.js +55 -0
  94. package/dist/prompts/stabilizer.js.map +1 -0
  95. package/dist/prompts/types.d.ts +14 -0
  96. package/dist/prompts/types.d.ts.map +1 -0
  97. package/dist/prompts/types.js +5 -0
  98. package/dist/prompts/types.js.map +1 -0
  99. package/dist/trace/index.d.ts +51 -0
  100. package/dist/trace/index.d.ts.map +1 -0
  101. package/dist/trace/index.js +60 -0
  102. package/dist/trace/index.js.map +1 -0
  103. package/dist/trace/trace-event.d.ts +72 -0
  104. package/dist/trace/trace-event.d.ts.map +1 -0
  105. package/dist/trace/trace-event.js +244 -0
  106. package/dist/trace/trace-event.js.map +1 -0
  107. package/dist/types/index.d.ts +206 -0
  108. package/dist/types/index.d.ts.map +1 -0
  109. package/dist/types/index.js +6 -0
  110. package/dist/types/index.js.map +1 -0
  111. package/dist/utils/ci-provider.d.ts +43 -0
  112. package/dist/utils/ci-provider.d.ts.map +1 -0
  113. package/dist/utils/ci-provider.js +130 -0
  114. package/dist/utils/ci-provider.js.map +1 -0
  115. package/dist/utils/config.d.ts +31 -0
  116. package/dist/utils/config.d.ts.map +1 -0
  117. package/dist/utils/config.js +85 -0
  118. package/dist/utils/config.js.map +1 -0
  119. package/dist/utils/error-provider.d.ts +51 -0
  120. package/dist/utils/error-provider.d.ts.map +1 -0
  121. package/dist/utils/error-provider.js +123 -0
  122. package/dist/utils/error-provider.js.map +1 -0
  123. package/dist/utils/file-utils.d.ts +18 -0
  124. package/dist/utils/file-utils.d.ts.map +1 -0
  125. package/dist/utils/file-utils.js +95 -0
  126. package/dist/utils/file-utils.js.map +1 -0
  127. package/dist/utils/index.d.ts +10 -0
  128. package/dist/utils/index.d.ts.map +1 -0
  129. package/dist/utils/index.js +10 -0
  130. package/dist/utils/index.js.map +1 -0
  131. package/dist/utils/logger.d.ts +36 -0
  132. package/dist/utils/logger.d.ts.map +1 -0
  133. package/dist/utils/logger.js +74 -0
  134. package/dist/utils/logger.js.map +1 -0
  135. package/docs/IMPLEMENTATION-STATUS.md +199 -0
  136. package/docs/PHASE-0-COMPLETE.md +252 -0
  137. package/docs/PHASE-1-COMPLETE.md +204 -0
  138. package/docs/PHASE-2-COMPLETE.md +233 -0
  139. package/docs/PHASE2_COMPLETION_CHECKLIST.md +290 -0
  140. package/docs/PHASE2_INTEGRATION_SUMMARY.md +255 -0
  141. package/docs/PHASE2_QUICK_REFERENCE.md +365 -0
  142. package/docs/PHASE2_TEST_RESULTS.md +282 -0
  143. package/docs/ROADMAP.md +746 -0
  144. package/docs/SNAPSHOT.md +376 -0
  145. package/docs/adrs/ADR-001-signal-computation.md +76 -0
  146. package/docs/adrs/ADR-002-inhibitor-signals.md +108 -0
  147. package/docs/adrs/ADR-003-llm-integration.md +156 -0
  148. package/docs/adrs/ADR-004-process-architecture.md +175 -0
  149. package/docs/adrs/ADR-005-testing-strategy.md +243 -0
  150. package/docs/pitch.md +94 -0
  151. package/docs/specs/fourth-spec.md +1973 -0
  152. package/docs/specs/initial-spec.md +2096 -0
  153. package/docs/specs/second-spec.md +2690 -0
  154. package/package.json +50 -0
  155. package/src/coordination/gradient-cache.ts +185 -0
  156. package/src/coordination/index.ts +10 -0
  157. package/src/core/agent-executor.ts +327 -0
  158. package/src/core/change-applier.ts +338 -0
  159. package/src/core/gradient.ts +258 -0
  160. package/src/core/index.ts +24 -0
  161. package/src/core/mode-selector.ts +243 -0
  162. package/src/core/signals/centrality.ts +328 -0
  163. package/src/core/signals/churn.ts +239 -0
  164. package/src/core/signals/complexity.ts +206 -0
  165. package/src/core/signals/debt.ts +111 -0
  166. package/src/core/signals/errors.ts +93 -0
  167. package/src/core/signals/index.ts +19 -0
  168. package/src/cost/cost-tracker.ts +410 -0
  169. package/src/cost/index.ts +143 -0
  170. package/src/index.ts +43 -0
  171. package/src/llm/anthropic-client.ts +415 -0
  172. package/src/llm/index.ts +43 -0
  173. package/src/prompts/complexity-reducer.ts +59 -0
  174. package/src/prompts/debt-payer.ts +59 -0
  175. package/src/prompts/error-reducer.ts +58 -0
  176. package/src/prompts/index.ts +128 -0
  177. package/src/prompts/stabilizer.ts +59 -0
  178. package/src/prompts/types.ts +15 -0
  179. package/src/trace/README.md +178 -0
  180. package/src/trace/index.ts +88 -0
  181. package/src/trace/trace-event.ts +324 -0
  182. package/src/types/index.ts +271 -0
  183. package/src/utils/ci-provider.ts +145 -0
  184. package/src/utils/config.ts +95 -0
  185. package/src/utils/error-provider.ts +138 -0
  186. package/src/utils/file-utils.ts +111 -0
  187. package/src/utils/index.ts +10 -0
  188. package/src/utils/logger.ts +94 -0
  189. package/test-8d713cc8-f4b7-403d-8153-57573172b94c.ts +3 -0
  190. package/tests/coordination/gradient-cache.test.ts +270 -0
  191. package/tests/core/agent-executor.test.ts +217 -0
  192. package/tests/core/change-applier.test.ts +336 -0
  193. package/tests/core/gradient.test.ts +263 -0
  194. package/tests/core/mode-selector.test.ts +239 -0
  195. package/tests/core/signals/centrality.test.ts +512 -0
  196. package/tests/core/signals/churn.test.ts +355 -0
  197. package/tests/core/signals/complexity.test.ts +284 -0
  198. package/tests/core/signals/debt.test.ts +437 -0
  199. package/tests/core/signals/errors.test.ts +350 -0
  200. package/tests/cost/cost-tracker.test.ts +475 -0
  201. package/tests/integration/phase2.test.ts +405 -0
  202. package/tests/llm/anthropic-client.test.ts +437 -0
  203. package/tests/prompts/prompts.test.ts +266 -0
  204. package/tests/trace/trace-event.test.ts +666 -0
  205. package/tests/utils/file-utils.test.ts +148 -0
  206. package/tsconfig.json +24 -0
  207. package/vitest.config.ts +28 -0
package/dist/index.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Claude-Mycelium v2.0
3
+ * Main Entry Point
4
+ *
5
+ * Decentralized, gradient-driven agent system for autonomous codebase improvement.
6
+ *
7
+ * Core exports:
8
+ * - Core: Signals, Gradient, Mode Selection
9
+ * - LLM: Anthropic integration
10
+ * - Trace: Event tracking
11
+ * - Cost: Token and cost tracking
12
+ * - Utils: Logging, file I/O, configuration
13
+ * - Types: Complete TypeScript interfaces
14
+ *
15
+ * Per initial-spec and Phase 2 spec.
16
+ *
17
+ * Usage:
18
+ * ```typescript
19
+ * import {
20
+ * calculateGradient,
21
+ * selectMode,
22
+ * createAnthropicClient,
23
+ * recordTraceEvent,
24
+ * calculateCost,
25
+ * } from 'claude-mycelium';
26
+ * ```
27
+ */
28
+ // Core Phase 1 modules
29
+ export * from './core/index.js';
30
+ export * from './coordination/index.js';
31
+ // Phase 2 modules - note: anthropic-client calculates cost too, so we
32
+ // only export from cost/index (not the full llm module to avoid conflicts)
33
+ export { createAnthropicClient, LLMError } from './llm/index.js';
34
+ export * from './trace/index.js';
35
+ export * from './cost/index.js';
36
+ // Utilities
37
+ export * from './utils/index.js';
38
+ // Types
39
+ export * from './types/index.js';
40
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,uBAAuB;AACvB,cAAc,iBAAiB,CAAC;AAChC,cAAc,yBAAyB,CAAC;AAExC,sEAAsE;AACtE,2EAA2E;AAC3E,OAAO,EAAE,qBAAqB,EAAqC,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AACpG,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAEhC,YAAY;AACZ,cAAc,kBAAkB,CAAC;AAEjC,QAAQ;AACR,cAAc,kBAAkB,CAAC"}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Anthropic API Client
3
+ * Per second-spec §3: LLM Integration
4
+ *
5
+ * Provides non-streaming and streaming interfaces to Claude API
6
+ * with automatic retries, error handling, and cost tracking.
7
+ */
8
+ /**
9
+ * Request configuration for LLM calls
10
+ */
11
+ export interface LLMRequest {
12
+ prompt: string;
13
+ model?: string;
14
+ maxTokens?: number;
15
+ temperature?: number;
16
+ systemPrompt?: string;
17
+ }
18
+ /**
19
+ * Response from LLM call with usage metrics
20
+ */
21
+ export interface LLMResponse {
22
+ content: string;
23
+ usage: {
24
+ inputTokens: number;
25
+ outputTokens: number;
26
+ };
27
+ model: string;
28
+ }
29
+ /**
30
+ * Error types for better error handling
31
+ */
32
+ export declare class LLMError extends Error {
33
+ readonly code: string;
34
+ readonly retryable: boolean;
35
+ readonly originalError?: unknown | undefined;
36
+ constructor(message: string, code: string, retryable?: boolean, originalError?: unknown | undefined);
37
+ }
38
+ /**
39
+ * Make a non-streaming LLM call with automatic retries
40
+ */
41
+ export declare function callLLM(request: LLMRequest): Promise<LLMResponse>;
42
+ /**
43
+ * Stream LLM responses with automatic retries
44
+ * Yields content chunks as they arrive
45
+ */
46
+ export declare function streamLLM(request: LLMRequest): AsyncGenerator<string, void, undefined>;
47
+ /**
48
+ * Calculate cost in USD for a given token usage
49
+ * Pricing per second-spec §3.3
50
+ */
51
+ export declare function calculateCost(model: string, inputTokens: number, outputTokens: number): number;
52
+ //# sourceMappingURL=anthropic-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-client.d.ts","sourceRoot":"","sources":["../../src/llm/anthropic-client.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE;QACL,WAAW,EAAE,MAAM,CAAC;QACpB,YAAY,EAAE,MAAM,CAAC;KACtB,CAAC;IACF,KAAK,EAAE,MAAM,CAAC;CACf;AAWD;;GAEG;AACH,qBAAa,QAAS,SAAQ,KAAK;aAGf,IAAI,EAAE,MAAM;aACZ,SAAS,EAAE,OAAO;aAClB,aAAa,CAAC,EAAE,OAAO;gBAHvC,OAAO,EAAE,MAAM,EACC,IAAI,EAAE,MAAM,EACZ,SAAS,GAAE,OAAe,EAC1B,aAAa,CAAC,EAAE,OAAO,YAAA;CAK1C;AAiID;;GAEG;AACH,wBAAsB,OAAO,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,WAAW,CAAC,CAgGvE;AAED;;;GAGG;AACH,wBAAuB,SAAS,CAC9B,OAAO,EAAE,UAAU,GAClB,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,SAAS,CAAC,CA8FzC;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,MAAM,GACnB,MAAM,CAkBR"}
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Anthropic API Client
3
+ * Per second-spec §3: LLM Integration
4
+ *
5
+ * Provides non-streaming and streaming interfaces to Claude API
6
+ * with automatic retries, error handling, and cost tracking.
7
+ */
8
+ import Anthropic from '@anthropic-ai/sdk';
9
+ import { logDebug, logError, logWarn } from '../utils/logger.js';
10
+ /**
11
+ * Configuration defaults
12
+ */
13
+ const DEFAULT_MODEL = 'claude-sonnet-4-5-20250929';
14
+ const DEFAULT_MAX_TOKENS = 8000;
15
+ const DEFAULT_TEMPERATURE = 0.7;
16
+ const MAX_RETRIES = 3;
17
+ const INITIAL_RETRY_DELAY_MS = 1000;
18
+ /**
19
+ * Error types for better error handling
20
+ */
21
+ export class LLMError extends Error {
22
+ code;
23
+ retryable;
24
+ originalError;
25
+ constructor(message, code, retryable = false, originalError) {
26
+ super(message);
27
+ this.code = code;
28
+ this.retryable = retryable;
29
+ this.originalError = originalError;
30
+ this.name = 'LLMError';
31
+ }
32
+ }
33
+ /**
34
+ * Validate that API key is configured
35
+ */
36
+ function getAPIKey() {
37
+ const apiKey = process.env.ANTHROPIC_API_KEY;
38
+ if (!apiKey) {
39
+ throw new LLMError('ANTHROPIC_API_KEY environment variable is not set. Please configure your API key.', 'MISSING_API_KEY', false);
40
+ }
41
+ return apiKey;
42
+ }
43
+ /**
44
+ * Create Anthropic client instance
45
+ */
46
+ function createClient() {
47
+ const apiKey = getAPIKey();
48
+ return new Anthropic({ apiKey });
49
+ }
50
+ /**
51
+ * Calculate exponential backoff delay
52
+ */
53
+ function calculateBackoff(attempt) {
54
+ return INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt);
55
+ }
56
+ /**
57
+ * Sleep utility for retry delays
58
+ */
59
+ function sleep(ms) {
60
+ return new Promise(resolve => setTimeout(resolve, ms));
61
+ }
62
+ /**
63
+ * Determine if an error is retryable
64
+ */
65
+ function isRetryableError(error) {
66
+ // Check for Anthropic API errors with status property
67
+ if (typeof error === 'object' && error !== null && 'status' in error) {
68
+ const status = error.status;
69
+ // Rate limit errors are retryable
70
+ if (status === 429)
71
+ return true;
72
+ // Server errors are retryable
73
+ if (status >= 500)
74
+ return true;
75
+ }
76
+ // Check for connection errors
77
+ if (error instanceof Error) {
78
+ if (error.message?.includes('ECONNRESET'))
79
+ return true;
80
+ if (error.message?.includes('ETIMEDOUT'))
81
+ return true;
82
+ }
83
+ return false;
84
+ }
85
+ /**
86
+ * Convert API error to LLMError
87
+ */
88
+ function handleAPIError(error) {
89
+ // Don't wrap if already an LLMError
90
+ if (error instanceof LLMError) {
91
+ return error;
92
+ }
93
+ // Handle Anthropic API errors with status code
94
+ if (typeof error === 'object' && error !== null && 'status' in error) {
95
+ const apiError = error;
96
+ const status = apiError.status;
97
+ const message = apiError.message || 'API error';
98
+ const retryable = isRetryableError(error);
99
+ if (status === 429) {
100
+ return new LLMError('Rate limit exceeded. Retrying with exponential backoff.', 'RATE_LIMIT', true, error);
101
+ }
102
+ if (status === 401) {
103
+ return new LLMError('Invalid API key. Please check your ANTHROPIC_API_KEY.', 'INVALID_API_KEY', false, error);
104
+ }
105
+ if (status >= 500) {
106
+ return new LLMError(`Anthropic API error: ${message}`, 'SERVER_ERROR', true, error);
107
+ }
108
+ return new LLMError(`API error: ${message}`, 'API_ERROR', retryable, error);
109
+ }
110
+ if (error instanceof Error) {
111
+ return new LLMError(`Unexpected error: ${error.message}`, 'UNKNOWN_ERROR', isRetryableError(error), error);
112
+ }
113
+ return new LLMError('Unknown error occurred', 'UNKNOWN_ERROR', false, error);
114
+ }
115
+ /**
116
+ * Make a non-streaming LLM call with automatic retries
117
+ */
118
+ export async function callLLM(request) {
119
+ const client = createClient();
120
+ const model = request.model ?? DEFAULT_MODEL;
121
+ const maxTokens = request.maxTokens ?? DEFAULT_MAX_TOKENS;
122
+ const temperature = request.temperature ?? DEFAULT_TEMPERATURE;
123
+ logDebug('Making LLM call', {
124
+ model,
125
+ maxTokens,
126
+ temperature,
127
+ promptLength: request.prompt.length,
128
+ hasSystemPrompt: !!request.systemPrompt,
129
+ });
130
+ let lastError = null;
131
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
132
+ try {
133
+ const response = await client.messages.create({
134
+ model,
135
+ max_tokens: maxTokens,
136
+ temperature,
137
+ system: request.systemPrompt,
138
+ messages: [
139
+ {
140
+ role: 'user',
141
+ content: request.prompt,
142
+ },
143
+ ],
144
+ });
145
+ // Extract text content
146
+ const textContent = response.content.find(block => block.type === 'text');
147
+ if (!textContent || textContent.type !== 'text') {
148
+ const error = new LLMError('No text content in API response', 'INVALID_RESPONSE', false);
149
+ logError('Invalid API response', error, { model });
150
+ throw error;
151
+ }
152
+ const result = {
153
+ content: textContent.text,
154
+ usage: {
155
+ inputTokens: response.usage.input_tokens,
156
+ outputTokens: response.usage.output_tokens,
157
+ },
158
+ model: response.model,
159
+ };
160
+ logDebug('LLM call completed', {
161
+ model: result.model,
162
+ inputTokens: result.usage.inputTokens,
163
+ outputTokens: result.usage.outputTokens,
164
+ contentLength: result.content.length,
165
+ attempts: attempt + 1,
166
+ });
167
+ return result;
168
+ }
169
+ catch (error) {
170
+ lastError = handleAPIError(error);
171
+ // Don't retry if error is not retryable
172
+ if (!lastError.retryable) {
173
+ logError('Non-retryable LLM error', lastError, {
174
+ code: lastError.code,
175
+ model,
176
+ });
177
+ throw lastError;
178
+ }
179
+ // Don't retry on last attempt
180
+ if (attempt === MAX_RETRIES - 1) {
181
+ break;
182
+ }
183
+ const backoffMs = calculateBackoff(attempt);
184
+ logWarn('LLM call failed, retrying', {
185
+ code: lastError.code,
186
+ attempt: attempt + 1,
187
+ maxRetries: MAX_RETRIES,
188
+ backoffMs,
189
+ });
190
+ await sleep(backoffMs);
191
+ }
192
+ }
193
+ // All retries exhausted
194
+ logError('LLM call failed after all retries', lastError, {
195
+ maxRetries: MAX_RETRIES,
196
+ model,
197
+ });
198
+ throw lastError;
199
+ }
200
+ /**
201
+ * Stream LLM responses with automatic retries
202
+ * Yields content chunks as they arrive
203
+ */
204
+ export async function* streamLLM(request) {
205
+ const client = createClient();
206
+ const model = request.model ?? DEFAULT_MODEL;
207
+ const maxTokens = request.maxTokens ?? DEFAULT_MAX_TOKENS;
208
+ const temperature = request.temperature ?? DEFAULT_TEMPERATURE;
209
+ logDebug('Starting LLM stream', {
210
+ model,
211
+ maxTokens,
212
+ temperature,
213
+ promptLength: request.prompt.length,
214
+ hasSystemPrompt: !!request.systemPrompt,
215
+ });
216
+ let lastError = null;
217
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
218
+ try {
219
+ const stream = await client.messages.create({
220
+ model,
221
+ max_tokens: maxTokens,
222
+ temperature,
223
+ system: request.systemPrompt,
224
+ messages: [
225
+ {
226
+ role: 'user',
227
+ content: request.prompt,
228
+ },
229
+ ],
230
+ stream: true,
231
+ });
232
+ let totalTokensIn = 0;
233
+ let totalTokensOut = 0;
234
+ let totalContent = '';
235
+ for await (const event of stream) {
236
+ if (event.type === 'message_start') {
237
+ totalTokensIn = event.message.usage.input_tokens;
238
+ }
239
+ else if (event.type === 'content_block_delta') {
240
+ if (event.delta.type === 'text_delta') {
241
+ const chunk = event.delta.text;
242
+ totalContent += chunk;
243
+ yield chunk;
244
+ }
245
+ }
246
+ else if (event.type === 'message_delta') {
247
+ totalTokensOut = event.usage.output_tokens;
248
+ }
249
+ }
250
+ logDebug('LLM stream completed', {
251
+ model,
252
+ inputTokens: totalTokensIn,
253
+ outputTokens: totalTokensOut,
254
+ contentLength: totalContent.length,
255
+ attempts: attempt + 1,
256
+ });
257
+ return;
258
+ }
259
+ catch (error) {
260
+ lastError = handleAPIError(error);
261
+ // Don't retry if error is not retryable
262
+ if (!lastError.retryable) {
263
+ logError('Non-retryable LLM streaming error', lastError, {
264
+ code: lastError.code,
265
+ model,
266
+ });
267
+ throw lastError;
268
+ }
269
+ // Don't retry on last attempt
270
+ if (attempt === MAX_RETRIES - 1) {
271
+ break;
272
+ }
273
+ const backoffMs = calculateBackoff(attempt);
274
+ logWarn('LLM stream failed, retrying', {
275
+ code: lastError.code,
276
+ attempt: attempt + 1,
277
+ maxRetries: MAX_RETRIES,
278
+ backoffMs,
279
+ });
280
+ await sleep(backoffMs);
281
+ }
282
+ }
283
+ // All retries exhausted
284
+ logError('LLM stream failed after all retries', lastError, {
285
+ maxRetries: MAX_RETRIES,
286
+ model,
287
+ });
288
+ throw lastError;
289
+ }
290
+ /**
291
+ * Calculate cost in USD for a given token usage
292
+ * Pricing per second-spec §3.3
293
+ */
294
+ export function calculateCost(model, inputTokens, outputTokens) {
295
+ const pricing = {
296
+ 'claude-sonnet-4-5-20250929': { input: 3.0, output: 15.0 },
297
+ 'claude-sonnet-4-20250514': { input: 3.0, output: 15.0 },
298
+ 'claude-haiku-4-20250514': { input: 0.25, output: 1.25 },
299
+ };
300
+ const modelPricing = pricing[model];
301
+ if (!modelPricing) {
302
+ logWarn('Unknown model for cost calculation, returning 0', { model });
303
+ return 0;
304
+ }
305
+ // Pricing is per million tokens
306
+ const inputCost = (inputTokens / 1_000_000) * modelPricing.input;
307
+ const outputCost = (outputTokens / 1_000_000) * modelPricing.output;
308
+ return inputCost + outputCost;
309
+ }
310
+ //# sourceMappingURL=anthropic-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic-client.js","sourceRoot":"","sources":["../../src/llm/anthropic-client.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAyBjE;;GAEG;AACH,MAAM,aAAa,GAAG,4BAA4B,CAAC;AACnD,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAChC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAEpC;;GAEG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IAGf;IACA;IACA;IAJlB,YACE,OAAe,EACC,IAAY,EACZ,YAAqB,KAAK,EAC1B,aAAuB;QAEvC,KAAK,CAAC,OAAO,CAAC,CAAC;QAJC,SAAI,GAAJ,IAAI,CAAQ;QACZ,cAAS,GAAT,SAAS,CAAiB;QAC1B,kBAAa,GAAb,aAAa,CAAU;QAGvC,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;IACzB,CAAC;CACF;AAED;;GAEG;AACH,SAAS,SAAS;IAChB,MAAM,MAAM,GAAG,OAAO,CAAC,GA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AAChC,CAAC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * LLM Module - Anthropic Integration
3
+ *
4
+ * Exports the Anthropic SDK client and utilities for AI model interactions.
5
+ * Per Phase 2 specification, this provides:
6
+ * - Model instantiation (Claude)
7
+ * - Prompt generation and response handling
8
+ * - Token counting and cost estimation
9
+ * - Automatic retries and error handling
10
+ *
11
+ * Usage:
12
+ * ```typescript
13
+ * import { createAnthropicClient, callClaude } from './llm/index.js';
14
+ * const client = createAnthropicClient();
15
+ * const response = await callClaude({ prompt: '...' });
16
+ * ```
17
+ */
18
+ import Anthropic from '@anthropic-ai/sdk';
19
+ export * from './anthropic-client.js';
20
+ /**
21
+ * Create and configure Anthropic client
22
+ * Uses API key from ANTHROPIC_API_KEY environment variable
23
+ */
24
+ export declare function createAnthropicClient(): Anthropic;
25
+ export type { Message, MessageParam, ContentBlock } from '@anthropic-ai/sdk/resources';
26
+ export { Anthropic };
27
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/llm/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAG1C,cAAc,uBAAuB,CAAC;AAEtC;;;GAGG;AACH,wBAAgB,qBAAqB,IAAI,SAAS,CAWjD;AAGD,YAAY,EAAE,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AACvF,OAAO,EAAE,SAAS,EAAE,CAAC"}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * LLM Module - Anthropic Integration
3
+ *
4
+ * Exports the Anthropic SDK client and utilities for AI model interactions.
5
+ * Per Phase 2 specification, this provides:
6
+ * - Model instantiation (Claude)
7
+ * - Prompt generation and response handling
8
+ * - Token counting and cost estimation
9
+ * - Automatic retries and error handling
10
+ *
11
+ * Usage:
12
+ * ```typescript
13
+ * import { createAnthropicClient, callClaude } from './llm/index.js';
14
+ * const client = createAnthropicClient();
15
+ * const response = await callClaude({ prompt: '...' });
16
+ * ```
17
+ */
18
+ import Anthropic from '@anthropic-ai/sdk';
19
+ // Export all utilities from anthropic-client
20
+ export * from './anthropic-client.js';
21
+ /**
22
+ * Create and configure Anthropic client
23
+ * Uses API key from ANTHROPIC_API_KEY environment variable
24
+ */
25
+ export function createAnthropicClient() {
26
+ const apiKey = process.env.ANTHROPIC_API_KEY;
27
+ if (!apiKey) {
28
+ throw new Error('ANTHROPIC_API_KEY environment variable not set. ' +
29
+ 'Please set your Anthropic API key to use the LLM module.');
30
+ }
31
+ return new Anthropic({ apiKey });
32
+ }
33
+ export { Anthropic };
34
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/llm/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAE1C,6CAA6C;AAC7C,cAAc,uBAAuB,CAAC;AAEtC;;;GAGG;AACH,MAAM,UAAU,qBAAqB;IACnC,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC;IAE7C,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CACb,kDAAkD;YAChD,0DAA0D,CAC7D,CAAC;IACJ,CAAC;IAED,OAAO,IAAI,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;AACnC,CAAC;AAID,OAAO,EAAE,SAAS,EAAE,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Complexity Reducer Prompt
3
+ * Focus: Simplify and refactor complex code
4
+ */
5
+ import type { PromptContext } from './types.js';
6
+ export declare function generatePrompt(context: PromptContext): string;
7
+ //# sourceMappingURL=complexity-reducer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"complexity-reducer.d.ts","sourceRoot":"","sources":["../../src/prompts/complexity-reducer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,wBAAgB,cAAc,CAAC,OAAO,EAAE,aAAa,GAAG,MAAM,CAkD7D"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Complexity Reducer Prompt
3
+ * Focus: Simplify and refactor complex code
4
+ */
5
+ import { getModeInstructions } from '../core/mode-selector.js';
6
+ export function generatePrompt(context) {
7
+ const { file, content, gradient, rank, totalFiles } = context;
8
+ const { dominantSignal, signals, score } = gradient;
9
+ const rankInfo = rank && totalFiles
10
+ ? `(ranked #${rank} of ${totalFiles})`
11
+ : '';
12
+ return `# Task
13
+ You are improving \`${file}\` in mode \`complexity_reducer\`.
14
+
15
+ ## File Context
16
+ **Current gradient**: ${score.toFixed(3)} ${rankInfo}
17
+ **Dominant issue**: ${dominantSignal.name} = ${dominantSignal.value.toFixed(3)}
18
+
19
+ ${getModeInstructions('complexity_reducer')}
20
+
21
+ ## Current File Content
22
+ \`\`\`typescript
23
+ ${content}
24
+ \`\`\`
25
+
26
+ ## Your Task
27
+ Simplify and refactor this code to reduce complexity:
28
+
29
+ 1. Identify complexity issues:
30
+ - Long functions (>20 lines)
31
+ - Deep nesting (>3 levels)
32
+ - Complex conditionals
33
+ - Duplicate code patterns
34
+ - Unclear variable names
35
+
36
+ 2. Refactor to simplify:
37
+ - Extract long functions into smaller ones
38
+ - Reduce nesting with early returns
39
+ - Simplify conditional logic
40
+ - Remove code duplication
41
+ - Improve naming for clarity
42
+
43
+ 3. Preserve behavior:
44
+ - Do NOT change functionality
45
+ - Do NOT fix bugs (use error_reducer for that)
46
+ - Do NOT remove tests or validation
47
+
48
+ **Important**:
49
+ - Make minimal, focused changes
50
+ - Preserve existing functionality
51
+ - Add tests if removing code
52
+ - Keep the same file structure
53
+ - Explain what you changed and why`;
54
+ }
55
+ //# sourceMappingURL=complexity-reducer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"complexity-reducer.js","sourceRoot":"","sources":["../../src/prompts/complexity-reducer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAG/D,MAAM,UAAU,cAAc,CAAC,OAAsB;IACnD,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC;IAC9D,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,QAAQ,CAAC;IAEpD,MAAM,QAAQ,GAAG,IAAI,IAAI,UAAU;QACjC,CAAC,CAAC,YAAY,IAAI,OAAO,UAAU,GAAG;QACtC,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO;sBACa,IAAI;;;wBAGF,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,QAAQ;sBAC9B,cAAc,CAAC,IAAI,MAAM,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;;EAE5E,mBAAmB,CAAC,oBAAoB,CAAC;;;;EAIzC,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCA8B0B,CAAC;AACpC,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Debt Payer Prompt
3
+ * Focus: Fix lint issues and improve code quality
4
+ */
5
+ import type { PromptContext } from './types.js';
6
+ export declare function generatePrompt(context: PromptContext): string;
7
+ //# sourceMappingURL=debt-payer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debt-payer.d.ts","sourceRoot":"","sources":["../../src/prompts/debt-payer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,wBAAgB,cAAc,CAAC,OAAO,EAAE,aAAa,GAAG,MAAM,CAkD7D"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Debt Payer Prompt
3
+ * Focus: Fix lint issues and improve code quality
4
+ */
5
+ import { getModeInstructions } from '../core/mode-selector.js';
6
+ export function generatePrompt(context) {
7
+ const { file, content, gradient, rank, totalFiles } = context;
8
+ const { dominantSignal, signals, score } = gradient;
9
+ const rankInfo = rank && totalFiles
10
+ ? `(ranked #${rank} of ${totalFiles})`
11
+ : '';
12
+ return `# Task
13
+ You are improving \`${file}\` in mode \`debt_payer\`.
14
+
15
+ ## File Context
16
+ **Current gradient**: ${score.toFixed(3)} ${rankInfo}
17
+ **Dominant issue**: ${dominantSignal.name} = ${dominantSignal.value.toFixed(3)}
18
+
19
+ ${getModeInstructions('debt_payer')}
20
+
21
+ ## Current File Content
22
+ \`\`\`typescript
23
+ ${content}
24
+ \`\`\`
25
+
26
+ ## Your Task
27
+ Fix technical debt and improve code quality:
28
+
29
+ 1. Identify quality issues:
30
+ - ESLint errors and warnings
31
+ - Missing type annotations
32
+ - Poor naming conventions
33
+ - Unused imports or variables
34
+ - Formatting inconsistencies
35
+
36
+ 2. Make quality improvements:
37
+ - Fix ESLint errors
38
+ - Add TypeScript types
39
+ - Improve variable/function names
40
+ - Remove unused code
41
+ - Fix formatting
42
+
43
+ 3. Stay focused on quality:
44
+ - Do NOT refactor structure (use complexity_reducer for that)
45
+ - Do NOT fix logic bugs (use error_reducer for that)
46
+ - Do NOT change functionality
47
+
48
+ **Important**:
49
+ - Make minimal, focused changes
50
+ - Preserve existing functionality
51
+ - Add tests if removing code
52
+ - Keep the same file structure
53
+ - Explain what you changed and why`;
54
+ }
55
+ //# sourceMappingURL=debt-payer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debt-payer.js","sourceRoot":"","sources":["../../src/prompts/debt-payer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAG/D,MAAM,UAAU,cAAc,CAAC,OAAsB;IACnD,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC;IAC9D,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,QAAQ,CAAC;IAEpD,MAAM,QAAQ,GAAG,IAAI,IAAI,UAAU;QACjC,CAAC,CAAC,YAAY,IAAI,OAAO,UAAU,GAAG;QACtC,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO;sBACa,IAAI;;;wBAGF,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,QAAQ;sBAC9B,cAAc,CAAC,IAAI,MAAM,cAAc,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;;EAE5E,mBAAmB,CAAC,YAAY,CAAC;;;;EAIjC,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mCA8B0B,CAAC;AACpC,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Error Reducer Prompt
3
+ * Focus: Fix bugs and add error handling
4
+ */
5
+ import type { PromptContext } from './types.js';
6
+ export declare function generatePrompt(context: PromptContext): string;
7
+ //# sourceMappingURL=error-reducer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-reducer.d.ts","sourceRoot":"","sources":["../../src/prompts/error-reducer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,wBAAgB,cAAc,CAAC,OAAO,EAAE,aAAa,GAAG,MAAM,CAiD7D"}