@token-dashboard/codex-usage-uploader 0.1.5 → 0.1.7

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 DELETED
@@ -1,753 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { CodexUsageUploader } from './collector.js';
4
- import { identityIsBound, promptConfirm } from './auth.js';
5
- import { CLI_NAME, DEFAULT_BACKEND_URL, DEFAULT_CONFIG_FILE, PRODUCT_NAME } from './constants.js';
6
- import { ensurePathInShellConfigs, findPackageRoot, getPackageVersion, installCurrentPackage, removePathFromShellConfigs } from './install.js';
7
- import { LaunchdServiceManager } from './launchd.js';
8
- import { collectLocalUsage, getLocalTimeZone } from './local-usage.js';
9
- import { formatStatusOutput, mergeRuntimeConfig, saveRuntimeConfig } from './runtime-config.js';
10
- import { StateDb } from './state-db.js';
11
-
12
- const HELP_TEXT = `${PRODUCT_NAME}
13
-
14
- Usage:
15
- ${CLI_NAME} init [--backend-url <url>] [--interval 30] [--yes] [--package-spec <spec>]
16
- ${CLI_NAME} bind [--email <email>] [--employee-name <name>] [--employee-id <id>] [--yes]
17
- ${CLI_NAME} clear [--yes]
18
- ${CLI_NAME} start
19
- ${CLI_NAME} stop
20
- ${CLI_NAME} restart
21
- ${CLI_NAME} status
22
- ${CLI_NAME} usage [--period <today|7d|30d|all>] [--from <date>] [--to <date>]
23
- ${CLI_NAME} logs [--lines 100]
24
- ${CLI_NAME} uninstall
25
-
26
- Common options:
27
- --config-file <path> Runtime config path. Default: ${DEFAULT_CONFIG_FILE}
28
- --backend-url <url> Dashboard backend URL
29
- --interval <seconds> Scan interval in seconds
30
- --codex-auth <path> Codex auth.json path
31
- --sessions-dir <path> Codex rollout root directory
32
- --state-db <path> Local SQLite state DB path
33
- --employee-id <id> Bind employee ID
34
- --email <email> Bind employee email
35
- --employee-name <name> Bind employee name
36
- --device-id <id> Override device ID
37
- --hostname <name> Override hostname
38
- --period <value> Usage range: today, 7d, 30d, or all
39
- --from <date> Usage range start date (YYYY-MM-DD)
40
- --to <date> Usage range end date (YYYY-MM-DD)
41
- --yes Skip interactive prompts
42
- --package-spec <spec> npm install spec used by init
43
- --lines <n> Number of log lines for service logs
44
- -v, --version Show version
45
- -h, --help Show help
46
- `;
47
-
48
- class CliOperationalError extends Error {
49
- constructor(message) {
50
- super(message);
51
- this.name = 'CliOperationalError';
52
- this.showUsage = false;
53
- }
54
- }
55
-
56
- export const cliDeps = {
57
- findPackageRoot,
58
- installCurrentPackage,
59
- ensurePathInShellConfigs,
60
- removePathFromShellConfigs,
61
- promptConfirm,
62
- createUploader(runtime) {
63
- return new CodexUsageUploader({
64
- sessionsDir: runtime.sessionsDir,
65
- stateDbPath: runtime.stateDbPath,
66
- backendUrl: runtime.backendUrl,
67
- intervalSeconds: runtime.intervalSeconds,
68
- codexAuthPath: runtime.codexAuthPath,
69
- persistentCollectorIdPath: runtime.persistentCollectorIdPath,
70
- });
71
- },
72
- createServiceManager(runtime) {
73
- return new LaunchdServiceManager(runtime);
74
- },
75
- };
76
-
77
- export function parseCliArgs(argv) {
78
- const options = {
79
- configFile: DEFAULT_CONFIG_FILE,
80
- interval: undefined,
81
- yes: false,
82
- lines: 100,
83
- };
84
- const positionals = [];
85
-
86
- for (let index = 0; index < argv.length; index += 1) {
87
- const token = argv[index];
88
- if (!token.startsWith('-')) {
89
- positionals.push(token);
90
- continue;
91
- }
92
-
93
- if (token === '-h' || token === '--help') {
94
- options.help = true;
95
- continue;
96
- }
97
- if (token === '-v' || token === '--version') {
98
- options.version = true;
99
- continue;
100
- }
101
- if (token === '--yes') {
102
- options.yes = true;
103
- continue;
104
- }
105
-
106
- const [key, inlineValue] = token.split('=', 2);
107
- const takesValue = new Set([
108
- '--config-file',
109
- '--backend-url',
110
- '--interval',
111
- '--codex-auth',
112
- '--sessions-dir',
113
- '--state-db',
114
- '--employee-id',
115
- '--email',
116
- '--employee-name',
117
- '--device-id',
118
- '--hostname',
119
- '--period',
120
- '--from',
121
- '--to',
122
- '--package-spec',
123
- '--lines',
124
- ]);
125
- if (!takesValue.has(key)) {
126
- throw new Error(`Unknown argument: ${token}`);
127
- }
128
- const value = inlineValue ?? argv[++index];
129
- if (value == null || value.startsWith('-')) {
130
- throw new Error(`Missing value for ${key}`);
131
- }
132
- assignOption(options, key, value);
133
- }
134
-
135
- return {
136
- command: positionals[0] ?? null,
137
- subcommand: positionals[1] ?? null,
138
- extraPositionals: positionals.slice(2),
139
- options,
140
- };
141
- }
142
-
143
- function assignOption(options, key, value) {
144
- switch (key) {
145
- case '--config-file':
146
- options.configFile = value;
147
- break;
148
- case '--backend-url':
149
- options.backendUrl = value;
150
- break;
151
- case '--interval':
152
- options.interval = parsePositiveInt(value, '--interval');
153
- break;
154
- case '--codex-auth':
155
- options.codexAuthPath = value;
156
- break;
157
- case '--sessions-dir':
158
- options.sessionsDir = value;
159
- break;
160
- case '--state-db':
161
- options.stateDbPath = value;
162
- break;
163
- case '--employee-id':
164
- options.employeeId = value;
165
- break;
166
- case '--email':
167
- options.employeeEmail = value;
168
- break;
169
- case '--employee-name':
170
- options.employeeName = value;
171
- break;
172
- case '--device-id':
173
- options.deviceId = value;
174
- break;
175
- case '--hostname':
176
- options.hostname = value;
177
- break;
178
- case '--period':
179
- options.period = value;
180
- break;
181
- case '--from':
182
- options.from = value;
183
- break;
184
- case '--to':
185
- options.to = value;
186
- break;
187
- case '--package-spec':
188
- options.packageSpec = value;
189
- break;
190
- case '--lines':
191
- options.lines = parsePositiveInt(value, '--lines');
192
- break;
193
- default:
194
- throw new Error(`Unknown argument: ${key}`);
195
- }
196
- }
197
-
198
- function parsePositiveInt(value, label) {
199
- const parsed = Number.parseInt(String(value), 10);
200
- if (!Number.isFinite(parsed) || parsed <= 0) {
201
- throw new Error(`${label} must be a positive integer`);
202
- }
203
- return parsed;
204
- }
205
-
206
- function runtimeOverrides(options) {
207
- const overrides = {};
208
- if (options.backendUrl !== undefined) overrides.backendUrl = options.backendUrl;
209
- if (options.interval !== undefined) overrides.intervalSeconds = options.interval;
210
- if (options.codexAuthPath !== undefined) overrides.codexAuthPath = options.codexAuthPath;
211
- if (options.sessionsDir !== undefined) overrides.sessionsDir = options.sessionsDir;
212
- if (options.stateDbPath !== undefined) overrides.stateDbPath = options.stateDbPath;
213
- return overrides;
214
- }
215
-
216
- function identityOverrides(options) {
217
- const overrides = {};
218
- if (options.employeeId !== undefined) overrides.employeeId = options.employeeId;
219
- if (options.employeeEmail !== undefined) overrides.employeeEmail = options.employeeEmail;
220
- if (options.employeeName !== undefined) overrides.employeeName = options.employeeName;
221
- if (options.deviceId !== undefined) overrides.deviceId = options.deviceId;
222
- if (options.hostname !== undefined) overrides.hostname = options.hostname;
223
- return overrides;
224
- }
225
-
226
- function assertBoundIdentity(uploader) {
227
- if (!identityIsBound(uploader.identity)) {
228
- throw new CliOperationalError(
229
- 'No employee identity is bound yet. Run `codex-usage-uploader bind` or rerun `init` with --email.',
230
- );
231
- }
232
- }
233
-
234
- function printUsage() {
235
- console.log(HELP_TEXT);
236
- }
237
-
238
- function validateCommandShape(command, subcommand, extraPositionals) {
239
- if (subcommand) {
240
- throw new Error(`Unexpected subcommand for ${command}: ${subcommand}`);
241
- }
242
- if (extraPositionals.length > 0) {
243
- throw new Error(`Unexpected extra arguments: ${extraPositionals.join(' ')}`);
244
- }
245
- }
246
-
247
- function printIdentity(identity) {
248
- console.log('Identity binding:');
249
- console.log(` collectorId: ${identity.collectorId}`);
250
- console.log(` employeeEmail: ${identity.employeeEmail ?? '-'}`);
251
- console.log(` employeeName: ${identity.employeeName ?? '-'}`);
252
- console.log(` employeeId: ${identity.employeeId ?? '-'}`);
253
- console.log(` deviceId: ${identity.deviceId ?? '-'}`);
254
- console.log(` hostname: ${identity.hostname ?? '-'}`);
255
- }
256
-
257
- function tailFile(filePath, lines) {
258
- if (!fs.existsSync(filePath)) return [];
259
- const content = fs.readFileSync(filePath, 'utf8');
260
- return content
261
- .split(/\r?\n/)
262
- .filter((line, index, array) => !(index === array.length - 1 && line === ''))
263
- .slice(-lines);
264
- }
265
-
266
- async function bindIdentity(uploader, options) {
267
- const overrides = identityOverrides(options);
268
- if (options.yes) {
269
- const identity = uploader.configureIdentityWithDefaults(overrides);
270
- assertBoundIdentity(uploader);
271
- return identity;
272
- }
273
- const identity = await uploader.configureIdentityInteractive(overrides);
274
- assertBoundIdentity(uploader);
275
- return identity;
276
- }
277
-
278
- function formatDuration(durationMs) {
279
- const seconds = Math.max(0, Math.round(durationMs / 1000));
280
- return `${seconds}s`;
281
- }
282
-
283
- function printCatchUpProgress(event) {
284
- switch (event.phase) {
285
- case 'start':
286
- console.log(`[scan] start files=${event.totalFiles}`);
287
- return;
288
- case 'file':
289
- console.log(
290
- `[scan] file ${event.filesProcessed}/${event.totalFiles} current=${event.file} events=${event.eventsParsed}`,
291
- );
292
- return;
293
- case 'done':
294
- console.log(
295
- `[scan] complete files=${event.filesProcessed}/${event.totalFiles} events=${event.eventsParsed} pending_batches=${event.pendingBatches} duration=${formatDuration(event.durationMs)}`,
296
- );
297
- return;
298
- case 'error':
299
- console.error(
300
- `[scan] failed stage=${event.stage} message=${event.message}`,
301
- );
302
- return;
303
- }
304
- }
305
-
306
- function wrapCatchUpFailure(error) {
307
- return new CliOperationalError(
308
- `Foreground catch-up failed: ${
309
- error instanceof Error ? error.message : String(error)
310
- }`,
311
- );
312
- }
313
-
314
- function wrapUsageFailure(error) {
315
- return new CliOperationalError(
316
- `Usage query failed: ${
317
- error instanceof Error ? error.message : String(error)
318
- }`,
319
- );
320
- }
321
-
322
- async function resolveAutoStartOnLogin(runtime, options) {
323
- if (options.yes) {
324
- return runtime.autoStartOnLogin;
325
- }
326
- return cliDeps.promptConfirm(
327
- 'Start automatically when you log in on this Mac?',
328
- runtime.autoStartOnLogin,
329
- );
330
- }
331
-
332
- async function runInit(options) {
333
- const overrides = runtimeOverrides(options);
334
- if (!overrides.backendUrl) {
335
- overrides.backendUrl = DEFAULT_BACKEND_URL;
336
- }
337
- let runtime = mergeRuntimeConfig(options.configFile, overrides);
338
- if (!runtime.backendUrl) {
339
- throw new Error(
340
- '--backend-url is required for init unless already configured in config.json',
341
- );
342
- }
343
-
344
- runtime = cliDeps.installCurrentPackage(runtime, {
345
- packageRoot: cliDeps.findPackageRoot(),
346
- packageSpec: options.packageSpec,
347
- nodePath: process.execPath,
348
- });
349
-
350
- let manager = cliDeps.createServiceManager(runtime);
351
- manager.stop();
352
-
353
- const uploader = cliDeps.createUploader(runtime);
354
- try {
355
- const identity = await bindIdentity(uploader, options);
356
- console.log(`${PRODUCT_NAME} install is ready.`);
357
- console.log(`Backend: ${runtime.backendUrl}`);
358
- console.log(`Install root: ${runtime.installRoot}`);
359
- console.log(`Config file: ${runtime.configFile}`);
360
- printIdentity(identity);
361
- console.log('Scanning local Codex sessions...');
362
-
363
- let scanResult;
364
- try {
365
- scanResult = await uploader.runForegroundCatchUp({
366
- onProgress: printCatchUpProgress,
367
- });
368
- } catch (error) {
369
- throw wrapCatchUpFailure(error);
370
- }
371
-
372
- runtime.autoStartOnLogin = await resolveAutoStartOnLogin(runtime, options);
373
- runtime = saveRuntimeConfig(runtime);
374
- manager = cliDeps.createServiceManager(runtime);
375
- manager.start();
376
- console.log(`${PRODUCT_NAME} initialized and started.`);
377
- console.log(
378
- runtime.autoStartOnLogin
379
- ? 'Login auto-start is enabled.'
380
- : 'Login auto-start is disabled for future logins.',
381
- );
382
- if (scanResult.pendingBatches > 0) {
383
- console.log(
384
- `Background service is uploading ${scanResult.pendingBatches} batch(es) with ${scanResult.pendingEvents} event(s).`,
385
- );
386
- }
387
- console.log(`Use \`${CLI_NAME} status\` to check the local service.`);
388
- const linkDir = path.dirname(runtime.homeBinLink);
389
- const pathDirs = (process.env.PATH || '').split(path.delimiter);
390
- if (!pathDirs.includes(linkDir)) {
391
- cliDeps.ensurePathInShellConfigs(linkDir);
392
- console.log(`Open a new terminal to use \`${CLI_NAME}\` directly.`);
393
- }
394
- } finally {
395
- uploader.close();
396
- }
397
- }
398
-
399
- function formatCount(value) {
400
- return Number(value ?? 0).toLocaleString('en-US');
401
- }
402
-
403
- function renderTable(headers, rows, alignments = []) {
404
- const widths = headers.map((header, index) =>
405
- Math.max(
406
- header.length,
407
- ...rows.map((row) => String(row[index] ?? '').length),
408
- ),
409
- );
410
- const formatCell = (cell, index) => {
411
- const text = String(cell ?? '');
412
- return alignments[index] === 'right'
413
- ? text.padStart(widths[index])
414
- : text.padEnd(widths[index]);
415
- };
416
- const formatRow = (row) =>
417
- row
418
- .map((cell, index) => formatCell(cell, index))
419
- .join(' ')
420
- .trimEnd();
421
- return [
422
- formatRow(headers),
423
- ...rows.map((row) => formatRow(row)),
424
- ].join('\n');
425
- }
426
-
427
- function formatUsageDate(dateString) {
428
- const [year, month, day] = dateString.split('-').map(Number);
429
- return new Intl.DateTimeFormat('en-US', {
430
- timeZone: 'UTC',
431
- month: 'short',
432
- day: 'numeric',
433
- year: 'numeric',
434
- }).format(new Date(Date.UTC(year, month - 1, day)));
435
- }
436
-
437
- function printUsageReport(report) {
438
- if (report.tokenEventCount === 0) {
439
- console.log('No local Codex usage found for selected range.');
440
- return;
441
- }
442
-
443
- const rows = report.days.map((row) => [
444
- formatUsageDate(row.date),
445
- row.models.join(', '),
446
- formatCount(row.inputTokens),
447
- formatCount(row.outputTokens),
448
- formatCount(row.reasoningOutputTokens),
449
- formatCount(row.cachedInputTokens),
450
- formatCount(row.totalTokens),
451
- ]);
452
- rows.push([
453
- 'Total',
454
- '',
455
- formatCount(report.summary.inputTokens),
456
- formatCount(report.summary.outputTokens),
457
- formatCount(report.summary.reasoningOutputTokens),
458
- formatCount(report.summary.cachedInputTokens),
459
- formatCount(report.summary.totalTokens),
460
- ]);
461
-
462
- console.log(
463
- renderTable(
464
- ['Date', 'Models', 'Input', 'Output', 'Reasoning', 'Cache Read', 'Total Tokens'],
465
- rows,
466
- ['left', 'left', 'right', 'right', 'right', 'right', 'right'],
467
- ),
468
- );
469
- }
470
-
471
- async function runUsage(options) {
472
- const runtime = mergeRuntimeConfig(options.configFile, runtimeOverrides(options));
473
-
474
- console.log('Scanning local Codex usage...');
475
-
476
- let report;
477
- try {
478
- report = await collectLocalUsage({
479
- sessionsDir: runtime.sessionsDir,
480
- period: options.period,
481
- from: options.from,
482
- to: options.to,
483
- timeZone: getLocalTimeZone(),
484
- });
485
- } catch (error) {
486
- throw wrapUsageFailure(error);
487
- }
488
-
489
- printUsageReport(report);
490
- }
491
-
492
- async function runBind(options) {
493
- const runtime = mergeRuntimeConfig(options.configFile, runtimeOverrides(options));
494
- const uploader = cliDeps.createUploader(runtime);
495
- try {
496
- const identity = await bindIdentity(uploader, options);
497
- printIdentity(identity);
498
- if (await restartRunningServiceIfNeeded(runtime)) {
499
- console.log(
500
- 'Background service restarted to apply the updated identity.',
501
- );
502
- }
503
- } finally {
504
- uploader.close();
505
- }
506
- }
507
-
508
- async function runInternalWorker(options) {
509
- const runtime = mergeRuntimeConfig(options.configFile, runtimeOverrides(options));
510
- const uploader = cliDeps.createUploader(runtime);
511
- try {
512
- assertBoundIdentity(uploader);
513
- console.log(
514
- `[run] backend=${runtime.backendUrl ?? '-'} interval=${runtime.intervalSeconds}s sessions_dir=${runtime.sessionsDir}`,
515
- );
516
- await uploader.watch();
517
- } finally {
518
- uploader.close();
519
- }
520
- }
521
-
522
- function loadQueueStats(stateDbPath) {
523
- if (!fs.existsSync(stateDbPath)) {
524
- return {
525
- collectorId: null,
526
- bufferingBatchCount: 0,
527
- pendingBatchCount: 0,
528
- retryingBatchCount: 0,
529
- queuedSessions: 0,
530
- queuedTurns: 0,
531
- queuedEvents: 0,
532
- oldestPendingAgeSeconds: null,
533
- };
534
- }
535
- const stateDb = new StateDb(stateDbPath);
536
- try {
537
- const identity = stateDb.getIdentity();
538
- return {
539
- collectorId: identity.collectorId ?? null,
540
- ...stateDb.getQueueStats(),
541
- };
542
- } finally {
543
- stateDb.close();
544
- }
545
- }
546
-
547
- function printStatus(runtime, status) {
548
- const payload = {
549
- ...formatStatusOutput(runtime, status),
550
- ...loadQueueStats(runtime.stateDbPath),
551
- };
552
- const lines = [
553
- ['Config exists', payload.configExists ? 'yes' : 'no'],
554
- ['Loaded', payload.loaded ? 'yes' : 'no'],
555
- ['Running', payload.running ? 'yes' : 'no'],
556
- ['Auto start on login', payload.autoStartOnLogin ? 'yes' : 'no'],
557
- ['PID', payload.pid ?? '-'],
558
- ['State', payload.state ?? '-'],
559
- ['Last exit code', payload.lastExitCode ?? '-'],
560
- ['Collector ID', payload.collectorId ?? '-'],
561
- ['Upload URL', payload.backendUrl ? `${payload.backendUrl}/codex-usage/upload` : '-'],
562
- ['Register URL', payload.backendUrl ? `${payload.backendUrl}/codex-usage/collectors/register` : '-'],
563
- ['Interval', `${payload.intervalSeconds}s`],
564
- ['Buffering batches', payload.bufferingBatchCount],
565
- ['Pending batches', payload.pendingBatchCount],
566
- ['Retrying batches', payload.retryingBatchCount],
567
- ['Queued sessions', payload.queuedSessions],
568
- ['Queued turns', payload.queuedTurns],
569
- ['Queued events', payload.queuedEvents],
570
- [
571
- 'Oldest pending age',
572
- payload.oldestPendingAgeSeconds == null
573
- ? '-'
574
- : `${payload.oldestPendingAgeSeconds}s`,
575
- ],
576
- ['Config file', payload.configFile],
577
- ['State DB', payload.stateDbPath],
578
- ['Stdout log', payload.stdoutLogPath],
579
- ['Stderr log', payload.stderrLogPath],
580
- ['Service plist', payload.plistPath],
581
- ['LaunchAgent plist', payload.launchAgentPath],
582
- ['Label', payload.label],
583
- ];
584
- for (const [label, value] of lines) {
585
- console.log(`${label}: ${value}`);
586
- }
587
- }
588
-
589
- function ensureInitialized(runtime) {
590
- if (!fs.existsSync(runtime.configFile) || !runtime.entryFile) {
591
- throw new CliOperationalError(
592
- `Uploader is not initialized yet. Run \`${CLI_NAME} init\` first.`,
593
- );
594
- }
595
- }
596
-
597
- async function runClear(options) {
598
- const runtime = mergeRuntimeConfig(options.configFile, runtimeOverrides(options));
599
- ensureInitialized(runtime);
600
-
601
- const manager = cliDeps.createServiceManager(runtime);
602
- const status = manager.status();
603
- if (status.running) {
604
- throw new CliOperationalError(
605
- `Background service is still running. Stop it first with \`${CLI_NAME} stop\`.`,
606
- );
607
- }
608
-
609
- if (!options.yes) {
610
- const confirmed = await cliDeps.promptConfirm(
611
- 'Clear local backfill state and queued uploads?',
612
- false,
613
- );
614
- if (!confirmed) {
615
- console.log('Clear cancelled.');
616
- return;
617
- }
618
- }
619
-
620
- const uploader = cliDeps.createUploader(runtime);
621
- try {
622
- uploader.resetBackfillState();
623
- } finally {
624
- uploader.close();
625
- }
626
-
627
- console.log('Local backfill state has been cleared.');
628
- console.log(
629
- `Run \`${CLI_NAME} init\` when you want to backfill history again.`,
630
- );
631
- }
632
-
633
- async function restartRunningServiceIfNeeded(runtime) {
634
- if (process.platform !== 'darwin') return false;
635
- if (!fs.existsSync(runtime.configFile) || !runtime.entryFile) return false;
636
- const manager = cliDeps.createServiceManager(runtime);
637
- let status;
638
- try {
639
- status = manager.status();
640
- } catch {
641
- return false;
642
- }
643
- if (!status.running) return false;
644
- manager.restart();
645
- return true;
646
- }
647
-
648
- function runLifecycleCommand(action, options) {
649
- const runtime = mergeRuntimeConfig(options.configFile, runtimeOverrides(options));
650
- const manager = cliDeps.createServiceManager(runtime);
651
-
652
- switch (action) {
653
- case 'start':
654
- ensureInitialized(runtime);
655
- manager.start();
656
- console.log(`Service started: ${runtime.launchdLabel}`);
657
- return;
658
- case 'stop':
659
- manager.stop();
660
- console.log(`Service stopped: ${runtime.launchdLabel}`);
661
- return;
662
- case 'restart':
663
- ensureInitialized(runtime);
664
- manager.restart();
665
- console.log(`Service restarted: ${runtime.launchdLabel}`);
666
- return;
667
- case 'status':
668
- printStatus(runtime, manager.status());
669
- return;
670
- case 'logs': {
671
- const stdoutLines = tailFile(runtime.stdoutLogPath, options.lines);
672
- const stderrLines = tailFile(runtime.stderrLogPath, options.lines);
673
- console.log(`== stdout (${runtime.stdoutLogPath}) ==`);
674
- console.log(stdoutLines.length ? stdoutLines.join('\n') : '(empty)');
675
- console.log(`== stderr (${runtime.stderrLogPath}) ==`);
676
- console.log(stderrLines.length ? stderrLines.join('\n') : '(empty)');
677
- return;
678
- }
679
- case 'uninstall':
680
- manager.uninstall();
681
- cliDeps.removePathFromShellConfigs();
682
- fs.rmSync(runtime.installRoot, { recursive: true, force: true });
683
- console.log(`${PRODUCT_NAME} uninstalled from ${runtime.installRoot}`);
684
- return;
685
- default:
686
- throw new Error(`Unknown lifecycle command: ${action ?? '(empty)'}`);
687
- }
688
- }
689
-
690
- export async function main(argv = process.argv.slice(2)) {
691
- try {
692
- const { command, subcommand, extraPositionals, options } = parseCliArgs(argv);
693
- if (options.version) {
694
- console.log(getPackageVersion());
695
- return 0;
696
- }
697
- if (!command || options.help) {
698
- printUsage();
699
- return 0;
700
- }
701
-
702
- const knownCommands = new Set([
703
- 'init',
704
- 'bind',
705
- 'clear',
706
- 'start',
707
- 'stop',
708
- 'restart',
709
- 'status',
710
- 'usage',
711
- 'logs',
712
- 'uninstall',
713
- 'run',
714
- ]);
715
- if (!knownCommands.has(command)) {
716
- throw new Error(`Unknown command: ${command}`);
717
- }
718
-
719
- validateCommandShape(command, subcommand, extraPositionals);
720
-
721
- switch (command) {
722
- case 'init':
723
- await runInit(options);
724
- return 0;
725
- case 'bind':
726
- await runBind(options);
727
- return 0;
728
- case 'clear':
729
- await runClear(options);
730
- return 0;
731
- case 'usage':
732
- await runUsage(options);
733
- return 0;
734
- case 'run':
735
- await runInternalWorker(options);
736
- return 0;
737
- case 'start':
738
- case 'stop':
739
- case 'restart':
740
- case 'status':
741
- case 'logs':
742
- case 'uninstall':
743
- runLifecycleCommand(command, options);
744
- return 0;
745
- }
746
- } catch (error) {
747
- console.error(error instanceof Error ? error.message : String(error));
748
- if (error?.showUsage !== false) {
749
- console.error(`Run \`${CLI_NAME} --help\` for usage.`);
750
- }
751
- return 1;
752
- }
753
- }