omnitrix 0.0.0-stage → 0.4.3
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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +341 -2
- package/dist/cli.js +972 -0
- package/dist/dashboard-launch.js +185 -0
- package/dist/dashboard.js +466 -0
- package/dist/drivers/anthropic.js +46 -0
- package/dist/drivers/cli.js +432 -0
- package/dist/drivers/http.js +197 -0
- package/dist/drivers/index.js +21 -0
- package/dist/drivers/ollama.js +33 -0
- package/dist/drivers/openai.js +64 -0
- package/dist/engine.js +1174 -0
- package/dist/index.js +6 -0
- package/dist/init.js +57 -0
- package/dist/mcp.js +351 -0
- package/dist/models.js +84 -0
- package/dist/owner.js +59 -0
- package/dist/providers.js +48 -0
- package/dist/quota.js +215 -0
- package/dist/router.js +239 -0
- package/dist/seats.js +119 -0
- package/dist/stats.js +47 -0
- package/dist/statusline.js +76 -0
- package/dist/store.js +303 -0
- package/dist/team.js +406 -0
- package/dist/types.js +24 -0
- package/dist/usage.js +361 -0
- package/dist/verify.js +144 -0
- package/dist/version.js +1 -0
- package/dist/worktree.js +146 -0
- package/package.json +67 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,972 @@
|
|
|
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, 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
|
+
const queue = o.model ? [o.model] : acc.models.length ? acc.models.map((m) => m.id) : ['default'];
|
|
451
|
+
for (const model of queue) {
|
|
452
|
+
const t0 = Date.now();
|
|
453
|
+
process.stdout.write(`testing ${id}/${model} ... `);
|
|
454
|
+
try {
|
|
455
|
+
const r = await runDriver({ account: acc, model, prompt: 'Reply with the single word OK.', timeoutMs: 180_000, maxOutputTokens: 64 });
|
|
456
|
+
const ms = Date.now() - t0;
|
|
457
|
+
const costUsd = r.costUsd ?? estimateCost(acc.models.find((m) => m.id === model), r.inputTokens, r.outputTokens);
|
|
458
|
+
const rec = { ts: Date.now(), accountId: id, model, inputTokens: r.inputTokens, outputTokens: r.outputTokens, ok: true, latencyMs: ms, costUsd };
|
|
459
|
+
// a test on a team account spends the team's money like any other request
|
|
460
|
+
const team = acc.team && cfg.settings.team ? loadTeam(cfg.settings.team) : undefined;
|
|
461
|
+
const tagged = team?.team ? { ...rec, user: team.membership.user, team: team.team.name } : rec;
|
|
462
|
+
recordUsage(tagged);
|
|
463
|
+
if (team?.team?.auditDir)
|
|
464
|
+
shareRecord(team.team.auditDir, team.membership.user, tagged);
|
|
465
|
+
saveHealth({ [id]: { state: 'ready', measured: r.rate ? { ...r.rate, at: Date.now(), source: 'response headers' } : undefined } });
|
|
466
|
+
console.log(`ok in ${(ms / 1000).toFixed(1)}s: "${r.text.trim().slice(0, 60)}"`);
|
|
467
|
+
if (r.rate?.remainingRequests !== undefined)
|
|
468
|
+
console.log(`provider says ${r.rate.remainingRequests} requests left in this window`);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
catch (err) {
|
|
472
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
473
|
+
console.log('failed');
|
|
474
|
+
if (err instanceof DriverError && err.kind === 'model_gone' && !o.model) {
|
|
475
|
+
dropModel(id, model);
|
|
476
|
+
console.log(` ${model} is no longer available, so it was removed from ${id}; trying the next model`);
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
if (err instanceof DriverError && err.kind === 'auth')
|
|
480
|
+
saveHealth({ [id]: { state: 'auth_error', reason: msg.slice(0, 160) } });
|
|
481
|
+
fail(redact(msg));
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
fail(`no model on ${id} answered`);
|
|
486
|
+
});
|
|
487
|
+
program
|
|
488
|
+
.command('run <prompt...>')
|
|
489
|
+
.description('send one task through the router and print the answer')
|
|
490
|
+
.addOption(new Option('--type <type>', 'task type').choices([...TASK_TYPES]).default('writing'))
|
|
491
|
+
.addOption(new Option('--privacy <level>').choices(['public', 'private', 'secret']))
|
|
492
|
+
.option('--use <account[/model]>', 'force an account or model')
|
|
493
|
+
.addOption(new Option('--effort <level>', 'how hard a reasoning model should think').choices([...EFFORTS]))
|
|
494
|
+
.option('--repo <path>', 'git repo for code tasks')
|
|
495
|
+
.option('--fast', 'prefer models that answered quickly before')
|
|
496
|
+
.action(async (words, o) => {
|
|
497
|
+
const engine = new Engine();
|
|
498
|
+
const prompt = words.join(' ');
|
|
499
|
+
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 }]);
|
|
500
|
+
// wait a moment first so the chosen account is printed before the answer arrives
|
|
501
|
+
let done = await engine.wait([job.id], 1);
|
|
502
|
+
if (done[0]?.accountId)
|
|
503
|
+
process.stderr.write(`-> ${done[0].accountId}/${done[0].model}\n`);
|
|
504
|
+
while (done[0] && (done[0].status === 'queued' || done[0].status === 'running'))
|
|
505
|
+
done = await engine.wait([job.id], 30);
|
|
506
|
+
const j = done[0];
|
|
507
|
+
if (j.status !== 'done') {
|
|
508
|
+
fail(j.error ?? j.status);
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
process.stderr.write(`(${j.accountId}/${j.model}, ${(j.usage?.inputTokens ?? 0) + (j.usage?.outputTokens ?? 0)} tokens)\n`);
|
|
512
|
+
console.log(engine.readOutput(j.id) ?? j.preview);
|
|
513
|
+
// no process.exit here: exiting while a connection is still closing crashes Node on Windows
|
|
514
|
+
});
|
|
515
|
+
program
|
|
516
|
+
.command('route <prompt...>')
|
|
517
|
+
.description('show which account and model would get a task, without running it')
|
|
518
|
+
.addOption(new Option('--type <type>', 'task type').choices([...TASK_TYPES]).default('writing'))
|
|
519
|
+
.addOption(new Option('--privacy <level>').choices(['public', 'private', 'secret']))
|
|
520
|
+
.option('--fast', 'prefer models that answered quickly before')
|
|
521
|
+
.action((words, o) => {
|
|
522
|
+
const { candidates, rejected } = new Engine().preview({ title: 'preview', type: o.type, prompt: words.join(' '), privacy: o.privacy, fast: o.fast });
|
|
523
|
+
if (!candidates.length)
|
|
524
|
+
console.log('nobody can take this task');
|
|
525
|
+
const shown = candidates.slice(0, 8);
|
|
526
|
+
const width = Math.max(46, ...shown.map((c) => `${c.accountId}/${c.model}`.length));
|
|
527
|
+
shown.forEach((c, i) => console.log(`${String(i + 1).padStart(2)}. ${`${c.accountId}/${c.model}`.padEnd(width)} ${c.score.toFixed(3)} ${c.why.join(', ')}`));
|
|
528
|
+
if (rejected.length) {
|
|
529
|
+
console.log('\nskipped:');
|
|
530
|
+
for (const r of rejected.slice(0, 12))
|
|
531
|
+
console.log(` ${r.accountId}${r.model ? '/' + r.model : ''}: ${r.reason}`);
|
|
532
|
+
}
|
|
533
|
+
});
|
|
534
|
+
program
|
|
535
|
+
.command('settings')
|
|
536
|
+
.description('show or change global settings')
|
|
537
|
+
.addOption(new Option('--mode <mode>', 'balanced, quality (best model) or saver (cheapest)').choices(['balanced', 'quality', 'saver']))
|
|
538
|
+
.addOption(new Option('--protect-private <on|off>', 'keep private tasks away from providers that train on data').choices(['on', 'off']))
|
|
539
|
+
.option('--ban <provider>', 'never use this provider')
|
|
540
|
+
.option('--unban <provider>')
|
|
541
|
+
.option('--pin <type=account[/model],...>', 'always try these first for a task type, e.g. code=codex-main')
|
|
542
|
+
.option('--unpin <type>')
|
|
543
|
+
.option('--timeout <seconds>', 'job timeout', int)
|
|
544
|
+
.option('--preview-chars <n>', 'how much of each result Claude sees', int)
|
|
545
|
+
.action((o) => {
|
|
546
|
+
const s = updateConfig((cfg) => {
|
|
547
|
+
const s = cfg.settings;
|
|
548
|
+
if (o.mode)
|
|
549
|
+
s.mode = o.mode;
|
|
550
|
+
if (o.protectPrivate)
|
|
551
|
+
s.protectPrivate = o.protectPrivate === 'on';
|
|
552
|
+
if (o.ban && !s.bannedProviders.includes(o.ban))
|
|
553
|
+
s.bannedProviders.push(o.ban);
|
|
554
|
+
if (o.unban)
|
|
555
|
+
s.bannedProviders = s.bannedProviders.filter((p) => p !== o.unban);
|
|
556
|
+
if (o.pin) {
|
|
557
|
+
const [type, list] = String(o.pin).split('=');
|
|
558
|
+
if (!type || !list || !TASK_TYPES.includes(type))
|
|
559
|
+
die('use --pin type=account[/model],... with a valid task type');
|
|
560
|
+
s.pins[type] = list.split(',').map((x) => x.trim()).filter(Boolean);
|
|
561
|
+
}
|
|
562
|
+
if (o.unpin)
|
|
563
|
+
delete s.pins[o.unpin];
|
|
564
|
+
if (o.timeout)
|
|
565
|
+
s.jobTimeoutSec = o.timeout;
|
|
566
|
+
if (o.previewChars)
|
|
567
|
+
s.resultPreviewChars = o.previewChars;
|
|
568
|
+
return s;
|
|
569
|
+
});
|
|
570
|
+
console.log(JSON.stringify(s, null, 2));
|
|
571
|
+
});
|
|
572
|
+
program
|
|
573
|
+
.command('statusline')
|
|
574
|
+
.description('one-line pool summary for the Claude Code status line (reads Claude\'s JSON on stdin)')
|
|
575
|
+
.action(async () => {
|
|
576
|
+
let input = '';
|
|
577
|
+
if (!process.stdin.isTTY) {
|
|
578
|
+
input = await new Promise((resolve) => {
|
|
579
|
+
let data = '';
|
|
580
|
+
const t = setTimeout(() => resolve(data), 250);
|
|
581
|
+
process.stdin.on('data', (d) => (data += d));
|
|
582
|
+
process.stdin.on('end', () => {
|
|
583
|
+
clearTimeout(t);
|
|
584
|
+
resolve(data);
|
|
585
|
+
});
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
process.stdout.write(renderStatusLine(input) + '\n');
|
|
589
|
+
process.exit(0);
|
|
590
|
+
});
|
|
591
|
+
program
|
|
592
|
+
.command('dashboard')
|
|
593
|
+
.description('open the live dashboard; it keeps running in the background')
|
|
594
|
+
.option('--port <n>', 'port', int, DEFAULT_PORT)
|
|
595
|
+
.option('--no-open', 'do not open a browser tab')
|
|
596
|
+
.option('--stop', 'stop the background dashboard')
|
|
597
|
+
.option('--serve', 'run the dashboard in this terminal until Ctrl+C')
|
|
598
|
+
.action(async (o) => {
|
|
599
|
+
if (o.stop)
|
|
600
|
+
return console.log((await stopDashboard(o.port)) ? 'dashboard stopped' : 'no dashboard was running');
|
|
601
|
+
if (o.serve)
|
|
602
|
+
return serveDashboard(o.port);
|
|
603
|
+
await showDashboard(o.port, o.open);
|
|
604
|
+
});
|
|
605
|
+
/** Start or find the background dashboard and open it, unless a tab is already open. */
|
|
606
|
+
async function showDashboard(port, open, onlyToLook = false) {
|
|
607
|
+
// test runs and CI machines have no one to look at a browser
|
|
608
|
+
const quiet = !open || process.env.OMNITRIX_NO_BROWSER === '1' || !!process.env.CI;
|
|
609
|
+
// after setup the dashboard is for looking at; with nobody to look, it is not started
|
|
610
|
+
if (quiet && onlyToLook)
|
|
611
|
+
return console.log('See everything live with "omnitrix dashboard".');
|
|
612
|
+
const d = await ensureDashboard({ port, open: quiet ? false : undefined });
|
|
613
|
+
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)'}`);
|
|
614
|
+
}
|
|
615
|
+
program
|
|
616
|
+
.command('mcp')
|
|
617
|
+
.description('run the MCP server (Claude Code starts this for you)')
|
|
618
|
+
.action(async () => {
|
|
619
|
+
const { startMcp } = await import('./mcp.js');
|
|
620
|
+
startMcp();
|
|
621
|
+
});
|
|
622
|
+
program
|
|
623
|
+
.command('init')
|
|
624
|
+
.description('find AI tools, API keys and local models on this computer and connect them')
|
|
625
|
+
.option('--apply', 'connect what was found; without it, nothing is changed')
|
|
626
|
+
.option('--no-open', 'do not open the dashboard afterwards')
|
|
627
|
+
.action(async (o) => {
|
|
628
|
+
// looking changes nothing; addAccount creates the data folder when something is connected
|
|
629
|
+
const found = await detect(loadConfig());
|
|
630
|
+
if (!found.length) {
|
|
631
|
+
console.log('Nothing to connect was found. Run "omnitrix providers" to see what omnitrix supports.');
|
|
632
|
+
// the dashboard shows the same first steps, and updates by itself once something is connected
|
|
633
|
+
await showDashboard(DEFAULT_PORT, o.open, true).catch((err) => console.log(`could not open the dashboard: ${err instanceof Error ? err.message : err}`));
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
console.log('Found on this computer:');
|
|
637
|
+
for (const f of found) {
|
|
638
|
+
const mark = f.action === 'add' ? '+' : f.action === 'connected' ? '=' : '-';
|
|
639
|
+
const state = f.action === 'add' ? (o.apply ? 'connecting' : 'not connected yet')
|
|
640
|
+
: f.action === 'connected' ? `already connected as ${f.connectedAs.join(', ')}` : `not added: ${f.reason}`;
|
|
641
|
+
console.log(` ${mark} ${f.name.padEnd(26)} ${f.how.padEnd(44)} ${state}`);
|
|
642
|
+
}
|
|
643
|
+
const todo = found.filter((f) => f.action === 'add');
|
|
644
|
+
if (!o.apply) {
|
|
645
|
+
console.log(todo.length ? `\nNothing was changed. Run "omnitrix init --apply" to connect the ${todo.length} marked with +.` : '\nEverything found is already connected.');
|
|
646
|
+
}
|
|
647
|
+
else {
|
|
648
|
+
for (const f of todo) {
|
|
649
|
+
console.log(`\n${f.name}:`);
|
|
650
|
+
await addAccount(f.provider, { owner: 'me' });
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
console.log('\nTo use omnitrix from Claude Code, run "omnitrix setup-claude" once, then restart Claude Code.');
|
|
654
|
+
await showDashboard(DEFAULT_PORT, o.open, true).catch((err) => console.log(`could not open the dashboard: ${err instanceof Error ? err.message : err}`));
|
|
655
|
+
});
|
|
656
|
+
function money(v) {
|
|
657
|
+
return `$${v.toFixed(2)}`;
|
|
658
|
+
}
|
|
659
|
+
/** Who this developer is in the team: an explicit name, else their git email, else their login name. */
|
|
660
|
+
function defaultUser() {
|
|
661
|
+
const git = spawnSync('git', ['config', '--global', 'user.email'], { encoding: 'utf8', windowsHide: true });
|
|
662
|
+
return git.status === 0 && git.stdout.trim() ? git.stdout.trim() : os.userInfo().username;
|
|
663
|
+
}
|
|
664
|
+
const team = program.command('team').description('share company API accounts, prices and budgets through a team file');
|
|
665
|
+
team
|
|
666
|
+
.command('join <file>')
|
|
667
|
+
.description('review a team file, then join it with --yes')
|
|
668
|
+
.option('--as <name>', 'who you are in the team (default: your git email)')
|
|
669
|
+
.option('--yes <code>', 'join, giving the review code shown when you reviewed the file')
|
|
670
|
+
.action((file, o) => {
|
|
671
|
+
const full = path.resolve(file);
|
|
672
|
+
let text;
|
|
673
|
+
try {
|
|
674
|
+
text = fs.readFileSync(full, 'utf8');
|
|
675
|
+
}
|
|
676
|
+
catch {
|
|
677
|
+
die(`cannot read ${full}`);
|
|
678
|
+
}
|
|
679
|
+
let parsed;
|
|
680
|
+
try {
|
|
681
|
+
parsed = parseTeam(text);
|
|
682
|
+
}
|
|
683
|
+
catch (err) {
|
|
684
|
+
die(err instanceof Error ? err.message : String(err));
|
|
685
|
+
}
|
|
686
|
+
const user = o.as ?? defaultUser();
|
|
687
|
+
const code = reviewCode(text);
|
|
688
|
+
if (o.yes !== undefined && o.yes !== code) {
|
|
689
|
+
// the code ties the join to the exact contents that were reviewed, so a file edited in between is not pinned
|
|
690
|
+
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`);
|
|
691
|
+
}
|
|
692
|
+
// everything a key could be sent to, so the developer can see where their keys would go
|
|
693
|
+
console.log(`${parsed.name} (${full})`);
|
|
694
|
+
console.log('Accounts, and where their keys would be sent:');
|
|
695
|
+
const warnings = [];
|
|
696
|
+
for (const a of teamAccounts(parsed)) {
|
|
697
|
+
const spec = parsed.accounts.find((s) => s.id === a.id);
|
|
698
|
+
const host = new URL(a.baseUrl).host;
|
|
699
|
+
const official = officialHost(a.provider);
|
|
700
|
+
const where = official === undefined ? `${host} (a custom address)` : host === official ? host : `${host} (not the provider's own address, ${official})`;
|
|
701
|
+
const set = process.env[spec.keyEnv] ? 'set' : 'not set on this computer';
|
|
702
|
+
const limit = [spec.usdPerDay !== undefined ? `${money(spec.usdPerDay)} a day` : '', spec.usdPerMonth !== undefined ? `${money(spec.usdPerMonth)} a month` : ''].filter(Boolean).join(', ');
|
|
703
|
+
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' : ''}`);
|
|
704
|
+
if (PROVIDERS.some((p) => p.keyEnv === spec.keyEnv))
|
|
705
|
+
warnings.push(`${spec.keyEnv} usually holds a personal key; ask the team to use a variable of its own, such as ACME_${spec.keyEnv}`);
|
|
706
|
+
}
|
|
707
|
+
for (const m of unpricedModels(parsed))
|
|
708
|
+
warnings.push(`no price for ${m}, so its requests count as costing nothing against budgets`);
|
|
709
|
+
const b = budgetFor(parsed, user);
|
|
710
|
+
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'}`);
|
|
711
|
+
if (o.as && o.as !== defaultUser())
|
|
712
|
+
console.log(` (your git email is ${defaultUser()})`);
|
|
713
|
+
if (parsed.auditDir)
|
|
714
|
+
console.log(`Your name and your requests on team accounts (account, model, tokens, cost; never prompts or results) are also copied to ${parsed.auditDir}`);
|
|
715
|
+
for (const w of warnings)
|
|
716
|
+
console.log(`warning: ${w}`);
|
|
717
|
+
if (o.yes === undefined) {
|
|
718
|
+
console.log(`\nreview code: ${code}`);
|
|
719
|
+
console.log(`Nothing was changed. If this looks right, join with: omnitrix team join ${file}${o.as ? ` --as ${o.as}` : ''} --yes ${code}`);
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
const clash = updateConfig((cfg) => {
|
|
723
|
+
cfg.settings.team = { file: full, user, sha256: fingerprint(text) };
|
|
724
|
+
return parsed.accounts.filter((a) => cfg.accounts.some((own) => own.id === a.id && !own.team)).map((a) => a.id);
|
|
725
|
+
});
|
|
726
|
+
console.log(`\njoined ${parsed.name} as ${user}`);
|
|
727
|
+
if (clash.length)
|
|
728
|
+
console.log(`note: you already have accounts named ${clash.join(', ')}; your own ones are used, and the team's are not loaded`);
|
|
729
|
+
console.log('If the team file changes later, its accounts stop loading until you review it here again.');
|
|
730
|
+
});
|
|
731
|
+
team
|
|
732
|
+
.command('leave')
|
|
733
|
+
.description('stop using the team file')
|
|
734
|
+
.action(() => {
|
|
735
|
+
const cfg = loadConfig();
|
|
736
|
+
const state = cfg.settings.team ? loadTeam(cfg.settings.team) : undefined;
|
|
737
|
+
if (!state) {
|
|
738
|
+
console.log('You are not in a team.');
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
updateConfig((latest) => {
|
|
742
|
+
latest.settings.team = undefined;
|
|
743
|
+
});
|
|
744
|
+
console.log(`left ${state.team?.name ?? 'the team'}`);
|
|
745
|
+
});
|
|
746
|
+
team
|
|
747
|
+
.command('status', { isDefault: true })
|
|
748
|
+
.description('show the team, who you are and what you have spent')
|
|
749
|
+
.action(() => {
|
|
750
|
+
const cfg = loadConfig();
|
|
751
|
+
if (!cfg.settings.team) {
|
|
752
|
+
console.log('You are not in a team. Join one with: omnitrix team join <file>');
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
const state = loadTeam(cfg.settings.team);
|
|
756
|
+
if (!state.team) {
|
|
757
|
+
console.log(`Team accounts are not loaded: ${state.error}`);
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
const { user } = state.membership;
|
|
761
|
+
const s = personSpend(state.team, user, readLedger(periodStart(Date.now(), 'month')));
|
|
762
|
+
const b = budgetFor(state.team, user);
|
|
763
|
+
console.log(`${state.team.name}, as ${user} (${state.membership.file})`);
|
|
764
|
+
console.log(` today: ${money(s.day)}${b.day !== undefined ? ` of ${money(b.day)}` : ''}`);
|
|
765
|
+
console.log(` this month: ${money(s.month)}${b.month !== undefined ? ` of ${money(b.month)}` : ''}`);
|
|
766
|
+
console.log(` accounts: ${state.accounts.map((a) => a.id).join(', ')}`);
|
|
767
|
+
});
|
|
768
|
+
program
|
|
769
|
+
.command('usage')
|
|
770
|
+
.description('requests, tokens and cost, grouped by person, account or model')
|
|
771
|
+
.addOption(new Option('--by <what>', 'how to group').choices(['person', 'account', 'model']).default('account'))
|
|
772
|
+
.option('--days <n>', 'how far back', int, 30)
|
|
773
|
+
.option('--team', "everyone's usage from the team's shared folder instead of this computer's")
|
|
774
|
+
.action((o) => {
|
|
775
|
+
const since = Date.now() - o.days * 24 * 3600_000;
|
|
776
|
+
let records;
|
|
777
|
+
if (o.team) {
|
|
778
|
+
const cfg = loadConfig();
|
|
779
|
+
const state = cfg.settings.team ? loadTeam(cfg.settings.team) : undefined;
|
|
780
|
+
if (!state?.team?.auditDir)
|
|
781
|
+
die('the team file names no shared folder (auditDir), so there is no team-wide log to read');
|
|
782
|
+
records = readShared(state.team.auditDir, since);
|
|
783
|
+
}
|
|
784
|
+
else {
|
|
785
|
+
records = readLedger(since);
|
|
786
|
+
}
|
|
787
|
+
const groups = new Map();
|
|
788
|
+
for (const r of records) {
|
|
789
|
+
const key = o.by === 'person' ? r.user ?? '(you, outside a team)' : o.by === 'model' ? `${r.accountId}/${r.model}` : r.accountId;
|
|
790
|
+
const g = groups.get(key) ?? { n: 0, failed: 0, tokens: 0, cost: 0 };
|
|
791
|
+
g.n++;
|
|
792
|
+
if (!r.ok)
|
|
793
|
+
g.failed++;
|
|
794
|
+
g.tokens += r.inputTokens + r.outputTokens;
|
|
795
|
+
g.cost += r.costUsd ?? 0;
|
|
796
|
+
groups.set(key, g);
|
|
797
|
+
}
|
|
798
|
+
if (!groups.size) {
|
|
799
|
+
console.log(`no requests in the last ${o.days} days`);
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
const rows = [...groups.entries()].sort((a, b) => b[1].cost - a[1].cost || b[1].n - a[1].n);
|
|
803
|
+
const width = Math.max(...rows.map(([k]) => k.length)) + 2;
|
|
804
|
+
for (const [key, g] of rows) {
|
|
805
|
+
// shared records come from colleagues' machines; never print control characters from them
|
|
806
|
+
const k = key.replace(/[\p{Cc}\p{Cf}]/gu, '?');
|
|
807
|
+
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` : ''}`);
|
|
808
|
+
}
|
|
809
|
+
console.log('\nCosts are those reported by the provider, or estimated from model prices where they are known.');
|
|
810
|
+
});
|
|
811
|
+
program
|
|
812
|
+
.command('setup-claude')
|
|
813
|
+
.description('register omnitrix in Claude Code and add the status line')
|
|
814
|
+
.addOption(new Option('--scope <scope>', 'where to register the MCP server').choices(['user', 'project', 'local']).default('user'))
|
|
815
|
+
.option('--no-statusline', 'do not touch the status line')
|
|
816
|
+
.option('--dry-run', 'only print what would be done')
|
|
817
|
+
.action((o) => {
|
|
818
|
+
const script = fileURLToPath(import.meta.url);
|
|
819
|
+
const node = process.execPath;
|
|
820
|
+
const mcpArgs = ['mcp', 'add', '--scope', o.scope, 'omnitrix', '--', node, script, 'mcp'];
|
|
821
|
+
console.log(`1. claude ${mcpArgs.map((a) => (/\s/.test(a) ? `"${a}"` : a)).join(' ')}`);
|
|
822
|
+
if (!o.dryRun) {
|
|
823
|
+
const claude = resolveCommand('claude');
|
|
824
|
+
if (!claude) {
|
|
825
|
+
console.log(' Claude Code CLI not found on PATH; run the line above yourself after installing it.');
|
|
826
|
+
}
|
|
827
|
+
else {
|
|
828
|
+
const r = spawnSync(claude.file, [...claude.prefix, ...mcpArgs], { stdio: 'inherit', shell: claude.shell });
|
|
829
|
+
if (r.status !== 0)
|
|
830
|
+
console.log(' that did not work; if omnitrix is already registered, remove it with "claude mcp remove omnitrix" and retry.');
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
if (o.statusline) {
|
|
834
|
+
const settingsFile = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'settings.json');
|
|
835
|
+
const command = `"${node}" "${script}" statusline`;
|
|
836
|
+
console.log(`2. statusLine in ${settingsFile}: ${command}`);
|
|
837
|
+
if (!o.dryRun) {
|
|
838
|
+
let settings = {};
|
|
839
|
+
if (fs.existsSync(settingsFile)) {
|
|
840
|
+
try {
|
|
841
|
+
settings = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
|
|
842
|
+
}
|
|
843
|
+
catch {
|
|
844
|
+
die(`${settingsFile} is not valid JSON; fix it first`);
|
|
845
|
+
}
|
|
846
|
+
// keep a copy so the user can always get their old settings back
|
|
847
|
+
fs.copyFileSync(settingsFile, `${settingsFile}.bak-omnitrix`);
|
|
848
|
+
}
|
|
849
|
+
// never replace a status line someone set up themselves
|
|
850
|
+
if (settings.statusLine && !String(settings.statusLine.command ?? '').includes('omnitrix') && !String(settings.statusLine.command ?? '').includes('statusline')) {
|
|
851
|
+
console.log(` you already have a status line (${settings.statusLine.command}); left it alone. Use --no-statusline to skip this step.`);
|
|
852
|
+
}
|
|
853
|
+
else {
|
|
854
|
+
// Claude Code stops redrawing while it waits on tools, so refresh on a timer as well
|
|
855
|
+
settings.statusLine = { type: 'command', command, refreshInterval: 15 };
|
|
856
|
+
fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
|
|
857
|
+
fs.writeFileSync(settingsFile, JSON.stringify(settings, null, 2) + '\n');
|
|
858
|
+
console.log(' done (backup saved next to it).');
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
console.log('Restart Claude Code, then ask it to "use omnitrix" for big jobs.');
|
|
863
|
+
});
|
|
864
|
+
program
|
|
865
|
+
.command('clean')
|
|
866
|
+
.description('delete old job records, outputs and worktrees; --branches also deletes branches no longer needed')
|
|
867
|
+
.option('--days <n>', 'only things older than this many days', int, 14)
|
|
868
|
+
.option('--branches', 'also delete the branches of rejected, failed or cancelled jobs, and of other jobs once merged')
|
|
869
|
+
.option('--dry-run', 'only report what would be deleted')
|
|
870
|
+
.action((o) => {
|
|
871
|
+
const cutoff = Date.now() - o.days * 24 * 3600_000;
|
|
872
|
+
let jobs = 0;
|
|
873
|
+
let trees = 0;
|
|
874
|
+
let branches = 0;
|
|
875
|
+
const kept = [];
|
|
876
|
+
let stuck = 0;
|
|
877
|
+
for (const name of fs.existsSync(files.jobs()) ? fs.readdirSync(files.jobs()) : []) {
|
|
878
|
+
const file = path.join(files.jobs(), name);
|
|
879
|
+
// cancel notes are empty files; one left from a cancel that raced a finishing job is just litter
|
|
880
|
+
if (name.endsWith('.cancel')) {
|
|
881
|
+
if (!o.dryRun && fs.statSync(file).mtimeMs < cutoff)
|
|
882
|
+
fs.rmSync(file, { force: true });
|
|
883
|
+
continue;
|
|
884
|
+
}
|
|
885
|
+
const job = readJson(file, null);
|
|
886
|
+
// a record that is not omnitrix's own for this file name could point anywhere, so it is left alone
|
|
887
|
+
if (!job || `${job.id}.json` !== name || !JOB_ID.test(job.id))
|
|
888
|
+
continue;
|
|
889
|
+
if (job.updatedAt > cutoff || job.status === 'queued' || job.status === 'running')
|
|
890
|
+
continue;
|
|
891
|
+
jobs++;
|
|
892
|
+
// only a worktree inside omnitrix's own folder is ever deleted
|
|
893
|
+
const tree = job.worktree && path.resolve(job.worktree.path) !== path.resolve(files.worktrees()) && inside(job.worktree.path, files.worktrees()) ? job.worktree.path : undefined;
|
|
894
|
+
if (o.dryRun) {
|
|
895
|
+
if (tree)
|
|
896
|
+
trees++;
|
|
897
|
+
}
|
|
898
|
+
else {
|
|
899
|
+
if (tree && pruneWorktree(tree))
|
|
900
|
+
trees++;
|
|
901
|
+
}
|
|
902
|
+
const repo = job.task.repo;
|
|
903
|
+
// only the branch omnitrix made for this job, in a repository given by absolute path, is ever touched
|
|
904
|
+
const branch = job.worktree?.branch === `omnitrix/${job.id}` ? job.worktree.branch : undefined;
|
|
905
|
+
let keepRecord = false;
|
|
906
|
+
if (o.branches && repo && branch && path.isAbsolute(repo) && fs.existsSync(repo) && branchExists(repo, branch)) {
|
|
907
|
+
// rejected or broken work is not wanted; anything else goes only once it is in the repo's history
|
|
908
|
+
const unwanted = job.verdict === 'rejected' || job.status === 'failed' || job.status === 'cancelled';
|
|
909
|
+
if (!unwanted && !branchMerged(repo, branch)) {
|
|
910
|
+
kept.push(branch);
|
|
911
|
+
keepRecord = true;
|
|
912
|
+
}
|
|
913
|
+
else if (o.dryRun || deleteBranch(repo, branch)) {
|
|
914
|
+
branches++;
|
|
915
|
+
}
|
|
916
|
+
else {
|
|
917
|
+
// for example, the branch is checked out somewhere
|
|
918
|
+
stuck++;
|
|
919
|
+
keepRecord = true;
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
// a kept branch keeps its record, so a later clean can still decide about it once it is merged or rejected
|
|
923
|
+
if (o.dryRun || keepRecord)
|
|
924
|
+
continue;
|
|
925
|
+
fs.rmSync(path.join(files.outputs(), `${job.id}.md`), { force: true });
|
|
926
|
+
fs.rmSync(file, { force: true });
|
|
927
|
+
}
|
|
928
|
+
// read-only copies are not on any job record; one left by a process that died is removed once it is old
|
|
929
|
+
for (const name of fs.existsSync(files.worktrees()) ? fs.readdirSync(files.worktrees()) : []) {
|
|
930
|
+
const dir = path.join(files.worktrees(), name);
|
|
931
|
+
if (!/^j[0-9a-z]{4,40}-ro(-[0-9a-z]+)?$/.test(name) || fs.statSync(dir).mtimeMs >= cutoff)
|
|
932
|
+
continue;
|
|
933
|
+
trees++;
|
|
934
|
+
if (!o.dryRun)
|
|
935
|
+
pruneWorktree(dir);
|
|
936
|
+
}
|
|
937
|
+
const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
938
|
+
console.log(`${o.dryRun ? 'would remove' : 'removed'} ${count(jobs, 'old job', 'old jobs')} and ${count(trees, 'worktree', 'worktrees')}`);
|
|
939
|
+
if (o.branches) {
|
|
940
|
+
// Work copied with "git checkout <branch> -- <file>" never counts as merged, so a kept branch is named:
|
|
941
|
+
// only the user knows whether it is still needed.
|
|
942
|
+
const names = kept.sort();
|
|
943
|
+
const shown = names.length ? `: ${names.slice(0, 10).join(', ')}${names.length > 10 ? ', ...' : ''}` : '';
|
|
944
|
+
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}` : ''}`);
|
|
945
|
+
if (names.length)
|
|
946
|
+
console.log('Once a kept branch is no longer needed, delete it with "git branch -D <name>" in its repository.');
|
|
947
|
+
}
|
|
948
|
+
});
|
|
949
|
+
program
|
|
950
|
+
.command('doctor')
|
|
951
|
+
.description('check the setup and every account')
|
|
952
|
+
.action(() => {
|
|
953
|
+
const ok = (b, msg) => console.log(`${b ? ' ok ' : 'FAIL'} ${msg}`);
|
|
954
|
+
const major = Number(process.versions.node.split('.')[0]);
|
|
955
|
+
ok(major >= 20, `node ${process.versions.node} (needs 20+)`);
|
|
956
|
+
ensureHome();
|
|
957
|
+
ok(fs.existsSync(homeDir()), `data folder ${homeDir()}`);
|
|
958
|
+
const cfg = loadConfig();
|
|
959
|
+
ok(cfg.accounts.length > 0, `${cfg.accounts.length} accounts`);
|
|
960
|
+
for (const a of cfg.accounts) {
|
|
961
|
+
if (a.driver === 'cli') {
|
|
962
|
+
const tool = CLI_TOOLS[providerTool(a.provider)];
|
|
963
|
+
ok(!!tool && !!resolveCommand(tool.command), `${a.id}: ${tool?.command ?? a.provider} installed`);
|
|
964
|
+
}
|
|
965
|
+
else {
|
|
966
|
+
const keyOk = a.local || (a.apiKey?.startsWith('env:') ? !!process.env[a.apiKey.slice(4)] : a.apiKey === 'secret');
|
|
967
|
+
ok(keyOk, `${a.id}: API key ${a.apiKey?.startsWith('env:') ? `from ${a.apiKey.slice(4)}` : a.local ? 'not needed' : 'saved'}`);
|
|
968
|
+
}
|
|
969
|
+
ok(a.models.length > 0, `${a.id}: ${a.models.length} models`);
|
|
970
|
+
}
|
|
971
|
+
});
|
|
972
|
+
program.parseAsync().catch((err) => fail(err instanceof Error ? err.message : String(err)));
|