@drsamonline/cli 0.0.0-stage → 0.12.2

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/src/cli.js ADDED
@@ -0,0 +1,676 @@
1
+ /**
2
+ * The `sui` command line.
3
+ *
4
+ * sui first run: find keys, find tools, prove the route, start
5
+ * sui init the same, explicitly
6
+ * sui up run the gateway
7
+ * sui doctor one real turn per combo, and say what broke
8
+ * sui models what this gateway will answer to
9
+ * sui cost what it has spent, and on what
10
+ * sui tools point a coding tool at the gateway
11
+ * sui migrate <file> import providers/aliases from another router
12
+ */
13
+
14
+ import { existsSync, readFileSync, writeFileSync, copyFileSync } from 'node:fs';
15
+ import { createInterface } from 'node:readline/promises';
16
+ import { stdin, stdout } from 'node:process';
17
+ import { dirname, join, resolve } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { createGateway, loadEnvFile } from '@drsamonline/gateway';
20
+ import { auditConfig, defaultConfigPath, hashApiKey, normalizeConfig, providerHasCredentials, sanitizeConfig, suiHome, INVARIANTS } from '@drsamonline/core';
21
+ import { runInit } from './onboarding.js';
22
+ import { detectTools, writeToolConfig } from './tools.js';
23
+ import { applyImport, diffImport, readMigrationSource, smokeTest } from './migrate.js';
24
+ import { cmdBudget, cmdCatalog, cmdCompress, cmdConfig, cmdExplain, cmdKits, cmdLocal, cmdMcp, cmdProbe, cmdRecipe, cmdRedteam, cmdSandbox, cmdSavings, cmdTenants, cmdTokens, cmdVault, writeExport } from './commands-extra.js';
25
+ import { kitStatus } from '@drsamonline/kits';
26
+ import { ConfigError } from '@drsamonline/core';
27
+
28
+ // One source of truth for the version: the package manifest.
29
+ const HERE_DIR = dirname(fileURLToPath(import.meta.url));
30
+ /**
31
+ * How should the user run the next command?
32
+ *
33
+ * `npx sui` only works once the package is on npm, which it is not. Printing it
34
+ * anyway sends people to a command that fails — and the failure looks like a
35
+ * broken install rather than an unpublished package.
36
+ */
37
+ const RUN_AS = (() => {
38
+ const invoked = String(process.argv[1] ?? '');
39
+ // a global install (npm link, or a published package) has a bare `sui` on PATH
40
+ if (/node_modules/.test(invoked) || !/apps[\\/]cli[\\/]bin/.test(invoked)) return 'sui';
41
+ return process.platform === 'win32' ? '.\\sui.cmd' : './sui';
42
+ })();
43
+
44
+ const VERSION = (() => {
45
+ try {
46
+ return JSON.parse(readFileSync(join(HERE_DIR, '..', '..', '..', 'package.json'), 'utf8')).version;
47
+ } catch {
48
+ return '0.0.0-unknown';
49
+ }
50
+ })();
51
+
52
+ export async function run(argv = process.argv.slice(2)) {
53
+ const { command, args, flags } = parse(argv);
54
+
55
+ // `sui --version` and `sui --help` are the two things anyone types first, and
56
+ // both arrive as flags rather than as a command. Answer them before dispatch.
57
+ if (!command && (flags.version === true || flags.v === true)) return console.log(VERSION);
58
+ if (!command && (flags.help === true || flags.h === true)) return help();
59
+
60
+ switch (command) {
61
+ case undefined:
62
+ case 'init':
63
+ return cmdInit(flags);
64
+ case 'up':
65
+ case 'start':
66
+ case 'serve':
67
+ return cmdUp(flags);
68
+ case 'keys':
69
+ return cmdKeys(flags, args);
70
+ case 'catalog':
71
+ return cmdCatalog(flags, args);
72
+ case 'probe':
73
+ return cmdProbe(flags, args);
74
+ case 'compress':
75
+ return cmdCompress(flags, args);
76
+ case 'budget':
77
+ return cmdBudget(flags);
78
+ case 'savings':
79
+ return cmdSavings(flags);
80
+ case 'explain':
81
+ return cmdExplain(flags, args);
82
+ case 'tenants':
83
+ return cmdTenants(flags);
84
+ case 'mcp':
85
+ return cmdMcp(flags);
86
+ case 'recipe':
87
+ return cmdRecipe(flags, args);
88
+ case 'local':
89
+ return cmdLocal(flags);
90
+ case 'sandbox':
91
+ return cmdSandbox(flags, args);
92
+ case 'redteam':
93
+ return cmdRedteam(flags, args);
94
+ case 'vault':
95
+ return cmdVault(flags, args);
96
+ case 'config':
97
+ return cmdConfig(flags, args);
98
+ case 'tokens':
99
+ return cmdTokens(flags);
100
+ case 'kits':
101
+ return cmdKits(flags);
102
+ case 'invariants':
103
+ return cmdInvariants(flags);
104
+ case 'doctor':
105
+ return cmdDoctor(flags);
106
+ case 'models':
107
+ return cmdModels(flags);
108
+ case 'cost':
109
+ case 'usage':
110
+ return cmdCost(flags);
111
+ case 'tools':
112
+ return cmdTools(flags, args);
113
+ case 'migrate':
114
+ return cmdMigrate(flags, args);
115
+ case 'help':
116
+ case '--help':
117
+ case '-h':
118
+ return help();
119
+ case 'version':
120
+ case '--version':
121
+ case '-v':
122
+ return console.log(VERSION);
123
+ default:
124
+ console.error(`Unknown command "${command}". Try: sui help`);
125
+ process.exitCode = 1;
126
+ }
127
+ }
128
+
129
+ /* ------------------------------------------------------------------ commands */
130
+
131
+ async function cmdInit(flags) {
132
+ const interactive = Boolean(stdin.isTTY) && !flags.yes;
133
+ const prompt = interactive ? makePrompt() : null;
134
+ try {
135
+ const result = await runInit({
136
+ cwd: process.cwd(),
137
+ env: loadEnvFile(process.env.SUI_ENV_FILE ?? '.env', { ...process.env }),
138
+ interactive,
139
+ force: Boolean(flags.force),
140
+ demo: Boolean(flags.demo),
141
+ port: flags.port ? Number(flags.port) : undefined,
142
+ prompt,
143
+ });
144
+ if (!result.ok) {
145
+ process.exitCode = 1;
146
+ return;
147
+ }
148
+ if (flags['no-serve'] || !interactive) {
149
+ console.log('');
150
+ console.log(`Start it with: ${RUN_AS} start`);
151
+ return;
152
+ }
153
+ const answer = await prompt.ask('Start the gateway now? (Y/n)', 'y');
154
+ if (/^y/i.test(answer) || answer === '') return cmdUp({ ...flags, config: result.configPath });
155
+ console.log(`Fine — run \`${RUN_AS} start\` when you want it.`);
156
+ } finally {
157
+ prompt?.close();
158
+ }
159
+ }
160
+
161
+ async function cmdUp(flags) {
162
+ // `sui start` is the one place background jobs run.
163
+ //
164
+ // --role and --model-plane override the config for one run, because the
165
+ // two-plane split (B5.7) is a deployment choice, not a property of the file:
166
+ // the same config should be startable as either half.
167
+ const role = flags.role ? String(flags.role) : undefined;
168
+ if (role && !['both', 'model', 'agent'].includes(role)) {
169
+ throw new ConfigError(`Unknown plane role "${role}". Use one of: both, model, agent.`, { path: 'planes.role' });
170
+ }
171
+
172
+ const configOverride = {};
173
+ if (role) configOverride.planes = { ...(configOverride.planes ?? {}), role };
174
+ if (flags['model-plane']) {
175
+ configOverride.planes = { ...(configOverride.planes ?? {}), modelPlaneUrl: String(flags['model-plane']) };
176
+ }
177
+
178
+ const gateway = await createGateway({
179
+ configPath: flags.config,
180
+ startWorkers: flags['no-workers'] !== true,
181
+ ...(Object.keys(configOverride).length ? { configOverride } : {}),
182
+ });
183
+ const { config, server } = gateway;
184
+ const host = config.server.host;
185
+ const port = flags.port ? Number(flags.port) : config.server.port;
186
+
187
+ try {
188
+ await new Promise((res, rej) => {
189
+ server.once('error', rej);
190
+ server.listen(port, host, res);
191
+ });
192
+ } catch (err) {
193
+ const e = /** @type {any} */ (err);
194
+ if (e.code === 'EADDRINUSE') {
195
+ throw new ConfigError(
196
+ `Port ${port} is already in use. Either stop what is on it, or start sui elsewhere: npx sui start --port ${port + 1}`,
197
+ { detail: e.message, path: 'server.port' },
198
+ );
199
+ }
200
+ if (e.code === 'EACCES') {
201
+ throw new ConfigError(`Not allowed to bind ${host}:${port}. Ports below 1024 need elevated privileges — use a higher port and put a proxy in front.`, {
202
+ detail: e.message,
203
+ path: 'server.port',
204
+ });
205
+ }
206
+ throw err;
207
+ }
208
+
209
+ const shown = host === '0.0.0.0' ? '127.0.0.1' : host;
210
+ const combos = Object.keys(config.combos);
211
+ console.log('');
212
+ console.log(`sui ${VERSION} is up`);
213
+ console.log(` endpoint http://${shown}:${port}/v1`);
214
+ console.log(` dashboard http://${shown}:${port}/`);
215
+ console.log(` config ${config.path ?? '(none)'}`);
216
+ console.log(` combos ${combos.join(', ')}`);
217
+ console.log(` paid tier ${config.paidTiers?.enabled ? 'ENABLED — paid credentials will load' : 'closed (paid credentials are never read)'}`);
218
+ const unconfigured = Object.entries(config.models)
219
+ .filter(([, m]) => !providerHasCredentials(config.providers[/** @type {any} */ (m).provider], config.env))
220
+ .map(([id]) => id);
221
+ if (unconfigured.length) console.log(` no key yet ${unconfigured.join(', ')}`);
222
+ console.log('');
223
+ const jobs = gateway.workers.snapshot();
224
+ if (jobs.enabled && jobs.jobs.length) {
225
+ console.log(` workers ${jobs.jobs.map((j) => `${j.name} every ${Math.round(j.intervalMs / 1000)}s`).join(', ')}`);
226
+ } else {
227
+ console.log(' workers off (pass --no-workers to keep them off, or set workers.enabled:false)');
228
+ }
229
+ console.log('Ctrl-C to stop.');
230
+
231
+ const shutdown = () => {
232
+ console.log('\nstopping…');
233
+ gateway.workers.stop();
234
+ server.close(() => process.exit(0));
235
+ setTimeout(() => process.exit(0), 1500).unref();
236
+ };
237
+ process.on('SIGINT', shutdown);
238
+ process.on('SIGTERM', shutdown);
239
+ }
240
+
241
+ async function cmdDoctor(flags) {
242
+ const gateway = await createGateway({ configPath: flags.config, ledgerFile: null });
243
+ const { config, router } = gateway;
244
+ const combos = flags.combo ? [String(flags.combo)] : Object.keys(config.combos);
245
+
246
+ console.log('');
247
+ console.log('sui doctor — one real turn per combo');
248
+ console.log('');
249
+
250
+ const rows = [];
251
+ let anyOk = false;
252
+ for (const combo of combos) {
253
+ const started = Date.now();
254
+ try {
255
+ const res = await router.chat({
256
+ combo,
257
+ body: { messages: [{ role: 'user', content: 'Reply with the single word: ready' }], max_tokens: 16 },
258
+ });
259
+ anyOk = true;
260
+ rows.push([
261
+ combo,
262
+ 'ok',
263
+ res.meta.modelId,
264
+ res.meta.provider,
265
+ `${res.meta.latencyMs} ms`,
266
+ `${res.usage.prompt_tokens}+${res.usage.completion_tokens} tok`,
267
+ `$${res.meta.costUsd.toFixed(6)}`,
268
+ ]);
269
+ } catch (err) {
270
+ const message = /** @type {any} */ (err).message ?? String(err);
271
+ rows.push([combo, 'failed', '—', '—', `${Date.now() - started} ms`, '—', message.slice(0, 80)]);
272
+ }
273
+ }
274
+
275
+ console.log(table(['combo', 'result', 'answered by', 'provider', 'latency', 'tokens', 'cost'], rows));
276
+
277
+ const healthy = Object.entries(config.models).filter(([, m]) =>
278
+ providerHasCredentials(config.providers[/** @type {any} */ (m).provider], config.env),
279
+ ).length;
280
+ console.log('');
281
+ console.log(`${healthy} of ${Object.keys(config.models).length} models have credentials.`);
282
+
283
+ const kits = kitStatus();
284
+ const kitsBroken = kits.filter((k) => !k.loaded);
285
+ console.log('');
286
+ console.log(`Vendored kits: ${kits.length - kitsBroken.length}/${kits.length} loaded${kitsBroken.length ? ` — broken: ${kitsBroken.map((k) => k.name).join(', ')}` : ''}`);
287
+ console.log(`Paid vault: ${config.vault?.reason ?? 'not opened'}`);
288
+
289
+ const audit = auditConfig(config);
290
+ const failing = audit.filter((a) => !a.ok);
291
+ console.log('');
292
+ console.log('Invariants that can be checked without sending a request');
293
+ for (const a of audit) console.log(` ${a.ok ? 'ok ' : 'WARN'} ${a.id} ${a.detail}`);
294
+ if (failing.length) console.log(`\n${failing.length} invariant warning(s) — see docs/ARCHITECTURE.md and \`${RUN_AS} invariants\`.`);
295
+ if (!anyOk) {
296
+ console.log('No combo answered. That is the thing to fix before anything else.');
297
+ process.exitCode = 1;
298
+ }
299
+ }
300
+
301
+ async function cmdModels(flags) {
302
+ const gateway = await createGateway({ configPath: flags.config, ledgerFile: null });
303
+ const { config } = gateway;
304
+ if (flags.json) {
305
+ console.log(JSON.stringify(sanitizeConfig(config), null, 2));
306
+ return;
307
+ }
308
+ console.log('');
309
+ console.log('Combos — the names your tools call');
310
+ console.log('');
311
+ const comboRows = Object.entries(config.combos).map(([id, c]) => {
312
+ const combo = /** @type {any} */ (c);
313
+ const targets = combo.targets.map((t) => (typeof t === 'string' ? t : `${t.model} (${t.weight})`));
314
+ return [id, combo.strategy, combo.label ?? '', targets.join(' → ')];
315
+ });
316
+ console.log(table(['combo', 'strategy', 'what it is', 'order'], comboRows));
317
+
318
+ console.log('');
319
+ console.log('Models — what a combo can reach');
320
+ console.log('');
321
+ const modelRows = Object.entries(config.models).map(([id, m]) => {
322
+ const model = /** @type {any} */ (m);
323
+ const ready = providerHasCredentials(config.providers[model.provider], config.env);
324
+ const cost = model.costPer1kIn != null ? `$${model.costPer1kIn}/$${model.costPer1kOut} per 1k` : 'not priced';
325
+ return [id, model.provider, model.model, ready ? 'ready' : `needs ${config.providers[model.provider]?.apiKeyEnv ?? 'credentials'}`, cost];
326
+ });
327
+ console.log(table(['model', 'provider', 'upstream name', 'status', 'cost in/out'], modelRows));
328
+ }
329
+
330
+ async function cmdCost(flags) {
331
+ const gateway = await createGateway({ configPath: flags.config });
332
+ const { ledger, config } = gateway;
333
+ const today = new Date();
334
+ today.setHours(0, 0, 0, 0);
335
+ const agg = ledger.aggregate({ since: flags.all ? 0 : today.getTime() });
336
+
337
+ // B7.1: charge-back view — who asked, and with what
338
+ if (flags.by === 'user' || flags.by === 'tool') {
339
+ const groups = flags.by === 'user' ? agg.byUser : agg.byTool;
340
+ console.log('');
341
+ console.log(`Cost by ${flags.by}`);
342
+ console.log('');
343
+ console.log(
344
+ table(
345
+ [flags.by, 'turns', 'failed', 'cost'],
346
+ Object.entries(groups)
347
+ .sort((a, b) => b[1].costUsd - a[1].costUsd)
348
+ .map(([name, g]) => [name, String(g.turns), String(g.failed), `$${g.costUsd.toFixed(4)}`]),
349
+ ),
350
+ );
351
+ console.log('');
352
+ return;
353
+ }
354
+
355
+ if (flags.json) {
356
+ console.log(JSON.stringify(agg, null, 2));
357
+ return;
358
+ }
359
+
360
+ const daily = config.budgets.dailyUsd;
361
+ const spent = ledger.todaySpendUsd();
362
+ console.log('');
363
+ console.log(`Spend today $${spent.toFixed(4)}${daily ? ` of $${Number(daily).toFixed(2)} (${Math.min(100, Math.round((spent / Number(daily)) * 100))}%)` : ''}`);
364
+ if (daily) console.log(`Budget ${bar(spent / Number(daily), 32)}`);
365
+ console.log(`Turns ${agg.totals.turns} (${agg.totals.ok} ok, ${agg.totals.failed} failed, ${agg.totals.cached} cached)`);
366
+ console.log(`Tokens ${agg.totals.promptTokens} in / ${agg.totals.completionTokens} out`);
367
+ console.log(`Latency p50 ${agg.totals.p50LatencyMs} ms · p95 ${agg.totals.p95LatencyMs} ms · first token ${agg.totals.avgTtftMs} ms`);
368
+ console.log('');
369
+
370
+ const providerRows = Object.entries(agg.byProvider).map(([id, v]) => [
371
+ id, String(/** @type {any} */ (v).turns), `$${/** @type {any} */ (v).costUsd.toFixed(4)}`, `${/** @type {any} */ (v).avgLatencyMs} ms`,
372
+ ]);
373
+ if (providerRows.length) console.log(table(['provider', 'turns', 'cost', 'avg latency'], providerRows));
374
+
375
+ const armRows = Object.entries(agg.byArm).map(([id, v]) => [
376
+ id, String(/** @type {any} */ (v).turns), `$${/** @type {any} */ (v).costUsd.toFixed(4)}`, `${/** @type {any} */ (v).avgLatencyMs} ms`,
377
+ ]);
378
+ if (armRows.length) {
379
+ console.log('');
380
+ console.log('A/B arms');
381
+ console.log(table(['combo/arm', 'turns', 'cost', 'avg latency'], armRows));
382
+ }
383
+ if (flags.export || flags.gzip) {
384
+ await writeExport({
385
+ ledger,
386
+ file: typeof flags.export === 'string' ? flags.export : undefined,
387
+ format: flags.json ? 'json' : 'csv',
388
+ gzip: Boolean(flags.gzip),
389
+ });
390
+ } else {
391
+ console.log('');
392
+ console.log(`Export: ${RUN_AS} cost --export usage.csv [--gzip] (or the dashboard's Export CSV)`);
393
+ }
394
+ }
395
+
396
+ async function cmdTools(flags, args) {
397
+ const tools = detectTools({ env: loadEnvFile('.env', { ...process.env }) });
398
+ const want = flags.set ?? args[0];
399
+
400
+ if (want) {
401
+ const configPath = defaultConfigPath();
402
+ const config = configPath ? JSON.parse(readFileSync(configPath, 'utf8')) : null;
403
+ if (!config) throw new ConfigError('No config yet. Run `npx sui init` first.');
404
+ const combo = flags.combo ?? Object.keys(config.combos ?? {})[0];
405
+ const port = config.server?.port ?? 8787;
406
+ const result = writeToolConfig(want, {
407
+ baseUrl: `http://${config.server?.host === '0.0.0.0' ? '127.0.0.1' : config.server?.host ?? '127.0.0.1'}:${port}`,
408
+ combo,
409
+ apiKey: config.apiKeys?.[0]?.key ?? 'sui-local',
410
+ dryRun: Boolean(flags['dry-run']),
411
+ });
412
+ console.log(result.message);
413
+ if (result.snippet) console.log(result.snippet);
414
+ if (!result.ok) process.exitCode = 1;
415
+ return;
416
+ }
417
+
418
+ console.log('');
419
+ console.log('Coding tools on this machine');
420
+ console.log('');
421
+ console.log(
422
+ table(
423
+ ['tool', 'status', 'setup', 'where'],
424
+ tools.map((t) => [
425
+ t.name,
426
+ t.detected ? 'found' : 'not found',
427
+ t.setup === 'file' ? 'I can write it' : 'paste 2 fields',
428
+ t.detected ? t.configPath ?? t.evidence ?? '—' : '—',
429
+ ]),
430
+ ),
431
+ );
432
+ console.log('');
433
+ console.log(`Point one at the gateway: ${RUN_AS} tools --set continue`);
434
+ console.log('Available ids: ' + tools.map((t) => t.id).join(', '));
435
+ }
436
+
437
+ async function cmdMigrate(flags, args) {
438
+ const file = args[0] ?? flags.from;
439
+ if (!file) {
440
+ throw new ConfigError('Say which config to import: npx sui migrate ./9router.json');
441
+ }
442
+ const imported = readMigrationSource(resolve(file));
443
+ const configPath = flags.config ?? defaultConfigPath();
444
+ if (!configPath) throw new ConfigError('No sui config yet. Run `npx sui init` first.');
445
+ const currentRaw = JSON.parse(readFileSync(configPath, 'utf8'));
446
+ const gateway = await createGateway({ configPath, ledgerFile: null });
447
+ const diff = diffImport(gateway.config, imported);
448
+
449
+ console.log('');
450
+ console.log(`Reading ${file} — looks like ${imported.source}`);
451
+ console.log('');
452
+ console.log(`Found ${Object.keys(imported.providers).length} providers · ${Object.keys(imported.models).length} models · ${Object.keys(imported.combos).length} combos`);
453
+ console.log('');
454
+ console.log('New to your config');
455
+ console.log(` providers ${diff.added.providers.join(', ') || '—'}`);
456
+ console.log(` models ${diff.added.models.join(', ') || '—'}`);
457
+ console.log(` combos ${diff.added.combos.join(', ') || '—'}`);
458
+ if (diff.conflicts.length) {
459
+ console.log('');
460
+ console.log('Skipped (already exist here)');
461
+ for (const c of diff.conflicts) console.log(` ${c.kind} ${c.id} — ${c.reason}`);
462
+ }
463
+ if (diff.dangling.length) {
464
+ console.log('');
465
+ console.log(`Models whose provider is not coming along: ${diff.dangling.join(', ')}`);
466
+ }
467
+ if (diff.danglingCombos.length) {
468
+ console.log(`Combos pointing at models that are not coming along: ${diff.danglingCombos.join(', ')}`);
469
+ }
470
+ if (imported.warnings.length) {
471
+ console.log('');
472
+ console.log('Notes');
473
+ for (const w of imported.warnings) console.log(` - ${w}`);
474
+ }
475
+ if (imported.unknownKeys.length) {
476
+ console.log('');
477
+ console.log(`Keys I did not recognise (left untouched): ${imported.unknownKeys.join(', ')}`);
478
+ }
479
+
480
+ if (!flags.apply) {
481
+ console.log('');
482
+ console.log(`Nothing written. Re-run with --apply to import ${diff.total} entr${diff.total === 1 ? 'y' : 'ies'}.`);
483
+ return;
484
+ }
485
+
486
+ const select = flags.only
487
+ ? {
488
+ providers: diff.added.providers.filter((id) => String(flags.only).split(',').includes(id)),
489
+ models: diff.added.models.filter((id) => String(flags.only).split(',').includes(id)),
490
+ combos: diff.added.combos.filter((id) => String(flags.only).split(',').includes(id)),
491
+ }
492
+ : {};
493
+ const next = applyImport(currentRaw, imported, select);
494
+ const backup = `${configPath}.bak-${Date.now()}`;
495
+ copyFileSync(configPath, backup);
496
+ writeFileSync(configPath, JSON.stringify(next, null, 2) + '\n');
497
+ console.log('');
498
+ console.log(`Imported into ${configPath} (previous version kept as ${backup}).`);
499
+
500
+ const importedCombos = (select.combos?.length ? select.combos : diff.added.combos).filter((c) => next.combos[c]);
501
+ if (!importedCombos.length) {
502
+ console.log('No new combos to smoke-test.');
503
+ return;
504
+ }
505
+ console.log('');
506
+ console.log('Smoke test — one small turn per imported combo');
507
+ const fresh = await createGateway({ configPath, ledgerFile: null });
508
+ const results = await smokeTest(fresh.router, importedCombos);
509
+ console.log(
510
+ table(
511
+ ['combo', 'result', 'provider', 'note'],
512
+ results.map((r) => [r.combo, r.status, r.provider ?? '—', r.note ?? `${r.ms} ms`]),
513
+ ),
514
+ );
515
+ if (results.some((r) => r.status === 'failed')) process.exitCode = 1;
516
+ }
517
+
518
+ /**
519
+ * `sui keys hash` — replace plaintext API keys in the config with SHA-256
520
+ * hashes, so a leaked config file is not a leaked key (I15).
521
+ */
522
+ async function cmdKeys(flags, args) {
523
+ const sub = args[0] ?? (flags.hash ? 'hash' : null);
524
+ if (sub !== 'hash') {
525
+ console.log('');
526
+ console.log('Usage: npx sui keys hash [--config <file>]');
527
+ console.log('');
528
+ console.log('Rewrites every plaintext key in apiKeys as a SHA-256 hash. The keys');
529
+ console.log('themselves still work — they are simply no longer stored in the file.');
530
+ return;
531
+ }
532
+ const path = flags.config ?? defaultConfigPath();
533
+ if (!path) throw new ConfigError('No config found. Run `npx sui init` first.');
534
+ const raw = JSON.parse(readFileSync(path, 'utf8'));
535
+ const keys = Array.isArray(raw.apiKeys) ? raw.apiKeys : [];
536
+ let changed = 0;
537
+ for (const k of keys) {
538
+ if (k.key && !k.key_hash) {
539
+ k.key_hash = hashApiKey(k.key);
540
+ delete k.key;
541
+ changed += 1;
542
+ }
543
+ }
544
+ if (!changed) {
545
+ console.log('Nothing to do: every configured key is already hashed, or there are none.');
546
+ return;
547
+ }
548
+ copyFileSync(path, `${path}.bak-${Date.now()}`);
549
+ writeFileSync(path, JSON.stringify(raw, null, 2) + '\n');
550
+ console.log(`Hashed ${changed} key(s) in ${path}. Previous version kept as a .bak file.`);
551
+ console.log('Restart the gateway to pick it up.');
552
+ }
553
+
554
+ function cmdInvariants(flags) {
555
+ const gatewayConfig = flags.config ? createGatewayConfig(flags.config) : createGatewayConfig();
556
+ const audit = auditConfig(gatewayConfig);
557
+ console.log('');
558
+ console.log('Invariants');
559
+ console.log('');
560
+ console.log(table(['id', 'status', 'statement'], INVARIANTS.map((i) => [i.id, i.status, i.statement])));
561
+ console.log('');
562
+ console.log('Checked now');
563
+ for (const a of audit) console.log(` ${a.ok ? 'ok ' : 'WARN'} ${a.id} ${a.detail}`);
564
+ console.log('');
565
+ const gaps = INVARIANTS.filter((i) => i.gap);
566
+ if (gaps.length) {
567
+ console.log('Known gaps');
568
+ for (const g of gaps) console.log(` ${g.id} ${g.gap}`);
569
+ console.log('');
570
+ }
571
+ }
572
+
573
+ function createGatewayConfig(path) {
574
+ const resolved = path ?? defaultConfigPath();
575
+ if (!resolved) throw new ConfigError('No config found. Run `npx sui init` first.');
576
+ return normalizeConfig(JSON.parse(readFileSync(resolved, 'utf8')), { path: resolved, env: loadEnvFile('.env', { ...process.env }) });
577
+ }
578
+
579
+ function help() {
580
+ console.log(`
581
+ sui ${VERSION} — one endpoint for every LLM
582
+
583
+ npx sui first run: find keys, find tools, prove the route, start
584
+ npx sui init the same, explicitly --demo --force --port 8787
585
+ npx sui start run the gateway --port 8787 --config <file> --no-workers
586
+ (aliases: up, serve)
587
+ npx sui invariants every hard constraint, and which are enforced
588
+ npx sui keys hash replace plaintext API keys with SHA-256 hashes
589
+ npx sui doctor one real turn per combo, and say what broke
590
+ npx sui models the combos and what they can reach --json
591
+ npx sui cost spend, latency and A/B arms --json --all (alias: usage)
592
+ --by user|tool for charge-back attribution
593
+ npx sui tools point a coding tool here --set <tool-id>
594
+ npx sui migrate <file> import from 9router / OmniRoute / HubGate --apply --only a,b
595
+ npx sui catalog [q] the provider catalogue, and what is still unverified
596
+ npx sui probe [name] liveness, readiness and suitability checks (B2.3)
597
+ npx sui compress <file|-> [--preset lite|standard|aggressive|ultra] [--text "…"]
598
+ npx sui budget which preset the remaining quota would choose
599
+ npx sui savings what cache hits and compression did not spend --all
600
+ npx sui explain [combo] why a route would go where it goes (B7.4)
601
+ npx sui tenants what each API key has spent, and what it may reach
602
+ npx sui mcp serve the gateway over MCP --transport stdio|http --port 8788
603
+ npx sui recipe list named config patches: list, show, apply --dry-run --force
604
+ npx sui local find a model server on this machine --write --timeout 300
605
+ npx sui sandbox run code in a contained process --self-test --wall --heap
606
+ npx sui redteam [combo] attack your own route with 10 obfuscations (B6.2)
607
+ npx sui vault <cmd> init | set <provider> | list | remove <provider> | status
608
+ npx sui config <cmd> show | get <path> | set <path> <value> | unset <path>
609
+ npx sui tokens --check WCAG AA on the dashboard tokens, computed by tokens-kit
610
+ npx sui kits the vendored kits and whether they load
611
+
612
+ Endpoint, once running: http://127.0.0.1:8787/v1
613
+ Dashboard: http://127.0.0.1:8787/
614
+ Docs: docs/ARCHITECTURE.md, docs/ROUTING.md, docs/MIGRATION.md
615
+ `);
616
+ }
617
+
618
+ /* ------------------------------------------------------------------- helpers */
619
+
620
+ /** Flags that take a value, so `--config ./x.json` works as well as `--config=./x.json`. */
621
+ const VALUE_FLAGS = new Set(['config', 'port', 'set', 'only', 'from', 'combo', 'env', 'export', 'provider', 'key', 'q', 'preset', 'text', 'out', 'fraction', 'timeout', 'by', 'transport', 'wall', 'heap', 'file', 'role', 'model-plane']);
622
+
623
+ function parse(argv) {
624
+ const args = [];
625
+ const flags = {};
626
+ let command;
627
+ for (let i = 0; i < argv.length; i++) {
628
+ const a = argv[i];
629
+ if (a.startsWith('--')) {
630
+ const [k, inline] = a.slice(2).split('=');
631
+ if (inline !== undefined) {
632
+ flags[k] = inline;
633
+ } else if (VALUE_FLAGS.has(k) && argv[i + 1] && !argv[i + 1].startsWith('-')) {
634
+ flags[k] = argv[++i];
635
+ } else {
636
+ flags[k] = true;
637
+ }
638
+ } else if (a.startsWith('-') && a.length === 2) {
639
+ flags[a.slice(1)] = true;
640
+ } else if (!command && !/^\d+$/.test(a)) {
641
+ command = a;
642
+ } else {
643
+ args.push(a);
644
+ }
645
+ }
646
+ return { command, args, flags };
647
+ }
648
+
649
+ function makePrompt() {
650
+ const rl = createInterface({ input: stdin, output: stdout });
651
+ return {
652
+ ask: (q, dflt = '') => rl.question(`${q}${dflt ? ` [${dflt}]` : ''} `).then((a) => (a.trim() || dflt)),
653
+ async choose(q, options) {
654
+ console.log('');
655
+ console.log(q);
656
+ options.forEach((o, i) => console.log(` ${i + 1}. ${o}`));
657
+ const answer = await rl.question(`Pick 1-${options.length} [${options.length}] `);
658
+ const idx = Number(answer.trim() || options.length) - 1;
659
+ return options[Math.min(Math.max(idx, 0), options.length - 1)];
660
+ },
661
+ close: () => rl.close(),
662
+ };
663
+ }
664
+
665
+ function table(headers, rows) {
666
+ const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => String(r[i] ?? '').length)));
667
+ const line = (cells) => ' ' + cells.map((c, i) => String(c ?? '').padEnd(widths[i])).join(' ').trimEnd();
668
+ return [line(headers), ' ' + widths.map((w) => '─'.repeat(w)).join(' '), ...rows.map(line)].join('\n');
669
+ }
670
+
671
+ function bar(ratio, width) {
672
+ const filled = Math.max(0, Math.min(width, Math.round(ratio * width)));
673
+ return `[${'█'.repeat(filled)}${'░'.repeat(width - filled)}]`;
674
+ }
675
+
676
+ export { table, bar };