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,413 +0,0 @@
1
- /**
2
- * Provider Layer: OpenAIProvider
3
- * Implements IModelProvider for OpenAI API
4
- *
5
- * Phase 4C: OpenAI Provider Implementation
6
- *
7
- * Uses OpenAI REST API directly (no SDK dependency) to keep dependencies minimal.
8
- * Supports GPT-4, GPT-3.5, and text-embedding models.
9
- */
10
- import { config } from 'dotenv';
11
- import { join, dirname } from 'path';
12
- import { fileURLToPath } from 'url';
13
- import { encoding_for_model } from 'tiktoken';
14
- import { retryWithBackoff } from '../../error-handler.js';
15
- // Load .env (same pattern as CohereProvider)
16
- try {
17
- const __filename = fileURLToPath(import.meta.url);
18
- const __dirname = dirname(__filename);
19
- const agentDir = join(__dirname, '../../../..');
20
- config({ path: join(agentDir, '.env') });
21
- }
22
- catch { }
23
- config();
24
- // Token counting (using tiktoken - OpenAI's tokenizer)
25
- let tokenEncoder = null;
26
- function getTokenEncoder() {
27
- if (!tokenEncoder) {
28
- try {
29
- tokenEncoder = encoding_for_model('gpt-3.5-turbo');
30
- }
31
- catch {
32
- tokenEncoder = encoding_for_model('gpt-4');
33
- }
34
- }
35
- return tokenEncoder;
36
- }
37
- function countTokens(text) {
38
- try {
39
- const encoder = getTokenEncoder();
40
- return encoder.encode(text).length;
41
- }
42
- catch (error) {
43
- console.warn('Warning: tiktoken failed, using character-based estimate (less accurate)');
44
- return Math.ceil(text.length / 4);
45
- }
46
- }
47
- /**
48
- * OpenAI Provider
49
- * Implements IModelProvider using OpenAI REST API
50
- */
51
- export class OpenAIProvider {
52
- id = 'openai';
53
- name = 'OpenAI';
54
- capabilities = {
55
- chat: true,
56
- streaming: true,
57
- embedding: true,
58
- embeddingQuery: false, // OpenAI doesn't have separate query embeddings
59
- rerank: false, // OpenAI doesn't have rerank API
60
- toolCalling: true, // OpenAI supports function calling
61
- };
62
- apiKey;
63
- baseUrl;
64
- defaultChatModel;
65
- defaultEmbedModel;
66
- constructor(apiKey, baseUrl) {
67
- const key = apiKey || process.env.CODEHERE_OPENAI_API_KEY || process.env.OPENAI_API_KEY;
68
- if (!key) {
69
- throw new Error('CODEHERE_OPENAI_API_KEY or OPENAI_API_KEY not found in environment');
70
- }
71
- this.apiKey = key;
72
- this.baseUrl = baseUrl || process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1';
73
- this.defaultChatModel = process.env.CODEHERE_OPENAI_MODEL || 'gpt-4o-mini';
74
- this.defaultEmbedModel = process.env.CODEHERE_OPENAI_EMBED_MODEL || 'text-embedding-3-small';
75
- }
76
- async getModels() {
77
- // Return known OpenAI models (can be enhanced to fetch from API later)
78
- return [
79
- {
80
- id: 'gpt-4o',
81
- name: 'GPT-4o',
82
- providerId: 'openai',
83
- providerModelId: 'gpt-4o',
84
- contextWindow: 128000,
85
- capabilities: {
86
- chat: true,
87
- streaming: true,
88
- embedding: false,
89
- embeddingQuery: false,
90
- rerank: false,
91
- toolCalling: true,
92
- },
93
- },
94
- {
95
- id: 'gpt-4o-mini',
96
- name: 'GPT-4o Mini',
97
- providerId: 'openai',
98
- providerModelId: 'gpt-4o-mini',
99
- contextWindow: 128000,
100
- capabilities: {
101
- chat: true,
102
- streaming: true,
103
- embedding: false,
104
- embeddingQuery: false,
105
- rerank: false,
106
- toolCalling: true,
107
- },
108
- },
109
- {
110
- id: 'gpt-4-turbo',
111
- name: 'GPT-4 Turbo',
112
- providerId: 'openai',
113
- providerModelId: 'gpt-4-turbo',
114
- contextWindow: 128000,
115
- capabilities: {
116
- chat: true,
117
- streaming: true,
118
- embedding: false,
119
- embeddingQuery: false,
120
- rerank: false,
121
- toolCalling: true,
122
- },
123
- },
124
- {
125
- id: 'gpt-3.5-turbo',
126
- name: 'GPT-3.5 Turbo',
127
- providerId: 'openai',
128
- providerModelId: 'gpt-3.5-turbo',
129
- contextWindow: 16385,
130
- capabilities: {
131
- chat: true,
132
- streaming: true,
133
- embedding: false,
134
- embeddingQuery: false,
135
- rerank: false,
136
- toolCalling: true,
137
- },
138
- },
139
- {
140
- id: 'text-embedding-3-small',
141
- name: 'Text Embedding 3 Small',
142
- providerId: 'openai',
143
- providerModelId: 'text-embedding-3-small',
144
- contextWindow: 8191,
145
- capabilities: {
146
- chat: false,
147
- streaming: false,
148
- embedding: true,
149
- embeddingQuery: false,
150
- rerank: false,
151
- toolCalling: false,
152
- },
153
- },
154
- {
155
- id: 'text-embedding-3-large',
156
- name: 'Text Embedding 3 Large',
157
- providerId: 'openai',
158
- providerModelId: 'text-embedding-3-large',
159
- contextWindow: 8191,
160
- capabilities: {
161
- chat: false,
162
- streaming: false,
163
- embedding: true,
164
- embeddingQuery: false,
165
- rerank: false,
166
- toolCalling: false,
167
- },
168
- },
169
- ];
170
- }
171
- getDefaultModel() {
172
- return this.defaultChatModel;
173
- }
174
- async chat(prompt, options) {
175
- const model = options?.model || this.defaultChatModel;
176
- return await retryWithBackoff(async () => {
177
- const response = await fetch(`${this.baseUrl}/chat/completions`, {
178
- method: 'POST',
179
- headers: {
180
- 'Content-Type': 'application/json',
181
- 'Authorization': `Bearer ${this.apiKey}`,
182
- },
183
- body: JSON.stringify({
184
- model,
185
- messages: [
186
- {
187
- role: 'user',
188
- content: prompt,
189
- },
190
- ],
191
- temperature: options?.temperature ?? 0.7,
192
- max_tokens: options?.maxTokens,
193
- }),
194
- });
195
- if (!response.ok) {
196
- const errorText = await response.text();
197
- let errorMessage = `OpenAI API error: ${response.status} ${response.statusText}`;
198
- try {
199
- const errorJson = JSON.parse(errorText);
200
- errorMessage = errorJson.error?.message || errorMessage;
201
- }
202
- catch {
203
- errorMessage = errorText || errorMessage;
204
- }
205
- throw new Error(errorMessage);
206
- }
207
- const data = await response.json();
208
- const text = data.choices?.[0]?.message?.content || 'No response generated';
209
- const usage = data.usage || {};
210
- return {
211
- text,
212
- model: data.model || model,
213
- usage: {
214
- inputTokens: usage.prompt_tokens || countTokens(prompt),
215
- outputTokens: usage.completion_tokens || countTokens(text),
216
- },
217
- finishReason: data.choices?.[0]?.finish_reason,
218
- };
219
- }, {
220
- maxRetries: 5,
221
- baseDelay: 2000,
222
- maxDelay: 60000,
223
- operationName: 'openai-provider-chat',
224
- });
225
- }
226
- async chatStream(prompt, options, onEvent) {
227
- const model = options?.model || this.defaultChatModel;
228
- let fullText = '';
229
- try {
230
- if (onEvent) {
231
- onEvent({ type: 'start' });
232
- }
233
- const response = await fetch(`${this.baseUrl}/chat/completions`, {
234
- method: 'POST',
235
- headers: {
236
- 'Content-Type': 'application/json',
237
- 'Authorization': `Bearer ${this.apiKey}`,
238
- },
239
- body: JSON.stringify({
240
- model,
241
- messages: [
242
- {
243
- role: 'user',
244
- content: prompt,
245
- },
246
- ],
247
- temperature: options?.temperature ?? 0.7,
248
- max_tokens: options?.maxTokens,
249
- stream: true,
250
- }),
251
- });
252
- if (!response.ok) {
253
- const errorText = await response.text();
254
- throw new Error(`OpenAI API error: ${response.status} ${errorText}`);
255
- }
256
- if (!response.body) {
257
- throw new Error('No response body for streaming');
258
- }
259
- const reader = response.body.getReader();
260
- const decoder = new TextDecoder();
261
- while (true) {
262
- const { done, value } = await reader.read();
263
- if (done)
264
- break;
265
- const chunk = decoder.decode(value, { stream: true });
266
- const lines = chunk.split('\n').filter(line => line.trim() !== '');
267
- for (const line of lines) {
268
- if (line.startsWith('data: ')) {
269
- const data = line.slice(6);
270
- if (data === '[DONE]') {
271
- if (onEvent) {
272
- onEvent({ type: 'complete', text: fullText });
273
- }
274
- break;
275
- }
276
- try {
277
- const json = JSON.parse(data);
278
- const delta = json.choices?.[0]?.delta?.content;
279
- if (delta) {
280
- fullText += delta;
281
- if (onEvent) {
282
- onEvent({ type: 'delta', text: delta });
283
- }
284
- }
285
- }
286
- catch (e) {
287
- // Skip invalid JSON chunks
288
- }
289
- }
290
- }
291
- }
292
- if (onEvent && !fullText) {
293
- onEvent({ type: 'complete', text: fullText });
294
- }
295
- const inputTokens = countTokens(prompt);
296
- const outputTokens = countTokens(fullText);
297
- return {
298
- text: fullText,
299
- model: model || 'default',
300
- usage: {
301
- inputTokens,
302
- outputTokens,
303
- },
304
- };
305
- }
306
- catch (error) {
307
- if (onEvent) {
308
- onEvent({
309
- type: 'error',
310
- error: error instanceof Error ? error : new Error(String(error)),
311
- });
312
- }
313
- throw error;
314
- }
315
- }
316
- async embed(text) {
317
- const texts = Array.isArray(text) ? text : [text];
318
- return await retryWithBackoff(async () => {
319
- const response = await fetch(`${this.baseUrl}/embeddings`, {
320
- method: 'POST',
321
- headers: {
322
- 'Content-Type': 'application/json',
323
- 'Authorization': `Bearer ${this.apiKey}`,
324
- },
325
- body: JSON.stringify({
326
- model: this.defaultEmbedModel,
327
- input: texts,
328
- }),
329
- });
330
- if (!response.ok) {
331
- const errorText = await response.text();
332
- throw new Error(`OpenAI API error: ${response.status} ${errorText}`);
333
- }
334
- const data = await response.json();
335
- const embeddings = data.data?.map((item) => item.embedding) || [];
336
- if (texts.length === 1) {
337
- return embeddings[0];
338
- }
339
- return embeddings;
340
- }, {
341
- maxRetries: 5,
342
- baseDelay: 2000,
343
- maxDelay: 60000,
344
- operationName: 'openai-provider-embed',
345
- });
346
- }
347
- async embedQuery(query) {
348
- // OpenAI doesn't have separate query embeddings, use regular embed
349
- const result = await this.embed(query);
350
- return Array.isArray(result[0]) ? result[0] : result;
351
- }
352
- async countTokens(text, _model) {
353
- return Promise.resolve(countTokens(text));
354
- }
355
- async isAvailable() {
356
- try {
357
- // Simple availability check - try a minimal API call
358
- const response = await fetch(`${this.baseUrl}/models`, {
359
- method: 'GET',
360
- headers: {
361
- 'Authorization': `Bearer ${this.apiKey}`,
362
- },
363
- });
364
- return response.ok;
365
- }
366
- catch {
367
- return false;
368
- }
369
- }
370
- handleError(error) {
371
- const errorMessage = error instanceof Error ? error.message : String(error);
372
- const lowerMessage = errorMessage.toLowerCase();
373
- // Rate limiting (429)
374
- if (errorMessage.includes('429') || lowerMessage.includes('rate limit') || lowerMessage.includes('rate_limit')) {
375
- return {
376
- type: 'rate_limit',
377
- retryable: false,
378
- message: 'Rate limit exceeded',
379
- };
380
- }
381
- // Authentication errors (401)
382
- if (errorMessage.includes('401') || errorMessage.includes('Unauthorized')) {
383
- return {
384
- type: 'auth_error',
385
- retryable: false,
386
- message: 'Authentication failed - check API key',
387
- };
388
- }
389
- // Quota exceeded (429 or specific messages)
390
- if (errorMessage.includes('quota') || errorMessage.includes('insufficient_quota')) {
391
- return {
392
- type: 'quota_exceeded',
393
- retryable: false,
394
- message: 'API quota exceeded',
395
- };
396
- }
397
- // Network errors
398
- if (errorMessage.includes('network') || errorMessage.includes('timeout') || errorMessage.includes('ECONNREFUSED')) {
399
- return {
400
- type: 'network_error',
401
- retryable: true,
402
- message: errorMessage,
403
- };
404
- }
405
- // Default to retryable
406
- return {
407
- type: 'unknown',
408
- retryable: true,
409
- message: errorMessage,
410
- };
411
- }
412
- }
413
- //# sourceMappingURL=openai-provider.js.map