omnitrix 0.0.0-stage → 0.5.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.
@@ -0,0 +1,432 @@
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { getProvider } from '../providers.js';
6
+ import { redact, resolveKey } from '../store.js';
7
+ import { DriverError } from '../types.js';
8
+ const SAFE_ARG = /^[\w.:@\/=,+\-]+$/;
9
+ function lines(stdout) {
10
+ const out = [];
11
+ for (const line of stdout.split(/\r?\n/)) {
12
+ const t = line.trim();
13
+ if (!t.startsWith('{'))
14
+ continue;
15
+ try {
16
+ out.push(JSON.parse(t));
17
+ }
18
+ catch {
19
+ /* not JSON */
20
+ }
21
+ }
22
+ return out;
23
+ }
24
+ function lastJson(stdout) {
25
+ const all = lines(stdout);
26
+ if (all.length)
27
+ return all[all.length - 1];
28
+ const start = stdout.indexOf('{');
29
+ if (start >= 0) {
30
+ try {
31
+ return JSON.parse(stdout.slice(start));
32
+ }
33
+ catch {
34
+ /* fall through */
35
+ }
36
+ }
37
+ return undefined;
38
+ }
39
+ export const CLI_TOOLS = {
40
+ codex: {
41
+ id: 'codex',
42
+ command: 'codex',
43
+ profileEnv: 'CODEX_HOME',
44
+ args: ({ model, edit, cwd, outFile, effort }) => [
45
+ 'exec', '--json', '--skip-git-repo-check', '--ephemeral',
46
+ ...(effort ? ['-c', `model_reasoning_effort=${effort}`] : []),
47
+ // plain workspace-write still refuses file writes on Windows; --approve-for-me keeps that
48
+ // sandbox but lets Codex's own reviewer approve the edits instead of a human
49
+ ...(edit ? ['--approve-for-me'] : ['--sandbox', 'read-only']),
50
+ '-C', cwd, '-o', outFile,
51
+ ...(model && model !== 'default' ? ['-m', model] : []),
52
+ '-',
53
+ ],
54
+ parse(stdout, outFile) {
55
+ const events = lines(stdout);
56
+ let inputTokens = 0;
57
+ let outputTokens = 0;
58
+ let error;
59
+ let lastMessage = '';
60
+ for (const e of events) {
61
+ if (e.type === 'turn.completed' && e.usage) {
62
+ inputTokens += Number(e.usage.input_tokens ?? 0);
63
+ outputTokens += Number(e.usage.output_tokens ?? 0) + Number(e.usage.reasoning_output_tokens ?? 0);
64
+ }
65
+ if (e.type === 'turn.failed')
66
+ error = e.error?.message ?? 'turn failed';
67
+ if (e.type === 'error')
68
+ error = e.message ?? 'error';
69
+ if (e.type === 'item.completed' && e.item?.type === 'agent_message' && typeof e.item.text === 'string')
70
+ lastMessage = e.item.text;
71
+ }
72
+ let text = lastMessage;
73
+ try {
74
+ text = fs.readFileSync(outFile, 'utf8') || lastMessage;
75
+ }
76
+ catch {
77
+ /* -o file missing: use the streamed message */
78
+ }
79
+ return { text, inputTokens, outputTokens, error: text ? undefined : error };
80
+ },
81
+ loginArgs: ['login'],
82
+ initProfile(dir) {
83
+ // keep the login inside this folder instead of the shared OS keychain
84
+ const file = path.join(dir, 'config.toml');
85
+ if (!fs.existsSync(file))
86
+ fs.writeFileSync(file, 'cli_auth_credentials_store = "file"\n');
87
+ },
88
+ },
89
+ claude: {
90
+ id: 'claude',
91
+ command: 'claude',
92
+ profileEnv: 'CLAUDE_CONFIG_DIR',
93
+ args: ({ model, edit }) => [
94
+ // documented as `cat file | claude -p '...'`: the short prompt here, the task on standard input
95
+ '-p', 'Follow the instructions given on standard input.',
96
+ '--output-format', 'json', '--permission-prompts', 'none',
97
+ '--permission-mode', edit ? 'acceptEdits' : 'dontAsk',
98
+ '--allowedTools', edit ? 'Read,Edit,Write,Glob,Grep' : 'Read,Glob,Grep',
99
+ ...(model && model !== 'default' ? ['--model', model] : []),
100
+ ],
101
+ parse(stdout) {
102
+ const j = lastJson(stdout);
103
+ if (!j)
104
+ return { text: '', inputTokens: 0, outputTokens: 0, error: 'no JSON result from claude' };
105
+ const u = j.usage ?? {};
106
+ const text = typeof j.result === 'string' ? j.result : '';
107
+ return {
108
+ text,
109
+ inputTokens: Number(u.input_tokens ?? 0) + Number(u.cache_read_input_tokens ?? 0) + Number(u.cache_creation_input_tokens ?? 0),
110
+ outputTokens: Number(u.output_tokens ?? 0),
111
+ costUsd: typeof j.total_cost_usd === 'number' ? j.total_cost_usd : undefined,
112
+ error: j.is_error ? text || j.subtype || 'claude returned an error' : undefined,
113
+ };
114
+ },
115
+ loginArgs: ['auth', 'login'],
116
+ env(account) {
117
+ // Without a key the subscription login in the profile folder is used.
118
+ // With a key and base URL this drives a coding plan (GLM, Kimi, MiniMax...) through Claude Code.
119
+ const key = resolveKey(account);
120
+ return {
121
+ ANTHROPIC_API_KEY: key && !account.baseUrl ? key : undefined,
122
+ ANTHROPIC_AUTH_TOKEN: key && account.baseUrl ? key : undefined,
123
+ ANTHROPIC_BASE_URL: account.baseUrl,
124
+ };
125
+ },
126
+ },
127
+ gemini: {
128
+ id: 'gemini',
129
+ command: 'gemini',
130
+ profileEnv: 'GEMINI_CLI_HOME',
131
+ args: ({ model, edit }) => [
132
+ '-p', 'Follow the instructions given on standard input.',
133
+ '--output-format', 'json',
134
+ '--approval-mode', edit ? 'auto_edit' : 'default',
135
+ ...(model && model !== 'default' ? ['-m', model] : []),
136
+ ],
137
+ parse: parseGeminiStyle,
138
+ loginArgs: [],
139
+ env: (account) => ({ GEMINI_API_KEY: resolveKey(account) }),
140
+ },
141
+ qwen: {
142
+ id: 'qwen',
143
+ command: 'qwen',
144
+ profileEnv: 'HOME',
145
+ args: ({ model, edit }) => [
146
+ '-p', 'Follow the instructions given on standard input.',
147
+ '--output-format', 'json',
148
+ // Qwen Code spells this mode "auto-edit"; Gemini CLI spells it "auto_edit"
149
+ '--approval-mode', edit ? 'auto-edit' : 'default',
150
+ ...(model && model !== 'default' ? ['-m', model] : []),
151
+ ],
152
+ parse: parseGeminiStyle,
153
+ loginArgs: [],
154
+ env: (account) => ({ OPENAI_API_KEY: resolveKey(account), OPENAI_BASE_URL: account.baseUrl }),
155
+ },
156
+ agy: {
157
+ id: 'agy',
158
+ command: 'agy',
159
+ profileEnv: 'HOME',
160
+ // Antigravity has no --approval-mode; its documented --mode accept-edits lets a code task change files
161
+ args: ({ model, edit }) => [
162
+ '-p', 'Follow the instructions given on standard input.',
163
+ '--output-format', 'json',
164
+ ...(edit ? ['--mode', 'accept-edits'] : []),
165
+ ...(model && model !== 'default' ? ['--model', model] : []),
166
+ ],
167
+ parse: parseGeminiStyle,
168
+ loginArgs: [],
169
+ },
170
+ opencode: {
171
+ id: 'opencode',
172
+ command: 'opencode',
173
+ profileEnv: 'HOME',
174
+ args: ({ model }) => ['run', ...(model && model !== 'default' ? ['--model', model] : [])],
175
+ parse: (stdout) => ({ text: stdout.trim(), inputTokens: 0, outputTokens: 0 }),
176
+ loginArgs: ['auth', 'login'],
177
+ },
178
+ };
179
+ /** The JSON answer: Qwen Code prints one list of messages, ending in the "result"; others print objects. */
180
+ function answerJson(stdout) {
181
+ const t = stdout.trim();
182
+ if (t.startsWith('[')) {
183
+ try {
184
+ const all = JSON.parse(t);
185
+ if (Array.isArray(all))
186
+ return [...all].reverse().find((m) => m?.type === 'result') ?? all.at(-1);
187
+ }
188
+ catch {
189
+ // not one JSON list; read it line by line below
190
+ }
191
+ }
192
+ return lastJson(stdout);
193
+ }
194
+ function parseGeminiStyle(stdout) {
195
+ const j = answerJson(stdout);
196
+ if (!j)
197
+ return { text: stdout.trim(), inputTokens: 0, outputTokens: 0 };
198
+ let inputTokens = Number(j.usage?.input_tokens ?? 0);
199
+ let outputTokens = Number(j.usage?.output_tokens ?? 0);
200
+ const models = j.stats?.models;
201
+ if (models && typeof models === 'object') {
202
+ for (const m of Object.values(models)) {
203
+ inputTokens += Number(m?.tokens?.prompt ?? m?.tokens?.input ?? 0);
204
+ outputTokens += Number(m?.tokens?.candidates ?? m?.tokens?.output ?? 0);
205
+ }
206
+ }
207
+ const text = typeof j.response === 'string' ? j.response : typeof j.result === 'string' ? j.result : '';
208
+ const error = j.error ? (typeof j.error === 'string' ? j.error : j.error.message ?? 'error') : j.status && j.status !== 'success' && !text ? String(j.status) : undefined;
209
+ return { text, inputTokens, outputTokens, error };
210
+ }
211
+ /** Find how to start a command. On Windows, npm installs ".cmd" shims; we run the script inside with node directly. */
212
+ export function resolveCommand(command) {
213
+ if (process.platform !== 'win32') {
214
+ const r = spawnSync('sh', ['-c', `command -v ${command}`], { encoding: 'utf8' });
215
+ const found = r.stdout?.trim();
216
+ return found ? { file: found, prefix: [], shell: false } : undefined;
217
+ }
218
+ const r = spawnSync('where', [command], { encoding: 'utf8' });
219
+ // `where` looks in the current folder before PATH, so a cloned repo could plant its own codex.cmd.
220
+ const cwd = path.resolve(process.cwd()).toLowerCase();
221
+ const hits = (r.stdout ?? '').split(/\r?\n/).map((s) => s.trim()).filter(Boolean)
222
+ .filter((h) => path.dirname(path.resolve(h)).toLowerCase() !== cwd);
223
+ const exe = hits.find((h) => /\.exe$/i.test(h));
224
+ if (exe)
225
+ return { file: exe, prefix: [], shell: false };
226
+ const cmd = hits.find((h) => /\.cmd$/i.test(h));
227
+ if (!cmd)
228
+ return undefined;
229
+ try {
230
+ const shim = fs.readFileSync(cmd, 'utf8');
231
+ const m = shim.match(/"%dp0%\\([^"]+\.(?:js|cjs|mjs))"/i);
232
+ if (m) {
233
+ const script = path.resolve(path.dirname(cmd), m[1]);
234
+ if (fs.existsSync(script))
235
+ return { file: process.execPath, prefix: [script], shell: false };
236
+ }
237
+ }
238
+ catch {
239
+ /* fall back to the shell */
240
+ }
241
+ return { file: cmd, prefix: [], shell: true };
242
+ }
243
+ /** Text without the escape sequences that terminals use for colours, cursor moves and titles. */
244
+ export function stripTerminalCodes(text) {
245
+ return text.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(\u0007|\u001b\\)|\u001b[@-Z\\-_]/g, '');
246
+ }
247
+ /**
248
+ * How to start a resolved program. A .cmd program needs cmd.exe: omnitrix starts cmd.exe itself, from an
249
+ * absolute path, with a fixed command text in which the program path arrives in a variable and every
250
+ * argument is quoted, so spaces and & | < > stay text. Inside quotes cmd.exe still reads " and %, so an
251
+ * argument with either, or with a line break, is refused rather than run; /v:off keeps ! as text.
252
+ */
253
+ export function launch(resolved, args) {
254
+ const all = [...resolved.prefix, ...args];
255
+ // Windows looks for programs in the current folder first, which may be a worker's folder
256
+ const base = process.platform === 'win32' ? { NoDefaultCurrentDirectoryInExePath: '1' } : {};
257
+ if (!resolved.shell)
258
+ return { file: resolved.file, args: all, verbatim: false, env: base };
259
+ if (all.some((a) => /["%\r\n]/.test(a))) {
260
+ return { file: '', args: [], verbatim: true, env: {}, error: 'an argument contains a quotation mark, a percent sign or a line break, which cmd.exe could read as part of a command' };
261
+ }
262
+ const line = ['%OMNITRIX_PROGRAM%', ...all].map((a) => `"${a}"`).join(' ');
263
+ const comspec = process.env.ComSpec && path.isAbsolute(process.env.ComSpec) ? process.env.ComSpec : path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'cmd.exe');
264
+ return { file: comspec, args: ['/d', '/v:off', '/s', '/c', `"${line}"`], verbatim: true, env: { ...base, OMNITRIX_PROGRAM: resolved.file } };
265
+ }
266
+ export function profileEnv(tool, dir) {
267
+ if (tool.profileEnv === 'HOME')
268
+ return { HOME: dir, USERPROFILE: dir };
269
+ return { [tool.profileEnv]: dir };
270
+ }
271
+ // Names that hold a secret: an agent CLI runs what a prompt tells it to, so it must never see them.
272
+ const SECRET_NAME = /(KEY|TOKEN|SECRET|PASSW|CREDENTIAL|_AUTH|AUTH_|COOKIE|SESSION_ID)/i;
273
+ // Settings that would point a CLI at the parent's provider or session instead of the account's own login.
274
+ const PARENT_SETTING = /^(.*_BASE_URL|CLAUDECODE|CLAUDE_CODE_.*|GOOGLE_GENAI_USE_VERTEXAI|GOOGLE_CLOUD_PROJECT|GOOGLE_CLOUD_LOCATION|CODEX_HOME|GEMINI_CLI_.*)$/i;
275
+ /**
276
+ * The environment for an agent CLI: the parent's, without anything that looks like a credential or a
277
+ * provider setting, then the tool's own variables (its profile folder, or the account's own key).
278
+ */
279
+ export function childEnv(parent, toolEnv) {
280
+ const env = {};
281
+ for (const [k, v] of Object.entries(parent)) {
282
+ // a database address or proxy setting can carry a password inside it, such as postgres://user:pw@host
283
+ if (v === undefined || SECRET_NAME.test(k) || PARENT_SETTING.test(k) || /:\/\/[^/\s:@]*:[^/\s@]+@/.test(v))
284
+ continue;
285
+ env[k] = v;
286
+ }
287
+ for (const [k, v] of Object.entries(toolEnv))
288
+ if (v !== undefined)
289
+ env[k] = v;
290
+ return env;
291
+ }
292
+ export function killTree(pid) {
293
+ if (!pid)
294
+ return;
295
+ try {
296
+ if (process.platform === 'win32')
297
+ spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
298
+ else
299
+ process.kill(-pid, 'SIGKILL');
300
+ }
301
+ catch {
302
+ /* already gone */
303
+ }
304
+ }
305
+ export function classifyCliError(text) {
306
+ const t = text.toLowerCase();
307
+ // a prompt that is too long is the task's problem, wherever it ran
308
+ if (/(context length|context window|too many tokens|prompt is too long|maximum.{0,20}tokens)/.test(t))
309
+ return 'bad_request';
310
+ // "rate limit exceeded" is a short wait, not a used-up plan, so it is checked first
311
+ if (/(rate limit|rate-limit|too many requests|\b429\b)/.test(t))
312
+ return 'rate_limit';
313
+ // "insufficient permissions" is a login problem, not a used-up plan
314
+ if (/(not logged in|login|unauthori[sz]ed|\b401\b|\b403\b|authenticat|api key|permission)/.test(t))
315
+ return 'auth';
316
+ if (/(usage limit|quota|exceeded|out of credits|insufficient|limit reached|hit your limit)/.test(t))
317
+ return 'quota';
318
+ return 'unknown';
319
+ }
320
+ const MAX_OUTPUT = 20 * 1024 * 1024;
321
+ export async function runCli(req, edit) {
322
+ const { account } = req;
323
+ const tool = CLI_TOOLS[providerTool(account.provider)];
324
+ if (!tool)
325
+ throw new DriverError(`unknown CLI tool for provider ${account.provider}`, 'bad_request');
326
+ if (req.model && !SAFE_ARG.test(req.model))
327
+ throw new DriverError(`unsafe model name: ${req.model}`, 'bad_request');
328
+ const resolved = resolveCommand(tool.command);
329
+ if (!resolved)
330
+ throw new DriverError(`"${tool.command}" is not installed or not on PATH`, 'auth');
331
+ const tempCwd = req.cwd ? undefined : fs.mkdtempSync(path.join(os.tmpdir(), 'omnitrix-'));
332
+ const cwd = req.cwd ?? tempCwd;
333
+ const outFile = path.join(os.tmpdir(), `omnitrix-out-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`);
334
+ const start = launch(resolved, tool.args({ model: req.model, edit, cwd, outFile, effort: req.effort }));
335
+ if (start.error) {
336
+ if (tempCwd)
337
+ fs.rmSync(tempCwd, { recursive: true, force: true });
338
+ throw new DriverError(`cannot start ${tool.command} safely: ${start.error}`, 'bad_request');
339
+ }
340
+ // never let the parent's keys leak into a worker, which may run whatever a prompt asks
341
+ const env = childEnv(process.env, { ...(account.profileDir ? profileEnv(tool, account.profileDir) : {}), ...(tool.env?.(account) ?? {}), ...start.env });
342
+ const fullPrompt = req.system ? `${req.system}\n\n${req.prompt}` : req.prompt;
343
+ return await new Promise((resolve, reject) => {
344
+ const child = spawn(start.file, start.args, {
345
+ cwd,
346
+ env: env,
347
+ windowsVerbatimArguments: start.verbatim,
348
+ windowsHide: true,
349
+ detached: process.platform !== 'win32',
350
+ stdio: ['pipe', 'pipe', 'pipe'],
351
+ });
352
+ let stdout = '';
353
+ let stderr = '';
354
+ let finished = false;
355
+ const finish = (fn) => {
356
+ if (finished)
357
+ return;
358
+ finished = true;
359
+ clearTimeout(timer);
360
+ req.signal?.removeEventListener('abort', onAbort);
361
+ fs.rm(outFile, { force: true }, () => { });
362
+ if (tempCwd)
363
+ fs.rm(tempCwd, { recursive: true, force: true }, () => { });
364
+ fn();
365
+ };
366
+ const timer = setTimeout(() => {
367
+ killTree(child.pid);
368
+ finish(() => reject(new DriverError(`${tool.command} did not finish in ${Math.round(req.timeoutMs / 1000)}s`, 'timeout')));
369
+ }, req.timeoutMs);
370
+ const onAbort = () => {
371
+ killTree(child.pid);
372
+ finish(() => reject(new DriverError('cancelled', 'cancelled')));
373
+ };
374
+ req.signal?.addEventListener('abort', onAbort, { once: true });
375
+ // decoded as one stream, so a character split across two chunks stays whole
376
+ child.stdout.setEncoding('utf8');
377
+ child.stderr.setEncoding('utf8');
378
+ child.stdout.on('data', (d) => {
379
+ if (stdout.length < MAX_OUTPUT)
380
+ stdout += d;
381
+ });
382
+ child.stderr.on('data', (d) => {
383
+ if (stderr.length < 200_000)
384
+ stderr += d;
385
+ });
386
+ child.on('error', (err) => finish(() => reject(new DriverError(`cannot start ${tool.command}: ${err.message}`, 'network'))));
387
+ child.on('close', (code) => {
388
+ // read the -o file before finish() deletes it
389
+ let parsed;
390
+ try {
391
+ parsed = tool.parse(stdout, outFile);
392
+ }
393
+ catch (err) {
394
+ parsed = { text: '', inputTokens: 0, outputTokens: 0, error: String(err) };
395
+ }
396
+ finish(() => {
397
+ // an agent that edited files may finish without a closing message; the diff is the result then
398
+ const editedQuietly = edit && code === 0 && !parsed.error;
399
+ // text from a tool that then crashed may be cut off, so only a clean exit counts
400
+ if ((parsed.text && !parsed.error && code === 0) || editedQuietly) {
401
+ resolve({ text: parsed.text || '(no summary from the agent; see the diff)', inputTokens: parsed.inputTokens, outputTokens: parsed.outputTokens, costUsd: parsed.costUsd });
402
+ return;
403
+ }
404
+ const detail = redact(stripTerminalCodes((parsed.error ?? '') + '\n' + stderr.slice(-1500) + (parsed.text ? '' : '\n' + stdout.slice(-500)))).trim();
405
+ reject(new DriverError(`${tool.command} exited with code ${code}: ${detail || 'no output'}`, classifyCliError(detail)));
406
+ });
407
+ });
408
+ child.stdin.on('error', () => {
409
+ /* the tool may exit before reading stdin; the close handler reports it */
410
+ });
411
+ child.stdin.end(fullPrompt);
412
+ });
413
+ }
414
+ /** Which CLI tool a provider runs, from the provider catalog. */
415
+ export function providerTool(provider) {
416
+ return getProvider(provider)?.cli ?? provider;
417
+ }
418
+ /** Run the tool's own login inside the account's profile folder, in this terminal. */
419
+ export function loginCli(account) {
420
+ const tool = CLI_TOOLS[providerTool(account.provider)];
421
+ if (!tool)
422
+ throw new Error(`unknown CLI tool for provider ${account.provider}`);
423
+ const resolved = resolveCommand(tool.command);
424
+ if (!resolved)
425
+ throw new Error(`"${tool.command}" is not installed or not on PATH`);
426
+ const start = launch(resolved, tool.loginArgs);
427
+ if (start.error)
428
+ throw new Error(`cannot start ${tool.command} safely: ${start.error}`);
429
+ const env = childEnv(process.env, { ...(account.profileDir ? profileEnv(tool, account.profileDir) : {}), ...start.env });
430
+ const r = spawnSync(start.file, start.args, { stdio: 'inherit', env, windowsVerbatimArguments: start.verbatim });
431
+ return r.status ?? 1;
432
+ }
@@ -0,0 +1,214 @@
1
+ // Shared pieces for the API drivers: requests with a timeout, and turning provider errors and
2
+ // rate-limit headers into something the router can act on.
3
+ import { redact } from '../store.js';
4
+ import { DriverError } from '../types.js';
5
+ /**
6
+ * Why an account has no key, in words that lead to the fix. A key variable set in a terminal is not seen by
7
+ * omnitrix when Claude Code started it before the variable existed, which `omnitrix doctor` in that
8
+ * terminal cannot show.
9
+ */
10
+ export function missingKey(account) {
11
+ if (account.apiKey?.startsWith('env:')) {
12
+ const name = account.apiKey.slice(4);
13
+ return `no API key for ${account.id}: ${name} is not set where omnitrix runs. If it is set in your terminal, restart Claude Code, which passes on only the variables that existed when it started`;
14
+ }
15
+ if (account.apiKey === 'secret')
16
+ return `no API key for ${account.id}: no key is saved for it; save one with "omnitrix set ${account.id} --key-env NAME"`;
17
+ return `no API key for ${account.id}: none is set; use "omnitrix set ${account.id} --key-env NAME"`;
18
+ }
19
+ export function classifyStatus(status, body) {
20
+ const text = body.toLowerCase();
21
+ if (status === 401 || status === 403)
22
+ return 'auth';
23
+ if (status === 402)
24
+ return 'quota';
25
+ if (status === 429) {
26
+ // "limit: 0" means the plan includes no allowance for this model at all (Gemini's free tier and Pro
27
+ // models, for example). That is the model's problem, not a sign that the whole account is used up.
28
+ if (/limit: 0(?![\d.])/.test(text))
29
+ return 'model_gone';
30
+ // some providers use 429 for "you are out of credits" as well as "slow down"
31
+ return /(quota|insufficient|exceeded your current|billing|credit|balance)/.test(text) ? 'quota' : 'rate_limit';
32
+ }
33
+ if (status === 408)
34
+ return 'timeout';
35
+ if (status >= 500)
36
+ return 'server';
37
+ // Providers retire models but keep listing them; this is the model's fault, not the task's. The text must
38
+ // name the model itself: "parameter X is not supported with this model" is about the request instead.
39
+ if ((status === 404 || status === 400) && retiredModel(text))
40
+ return 'model_gone';
41
+ if (status >= 400)
42
+ return 'bad_request';
43
+ return 'unknown';
44
+ }
45
+ function retiredModel(text) {
46
+ if (/(parameter|\bparam\b|argument|max_tokens|max_completion_tokens|reasoning_effort|temperature)/.test(text))
47
+ return false;
48
+ // NVIDIA lists models that a given key cannot call and answers them with "Function '<id>': Not found for account"
49
+ if (/function '[^']*': not found for account/.test(text))
50
+ return true;
51
+ const names = /(model_not_found|invalid_model|models\/|the model|model `|model ')/.test(text);
52
+ return names && /(no longer available|not found|does not exist|is not supported|deprecated|retired)/.test(text);
53
+ }
54
+ // Largest answers read from a provider; anything bigger is a broken or hostile server.
55
+ const MAX_ANSWER = 32 * 1024 * 1024;
56
+ const MAX_LIST = 4 * 1024 * 1024;
57
+ /** Read a response body, stopping once it passes `limit` bytes. */
58
+ export async function readCapped(res, limit) {
59
+ if (!res.body)
60
+ return '';
61
+ const reader = res.body.getReader();
62
+ const chunks = [];
63
+ let size = 0;
64
+ for (;;) {
65
+ const { done, value } = await reader.read();
66
+ if (done)
67
+ break;
68
+ size += value.byteLength;
69
+ if (size > limit) {
70
+ await reader.cancel().catch(() => undefined);
71
+ throw new DriverError(`the answer is too large (over ${Math.round(limit / 1024 / 1024)} MB)`, 'server', res.status);
72
+ }
73
+ chunks.push(value);
74
+ }
75
+ return Buffer.concat(chunks).toString('utf8');
76
+ }
77
+ // A provider asking for a longer wait than this is wrong or hostile; the account is looked at again after a day.
78
+ const MAX_WAIT = 24 * 3600_000;
79
+ /** Parse Retry-After (seconds or HTTP date) and the common reset headers, at most a day. */
80
+ export function retryAfterMs(headers, now = Date.now()) {
81
+ const ms = waitFromHeaders(headers, now);
82
+ return ms === undefined ? undefined : Math.min(ms, MAX_WAIT);
83
+ }
84
+ function waitFromHeaders(headers, now) {
85
+ const ra = headers.get('retry-after');
86
+ if (ra) {
87
+ const secs = Number(ra);
88
+ if (Number.isFinite(secs))
89
+ return Math.max(0, secs * 1000);
90
+ const date = Date.parse(ra);
91
+ if (Number.isFinite(date))
92
+ return Math.max(0, date - now);
93
+ }
94
+ const reset = headers.get('x-ratelimit-reset-requests') ?? headers.get('x-ratelimit-reset');
95
+ if (reset)
96
+ return parseDuration(reset, now);
97
+ return undefined;
98
+ }
99
+ /** "1m30s", "12.5s", "250ms", a unix timestamp, or plain seconds. */
100
+ export function parseDuration(value, now = Date.now()) {
101
+ const v = value.trim();
102
+ if (/^\d+(\.\d+)?$/.test(v)) {
103
+ const n = Number(v);
104
+ if (n > 1e12)
105
+ return Math.max(0, n - now); // ms timestamp
106
+ if (n > 1e9)
107
+ return Math.max(0, n * 1000 - now); // s timestamp
108
+ return n * 1000;
109
+ }
110
+ let total = 0;
111
+ let matched = false;
112
+ for (const m of v.matchAll(/(\d+(?:\.\d+)?)(ms|h|m|s)/g)) {
113
+ matched = true;
114
+ const n = Number(m[1]);
115
+ total += m[2] === 'h' ? n * 3600_000 : m[2] === 'm' ? n * 60_000 : m[2] === 's' ? n * 1000 : n;
116
+ }
117
+ if (matched)
118
+ return total;
119
+ const date = Date.parse(v);
120
+ return Number.isFinite(date) ? Math.max(0, date - now) : undefined;
121
+ }
122
+ export function readRateHeaders(headers, now = Date.now()) {
123
+ const num = (name) => {
124
+ const v = headers.get(name);
125
+ if (v === null)
126
+ return undefined;
127
+ const n = Number(v);
128
+ return Number.isFinite(n) ? n : undefined;
129
+ };
130
+ const remainingRequests = num('x-ratelimit-remaining-requests') ?? num('anthropic-ratelimit-requests-remaining') ?? num('x-ratelimit-remaining');
131
+ const remainingTokens = num('x-ratelimit-remaining-tokens') ?? num('anthropic-ratelimit-tokens-remaining');
132
+ if (remainingRequests === undefined && remainingTokens === undefined)
133
+ return undefined;
134
+ let resetAt;
135
+ const reset = headers.get('x-ratelimit-reset-requests') ?? headers.get('anthropic-ratelimit-requests-reset');
136
+ if (reset) {
137
+ const ms = parseDuration(reset, now);
138
+ if (ms !== undefined)
139
+ resetAt = now + ms;
140
+ }
141
+ return { remainingRequests, remainingTokens, resetAt };
142
+ }
143
+ /**
144
+ * What a provider said went wrong, on one line: the sentence from a JSON error such as Gemini's
145
+ * [{"error":{"message":"..."}}], or else the body itself. Only for people and Claude to read; the kind
146
+ * of error is decided from the whole body.
147
+ */
148
+ export function errorMessage(text) {
149
+ try {
150
+ let j = JSON.parse(text);
151
+ if (Array.isArray(j))
152
+ j = j[0];
153
+ const m = j?.error?.message ?? (typeof j?.error === 'string' ? j.error : undefined) ?? j?.message ?? j?.detail;
154
+ if (typeof m === 'string' && m.trim())
155
+ return m.replace(/\s+/g, ' ').trim();
156
+ }
157
+ catch {
158
+ // not JSON
159
+ }
160
+ return text.replace(/\s+/g, ' ').trim();
161
+ }
162
+ export async function postJson(url, headers, body, timeoutMs, signal) {
163
+ const ctrl = new AbortController();
164
+ const timer = setTimeout(() => ctrl.abort(new Error('timeout')), timeoutMs);
165
+ const onAbort = () => ctrl.abort(new Error('cancelled'));
166
+ signal?.addEventListener('abort', onAbort, { once: true });
167
+ try {
168
+ const res = await fetch(url, {
169
+ method: 'POST',
170
+ headers: { 'content-type': 'application/json', ...headers },
171
+ body: JSON.stringify(body),
172
+ signal: ctrl.signal,
173
+ // a redirect would carry the key and the prompt to another server
174
+ redirect: 'error',
175
+ });
176
+ const text = await readCapped(res, MAX_ANSWER);
177
+ if (!res.ok) {
178
+ const kind = classifyStatus(res.status, text);
179
+ throw new DriverError(`HTTP ${res.status}: ${redact(errorMessage(text).slice(0, 400))}`, kind, res.status, retryAfterMs(res.headers));
180
+ }
181
+ let json;
182
+ try {
183
+ json = JSON.parse(text);
184
+ }
185
+ catch {
186
+ throw new DriverError(`provider returned invalid JSON: ${redact(text.slice(0, 200))}`, 'server', res.status);
187
+ }
188
+ return { json, headers: res.headers };
189
+ }
190
+ catch (err) {
191
+ if (err instanceof DriverError)
192
+ throw err;
193
+ if (signal?.aborted)
194
+ throw new DriverError('cancelled', 'cancelled');
195
+ if (ctrl.signal.aborted)
196
+ throw new DriverError(`no answer after ${Math.round(timeoutMs / 1000)}s`, 'timeout');
197
+ const msg = err instanceof Error ? (err.cause instanceof Error ? `${err.message}: ${err.cause.message}` : err.message) : String(err);
198
+ throw new DriverError(`cannot reach ${new URL(url).host}: ${redact(msg)}`, 'network');
199
+ }
200
+ finally {
201
+ clearTimeout(timer);
202
+ signal?.removeEventListener('abort', onAbort);
203
+ }
204
+ }
205
+ export async function getJson(url, headers, timeoutMs = 15_000) {
206
+ const res = await fetch(url, { headers, signal: AbortSignal.timeout(timeoutMs), redirect: 'error' });
207
+ const text = await readCapped(res, MAX_LIST);
208
+ if (!res.ok)
209
+ throw new DriverError(`HTTP ${res.status}: ${redact(errorMessage(text).slice(0, 300))}`, classifyStatus(res.status, text), res.status);
210
+ return JSON.parse(text);
211
+ }
212
+ export function joinUrl(base, path) {
213
+ return base.replace(/\/+$/, '') + '/' + path.replace(/^\/+/, '');
214
+ }
@@ -0,0 +1,21 @@
1
+ import { listAnthropicModels, runAnthropic } from './anthropic.js';
2
+ import { runCli } from './cli.js';
3
+ import { listOpenAIModels, runOpenAI } from './openai.js';
4
+ export function runDriver(req, edit = false) {
5
+ switch (req.account.driver) {
6
+ case 'openai':
7
+ return runOpenAI(req);
8
+ case 'anthropic':
9
+ return runAnthropic(req);
10
+ case 'cli':
11
+ return runCli(req, edit);
12
+ }
13
+ }
14
+ /** Ask the provider which models it has. CLI tools do not support this. */
15
+ export async function discoverModels(account) {
16
+ if (account.driver === 'openai')
17
+ return listOpenAIModels(account);
18
+ if (account.driver === 'anthropic')
19
+ return listAnthropicModels(account);
20
+ return [];
21
+ }