agy-bar 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,971 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, realpathSync, rmSync } from 'node:fs';
3
+ import { delimiter, dirname, resolve } from 'node:path';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { fileURLToPath } from 'node:url';
6
+ import {
7
+ applyConfigCommand,
8
+ BAR_STYLE_NAMES,
9
+ COLOR_MODES,
10
+ loadConfig,
11
+ PRESET_NAMES,
12
+ saveConfig,
13
+ TAB_TITLE_SOURCES,
14
+ } from '../src/config.mjs';
15
+ import {
16
+ computeUsageSummary,
17
+ readConversationParentMap,
18
+ saveUsageSummary,
19
+ scanConversationHistory,
20
+ usageSummaryPath,
21
+ } from '../src/history-scan.mjs';
22
+ import { installAgyBar, runDoctor, uninstallAgyBar } from '../src/installer.mjs';
23
+ import { startMonitor } from '../src/monitor.mjs';
24
+ import { buildPreviewOutput } from '../src/preview.mjs';
25
+ import {
26
+ BUILTIN_RATES,
27
+ clearPricingMemo,
28
+ lookupRates,
29
+ normalizeModelKey,
30
+ pricingCachePath,
31
+ readPricingCache,
32
+ } from '../src/pricing.mjs';
33
+ import {
34
+ maybeTriggerBackgroundPricingSync,
35
+ PRICING_SOURCE_NAMES,
36
+ syncPricingCache,
37
+ } from '../src/pricing-sync.mjs';
38
+ import {
39
+ AGY_BAR_CLEANUP_ENV_VARS,
40
+ checkLocalPort,
41
+ COMMON_LOCAL_PROXY_PORTS,
42
+ DEFAULT_PROXY_BYPASS,
43
+ DEFAULT_PROXY_CONFIG,
44
+ detectLocalProxy,
45
+ formatShellCleanup,
46
+ formatShellExports,
47
+ launchAgyWithProxy,
48
+ normalizeBypassList,
49
+ PROXY_MODES,
50
+ readEnvProxy,
51
+ redactProxyUrl,
52
+ resolveEffectiveProxy,
53
+ validateProxyUrl,
54
+ } from '../src/proxy.mjs';
55
+ import { detectModelGroup, selectQuotaEntries } from '../src/render.mjs';
56
+ import {
57
+ detectShell,
58
+ formatShellHookPrompt,
59
+ inspectShellHook,
60
+ installShellHook,
61
+ resolveInstallShellHookChoice,
62
+ SUPPORTED_SHELLS,
63
+ uninstallShellHook,
64
+ } from '../src/shell-hook.mjs';
65
+ import { aggregateStats, formatStatsReport, HEATMAP_PALETTE_NAMES, PERIOD_NAMES, readLedger, SOURCE_NAMES } from '../src/stats.mjs';
66
+ import { runStatusline } from '../src/statusline.mjs';
67
+ import { buildTabTitle, writeOscTitle } from '../src/tab-title.mjs';
68
+ import { armPayloadCapture, listSessions, readCapturedPayload, setSessionCustomTitle, updateSessionTabTitle } from '../src/telemetry.mjs';
69
+ import { THEME_NAMES } from '../src/themes.mjs';
70
+
71
+ const pkg = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'));
72
+
73
+ export const HELP_TEXT = [
74
+ `agy-bar v${pkg.version} — Modern minimal dashboard statusline & CLI HUD for Antigravity CLI (agy)`,
75
+ '',
76
+ 'Usage: agy-bar <command> [options]',
77
+ '',
78
+ 'Commands:',
79
+ ' install [options] Install statusline + global ~/.local/bin/agy-bar command',
80
+ ' --proxy-hook Also install managed agy() shell hook without prompting',
81
+ ' --no-proxy-hook Skip shell hook without prompting (leaves ~/.zshrc untouched)',
82
+ ' --no-skill Skip installing the companion /agy-bar skill',
83
+ ' --no-shim Skip installing the ~/.local/bin/agy-bar shortcut command',
84
+ ' -y, --yes Non-interactive install (keeps ~/.zshrc untouched unless --proxy-hook)',
85
+ ` --shell <name> Target shell for the hook (${SUPPORTED_SHELLS.join(' | ')})`,
86
+ ` --preset <name> Initial preset (${PRESET_NAMES.join(' | ')})`,
87
+ ` --theme <name> Initial theme (${THEME_NAMES.join(' | ')})`,
88
+ ` --bar-style <style> Gauge style (${BAR_STYLE_NAMES.join(' | ')})`,
89
+ '',
90
+ ' run [opts] [agy args..] Launch agy through your local proxy without TUN mode',
91
+ ' --proxy <url> Override proxy URL for this session (e.g. 127.0.0.1:7897)',
92
+ ' --no-proxy Launch agy directly without proxy environment variables',
93
+ ' --agy-bin <path> Explicit path to the agy executable',
94
+ ' -q, --quiet Suppress the one-line launch banner on stderr',
95
+ ' -- Stop agy-bar option parsing; forward all remaining args to agy',
96
+ '',
97
+ ' proxy [subcommand] Configure, auto-detect, hook, or test no-TUN proxy settings',
98
+ ' status | check Show effective proxy, shell hook & live TCP reachability (default)',
99
+ ' auto Auto-detect OS or local Clash/Surge/v2ray proxy and save it',
100
+ ' set <url> Save a manual proxy URL (e.g. http://127.0.0.1:7897)',
101
+ ' on | off Enable or disable proxy injection without losing saved URL',
102
+ ` mode <mode> Switch proxy mode (${PROXY_MODES.join(' | ')})`,
103
+ ' hook [--shell <sh>] Install managed agy() shell hook so plain "agy" uses proxy without TUN',
104
+ ' unhook Remove the managed agy() shell hook from your shell rc file',
105
+ ' bypass <list|reset> Set comma-separated NO_PROXY list (always keeps loopback)',
106
+ ' env [--sh|--fish|--pwsh] Print shell export commands (e.g. eval "$(agy-bar proxy env)")',
107
+ ' clear Reset proxy settings back to default auto-detect mode',
108
+ '',
109
+ ' uninstall [options] Remove agy-bar, shell hook & restore previous statusLine setting',
110
+ ' --remove-skill Also remove the managed /agy-bar skill',
111
+ ' --purge Also remove ~/.gemini/config/agy-bar/config.json & telemetry',
112
+ ' --print-cleanup Print shell unset commands for current terminal (use with eval)',
113
+ '',
114
+ ' config <subcommand> Inspect or update display preferences',
115
+ ' show Print effective configuration as JSON',
116
+ ` preset <name> Switch layout preset (${PRESET_NAMES.join(' | ')})`,
117
+ ` theme <name> Switch theme (${THEME_NAMES.join(' | ')})`,
118
+ ` bar-style <style> Switch bar style (${BAR_STYLE_NAMES.join(' | ')})`,
119
+ ' enable <items...> Enable items (ttft, speed, dir, vim, cost, session, contextDelta, ...)',
120
+ ' disable <items...> Disable items',
121
+ ` set <key> <value>... Set colorMode (${COLOR_MODES.join('|')}), dirStyle (short|parent|name), barWidth, ttftWarnSec, dbTiming, pricingAutoSync, ledger`,
122
+ ' reset Restore default settings',
123
+ '',
124
+ ' stats [period] [opts] Full-history token dashboard, terminal heatmap & API cost estimate',
125
+ ` period ${PERIOD_NAMES.join(' | ')} (default: 7d)`,
126
+ ` --source <src> ${SOURCE_NAMES.join(' | ')} (default: all — scans CLI + Desktop DBs)`,
127
+ ` --palette <name> Heatmap ramp: ${HEATMAP_PALETTE_NAMES.join(' | ')} (default: purple)`,
128
+ ' --model <filter> Filter by model substring (e.g. claude, carbon, neon)',
129
+ ' --no-cache Force full re-scan of conversation DBs',
130
+ ' --json Output machine-readable JSON',
131
+ ' --plain Disable ANSI colors',
132
+ '',
133
+ ' pricing [subcommand] Inspect, sync, or override local model reference API pricing',
134
+ ' show [--json] Show cache status and active per-1M token rates (default)',
135
+ ` sync [options] Sync latest public rates (${PRICING_SOURCE_NAMES.join(' | ')}) via proxy or direct`,
136
+ ' --source <src> auto (models.dev -> litellm) | models.dev | litellm',
137
+ ' --force Ignore ETag and force refresh',
138
+ ' set <model> <in> <out> [cacheRead] [cacheWrite] Save custom USD/1M override',
139
+ ' reset [model|--cache] Remove custom override(s) or clear synced pricing cache',
140
+ '',
141
+ ' monitor [options] Live multi-CLI HUD tracking all active agy terminals',
142
+ ' --interval <ms> Refresh interval in milliseconds (default: 1000)',
143
+ ' --once Print a single snapshot and exit',
144
+ ' --plain Disable ANSI colors',
145
+ '',
146
+ ' title [text] [options] Set or inspect the terminal tab title for the current session',
147
+ ' --session <id> Target a specific session ID (defaults to most recent active)',
148
+ ' --clear Clear custom title and revert to AGY conversation_title',
149
+ ` (configure with: config set tabTitle on|off tabTitleSource ${TAB_TITLE_SOURCES.join('|')})`,
150
+ '',
151
+ ' debug [options] Capture or inspect a PII-redacted AGY statusLine JSON payload',
152
+ ' --capture Arm one-shot capture on the next AGY statusline refresh',
153
+ ' --show Display the last captured redacted payload (default)',
154
+ '',
155
+ ' preview [options] Render live sample statuslines in your terminal',
156
+ ' --scenario <name> normal | warning | critical | claude | all (default: normal)',
157
+ ' --width <cols> Simulated terminal width (default: 116)',
158
+ ' --preset <name> Override preset for preview',
159
+ ' --theme <name> Override theme for preview',
160
+ ` --color-mode <mode> Override colorMode (${COLOR_MODES.join(' | ')})`,
161
+ ' --bar-style <style> Override gauge style for preview',
162
+ ' --plain Disable ANSI colors',
163
+ '',
164
+ ' doctor Verify installation, Node version, and run a self-test',
165
+ ' render Read AGY JSON payload from stdin and render to stdout',
166
+ ].join('\n');
167
+
168
+ function parseFlags(args) {
169
+ const flags = {};
170
+ const positional = [];
171
+ for (let i = 0; i < args.length; i++) {
172
+ const arg = args[i];
173
+ if (arg === '--no-skill') flags.withSkill = false;
174
+ else if (arg === '--with-skill') flags.withSkill = true;
175
+ else if (arg === '--no-shim') flags.withShim = false;
176
+ else if (arg === '--with-shim') flags.withShim = true;
177
+ else if (arg === '--no-shell-hook' || arg === '--no-proxy-hook') flags.withShellHook = false;
178
+ else if (arg === '--with-shell-hook' || arg === '--proxy-hook') flags.withShellHook = true;
179
+ else if (arg === '--yes' || arg === '-y') flags.yes = true;
180
+ else if (arg === '--remove-skill') flags.removeSkill = true;
181
+ else if (arg === '--purge') flags.purge = true;
182
+ else if (arg === '--print-cleanup') flags.printCleanup = true;
183
+ else if (arg === '--plain') flags.plain = true;
184
+ else if (arg === '--json') flags.json = true;
185
+ else if (arg === '--once') flags.once = true;
186
+ else if (arg === '--capture') flags.capture = true;
187
+ else if (arg === '--show') flags.show = true;
188
+ else if (arg === '--clear') flags.clear = true;
189
+ else if (arg === '--no-cache') flags.noCache = true;
190
+ else if (arg === '--cache') flags.cache = true;
191
+ else if (arg === '--force') flags.force = true;
192
+ else if (arg === '--quiet' || arg === '-q') flags.quiet = true;
193
+ else if (arg === '--sh') flags.shell = 'sh';
194
+ else if (arg === '--fish') flags.shell = 'fish';
195
+ else if (arg === '--pwsh') flags.shell = 'pwsh';
196
+ else if (['--preset', '--theme', '--bar-style', '--color-mode', '--scenario', '--width', '--model', '--interval', '--session', '--source', '--palette', '--shell'].includes(arg)) {
197
+ const value = args[++i];
198
+ if (!value) throw new Error(`Missing value for ${arg}`);
199
+ const key = arg.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
200
+ flags[key] = value;
201
+ } else if (arg.startsWith('-')) {
202
+ throw new Error(`Unknown option: ${arg}`);
203
+ } else {
204
+ positional.push(arg);
205
+ }
206
+ }
207
+ return { flags, positional };
208
+ }
209
+
210
+ export async function main(argv = process.argv.slice(2)) {
211
+ const [command, ...rest] = argv;
212
+
213
+ if (!command || command === 'help' || command === '--help' || command === '-h') {
214
+ console.log(HELP_TEXT);
215
+ return;
216
+ }
217
+
218
+ if (command === '--version' || command === '-v') {
219
+ console.log(pkg.version);
220
+ return;
221
+ }
222
+
223
+ if (command === 'render') {
224
+ await runStatusline({ argv: rest });
225
+ return;
226
+ }
227
+
228
+ if (command === 'run') {
229
+ const cfg = loadConfig();
230
+ const res = await launchAgyWithProxy(rest, { proxyConfig: cfg.proxy });
231
+ if (res.exitCode) process.exitCode = res.exitCode;
232
+ return;
233
+ }
234
+
235
+ if (command === 'proxy') {
236
+ await handleProxyCommand(rest);
237
+ return;
238
+ }
239
+
240
+ if (command === 'pricing') {
241
+ await handlePricingCommand(rest);
242
+ return;
243
+ }
244
+
245
+ if (command === 'install') {
246
+ const { flags } = parseFlags(rest);
247
+ const withShim = flags.withShim ?? true;
248
+ const hookState = inspectShellHook({ shell: flags.shell ?? null });
249
+ const hookDecision = await resolveInstallShellHookChoice({
250
+ flagValue: flags.withShellHook,
251
+ withShim,
252
+ alreadyInstalled: hookState.installed,
253
+ isInteractive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
254
+ yes: Boolean(flags.yes),
255
+ promptFn: async () => {
256
+ console.log(formatShellHookPrompt(hookState));
257
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
258
+ try {
259
+ const answer = await rl.question(`Enable plain "agy" no-TUN proxy hook in ${hookState.rcPath}? [y/N]: `);
260
+ return /^(?:y|yes)$/i.test(answer.trim());
261
+ } finally {
262
+ rl.close();
263
+ }
264
+ },
265
+ });
266
+
267
+ const result = installAgyBar({
268
+ withSkill: flags.withSkill ?? true,
269
+ withShim,
270
+ withShellHook: hookDecision.enable,
271
+ shell: flags.shell ?? null,
272
+ preset: flags.preset ?? null,
273
+ theme: flags.theme ?? null,
274
+ barStyle: flags.barStyle ?? null,
275
+ });
276
+ console.log(`Installed agy-bar statusline at ${result.scriptPath}`);
277
+ console.log(`Updated AGY settings: ${result.settingsPath}`);
278
+ if (result.shimPath) {
279
+ console.log(`Installed global CLI command: ${result.shimPath}`);
280
+ const shimDir = dirname(result.shimPath);
281
+ const pathDirs = String(process.env.PATH || process.env.Path || '').split(delimiter).filter(Boolean);
282
+ const normPath = (p) => (process.platform === 'win32' ? resolve(p).toLowerCase() : resolve(p));
283
+ const onPath = pathDirs.some((p) => normPath(p) === normPath(shimDir));
284
+ if (!onPath) {
285
+ console.log(`Note: add ${shimDir} to your PATH to run "agy-bar" directly.`);
286
+ }
287
+ } else if (result.shimWarning) {
288
+ console.log(`Note: ${result.shimWarning}`);
289
+ }
290
+ if (result.shellHook?.installed) {
291
+ console.log(
292
+ `${result.shellHook.updated ? 'Updated' : 'Installed'} shell hook (${result.shellHook.shell}): ${result.shellHook.rcPath}`,
293
+ );
294
+ if (!result.shellHook.updated) {
295
+ console.log(
296
+ `Run "${result.shellHook.reloadCmd}" (or open a new terminal) — then plain "agy" automatically uses your local proxy without TUN.`,
297
+ );
298
+ }
299
+ } else if (result.shellHook?.warning) {
300
+ console.log(`Note: ${result.shellHook.warning}`);
301
+ } else if (withShim) {
302
+ console.log(
303
+ `Shell rc untouched (${hookState.rcPath}). Launch via local proxy with "agy-bar run", or enable plain "agy" anytime with "agy-bar proxy hook".`,
304
+ );
305
+ }
306
+ if (result.skillPath) {
307
+ console.log(`Installed companion /agy-bar skill: ${result.skillPath}`);
308
+ }
309
+ console.log('Restart agy to activate the new statusline.');
310
+ return;
311
+ }
312
+
313
+ if (command === 'uninstall') {
314
+ const { flags } = parseFlags(rest);
315
+ const result = uninstallAgyBar({
316
+ removeSkill: Boolean(flags.removeSkill),
317
+ purge: Boolean(flags.purge),
318
+ });
319
+ const rawShell = flags.shell || detectShell();
320
+ const cleanupShell = rawShell === 'fish' ? 'fish' : rawShell === 'pwsh' ? 'pwsh' : 'sh';
321
+ const cleanupCmd = formatShellCleanup({ shell: cleanupShell, includeUnsetFunc: true });
322
+ const hasProxyEnvInShell = AGY_BAR_CLEANUP_ENV_VARS.some((k) => Boolean(process.env[k]));
323
+
324
+ if (flags.printCleanup) {
325
+ process.stderr.write(`${result.message}\n`);
326
+ if (result.shellHookPaths?.length) {
327
+ process.stderr.write(`Removed managed shell hook from: ${result.shellHookPaths.join(', ')}\n`);
328
+ }
329
+ console.log(cleanupCmd);
330
+ return;
331
+ }
332
+
333
+ console.log(result.message);
334
+ if (result.shellHookPaths?.length) {
335
+ console.log(`Removed managed shell hook from: ${result.shellHookPaths.join(', ')}`);
336
+ }
337
+ if (result.shellHookRemoved || hasProxyEnvInShell) {
338
+ console.log('To clear proxy env vars & agy() function in this already-open terminal immediately, run:');
339
+ console.log(` ${cleanupCmd}`);
340
+ }
341
+ return;
342
+ }
343
+
344
+ if (command === 'config') {
345
+ const result = applyConfigCommand(rest);
346
+ const safeResult = {
347
+ ...result,
348
+ config: {
349
+ ...result.config,
350
+ proxy: {
351
+ ...result.config.proxy,
352
+ url: redactProxyUrl(result.config.proxy?.url),
353
+ },
354
+ },
355
+ };
356
+ console.log(JSON.stringify(safeResult, null, 2));
357
+ return;
358
+ }
359
+
360
+ if (command === 'stats') {
361
+ const { flags, positional } = parseFlags(rest);
362
+ const period = positional[0] || '7d';
363
+ const source = (flags.source || 'all').toLowerCase();
364
+ if (!SOURCE_NAMES.includes(source)) {
365
+ throw new Error(`Invalid --source "${source}". Choose one of: ${SOURCE_NAMES.join(', ')}`);
366
+ }
367
+ const palette = (flags.palette || 'purple').toLowerCase();
368
+ if (!HEATMAP_PALETTE_NAMES.includes(palette)) {
369
+ throw new Error(`Invalid --palette "${palette}". Choose one of: ${HEATMAP_PALETTE_NAMES.join(', ')}`);
370
+ }
371
+
372
+ let entries = [];
373
+ let sourceLabel = source;
374
+ if (source === 'ledger') {
375
+ entries = readLedger();
376
+ } else {
377
+ const scan = await scanConversationHistory({
378
+ sourceFilter: source,
379
+ useCache: !flags.noCache,
380
+ });
381
+ if (scan.supported && scan.entries.length > 0) {
382
+ entries = scan.entries;
383
+ sourceLabel = source === 'all' ? 'cli+desktop' : source;
384
+ if (source === 'all') {
385
+ const parentMap = await readConversationParentMap();
386
+ saveUsageSummary(computeUsageSummary(scan.entries, { parentMap }));
387
+ }
388
+ } else {
389
+ entries = readLedger();
390
+ sourceLabel = 'ledger';
391
+ }
392
+ }
393
+
394
+ const report = aggregateStats(entries, { period, modelFilter: flags.model || null, sourceLabel });
395
+ if (flags.json) {
396
+ console.log(JSON.stringify(report, null, 2));
397
+ return;
398
+ }
399
+ const cfg = loadConfig();
400
+ if (cfg.pricingAutoSync) {
401
+ maybeTriggerBackgroundPricingSync({ enabled: true });
402
+ }
403
+ const color = !flags.plain && !('NO_COLOR' in process.env) && cfg.theme !== 'mono';
404
+ console.log(formatStatsReport(report, { color, theme: cfg.theme, heatmapPalette: palette }));
405
+ return;
406
+ }
407
+
408
+ if (command === 'monitor') {
409
+ const { flags } = parseFlags(rest);
410
+ const intervalMs = flags.interval ? Number(flags.interval) : 1000;
411
+ if (!Number.isFinite(intervalMs) || intervalMs < 250 || intervalMs > 60000) {
412
+ throw new Error('--interval must be between 250 and 60000 milliseconds.');
413
+ }
414
+ const cfg = loadConfig();
415
+ if (cfg.pricingAutoSync) {
416
+ maybeTriggerBackgroundPricingSync({ enabled: true });
417
+ }
418
+ const color = !flags.plain && !('NO_COLOR' in process.env) && cfg.theme !== 'mono';
419
+ await startMonitor({ intervalMs, once: Boolean(flags.once), color });
420
+ return;
421
+ }
422
+
423
+ if (command === 'title') {
424
+ const { flags, positional } = parseFlags(rest);
425
+ const cfg = loadConfig();
426
+ if (!flags.clear && positional.length === 0) {
427
+ const recent = listSessions();
428
+ const target = flags.session ? recent.find((s) => s.sessionId === flags.session) : recent[0];
429
+ if (!target) {
430
+ console.log('No active agy-bar session found yet.');
431
+ return;
432
+ }
433
+ console.log(
434
+ JSON.stringify(
435
+ {
436
+ sessionId: target.sessionId,
437
+ tabTitleEnabled: cfg.tabTitle,
438
+ source: cfg.tabTitleSource,
439
+ customTitle: target.customTitle || null,
440
+ conversationTitle: target.conversationTitle || null,
441
+ activeTabTitle: target.lastTabTitle || null,
442
+ },
443
+ null,
444
+ 2,
445
+ ),
446
+ );
447
+ return;
448
+ }
449
+
450
+ const rawText = positional.join(' ').trim();
451
+ const updated = setSessionCustomTitle(rawText, {
452
+ sessionId: flags.session || null,
453
+ clear: Boolean(flags.clear),
454
+ });
455
+ const renderedTitle = buildTabTitle(
456
+ {
457
+ agent_state: updated.agentState,
458
+ conversation_title: updated.conversationTitle,
459
+ cwd: updated.cwd,
460
+ },
461
+ {
462
+ config: cfg,
463
+ git: updated.branch ? { branch: updated.branch, dirty: updated.dirty } : null,
464
+ customTitle: updated.customTitle,
465
+ },
466
+ );
467
+ const writeRes = renderedTitle && cfg.tabTitle ? writeOscTitle(renderedTitle) : { written: false, tty: null };
468
+ if (writeRes.written) {
469
+ updateSessionTabTitle(updated.sessionId, renderedTitle, { hostPid: writeRes.hostPid });
470
+ }
471
+ console.log(
472
+ flags.clear
473
+ ? `Cleared custom tab title for session ${updated.sessionId}${renderedTitle ? ` (reverted to "${renderedTitle}")` : ''}.`
474
+ : `Set tab title: ${renderedTitle || updated.customTitle}${writeRes.tty ? ` (${writeRes.tty})` : ''}`,
475
+ );
476
+ return;
477
+ }
478
+
479
+ if (command === 'debug') {
480
+ const { flags } = parseFlags(rest);
481
+ if (flags.capture) {
482
+ const armed = armPayloadCapture();
483
+ console.log(`Armed one-shot redacted payload capture.`);
484
+ console.log(`Next time Antigravity CLI refreshes the statusline, a sanitized snapshot will be saved to:`);
485
+ console.log(` ${armed.target}`);
486
+ console.log(`Run "agy-bar debug" afterward to inspect it.`);
487
+ return;
488
+ }
489
+ const captured = readCapturedPayload();
490
+ if (!captured) {
491
+ console.log('No captured payload found yet. Run "agy-bar debug --capture", wait for one agy refresh, then run "agy-bar debug".');
492
+ return;
493
+ }
494
+ const cfg = loadConfig();
495
+ const p = captured.payload || {};
496
+ const group = detectModelGroup(p.model, p.quota);
497
+ const matchedBuckets = selectQuotaEntries(p.quota, p.model, cfg.show).map((b) => b.id);
498
+ console.log(
499
+ JSON.stringify(
500
+ {
501
+ capturedAt: captured.capturedAt,
502
+ detectedModelGroup: group,
503
+ matchedQuotaBuckets: matchedBuckets,
504
+ payload: p,
505
+ },
506
+ null,
507
+ 2,
508
+ ),
509
+ );
510
+ return;
511
+ }
512
+
513
+ if (command === 'preview') {
514
+ const { flags } = parseFlags(rest);
515
+ const width = flags.width ? Number(flags.width) : 116;
516
+ if (!Number.isFinite(width) || width < 20 || width > 300) {
517
+ throw new Error('--width must be a number between 20 and 300.');
518
+ }
519
+ const output = buildPreviewOutput({
520
+ scenario: flags.scenario || 'normal',
521
+ width,
522
+ preset: flags.preset || null,
523
+ theme: flags.theme || null,
524
+ barStyle: flags.barStyle || null,
525
+ colorMode: flags.colorMode || null,
526
+ color: !flags.plain && !('NO_COLOR' in process.env),
527
+ });
528
+ console.log(output);
529
+ return;
530
+ }
531
+
532
+ if (command === 'doctor') {
533
+ const report = runDoctor();
534
+ for (const check of report.checks) {
535
+ const icon = check.ok ? '✓' : '✗';
536
+ console.log(`${icon} ${check.name}: ${check.detail}`);
537
+ }
538
+ if (!report.ok) process.exitCode = 1;
539
+ return;
540
+ }
541
+
542
+ throw new Error(`Unknown command "${command}". Run "agy-bar --help" for usage.`);
543
+ }
544
+
545
+ async function handleProxyCommand(args) {
546
+ const [sub = 'status', ...rest] = args;
547
+
548
+ if (sub === 'run') {
549
+ const cfg = loadConfig();
550
+ const res = await launchAgyWithProxy(rest, { proxyConfig: cfg.proxy });
551
+ if (res.exitCode) process.exitCode = res.exitCode;
552
+ return;
553
+ }
554
+
555
+ if (sub === 'help' || sub === '--help' || sub === '-h') {
556
+ console.log(
557
+ [
558
+ 'Usage: agy-bar proxy <subcommand>',
559
+ '',
560
+ ' status | check Show configured & effective proxy + live reachability',
561
+ ' auto Auto-detect OS or local Clash/Surge/v2ray proxy and save it',
562
+ ' set <url> Save a manual proxy URL (e.g. http://127.0.0.1:7897)',
563
+ ' on | off Enable or disable proxy injection',
564
+ ` mode <${PROXY_MODES.join('|')}> Switch proxy resolution mode`,
565
+ ` hook [--shell <${SUPPORTED_SHELLS.join('|')}>] Install agy() shell hook so plain "agy" uses proxy`,
566
+ ' unhook Remove the managed agy() shell hook',
567
+ ' bypass <list | reset> Update comma-separated NO_PROXY list',
568
+ ' env [--sh|--fish|--pwsh] Output shell export commands for eval',
569
+ ' clear Reset proxy settings to default auto mode',
570
+ ' run [agy args...] Alias for "agy-bar run [agy args...]"',
571
+ ].join('\n'),
572
+ );
573
+ return;
574
+ }
575
+
576
+ const cfg = loadConfig();
577
+
578
+ if (sub === 'status' || sub === 'check') {
579
+ const { flags } = parseFlags(rest);
580
+ const resolved = await resolveEffectiveProxy(cfg.proxy);
581
+ const hookInfo = inspectShellHook();
582
+ let check = null;
583
+ if (resolved.active && resolved.host && resolved.port) {
584
+ check = await checkLocalPort(resolved.host, resolved.port, 500);
585
+ }
586
+
587
+ const summary = {
588
+ mode: cfg.proxy.mode,
589
+ savedUrl: redactProxyUrl(cfg.proxy.url),
590
+ active: resolved.active,
591
+ effectiveUrl: redactProxyUrl(resolved.url),
592
+ source: resolved.source || null,
593
+ reachable: check ? check.reachable : null,
594
+ latencyMs: check ? check.latencyMs : null,
595
+ error: check && !check.reachable ? check.error : null,
596
+ bypass: resolved.bypass,
597
+ shellHook: hookInfo,
598
+ warning: resolved.warning || null,
599
+ reason: resolved.active ? null : resolved.reason,
600
+ };
601
+
602
+ if (flags.json) {
603
+ console.log(JSON.stringify(summary, null, 2));
604
+ return;
605
+ }
606
+
607
+ const lines = [
608
+ `agy-bar no-TUN proxy`,
609
+ ` Mode: ${summary.mode}`,
610
+ ` Saved URL: ${summary.savedUrl || '(none — auto-detect)'}`,
611
+ ` Effective: ${summary.effectiveUrl ? `${summary.effectiveUrl} (${summary.source})` : `(none — ${summary.reason})`}`,
612
+ ];
613
+ if (check) {
614
+ lines.push(
615
+ ` Status: ${check.reachable ? `✓ reachable (${check.latencyMs}ms)` : `✗ unreachable (${check.error || 'refused'})`}`,
616
+ );
617
+ }
618
+ lines.push(` NO_PROXY: ${summary.bypass.join(',')}`);
619
+ lines.push(
620
+ ` Shell hook: ${hookInfo.installed ? `✓ active in ${hookInfo.rcPath} (plain "agy" auto-proxies)` : `not installed (run "agy-bar proxy hook" to enable plain "agy")`}`,
621
+ );
622
+ if (summary.warning) {
623
+ lines.push(` Note: ${summary.warning}`);
624
+ }
625
+ lines.push('');
626
+ lines.push(
627
+ hookInfo.installed
628
+ ? ' Launch agy without TUN: agy [args...] (bypass once: command agy / AGY_BAR_NO_PROXY=1 agy)'
629
+ : ' Launch agy without TUN: agy-bar run [agy args...] (or enable plain "agy": agy-bar proxy hook)',
630
+ );
631
+ console.log(lines.join('\n'));
632
+ return;
633
+ }
634
+
635
+ if (sub === 'hook') {
636
+ const { flags } = parseFlags(rest);
637
+ const res = installShellHook({ shell: flags.shell || null });
638
+ if (res.skipped) {
639
+ console.log(res.warning);
640
+ process.exitCode = 1;
641
+ return;
642
+ }
643
+ console.log(`${res.updated ? 'Updated' : 'Installed'} agy-bar shell hook (${res.shell}) in ${res.rcPath}`);
644
+ console.log(`Run "${res.reloadCmd}" (or open a new terminal) — then just type "agy" to launch through your local proxy without TUN.`);
645
+ return;
646
+ }
647
+
648
+ if (sub === 'unhook') {
649
+ const { flags } = parseFlags(rest);
650
+ const res = uninstallShellHook({ shell: flags.shell || null });
651
+ if (!res.removed) {
652
+ console.log('No managed agy-bar shell hook was found.');
653
+ return;
654
+ }
655
+ console.log(`Removed agy-bar shell hook from: ${res.rcPaths.join(', ')}`);
656
+ console.log('Open a new terminal (or run "unset -f agy") to restore plain agy immediately.');
657
+ return;
658
+ }
659
+
660
+ if (sub === 'set') {
661
+ const rawUrl = rest[0];
662
+ if (!rawUrl || rest.length > 1) {
663
+ throw new Error('Usage: agy-bar proxy set <url> (e.g. agy-bar proxy set http://127.0.0.1:7897)');
664
+ }
665
+ const parsed = validateProxyUrl(rawUrl);
666
+ saveConfig({
667
+ ...cfg,
668
+ proxy: { ...cfg.proxy, mode: 'manual', url: parsed.url },
669
+ });
670
+ const check = await checkLocalPort(parsed.host, parsed.port, 500);
671
+ console.log(`Saved proxy: ${redactProxyUrl(parsed.url)} (mode=manual)`);
672
+ console.log(
673
+ `Reachability: ${check.reachable ? `✓ listening (${check.latencyMs}ms)` : `✗ not listening right now (${check.error || 'refused'})`}`,
674
+ );
675
+ if (parsed.warning) console.log(`Note: ${parsed.warning}`);
676
+ console.log('Launch agy with: agy-bar run');
677
+ return;
678
+ }
679
+
680
+ if (sub === 'auto') {
681
+ const detected = (await detectLocalProxy({ includeEnv: false })) || readEnvProxy();
682
+ if (!detected) {
683
+ const portList = COMMON_LOCAL_PROXY_PORTS.map((p) => p.port).join(', ');
684
+ throw new Error(
685
+ `No active local proxy detected (checked OS system proxy and 127.0.0.1 ports: ${portList}). Start Clash/Surge/v2ray or set one manually with "agy-bar proxy set http://127.0.0.1:<port>".`,
686
+ );
687
+ }
688
+ const parsed = validateProxyUrl(detected.url);
689
+ const check = await checkLocalPort(parsed.host, parsed.port, 500);
690
+ const mergedBypass = normalizeBypassList([...cfg.proxy.bypass, ...(detected.bypass || [])]);
691
+ saveConfig({
692
+ ...cfg,
693
+ proxy: { mode: 'manual', url: parsed.url, bypass: mergedBypass },
694
+ });
695
+ console.log(`Detected & saved proxy: ${redactProxyUrl(parsed.url)} (${detected.source})`);
696
+ console.log(
697
+ `Reachability: ${check.reachable ? `✓ listening (${check.latencyMs}ms)` : `✗ unreachable (${check.error || 'refused'})`}`,
698
+ );
699
+ if (parsed.warning) console.log(`Note: ${parsed.warning}`);
700
+ console.log('Launch agy with: agy-bar run');
701
+ return;
702
+ }
703
+
704
+ if (sub === 'on') {
705
+ const nextMode = cfg.proxy.url ? 'manual' : 'auto';
706
+ saveConfig({ ...cfg, proxy: { ...cfg.proxy, mode: nextMode } });
707
+ console.log(
708
+ nextMode === 'manual'
709
+ ? `Enabled proxy: ${redactProxyUrl(cfg.proxy.url)} (mode=manual)`
710
+ : 'Enabled proxy in auto-detect mode (mode=auto).',
711
+ );
712
+ return;
713
+ }
714
+
715
+ if (sub === 'off') {
716
+ saveConfig({ ...cfg, proxy: { ...cfg.proxy, mode: 'off' } });
717
+ console.log('Disabled agy-bar proxy injection (mode=off). Saved URL was preserved.');
718
+ return;
719
+ }
720
+
721
+ if (sub === 'mode') {
722
+ const mode = String(rest[0] || '').toLowerCase();
723
+ if (!PROXY_MODES.includes(mode)) {
724
+ throw new Error(`Invalid proxy mode "${rest[0] || ''}". Choose one of: ${PROXY_MODES.join(', ')}`);
725
+ }
726
+ if (mode === 'manual' && !cfg.proxy.url) {
727
+ throw new Error('Cannot switch to manual mode without a saved URL. Run "agy-bar proxy set <url>" or "agy-bar proxy auto" first.');
728
+ }
729
+ saveConfig({ ...cfg, proxy: { ...cfg.proxy, mode } });
730
+ console.log(`Switched proxy mode to "${mode}".`);
731
+ return;
732
+ }
733
+
734
+ if (sub === 'bypass') {
735
+ if (rest.length === 0) {
736
+ console.log(cfg.proxy.bypass.join(','));
737
+ return;
738
+ }
739
+ const nextBypass =
740
+ rest[0].toLowerCase() === 'reset'
741
+ ? [...DEFAULT_PROXY_BYPASS]
742
+ : normalizeBypassList(['127.0.0.1', 'localhost', '::1', ...rest.join(',').split(',')]);
743
+ saveConfig({ ...cfg, proxy: { ...cfg.proxy, bypass: nextBypass } });
744
+ console.log(`Updated NO_PROXY: ${nextBypass.join(',')}`);
745
+ return;
746
+ }
747
+
748
+ if (sub === 'env') {
749
+ const { flags } = parseFlags(rest);
750
+ const shell = flags.shell || (process.platform === 'win32' ? 'pwsh' : 'sh');
751
+ const resolved = await resolveEffectiveProxy(cfg.proxy);
752
+ console.log(formatShellExports(resolved, { shell }));
753
+ return;
754
+ }
755
+
756
+ if (sub === 'clear' || sub === 'reset') {
757
+ saveConfig({ ...cfg, proxy: { ...DEFAULT_PROXY_CONFIG, bypass: [...DEFAULT_PROXY_BYPASS] } });
758
+ console.log('Reset proxy settings to default auto-detect mode.');
759
+ return;
760
+ }
761
+
762
+ throw new Error(`Unknown proxy subcommand "${sub}". Run "agy-bar proxy --help" for usage.`);
763
+ }
764
+
765
+ async function handlePricingCommand(args) {
766
+ const [sub = 'show', ...rest] = args;
767
+ const cfg = loadConfig();
768
+
769
+ if (sub === 'help' || sub === '--help' || sub === '-h') {
770
+ console.log(
771
+ [
772
+ 'Usage: agy-bar pricing <subcommand>',
773
+ '',
774
+ ' show [--json] Show cache status & active per-1M rates (default)',
775
+ ` sync [--source ${PRICING_SOURCE_NAMES.join('|')}] [--force] Sync latest public pricing catalog`,
776
+ ' set <model> <in> <out> [cacheRead] [cacheWrite] Save custom USD per 1M token override',
777
+ ' reset [model | --cache] Clear custom overrides or synced cache',
778
+ ].join('\n'),
779
+ );
780
+ return;
781
+ }
782
+
783
+ if (sub === 'show' || sub === 'status') {
784
+ const { flags } = parseFlags(rest);
785
+ const cache = readPricingCache();
786
+ const ageHours = cache?.fetchedAt ? Math.round(((Date.now() - cache.fetchedAt) / 3_600_000) * 10) / 10 : null;
787
+ const sampleModels = [
788
+ 'Gemini 4 Neon',
789
+ 'Gemini 4 Carbon',
790
+ 'Gemini 4 Argon',
791
+ 'Gemini 4 Hydrogen',
792
+ 'Gemini 3.8 Flash',
793
+ 'Gemini 2.5 Pro',
794
+ 'Gemini 2.5 Flash',
795
+ 'Claude Opus 4.6',
796
+ 'Claude Sonnet 4.6',
797
+ 'Claude Haiku 4.5',
798
+ ];
799
+ for (const customKey of Object.keys(cfg.customPricing || {})) {
800
+ if (!sampleModels.some((m) => normalizeModelKey(m) === normalizeModelKey(customKey))) {
801
+ sampleModels.push(customKey);
802
+ }
803
+ }
804
+ const rows = sampleModels.map((model) => {
805
+ const rate = lookupRates(model, { customPricing: cfg.customPricing, pricingCache: cache });
806
+ return {
807
+ model,
808
+ input: rate?.input ?? null,
809
+ output: rate?.output ?? null,
810
+ cacheRead: rate?.cacheRead ?? null,
811
+ cacheWrite: rate?.cacheWrite ?? null,
812
+ source: rate?.source ?? 'unpriced',
813
+ };
814
+ });
815
+
816
+ if (flags.json) {
817
+ console.log(
818
+ JSON.stringify(
819
+ {
820
+ autoSync: cfg.pricingAutoSync,
821
+ cache: cache
822
+ ? {
823
+ source: cache.source,
824
+ fetchedAt: new Date(cache.fetchedAt).toISOString(),
825
+ ageHours,
826
+ cachedModels: Object.keys(cache.rates || {}).length,
827
+ path: pricingCachePath(),
828
+ }
829
+ : null,
830
+ customOverrides: cfg.customPricing,
831
+ effectiveRates: rows,
832
+ },
833
+ null,
834
+ 2,
835
+ ),
836
+ );
837
+ return;
838
+ }
839
+
840
+ const lines = [
841
+ 'agy-bar model pricing (USD per 1M tokens)',
842
+ ` Auto-sync: ${cfg.pricingAutoSync ? 'on (24h background SWR; disable: agy-bar config set pricingAutoSync off)' : 'off (manual: agy-bar pricing sync)'}`,
843
+ ` Cache: ${cache ? `${cache.source} · ${Object.keys(cache.rates || {}).length} models · updated ${ageHours}h ago` : 'not synced yet (using built-in calibrated rates)'}`,
844
+ '',
845
+ ` ${'Model'.padEnd(20)} ${'Input'.padStart(7)} ${'Output'.padStart(7)} ${'CacheRd'.padStart(8)} Source`,
846
+ ` ${'─'.repeat(58)}`,
847
+ ];
848
+ for (const r of rows) {
849
+ const fmt = (n) => (typeof n === 'number' ? `$${n < 1 ? n.toFixed(3).replace(/0+$/, '') : n.toFixed(2)}` : '--');
850
+ lines.push(
851
+ ` ${r.model.padEnd(20)} ${fmt(r.input).padStart(7)} ${fmt(r.output).padStart(7)} ${fmt(r.cacheRead).padStart(8)} ${r.source}`,
852
+ );
853
+ }
854
+ lines.push('');
855
+ lines.push(' Refresh now: agy-bar pricing sync | Override: agy-bar pricing set <model> <in> <out> [cacheRead]');
856
+ console.log(lines.join('\n'));
857
+ return;
858
+ }
859
+
860
+ if (sub === 'sync') {
861
+ const { flags } = parseFlags(rest);
862
+ const source = (flags.source || 'auto').toLowerCase();
863
+ if (!PRICING_SOURCE_NAMES.includes(source)) {
864
+ throw new Error(`Invalid --source "${source}". Choose one of: ${PRICING_SOURCE_NAMES.join(', ')}`);
865
+ }
866
+ const res = await syncPricingCache({
867
+ proxyConfig: cfg.proxy,
868
+ source,
869
+ force: Boolean(flags.force),
870
+ });
871
+ if (!res.ok) {
872
+ if (!flags.quiet) {
873
+ throw new Error(`Pricing sync failed (${res.error}). Keeping existing local rates.`);
874
+ }
875
+ process.exitCode = 1;
876
+ return;
877
+ }
878
+ if (!flags.quiet) {
879
+ console.log(
880
+ res.notModified
881
+ ? `Pricing cache is already up to date (${res.source}, ${res.count} models, HTTP 304).`
882
+ : `Synced ${res.count} model rates from ${res.source} -> ${res.cachePath}`,
883
+ );
884
+ }
885
+ return;
886
+ }
887
+
888
+ if (sub === 'set') {
889
+ const [rawModel, rawIn, rawOut, rawCr, rawCw] = rest;
890
+ if (!rawModel || !rawIn || !rawOut) {
891
+ throw new Error('Usage: agy-bar pricing set <model> <input> <output> [cacheRead] [cacheWrite] (USD per 1M tokens)');
892
+ }
893
+ const key = normalizeModelKey(rawModel);
894
+ const input = Number(rawIn);
895
+ const output = Number(rawOut);
896
+ const cacheRead = rawCr !== undefined ? Number(rawCr) : Math.round(input * 1000) / 10_000;
897
+ const cacheWrite = rawCw !== undefined ? Number(rawCw) : input;
898
+ if (!key || !Number.isFinite(input) || input <= 0 || input > 500 || !Number.isFinite(output) || output <= 0 || output > 1000) {
899
+ throw new Error('Input (0..500) and output (0..1000) must be valid positive numbers in USD per 1M tokens.');
900
+ }
901
+ if (!Number.isFinite(cacheRead) || cacheRead < 0 || !Number.isFinite(cacheWrite) || cacheWrite < 0) {
902
+ throw new Error('cacheRead and cacheWrite must be non-negative numbers.');
903
+ }
904
+ const nextCustom = {
905
+ ...(cfg.customPricing || {}),
906
+ [key]: { input, output, cacheRead, cacheWrite },
907
+ };
908
+ saveConfig({ ...cfg, customPricing: nextCustom });
909
+ clearPricingMemo();
910
+ try {
911
+ rmSync(usageSummaryPath(), { force: true });
912
+ } catch {
913
+ // Ignore cleanup errors.
914
+ }
915
+ console.log(`Saved custom pricing for "${key}": in=$${input}/1M out=$${output}/1M cacheRead=$${cacheRead}/1M`);
916
+ return;
917
+ }
918
+
919
+ if (sub === 'reset') {
920
+ const { flags, positional } = parseFlags(rest);
921
+ const invalidateSummary = () => {
922
+ try {
923
+ rmSync(usageSummaryPath(), { force: true });
924
+ } catch {
925
+ // Ignore cleanup errors.
926
+ }
927
+ };
928
+ if (flags.cache) {
929
+ rmSync(pricingCachePath(), { force: true });
930
+ clearPricingMemo();
931
+ invalidateSummary();
932
+ console.log('Cleared synced pricing cache (reverted to built-in calibrated rates).');
933
+ return;
934
+ }
935
+ const target = positional[0] ? normalizeModelKey(positional[0]) : null;
936
+ if (target) {
937
+ const nextCustom = { ...(cfg.customPricing || {}) };
938
+ delete nextCustom[target];
939
+ saveConfig({ ...cfg, customPricing: nextCustom });
940
+ clearPricingMemo();
941
+ invalidateSummary();
942
+ console.log(`Removed custom pricing override for "${target}".`);
943
+ return;
944
+ }
945
+ saveConfig({ ...cfg, customPricing: {} });
946
+ clearPricingMemo();
947
+ invalidateSummary();
948
+ console.log(`Cleared all custom pricing overrides (${BUILTIN_RATES.length} built-in fallback rates active).`);
949
+ return;
950
+ }
951
+
952
+ throw new Error(`Unknown pricing subcommand "${sub}". Run "agy-bar pricing --help" for usage.`);
953
+ }
954
+
955
+ function isDirectInvocation() {
956
+ if (!process.argv[1]) return false;
957
+ try {
958
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
959
+ } catch {
960
+ return resolve(process.argv[1]) === fileURLToPath(import.meta.url);
961
+ }
962
+ }
963
+
964
+ if (isDirectInvocation()) {
965
+ try {
966
+ await main();
967
+ } catch (error) {
968
+ console.error(error.message);
969
+ process.exitCode = 1;
970
+ }
971
+ }