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.
package/dist/cli.js ADDED
@@ -0,0 +1,1001 @@
1
+ #!/usr/bin/env node
2
+ // The omnitrix command line: add and manage accounts, check usage, and wire omnitrix into Claude Code.
3
+ // It reads and writes the same files in ~/.omnitrix that the MCP server uses.
4
+ import { Command, Option } from 'commander';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { spawnSync } from 'node:child_process';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { serveDashboard } from './dashboard.js';
11
+ import { DEFAULT_PORT, ensureDashboard, stopDashboard } from './dashboard-launch.js';
12
+ import { discoverModels, runDriver } from './drivers/index.js';
13
+ import { CLI_TOOLS, loginCli, providerTool, resolveCommand } from './drivers/cli.js';
14
+ import { Engine } from './engine.js';
15
+ import { describeAccount } from './mcp.js';
16
+ import { localModels } from './drivers/ollama.js';
17
+ import { basisOf, isChatModel, makeModel, statsKey } from './models.js';
18
+ import { loadStats } from './stats.js';
19
+ import { PROVIDERS, getProvider } from './providers.js';
20
+ import { renderStatusLine } from './statusline.js';
21
+ import { deleteSecret, dropModel, ensureHome, files, findAccount, homeDir, inside, JOB_ID, loadConfig, loadHealth, updateConfig, readJson, redact, saveHealth, setSecret, uniqueAccountId } from './store.js';
22
+ import { branchExists, branchMerged, deleteBranch, pruneWorktree } from './worktree.js';
23
+ import { EFFORTS, DriverError, TASK_TYPES } from './types.js';
24
+ import { refreshQuotas } from './quota.js';
25
+ import { formatTokens, readLedger, recordUsage, typicalLatency } from './usage.js';
26
+ /** A typical answer time as people read it: "4.2 s", "38 s", or "-" when there is none yet. */
27
+ function seconds(ms) {
28
+ // the same form as the router's "typical 4.2 s"
29
+ return ms === undefined ? '-' : `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0).replace(/\.0$/, '')} s`;
30
+ }
31
+ import { detect } from './init.js';
32
+ import { budgetFor, estimateCost, fingerprint, loadTeam, officialHost, parseTeam, periodStart, personSpend, readShared, reviewCode, shareRecord, teamAccounts, unpricedModels } from './team.js';
33
+ import { VERSION } from './version.js';
34
+ const program = new Command();
35
+ program.name('omnitrix').description('One Claude brain, every AI account you have.').version(VERSION);
36
+ /** Report a failure after network work without calling process.exit: exiting while a connection is still
37
+ * closing trips a libuv assertion on Windows (UV_HANDLE_CLOSING). Node exits once its handles are done. */
38
+ function fail(msg) {
39
+ process.stderr.write(`error: ${msg}
40
+ `);
41
+ process.exitCode = 1;
42
+ }
43
+ function die(msg) {
44
+ process.stderr.write(`error: ${msg}\n`);
45
+ process.exit(1);
46
+ }
47
+ /** Team accounts come from the team file; a local change would be lost on the next load, so refuse it. */
48
+ function ownAccount(cfg, id) {
49
+ const acc = findAccount(cfg, id) ?? die(`no account "${id}"`);
50
+ if (acc.team)
51
+ die(`${id} is managed by the team file ${cfg.settings.team?.file ?? ''}; change it there`);
52
+ return acc;
53
+ }
54
+ function int(v) {
55
+ const n = Number.parseInt(v, 10);
56
+ if (!Number.isFinite(n) || n < 0)
57
+ throw new Error(`not a number: ${v}`);
58
+ return n;
59
+ }
60
+ function limitOptions(cmd) {
61
+ return cmd
62
+ .option('--rpm <n>', 'requests per minute limit', int)
63
+ .option('--r5h <n>', 'requests per 5 hours limit', int)
64
+ .option('--rpd <n>', 'requests per day limit', int)
65
+ .option('--rpw <n>', 'requests per week limit', int)
66
+ .option('--tpd <n>', 'tokens per day limit', int)
67
+ .option('--tpm <n>', 'tokens per month limit', int);
68
+ }
69
+ function limitsFrom(o, base = {}) {
70
+ const l = { ...base };
71
+ if (o.rpm !== undefined)
72
+ l.requestsPerMinute = o.rpm;
73
+ if (o.r5h !== undefined)
74
+ l.requestsPer5h = o.r5h;
75
+ if (o.rpd !== undefined)
76
+ l.requestsPerDay = o.rpd;
77
+ if (o.rpw !== undefined)
78
+ l.requestsPerWeek = o.rpw;
79
+ if (o.tpd !== undefined)
80
+ l.tokensPerDay = o.tpd;
81
+ if (o.tpm !== undefined)
82
+ l.tokensPerMonth = o.tpm;
83
+ return l;
84
+ }
85
+ program
86
+ .command('providers')
87
+ .description('list the providers you can connect')
88
+ .option('--free', 'only providers with a free tier or free allowance, and local ones')
89
+ .action((o) => {
90
+ const groups = [
91
+ ['Agent CLIs (sign in with a subscription, can edit files)', (p) => p.driver === 'cli'],
92
+ ['Hosted APIs', (p) => p.driver !== 'cli' && !p.local && !p.id.startsWith('custom')],
93
+ ['On your own machine', (p) => !!p.local],
94
+ ['Anything else', (p) => p.id.startsWith('custom')],
95
+ ];
96
+ for (const [title, test] of groups) {
97
+ const shown = PROVIDERS.filter(test).filter((p) => !o.free || p.free || p.local);
98
+ if (!shown.length)
99
+ continue;
100
+ console.log(`\n${title}`);
101
+ for (const p of shown) {
102
+ const pad = `\n ${''.padEnd(17)} `;
103
+ console.log(` ${p.id.padEnd(17)} ${p.name}${p.signup ? `${pad}${p.signup}` : ''}${p.note ? `${pad}${p.note}` : ''}`);
104
+ }
105
+ }
106
+ console.log('\nAdd one with: omnitrix add <provider> --key-env NAME (or --key, --base-url, --model)');
107
+ });
108
+ limitOptions(program
109
+ .command('add <provider>')
110
+ .description('connect an account (API key, subscription CLI or local model)')
111
+ .option('--label <text>', 'display name, e.g. "Hashim ChatGPT Plus"')
112
+ .option('--owner <name>', 'who owns this account', 'me')
113
+ .option('--id <id>', 'account id (default: made from the label)')
114
+ .option('--key <value>', 'API key, saved in the omnitrix secrets file')
115
+ .option('--key-env <NAME>', 'read the API key from this environment variable instead of saving it')
116
+ .option('--base-url <url>', 'API base URL (needed for custom providers)')
117
+ .option('--anthropic', 'use the provider\'s Anthropic-compatible endpoint')
118
+ .option('--model <ids>', 'comma separated model ids (skips auto-discovery)')
119
+ .option('--concurrency <n>', 'jobs at the same time on this account', int)
120
+ .option('--trains-on-data', 'mark that this provider may train on your prompts')
121
+ .option('--no-trains-on-data', 'mark that this provider does not train on your prompts')
122
+ .option('--login', 'for CLI accounts: sign in right away')).action(addAccount);
123
+ /** Shared by `add` and `init --apply`, so both connect an account in exactly the same way. */
124
+ async function addAccount(providerId, o) {
125
+ const spec = getProvider(providerId);
126
+ if (!spec)
127
+ die(`unknown provider "${providerId}". Run "omnitrix providers".`);
128
+ if (o.key && o.keyEnv)
129
+ die('use either --key or --key-env, not both');
130
+ ensureHome();
131
+ const cfg = loadConfig();
132
+ const label = o.label ?? spec.name;
133
+ const id = o.id ? uniqueAccountId(cfg, o.id) : uniqueAccountId(cfg, label === spec.name ? spec.id : label);
134
+ let driver = spec.driver;
135
+ let baseUrl = o.baseUrl ?? spec.baseUrl;
136
+ if (o.anthropic) {
137
+ if (!spec.anthropicUrl && !o.baseUrl)
138
+ die(`${spec.id} has no known Anthropic endpoint; pass --base-url`);
139
+ driver = 'anthropic';
140
+ baseUrl = o.baseUrl ?? spec.anthropicUrl;
141
+ }
142
+ if (driver !== 'cli' && !baseUrl)
143
+ die(spec.baseUrlHint ? `this provider needs --base-url ${spec.baseUrlHint}` : 'this provider needs --base-url');
144
+ if (driver === 'cli' && o.baseUrl)
145
+ baseUrl = o.baseUrl;
146
+ else if (driver === 'cli')
147
+ baseUrl = undefined;
148
+ let apiKey;
149
+ if (o.keyEnv)
150
+ apiKey = `env:${o.keyEnv}`;
151
+ else if (o.key)
152
+ apiKey = 'secret';
153
+ // a key already sitting in the usual environment variable is used without asking (also by CLIs that need one)
154
+ else if (spec.keyEnv && process.env[spec.keyEnv])
155
+ apiKey = `env:${spec.keyEnv}`;
156
+ if (!apiKey && driver !== 'cli' && !spec.local)
157
+ die(`an API key is needed: --key-env ${spec.keyEnv ?? 'NAME'} or --key <value>`);
158
+ const account = {
159
+ id,
160
+ label,
161
+ owner: o.owner,
162
+ provider: spec.id,
163
+ driver,
164
+ baseUrl,
165
+ apiKey,
166
+ models: [],
167
+ limits: limitsFrom(o, spec.limits ?? {}),
168
+ concurrency: o.concurrency ?? (driver === 'cli' ? 1 : spec.local ? 1 : 2),
169
+ enabled: true,
170
+ trainsOnData: o.trainsOnData ?? !!spec.trainsOnData,
171
+ local: !!spec.local,
172
+ priority: cfg.accounts.length,
173
+ addedAt: new Date().toISOString(),
174
+ };
175
+ if (o.key)
176
+ setSecret(id, o.key);
177
+ if (driver === 'cli') {
178
+ const tool = CLI_TOOLS[providerTool(spec.id)];
179
+ account.profileDir = path.join(files.profiles(), id);
180
+ fs.mkdirSync(account.profileDir, { recursive: true });
181
+ tool?.initProfile?.(account.profileDir);
182
+ if (tool && !resolveCommand(tool.command))
183
+ console.log(`note: "${tool.command}" is not installed yet. Install it, then run: omnitrix login ${id}`);
184
+ }
185
+ if (o.model) {
186
+ account.models = String(o.model).split(',').map((s) => s.trim()).filter(Boolean).map((m) => makeModel(m));
187
+ }
188
+ else if (driver === 'cli') {
189
+ account.models = [makeModel('default')];
190
+ }
191
+ else {
192
+ try {
193
+ const found = (await discoverModels(account)).filter(isChatModel);
194
+ account.models = await modelsFor(account, found.slice(0, 200));
195
+ console.log(`found ${found.length} models`);
196
+ }
197
+ catch (err) {
198
+ console.log(`could not list models (${err instanceof Error ? redact(err.message) : err})`);
199
+ }
200
+ if (!account.models.length && spec.models?.length)
201
+ account.models = spec.models.map((m) => makeModel(m));
202
+ if (!account.models.length) {
203
+ if (o.key)
204
+ deleteSecret(id);
205
+ fail('no models found; pass them with --model id1,id2');
206
+ return;
207
+ }
208
+ }
209
+ updateConfig((latest) => {
210
+ // another command may have added an account with this id while this one asked the provider
211
+ if (findAccount(latest, id))
212
+ die(`an account "${id}" was added meanwhile; run the command again`);
213
+ latest.accounts.push(account);
214
+ });
215
+ console.log(`added ${id} (${spec.name}, ${account.models.length} model${account.models.length === 1 ? '' : 's'}, owner ${account.owner})`);
216
+ if (spec.note)
217
+ console.log(`note: ${spec.note}`);
218
+ if (account.owner !== 'me' && (spec.id === 'claude-code' || spec.id === 'antigravity')) {
219
+ console.log('warning: Anthropic and Google do not allow letting other people use an account. Use accounts you own.');
220
+ }
221
+ if (driver === 'cli') {
222
+ if (o.login) {
223
+ const code = loginCli(account);
224
+ if (code !== 0)
225
+ console.log(`login exited with code ${code}; try again with: omnitrix login ${id}`);
226
+ }
227
+ else if (!account.apiKey) {
228
+ // each CLI account has its own empty profile, so it must sign in once before it can run jobs
229
+ console.log(`next: omnitrix login ${id}`);
230
+ }
231
+ }
232
+ console.log(`check it with: omnitrix test ${id}`);
233
+ }
234
+ program
235
+ .command('login <id>')
236
+ .description('sign in a CLI account inside its own profile folder')
237
+ .action((id) => {
238
+ const acc = findAccount(loadConfig(), id) ?? die(`no account "${id}"`);
239
+ if (acc.driver !== 'cli')
240
+ die(`${id} uses an API key; nothing to sign in`);
241
+ try {
242
+ process.exit(loginCli(acc));
243
+ }
244
+ catch (err) {
245
+ die(err instanceof Error ? err.message : String(err));
246
+ }
247
+ });
248
+ program
249
+ .command('list')
250
+ .alias('status')
251
+ .description('show all accounts with usage and what is left')
252
+ .option('--json', 'print JSON')
253
+ .action(async (o) => {
254
+ await refreshQuotas(loadConfig().accounts, 60_000, 5_000);
255
+ const pool = new Engine().pool();
256
+ if (o.json)
257
+ return console.log(JSON.stringify(pool, null, 2));
258
+ if (!pool.length)
259
+ return console.log('no accounts yet. Start with: omnitrix providers');
260
+ const ready = pool.filter((a) => a.state === 'ready' || a.state === 'busy').length;
261
+ console.log(`${ready}/${pool.length} accounts available (data: ${homeDir()})\n`);
262
+ for (const a of pool)
263
+ console.log(describeAccount(a));
264
+ });
265
+ limitOptions(program
266
+ .command('set <id>')
267
+ .description('change an account: label, owner, limits, concurrency, priority')
268
+ .option('--label <text>')
269
+ .option('--owner <name>')
270
+ .option('--concurrency <n>', 'jobs at the same time', int)
271
+ .option('--priority <n>', 'lower is preferred when scores tie', int)
272
+ .option('--trains-on-data')
273
+ .option('--no-trains-on-data')
274
+ .option('--key <value>')
275
+ .option('--key-env <NAME>')
276
+ .option('--base-url <url>')).action((id, o) => {
277
+ updateConfig((cfg) => {
278
+ const acc = ownAccount(cfg, id);
279
+ if (o.label)
280
+ acc.label = o.label;
281
+ if (o.owner)
282
+ acc.owner = o.owner;
283
+ if (o.concurrency !== undefined)
284
+ acc.concurrency = Math.max(1, o.concurrency);
285
+ if (o.priority !== undefined)
286
+ acc.priority = o.priority;
287
+ if (o.trainsOnData !== undefined)
288
+ acc.trainsOnData = o.trainsOnData;
289
+ if (o.baseUrl)
290
+ acc.baseUrl = o.baseUrl;
291
+ if (o.key) {
292
+ setSecret(id, o.key);
293
+ acc.apiKey = 'secret';
294
+ }
295
+ else if (o.keyEnv) {
296
+ deleteSecret(id);
297
+ acc.apiKey = `env:${o.keyEnv}`;
298
+ }
299
+ acc.limits = limitsFrom(o, acc.limits);
300
+ });
301
+ if (o.key || o.keyEnv)
302
+ saveHealth({ [id]: { state: 'ready' } });
303
+ console.log(`updated ${id}`);
304
+ });
305
+ for (const [name, value] of [['enable', true], ['disable', false]]) {
306
+ program
307
+ .command(`${name} <id>`)
308
+ .description(`${name} an account`)
309
+ .action((id) => {
310
+ updateConfig((cfg) => {
311
+ ownAccount(cfg, id).enabled = value;
312
+ });
313
+ if (value)
314
+ saveHealth({ [id]: { state: 'ready' } });
315
+ console.log(`${id} ${value ? 'enabled' : 'disabled'}`);
316
+ });
317
+ }
318
+ program
319
+ .command('remove <id>')
320
+ .description('remove an account (its CLI profile folder is kept unless --purge)')
321
+ .option('--purge', 'also delete the profile folder with the saved login')
322
+ .action((id, o) => {
323
+ const acc = updateConfig((cfg) => {
324
+ const found = ownAccount(cfg, id);
325
+ cfg.accounts = cfg.accounts.filter((a) => a.id !== id);
326
+ return found;
327
+ });
328
+ deleteSecret(id);
329
+ if (o.purge && acc.profileDir)
330
+ fs.rmSync(acc.profileDir, { recursive: true, force: true });
331
+ console.log(`removed ${id}${acc.profileDir && !o.purge ? ` (profile kept at ${acc.profileDir})` : ''}`);
332
+ });
333
+ /** Model entries for an account: local servers describe their own models, others are scored from the name. */
334
+ async function modelsFor(account, ids) {
335
+ if (account.provider === 'ollama' && account.baseUrl)
336
+ return localModels(account.baseUrl, ids);
337
+ return ids.map((m) => makeModel(m, {}, { local: account.local }));
338
+ }
339
+ program
340
+ .command('models <id>')
341
+ .description('show an account\'s models and their skill scores')
342
+ .option('--refresh', 'ask the provider for its current model list')
343
+ .action(async (id, o) => {
344
+ let acc = o.refresh ? ownAccount(loadConfig(), id) : findAccount(loadConfig(), id) ?? die(`no account "${id}"`);
345
+ if (o.refresh) {
346
+ const found = (await discoverModels(acc)).filter(isChatModel);
347
+ if (!found.length)
348
+ die('the provider returned no models');
349
+ const fresh = await modelsFor(acc, found);
350
+ acc = updateConfig((cfg) => {
351
+ const latest = ownAccount(cfg, id);
352
+ const old = new Map(latest.models.map((m) => [m.id, m]));
353
+ // scores set by hand stay; guesses are made again, with what the server now reports
354
+ latest.models = fresh.map((m) => {
355
+ const before = old.get(m.id);
356
+ if (before?.pinned)
357
+ return { ...before, digest: m.digest ?? before.digest };
358
+ return { ...m, inputPrice: before?.inputPrice, outputPrice: before?.outputPrice };
359
+ });
360
+ return latest;
361
+ });
362
+ console.log(`now ${acc.models.length} models`);
363
+ }
364
+ const stats = loadStats();
365
+ // the name column fits the longest name, so a long one never runs into the scores
366
+ const width = Math.max(44, ...acc.models.map((m) => m.id.length + 2));
367
+ // typical answer time from this computer's usage, so a user can see which models are quick
368
+ const typical = typicalLatency(readLedger(Date.now() - 31 * 24 * 3600_000));
369
+ console.log('model'.padEnd(width) + 'code reas writ long vis speed typical scores Claude accepted');
370
+ for (const m of acc.models) {
371
+ const s = m.skills;
372
+ // verdicts fade over 30 days, so the counts are rounded
373
+ let ok = 0;
374
+ let all = 0;
375
+ for (const [k, c] of Object.entries(stats)) {
376
+ if (!k.startsWith(`${statsKey(m)}|`))
377
+ continue;
378
+ ok += c.ok;
379
+ all += c.ok + c.bad;
380
+ }
381
+ const rated = Math.round(all) ? `${Math.round(ok)} of ${Math.round(all)} rated jobs` : 'no rated jobs';
382
+ console.log(`${m.id.padEnd(width)}${[s.coding, s.reasoning, s.writing, s.longContext, s.vision, s.speed].map((n) => String(n).padEnd(5)).join('')} ${seconds(typical[`${acc.id}/${m.id}`]).padEnd(9)}${basisOf(m).padEnd(11)}${rated}`);
383
+ }
384
+ console.log('\nScores: "untested" means no information, "estimated" a guess from the name or from what the server reports, "manual" set with "omnitrix model".');
385
+ console.log('They are starting points; the router also follows how often Claude accepted each model\'s work.');
386
+ });
387
+ program
388
+ .command('model <id> <model>')
389
+ .description('set skill scores (0-10) or prices for one model, or add/remove it')
390
+ .option('--coding <n>', '', int)
391
+ .option('--reasoning <n>', '', int)
392
+ .option('--writing <n>', '', int)
393
+ .option('--long-context <n>', '', int)
394
+ .option('--vision <n>', '', int)
395
+ .option('--speed <n>', '', int)
396
+ .option('--input-price <usd>', 'USD per million input tokens', parseFloat)
397
+ .option('--output-price <usd>', 'USD per million output tokens', parseFloat)
398
+ .option('--add', 'add this model to the account')
399
+ .option('--remove', 'remove this model from the account')
400
+ .action((id, modelId, o) => {
401
+ if (o.remove) {
402
+ updateConfig((cfg) => {
403
+ const acc = ownAccount(cfg, id);
404
+ acc.models = acc.models.filter((m) => m.id !== modelId);
405
+ });
406
+ return console.log(`removed ${modelId} from ${id}`);
407
+ }
408
+ const m = updateConfig((cfg) => {
409
+ const acc = ownAccount(cfg, id);
410
+ let m = acc.models.find((x) => x.id === modelId);
411
+ if (!m) {
412
+ if (!o.add)
413
+ die(`${id} has no model "${modelId}" (use --add)`);
414
+ // a model added by hand to a local account follows the local rules: its name proves nothing
415
+ m = makeModel(modelId, {}, { local: acc.local });
416
+ acc.models.push(m);
417
+ }
418
+ const clamp = (n) => Math.max(0, Math.min(10, n));
419
+ const map = { coding: 'coding', reasoning: 'reasoning', writing: 'writing', longContext: 'longContext', vision: 'vision', speed: 'speed' };
420
+ let touched = false;
421
+ for (const [opt, skill] of Object.entries(map)) {
422
+ if (o[opt] !== undefined) {
423
+ m.skills[skill] = clamp(o[opt]);
424
+ touched = true;
425
+ }
426
+ }
427
+ if (touched) {
428
+ m.pinned = true;
429
+ m.basis = 'manual';
430
+ }
431
+ // a person who sets a vision score vouches for it, on any server
432
+ if (o.vision !== undefined)
433
+ m.visionChecked = true;
434
+ if (o.inputPrice !== undefined)
435
+ m.inputPrice = o.inputPrice;
436
+ if (o.outputPrice !== undefined)
437
+ m.outputPrice = o.outputPrice;
438
+ return m;
439
+ });
440
+ console.log(`${id}/${modelId}: ${JSON.stringify(m.skills)}`);
441
+ });
442
+ program
443
+ .command('test <id>')
444
+ .description('send a tiny request to check that an account works')
445
+ .option('--model <id>')
446
+ .action(async (id, o) => {
447
+ const cfg = loadConfig();
448
+ const acc = findAccount(cfg, id) ?? die(`no account "${id}"`);
449
+ // try the listed models in order until one answers; a provider may still list models it has retired
450
+ // a code-completion or scoring model in the list would fail a chat test for reasons of its own
451
+ const chat = acc.models.map((m) => m.id).filter(isChatModel);
452
+ const queue = o.model ? [o.model] : chat.length ? chat : acc.models.length ? acc.models.map((m) => m.id) : ['default'];
453
+ for (const model of queue) {
454
+ const t0 = Date.now();
455
+ process.stdout.write(`testing ${id}/${model} ... `);
456
+ try {
457
+ const r = await runDriver({ account: acc, model, prompt: 'Reply with the single word OK.', timeoutMs: 180_000, maxOutputTokens: 64 });
458
+ const ms = Date.now() - t0;
459
+ // an empty answer means the model cannot do chat work as it is, so it is not counted as a success
460
+ if (!r.text.trim()) {
461
+ console.log(`answered in ${(ms / 1000).toFixed(1)}s, but the answer was empty`);
462
+ if (!o.model)
463
+ continue;
464
+ fail(`${model} gave an empty answer; it may need more output room, or it may not suit chat tasks`);
465
+ return;
466
+ }
467
+ const costUsd = r.costUsd ?? estimateCost(acc.models.find((m) => m.id === model), r.inputTokens, r.outputTokens);
468
+ const rec = { ts: Date.now(), accountId: id, model, inputTokens: r.inputTokens, outputTokens: r.outputTokens, ok: true, latencyMs: ms, costUsd };
469
+ // a test on a team account spends the team's money like any other request
470
+ const team = acc.team && cfg.settings.team ? loadTeam(cfg.settings.team) : undefined;
471
+ const tagged = team?.team ? { ...rec, user: team.membership.user, team: team.team.name } : rec;
472
+ recordUsage(tagged);
473
+ if (team?.team?.auditDir)
474
+ shareRecord(team.team.auditDir, team.membership.user, tagged);
475
+ saveHealth({ [id]: { state: 'ready', measured: r.rate ? { ...r.rate, at: Date.now(), source: 'response headers' } : undefined } });
476
+ console.log(`ok in ${(ms / 1000).toFixed(1)}s: "${r.text.trim().slice(0, 60)}"`);
477
+ if (r.rate?.remainingRequests !== undefined)
478
+ console.log(`provider says ${r.rate.remainingRequests} requests left in this window`);
479
+ return;
480
+ }
481
+ catch (err) {
482
+ const msg = err instanceof Error ? err.message : String(err);
483
+ console.log('failed');
484
+ if (err instanceof DriverError && err.kind === 'model_gone' && !o.model) {
485
+ dropModel(id, model);
486
+ console.log(` ${model} is no longer available, so it was removed from ${id}; trying the next model`);
487
+ continue;
488
+ }
489
+ if (err instanceof DriverError && err.kind === 'auth')
490
+ saveHealth({ [id]: { state: 'auth_error', reason: msg.slice(0, 160) } });
491
+ fail(redact(msg));
492
+ return;
493
+ }
494
+ }
495
+ fail(`no model on ${id} answered`);
496
+ });
497
+ program
498
+ .command('run <prompt...>')
499
+ .description('send one task through the router and print the answer')
500
+ .addOption(new Option('--type <type>', 'task type').choices([...TASK_TYPES]).default('writing'))
501
+ .addOption(new Option('--privacy <level>').choices(['public', 'private', 'secret']))
502
+ .option('--use <account[/model]>', 'force an account or model')
503
+ .addOption(new Option('--effort <level>', 'how hard a reasoning model should think').choices([...EFFORTS]))
504
+ .option('--repo <path>', 'git repo for code tasks')
505
+ .option('--fast', 'prefer models that answered quickly before')
506
+ .action(async (words, o) => {
507
+ const engine = new Engine();
508
+ const prompt = words.join(' ');
509
+ const [job] = engine.dispatch([{ title: prompt.slice(0, 60), type: o.type, prompt, privacy: o.privacy, use: o.use, effort: o.effort, fast: o.fast, repo: o.repo ? path.resolve(o.repo) : undefined }]);
510
+ // wait a moment first so the chosen account is printed before the answer arrives
511
+ let done = await engine.wait([job.id], 1);
512
+ if (done[0]?.accountId)
513
+ process.stderr.write(`-> ${done[0].accountId}/${done[0].model}\n`);
514
+ while (done[0] && (done[0].status === 'queued' || done[0].status === 'running'))
515
+ done = await engine.wait([job.id], 30);
516
+ const j = done[0];
517
+ if (j.status !== 'done') {
518
+ fail(j.error ?? j.status);
519
+ return;
520
+ }
521
+ process.stderr.write(`(${j.accountId}/${j.model}, ${(j.usage?.inputTokens ?? 0) + (j.usage?.outputTokens ?? 0)} tokens)\n`);
522
+ console.log(engine.readOutput(j.id) ?? j.preview);
523
+ // no process.exit here: exiting while a connection is still closing crashes Node on Windows
524
+ });
525
+ program
526
+ .command('route <prompt...>')
527
+ .description('show which account and model would get a task, without running it')
528
+ .addOption(new Option('--type <type>', 'task type').choices([...TASK_TYPES]).default('writing'))
529
+ .addOption(new Option('--privacy <level>').choices(['public', 'private', 'secret']))
530
+ .option('--fast', 'prefer models that answered quickly before')
531
+ .action((words, o) => {
532
+ const { candidates, rejected } = new Engine().preview({ title: 'preview', type: o.type, prompt: words.join(' '), privacy: o.privacy, fast: o.fast });
533
+ if (!candidates.length)
534
+ console.log('nobody can take this task');
535
+ const shown = candidates.slice(0, 8);
536
+ const width = Math.max(46, ...shown.map((c) => `${c.accountId}/${c.model}`.length));
537
+ shown.forEach((c, i) => console.log(`${String(i + 1).padStart(2)}. ${`${c.accountId}/${c.model}`.padEnd(width)} ${c.score.toFixed(3)} ${c.why.join(', ')}`));
538
+ if (rejected.length) {
539
+ console.log('\nskipped:');
540
+ for (const r of rejected.slice(0, 12))
541
+ console.log(` ${r.accountId}${r.model ? '/' + r.model : ''}: ${r.reason}`);
542
+ }
543
+ });
544
+ program
545
+ .command('settings')
546
+ .description('show or change global settings')
547
+ .addOption(new Option('--mode <mode>', 'balanced, quality (best model) or saver (cheapest)').choices(['balanced', 'quality', 'saver']))
548
+ .addOption(new Option('--protect-private <on|off>', 'keep private tasks away from providers that train on data').choices(['on', 'off']))
549
+ .option('--ban <provider>', 'never use this provider')
550
+ .option('--unban <provider>')
551
+ .option('--pin <type=account[/model],...>', 'always try these first for a task type, e.g. code=codex-main')
552
+ .option('--unpin <type>')
553
+ .option('--timeout <seconds>', 'job timeout', int)
554
+ .option('--preview-chars <n>', 'how much of each result Claude sees', int)
555
+ .action((o) => {
556
+ const s = updateConfig((cfg) => {
557
+ const s = cfg.settings;
558
+ if (o.mode)
559
+ s.mode = o.mode;
560
+ if (o.protectPrivate)
561
+ s.protectPrivate = o.protectPrivate === 'on';
562
+ if (o.ban && !s.bannedProviders.includes(o.ban))
563
+ s.bannedProviders.push(o.ban);
564
+ if (o.unban)
565
+ s.bannedProviders = s.bannedProviders.filter((p) => p !== o.unban);
566
+ if (o.pin) {
567
+ const [type, list] = String(o.pin).split('=');
568
+ if (!type || !list || !TASK_TYPES.includes(type))
569
+ die('use --pin type=account[/model],... with a valid task type');
570
+ s.pins[type] = list.split(',').map((x) => x.trim()).filter(Boolean);
571
+ }
572
+ if (o.unpin)
573
+ delete s.pins[o.unpin];
574
+ if (o.timeout)
575
+ s.jobTimeoutSec = o.timeout;
576
+ if (o.previewChars)
577
+ s.resultPreviewChars = o.previewChars;
578
+ return s;
579
+ });
580
+ console.log(JSON.stringify(s, null, 2));
581
+ });
582
+ program
583
+ .command('statusline')
584
+ .description('one-line pool summary for the Claude Code status line (reads Claude\'s JSON on stdin)')
585
+ .action(async () => {
586
+ let input = '';
587
+ if (!process.stdin.isTTY) {
588
+ input = await new Promise((resolve) => {
589
+ let data = '';
590
+ const t = setTimeout(() => resolve(data), 250);
591
+ process.stdin.on('data', (d) => (data += d));
592
+ process.stdin.on('end', () => {
593
+ clearTimeout(t);
594
+ resolve(data);
595
+ });
596
+ });
597
+ }
598
+ process.stdout.write(renderStatusLine(input) + '\n');
599
+ process.exit(0);
600
+ });
601
+ program
602
+ .command('dashboard')
603
+ .description('open the live dashboard; it keeps running in the background')
604
+ .option('--port <n>', 'port', int, DEFAULT_PORT)
605
+ .option('--no-open', 'do not open a browser tab')
606
+ .option('--stop', 'stop the background dashboard')
607
+ .option('--serve', 'run the dashboard in this terminal until Ctrl+C')
608
+ .action(async (o) => {
609
+ if (o.stop)
610
+ return console.log((await stopDashboard(o.port)) ? 'dashboard stopped' : 'no dashboard was running');
611
+ if (o.serve)
612
+ return serveDashboard(o.port);
613
+ await showDashboard(o.port, o.open);
614
+ });
615
+ /** Start or find the background dashboard and open it, unless a tab is already open. */
616
+ async function showDashboard(port, open, onlyToLook = false) {
617
+ // test runs and CI machines have no one to look at a browser
618
+ const quiet = !open || process.env.OMNITRIX_NO_BROWSER === '1' || !!process.env.CI;
619
+ // after setup the dashboard is for looking at; with nobody to look, it is not started
620
+ if (quiet && onlyToLook)
621
+ return console.log('See everything live with "omnitrix dashboard".');
622
+ const d = await ensureDashboard({ port, open: quiet ? false : undefined });
623
+ console.log(`dashboard: ${d.url}${d.started ? ' (started in the background; stop it with "omnitrix dashboard --stop")' : ''}${d.opened ? '' : quiet ? '' : ' (already open in a browser tab)'}`);
624
+ }
625
+ program
626
+ .command('mcp')
627
+ .description('run the MCP server (Claude Code starts this for you)')
628
+ .action(async () => {
629
+ const { startMcp } = await import('./mcp.js');
630
+ startMcp();
631
+ });
632
+ program
633
+ .command('init')
634
+ .description('find AI tools, API keys and local models on this computer and connect them')
635
+ .option('--apply', 'connect what was found; without it, nothing is changed')
636
+ .option('--no-open', 'do not open the dashboard afterwards')
637
+ .action(async (o) => {
638
+ // looking changes nothing; addAccount creates the data folder when something is connected
639
+ const found = await detect(loadConfig());
640
+ // only --apply starts anything; looking, as the first step is described, changes nothing at all
641
+ const dashboard = async () => {
642
+ if (o.apply)
643
+ await showDashboard(DEFAULT_PORT, o.open, true).catch((err) => console.log(`could not open the dashboard: ${err instanceof Error ? err.message : err}`));
644
+ else
645
+ console.log('See the pool live with "omnitrix dashboard".');
646
+ };
647
+ if (!found.length) {
648
+ console.log('Nothing to connect was found. Run "omnitrix providers" to see what omnitrix supports.');
649
+ await dashboard();
650
+ return;
651
+ }
652
+ console.log('Found on this computer:');
653
+ for (const f of found) {
654
+ const mark = f.action === 'add' ? '+' : f.action === 'connected' ? '=' : '-';
655
+ const state = f.action === 'add' ? (o.apply ? 'connecting' : 'not connected yet')
656
+ : f.action === 'connected' ? `already connected as ${f.connectedAs.join(', ')}` : `not added: ${f.reason}`;
657
+ console.log(` ${mark} ${f.name.padEnd(26)} ${f.how.padEnd(44)} ${state}`);
658
+ }
659
+ const todo = found.filter((f) => f.action === 'add');
660
+ if (!o.apply) {
661
+ console.log(todo.length ? `\nNothing was changed. Run "omnitrix init --apply" to connect the ${todo.length} marked with +.` : '\nEverything found is already connected.');
662
+ }
663
+ else {
664
+ for (const f of todo) {
665
+ console.log(`\n${f.name}:`);
666
+ await addAccount(f.provider, { owner: 'me' });
667
+ }
668
+ }
669
+ console.log('\nTo use omnitrix from Claude Code, run "omnitrix setup-claude" once, then restart Claude Code.');
670
+ await dashboard();
671
+ });
672
+ function money(v) {
673
+ return `$${v.toFixed(2)}`;
674
+ }
675
+ /** Who this developer is in the team: an explicit name, else their git email, else their login name. */
676
+ function defaultUser() {
677
+ const git = spawnSync('git', ['config', '--global', 'user.email'], { encoding: 'utf8', windowsHide: true });
678
+ return git.status === 0 && git.stdout.trim() ? git.stdout.trim() : os.userInfo().username;
679
+ }
680
+ const team = program.command('team').description('share company API accounts, prices and budgets through a team file');
681
+ team
682
+ .command('join <file>')
683
+ .description('review a team file, then join it with --yes')
684
+ .option('--as <name>', 'who you are in the team (default: your git email)')
685
+ .option('--yes <code>', 'join, giving the review code shown when you reviewed the file')
686
+ .action((file, o) => {
687
+ const full = path.resolve(file);
688
+ let text;
689
+ try {
690
+ text = fs.readFileSync(full, 'utf8');
691
+ }
692
+ catch {
693
+ die(`cannot read ${full}`);
694
+ }
695
+ let parsed;
696
+ try {
697
+ parsed = parseTeam(text);
698
+ }
699
+ catch (err) {
700
+ die(err instanceof Error ? err.message : String(err));
701
+ }
702
+ const user = o.as ?? defaultUser();
703
+ const code = reviewCode(text);
704
+ if (o.yes !== undefined && o.yes !== code) {
705
+ // the code ties the join to the exact contents that were reviewed, so a file edited in between is not pinned
706
+ die(`the review code ${o.yes} does not match this file: it has changed since you reviewed it, or the code is wrong. Run "omnitrix team join ${file}" without --yes to review it again`);
707
+ }
708
+ // everything a key could be sent to, so the developer can see where their keys would go
709
+ console.log(`${parsed.name} (${full})`);
710
+ console.log('Accounts, and where their keys would be sent:');
711
+ const warnings = [];
712
+ for (const a of teamAccounts(parsed)) {
713
+ const spec = parsed.accounts.find((s) => s.id === a.id);
714
+ const host = new URL(a.baseUrl).host;
715
+ const official = officialHost(a.provider);
716
+ const where = official === undefined ? `${host} (a custom address)` : host === official ? host : `${host} (not the provider's own address, ${official})`;
717
+ const set = process.env[spec.keyEnv] ? 'set' : 'not set on this computer';
718
+ const limit = [spec.usdPerDay !== undefined ? `${money(spec.usdPerDay)} a day` : '', spec.usdPerMonth !== undefined ? `${money(spec.usdPerMonth)} a month` : ''].filter(Boolean).join(', ');
719
+ console.log(` ${a.id.padEnd(18)} ${a.provider.padEnd(14)} ${where.padEnd(30)} key from ${spec.keyEnv} (${set})${limit ? `; team limit ${limit}` : ''}${a.trainsOnData ? '; may train on prompts, so public tasks only' : ''}`);
720
+ if (PROVIDERS.some((p) => p.keyEnv === spec.keyEnv))
721
+ warnings.push(`${spec.keyEnv} usually holds a personal key; ask the team to use a variable of its own, such as ACME_${spec.keyEnv}`);
722
+ }
723
+ for (const m of unpricedModels(parsed))
724
+ warnings.push(`no price for ${m}, so its requests count as costing nothing against budgets`);
725
+ const b = budgetFor(parsed, user);
726
+ console.log(`Your budget as ${user}: ${b.day !== undefined ? `${money(b.day)} a day` : 'no daily limit'}, ${b.month !== undefined ? `${money(b.month)} a month` : 'no monthly limit'}`);
727
+ if (o.as && o.as !== defaultUser())
728
+ console.log(` (your git email is ${defaultUser()})`);
729
+ if (parsed.auditDir)
730
+ console.log(`Your name and your requests on team accounts (account, model, tokens, cost; never prompts or results) are also copied to ${parsed.auditDir}`);
731
+ for (const w of warnings)
732
+ console.log(`warning: ${w}`);
733
+ if (o.yes === undefined) {
734
+ console.log(`\nreview code: ${code}`);
735
+ console.log(`Nothing was changed. If this looks right, join with: omnitrix team join ${file}${o.as ? ` --as ${o.as}` : ''} --yes ${code}`);
736
+ return;
737
+ }
738
+ const clash = updateConfig((cfg) => {
739
+ cfg.settings.team = { file: full, user, sha256: fingerprint(text) };
740
+ return parsed.accounts.filter((a) => cfg.accounts.some((own) => own.id === a.id && !own.team)).map((a) => a.id);
741
+ });
742
+ console.log(`\njoined ${parsed.name} as ${user}`);
743
+ if (clash.length)
744
+ console.log(`note: you already have accounts named ${clash.join(', ')}; your own ones are used, and the team's are not loaded`);
745
+ console.log('If the team file changes later, its accounts stop loading until you review it here again.');
746
+ });
747
+ team
748
+ .command('leave')
749
+ .description('stop using the team file')
750
+ .action(() => {
751
+ const cfg = loadConfig();
752
+ const state = cfg.settings.team ? loadTeam(cfg.settings.team) : undefined;
753
+ if (!state) {
754
+ console.log('You are not in a team.');
755
+ return;
756
+ }
757
+ updateConfig((latest) => {
758
+ latest.settings.team = undefined;
759
+ });
760
+ console.log(`left ${state.team?.name ?? 'the team'}`);
761
+ });
762
+ team
763
+ .command('status', { isDefault: true })
764
+ .description('show the team, who you are and what you have spent')
765
+ .action(() => {
766
+ const cfg = loadConfig();
767
+ if (!cfg.settings.team) {
768
+ console.log('You are not in a team. Join one with: omnitrix team join <file>');
769
+ return;
770
+ }
771
+ const state = loadTeam(cfg.settings.team);
772
+ if (!state.team) {
773
+ console.log(`Team accounts are not loaded: ${state.error}`);
774
+ return;
775
+ }
776
+ const { user } = state.membership;
777
+ const s = personSpend(state.team, user, readLedger(periodStart(Date.now(), 'month')));
778
+ const b = budgetFor(state.team, user);
779
+ console.log(`${state.team.name}, as ${user} (${state.membership.file})`);
780
+ console.log(` today: ${money(s.day)}${b.day !== undefined ? ` of ${money(b.day)}` : ''}`);
781
+ console.log(` this month: ${money(s.month)}${b.month !== undefined ? ` of ${money(b.month)}` : ''}`);
782
+ console.log(` accounts: ${state.accounts.map((a) => a.id).join(', ')}`);
783
+ });
784
+ program
785
+ .command('usage')
786
+ .description('requests, tokens and cost, grouped by person, account or model')
787
+ .addOption(new Option('--by <what>', 'how to group').choices(['person', 'account', 'model']).default('account'))
788
+ .option('--days <n>', 'how far back', int, 30)
789
+ .option('--team', "everyone's usage from the team's shared folder instead of this computer's")
790
+ .action((o) => {
791
+ const since = Date.now() - o.days * 24 * 3600_000;
792
+ let records;
793
+ if (o.team) {
794
+ const cfg = loadConfig();
795
+ const state = cfg.settings.team ? loadTeam(cfg.settings.team) : undefined;
796
+ if (!state?.team?.auditDir)
797
+ die('the team file names no shared folder (auditDir), so there is no team-wide log to read');
798
+ records = readShared(state.team.auditDir, since);
799
+ }
800
+ else {
801
+ records = readLedger(since);
802
+ }
803
+ const groups = new Map();
804
+ for (const r of records) {
805
+ const key = o.by === 'person' ? r.user ?? '(you, outside a team)' : o.by === 'model' ? `${r.accountId}/${r.model}` : r.accountId;
806
+ const g = groups.get(key) ?? { n: 0, failed: 0, tokens: 0, cost: 0 };
807
+ g.n++;
808
+ if (!r.ok)
809
+ g.failed++;
810
+ g.tokens += r.inputTokens + r.outputTokens;
811
+ g.cost += r.costUsd ?? 0;
812
+ groups.set(key, g);
813
+ }
814
+ if (!groups.size) {
815
+ console.log(`no requests in the last ${o.days} days`);
816
+ return;
817
+ }
818
+ const rows = [...groups.entries()].sort((a, b) => b[1].cost - a[1].cost || b[1].n - a[1].n);
819
+ const width = Math.max(...rows.map(([k]) => k.length)) + 2;
820
+ for (const [key, g] of rows) {
821
+ // shared records come from colleagues' machines; never print control characters from them
822
+ const k = key.replace(/[\p{Cc}\p{Cf}]/gu, '?');
823
+ console.log(`${k.padEnd(width)}${`${g.n} requests`.padEnd(14)}${`${formatTokens(g.tokens)} tokens`.padEnd(16)}${money(g.cost).padEnd(10)}${g.failed ? `${g.failed} failed` : ''}`);
824
+ }
825
+ console.log('\nCosts are those reported by the provider, or estimated from model prices where they are known.');
826
+ });
827
+ program
828
+ .command('setup-claude')
829
+ .description('register omnitrix in Claude Code and add the status line')
830
+ .addOption(new Option('--scope <scope>', 'where to register the MCP server').choices(['user', 'project', 'local']).default('user'))
831
+ .option('--no-statusline', 'do not touch the status line')
832
+ .option('--dry-run', 'only print what would be done')
833
+ .action((o) => {
834
+ const script = fileURLToPath(import.meta.url);
835
+ const node = process.execPath;
836
+ const mcpArgs = ['mcp', 'add', '--scope', o.scope, 'omnitrix', '--', node, script, 'mcp'];
837
+ console.log(`1. claude ${mcpArgs.map((a) => (/\s/.test(a) ? `"${a}"` : a)).join(' ')}`);
838
+ if (!o.dryRun) {
839
+ const claude = resolveCommand('claude');
840
+ if (!claude) {
841
+ console.log(' Claude Code CLI not found on PATH; run the line above yourself after installing it.');
842
+ }
843
+ else {
844
+ const r = spawnSync(claude.file, [...claude.prefix, ...mcpArgs], { stdio: 'inherit', shell: claude.shell });
845
+ if (r.status !== 0)
846
+ console.log(' that did not work; if omnitrix is already registered, remove it with "claude mcp remove omnitrix" and retry.');
847
+ }
848
+ }
849
+ if (o.statusline) {
850
+ const settingsFile = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'settings.json');
851
+ const command = `"${node}" "${script}" statusline`;
852
+ console.log(`2. statusLine in ${settingsFile}: ${command}`);
853
+ if (!o.dryRun) {
854
+ let settings = {};
855
+ if (fs.existsSync(settingsFile)) {
856
+ try {
857
+ settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
858
+ }
859
+ catch {
860
+ die(`${settingsFile} is not valid JSON; fix it first`);
861
+ }
862
+ // keep a copy so the user can always get their old settings back
863
+ fs.copyFileSync(settingsFile, `${settingsFile}.bak-omnitrix`);
864
+ }
865
+ // never replace a status line someone set up themselves
866
+ if (settings.statusLine && !String(settings.statusLine.command ?? '').includes('omnitrix') && !String(settings.statusLine.command ?? '').includes('statusline')) {
867
+ console.log(` you already have a status line (${settings.statusLine.command}); left it alone. Use --no-statusline to skip this step.`);
868
+ }
869
+ else {
870
+ // Claude Code stops redrawing while it waits on tools, so refresh on a timer as well
871
+ settings.statusLine = { type: 'command', command, refreshInterval: 15 };
872
+ fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
873
+ fs.writeFileSync(settingsFile, JSON.stringify(settings, null, 2) + '\n');
874
+ console.log(' done (backup saved next to it).');
875
+ }
876
+ }
877
+ }
878
+ console.log('Restart Claude Code, then ask it to "use omnitrix" for big jobs.');
879
+ });
880
+ program
881
+ .command('clean')
882
+ .description('delete old job records, outputs and worktrees; --branches also deletes branches no longer needed')
883
+ .option('--days <n>', 'only things older than this many days', int, 14)
884
+ .option('--branches', 'also delete the branches of rejected, failed or cancelled jobs, and of other jobs once merged')
885
+ .option('--dry-run', 'only report what would be deleted')
886
+ .action((o) => {
887
+ const cutoff = Date.now() - o.days * 24 * 3600_000;
888
+ let jobs = 0;
889
+ let trees = 0;
890
+ let branches = 0;
891
+ const kept = [];
892
+ let stuck = 0;
893
+ for (const name of fs.existsSync(files.jobs()) ? fs.readdirSync(files.jobs()) : []) {
894
+ const file = path.join(files.jobs(), name);
895
+ // cancel notes are empty files; one left from a cancel that raced a finishing job is just litter
896
+ if (name.endsWith('.cancel')) {
897
+ if (!o.dryRun && fs.statSync(file).mtimeMs < cutoff)
898
+ fs.rmSync(file, { force: true });
899
+ continue;
900
+ }
901
+ const job = readJson(file, null);
902
+ // a record that is not omnitrix's own for this file name could point anywhere, so it is left alone
903
+ if (!job || `${job.id}.json` !== name || !JOB_ID.test(job.id))
904
+ continue;
905
+ if (job.updatedAt > cutoff || job.status === 'queued' || job.status === 'running')
906
+ continue;
907
+ jobs++;
908
+ // only a worktree inside omnitrix's own folder is ever deleted
909
+ const tree = job.worktree && path.resolve(job.worktree.path) !== path.resolve(files.worktrees()) && inside(job.worktree.path, files.worktrees()) ? job.worktree.path : undefined;
910
+ if (o.dryRun) {
911
+ if (tree)
912
+ trees++;
913
+ }
914
+ else {
915
+ if (tree && pruneWorktree(tree))
916
+ trees++;
917
+ }
918
+ const repo = job.task.repo;
919
+ // only the branch omnitrix made for this job, in a repository given by absolute path, is ever touched
920
+ const branch = job.worktree?.branch === `omnitrix/${job.id}` ? job.worktree.branch : undefined;
921
+ let keepRecord = false;
922
+ if (o.branches && repo && branch && path.isAbsolute(repo) && fs.existsSync(repo) && branchExists(repo, branch)) {
923
+ // rejected or broken work is not wanted; anything else goes only once it is in the repo's history
924
+ const unwanted = job.verdict === 'rejected' || job.status === 'failed' || job.status === 'cancelled';
925
+ if (!unwanted && !branchMerged(repo, branch)) {
926
+ kept.push(branch);
927
+ keepRecord = true;
928
+ }
929
+ else if (o.dryRun || deleteBranch(repo, branch)) {
930
+ branches++;
931
+ }
932
+ else {
933
+ // for example, the branch is checked out somewhere
934
+ stuck++;
935
+ keepRecord = true;
936
+ }
937
+ }
938
+ // a kept branch keeps its record, so a later clean can still decide about it once it is merged or rejected
939
+ if (o.dryRun || keepRecord)
940
+ continue;
941
+ fs.rmSync(path.join(files.outputs(), `${job.id}.md`), { force: true });
942
+ fs.rmSync(file, { force: true });
943
+ }
944
+ // read-only copies are not on any job record; one left by a process that died is removed once it is old
945
+ for (const name of fs.existsSync(files.worktrees()) ? fs.readdirSync(files.worktrees()) : []) {
946
+ const dir = path.join(files.worktrees(), name);
947
+ if (!/^j[0-9a-z]{4,40}-ro(-[0-9a-z]+)?$/.test(name) || fs.statSync(dir).mtimeMs >= cutoff)
948
+ continue;
949
+ trees++;
950
+ if (!o.dryRun)
951
+ pruneWorktree(dir);
952
+ }
953
+ const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
954
+ console.log(`${o.dryRun ? 'would remove' : 'removed'} ${count(jobs, 'old job', 'old jobs')} and ${count(trees, 'worktree', 'worktrees')}`);
955
+ if (o.branches) {
956
+ // Work copied with "git checkout <branch> -- <file>" never counts as merged, so a kept branch is named:
957
+ // only the user knows whether it is still needed.
958
+ const names = kept.sort();
959
+ const shown = names.length ? `: ${names.slice(0, 10).join(', ')}${names.length > 10 ? ', ...' : ''}` : '';
960
+ console.log(`${o.dryRun ? 'would delete' : 'deleted'} ${count(branches, 'branch', 'branches')}, ${o.dryRun ? 'would keep' : 'kept'} ${kept.length} that are not merged${shown}${stuck ? `, could not delete ${stuck}` : ''}`);
961
+ if (names.length)
962
+ console.log('Once a kept branch is no longer needed, delete it with "git branch -D <name>" in its repository.');
963
+ }
964
+ });
965
+ program
966
+ .command('doctor')
967
+ .description('check the setup and every account')
968
+ .action(() => {
969
+ const ok = (b, msg) => console.log(`${b ? ' ok ' : 'FAIL'} ${msg}`);
970
+ const major = Number(process.versions.node.split('.')[0]);
971
+ ok(major >= 20, `node ${process.versions.node} (needs 20+)`);
972
+ ensureHome();
973
+ ok(fs.existsSync(homeDir()), `data folder ${homeDir()}`);
974
+ const cfg = loadConfig();
975
+ ok(cfg.accounts.length > 0, `${cfg.accounts.length} accounts`);
976
+ const health = loadHealth();
977
+ const answered = new Set(readLedger(Date.now() - 32 * 24 * 3600_000).filter((r) => r.ok).map((r) => r.accountId));
978
+ for (const a of cfg.accounts) {
979
+ if (a.driver === 'cli') {
980
+ const tool = CLI_TOOLS[providerTool(a.provider)];
981
+ ok(!!tool && !!resolveCommand(tool.command), `${a.id}: ${tool?.command ?? a.provider} installed`);
982
+ }
983
+ else {
984
+ const keyOk = a.local || (a.apiKey?.startsWith('env:') ? !!process.env[a.apiKey.slice(4)] : a.apiKey === 'secret');
985
+ ok(keyOk, `${a.id}: API key ${a.apiKey?.startsWith('env:') ? `from ${a.apiKey.slice(4)}` : a.local ? 'not needed' : 'saved'}`);
986
+ }
987
+ ok(a.models.length > 0, `${a.id}: ${a.models.length} models`);
988
+ // A key and a model list do not prove that requests work, so the last real request counts too.
989
+ // doctor itself sends nothing, so it never spends anyone's quota.
990
+ const h = health[a.id];
991
+ const broken = h && (h.state === 'auth_error' || h.state === 'disabled' || ((h.state === 'offline' || h.state === 'exhausted') && (h.until ?? Infinity) > Date.now()));
992
+ if (broken)
993
+ ok(false, `${a.id}: last request failed: ${(h.reason ?? h.state).slice(0, 160)}`);
994
+ else if (!answered.has(a.id))
995
+ console.log(`note ${a.id}: no request has been sent yet; "omnitrix test ${a.id}" sends one`);
996
+ }
997
+ if (cfg.accounts.some((a) => a.apiKey?.startsWith('env:'))) {
998
+ console.log('note Claude Code passes on only the key variables that existed when it started; restart it after setting one');
999
+ }
1000
+ });
1001
+ program.parseAsync().catch((err) => fail(err instanceof Error ? err.message : String(err)));