akbo-cli 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +786 -2
- package/dist/catalog_store.d.ts +131 -0
- package/dist/catalog_store.js +506 -0
- package/dist/cleaner.d.ts +11 -0
- package/dist/cleaner.js +92 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1961 -0
- package/dist/dream_engine.d.ts +61 -0
- package/dist/dream_engine.js +330 -0
- package/dist/extractors/base.d.ts +35 -0
- package/dist/extractors/base.js +17 -0
- package/dist/extractors/custom_extractor.d.ts +55 -0
- package/dist/extractors/custom_extractor.js +198 -0
- package/dist/extractors/dotnet_extractor.d.ts +11 -0
- package/dist/extractors/dotnet_extractor.js +579 -0
- package/dist/extractors/golang_extractor.d.ts +11 -0
- package/dist/extractors/golang_extractor.js +73 -0
- package/dist/extractors/index.d.ts +14 -0
- package/dist/extractors/index.js +30 -0
- package/dist/extractors/jvm_extractor.d.ts +11 -0
- package/dist/extractors/jvm_extractor.js +319 -0
- package/dist/extractors/node_extractor.d.ts +11 -0
- package/dist/extractors/node_extractor.js +306 -0
- package/dist/extractors/proto_graphql_extractor.d.ts +11 -0
- package/dist/extractors/proto_graphql_extractor.js +125 -0
- package/dist/extractors/python_extractor.d.ts +11 -0
- package/dist/extractors/python_extractor.js +298 -0
- package/dist/extractors/rust_extractor.d.ts +11 -0
- package/dist/extractors/rust_extractor.js +66 -0
- package/dist/graph_builder.d.ts +87 -0
- package/dist/graph_builder.js +1516 -0
- package/dist/guard_service.d.ts +33 -0
- package/dist/guard_service.js +167 -0
- package/dist/harvester.d.ts +38 -0
- package/dist/harvester.js +461 -0
- package/dist/hook_generator.d.ts +34 -0
- package/dist/hook_generator.js +269 -0
- package/dist/importers/skill_importer.d.ts +43 -0
- package/dist/importers/skill_importer.js +470 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +20 -0
- package/dist/indexer.d.ts +19 -0
- package/dist/indexer.js +108 -0
- package/dist/init_service.d.ts +37 -0
- package/dist/init_service.js +246 -0
- package/dist/mcp_server.d.ts +10 -0
- package/dist/mcp_server.js +846 -0
- package/dist/pool_resolver.d.ts +40 -0
- package/dist/pool_resolver.js +84 -0
- package/dist/provider.d.ts +135 -0
- package/dist/provider.js +880 -0
- package/dist/query_service.d.ts +33 -0
- package/dist/query_service.js +161 -0
- package/dist/schema_generator.d.ts +236 -0
- package/dist/schema_generator.js +264 -0
- package/dist/standards_loader.d.ts +7 -0
- package/dist/standards_loader.js +33 -0
- package/dist/types.d.ts +323 -0
- package/dist/types.js +123 -0
- package/dist/unit_synthesizer.d.ts +22 -0
- package/dist/unit_synthesizer.js +196 -0
- package/dist/validator.d.ts +13 -0
- package/dist/validator.js +152 -0
- package/dist/version.d.ts +6 -0
- package/dist/version.js +16 -0
- package/dist/watcher.d.ts +38 -0
- package/dist/watcher.js +132 -0
- package/package.json +56 -6
- package/schemas/index-schema.json +98 -0
- package/schemas/knowledge-unit.json +154 -0
package/dist/provider.js
ADDED
|
@@ -0,0 +1,880 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { spawn, execSync } from 'node:child_process';
|
|
5
|
+
/**
|
|
6
|
+
* Resolves an API key from explicit parameters, environment variables, or provider configuration.
|
|
7
|
+
* Fully supports multi-provider lookup (Gemini, OpenAI, Anthropic, DeepSeek, Groq, Ollama, generic).
|
|
8
|
+
*/
|
|
9
|
+
export function resolveApiKey(explicitKeyOrProvider, explicitKeyIfProviderGiven) {
|
|
10
|
+
let provider;
|
|
11
|
+
let explicitKey;
|
|
12
|
+
const knownProviders = ['gemini', 'openai', 'anthropic', 'deepseek', 'groq', 'mistral', 'openrouter', 'ollama', 'local', 'custom', 'cli', 'agy', 'agy-cli'];
|
|
13
|
+
if (explicitKeyIfProviderGiven !== undefined) {
|
|
14
|
+
provider = explicitKeyOrProvider?.toLowerCase().trim();
|
|
15
|
+
explicitKey = explicitKeyIfProviderGiven;
|
|
16
|
+
}
|
|
17
|
+
else if (explicitKeyOrProvider) {
|
|
18
|
+
if (knownProviders.includes(explicitKeyOrProvider.toLowerCase().trim())) {
|
|
19
|
+
provider = explicitKeyOrProvider.toLowerCase().trim();
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
explicitKey = explicitKeyOrProvider;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
if (explicitKey && explicitKey.trim()) {
|
|
26
|
+
return explicitKey.trim();
|
|
27
|
+
}
|
|
28
|
+
// Provider-specific resolution
|
|
29
|
+
if (provider === 'openai') {
|
|
30
|
+
if (process.env.OPENAI_API_KEY && process.env.OPENAI_API_KEY.trim())
|
|
31
|
+
return process.env.OPENAI_API_KEY.trim();
|
|
32
|
+
}
|
|
33
|
+
else if (provider === 'anthropic') {
|
|
34
|
+
if (process.env.ANTHROPIC_API_KEY && process.env.ANTHROPIC_API_KEY.trim())
|
|
35
|
+
return process.env.ANTHROPIC_API_KEY.trim();
|
|
36
|
+
}
|
|
37
|
+
else if (provider === 'deepseek') {
|
|
38
|
+
if (process.env.DEEPSEEK_API_KEY && process.env.DEEPSEEK_API_KEY.trim())
|
|
39
|
+
return process.env.DEEPSEEK_API_KEY.trim();
|
|
40
|
+
}
|
|
41
|
+
else if (provider === 'groq') {
|
|
42
|
+
if (process.env.GROQ_API_KEY && process.env.GROQ_API_KEY.trim())
|
|
43
|
+
return process.env.GROQ_API_KEY.trim();
|
|
44
|
+
}
|
|
45
|
+
else if (provider === 'mistral') {
|
|
46
|
+
if (process.env.MISTRAL_API_KEY && process.env.MISTRAL_API_KEY.trim())
|
|
47
|
+
return process.env.MISTRAL_API_KEY.trim();
|
|
48
|
+
}
|
|
49
|
+
else if (provider === 'openrouter') {
|
|
50
|
+
if (process.env.OPENROUTER_API_KEY && process.env.OPENROUTER_API_KEY.trim())
|
|
51
|
+
return process.env.OPENROUTER_API_KEY.trim();
|
|
52
|
+
}
|
|
53
|
+
else if (provider === 'ollama' || provider === 'local') {
|
|
54
|
+
if (process.env.OLLAMA_API_KEY && process.env.OLLAMA_API_KEY.trim())
|
|
55
|
+
return process.env.OLLAMA_API_KEY.trim();
|
|
56
|
+
return 'ollama';
|
|
57
|
+
}
|
|
58
|
+
else if (provider === 'agy' || provider === 'agy-cli') {
|
|
59
|
+
return 'agy-cli';
|
|
60
|
+
}
|
|
61
|
+
else if (provider === 'gemini') {
|
|
62
|
+
if (process.env.GEMINI_API_KEY && process.env.GEMINI_API_KEY.trim())
|
|
63
|
+
return process.env.GEMINI_API_KEY.trim();
|
|
64
|
+
if (process.env.GOOGLE_API_KEY && process.env.GOOGLE_API_KEY.trim())
|
|
65
|
+
return process.env.GOOGLE_API_KEY.trim();
|
|
66
|
+
if (process.env.GOOGLE_GENAI_API_KEY && process.env.GOOGLE_GENAI_API_KEY.trim())
|
|
67
|
+
return process.env.GOOGLE_GENAI_API_KEY.trim();
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
// No specific provider specified - check priority
|
|
71
|
+
if (process.env.GEMINI_API_KEY && process.env.GEMINI_API_KEY.trim())
|
|
72
|
+
return process.env.GEMINI_API_KEY.trim();
|
|
73
|
+
if (process.env.GOOGLE_API_KEY && process.env.GOOGLE_API_KEY.trim())
|
|
74
|
+
return process.env.GOOGLE_API_KEY.trim();
|
|
75
|
+
if (process.env.GOOGLE_GENAI_API_KEY && process.env.GOOGLE_GENAI_API_KEY.trim())
|
|
76
|
+
return process.env.GOOGLE_GENAI_API_KEY.trim();
|
|
77
|
+
if (process.env.OPENAI_API_KEY && process.env.OPENAI_API_KEY.trim())
|
|
78
|
+
return process.env.OPENAI_API_KEY.trim();
|
|
79
|
+
if (process.env.ANTHROPIC_API_KEY && process.env.ANTHROPIC_API_KEY.trim())
|
|
80
|
+
return process.env.ANTHROPIC_API_KEY.trim();
|
|
81
|
+
if (process.env.DEEPSEEK_API_KEY && process.env.DEEPSEEK_API_KEY.trim())
|
|
82
|
+
return process.env.DEEPSEEK_API_KEY.trim();
|
|
83
|
+
if (process.env.GROQ_API_KEY && process.env.GROQ_API_KEY.trim())
|
|
84
|
+
return process.env.GROQ_API_KEY.trim();
|
|
85
|
+
if (process.env.CUSTOM_LLM_API_KEY && process.env.CUSTOM_LLM_API_KEY.trim())
|
|
86
|
+
return process.env.CUSTOM_LLM_API_KEY.trim();
|
|
87
|
+
}
|
|
88
|
+
// Check ~/.gemini/settings.json as fallback for Gemini
|
|
89
|
+
try {
|
|
90
|
+
const home = process.env.USERPROFILE || process.env.HOME || '';
|
|
91
|
+
const settingsPath = path.join(home, '.gemini', 'settings.json');
|
|
92
|
+
if (fs.existsSync(settingsPath)) {
|
|
93
|
+
const data = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
|
|
94
|
+
if (data.apiKey && typeof data.apiKey === 'string' && data.apiKey.trim()) {
|
|
95
|
+
return data.apiKey.trim();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
catch { }
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Checks if the Gemini CLI binary is available on PATH.
|
|
104
|
+
*/
|
|
105
|
+
export function isGeminiCliAvailable() {
|
|
106
|
+
try {
|
|
107
|
+
const checkCmd = process.platform === 'win32' ? 'where gemini' : 'which gemini';
|
|
108
|
+
execSync(checkCmd, { stdio: 'ignore' });
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Resolves the absolute path to the Antigravity CLI (agy) binary, checking PATH and common fallback locations.
|
|
117
|
+
*/
|
|
118
|
+
export function getAgyBinaryPath() {
|
|
119
|
+
const isWindows = process.platform === 'win32';
|
|
120
|
+
const binName = isWindows ? 'agy.exe' : 'agy';
|
|
121
|
+
try {
|
|
122
|
+
const checkCmd = isWindows ? 'where.exe agy' : 'which agy';
|
|
123
|
+
const resolved = execSync(checkCmd, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim().split(/\r?\n/)[0];
|
|
124
|
+
if (resolved && fs.existsSync(resolved)) {
|
|
125
|
+
return resolved;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch { }
|
|
129
|
+
// Fallback to ~/.gemini/bin/agy(.exe)
|
|
130
|
+
const homeFallback = path.join(os.homedir(), '.gemini', 'bin', binName);
|
|
131
|
+
if (fs.existsSync(homeFallback)) {
|
|
132
|
+
return homeFallback;
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Checks if the Google Antigravity CLI (agy) binary is available on PATH or fallback locations.
|
|
138
|
+
*/
|
|
139
|
+
export function isAgyCliAvailable() {
|
|
140
|
+
return getAgyBinaryPath() !== null;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Robustly extracts and parses JSON from LLM or CLI output.
|
|
144
|
+
* Handles markdown fences, preamble warnings, and trailing text.
|
|
145
|
+
*/
|
|
146
|
+
export function extractJson(text) {
|
|
147
|
+
const trimmed = text.trim();
|
|
148
|
+
// 1. Direct parse attempt
|
|
149
|
+
try {
|
|
150
|
+
return JSON.parse(trimmed);
|
|
151
|
+
}
|
|
152
|
+
catch { }
|
|
153
|
+
// 2. Extract from markdown code fence (```json ... ``` or ``` ...)
|
|
154
|
+
const fenceMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
|
|
155
|
+
if (fenceMatch) {
|
|
156
|
+
try {
|
|
157
|
+
return JSON.parse(fenceMatch[1].trim());
|
|
158
|
+
}
|
|
159
|
+
catch { }
|
|
160
|
+
}
|
|
161
|
+
// 3. Extract the outermost JSON object {...}
|
|
162
|
+
const startObj = trimmed.indexOf('{');
|
|
163
|
+
const endObj = trimmed.lastIndexOf('}');
|
|
164
|
+
if (startObj !== -1 && endObj > startObj) {
|
|
165
|
+
try {
|
|
166
|
+
return JSON.parse(trimmed.slice(startObj, endObj + 1));
|
|
167
|
+
}
|
|
168
|
+
catch { }
|
|
169
|
+
}
|
|
170
|
+
// 4. Extract the outermost JSON array [...]
|
|
171
|
+
const startArr = trimmed.indexOf('[');
|
|
172
|
+
const endArr = trimmed.lastIndexOf(']');
|
|
173
|
+
if (startArr !== -1 && endArr > startArr) {
|
|
174
|
+
try {
|
|
175
|
+
return JSON.parse(trimmed.slice(startArr, endArr + 1));
|
|
176
|
+
}
|
|
177
|
+
catch { }
|
|
178
|
+
}
|
|
179
|
+
throw new Error(`Failed to parse JSON from response:\n${text}`);
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Executes the Gemini CLI non-interactively using headless options.
|
|
183
|
+
*/
|
|
184
|
+
export function executeGeminiCli(prompt, model, options) {
|
|
185
|
+
return new Promise((resolve, reject) => {
|
|
186
|
+
const isWindows = process.platform === 'win32';
|
|
187
|
+
const binary = isWindows ? 'gemini.cmd' : 'gemini';
|
|
188
|
+
const args = [
|
|
189
|
+
'-p', '',
|
|
190
|
+
'-o', 'json',
|
|
191
|
+
'--skip-trust',
|
|
192
|
+
'--approval-mode', 'yolo'
|
|
193
|
+
];
|
|
194
|
+
if (model) {
|
|
195
|
+
args.push('-m', model);
|
|
196
|
+
}
|
|
197
|
+
const timeoutMs = options?.timeoutMs || 120000;
|
|
198
|
+
const child = spawn(binary, args, {
|
|
199
|
+
shell: isWindows,
|
|
200
|
+
stdio: ['pipe', 'pipe', 'pipe']
|
|
201
|
+
});
|
|
202
|
+
let stdout = '';
|
|
203
|
+
let stderr = '';
|
|
204
|
+
let timedOut = false;
|
|
205
|
+
const timer = setTimeout(() => {
|
|
206
|
+
timedOut = true;
|
|
207
|
+
child.kill();
|
|
208
|
+
reject(new Error(`Gemini CLI timed out after ${timeoutMs}ms`));
|
|
209
|
+
}, timeoutMs);
|
|
210
|
+
child.stdout.on('data', chunk => {
|
|
211
|
+
stdout += chunk.toString();
|
|
212
|
+
});
|
|
213
|
+
child.stderr.on('data', chunk => {
|
|
214
|
+
stderr += chunk.toString();
|
|
215
|
+
});
|
|
216
|
+
child.on('error', err => {
|
|
217
|
+
clearTimeout(timer);
|
|
218
|
+
reject(new Error(`Failed to spawn Gemini CLI: ${err.message}`));
|
|
219
|
+
});
|
|
220
|
+
child.on('close', code => {
|
|
221
|
+
clearTimeout(timer);
|
|
222
|
+
if (timedOut)
|
|
223
|
+
return;
|
|
224
|
+
const output = stdout.trim() || stderr.trim();
|
|
225
|
+
if (code !== 0 && !stdout.trim()) {
|
|
226
|
+
reject(new Error(`Gemini CLI exited with code ${code}: ${stderr || stdout}`));
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
resolve(output);
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
// Feed prompt via stdin safely
|
|
233
|
+
if (typeof child.stdin?.on === 'function') {
|
|
234
|
+
child.stdin.on('error', () => {
|
|
235
|
+
// Ignore EPIPE/EOF on stdin if child process exited early; child 'close' handler captures exit code and output
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
239
|
+
child.stdin.write(prompt);
|
|
240
|
+
child.stdin.end();
|
|
241
|
+
}
|
|
242
|
+
catch { }
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Executes the Google Antigravity CLI (agy) non-interactively using headless options.
|
|
247
|
+
* Streams prompt via stdin using stream-json to prevent Windows command-line length limits (ENAMETOOLONG).
|
|
248
|
+
*/
|
|
249
|
+
export function executeAgyCli(prompt, model, options) {
|
|
250
|
+
return new Promise((resolve, reject) => {
|
|
251
|
+
const isWindows = process.platform === 'win32';
|
|
252
|
+
const binary = getAgyBinaryPath() || (isWindows ? 'agy.exe' : 'agy');
|
|
253
|
+
const args = [
|
|
254
|
+
'--input-format', 'stream-json',
|
|
255
|
+
'--output-format', 'stream-json',
|
|
256
|
+
'--dangerously-skip-permissions',
|
|
257
|
+
'--disable-slash-commands'
|
|
258
|
+
];
|
|
259
|
+
if (model) {
|
|
260
|
+
args.push('--model', model);
|
|
261
|
+
}
|
|
262
|
+
const timeoutMs = options?.timeoutMs || 180000;
|
|
263
|
+
const child = spawn(binary, args, {
|
|
264
|
+
shell: false,
|
|
265
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
266
|
+
env: {
|
|
267
|
+
...process.env,
|
|
268
|
+
AKBO_NESTED_AGENT: '1'
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
let stdout = '';
|
|
272
|
+
let stderr = '';
|
|
273
|
+
let timedOut = false;
|
|
274
|
+
const timer = setTimeout(() => {
|
|
275
|
+
timedOut = true;
|
|
276
|
+
child.kill();
|
|
277
|
+
reject(new Error(`Antigravity CLI (agy) timed out after ${timeoutMs}ms`));
|
|
278
|
+
}, timeoutMs);
|
|
279
|
+
child.stdout.on('data', chunk => {
|
|
280
|
+
stdout += chunk.toString();
|
|
281
|
+
});
|
|
282
|
+
child.stderr.on('data', chunk => {
|
|
283
|
+
stderr += chunk.toString();
|
|
284
|
+
});
|
|
285
|
+
child.on('error', err => {
|
|
286
|
+
clearTimeout(timer);
|
|
287
|
+
reject(new Error(`Failed to spawn Antigravity CLI (agy): ${err.message}`));
|
|
288
|
+
});
|
|
289
|
+
child.on('close', code => {
|
|
290
|
+
clearTimeout(timer);
|
|
291
|
+
if (timedOut)
|
|
292
|
+
return;
|
|
293
|
+
// Parse NDJSON lines from stdout to extract the result event
|
|
294
|
+
let resultResponse = null;
|
|
295
|
+
let resultError = null;
|
|
296
|
+
for (const line of stdout.split('\n')) {
|
|
297
|
+
const trimmed = line.trim();
|
|
298
|
+
if (!trimmed)
|
|
299
|
+
continue;
|
|
300
|
+
try {
|
|
301
|
+
const parsed = JSON.parse(trimmed);
|
|
302
|
+
if (parsed.event === 'result' && parsed.result) {
|
|
303
|
+
if (parsed.result.response) {
|
|
304
|
+
resultResponse = parsed.result.response;
|
|
305
|
+
}
|
|
306
|
+
if (parsed.result.status === 'ERROR' && parsed.result.error) {
|
|
307
|
+
resultError = parsed.result.error;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
catch { }
|
|
312
|
+
}
|
|
313
|
+
if (resultError && !resultResponse) {
|
|
314
|
+
reject(new Error(`Antigravity CLI (agy) error: ${resultError}`));
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
const output = resultResponse || stdout.trim() || stderr.trim();
|
|
318
|
+
if (code !== 0 && !resultResponse && !stdout.trim()) {
|
|
319
|
+
reject(new Error(`Antigravity CLI (agy) exited with code ${code}: ${stderr || stdout}`));
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
resolve(output);
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
// Feed prompt safely via stdin (bypassing Windows command line length limit)
|
|
326
|
+
if (typeof child.stdin?.on === 'function') {
|
|
327
|
+
child.stdin.on('error', () => {
|
|
328
|
+
// Ignore EPIPE/EOF on stdin if child process exited early; child 'close' handler captures exit code and output
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
try {
|
|
332
|
+
child.stdin.write(JSON.stringify({
|
|
333
|
+
event: 'user',
|
|
334
|
+
message: { content: prompt }
|
|
335
|
+
}) + '\n');
|
|
336
|
+
child.stdin.end();
|
|
337
|
+
}
|
|
338
|
+
catch (err) {
|
|
339
|
+
clearTimeout(timer);
|
|
340
|
+
reject(new Error(`Failed to write prompt to Antigravity CLI stdin: ${err.message}`));
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Determines whether an error returned from Gemini API is transient and retryable.
|
|
346
|
+
* Non-retryable errors (e.g. 401 Unauthorized, 403 Forbidden, 404 Model Not Found, 400 Bad Request)
|
|
347
|
+
* fail fast immediately to avoid stalling execution.
|
|
348
|
+
*/
|
|
349
|
+
export function isRetryableError(err) {
|
|
350
|
+
if (!err)
|
|
351
|
+
return false;
|
|
352
|
+
// Check HTTP status code
|
|
353
|
+
const status = err.status || err.statusCode || err.code;
|
|
354
|
+
if (status === 401 || status === 403 || status === 404) {
|
|
355
|
+
return false;
|
|
356
|
+
}
|
|
357
|
+
if (status === 400 && !/quota|rate/i.test(err.message || '')) {
|
|
358
|
+
return false;
|
|
359
|
+
}
|
|
360
|
+
if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {
|
|
361
|
+
return true;
|
|
362
|
+
}
|
|
363
|
+
// Check error message strings
|
|
364
|
+
const msg = (err.message || '').toLowerCase();
|
|
365
|
+
if (msg.includes('api_key_invalid') ||
|
|
366
|
+
msg.includes('api key not valid') ||
|
|
367
|
+
msg.includes('unauthorized') ||
|
|
368
|
+
msg.includes('permission_denied') ||
|
|
369
|
+
msg.includes('not found') ||
|
|
370
|
+
msg.includes('invalid argument')) {
|
|
371
|
+
return false;
|
|
372
|
+
}
|
|
373
|
+
if (msg.includes('resource_exhausted') ||
|
|
374
|
+
msg.includes('rate limit') ||
|
|
375
|
+
msg.includes('too many requests') ||
|
|
376
|
+
msg.includes('quota') ||
|
|
377
|
+
msg.includes('overloaded') ||
|
|
378
|
+
msg.includes('econnreset') ||
|
|
379
|
+
msg.includes('etimedout') ||
|
|
380
|
+
msg.includes('fetch failed')) {
|
|
381
|
+
return true;
|
|
382
|
+
}
|
|
383
|
+
// Default to true for transient / unknown network errors
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Direct Gemini API provider using Node 20+ native fetch (zero third-party SDK dependencies).
|
|
388
|
+
*/
|
|
389
|
+
export class GeminiApiProvider {
|
|
390
|
+
name = 'gemini-api';
|
|
391
|
+
apiKey;
|
|
392
|
+
modelName;
|
|
393
|
+
baseUrl;
|
|
394
|
+
initialRetryDelay;
|
|
395
|
+
client;
|
|
396
|
+
constructor(apiKey, modelName = process.env.GEMINI_MODEL || 'gemini-3.5-flash', initialRetryDelay = 2000, baseUrl = process.env.GEMINI_BASE_URL || 'https://generativelanguage.googleapis.com/v1beta') {
|
|
397
|
+
this.apiKey = apiKey;
|
|
398
|
+
this.modelName = modelName;
|
|
399
|
+
this.baseUrl = baseUrl.replace(/\/+$/, '');
|
|
400
|
+
this.initialRetryDelay = initialRetryDelay;
|
|
401
|
+
this.client = {
|
|
402
|
+
models: {
|
|
403
|
+
generateContent: async (req) => {
|
|
404
|
+
const targetModel = req.model || this.modelName;
|
|
405
|
+
const url = `${this.baseUrl}/models/${encodeURIComponent(targetModel)}:generateContent?key=${encodeURIComponent(this.apiKey)}`;
|
|
406
|
+
const payload = {
|
|
407
|
+
contents: [
|
|
408
|
+
{
|
|
409
|
+
parts: [{ text: req.contents }]
|
|
410
|
+
}
|
|
411
|
+
]
|
|
412
|
+
};
|
|
413
|
+
if (req.config?.responseMimeType) {
|
|
414
|
+
payload.generationConfig = {
|
|
415
|
+
responseMimeType: req.config.responseMimeType
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
const res = await fetch(url, {
|
|
419
|
+
method: 'POST',
|
|
420
|
+
headers: {
|
|
421
|
+
'Content-Type': 'application/json'
|
|
422
|
+
},
|
|
423
|
+
body: JSON.stringify(payload)
|
|
424
|
+
});
|
|
425
|
+
if (!res.ok) {
|
|
426
|
+
const errBody = await res.text().catch(() => '');
|
|
427
|
+
let parsedErr;
|
|
428
|
+
try {
|
|
429
|
+
parsedErr = JSON.parse(errBody);
|
|
430
|
+
}
|
|
431
|
+
catch { }
|
|
432
|
+
const errorMsg = parsedErr?.error?.message || errBody || res.statusText;
|
|
433
|
+
const errObj = new Error(`Gemini API error (${res.status}): ${errorMsg}`);
|
|
434
|
+
errObj.status = res.status;
|
|
435
|
+
errObj.responseBody = errBody;
|
|
436
|
+
throw errObj;
|
|
437
|
+
}
|
|
438
|
+
const data = await res.json();
|
|
439
|
+
const text = data?.candidates?.[0]?.content?.parts?.map((p) => p.text).join('') || '';
|
|
440
|
+
return { text };
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
async generateJson(prompt) {
|
|
446
|
+
let retries = 3;
|
|
447
|
+
let delay = this.initialRetryDelay;
|
|
448
|
+
let response;
|
|
449
|
+
while (retries > 0) {
|
|
450
|
+
try {
|
|
451
|
+
response = await this.client.models.generateContent({
|
|
452
|
+
model: this.modelName,
|
|
453
|
+
contents: prompt,
|
|
454
|
+
config: {
|
|
455
|
+
responseMimeType: 'application/json'
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
break;
|
|
459
|
+
}
|
|
460
|
+
catch (err) {
|
|
461
|
+
if (!isRetryableError(err)) {
|
|
462
|
+
throw err;
|
|
463
|
+
}
|
|
464
|
+
retries--;
|
|
465
|
+
if (retries === 0)
|
|
466
|
+
throw err;
|
|
467
|
+
await new Promise(r => setTimeout(r, delay));
|
|
468
|
+
delay *= 2;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
const text = response?.text?.trim() || '{}';
|
|
472
|
+
return extractJson(text);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Direct OpenAI API provider supporting GPT-4o, GPT-4o-mini, o1, o3, etc.
|
|
477
|
+
*/
|
|
478
|
+
export class OpenAiApiProvider {
|
|
479
|
+
name = 'openai';
|
|
480
|
+
apiKey;
|
|
481
|
+
modelName;
|
|
482
|
+
baseUrl;
|
|
483
|
+
initialRetryDelay;
|
|
484
|
+
constructor(apiKey, modelName = process.env.OPENAI_MODEL || 'gpt-4o-mini', baseUrl = process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1', initialRetryDelay = 2000) {
|
|
485
|
+
this.apiKey = apiKey;
|
|
486
|
+
this.modelName = modelName;
|
|
487
|
+
this.baseUrl = baseUrl.replace(/\/+$/, '');
|
|
488
|
+
this.initialRetryDelay = initialRetryDelay;
|
|
489
|
+
}
|
|
490
|
+
async generateJson(prompt) {
|
|
491
|
+
let retries = 3;
|
|
492
|
+
let delay = this.initialRetryDelay;
|
|
493
|
+
let lastError;
|
|
494
|
+
while (retries > 0) {
|
|
495
|
+
try {
|
|
496
|
+
const payload = {
|
|
497
|
+
model: this.modelName,
|
|
498
|
+
messages: [
|
|
499
|
+
{
|
|
500
|
+
role: 'system',
|
|
501
|
+
content: 'You are an expert software architect and deterministic knowledge base synthesizer. You must respond with valid JSON only. Do not include markdown code fences, preambles, or explanations.'
|
|
502
|
+
},
|
|
503
|
+
{
|
|
504
|
+
role: 'user',
|
|
505
|
+
content: prompt
|
|
506
|
+
}
|
|
507
|
+
]
|
|
508
|
+
};
|
|
509
|
+
if (!this.modelName.startsWith('o1-mini') && !this.modelName.startsWith('o1-preview')) {
|
|
510
|
+
payload.response_format = { type: 'json_object' };
|
|
511
|
+
}
|
|
512
|
+
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
513
|
+
method: 'POST',
|
|
514
|
+
headers: {
|
|
515
|
+
'Content-Type': 'application/json',
|
|
516
|
+
'Authorization': `Bearer ${this.apiKey}`
|
|
517
|
+
},
|
|
518
|
+
body: JSON.stringify(payload)
|
|
519
|
+
});
|
|
520
|
+
if (!res.ok) {
|
|
521
|
+
const errBody = await res.text().catch(() => '');
|
|
522
|
+
let parsedErr;
|
|
523
|
+
try {
|
|
524
|
+
parsedErr = JSON.parse(errBody);
|
|
525
|
+
}
|
|
526
|
+
catch { }
|
|
527
|
+
const errorMsg = parsedErr?.error?.message || errBody || res.statusText;
|
|
528
|
+
const errObj = new Error(`OpenAI API error (${res.status}): ${errorMsg}`);
|
|
529
|
+
errObj.status = res.status;
|
|
530
|
+
errObj.responseBody = errBody;
|
|
531
|
+
throw errObj;
|
|
532
|
+
}
|
|
533
|
+
const data = await res.json();
|
|
534
|
+
const text = data?.choices?.[0]?.message?.content?.trim() || '{}';
|
|
535
|
+
return extractJson(text);
|
|
536
|
+
}
|
|
537
|
+
catch (err) {
|
|
538
|
+
lastError = err;
|
|
539
|
+
if (!isRetryableError(err)) {
|
|
540
|
+
throw err;
|
|
541
|
+
}
|
|
542
|
+
retries--;
|
|
543
|
+
if (retries === 0)
|
|
544
|
+
throw err;
|
|
545
|
+
await new Promise(r => setTimeout(r, delay));
|
|
546
|
+
delay *= 2;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
throw lastError;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Direct Anthropic API provider supporting Claude 3.5 Sonnet, Claude 3.7 Sonnet, Claude 3.5 Haiku, etc.
|
|
554
|
+
*/
|
|
555
|
+
export class AnthropicApiProvider {
|
|
556
|
+
name = 'anthropic';
|
|
557
|
+
apiKey;
|
|
558
|
+
modelName;
|
|
559
|
+
baseUrl;
|
|
560
|
+
initialRetryDelay;
|
|
561
|
+
constructor(apiKey, modelName = process.env.ANTHROPIC_MODEL || 'claude-3-5-haiku-latest', baseUrl = process.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com/v1', initialRetryDelay = 2000) {
|
|
562
|
+
this.apiKey = apiKey;
|
|
563
|
+
this.modelName = modelName;
|
|
564
|
+
this.baseUrl = baseUrl.replace(/\/+$/, '');
|
|
565
|
+
this.initialRetryDelay = initialRetryDelay;
|
|
566
|
+
}
|
|
567
|
+
async generateJson(prompt) {
|
|
568
|
+
let retries = 3;
|
|
569
|
+
let delay = this.initialRetryDelay;
|
|
570
|
+
let lastError;
|
|
571
|
+
while (retries > 0) {
|
|
572
|
+
try {
|
|
573
|
+
const payload = {
|
|
574
|
+
model: this.modelName,
|
|
575
|
+
max_tokens: 4096,
|
|
576
|
+
system: 'You are an expert software architect and deterministic knowledge base synthesizer. You must respond with valid JSON only. Do not include markdown code fences, preambles, or explanations.',
|
|
577
|
+
messages: [
|
|
578
|
+
{
|
|
579
|
+
role: 'user',
|
|
580
|
+
content: prompt
|
|
581
|
+
}
|
|
582
|
+
]
|
|
583
|
+
};
|
|
584
|
+
const res = await fetch(`${this.baseUrl}/messages`, {
|
|
585
|
+
method: 'POST',
|
|
586
|
+
headers: {
|
|
587
|
+
'Content-Type': 'application/json',
|
|
588
|
+
'x-api-key': this.apiKey,
|
|
589
|
+
'anthropic-version': '2023-06-01'
|
|
590
|
+
},
|
|
591
|
+
body: JSON.stringify(payload)
|
|
592
|
+
});
|
|
593
|
+
if (!res.ok) {
|
|
594
|
+
const errBody = await res.text().catch(() => '');
|
|
595
|
+
let parsedErr;
|
|
596
|
+
try {
|
|
597
|
+
parsedErr = JSON.parse(errBody);
|
|
598
|
+
}
|
|
599
|
+
catch { }
|
|
600
|
+
const errorMsg = parsedErr?.error?.message || errBody || res.statusText;
|
|
601
|
+
const errObj = new Error(`Anthropic API error (${res.status}): ${errorMsg}`);
|
|
602
|
+
errObj.status = res.status;
|
|
603
|
+
errObj.responseBody = errBody;
|
|
604
|
+
throw errObj;
|
|
605
|
+
}
|
|
606
|
+
const data = await res.json();
|
|
607
|
+
const text = data?.content?.[0]?.text?.trim() || '{}';
|
|
608
|
+
return extractJson(text);
|
|
609
|
+
}
|
|
610
|
+
catch (err) {
|
|
611
|
+
lastError = err;
|
|
612
|
+
if (!isRetryableError(err)) {
|
|
613
|
+
throw err;
|
|
614
|
+
}
|
|
615
|
+
retries--;
|
|
616
|
+
if (retries === 0)
|
|
617
|
+
throw err;
|
|
618
|
+
await new Promise(r => setTimeout(r, delay));
|
|
619
|
+
delay *= 2;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
throw lastError;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Universal OpenAI-compatible provider supporting DeepSeek, Groq, Mistral, Ollama, OpenRouter, and custom endpoints.
|
|
627
|
+
*/
|
|
628
|
+
export class OpenAiCompatibleProvider {
|
|
629
|
+
name;
|
|
630
|
+
apiKey;
|
|
631
|
+
modelName;
|
|
632
|
+
baseUrl;
|
|
633
|
+
initialRetryDelay;
|
|
634
|
+
constructor(providerName, apiKey, modelName, baseUrl, initialRetryDelay = 2000) {
|
|
635
|
+
this.name = providerName;
|
|
636
|
+
this.apiKey = apiKey;
|
|
637
|
+
this.modelName = modelName;
|
|
638
|
+
this.baseUrl = baseUrl.replace(/\/+$/, '');
|
|
639
|
+
this.initialRetryDelay = initialRetryDelay;
|
|
640
|
+
}
|
|
641
|
+
async generateJson(prompt) {
|
|
642
|
+
let retries = 3;
|
|
643
|
+
let delay = this.initialRetryDelay;
|
|
644
|
+
let lastError;
|
|
645
|
+
let tryJsonFormat = true;
|
|
646
|
+
while (retries > 0) {
|
|
647
|
+
try {
|
|
648
|
+
const payload = {
|
|
649
|
+
model: this.modelName,
|
|
650
|
+
messages: [
|
|
651
|
+
{
|
|
652
|
+
role: 'system',
|
|
653
|
+
content: 'You are an expert software architect and deterministic knowledge base synthesizer. You must respond with valid JSON only. Do not include markdown code fences, preambles, or explanations.'
|
|
654
|
+
},
|
|
655
|
+
{
|
|
656
|
+
role: 'user',
|
|
657
|
+
content: prompt
|
|
658
|
+
}
|
|
659
|
+
]
|
|
660
|
+
};
|
|
661
|
+
if (tryJsonFormat) {
|
|
662
|
+
payload.response_format = { type: 'json_object' };
|
|
663
|
+
}
|
|
664
|
+
const url = this.baseUrl.endsWith('/chat/completions')
|
|
665
|
+
? this.baseUrl
|
|
666
|
+
: `${this.baseUrl}/chat/completions`;
|
|
667
|
+
const headers = {
|
|
668
|
+
'Content-Type': 'application/json'
|
|
669
|
+
};
|
|
670
|
+
if (this.apiKey && this.apiKey !== 'none' && this.apiKey !== 'ollama') {
|
|
671
|
+
headers['Authorization'] = `Bearer ${this.apiKey}`;
|
|
672
|
+
}
|
|
673
|
+
const res = await fetch(url, {
|
|
674
|
+
method: 'POST',
|
|
675
|
+
headers,
|
|
676
|
+
body: JSON.stringify(payload)
|
|
677
|
+
});
|
|
678
|
+
if (!res.ok) {
|
|
679
|
+
const errBody = await res.text().catch(() => '');
|
|
680
|
+
let parsedErr;
|
|
681
|
+
try {
|
|
682
|
+
parsedErr = JSON.parse(errBody);
|
|
683
|
+
}
|
|
684
|
+
catch { }
|
|
685
|
+
const errorMsg = parsedErr?.error?.message || errBody || res.statusText;
|
|
686
|
+
// If provider failed because response_format is unsupported (some local models), retry without response_format
|
|
687
|
+
if (tryJsonFormat && (res.status === 400 || res.status === 422) && /response_format|schema/i.test(errorMsg)) {
|
|
688
|
+
tryJsonFormat = false;
|
|
689
|
+
continue;
|
|
690
|
+
}
|
|
691
|
+
const errObj = new Error(`${this.name} API error (${res.status}): ${errorMsg}`);
|
|
692
|
+
errObj.status = res.status;
|
|
693
|
+
errObj.responseBody = errBody;
|
|
694
|
+
throw errObj;
|
|
695
|
+
}
|
|
696
|
+
const data = await res.json();
|
|
697
|
+
const text = data?.choices?.[0]?.message?.content?.trim() || '{}';
|
|
698
|
+
return extractJson(text);
|
|
699
|
+
}
|
|
700
|
+
catch (err) {
|
|
701
|
+
lastError = err;
|
|
702
|
+
if (!isRetryableError(err)) {
|
|
703
|
+
throw err;
|
|
704
|
+
}
|
|
705
|
+
retries--;
|
|
706
|
+
if (retries === 0)
|
|
707
|
+
throw err;
|
|
708
|
+
await new Promise(r => setTimeout(r, delay));
|
|
709
|
+
delay *= 2;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
throw lastError;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* CLI provider delegating generation to the installed system Gemini CLI.
|
|
717
|
+
*/
|
|
718
|
+
export class GeminiCliProvider {
|
|
719
|
+
name = 'gemini-cli';
|
|
720
|
+
modelName;
|
|
721
|
+
constructor(modelName) {
|
|
722
|
+
this.modelName = modelName;
|
|
723
|
+
}
|
|
724
|
+
async generateJson(prompt) {
|
|
725
|
+
const rawOutput = await executeGeminiCli(prompt, this.modelName);
|
|
726
|
+
return extractJson(rawOutput);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* CLI provider delegating generation to Google Antigravity CLI (agy).
|
|
731
|
+
*/
|
|
732
|
+
export class AgyCliProvider {
|
|
733
|
+
name = 'agy-cli';
|
|
734
|
+
modelName;
|
|
735
|
+
constructor(modelName) {
|
|
736
|
+
this.modelName = modelName;
|
|
737
|
+
}
|
|
738
|
+
async generateJson(prompt) {
|
|
739
|
+
const rawOutput = await executeAgyCli(prompt, this.modelName);
|
|
740
|
+
return extractJson(rawOutput);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* Factory creating the appropriate LLMProvider based on configuration, model name, and available keys.
|
|
745
|
+
*/
|
|
746
|
+
export function createLLMProvider(options = {}) {
|
|
747
|
+
if (options.forceAgy || options.provider === 'agy' || options.provider === 'agy-cli') {
|
|
748
|
+
if (!isAgyCliAvailable()) {
|
|
749
|
+
throw new Error('Antigravity CLI execution was requested (--agy / --provider agy), but "agy" executable was not found on PATH.\n' +
|
|
750
|
+
'Ensure Google Antigravity CLI is installed and available on PATH.');
|
|
751
|
+
}
|
|
752
|
+
return new AgyCliProvider(options.model);
|
|
753
|
+
}
|
|
754
|
+
if (options.forceCli || options.provider === 'cli') {
|
|
755
|
+
if (isGeminiCliAvailable()) {
|
|
756
|
+
return new GeminiCliProvider(options.model);
|
|
757
|
+
}
|
|
758
|
+
if (isAgyCliAvailable()) {
|
|
759
|
+
return new AgyCliProvider(options.model);
|
|
760
|
+
}
|
|
761
|
+
throw new Error('CLI execution was requested (--cli), but neither "gemini" nor "agy" executable was found on PATH.\n' +
|
|
762
|
+
'Install Gemini CLI via: npm install -g @google/gemini-cli\n' +
|
|
763
|
+
'Or Antigravity CLI (agy), or run with an API key via GEMINI_API_KEY in .env.');
|
|
764
|
+
}
|
|
765
|
+
// Determine target provider
|
|
766
|
+
let targetProvider = (options.provider || process.env.AKB_PROVIDER || '').toLowerCase().trim();
|
|
767
|
+
// Map common aliases
|
|
768
|
+
if (targetProvider === 'google')
|
|
769
|
+
targetProvider = 'gemini';
|
|
770
|
+
if (targetProvider === 'chatgpt')
|
|
771
|
+
targetProvider = 'openai';
|
|
772
|
+
if (targetProvider === 'claude')
|
|
773
|
+
targetProvider = 'anthropic';
|
|
774
|
+
if (targetProvider === 'local')
|
|
775
|
+
targetProvider = 'ollama';
|
|
776
|
+
if (targetProvider === 'antigravity')
|
|
777
|
+
targetProvider = 'agy';
|
|
778
|
+
if (targetProvider === 'agy' || targetProvider === 'agy-cli') {
|
|
779
|
+
if (!isAgyCliAvailable()) {
|
|
780
|
+
throw new Error('Antigravity CLI execution was requested (--provider agy), but "agy" executable was not found on PATH.\n' +
|
|
781
|
+
'Ensure Google Antigravity CLI is installed and available on PATH.');
|
|
782
|
+
}
|
|
783
|
+
return new AgyCliProvider(options.model);
|
|
784
|
+
}
|
|
785
|
+
// If no explicit provider, infer from model name
|
|
786
|
+
if (!targetProvider && options.model) {
|
|
787
|
+
const m = options.model.toLowerCase();
|
|
788
|
+
if (/^(?:gpt-|o1-|o3-|chatgpt)/i.test(m)) {
|
|
789
|
+
targetProvider = 'openai';
|
|
790
|
+
}
|
|
791
|
+
else if (/^claude-/i.test(m)) {
|
|
792
|
+
targetProvider = 'anthropic';
|
|
793
|
+
}
|
|
794
|
+
else if (/^deepseek-/i.test(m)) {
|
|
795
|
+
targetProvider = 'deepseek';
|
|
796
|
+
}
|
|
797
|
+
else if (/^gemini-/i.test(m)) {
|
|
798
|
+
targetProvider = 'gemini';
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
// If still undetermined, infer from available environment variables
|
|
802
|
+
if (!targetProvider) {
|
|
803
|
+
if (process.env.OPENAI_API_KEY && !process.env.GEMINI_API_KEY && !process.env.GOOGLE_API_KEY) {
|
|
804
|
+
targetProvider = 'openai';
|
|
805
|
+
}
|
|
806
|
+
else if (process.env.ANTHROPIC_API_KEY && !process.env.GEMINI_API_KEY && !process.env.GOOGLE_API_KEY) {
|
|
807
|
+
targetProvider = 'anthropic';
|
|
808
|
+
}
|
|
809
|
+
else if (process.env.DEEPSEEK_API_KEY && !process.env.GEMINI_API_KEY && !process.env.GOOGLE_API_KEY) {
|
|
810
|
+
targetProvider = 'deepseek';
|
|
811
|
+
}
|
|
812
|
+
else if (process.env.GROQ_API_KEY && !process.env.GEMINI_API_KEY && !process.env.GOOGLE_API_KEY) {
|
|
813
|
+
targetProvider = 'groq';
|
|
814
|
+
}
|
|
815
|
+
else {
|
|
816
|
+
targetProvider = 'gemini';
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
// Dispatch based on resolved provider
|
|
820
|
+
if (targetProvider === 'openai') {
|
|
821
|
+
const apiKey = resolveApiKey('openai', options.apiKey);
|
|
822
|
+
if (!apiKey) {
|
|
823
|
+
throw new Error('OPENAI_API_KEY environment variable is not set and no API key was provided.\n' +
|
|
824
|
+
'Please either set OPENAI_API_KEY in your environment, pass --api-key <key>, or use --provider gemini.');
|
|
825
|
+
}
|
|
826
|
+
return new OpenAiApiProvider(apiKey, options.model, options.baseUrl, options.initialRetryDelay);
|
|
827
|
+
}
|
|
828
|
+
if (targetProvider === 'anthropic') {
|
|
829
|
+
const apiKey = resolveApiKey('anthropic', options.apiKey);
|
|
830
|
+
if (!apiKey) {
|
|
831
|
+
throw new Error('ANTHROPIC_API_KEY environment variable is not set and no API key was provided.\n' +
|
|
832
|
+
'Please either set ANTHROPIC_API_KEY in your environment, pass --api-key <key>, or use --provider gemini.');
|
|
833
|
+
}
|
|
834
|
+
return new AnthropicApiProvider(apiKey, options.model, options.baseUrl, options.initialRetryDelay);
|
|
835
|
+
}
|
|
836
|
+
if (targetProvider === 'deepseek') {
|
|
837
|
+
const apiKey = resolveApiKey('deepseek', options.apiKey);
|
|
838
|
+
if (!apiKey) {
|
|
839
|
+
throw new Error('DEEPSEEK_API_KEY environment variable is not set and no API key was provided.\n' +
|
|
840
|
+
'Please set DEEPSEEK_API_KEY in your environment or pass --api-key <key>.');
|
|
841
|
+
}
|
|
842
|
+
return new OpenAiCompatibleProvider('deepseek', apiKey, options.model || process.env.DEEPSEEK_MODEL || 'deepseek-chat', options.baseUrl || process.env.DEEPSEEK_BASE_URL || 'https://api.deepseek.com', options.initialRetryDelay);
|
|
843
|
+
}
|
|
844
|
+
if (targetProvider === 'groq') {
|
|
845
|
+
const apiKey = resolveApiKey('groq', options.apiKey);
|
|
846
|
+
if (!apiKey) {
|
|
847
|
+
throw new Error('GROQ_API_KEY environment variable is not set and no API key was provided.\n' +
|
|
848
|
+
'Please set GROQ_API_KEY in your environment or pass --api-key <key>.');
|
|
849
|
+
}
|
|
850
|
+
return new OpenAiCompatibleProvider('groq', apiKey, options.model || process.env.GROQ_MODEL || 'llama-3.3-70b-versatile', options.baseUrl || process.env.GROQ_BASE_URL || 'https://api.groq.com/openai/v1', options.initialRetryDelay);
|
|
851
|
+
}
|
|
852
|
+
if (targetProvider === 'ollama') {
|
|
853
|
+
const apiKey = resolveApiKey('ollama', options.apiKey) || 'ollama';
|
|
854
|
+
const baseUrl = options.baseUrl || process.env.OLLAMA_BASE_URL || 'http://localhost:11434/v1';
|
|
855
|
+
return new OpenAiCompatibleProvider('ollama', apiKey, options.model || process.env.OLLAMA_MODEL || 'qwen2.5-coder', baseUrl, options.initialRetryDelay);
|
|
856
|
+
}
|
|
857
|
+
if (targetProvider === 'openai-compatible') {
|
|
858
|
+
const apiKey = resolveApiKey('custom', options.apiKey) || 'custom';
|
|
859
|
+
const baseUrl = options.baseUrl || process.env.CUSTOM_LLM_BASE_URL || 'http://localhost:8000/v1';
|
|
860
|
+
return new OpenAiCompatibleProvider('openai-compatible', apiKey, options.model || 'default', baseUrl, options.initialRetryDelay);
|
|
861
|
+
}
|
|
862
|
+
// Default: Gemini provider
|
|
863
|
+
const apiKey = resolveApiKey('gemini', options.apiKey);
|
|
864
|
+
if (apiKey) {
|
|
865
|
+
return new GeminiApiProvider(apiKey, options.model, options.initialRetryDelay, options.baseUrl);
|
|
866
|
+
}
|
|
867
|
+
// If in automated test environment (Vitest) without explicit key or --cli, require key
|
|
868
|
+
if (process.env.VITEST && !process.env.AKB_ALLOW_CLI_IN_TEST) {
|
|
869
|
+
throw new Error('GEMINI_API_KEY environment variable is not set and no API key was provided.');
|
|
870
|
+
}
|
|
871
|
+
// Fallback to installed Gemini CLI if available
|
|
872
|
+
if (isGeminiCliAvailable()) {
|
|
873
|
+
return new GeminiCliProvider(options.model);
|
|
874
|
+
}
|
|
875
|
+
throw new Error('GEMINI_API_KEY environment variable is not set and no API key was provided.\n' +
|
|
876
|
+
'Please either:\n' +
|
|
877
|
+
' 1. Set GEMINI_API_KEY in your .env file or environment, or\n' +
|
|
878
|
+
' 2. Install and log in with the Gemini CLI (npm i -g @google/gemini-cli && gemini), or\n' +
|
|
879
|
+
' 3. Pass a different provider: --provider openai, --provider anthropic, --provider deepseek, etc.\n');
|
|
880
|
+
}
|