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.
- package/README.md +88 -68
- package/dist/domain/entities/task.js +4 -4
- package/dist/error-handler.js +4 -9
- package/dist/index.js +261 -1224
- package/dist/infrastructure/config/product-context.js +7 -6
- package/dist/infrastructure/hooks/claude-sdk-hook.js +348 -72
- package/dist/infrastructure/observability/execution-tracer.js +11 -6
- package/dist/infrastructure/orchestration/agent-adapter.js +13 -0
- package/dist/infrastructure/orchestration/agent-installer.js +101 -0
- package/dist/infrastructure/orchestration/agents-config-seed.js +56 -0
- package/dist/infrastructure/orchestration/aider-adapter.js +319 -0
- package/dist/infrastructure/orchestration/artifacts-extractor.js +175 -0
- package/dist/infrastructure/orchestration/claude-code-adapter.js +352 -0
- package/dist/infrastructure/orchestration/codex-adapter.js +310 -0
- package/dist/infrastructure/orchestration/conductor-adapter.js +340 -0
- package/dist/infrastructure/orchestration/generic-cli-adapter.js +553 -0
- package/dist/infrastructure/orchestration/opencode-adapter.js +275 -0
- package/dist/infrastructure/orchestration/progress-aggregator.js +189 -0
- package/dist/infrastructure/orchestration/readiness.js +106 -0
- package/dist/infrastructure/orchestration/session-manager.js +278 -0
- package/dist/infrastructure/orchestration/session-persistence.js +109 -0
- package/dist/infrastructure/protocols/mcp-helpers.js +10 -30
- package/dist/infrastructure/protocols/mcp-server-impl.js +359 -21
- package/dist/infrastructure/protocols/probe-port.js +36 -0
- package/dist/infrastructure/protocols/ui-page.js +1827 -0
- package/dist/infrastructure/security/file-collection.js +115 -0
- package/dist/infrastructure/security/trust-scorer.js +301 -56
- package/dist/infrastructure/storage/task-repository.js +8 -7
- package/dist/monitoring.js +9 -38
- package/dist/presentation/cli/commands/help-command.js +96 -139
- package/dist/presentation/cli/commands/hook-command.js +17 -24
- package/dist/presentation/cli/commands/report-command.js +59 -72
- package/dist/presentation/cli/commands/setup-command.js +4 -4
- package/dist/presentation/cli/commands/status-command.js +321 -30
- package/dist/presentation/cli/commands/trust-command.js +84 -72
- package/dist/presentation/cli/error-display.js +17 -21
- package/dist/presentation/cli/repl.js +474 -0
- package/dist/ui.js +11 -11
- package/package.json +24 -62
- package/dist/agents/base.js +0 -101
- package/dist/agents/orchestrator-model-driven.js +0 -141
- package/dist/agents/react-orchestrator-agent.js +0 -54
- package/dist/application/agents/execution-agent.js +0 -508
- package/dist/application/agents/multi-agent-orchestrator.js +0 -295
- package/dist/application/agents/planning-agent.js +0 -433
- package/dist/application/agents/validation-agent.js +0 -317
- package/dist/application/architectures/plan-and-act.js +0 -242
- package/dist/application/index.js +0 -12
- package/dist/application/services/agent-factory.js +0 -28
- package/dist/application/services/dependency-container.js +0 -596
- package/dist/application/services/git-context-service.js +0 -83
- package/dist/application/services/intelligent-router.js +0 -934
- package/dist/application/services/tool-executor-service.js +0 -94
- package/dist/application/use-cases/ask-question-use-case.js +0 -338
- package/dist/application/use-cases/edit-file-use-case.js +0 -830
- package/dist/application/use-cases/explain-file-use-case.js +0 -50
- package/dist/application/use-cases/index-codebase-use-case.js +0 -113
- package/dist/application/use-cases/planning-use-case.js +0 -276
- package/dist/application/use-cases/react-orchestration-use-case.js +0 -329
- package/dist/application/use-cases/reflexion-use-case.js +0 -30
- package/dist/application/workflows/deterministic-workflows.js +0 -189
- package/dist/ast-parser.js +0 -331
- package/dist/cache.js +0 -180
- package/dist/chat.js +0 -251
- package/dist/code-analysis.js +0 -327
- package/dist/context.js +0 -187
- package/dist/docs.js +0 -146
- package/dist/domain/entities/code-chunk.js +0 -6
- package/dist/domain/entities/decision.js +0 -9
- package/dist/domain/entities/edit.js +0 -6
- package/dist/domain/entities/knowledge-node.js +0 -9
- package/dist/domain/entities/knowledge-preservation.js +0 -10
- package/dist/domain/entities/memory.js +0 -6
- package/dist/domain/entities/pattern.js +0 -7
- package/dist/domain/entities/plan.js +0 -6
- package/dist/domain/entities/query.js +0 -6
- package/dist/domain/errors/embeddings-not-found-error.js +0 -13
- package/dist/domain/index.js +0 -19
- package/dist/domain/interfaces/ai-service.interface.js +0 -6
- package/dist/domain/interfaces/code-analyzer.interface.js +0 -6
- package/dist/domain/interfaces/decision-repository.interface.js +0 -9
- package/dist/domain/interfaces/embedding-repository.interface.js +0 -6
- package/dist/domain/interfaces/knowledge-graph-repository.interface.js +0 -9
- package/dist/domain/interfaces/knowledge-preservation-repository.interface.js +0 -8
- package/dist/domain/interfaces/memory-repository.interface.js +0 -6
- package/dist/domain/interfaces/pattern-repository.interface.js +0 -6
- package/dist/domain/interfaces/verification-service.interface.js +0 -6
- package/dist/domain/services/cross-team-pattern-sharing.js +0 -125
- package/dist/domain/services/decision-recorder.js +0 -223
- package/dist/domain/services/decision-retriever.js +0 -133
- package/dist/domain/services/environment-mode-manager.js +0 -22
- package/dist/domain/services/graded-memory-activation.js +0 -69
- package/dist/domain/services/knowledge-access.js +0 -132
- package/dist/domain/services/knowledge-extractor.js +0 -247
- package/dist/domain/services/knowledge-graph-builder.js +0 -268
- package/dist/domain/services/knowledge-graph-query.js +0 -187
- package/dist/domain/services/memory-retriever.js +0 -82
- package/dist/domain/services/memory-synthesizer.js +0 -91
- package/dist/domain/services/pattern-extractor.js +0 -442
- package/dist/domain/services/query-intent-classifier.js +0 -140
- package/dist/domain/services/react-loop.js +0 -186
- package/dist/domain/services/risk-tier-detector.js +0 -78
- package/dist/edit.js +0 -319
- package/dist/embed.js +0 -459
- package/dist/formatter.js +0 -168
- package/dist/git.js +0 -198
- package/dist/infrastructure/ai/cohere-ai-service.js +0 -607
- package/dist/infrastructure/ai/command-r-evaluation.js +0 -206
- package/dist/infrastructure/ai/model-config.js +0 -84
- package/dist/infrastructure/ai/provider-ai-service.js +0 -477
- package/dist/infrastructure/cache/embedding-cache.js +0 -175
- package/dist/infrastructure/cache/query-result-cache.js +0 -66
- package/dist/infrastructure/cache/response-cache.js +0 -48
- package/dist/infrastructure/cache/security-scan-cache.js +0 -47
- package/dist/infrastructure/chunking/ast-code-chunker.js +0 -19
- package/dist/infrastructure/chunking/code-aware-chunker.js +0 -397
- package/dist/infrastructure/context/context-compressor.js +0 -329
- package/dist/infrastructure/context/conversation-context.js +0 -128
- package/dist/infrastructure/context/session-manager.js +0 -94
- package/dist/infrastructure/cost/cost-tracker.js +0 -360
- package/dist/infrastructure/file-scanner/file-scanner.js +0 -106
- package/dist/infrastructure/governance/nist-ai-rmf.js +0 -292
- package/dist/infrastructure/governance/policy-as-code.js +0 -258
- package/dist/infrastructure/governance/prompt-to-code-lineage.js +0 -239
- package/dist/infrastructure/index.js +0 -7
- package/dist/infrastructure/observability/prompt-versioner.js +0 -145
- package/dist/infrastructure/protocols/a2a-metadata.js +0 -137
- package/dist/infrastructure/protocols/a2a-protocol.js +0 -314
- package/dist/infrastructure/protocols/mcp-oauth.js +0 -184
- package/dist/infrastructure/protocols/mcp-server.js +0 -333
- package/dist/infrastructure/protocols/streaming-handler.js +0 -103
- package/dist/infrastructure/providers/cohere-provider.js +0 -444
- package/dist/infrastructure/providers/fake-provider.js +0 -130
- package/dist/infrastructure/providers/local-llm-provider.js +0 -330
- package/dist/infrastructure/providers/model-config.types.js +0 -9
- package/dist/infrastructure/providers/model-provider.interface.js +0 -8
- package/dist/infrastructure/providers/openai-provider.js +0 -413
- package/dist/infrastructure/providers/openrouter-provider.js +0 -399
- package/dist/infrastructure/providers/operation-provider-resolver.js +0 -105
- package/dist/infrastructure/providers/provider-config-loader.js +0 -120
- package/dist/infrastructure/providers/provider-registry.js +0 -88
- package/dist/infrastructure/safety/pattern-detector.js +0 -133
- package/dist/infrastructure/security/ai-sast-scanner.js +0 -290
- package/dist/infrastructure/security/docker-sandbox.js +0 -178
- package/dist/infrastructure/security/enhanced-security-gate.js +0 -151
- package/dist/infrastructure/security/license-scanner.js +0 -167
- package/dist/infrastructure/security/provider-bias-detector.js +0 -164
- package/dist/infrastructure/security/sandbox-executor.js +0 -64
- package/dist/infrastructure/serialization/toon-serializer.js +0 -119
- package/dist/infrastructure/storage/memory-stream-service.js +0 -204
- package/dist/infrastructure/storage/plan-repository.js +0 -96
- package/dist/infrastructure/storage/sqlite-decision-repository.js +0 -232
- package/dist/infrastructure/storage/sqlite-embedding-repository.js +0 -311
- package/dist/infrastructure/storage/sqlite-knowledge-graph-repository.js +0 -417
- package/dist/infrastructure/storage/sqlite-knowledge-preservation-repository.js +0 -230
- package/dist/infrastructure/storage/sqlite-memory-repository.js +0 -229
- package/dist/infrastructure/storage/sqlite-pattern-repository.js +0 -249
- package/dist/infrastructure/storage/task-helpers.js +0 -197
- package/dist/infrastructure/telemetry/telemetry-service.js +0 -167
- package/dist/infrastructure/ux/appropriate-friction.js +0 -213
- package/dist/infrastructure/ux/bi-directional-learning.js +0 -337
- package/dist/infrastructure/ux/capability-boundaries.js +0 -42
- package/dist/infrastructure/ux/comprehensive-formatter.js +0 -117
- package/dist/infrastructure/ux/contextual-feature-discovery.js +0 -10
- package/dist/infrastructure/ux/expectation-management.js +0 -327
- package/dist/infrastructure/ux/feature-discovery.js +0 -14
- package/dist/infrastructure/ux/feedback-prompt.js +0 -45
- package/dist/infrastructure/ux/hitl-validation.js +0 -297
- package/dist/infrastructure/ux/progress-indicator.js +0 -116
- package/dist/infrastructure/ux/progressive-disclosure.js +0 -236
- package/dist/infrastructure/ux/review-checkpoint.js +0 -72
- package/dist/infrastructure/ux/staged-feature-intro.js +0 -24
- package/dist/infrastructure/ux/stream-markdown.js +0 -151
- package/dist/infrastructure/ux/syntax-highlighter.js +0 -91
- package/dist/infrastructure/ux/team-standards.js +0 -196
- package/dist/infrastructure/ux/transparency.js +0 -71
- package/dist/infrastructure/validation/agent-feedback.js +0 -55
- package/dist/infrastructure/validation/agent-validation-helper.js +0 -137
- package/dist/infrastructure/validation/review-handler.js +0 -40
- package/dist/infrastructure/validation/summary-aggregator.js +0 -70
- package/dist/infrastructure/validation/summary-extractor.js +0 -45
- package/dist/infrastructure/validation/trace-summary.js +0 -52
- package/dist/infrastructure/verification/verification-service.js +0 -47
- package/dist/infrastructure/xai/attention-visualizer.js +0 -172
- package/dist/infrastructure/xai/cot-visualizer.js +0 -283
- package/dist/infrastructure/xai/decision-tree-log.js +0 -212
- package/dist/infrastructure/xai/interactive-xai.js +0 -260
- package/dist/infrastructure/xai/uncertainty-quantifier.js +0 -198
- package/dist/intelligent-retrieval.js +0 -272
- package/dist/intent/classifier.js +0 -2
- package/dist/intent/context.js +0 -2
- package/dist/iterative-refinement.js +0 -189
- package/dist/learning.js +0 -232
- package/dist/log.js +0 -31
- package/dist/migrate.js +0 -133
- package/dist/parallel-processor.js +0 -534
- package/dist/planner.js +0 -198
- package/dist/policy.js +0 -26
- package/dist/presentation/cli/commands/ask-command.js +0 -314
- package/dist/presentation/cli/commands/cost-command.js +0 -191
- package/dist/presentation/cli/commands/decision-command.js +0 -207
- package/dist/presentation/cli/commands/docs-command.js +0 -25
- package/dist/presentation/cli/commands/fix-command.js +0 -53
- package/dist/presentation/cli/commands/knowledge-command.js +0 -129
- package/dist/presentation/cli/commands/learning-dashboard-command.js +0 -183
- package/dist/presentation/cli/commands/models-command.js +0 -194
- package/dist/presentation/cli/commands/orchestrate-command.js +0 -207
- package/dist/presentation/cli/commands/plan-command.js +0 -246
- package/dist/presentation/cli/commands/product-command.js +0 -199
- package/dist/presentation/cli/commands/react-command.js +0 -181
- package/dist/presentation/cli/commands/review-command.js +0 -154
- package/dist/presentation/cli/commands/run-command.js +0 -188
- package/dist/presentation/cli/commands/smart-command.js +0 -395
- package/dist/presentation/cli/commands/suggest-command.js +0 -138
- package/dist/presentation/cli/commands/trace-command.js +0 -129
- package/dist/presentation/cli/commands/undo-command.js +0 -150
- package/dist/query-optimizer.js +0 -205
- package/dist/refactor.js +0 -116
- package/dist/review.js +0 -206
- package/dist/search.js +0 -163
- package/dist/session.js +0 -704
- package/dist/task-verification.js +0 -336
- package/dist/testgen.js +0 -166
- package/dist/token-optimizer.js +0 -277
- package/dist/tools/bash.js +0 -213
- package/dist/tools/edit.js +0 -235
- package/dist/tools/executor.js +0 -153
- package/dist/tools/git-tool.js +0 -292
- package/dist/tools/parser.js +0 -158
- package/dist/tools/registry.js +0 -302
- package/dist/tools/search.js +0 -100
- package/dist/types.js +0 -2
- package/dist/utils/check-api-status.js +0 -100
- package/dist/utils/diff-parser.js +0 -162
- package/dist/verification/backup.js +0 -259
- package/dist/verification/compiler.js +0 -264
- package/dist/verification/index.js +0 -273
- 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
|