codehere 0.2.1 → 0.3.0-rc.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 (235) 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 +253 -1219
  5. package/dist/infrastructure/config/product-context.js +7 -6
  6. package/dist/infrastructure/hooks/claude-sdk-hook.js +335 -63
  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/generic-cli-adapter.js +553 -0
  16. package/dist/infrastructure/orchestration/opencode-adapter.js +275 -0
  17. package/dist/infrastructure/orchestration/progress-aggregator.js +189 -0
  18. package/dist/infrastructure/orchestration/readiness.js +106 -0
  19. package/dist/infrastructure/orchestration/session-manager.js +272 -0
  20. package/dist/infrastructure/orchestration/session-persistence.js +109 -0
  21. package/dist/infrastructure/protocols/mcp-helpers.js +10 -30
  22. package/dist/infrastructure/protocols/mcp-server-impl.js +359 -21
  23. package/dist/infrastructure/protocols/ui-page.js +1827 -0
  24. package/dist/infrastructure/security/file-collection.js +115 -0
  25. package/dist/infrastructure/security/trust-scorer.js +301 -56
  26. package/dist/infrastructure/storage/task-repository.js +8 -7
  27. package/dist/monitoring.js +10 -49
  28. package/dist/presentation/cli/commands/help-command.js +96 -139
  29. package/dist/presentation/cli/commands/hook-command.js +17 -24
  30. package/dist/presentation/cli/commands/report-command.js +59 -72
  31. package/dist/presentation/cli/commands/setup-command.js +4 -4
  32. package/dist/presentation/cli/commands/status-command.js +334 -43
  33. package/dist/presentation/cli/commands/trust-command.js +115 -99
  34. package/dist/presentation/cli/error-display.js +17 -21
  35. package/dist/ui.js +17 -12
  36. package/package.json +35 -67
  37. package/dist/agents/base.js +0 -101
  38. package/dist/agents/orchestrator-model-driven.js +0 -141
  39. package/dist/agents/react-orchestrator-agent.js +0 -54
  40. package/dist/application/agents/execution-agent.js +0 -508
  41. package/dist/application/agents/multi-agent-orchestrator.js +0 -295
  42. package/dist/application/agents/planning-agent.js +0 -433
  43. package/dist/application/agents/validation-agent.js +0 -317
  44. package/dist/application/architectures/plan-and-act.js +0 -242
  45. package/dist/application/index.js +0 -12
  46. package/dist/application/services/agent-factory.js +0 -28
  47. package/dist/application/services/dependency-container.js +0 -596
  48. package/dist/application/services/git-context-service.js +0 -83
  49. package/dist/application/services/intelligent-router.js +0 -934
  50. package/dist/application/services/tool-executor-service.js +0 -94
  51. package/dist/application/use-cases/ask-question-use-case.js +0 -338
  52. package/dist/application/use-cases/edit-file-use-case.js +0 -830
  53. package/dist/application/use-cases/explain-file-use-case.js +0 -50
  54. package/dist/application/use-cases/index-codebase-use-case.js +0 -113
  55. package/dist/application/use-cases/planning-use-case.js +0 -276
  56. package/dist/application/use-cases/react-orchestration-use-case.js +0 -329
  57. package/dist/application/use-cases/reflexion-use-case.js +0 -30
  58. package/dist/application/workflows/deterministic-workflows.js +0 -189
  59. package/dist/ast-parser.js +0 -331
  60. package/dist/cache.js +0 -180
  61. package/dist/chat.js +0 -251
  62. package/dist/code-analysis.js +0 -327
  63. package/dist/context.js +0 -187
  64. package/dist/docs.js +0 -146
  65. package/dist/domain/entities/code-chunk.js +0 -6
  66. package/dist/domain/entities/decision.js +0 -9
  67. package/dist/domain/entities/edit.js +0 -6
  68. package/dist/domain/entities/knowledge-node.js +0 -9
  69. package/dist/domain/entities/knowledge-preservation.js +0 -10
  70. package/dist/domain/entities/memory.js +0 -6
  71. package/dist/domain/entities/pattern.js +0 -7
  72. package/dist/domain/entities/plan.js +0 -6
  73. package/dist/domain/entities/query.js +0 -6
  74. package/dist/domain/errors/embeddings-not-found-error.js +0 -13
  75. package/dist/domain/index.js +0 -19
  76. package/dist/domain/interfaces/ai-service.interface.js +0 -6
  77. package/dist/domain/interfaces/code-analyzer.interface.js +0 -6
  78. package/dist/domain/interfaces/decision-repository.interface.js +0 -9
  79. package/dist/domain/interfaces/embedding-repository.interface.js +0 -6
  80. package/dist/domain/interfaces/knowledge-graph-repository.interface.js +0 -9
  81. package/dist/domain/interfaces/knowledge-preservation-repository.interface.js +0 -8
  82. package/dist/domain/interfaces/memory-repository.interface.js +0 -6
  83. package/dist/domain/interfaces/pattern-repository.interface.js +0 -6
  84. package/dist/domain/interfaces/verification-service.interface.js +0 -6
  85. package/dist/domain/services/cross-team-pattern-sharing.js +0 -125
  86. package/dist/domain/services/decision-recorder.js +0 -223
  87. package/dist/domain/services/decision-retriever.js +0 -133
  88. package/dist/domain/services/environment-mode-manager.js +0 -22
  89. package/dist/domain/services/graded-memory-activation.js +0 -69
  90. package/dist/domain/services/knowledge-access.js +0 -132
  91. package/dist/domain/services/knowledge-extractor.js +0 -247
  92. package/dist/domain/services/knowledge-graph-builder.js +0 -268
  93. package/dist/domain/services/knowledge-graph-query.js +0 -187
  94. package/dist/domain/services/memory-retriever.js +0 -82
  95. package/dist/domain/services/memory-synthesizer.js +0 -91
  96. package/dist/domain/services/pattern-extractor.js +0 -442
  97. package/dist/domain/services/query-intent-classifier.js +0 -140
  98. package/dist/domain/services/react-loop.js +0 -186
  99. package/dist/domain/services/risk-tier-detector.js +0 -78
  100. package/dist/edit.js +0 -319
  101. package/dist/embed.js +0 -459
  102. package/dist/formatter.js +0 -168
  103. package/dist/git.js +0 -198
  104. package/dist/infrastructure/ai/cohere-ai-service.js +0 -607
  105. package/dist/infrastructure/ai/command-r-evaluation.js +0 -206
  106. package/dist/infrastructure/ai/model-config.js +0 -84
  107. package/dist/infrastructure/ai/provider-ai-service.js +0 -477
  108. package/dist/infrastructure/cache/embedding-cache.js +0 -175
  109. package/dist/infrastructure/cache/query-result-cache.js +0 -66
  110. package/dist/infrastructure/cache/response-cache.js +0 -48
  111. package/dist/infrastructure/cache/security-scan-cache.js +0 -47
  112. package/dist/infrastructure/chunking/ast-code-chunker.js +0 -19
  113. package/dist/infrastructure/chunking/code-aware-chunker.js +0 -397
  114. package/dist/infrastructure/context/context-compressor.js +0 -329
  115. package/dist/infrastructure/context/conversation-context.js +0 -128
  116. package/dist/infrastructure/context/session-manager.js +0 -94
  117. package/dist/infrastructure/cost/cost-tracker.js +0 -360
  118. package/dist/infrastructure/file-scanner/file-scanner.js +0 -106
  119. package/dist/infrastructure/governance/nist-ai-rmf.js +0 -292
  120. package/dist/infrastructure/governance/policy-as-code.js +0 -258
  121. package/dist/infrastructure/governance/prompt-to-code-lineage.js +0 -239
  122. package/dist/infrastructure/index.js +0 -7
  123. package/dist/infrastructure/observability/prompt-versioner.js +0 -145
  124. package/dist/infrastructure/protocols/a2a-metadata.js +0 -137
  125. package/dist/infrastructure/protocols/a2a-protocol.js +0 -314
  126. package/dist/infrastructure/protocols/mcp-oauth.js +0 -184
  127. package/dist/infrastructure/protocols/mcp-server.js +0 -333
  128. package/dist/infrastructure/protocols/streaming-handler.js +0 -103
  129. package/dist/infrastructure/providers/cohere-provider.js +0 -444
  130. package/dist/infrastructure/providers/fake-provider.js +0 -130
  131. package/dist/infrastructure/providers/local-llm-provider.js +0 -330
  132. package/dist/infrastructure/providers/model-config.types.js +0 -9
  133. package/dist/infrastructure/providers/model-provider.interface.js +0 -8
  134. package/dist/infrastructure/providers/openai-provider.js +0 -413
  135. package/dist/infrastructure/providers/openrouter-provider.js +0 -399
  136. package/dist/infrastructure/providers/operation-provider-resolver.js +0 -105
  137. package/dist/infrastructure/providers/provider-config-loader.js +0 -120
  138. package/dist/infrastructure/providers/provider-registry.js +0 -88
  139. package/dist/infrastructure/safety/pattern-detector.js +0 -133
  140. package/dist/infrastructure/security/ai-sast-scanner.js +0 -290
  141. package/dist/infrastructure/security/docker-sandbox.js +0 -178
  142. package/dist/infrastructure/security/enhanced-security-gate.js +0 -151
  143. package/dist/infrastructure/security/license-scanner.js +0 -167
  144. package/dist/infrastructure/security/provider-bias-detector.js +0 -164
  145. package/dist/infrastructure/security/sandbox-executor.js +0 -64
  146. package/dist/infrastructure/serialization/toon-serializer.js +0 -119
  147. package/dist/infrastructure/storage/memory-stream-service.js +0 -204
  148. package/dist/infrastructure/storage/plan-repository.js +0 -96
  149. package/dist/infrastructure/storage/sqlite-decision-repository.js +0 -232
  150. package/dist/infrastructure/storage/sqlite-embedding-repository.js +0 -311
  151. package/dist/infrastructure/storage/sqlite-knowledge-graph-repository.js +0 -417
  152. package/dist/infrastructure/storage/sqlite-knowledge-preservation-repository.js +0 -230
  153. package/dist/infrastructure/storage/sqlite-memory-repository.js +0 -229
  154. package/dist/infrastructure/storage/sqlite-pattern-repository.js +0 -249
  155. package/dist/infrastructure/storage/task-helpers.js +0 -197
  156. package/dist/infrastructure/telemetry/telemetry-service.js +0 -167
  157. package/dist/infrastructure/ux/appropriate-friction.js +0 -213
  158. package/dist/infrastructure/ux/bi-directional-learning.js +0 -337
  159. package/dist/infrastructure/ux/capability-boundaries.js +0 -42
  160. package/dist/infrastructure/ux/comprehensive-formatter.js +0 -117
  161. package/dist/infrastructure/ux/contextual-feature-discovery.js +0 -10
  162. package/dist/infrastructure/ux/expectation-management.js +0 -327
  163. package/dist/infrastructure/ux/feature-discovery.js +0 -14
  164. package/dist/infrastructure/ux/feedback-prompt.js +0 -45
  165. package/dist/infrastructure/ux/hitl-validation.js +0 -297
  166. package/dist/infrastructure/ux/progress-indicator.js +0 -116
  167. package/dist/infrastructure/ux/progressive-disclosure.js +0 -236
  168. package/dist/infrastructure/ux/review-checkpoint.js +0 -72
  169. package/dist/infrastructure/ux/staged-feature-intro.js +0 -24
  170. package/dist/infrastructure/ux/stream-markdown.js +0 -151
  171. package/dist/infrastructure/ux/syntax-highlighter.js +0 -91
  172. package/dist/infrastructure/ux/team-standards.js +0 -196
  173. package/dist/infrastructure/ux/transparency.js +0 -71
  174. package/dist/infrastructure/validation/agent-feedback.js +0 -55
  175. package/dist/infrastructure/validation/agent-validation-helper.js +0 -137
  176. package/dist/infrastructure/validation/review-handler.js +0 -40
  177. package/dist/infrastructure/validation/summary-aggregator.js +0 -70
  178. package/dist/infrastructure/validation/summary-extractor.js +0 -45
  179. package/dist/infrastructure/validation/trace-summary.js +0 -52
  180. package/dist/infrastructure/verification/verification-service.js +0 -47
  181. package/dist/infrastructure/xai/attention-visualizer.js +0 -172
  182. package/dist/infrastructure/xai/cot-visualizer.js +0 -283
  183. package/dist/infrastructure/xai/decision-tree-log.js +0 -212
  184. package/dist/infrastructure/xai/interactive-xai.js +0 -260
  185. package/dist/infrastructure/xai/uncertainty-quantifier.js +0 -198
  186. package/dist/intelligent-retrieval.js +0 -272
  187. package/dist/intent/classifier.js +0 -2
  188. package/dist/intent/context.js +0 -2
  189. package/dist/iterative-refinement.js +0 -189
  190. package/dist/learning.js +0 -232
  191. package/dist/log.js +0 -31
  192. package/dist/migrate.js +0 -133
  193. package/dist/parallel-processor.js +0 -530
  194. package/dist/planner.js +0 -198
  195. package/dist/policy.js +0 -26
  196. package/dist/presentation/cli/commands/ask-command.js +0 -314
  197. package/dist/presentation/cli/commands/cost-command.js +0 -191
  198. package/dist/presentation/cli/commands/decision-command.js +0 -207
  199. package/dist/presentation/cli/commands/docs-command.js +0 -25
  200. package/dist/presentation/cli/commands/fix-command.js +0 -53
  201. package/dist/presentation/cli/commands/knowledge-command.js +0 -129
  202. package/dist/presentation/cli/commands/learning-dashboard-command.js +0 -183
  203. package/dist/presentation/cli/commands/models-command.js +0 -194
  204. package/dist/presentation/cli/commands/orchestrate-command.js +0 -207
  205. package/dist/presentation/cli/commands/plan-command.js +0 -246
  206. package/dist/presentation/cli/commands/product-command.js +0 -199
  207. package/dist/presentation/cli/commands/react-command.js +0 -181
  208. package/dist/presentation/cli/commands/review-command.js +0 -154
  209. package/dist/presentation/cli/commands/run-command.js +0 -188
  210. package/dist/presentation/cli/commands/smart-command.js +0 -395
  211. package/dist/presentation/cli/commands/suggest-command.js +0 -138
  212. package/dist/presentation/cli/commands/trace-command.js +0 -129
  213. package/dist/presentation/cli/commands/undo-command.js +0 -150
  214. package/dist/query-optimizer.js +0 -205
  215. package/dist/refactor.js +0 -116
  216. package/dist/review.js +0 -206
  217. package/dist/search.js +0 -163
  218. package/dist/session.js +0 -652
  219. package/dist/task-verification.js +0 -336
  220. package/dist/testgen.js +0 -166
  221. package/dist/token-optimizer.js +0 -277
  222. package/dist/tools/bash.js +0 -213
  223. package/dist/tools/edit.js +0 -235
  224. package/dist/tools/executor.js +0 -153
  225. package/dist/tools/git-tool.js +0 -292
  226. package/dist/tools/parser.js +0 -158
  227. package/dist/tools/registry.js +0 -302
  228. package/dist/tools/search.js +0 -100
  229. package/dist/types.js +0 -2
  230. package/dist/utils/check-api-status.js +0 -100
  231. package/dist/utils/diff-parser.js +0 -162
  232. package/dist/verification/backup.js +0 -259
  233. package/dist/verification/compiler.js +0 -264
  234. package/dist/verification/index.js +0 -273
  235. package/dist/verification/test-runner.js +0 -379
@@ -1,399 +0,0 @@
1
- /**
2
- * Provider Layer: OpenRouterProvider
3
- * Implements IModelProvider for OpenRouter API
4
- *
5
- * Phase 4D: OpenRouter Provider Implementation
6
- *
7
- * OpenRouter provides unified access to 400+ AI models through a single API.
8
- * Supports GPT-4, Claude, Llama, Mistral, and many more models.
9
- *
10
- * Uses OpenRouter REST API directly (no SDK dependency) to keep dependencies minimal.
11
- */
12
- import { config } from 'dotenv';
13
- import { join, dirname } from 'path';
14
- import { fileURLToPath } from 'url';
15
- import { encoding_for_model } from 'tiktoken';
16
- import { retryWithBackoff } from '../../error-handler.js';
17
- // Load .env (same pattern as other providers)
18
- try {
19
- const __filename = fileURLToPath(import.meta.url);
20
- const __dirname = dirname(__filename);
21
- const agentDir = join(__dirname, '../../../..');
22
- config({ path: join(agentDir, '.env') });
23
- }
24
- catch { }
25
- config();
26
- // Token counting (using tiktoken - OpenAI's tokenizer, works for most models)
27
- let tokenEncoder = null;
28
- function getTokenEncoder() {
29
- if (!tokenEncoder) {
30
- try {
31
- tokenEncoder = encoding_for_model('gpt-3.5-turbo');
32
- }
33
- catch {
34
- tokenEncoder = encoding_for_model('gpt-4');
35
- }
36
- }
37
- return tokenEncoder;
38
- }
39
- function countTokens(text) {
40
- try {
41
- const encoder = getTokenEncoder();
42
- return encoder.encode(text).length;
43
- }
44
- catch (error) {
45
- console.warn('Warning: tiktoken failed, using character-based estimate (less accurate)');
46
- return Math.ceil(text.length / 4);
47
- }
48
- }
49
- /**
50
- * OpenRouter Provider
51
- * Implements IModelProvider using OpenRouter REST API
52
- */
53
- export class OpenRouterProvider {
54
- id = 'openrouter';
55
- name = 'OpenRouter';
56
- capabilities = {
57
- chat: true,
58
- streaming: true,
59
- embedding: false, // OpenRouter routes to model-specific endpoints (TBD)
60
- embeddingQuery: false,
61
- rerank: false, // OpenRouter doesn't have unified rerank API
62
- toolCalling: true, // Many models support tool calling
63
- };
64
- apiKey;
65
- baseUrl;
66
- defaultChatModel;
67
- constructor(apiKey) {
68
- const key = apiKey || process.env.OPENROUTER_API_KEY;
69
- if (!key) {
70
- throw new Error('OPENROUTER_API_KEY not found in environment');
71
- }
72
- this.apiKey = key;
73
- this.baseUrl = process.env.OPENROUTER_BASE_URL || 'https://openrouter.ai/api/v1';
74
- this.defaultChatModel = process.env.CODEHERE_OPENROUTER_CHAT_MODEL || 'openai/gpt-4o-mini';
75
- }
76
- async getModels() {
77
- // Fetch models from OpenRouter API
78
- try {
79
- const response = await fetch(`${this.baseUrl}/models`, {
80
- method: 'GET',
81
- headers: {
82
- 'Authorization': `Bearer ${this.apiKey}`,
83
- 'HTTP-Referer': 'https://github.com/muhammadegaa/codehere', // Optional: for analytics
84
- },
85
- });
86
- if (!response.ok) {
87
- // Fallback to known models if API call fails
88
- return this.getDefaultModels();
89
- }
90
- const data = await response.json();
91
- const models = data.data || [];
92
- // Transform OpenRouter model format to ModelInfo
93
- return models
94
- .filter((model) => model.id && model.name)
95
- .map((model) => ({
96
- id: model.id,
97
- name: model.name || model.id,
98
- providerId: 'openrouter',
99
- providerModelId: model.id,
100
- contextWindow: model.context_length || 8192,
101
- capabilities: {
102
- chat: model.top_provider?.supports_chat !== false,
103
- streaming: true,
104
- embedding: false, // OpenRouter embeddings TBD
105
- embeddingQuery: false,
106
- rerank: false,
107
- toolCalling: model.top_provider?.supports_function_calling === true,
108
- },
109
- }))
110
- .slice(0, 100); // Limit to top 100 models
111
- }
112
- catch (error) {
113
- // Fallback to known models on error
114
- console.warn('[OpenRouterProvider] Failed to fetch models, using defaults:', error instanceof Error ? error.message : String(error));
115
- return this.getDefaultModels();
116
- }
117
- }
118
- /**
119
- * Get default models (fallback if API call fails)
120
- */
121
- getDefaultModels() {
122
- return [
123
- {
124
- id: 'openai/gpt-4o',
125
- name: 'GPT-4o (via OpenRouter)',
126
- providerId: 'openrouter',
127
- providerModelId: 'openai/gpt-4o',
128
- contextWindow: 128000,
129
- capabilities: {
130
- chat: true,
131
- streaming: true,
132
- embedding: false,
133
- embeddingQuery: false,
134
- rerank: false,
135
- toolCalling: true,
136
- },
137
- },
138
- {
139
- id: 'openai/gpt-4o-mini',
140
- name: 'GPT-4o Mini (via OpenRouter)',
141
- providerId: 'openrouter',
142
- providerModelId: 'openai/gpt-4o-mini',
143
- contextWindow: 128000,
144
- capabilities: {
145
- chat: true,
146
- streaming: true,
147
- embedding: false,
148
- embeddingQuery: false,
149
- rerank: false,
150
- toolCalling: true,
151
- },
152
- },
153
- {
154
- id: 'anthropic/claude-3.5-sonnet',
155
- name: 'Claude 3.5 Sonnet (via OpenRouter)',
156
- providerId: 'openrouter',
157
- providerModelId: 'anthropic/claude-3.5-sonnet',
158
- contextWindow: 200000,
159
- capabilities: {
160
- chat: true,
161
- streaming: true,
162
- embedding: false,
163
- embeddingQuery: false,
164
- rerank: false,
165
- toolCalling: true,
166
- },
167
- },
168
- {
169
- id: 'meta-llama/llama-3.1-70b-instruct',
170
- name: 'Llama 3.1 70B (via OpenRouter)',
171
- providerId: 'openrouter',
172
- providerModelId: 'meta-llama/llama-3.1-70b-instruct',
173
- contextWindow: 131072,
174
- capabilities: {
175
- chat: true,
176
- streaming: true,
177
- embedding: false,
178
- embeddingQuery: false,
179
- rerank: false,
180
- toolCalling: false,
181
- },
182
- },
183
- ];
184
- }
185
- getDefaultModel() {
186
- return this.defaultChatModel;
187
- }
188
- async chat(prompt, options) {
189
- const model = options?.model || this.defaultChatModel;
190
- return await retryWithBackoff(async () => {
191
- const response = await fetch(`${this.baseUrl}/chat/completions`, {
192
- method: 'POST',
193
- headers: {
194
- 'Content-Type': 'application/json',
195
- 'Authorization': `Bearer ${this.apiKey}`,
196
- 'HTTP-Referer': 'https://github.com/muhammadegaa/codehere', // Optional: for analytics
197
- 'X-Title': 'Codehere CLI', // Optional: for analytics
198
- },
199
- body: JSON.stringify({
200
- model,
201
- messages: [
202
- {
203
- role: 'user',
204
- content: prompt,
205
- },
206
- ],
207
- temperature: options?.temperature ?? 0.7,
208
- max_tokens: options?.maxTokens,
209
- }),
210
- });
211
- if (!response.ok) {
212
- const errorText = await response.text();
213
- let errorMessage = `OpenRouter API error: ${response.status} ${response.statusText}`;
214
- try {
215
- const errorJson = JSON.parse(errorText);
216
- errorMessage = errorJson.error?.message || errorMessage;
217
- }
218
- catch {
219
- errorMessage = errorText || errorMessage;
220
- }
221
- throw new Error(errorMessage);
222
- }
223
- const data = await response.json();
224
- const text = data.choices?.[0]?.message?.content || 'No response generated';
225
- const usage = data.usage || {};
226
- return {
227
- text,
228
- model: data.model || model,
229
- usage: {
230
- inputTokens: usage.prompt_tokens || countTokens(prompt),
231
- outputTokens: usage.completion_tokens || countTokens(text),
232
- },
233
- finishReason: data.choices?.[0]?.finish_reason,
234
- };
235
- }, {
236
- maxRetries: 5,
237
- baseDelay: 2000,
238
- maxDelay: 60000,
239
- operationName: 'openrouter-provider-chat',
240
- });
241
- }
242
- async chatStream(prompt, options, onEvent) {
243
- const model = options?.model || this.defaultChatModel;
244
- let fullText = '';
245
- try {
246
- if (onEvent) {
247
- onEvent({ type: 'start' });
248
- }
249
- const response = await fetch(`${this.baseUrl}/chat/completions`, {
250
- method: 'POST',
251
- headers: {
252
- 'Content-Type': 'application/json',
253
- 'Authorization': `Bearer ${this.apiKey}`,
254
- 'HTTP-Referer': 'https://github.com/muhammadegaa/codehere',
255
- 'X-Title': 'Codehere CLI',
256
- },
257
- body: JSON.stringify({
258
- model,
259
- messages: [
260
- {
261
- role: 'user',
262
- content: prompt,
263
- },
264
- ],
265
- temperature: options?.temperature ?? 0.7,
266
- max_tokens: options?.maxTokens,
267
- stream: true,
268
- }),
269
- });
270
- if (!response.ok) {
271
- const errorText = await response.text();
272
- throw new Error(`OpenRouter API error: ${response.status} ${errorText}`);
273
- }
274
- if (!response.body) {
275
- throw new Error('No response body for streaming');
276
- }
277
- const reader = response.body.getReader();
278
- const decoder = new TextDecoder();
279
- while (true) {
280
- const { done, value } = await reader.read();
281
- if (done)
282
- break;
283
- const chunk = decoder.decode(value, { stream: true });
284
- const lines = chunk.split('\n').filter(line => line.trim() !== '');
285
- for (const line of lines) {
286
- if (line.startsWith('data: ')) {
287
- const data = line.slice(6);
288
- if (data === '[DONE]') {
289
- if (onEvent) {
290
- onEvent({ type: 'complete', text: fullText });
291
- }
292
- break;
293
- }
294
- try {
295
- const json = JSON.parse(data);
296
- const delta = json.choices?.[0]?.delta?.content;
297
- if (delta) {
298
- fullText += delta;
299
- if (onEvent) {
300
- onEvent({ type: 'delta', text: delta });
301
- }
302
- }
303
- }
304
- catch (e) {
305
- // Skip invalid JSON chunks
306
- }
307
- }
308
- }
309
- }
310
- if (onEvent && !fullText) {
311
- onEvent({ type: 'complete', text: fullText });
312
- }
313
- const inputTokens = countTokens(prompt);
314
- const outputTokens = countTokens(fullText);
315
- return {
316
- text: fullText,
317
- model: model || 'default',
318
- usage: {
319
- inputTokens,
320
- outputTokens,
321
- },
322
- };
323
- }
324
- catch (error) {
325
- if (onEvent) {
326
- onEvent({
327
- type: 'error',
328
- error: error instanceof Error ? error : new Error(String(error)),
329
- });
330
- }
331
- throw error;
332
- }
333
- }
334
- async embed(_text) {
335
- // OpenRouter embeddings support TBD - will route to model-specific endpoints
336
- throw new Error('Embeddings not yet supported via OpenRouter. Use direct provider (Cohere/OpenAI) for embeddings.');
337
- }
338
- async countTokens(text, _model) {
339
- return Promise.resolve(countTokens(text));
340
- }
341
- async isAvailable() {
342
- try {
343
- // Simple availability check - try a minimal API call
344
- const response = await fetch(`${this.baseUrl}/models`, {
345
- method: 'GET',
346
- headers: {
347
- 'Authorization': `Bearer ${this.apiKey}`,
348
- },
349
- });
350
- return response.ok;
351
- }
352
- catch {
353
- return false;
354
- }
355
- }
356
- handleError(error) {
357
- const errorMessage = error instanceof Error ? error.message : String(error);
358
- const lowerMessage = errorMessage.toLowerCase();
359
- // Rate limiting (429)
360
- if (errorMessage.includes('429') || lowerMessage.includes('rate limit') || lowerMessage.includes('rate_limit')) {
361
- return {
362
- type: 'rate_limit',
363
- retryable: true, // OpenRouter may have retry logic
364
- message: 'Rate limit exceeded',
365
- };
366
- }
367
- // Authentication errors (401)
368
- if (errorMessage.includes('401') || errorMessage.includes('Unauthorized') || lowerMessage.includes('no api key')) {
369
- return {
370
- type: 'auth_error',
371
- retryable: false,
372
- message: 'Authentication failed - check OPENROUTER_API_KEY',
373
- };
374
- }
375
- // Quota exceeded
376
- if (errorMessage.includes('quota') || errorMessage.includes('insufficient_quota') || lowerMessage.includes('insufficient credits')) {
377
- return {
378
- type: 'quota_exceeded',
379
- retryable: false,
380
- message: 'OpenRouter credits insufficient',
381
- };
382
- }
383
- // Network errors
384
- if (errorMessage.includes('network') || errorMessage.includes('timeout') || errorMessage.includes('ECONNREFUSED')) {
385
- return {
386
- type: 'network_error',
387
- retryable: true,
388
- message: errorMessage,
389
- };
390
- }
391
- // Default to retryable
392
- return {
393
- type: 'unknown',
394
- retryable: true,
395
- message: errorMessage,
396
- };
397
- }
398
- }
399
- //# sourceMappingURL=openrouter-provider.js.map
@@ -1,105 +0,0 @@
1
- /**
2
- * Provider Layer: Operation Provider Resolver
3
- * Resolves which provider to use for a given operation
4
- *
5
- * Phase 4F: Per-Operation Provider Selection
6
- * Internal-only routing logic (no user-facing config yet)
7
- */
8
- /**
9
- * Operation Provider Resolver
10
- * Resolves which provider to use for a given operation based on precedence rules
11
- *
12
- * Precedence (highest to lowest):
13
- * 1. CODEHERE_FAKE_AI=1 → FakeProvider always wins
14
- * 2. Config file:
15
- * - Operation-level override from config (if present)
16
- * - Config default provider (if set)
17
- * 3. Global provider env choice (CODEHERE_AI_PROVIDER)
18
- * 4. Registry default provider
19
- */
20
- export class OperationProviderResolver {
21
- operationConfig = null;
22
- configDefault = null;
23
- registry;
24
- constructor(registry, operationConfig, configDefaultProvider) {
25
- this.registry = registry;
26
- this.operationConfig = operationConfig || null;
27
- this.configDefault = configDefaultProvider || null;
28
- }
29
- /**
30
- * Resolve provider for a given operation
31
- *
32
- * @param operation - The operation type (chat, embedding, rerank)
33
- * @returns The IModelProvider to use for this operation
34
- */
35
- resolveProvider(operation) {
36
- // Precedence 1: FakeProvider always wins if CODEHERE_FAKE_AI=1
37
- if (process.env.CODEHERE_FAKE_AI === '1') {
38
- const fakeProvider = this.registry.get('fake');
39
- if (fakeProvider) {
40
- return fakeProvider;
41
- }
42
- }
43
- // Precedence 2: Operation-level override (if configured)
44
- if (this.operationConfig) {
45
- let providerId;
46
- switch (operation) {
47
- case 'chat':
48
- providerId = this.operationConfig.chat;
49
- break;
50
- case 'embedding':
51
- providerId = this.operationConfig.embedding;
52
- break;
53
- case 'rerank':
54
- providerId = this.operationConfig.rerank;
55
- break;
56
- }
57
- // If operation-specific provider is set, use it
58
- if (providerId) {
59
- const provider = this.registry.get(providerId);
60
- if (provider) {
61
- return provider;
62
- }
63
- // If operation provider is misconfigured, fall through to next precedence
64
- console.warn(`[OperationProviderResolver] Provider '${providerId}' not found for operation '${operation}', falling back to default`);
65
- }
66
- // Check for default in operation config
67
- if (this.operationConfig.default) {
68
- const provider = this.registry.get(this.operationConfig.default);
69
- if (provider) {
70
- return provider;
71
- }
72
- }
73
- }
74
- // Precedence 2b: Config default provider (if no operation override)
75
- if (this.configDefault) {
76
- const provider = this.registry.get(this.configDefault);
77
- if (provider) {
78
- return provider;
79
- }
80
- }
81
- // Precedence 3: Global provider env choice (CODEHERE_AI_PROVIDER)
82
- const requestedProvider = process.env.CODEHERE_AI_PROVIDER?.toLowerCase();
83
- if (requestedProvider) {
84
- const provider = this.registry.get(requestedProvider);
85
- if (provider) {
86
- return provider;
87
- }
88
- }
89
- // Precedence 4: Registry default provider (fallback)
90
- return this.registry.getDefault();
91
- }
92
- /**
93
- * Set operation-level configuration (for testing or future config file support)
94
- */
95
- setOperationConfig(config) {
96
- this.operationConfig = config;
97
- }
98
- /**
99
- * Get current operation configuration
100
- */
101
- getOperationConfig() {
102
- return this.operationConfig;
103
- }
104
- }
105
- //# sourceMappingURL=operation-provider-resolver.js.map
@@ -1,120 +0,0 @@
1
- /**
2
- * Provider Layer: Provider Config Loader
3
- * Loads user-facing provider configuration from JSON files
4
- *
5
- * Phase 4G: User-facing provider config files
6
- */
7
- import { existsSync, readFileSync } from 'fs';
8
- import { join, resolve } from 'path';
9
- import { findCodebaseRoot } from '../../domain/services/codebase-detector.js';
10
- /**
11
- * Load provider configuration from file
12
- *
13
- * @param options - Optional configuration
14
- * @param options.cwd - Working directory (defaults to process.cwd())
15
- * @returns ProviderConfig if file exists and is valid, undefined otherwise
16
- */
17
- export function loadProviderConfig(options) {
18
- const cwd = options?.cwd || process.cwd();
19
- // Determine config file path
20
- let configPath;
21
- // Check for explicit path override
22
- if (process.env.CODEHERE_PROVIDER_CONFIG_PATH) {
23
- configPath = resolve(process.env.CODEHERE_PROVIDER_CONFIG_PATH);
24
- }
25
- else {
26
- // Find codebase root
27
- const codebaseInfo = findCodebaseRoot(cwd);
28
- if (codebaseInfo) {
29
- // Default path: .codehere/providers.json
30
- configPath = join(codebaseInfo.rootPath, '.codehere', 'providers.json');
31
- }
32
- else {
33
- // Fallback to cwd if codebase root not found
34
- configPath = join(cwd, '.codehere', 'providers.json');
35
- }
36
- }
37
- // If file doesn't exist, return undefined (not an error)
38
- if (!configPath || !existsSync(configPath)) {
39
- return undefined;
40
- }
41
- try {
42
- // Read and parse JSON
43
- const fileContent = readFileSync(configPath, 'utf-8');
44
- const rawConfig = JSON.parse(fileContent);
45
- // Validate and normalize config
46
- return validateAndNormalizeConfig(rawConfig);
47
- }
48
- catch (error) {
49
- // Log warning but don't throw (non-fatal)
50
- const errorMessage = error instanceof Error ? error.message : String(error);
51
- console.warn(`[ProviderConfigLoader] Failed to load config from ${configPath}: ${errorMessage}`);
52
- return undefined;
53
- }
54
- }
55
- /**
56
- * Validate and normalize raw config object
57
- * Ignores unknown fields and invalid values gracefully
58
- */
59
- function validateAndNormalizeConfig(raw) {
60
- if (!raw || typeof raw !== 'object') {
61
- return undefined;
62
- }
63
- const config = {};
64
- const obj = raw;
65
- // Extract default provider
66
- if (obj.default !== undefined) {
67
- if (typeof obj.default === 'string' && obj.default.trim()) {
68
- config.default = obj.default.trim();
69
- }
70
- }
71
- // Extract operations
72
- if (obj.operations !== undefined && typeof obj.operations === 'object' && obj.operations !== null) {
73
- const operations = obj.operations;
74
- const normalizedOps = {};
75
- // Known operation types
76
- const validOperations = ['chat', 'embedding', 'rerank'];
77
- for (const op of validOperations) {
78
- if (operations[op] !== undefined) {
79
- const providerId = operations[op];
80
- if (typeof providerId === 'string' && providerId.trim()) {
81
- normalizedOps[op] = providerId.trim();
82
- }
83
- }
84
- }
85
- // Only set operations if at least one is valid
86
- if (Object.keys(normalizedOps).length > 0) {
87
- config.operations = normalizedOps;
88
- }
89
- }
90
- // Return config only if it has at least one meaningful field
91
- if (config.default || config.operations) {
92
- return config;
93
- }
94
- return undefined;
95
- }
96
- /**
97
- * Convert ProviderConfig to OperationProviderConfig
98
- * Used to pass config to OperationProviderResolver
99
- */
100
- export function configToOperationConfig(config) {
101
- const operationConfig = {};
102
- // Set default if present
103
- if (config.default) {
104
- operationConfig.default = config.default;
105
- }
106
- // Map operations
107
- if (config.operations) {
108
- if (config.operations.chat) {
109
- operationConfig.chat = config.operations.chat;
110
- }
111
- if (config.operations.embedding) {
112
- operationConfig.embedding = config.operations.embedding;
113
- }
114
- if (config.operations.rerank) {
115
- operationConfig.rerank = config.operations.rerank;
116
- }
117
- }
118
- return operationConfig;
119
- }
120
- //# sourceMappingURL=provider-config-loader.js.map