codehere 0.2.2 → 0.3.0-rc.10

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 (238) hide show
  1. package/README.md +88 -68
  2. package/dist/domain/entities/task.js +4 -4
  3. package/dist/error-handler.js +4 -9
  4. package/dist/index.js +261 -1224
  5. package/dist/infrastructure/config/product-context.js +7 -6
  6. package/dist/infrastructure/hooks/claude-sdk-hook.js +348 -72
  7. package/dist/infrastructure/observability/execution-tracer.js +11 -6
  8. package/dist/infrastructure/orchestration/agent-adapter.js +13 -0
  9. package/dist/infrastructure/orchestration/agent-installer.js +101 -0
  10. package/dist/infrastructure/orchestration/agents-config-seed.js +56 -0
  11. package/dist/infrastructure/orchestration/aider-adapter.js +319 -0
  12. package/dist/infrastructure/orchestration/artifacts-extractor.js +175 -0
  13. package/dist/infrastructure/orchestration/claude-code-adapter.js +352 -0
  14. package/dist/infrastructure/orchestration/codex-adapter.js +310 -0
  15. package/dist/infrastructure/orchestration/conductor-adapter.js +340 -0
  16. package/dist/infrastructure/orchestration/generic-cli-adapter.js +553 -0
  17. package/dist/infrastructure/orchestration/opencode-adapter.js +275 -0
  18. package/dist/infrastructure/orchestration/progress-aggregator.js +189 -0
  19. package/dist/infrastructure/orchestration/readiness.js +106 -0
  20. package/dist/infrastructure/orchestration/session-manager.js +278 -0
  21. package/dist/infrastructure/orchestration/session-persistence.js +109 -0
  22. package/dist/infrastructure/protocols/mcp-helpers.js +10 -30
  23. package/dist/infrastructure/protocols/mcp-server-impl.js +359 -21
  24. package/dist/infrastructure/protocols/probe-port.js +36 -0
  25. package/dist/infrastructure/protocols/ui-page.js +1827 -0
  26. package/dist/infrastructure/security/file-collection.js +115 -0
  27. package/dist/infrastructure/security/trust-scorer.js +301 -56
  28. package/dist/infrastructure/storage/task-repository.js +8 -7
  29. package/dist/monitoring.js +9 -38
  30. package/dist/presentation/cli/commands/help-command.js +96 -139
  31. package/dist/presentation/cli/commands/hook-command.js +17 -24
  32. package/dist/presentation/cli/commands/report-command.js +59 -72
  33. package/dist/presentation/cli/commands/setup-command.js +4 -4
  34. package/dist/presentation/cli/commands/status-command.js +321 -30
  35. package/dist/presentation/cli/commands/trust-command.js +84 -72
  36. package/dist/presentation/cli/error-display.js +17 -21
  37. package/dist/presentation/cli/repl.js +474 -0
  38. package/dist/ui.js +11 -11
  39. package/package.json +24 -62
  40. package/dist/agents/base.js +0 -101
  41. package/dist/agents/orchestrator-model-driven.js +0 -141
  42. package/dist/agents/react-orchestrator-agent.js +0 -54
  43. package/dist/application/agents/execution-agent.js +0 -508
  44. package/dist/application/agents/multi-agent-orchestrator.js +0 -295
  45. package/dist/application/agents/planning-agent.js +0 -433
  46. package/dist/application/agents/validation-agent.js +0 -317
  47. package/dist/application/architectures/plan-and-act.js +0 -242
  48. package/dist/application/index.js +0 -12
  49. package/dist/application/services/agent-factory.js +0 -28
  50. package/dist/application/services/dependency-container.js +0 -596
  51. package/dist/application/services/git-context-service.js +0 -83
  52. package/dist/application/services/intelligent-router.js +0 -934
  53. package/dist/application/services/tool-executor-service.js +0 -94
  54. package/dist/application/use-cases/ask-question-use-case.js +0 -338
  55. package/dist/application/use-cases/edit-file-use-case.js +0 -830
  56. package/dist/application/use-cases/explain-file-use-case.js +0 -50
  57. package/dist/application/use-cases/index-codebase-use-case.js +0 -113
  58. package/dist/application/use-cases/planning-use-case.js +0 -276
  59. package/dist/application/use-cases/react-orchestration-use-case.js +0 -329
  60. package/dist/application/use-cases/reflexion-use-case.js +0 -30
  61. package/dist/application/workflows/deterministic-workflows.js +0 -189
  62. package/dist/ast-parser.js +0 -331
  63. package/dist/cache.js +0 -180
  64. package/dist/chat.js +0 -251
  65. package/dist/code-analysis.js +0 -327
  66. package/dist/context.js +0 -187
  67. package/dist/docs.js +0 -146
  68. package/dist/domain/entities/code-chunk.js +0 -6
  69. package/dist/domain/entities/decision.js +0 -9
  70. package/dist/domain/entities/edit.js +0 -6
  71. package/dist/domain/entities/knowledge-node.js +0 -9
  72. package/dist/domain/entities/knowledge-preservation.js +0 -10
  73. package/dist/domain/entities/memory.js +0 -6
  74. package/dist/domain/entities/pattern.js +0 -7
  75. package/dist/domain/entities/plan.js +0 -6
  76. package/dist/domain/entities/query.js +0 -6
  77. package/dist/domain/errors/embeddings-not-found-error.js +0 -13
  78. package/dist/domain/index.js +0 -19
  79. package/dist/domain/interfaces/ai-service.interface.js +0 -6
  80. package/dist/domain/interfaces/code-analyzer.interface.js +0 -6
  81. package/dist/domain/interfaces/decision-repository.interface.js +0 -9
  82. package/dist/domain/interfaces/embedding-repository.interface.js +0 -6
  83. package/dist/domain/interfaces/knowledge-graph-repository.interface.js +0 -9
  84. package/dist/domain/interfaces/knowledge-preservation-repository.interface.js +0 -8
  85. package/dist/domain/interfaces/memory-repository.interface.js +0 -6
  86. package/dist/domain/interfaces/pattern-repository.interface.js +0 -6
  87. package/dist/domain/interfaces/verification-service.interface.js +0 -6
  88. package/dist/domain/services/cross-team-pattern-sharing.js +0 -125
  89. package/dist/domain/services/decision-recorder.js +0 -223
  90. package/dist/domain/services/decision-retriever.js +0 -133
  91. package/dist/domain/services/environment-mode-manager.js +0 -22
  92. package/dist/domain/services/graded-memory-activation.js +0 -69
  93. package/dist/domain/services/knowledge-access.js +0 -132
  94. package/dist/domain/services/knowledge-extractor.js +0 -247
  95. package/dist/domain/services/knowledge-graph-builder.js +0 -268
  96. package/dist/domain/services/knowledge-graph-query.js +0 -187
  97. package/dist/domain/services/memory-retriever.js +0 -82
  98. package/dist/domain/services/memory-synthesizer.js +0 -91
  99. package/dist/domain/services/pattern-extractor.js +0 -442
  100. package/dist/domain/services/query-intent-classifier.js +0 -140
  101. package/dist/domain/services/react-loop.js +0 -186
  102. package/dist/domain/services/risk-tier-detector.js +0 -78
  103. package/dist/edit.js +0 -319
  104. package/dist/embed.js +0 -459
  105. package/dist/formatter.js +0 -168
  106. package/dist/git.js +0 -198
  107. package/dist/infrastructure/ai/cohere-ai-service.js +0 -607
  108. package/dist/infrastructure/ai/command-r-evaluation.js +0 -206
  109. package/dist/infrastructure/ai/model-config.js +0 -84
  110. package/dist/infrastructure/ai/provider-ai-service.js +0 -477
  111. package/dist/infrastructure/cache/embedding-cache.js +0 -175
  112. package/dist/infrastructure/cache/query-result-cache.js +0 -66
  113. package/dist/infrastructure/cache/response-cache.js +0 -48
  114. package/dist/infrastructure/cache/security-scan-cache.js +0 -47
  115. package/dist/infrastructure/chunking/ast-code-chunker.js +0 -19
  116. package/dist/infrastructure/chunking/code-aware-chunker.js +0 -397
  117. package/dist/infrastructure/context/context-compressor.js +0 -329
  118. package/dist/infrastructure/context/conversation-context.js +0 -128
  119. package/dist/infrastructure/context/session-manager.js +0 -94
  120. package/dist/infrastructure/cost/cost-tracker.js +0 -360
  121. package/dist/infrastructure/file-scanner/file-scanner.js +0 -106
  122. package/dist/infrastructure/governance/nist-ai-rmf.js +0 -292
  123. package/dist/infrastructure/governance/policy-as-code.js +0 -258
  124. package/dist/infrastructure/governance/prompt-to-code-lineage.js +0 -239
  125. package/dist/infrastructure/index.js +0 -7
  126. package/dist/infrastructure/observability/prompt-versioner.js +0 -145
  127. package/dist/infrastructure/protocols/a2a-metadata.js +0 -137
  128. package/dist/infrastructure/protocols/a2a-protocol.js +0 -314
  129. package/dist/infrastructure/protocols/mcp-oauth.js +0 -184
  130. package/dist/infrastructure/protocols/mcp-server.js +0 -333
  131. package/dist/infrastructure/protocols/streaming-handler.js +0 -103
  132. package/dist/infrastructure/providers/cohere-provider.js +0 -444
  133. package/dist/infrastructure/providers/fake-provider.js +0 -130
  134. package/dist/infrastructure/providers/local-llm-provider.js +0 -330
  135. package/dist/infrastructure/providers/model-config.types.js +0 -9
  136. package/dist/infrastructure/providers/model-provider.interface.js +0 -8
  137. package/dist/infrastructure/providers/openai-provider.js +0 -413
  138. package/dist/infrastructure/providers/openrouter-provider.js +0 -399
  139. package/dist/infrastructure/providers/operation-provider-resolver.js +0 -105
  140. package/dist/infrastructure/providers/provider-config-loader.js +0 -120
  141. package/dist/infrastructure/providers/provider-registry.js +0 -88
  142. package/dist/infrastructure/safety/pattern-detector.js +0 -133
  143. package/dist/infrastructure/security/ai-sast-scanner.js +0 -290
  144. package/dist/infrastructure/security/docker-sandbox.js +0 -178
  145. package/dist/infrastructure/security/enhanced-security-gate.js +0 -151
  146. package/dist/infrastructure/security/license-scanner.js +0 -167
  147. package/dist/infrastructure/security/provider-bias-detector.js +0 -164
  148. package/dist/infrastructure/security/sandbox-executor.js +0 -64
  149. package/dist/infrastructure/serialization/toon-serializer.js +0 -119
  150. package/dist/infrastructure/storage/memory-stream-service.js +0 -204
  151. package/dist/infrastructure/storage/plan-repository.js +0 -96
  152. package/dist/infrastructure/storage/sqlite-decision-repository.js +0 -232
  153. package/dist/infrastructure/storage/sqlite-embedding-repository.js +0 -311
  154. package/dist/infrastructure/storage/sqlite-knowledge-graph-repository.js +0 -417
  155. package/dist/infrastructure/storage/sqlite-knowledge-preservation-repository.js +0 -230
  156. package/dist/infrastructure/storage/sqlite-memory-repository.js +0 -229
  157. package/dist/infrastructure/storage/sqlite-pattern-repository.js +0 -249
  158. package/dist/infrastructure/storage/task-helpers.js +0 -197
  159. package/dist/infrastructure/telemetry/telemetry-service.js +0 -167
  160. package/dist/infrastructure/ux/appropriate-friction.js +0 -213
  161. package/dist/infrastructure/ux/bi-directional-learning.js +0 -337
  162. package/dist/infrastructure/ux/capability-boundaries.js +0 -42
  163. package/dist/infrastructure/ux/comprehensive-formatter.js +0 -117
  164. package/dist/infrastructure/ux/contextual-feature-discovery.js +0 -10
  165. package/dist/infrastructure/ux/expectation-management.js +0 -327
  166. package/dist/infrastructure/ux/feature-discovery.js +0 -14
  167. package/dist/infrastructure/ux/feedback-prompt.js +0 -45
  168. package/dist/infrastructure/ux/hitl-validation.js +0 -297
  169. package/dist/infrastructure/ux/progress-indicator.js +0 -116
  170. package/dist/infrastructure/ux/progressive-disclosure.js +0 -236
  171. package/dist/infrastructure/ux/review-checkpoint.js +0 -72
  172. package/dist/infrastructure/ux/staged-feature-intro.js +0 -24
  173. package/dist/infrastructure/ux/stream-markdown.js +0 -151
  174. package/dist/infrastructure/ux/syntax-highlighter.js +0 -91
  175. package/dist/infrastructure/ux/team-standards.js +0 -196
  176. package/dist/infrastructure/ux/transparency.js +0 -71
  177. package/dist/infrastructure/validation/agent-feedback.js +0 -55
  178. package/dist/infrastructure/validation/agent-validation-helper.js +0 -137
  179. package/dist/infrastructure/validation/review-handler.js +0 -40
  180. package/dist/infrastructure/validation/summary-aggregator.js +0 -70
  181. package/dist/infrastructure/validation/summary-extractor.js +0 -45
  182. package/dist/infrastructure/validation/trace-summary.js +0 -52
  183. package/dist/infrastructure/verification/verification-service.js +0 -47
  184. package/dist/infrastructure/xai/attention-visualizer.js +0 -172
  185. package/dist/infrastructure/xai/cot-visualizer.js +0 -283
  186. package/dist/infrastructure/xai/decision-tree-log.js +0 -212
  187. package/dist/infrastructure/xai/interactive-xai.js +0 -260
  188. package/dist/infrastructure/xai/uncertainty-quantifier.js +0 -198
  189. package/dist/intelligent-retrieval.js +0 -272
  190. package/dist/intent/classifier.js +0 -2
  191. package/dist/intent/context.js +0 -2
  192. package/dist/iterative-refinement.js +0 -189
  193. package/dist/learning.js +0 -232
  194. package/dist/log.js +0 -31
  195. package/dist/migrate.js +0 -133
  196. package/dist/parallel-processor.js +0 -534
  197. package/dist/planner.js +0 -198
  198. package/dist/policy.js +0 -26
  199. package/dist/presentation/cli/commands/ask-command.js +0 -314
  200. package/dist/presentation/cli/commands/cost-command.js +0 -191
  201. package/dist/presentation/cli/commands/decision-command.js +0 -207
  202. package/dist/presentation/cli/commands/docs-command.js +0 -25
  203. package/dist/presentation/cli/commands/fix-command.js +0 -53
  204. package/dist/presentation/cli/commands/knowledge-command.js +0 -129
  205. package/dist/presentation/cli/commands/learning-dashboard-command.js +0 -183
  206. package/dist/presentation/cli/commands/models-command.js +0 -194
  207. package/dist/presentation/cli/commands/orchestrate-command.js +0 -207
  208. package/dist/presentation/cli/commands/plan-command.js +0 -246
  209. package/dist/presentation/cli/commands/product-command.js +0 -199
  210. package/dist/presentation/cli/commands/react-command.js +0 -181
  211. package/dist/presentation/cli/commands/review-command.js +0 -154
  212. package/dist/presentation/cli/commands/run-command.js +0 -188
  213. package/dist/presentation/cli/commands/smart-command.js +0 -395
  214. package/dist/presentation/cli/commands/suggest-command.js +0 -138
  215. package/dist/presentation/cli/commands/trace-command.js +0 -129
  216. package/dist/presentation/cli/commands/undo-command.js +0 -150
  217. package/dist/query-optimizer.js +0 -205
  218. package/dist/refactor.js +0 -116
  219. package/dist/review.js +0 -206
  220. package/dist/search.js +0 -163
  221. package/dist/session.js +0 -704
  222. package/dist/task-verification.js +0 -336
  223. package/dist/testgen.js +0 -166
  224. package/dist/token-optimizer.js +0 -277
  225. package/dist/tools/bash.js +0 -213
  226. package/dist/tools/edit.js +0 -235
  227. package/dist/tools/executor.js +0 -153
  228. package/dist/tools/git-tool.js +0 -292
  229. package/dist/tools/parser.js +0 -158
  230. package/dist/tools/registry.js +0 -302
  231. package/dist/tools/search.js +0 -100
  232. package/dist/types.js +0 -2
  233. package/dist/utils/check-api-status.js +0 -100
  234. package/dist/utils/diff-parser.js +0 -162
  235. package/dist/verification/backup.js +0 -259
  236. package/dist/verification/compiler.js +0 -264
  237. package/dist/verification/index.js +0 -273
  238. package/dist/verification/test-runner.js +0 -379
@@ -1,477 +0,0 @@
1
- /**
2
- * Infrastructure: ProviderAIService
3
- * Adapter from IModelProvider → IAIService
4
- *
5
- * Phase 4B: Provider Adapter Implementation
6
- * Bridges provider layer into existing IAIService abstraction
7
- *
8
- * This adapter:
9
- * - Implements IAIService interface
10
- * - Uses IModelProvider internally for actual AI operations
11
- * - Preserves all existing behavior (context compression, tracing, prompt building)
12
- * - Maintains backward compatibility with existing code
13
- */
14
- import { executionTracer } from '../observability/execution-tracer.js';
15
- import { promptVersioner } from '../observability/prompt-versioner.js';
16
- import { getModelConfigManager } from './model-config.js';
17
- import { OperationProviderResolver } from '../providers/operation-provider-resolver.js';
18
- import { ProviderRegistry } from '../providers/provider-registry.js';
19
- import { encoding_for_model } from 'tiktoken';
20
- import { serializeCodeChunks } from '../serialization/toon-serializer.js';
21
- // Token counting helper (same as CohereAIService for consistency)
22
- let tokenEncoder = null;
23
- function getTokenEncoder() {
24
- if (!tokenEncoder) {
25
- try {
26
- tokenEncoder = encoding_for_model('gpt-3.5-turbo');
27
- }
28
- catch {
29
- tokenEncoder = encoding_for_model('gpt-4');
30
- }
31
- }
32
- return tokenEncoder;
33
- }
34
- function countTokens(text) {
35
- try {
36
- const encoder = getTokenEncoder();
37
- return encoder.encode(text).length;
38
- }
39
- catch (error) {
40
- console.warn('Warning: tiktoken failed, using character-based estimate (less accurate)');
41
- return Math.ceil(text.length / 4);
42
- }
43
- }
44
- /**
45
- * ProviderAIService
46
- * Adapter that implements IAIService using IModelProvider(s)
47
- *
48
- * Phase 4F: Supports per-operation provider selection
49
- * Phase 4G: Supports user-facing config files
50
- */
51
- export class ProviderAIService {
52
- _contextCompressor;
53
- provider; // Default provider (backward compatibility)
54
- providerResolver = null;
55
- constructor(provider, contextCompressor, operationConfig, configDefaultProvider) {
56
- this.provider = provider; // Keep for backward compatibility
57
- this._contextCompressor = contextCompressor;
58
- // Phase 4F/4G: Initialize operation provider resolver if operation config is provided
59
- if (operationConfig !== undefined || configDefaultProvider !== undefined) {
60
- const registry = ProviderRegistry.getInstance();
61
- this.providerResolver = new OperationProviderResolver(registry, operationConfig || null, configDefaultProvider || null);
62
- }
63
- }
64
- /**
65
- * Get provider for a specific operation
66
- * Phase 4F: Operation-aware provider resolution
67
- */
68
- getProviderForOperation(operation) {
69
- // If resolver is configured, use it
70
- if (this.providerResolver) {
71
- return this.providerResolver.resolveProvider(operation);
72
- }
73
- // Otherwise, use default provider (backward compatible)
74
- return this.provider;
75
- }
76
- /**
77
- * Build prompt from query, context, and memories
78
- * Reuses logic from CohereAIService to preserve behavior
79
- */
80
- async buildPrompt(query, context, memories) {
81
- // Use TOON serialization if enabled, otherwise use traditional format
82
- const contextText = await serializeCodeChunks(context);
83
- const memoryText = memories && memories.length > 0
84
- ? `\n\nPREVIOUS EXPERIENCES:\n${memories.map(m => `- ${m.description}`).join('\n')}`
85
- : '';
86
- // Get conversation history if available in context
87
- let conversationHistoryText = '';
88
- if (context.length > 0 && context[0].conversationHistory) {
89
- const history = context[0].conversationHistory;
90
- if (history && history.length > 0) {
91
- const recentHistory = history.slice(-3);
92
- conversationHistoryText = `\n\nCONVERSATION HISTORY:\n${recentHistory.map((turn, idx) => `[Previous ${idx + 1}]: User asked "${turn.query}". Response: ${turn.response.substring(0, 150)}...`).join('\n')}\n`;
93
- }
94
- }
95
- return `You are a strict coding assistant for enterprise environments.
96
- Use ONLY the provided code context.
97
- ${conversationHistoryText ? 'Consider the conversation history when answering the current query, especially if the user uses references like "it", "that", or "the previous".' : ''}
98
-
99
- CONTEXT:
100
- ${contextText}${memoryText}${conversationHistoryText}
101
-
102
- USER QUERY:
103
- ${query}`;
104
- }
105
- /**
106
- * Select model based on context size and use case
107
- * Preserves existing model selection logic
108
- */
109
- selectModel(contextChunks, memoryCount, useCase = 'default') {
110
- const modelConfig = getModelConfigManager();
111
- if (modelConfig.isCommandModelAvailable()) {
112
- const preferredModel = modelConfig.getPreferredModel(useCase);
113
- if (preferredModel) {
114
- return preferredModel;
115
- }
116
- }
117
- // Use default model for now
118
- if (contextChunks > 20 || memoryCount > 10) {
119
- return undefined; // Use default
120
- }
121
- return undefined; // Use default
122
- }
123
- async chat(query, context, memories) {
124
- // Context Compression: Compress if context is too large (preserves CohereAIService behavior)
125
- let finalContext = context;
126
- let finalMemories = memories;
127
- let compressionMetrics;
128
- const contextCompressor = this._contextCompressor || this.contextCompressor;
129
- if (contextCompressor) {
130
- const estimatedTokens = context.reduce((sum, chunk) => sum + Math.ceil(chunk.content.length / 4), 0);
131
- const maxTokens = 3000; // Same threshold as CohereAIService
132
- if (estimatedTokens > maxTokens) {
133
- const strategy = {
134
- maxTokens,
135
- preserveCode: true,
136
- preserveErrors: true,
137
- compressMemories: true,
138
- compressObservations: false,
139
- };
140
- const compressed = await contextCompressor.compressWithSummarization(context, query, strategy);
141
- finalContext = compressed.chunks;
142
- compressionMetrics = {
143
- originalTokens: compressed.originalTokenCount,
144
- compressedTokens: compressed.compressedTokenCount,
145
- reductionPercent: compressed.reductionPercent,
146
- };
147
- if (strategy.compressMemories && memories && memories.length > 10) {
148
- finalMemories = await contextCompressor.compressMemories(memories, query, 10);
149
- }
150
- const runId = executionTracer.getCurrentRunId();
151
- if (runId) {
152
- executionTracer.trace({
153
- operationType: 'context_compression',
154
- operationName: 'compress_context',
155
- input: { contextCount: context.length, estimatedTokens },
156
- output: {
157
- compressedCount: finalContext.length,
158
- ...compressionMetrics
159
- },
160
- metadata: { strategy: 'llm_summarization' },
161
- });
162
- }
163
- }
164
- }
165
- const prompt = await this.buildPrompt(query, finalContext, finalMemories);
166
- const model = this.selectModel(finalContext.length, finalMemories?.length || 0, 'chat');
167
- // Register prompt version for reproducibility
168
- const promptVersionId = promptVersioner.registerVersion(prompt, {
169
- model: model || 'default',
170
- temperature: 0.7,
171
- operation: 'chat',
172
- });
173
- const runId = executionTracer.getCurrentRunId();
174
- if (runId) {
175
- promptVersioner.linkRunToVersion(prompt, runId);
176
- }
177
- const startTime = Date.now();
178
- // Phase 4F: Use operation-aware provider resolution
179
- const operationProvider = this.getProviderForOperation('chat');
180
- // Trace LLM call
181
- const traceId = executionTracer.trace({
182
- operationType: 'llm_call',
183
- operationName: 'chat',
184
- input: { query, contextCount: context.length, memoryCount: memories?.length || 0 },
185
- metadata: {
186
- model: model || 'default',
187
- temperature: 0.7,
188
- promptVersionId,
189
- },
190
- });
191
- try {
192
- const response = await operationProvider.chat(prompt, {
193
- model,
194
- temperature: 0.7,
195
- });
196
- const result = response.text || 'No response generated';
197
- const duration = Date.now() - startTime;
198
- // Phase 4F: Use operation-aware provider for token counting
199
- const inputTokens = response.usage?.inputTokens || await operationProvider.countTokens(prompt, model);
200
- const outputTokens = response.usage?.outputTokens || await operationProvider.countTokens(result, model);
201
- executionTracer.trace({
202
- operationType: 'llm_call',
203
- operationName: 'chat',
204
- output: { responseLength: result.length, inputTokens, outputTokens },
205
- duration,
206
- metadata: {
207
- model: model || 'default',
208
- temperature: 0.7,
209
- promptVersionId,
210
- },
211
- });
212
- return result;
213
- }
214
- catch (error) {
215
- executionTracer.trace({
216
- operationType: 'llm_call',
217
- operationName: 'chat',
218
- error: error instanceof Error ? error : new Error(String(error)),
219
- duration: Date.now() - startTime,
220
- metadata: {
221
- model: model || 'default',
222
- temperature: 0.7,
223
- promptVersionId,
224
- },
225
- });
226
- throw error;
227
- }
228
- }
229
- async chatStream(query, context, memories, streamHandler) {
230
- const prompt = await this.buildPrompt(query, context, memories);
231
- const model = this.selectModel(context.length, memories?.length || 0, 'chat');
232
- const promptVersionId = promptVersioner.registerVersion(prompt, {
233
- model: model || 'default',
234
- temperature: 0.7,
235
- operation: 'chat-stream',
236
- });
237
- const runId = executionTracer.getCurrentRunId();
238
- if (runId) {
239
- promptVersioner.linkRunToVersion(prompt, runId);
240
- }
241
- const startTime = Date.now();
242
- let fullText = '';
243
- try {
244
- executionTracer.trace({
245
- operationType: 'llm_call',
246
- operationName: 'chat-stream',
247
- input: { query, contextCount: context.length, memoryCount: memories?.length || 0 },
248
- metadata: {
249
- model: model || 'default',
250
- temperature: 0.7,
251
- promptVersionId,
252
- streaming: true,
253
- },
254
- });
255
- // Phase 4F: Use operation-aware provider resolution
256
- const operationProvider = this.getProviderForOperation('chat');
257
- if (operationProvider.chatStream) {
258
- // Use provider's streaming if available
259
- const response = await operationProvider.chatStream(prompt, {
260
- model,
261
- temperature: 0.7,
262
- }, (event) => {
263
- if (event.type === 'delta' && event.text) {
264
- fullText += event.text;
265
- if (streamHandler.onToken) {
266
- streamHandler.onToken(event.text);
267
- }
268
- }
269
- else if (event.type === 'complete' && event.text) {
270
- fullText = event.text;
271
- }
272
- else if (event.type === 'error' && event.error) {
273
- if (streamHandler.onError) {
274
- streamHandler.onError(event.error);
275
- }
276
- }
277
- });
278
- fullText = response.text || fullText;
279
- }
280
- else {
281
- // Fallback: Use regular chat and simulate streaming
282
- const response = await operationProvider.chat(prompt, {
283
- model,
284
- temperature: 0.7,
285
- });
286
- fullText = response.text || '';
287
- // Simulate streaming by sending chunks
288
- const chunkSize = 10;
289
- for (let i = 0; i < fullText.length; i += chunkSize) {
290
- const chunk = fullText.substring(i, i + chunkSize);
291
- if (streamHandler.onToken) {
292
- streamHandler.onToken(chunk);
293
- }
294
- if (fullText.length > chunkSize * 2) {
295
- await new Promise(resolve => setTimeout(resolve, 50));
296
- }
297
- }
298
- }
299
- const duration = Date.now() - startTime;
300
- const inputTokens = await operationProvider.countTokens(prompt, model);
301
- const outputTokens = await operationProvider.countTokens(fullText, model);
302
- executionTracer.trace({
303
- operationType: 'llm_call',
304
- operationName: 'chat-stream',
305
- output: { responseLength: fullText.length, inputTokens, outputTokens },
306
- duration,
307
- metadata: {
308
- model: model || 'default',
309
- temperature: 0.7,
310
- promptVersionId,
311
- streaming: true,
312
- },
313
- });
314
- if (streamHandler.onComplete) {
315
- streamHandler.onComplete(fullText);
316
- }
317
- return fullText;
318
- }
319
- catch (error) {
320
- const duration = Date.now() - startTime;
321
- executionTracer.trace({
322
- operationType: 'llm_call',
323
- operationName: 'chat-stream',
324
- error: error instanceof Error ? error : new Error(String(error)),
325
- duration,
326
- metadata: {
327
- model: model || 'default',
328
- temperature: 0.7,
329
- promptVersionId,
330
- streaming: true,
331
- },
332
- });
333
- if (streamHandler.onError) {
334
- streamHandler.onError(error instanceof Error ? error : new Error(String(error)));
335
- }
336
- throw error;
337
- }
338
- }
339
- async embed(text) {
340
- // Phase 4F: Use operation-aware provider resolution
341
- const operationProvider = this.getProviderForOperation('embedding');
342
- return await operationProvider.embed(text);
343
- }
344
- async embedQuery(query) {
345
- // Phase 4F: Use operation-aware provider resolution
346
- const operationProvider = this.getProviderForOperation('embedding');
347
- if (operationProvider.embedQuery) {
348
- return await operationProvider.embedQuery(query);
349
- }
350
- // Fallback: Use regular embed if embedQuery not available
351
- const result = await operationProvider.embed(query);
352
- return Array.isArray(result[0]) ? result[0] : result;
353
- }
354
- async generateEdit(fileContent, instruction, filepath) {
355
- const prompt = `You are a code editor. Return the COMPLETE modified file content.
356
-
357
- CRITICAL RULES:
358
- 1. Return ONLY the complete modified file content - no explanations, no markdown, no code blocks
359
- 2. If renaming a function/class/variable, you MUST update ALL references
360
- 3. Maintain exact indentation and formatting from the original
361
- 4. Only modify what's necessary for the instruction
362
- 5. Return the ENTIRE file, not just the changes
363
-
364
- FILE: ${filepath}
365
-
366
- CURRENT CODE:
367
- \`\`\`
368
- ${fileContent}
369
- \`\`\`
370
-
371
- INSTRUCTION: ${instruction}
372
-
373
- Return the COMPLETE modified file content (entire file, not a diff):`;
374
- // Phase 4F: Use operation-aware provider resolution (chat operation)
375
- const operationProvider = this.getProviderForOperation('chat');
376
- const response = await operationProvider.chat(prompt, {
377
- temperature: 0.3, // Lower for deterministic code generation
378
- });
379
- return response.text || '';
380
- }
381
- async generateFileContent(filepath, instruction, requirements = []) {
382
- const requirementsText = requirements.length > 0
383
- ? `\n\nREQUIREMENTS:\n${requirements.map((r, i) => `${i + 1}. ${r}`).join('\n')}`
384
- : '';
385
- const ext = filepath.split('.').pop()?.toLowerCase() || '';
386
- const languageMap = {
387
- 'ts': 'TypeScript',
388
- 'js': 'JavaScript',
389
- 'tsx': 'TypeScript React',
390
- 'jsx': 'JavaScript React',
391
- 'py': 'Python',
392
- 'java': 'Java',
393
- 'go': 'Go',
394
- 'rs': 'Rust',
395
- 'rb': 'Ruby',
396
- 'php': 'PHP',
397
- 'vue': 'Vue',
398
- 'svelte': 'Svelte',
399
- 'html': 'HTML',
400
- 'css': 'CSS',
401
- 'json': 'JSON',
402
- 'yaml': 'YAML',
403
- 'yml': 'YAML',
404
- 'md': 'Markdown',
405
- 'sh': 'Bash',
406
- 'bash': 'Bash',
407
- };
408
- const language = languageMap[ext] || 'code';
409
- const prompt = `You are a code generator. Create a NEW ${language} file from scratch.
410
-
411
- CRITICAL RULES:
412
- 1. Return ONLY the complete file content - no explanations, no markdown, no code blocks
413
- 2. Follow ${language} best practices and conventions
414
- 3. Include proper imports, exports, and structure
415
- 4. Add appropriate comments for clarity
416
- 5. Ensure the code is production-ready and well-structured
417
-
418
- FILE PATH: ${filepath}
419
- FILE TYPE: ${language}${requirementsText}
420
-
421
- INSTRUCTION: ${instruction}
422
-
423
- Return the COMPLETE file content (entire file, ready to save):`;
424
- // Phase 4F: Use operation-aware provider resolution (chat operation)
425
- const operationProvider = this.getProviderForOperation('chat');
426
- const response = await operationProvider.chat(prompt, {
427
- temperature: 0.35,
428
- });
429
- let content = response.text || '';
430
- // Clean up common markdown formatting
431
- content = content.replace(/^```[\w]*\n?/gm, '');
432
- content = content.replace(/^```$/gm, '');
433
- content = content.trim();
434
- return content;
435
- }
436
- async generateReflection(trajectory, reward, errors) {
437
- const prompt = `You are a self-reflection model. Analyze the following failed trajectory:
438
-
439
- Trajectory:
440
- ${JSON.stringify(trajectory, null, 2)}
441
-
442
- Reward: ${reward}
443
- Errors: ${errors.join('; ')}
444
-
445
- Generate a reflective text that:
446
- 1. Identifies the root cause of failure
447
- 2. Explains what went wrong
448
- 3. Suggests specific improvements for the next attempt
449
- 4. Extracts lessons learned
450
-
451
- Reflection:`;
452
- // Phase 4F: Use operation-aware provider resolution (chat operation)
453
- const operationProvider = this.getProviderForOperation('chat');
454
- const response = await operationProvider.chat(prompt, {
455
- temperature: 0.5,
456
- });
457
- return response.text || '';
458
- }
459
- async rerank(query, documents, topN = 10) {
460
- if (documents.length === 0) {
461
- return [];
462
- }
463
- // Phase 4F: Use operation-aware provider resolution
464
- const operationProvider = this.getProviderForOperation('rerank');
465
- if (!operationProvider.capabilities.rerank || !operationProvider.rerank) {
466
- // Fallback: Return original order if rerank not supported
467
- return documents.slice(0, topN).map((_, i) => ({ index: i, relevanceScore: 1.0 }));
468
- }
469
- const topNAdjusted = Math.min(topN, documents.length);
470
- const response = await operationProvider.rerank(query, documents, { topN: topNAdjusted });
471
- return response.results.map(result => ({
472
- index: result.index,
473
- relevanceScore: result.relevanceScore,
474
- }));
475
- }
476
- }
477
- //# sourceMappingURL=provider-ai-service.js.map
@@ -1,175 +0,0 @@
1
- /**
2
- * Infrastructure: Embedding Cache
3
- * Caches embeddings to avoid redundant API calls
4
- *
5
- * Performance optimization: Reduces API calls by ~30-50% for repeated queries
6
- */
7
- import { createHash } from 'crypto';
8
- export class EmbeddingCache {
9
- cache = new Map();
10
- maxSize;
11
- ttl; // Time to live in milliseconds
12
- constructor(maxSize = 1000, ttl = 3600000) {
13
- this.maxSize = maxSize;
14
- this.ttl = ttl;
15
- }
16
- /**
17
- * Generate cache key from query
18
- */
19
- getCacheKey(query) {
20
- // Normalize query (trim, lowercase) for better cache hits
21
- const normalized = query.trim().toLowerCase();
22
- return createHash('sha256').update(normalized).digest('hex');
23
- }
24
- /**
25
- * Get cached embedding if available and not expired
26
- * OPTIMIZATION: Also checks for similar queries with fuzzy matching
27
- */
28
- get(query, enableFuzzyMatch = true) {
29
- const key = this.getCacheKey(query);
30
- let cached = this.cache.get(key);
31
- // Direct cache hit
32
- if (cached) {
33
- const now = Date.now();
34
- if (now - cached.timestamp > this.ttl) {
35
- this.cache.delete(key);
36
- }
37
- else {
38
- return cached.embedding;
39
- }
40
- }
41
- // Fuzzy matching for similar queries
42
- // OPTIMIZATION: Use lower threshold (80%) for more aggressive caching
43
- // This helps with query variations like "what is main" vs "what is the main function"
44
- if (enableFuzzyMatch && this.cache.size > 0) {
45
- const normalizedQuery = query.trim().toLowerCase();
46
- // Try with standard threshold first (85%), then lower threshold (80%) for more aggressive matching
47
- let bestMatch = this.findSimilarQuery(normalizedQuery, 0.85);
48
- if (!bestMatch) {
49
- bestMatch = this.findSimilarQuery(normalizedQuery, 0.80);
50
- }
51
- if (bestMatch && bestMatch.embedding) {
52
- // Found similar query - reuse its embedding
53
- return bestMatch.embedding;
54
- }
55
- }
56
- return null;
57
- }
58
- /**
59
- * Find similar query using Levenshtein distance
60
- * Returns cached embedding if similarity >= threshold
61
- */
62
- findSimilarQuery(query, threshold = 0.85) {
63
- let bestMatch = null;
64
- const now = Date.now();
65
- for (const [key, cached] of this.cache.entries()) {
66
- // Skip expired entries
67
- if (now - cached.timestamp > this.ttl) {
68
- continue;
69
- }
70
- const normalizedCached = cached.query.trim().toLowerCase();
71
- const similarity = this.calculateSimilarity(query, normalizedCached);
72
- if (similarity >= threshold) {
73
- if (!bestMatch || similarity > bestMatch.similarity) {
74
- bestMatch = { cached, similarity };
75
- }
76
- }
77
- }
78
- return bestMatch ? bestMatch.cached : null;
79
- }
80
- /**
81
- * Calculate string similarity using word overlap with stop word filtering
82
- * Returns value between 0.0 (no similarity) and 1.0 (identical)
83
- * OPTIMIZATION: Filters common stop words to focus on meaningful content
84
- */
85
- calculateSimilarity(str1, str2) {
86
- if (str1 === str2)
87
- return 1.0;
88
- if (str1.length === 0 || str2.length === 0)
89
- return 0.0;
90
- // Common stop words to ignore for better matching
91
- const stopWords = new Set(['the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'should', 'could', 'may', 'might', 'must', 'can', 'this', 'that', 'these', 'those', 'what', 'which', 'who', 'where', 'when', 'why', 'how', 'to', 'of', 'in', 'on', 'at', 'by', 'for', 'with', 'from', 'as', 'about', 'into', 'through', 'during', 'including', 'against', 'among', 'throughout', 'despite', 'towards', 'upon', 'concerning', 'to', 'of', 'in', 'on', 'at', 'by', 'for', 'with', 'from']);
92
- // Filter out stop words and short words for better matching
93
- const filterWords = (text) => {
94
- return text.split(/\s+/)
95
- .filter(w => w.length > 2 && !stopWords.has(w.toLowerCase()))
96
- .map(w => w.toLowerCase().replace(/[^\w]/g, '')); // Normalize
97
- };
98
- const words1 = new Set(filterWords(str1));
99
- const words2 = new Set(filterWords(str2));
100
- if (words1.size === 0 || words2.size === 0)
101
- return 0.0;
102
- // Calculate Jaccard similarity (word overlap)
103
- let intersection = 0;
104
- for (const word of words1) {
105
- if (words2.has(word)) {
106
- intersection++;
107
- }
108
- }
109
- const union = words1.size + words2.size - intersection;
110
- return union > 0 ? intersection / union : 0.0;
111
- }
112
- /**
113
- * Store embedding in cache
114
- */
115
- set(query, embedding) {
116
- const key = this.getCacheKey(query);
117
- // Evict oldest entries if cache is full
118
- if (this.cache.size >= this.maxSize) {
119
- this.evictOldest();
120
- }
121
- this.cache.set(key, {
122
- embedding,
123
- timestamp: Date.now(),
124
- query: query.trim(),
125
- });
126
- }
127
- /**
128
- * Evict oldest entries (LRU eviction)
129
- */
130
- evictOldest() {
131
- // Remove 10% of oldest entries
132
- const entriesToRemove = Math.ceil(this.maxSize * 0.1);
133
- const entries = Array.from(this.cache.entries())
134
- .sort((a, b) => a[1].timestamp - b[1].timestamp)
135
- .slice(0, entriesToRemove);
136
- for (const [key] of entries) {
137
- this.cache.delete(key);
138
- }
139
- }
140
- /**
141
- * Clear expired entries
142
- */
143
- clearExpired() {
144
- const now = Date.now();
145
- for (const [key, value] of this.cache.entries()) {
146
- if (now - value.timestamp > this.ttl) {
147
- this.cache.delete(key);
148
- }
149
- }
150
- }
151
- /**
152
- * Clear all cache
153
- */
154
- clear() {
155
- this.cache.clear();
156
- }
157
- /**
158
- * Get cache statistics
159
- */
160
- getStats() {
161
- return {
162
- size: this.cache.size,
163
- maxSize: this.maxSize,
164
- };
165
- }
166
- }
167
- // Singleton instance
168
- let embeddingCacheInstance = null;
169
- export function getEmbeddingCache() {
170
- if (!embeddingCacheInstance) {
171
- embeddingCacheInstance = new EmbeddingCache();
172
- }
173
- return embeddingCacheInstance;
174
- }
175
- //# sourceMappingURL=embedding-cache.js.map