agy-bar 1.0.1 → 1.1.1

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/bin/agy-bar.mjs CHANGED
@@ -3,6 +3,29 @@ import { readFileSync, realpathSync, rmSync } from 'node:fs';
3
3
  import { delimiter, dirname, resolve } from 'node:path';
4
4
  import { createInterface } from 'node:readline/promises';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import {
7
+ ACCOUNT_FAMILIES,
8
+ detectQuotaFamilyFromModel,
9
+ formatAccountTable,
10
+ listAccountsWithQuota,
11
+ maybeAutoSwitchAccount,
12
+ pickNextBestAccount,
13
+ sanitizeAccountForJson,
14
+ } from '../src/account-quota.mjs';
15
+ import { IMPORT_SOURCES, importExternalAccounts } from '../src/account-import.mjs';
16
+ import {
17
+ exportEncryptedBackup,
18
+ importEncryptedBackup,
19
+ prepareForNewAccountLogin,
20
+ readActiveAccountState,
21
+ removeAccount,
22
+ renameAccount,
23
+ restorePreservedLogin,
24
+ saveCurrentAccount,
25
+ switchToAccount,
26
+ syncActiveAccountBeforeLaunch,
27
+ VAULT_STORAGE_MODES,
28
+ } from '../src/account-store.mjs';
6
29
  import {
7
30
  applyConfigCommand,
8
31
  BAR_STYLE_NAMES,
@@ -12,6 +35,8 @@ import {
12
35
  saveConfig,
13
36
  TAB_TITLE_SOURCES,
14
37
  } from '../src/config.mjs';
38
+ import { writeFileAtomic } from '../src/fs-atomic.mjs';
39
+ import { prepareHandoff } from '../src/handoff.mjs';
15
40
  import {
16
41
  computeUsageSummary,
17
42
  readConversationParentMap,
@@ -20,6 +45,7 @@ import {
20
45
  usageSummaryPath,
21
46
  } from '../src/history-scan.mjs';
22
47
  import { installAgyBar, runDoctor, uninstallAgyBar } from '../src/installer.mjs';
48
+ import { readActiveAgyCredential } from '../src/keyring.mjs';
23
49
  import { startMonitor } from '../src/monitor.mjs';
24
50
  import { buildPreviewOutput } from '../src/preview.mjs';
25
51
  import {
@@ -46,6 +72,7 @@ import {
46
72
  formatShellExports,
47
73
  launchAgyWithProxy,
48
74
  normalizeBypassList,
75
+ parseRunArgs,
49
76
  PROXY_MODES,
50
77
  readEnvProxy,
51
78
  redactProxyUrl,
@@ -100,6 +127,9 @@ export const HELP_TEXT = [
100
127
  ' run [opts] [agy args..] Launch agy through your local proxy without TUN mode',
101
128
  ' --proxy <url> Override proxy URL for this session (e.g. 127.0.0.1:7897)',
102
129
  ' --no-proxy Launch agy directly without proxy environment variables',
130
+ ' --auto-switch Auto-switch to next READY account before launch if active account is LIMITED',
131
+ ' --auto-handoff Exit-and-resume guard: if active account hits 0%, /exit auto-switches & resumes agy -i',
132
+ ` --family <f> Preferred quota family for auto-switch/handoff (${ACCOUNT_FAMILIES.join(' | ')})`,
103
133
  ' --agy-bin <path> Explicit path to the agy executable',
104
134
  ' -q, --quiet Suppress the one-line launch banner on stderr',
105
135
  ' -- Stop agy-bar option parsing; forward all remaining args to agy',
@@ -116,6 +146,25 @@ export const HELP_TEXT = [
116
146
  ' env [--sh|--fish|--pwsh] Print shell export commands (e.g. eval "$(agy-bar proxy env)")',
117
147
  ' clear Reset proxy settings back to default auto-detect mode',
118
148
  '',
149
+ ' account [subcommand] Browser-free multi-account vault & passive CLI quota dashboard (alias: accounts)',
150
+ ' ls | status [--json] List saved accounts, 5h/7d quotas, READY/LOW/LIMITED & reset timers (default)',
151
+ ' save [alias] Snapshot current logged-in agy account into vault (macOS/Linux/Windows)',
152
+ ' add [alias] Preserve current account, launch official agy for one-time OAuth, and capture it',
153
+ ' import [path] Import accounts from Cockpit Tools (~/.cockpit_tools) or an exported JSON file',
154
+ ' use <alias> Switch active agy credential to <alias> without opening a browser',
155
+ ` next [--family <f>] Auto-switch to best READY account (${ACCOUNT_FAMILIES.join(' | ')})`,
156
+ ' rename <old> <new> Rename a saved account alias',
157
+ ' rm <alias> Remove a saved account from vault',
158
+ ' backup <file> Export AES-256-GCM encrypted vault backup (passphrase prompt or AGY_BAR_BACKUP_PASSPHRASE)',
159
+ ' restore <file> Import accounts from an encrypted vault backup',
160
+ '',
161
+ ' switch [alias|next] Quick-switch account (arrow-key picker if omitted)',
162
+ ` --family <f> Preferred quota family for "next" (${ACCOUNT_FAMILIES.join(' | ')})`,
163
+ ' --handoff Generate compact workspace/transcript handoff and launch fresh agy -i',
164
+ ' --print With --handoff, print the handoff prompt instead of launching agy',
165
+ '',
166
+ ' handoff [--print] Generate workspace + recent transcript handoff and launch fresh agy -i',
167
+ '',
119
168
  ' uninstall [options] Remove agy-bar, shell hook & restore previous statusLine setting',
120
169
  ' --remove-skill Also remove the managed /agy-bar skill',
121
170
  ' --purge Also remove ~/.gemini/config/agy-bar/config.json & telemetry',
@@ -128,7 +177,7 @@ export const HELP_TEXT = [
128
177
  ` bar-style <style> Switch bar style (${BAR_STYLE_NAMES.join(' | ')})`,
129
178
  ' enable <items...> Enable items (ttft, speed, dir, vim, cost, session, contextDelta, ...)',
130
179
  ' disable <items...> Disable items',
131
- ` set <key> <value>... Set colorMode (${COLOR_MODES.join('|')}), dirStyle (short|parent|name), barWidth, ttftWarnSec, dbTiming, pricingAutoSync, ledger`,
180
+ ` set <key> <value>... Set colorMode (${COLOR_MODES.join('|')}), dirStyle (short|parent|name), barWidth, swapHint, autoSwitchOnLimit, autoHandoff, dbTiming, pricingAutoSync`,
132
181
  ' reset Restore default settings',
133
182
  '',
134
183
  ' stats [period] [opts] Full-history token dashboard, terminal heatmap & API cost estimate',
@@ -202,10 +251,33 @@ function parseFlags(args) {
202
251
  else if (arg === '--cache') flags.cache = true;
203
252
  else if (arg === '--force') flags.force = true;
204
253
  else if (arg === '--quiet' || arg === '-q') flags.quiet = true;
254
+ else if (arg === '--handoff') flags.handoff = true;
255
+ else if (arg === '--print') flags.print = true;
256
+ else if (arg === '--dry-run') flags.dryRun = true;
257
+ else if (arg === '--include-disabled') flags.includeDisabled = true;
205
258
  else if (arg === '--sh') flags.shell = 'sh';
206
259
  else if (arg === '--fish') flags.shell = 'fish';
207
260
  else if (arg === '--pwsh') flags.shell = 'pwsh';
208
- else if (['--preset', '--theme', '--bar-style', '--color-mode', '--scenario', '--width', '--model', '--interval', '--session', '--source', '--palette', '--shell'].includes(arg)) {
261
+ else if (
262
+ [
263
+ '--preset',
264
+ '--theme',
265
+ '--bar-style',
266
+ '--color-mode',
267
+ '--scenario',
268
+ '--width',
269
+ '--model',
270
+ '--interval',
271
+ '--session',
272
+ '--source',
273
+ '--palette',
274
+ '--shell',
275
+ '--family',
276
+ '--storage',
277
+ '--passphrase',
278
+ '--from',
279
+ ].includes(arg)
280
+ ) {
209
281
  const value = args[++i];
210
282
  if (!value) throw new Error(`Missing value for ${arg}`);
211
283
  const key = arg.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
@@ -238,8 +310,7 @@ export async function main(argv = process.argv.slice(2)) {
238
310
  }
239
311
 
240
312
  if (command === 'run') {
241
- const cfg = loadConfig();
242
- const res = await launchAgyWithProxy(rest, { proxyConfig: cfg.proxy });
313
+ const res = await runManagedAgy(rest);
243
314
  if (res.exitCode) process.exitCode = res.exitCode;
244
315
  return;
245
316
  }
@@ -249,6 +320,21 @@ export async function main(argv = process.argv.slice(2)) {
249
320
  return;
250
321
  }
251
322
 
323
+ if (command === 'account' || command === 'accounts') {
324
+ await handleAccountCommand(rest);
325
+ return;
326
+ }
327
+
328
+ if (command === 'switch') {
329
+ await handleSwitchCommand(rest);
330
+ return;
331
+ }
332
+
333
+ if (command === 'handoff') {
334
+ await handleHandoffCommand(rest);
335
+ return;
336
+ }
337
+
252
338
  if (command === 'pricing') {
253
339
  await handlePricingCommand(rest);
254
340
  return;
@@ -468,6 +554,7 @@ export async function main(argv = process.argv.slice(2)) {
468
554
  subagents: target.runningSubagents || 0,
469
555
  task_count: target.runningTasks || 0,
470
556
  tool_confirmation_pending: Boolean(target.toolConfirmationPending),
557
+ waiting_for_input: Boolean(target.dbWaitingForInput),
471
558
  conversation_title: resolvedConvTitle,
472
559
  cwd: target.cwd,
473
560
  },
@@ -607,8 +694,7 @@ async function handleProxyCommand(args) {
607
694
  const [sub = 'status', ...rest] = args;
608
695
 
609
696
  if (sub === 'run') {
610
- const cfg = loadConfig();
611
- const res = await launchAgyWithProxy(rest, { proxyConfig: cfg.proxy });
697
+ const res = await runManagedAgy(rest);
612
698
  if (res.exitCode) process.exitCode = res.exitCode;
613
699
  return;
614
700
  }
@@ -1013,6 +1099,520 @@ async function handlePricingCommand(args) {
1013
1099
  throw new Error(`Unknown pricing subcommand "${sub}". Run "agy-bar pricing --help" for usage.`);
1014
1100
  }
1015
1101
 
1102
+ async function promptHiddenPassphrase(promptText) {
1103
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
1104
+ throw new Error('Passphrase required. Set AGY_BAR_BACKUP_PASSPHRASE or pass --passphrase <pw> in non-interactive mode.');
1105
+ }
1106
+ return new Promise((resolvePromise, rejectPromise) => {
1107
+ process.stdout.write(promptText);
1108
+ const stdin = process.stdin;
1109
+ const wasRaw = Boolean(stdin.isRaw);
1110
+ let value = '';
1111
+ stdin.setRawMode(true);
1112
+ stdin.resume();
1113
+
1114
+ const cleanup = () => {
1115
+ stdin.off('data', onData);
1116
+ try {
1117
+ stdin.setRawMode(wasRaw);
1118
+ } catch {
1119
+ // Ignore raw mode restore errors.
1120
+ }
1121
+ stdin.pause();
1122
+ };
1123
+
1124
+ const onData = (buf) => {
1125
+ const str = buf.toString('utf8');
1126
+ for (const ch of str) {
1127
+ if (ch === '\r' || ch === '\n') {
1128
+ cleanup();
1129
+ process.stdout.write('\n');
1130
+ resolvePromise(value);
1131
+ return;
1132
+ }
1133
+ if (ch === '\x03') {
1134
+ cleanup();
1135
+ process.stdout.write('\n');
1136
+ rejectPromise(new Error('Cancelled.'));
1137
+ return;
1138
+ }
1139
+ if (ch === '\x7f' || ch === '\b') {
1140
+ value = value.slice(0, -1);
1141
+ continue;
1142
+ }
1143
+ if (ch >= ' ') {
1144
+ value += ch;
1145
+ }
1146
+ }
1147
+ };
1148
+
1149
+ stdin.on('data', onData);
1150
+ });
1151
+ }
1152
+
1153
+ async function promptAccountPicker(rows) {
1154
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
1155
+ const names = rows.map((r) => r.alias).join(', ');
1156
+ throw new Error(`Specify an account alias or "next" in non-interactive mode. Saved accounts: ${names}`);
1157
+ }
1158
+ return new Promise((resolvePromise, rejectPromise) => {
1159
+ let selected = Math.max(
1160
+ 0,
1161
+ rows.findIndex((r) => r.isActive),
1162
+ );
1163
+ const stdin = process.stdin;
1164
+ const wasRaw = Boolean(stdin.isRaw);
1165
+ let renderedLines = 0;
1166
+
1167
+ const formatRow = (row, idx) => {
1168
+ const cursor = idx === selected ? '›' : ' ';
1169
+ const active = row.isActive ? '●' : ' ';
1170
+ const g5 = row.gemini.fiveHourPct !== null ? `G:${row.gemini.fiveHourPct}%` : 'G:--';
1171
+ const c5 = row.claude.fiveHourPct !== null ? `C:${row.claude.fiveHourPct}%` : 'C:--';
1172
+ const email = row.maskedEmail ? ` (${row.maskedEmail})` : '';
1173
+ return ` ${cursor} ${active} ${row.alias.padEnd(14)} ${row.overallStatus.padEnd(7)} ${g5.padEnd(6)} ${c5.padEnd(6)}${email}`;
1174
+ };
1175
+
1176
+ const render = () => {
1177
+ if (renderedLines > 0) {
1178
+ process.stdout.write(`\x1b[${renderedLines}A\x1b[J`);
1179
+ }
1180
+ const lines = [
1181
+ 'Select Antigravity account (↑/↓ move, Enter switch, Esc cancel):',
1182
+ ...rows.map((r, i) => formatRow(r, i)),
1183
+ ];
1184
+ process.stdout.write(`${lines.join('\n')}\n`);
1185
+ renderedLines = lines.length;
1186
+ };
1187
+
1188
+ const cleanup = () => {
1189
+ stdin.off('data', onData);
1190
+ try {
1191
+ stdin.setRawMode(wasRaw);
1192
+ } catch {
1193
+ // Ignore raw mode restore errors.
1194
+ }
1195
+ stdin.pause();
1196
+ };
1197
+
1198
+ const onData = (buf) => {
1199
+ const key = buf.toString('utf8');
1200
+ if (key === '\x03' || key === 'q' || key === '\x1b') {
1201
+ cleanup();
1202
+ rejectPromise(new Error('Switch cancelled.'));
1203
+ return;
1204
+ }
1205
+ if (key === '\r' || key === '\n') {
1206
+ cleanup();
1207
+ resolvePromise(rows[selected]);
1208
+ return;
1209
+ }
1210
+ if (key === '\x1b[A' || key === 'k') {
1211
+ selected = (selected - 1 + rows.length) % rows.length;
1212
+ render();
1213
+ return;
1214
+ }
1215
+ if (key === '\x1b[B' || key === 'j') {
1216
+ selected = (selected + 1) % rows.length;
1217
+ render();
1218
+ }
1219
+ };
1220
+
1221
+ stdin.setRawMode(true);
1222
+ stdin.resume();
1223
+ render();
1224
+ stdin.on('data', onData);
1225
+ });
1226
+ }
1227
+
1228
+ function detectRecentSessionFamily(cwd, startedAt) {
1229
+ try {
1230
+ const normCwd = resolve(cwd);
1231
+ const sessions = listSessions();
1232
+ const match = sessions.find(
1233
+ (s) => s?.cwd && resolve(s.cwd) === normCwd && Number(s.updatedAt || 0) >= startedAt - 15_000,
1234
+ );
1235
+ if (match?.model) {
1236
+ return detectQuotaFamilyFromModel(match.model);
1237
+ }
1238
+ } catch {
1239
+ // Fall back to auto family.
1240
+ }
1241
+ return 'auto';
1242
+ }
1243
+
1244
+ async function runManagedAgy(rawArgs) {
1245
+ const cfg = loadConfig();
1246
+ const { options } = parseRunArgs(rawArgs);
1247
+ const autoSwitchEnabled = options.autoSwitch ?? cfg.autoSwitchOnLimit;
1248
+ const autoHandoffEnabled = options.autoHandoff ?? cfg.autoHandoff;
1249
+ const visitedAccountIds = new Set();
1250
+
1251
+ const autoSwitchAccount = autoSwitchEnabled
1252
+ ? ({ family = 'auto' } = {}) => maybeAutoSwitchAccount({ family })
1253
+ : null;
1254
+
1255
+ const autoHandoffHook = autoHandoffEnabled
1256
+ ? ({ startedAt, family }) => {
1257
+ const effectiveFamily = family || detectRecentSessionFamily(process.cwd(), startedAt);
1258
+ const sw = maybeAutoSwitchAccount({
1259
+ family: effectiveFamily,
1260
+ excludeIds: [...visitedAccountIds],
1261
+ });
1262
+ if (!sw?.switched) return null;
1263
+ if (sw.fromId) visitedAccountIds.add(sw.fromId);
1264
+ if (sw.toId) visitedAccountIds.add(sw.toId);
1265
+ const handoff = prepareHandoff({
1266
+ cwd: process.cwd(),
1267
+ fromAlias: sw.fromAlias,
1268
+ targetAlias: sw.toAlias,
1269
+ });
1270
+ return {
1271
+ resume: true,
1272
+ prompt: handoff.prompt,
1273
+ savedPath: handoff.savedPath,
1274
+ fromAlias: sw.fromAlias,
1275
+ toAlias: sw.toAlias,
1276
+ family: effectiveFamily,
1277
+ };
1278
+ }
1279
+ : null;
1280
+
1281
+ return launchAgyWithProxy(rawArgs, {
1282
+ proxyConfig: cfg.proxy,
1283
+ syncAccount: syncActiveAccountBeforeLaunch,
1284
+ autoSwitchAccount,
1285
+ autoHandoffHook,
1286
+ });
1287
+ }
1288
+
1289
+ async function runPostSwitchHandoff({ fromAlias, targetAlias, printOnly = false }) {
1290
+ const handoff = prepareHandoff({ cwd: process.cwd(), fromAlias, targetAlias });
1291
+ if (printOnly) {
1292
+ console.log(handoff.prompt);
1293
+ return;
1294
+ }
1295
+ const cfg = loadConfig();
1296
+ const summaryBits = [
1297
+ handoff.artifactCount ? `${handoff.artifactCount} artifact(s)` : null,
1298
+ handoff.hasTranscript ? 'transcript' : null,
1299
+ handoff.hasGit ? 'git' : null,
1300
+ ]
1301
+ .filter(Boolean)
1302
+ .join(' + ');
1303
+ process.stderr.write(
1304
+ `agy-bar: launching fresh agy session on "${targetAlias}" with workspace handoff (${summaryBits || 'workspace'})...\n`,
1305
+ );
1306
+ const res = await launchAgyWithProxy(['-i', handoff.prompt], {
1307
+ proxyConfig: cfg.proxy,
1308
+ syncAccount: syncActiveAccountBeforeLaunch,
1309
+ handoffSavedPath: handoff.savedPath,
1310
+ });
1311
+ if (res.exitCode) process.exitCode = res.exitCode;
1312
+ }
1313
+
1314
+ async function handleSwitchCommand(args) {
1315
+ const { flags, positional } = parseFlags(args);
1316
+ const targetArg = positional[0] || null;
1317
+ const rows = listAccountsWithQuota();
1318
+ if (rows.length === 0) {
1319
+ throw new Error('No saved accounts yet. Run "agy-bar account save <alias>" first.');
1320
+ }
1321
+
1322
+ let targetAlias = targetArg;
1323
+ let pickedInfo = null;
1324
+ if (!targetAlias) {
1325
+ const chosen = await promptAccountPicker(rows);
1326
+ targetAlias = chosen.alias;
1327
+ } else if (targetAlias.toLowerCase() === 'next') {
1328
+ const state = readActiveAccountState();
1329
+ pickedInfo = pickNextBestAccount(rows, {
1330
+ currentId: state?.activeAccountId || null,
1331
+ family: flags.family || 'auto',
1332
+ });
1333
+ targetAlias = pickedInfo.account.alias;
1334
+ }
1335
+
1336
+ const res = switchToAccount(targetAlias);
1337
+ const writebackNote = res.wroteBackOutgoing && res.fromAlias ? ` (saved refreshed token for "${res.fromAlias}")` : '';
1338
+ const limitedNote = pickedInfo?.allLimited
1339
+ ? ' [all accounts currently LIMITED — picked earliest reset]'
1340
+ : '';
1341
+ console.log(
1342
+ `Switched active account -> ${res.account.alias}${res.account.maskedEmail ? ` (${res.account.maskedEmail})` : ''}${writebackNote}${limitedNote}`,
1343
+ );
1344
+ if (flags.handoff) {
1345
+ await runPostSwitchHandoff({
1346
+ fromAlias: res.fromAlias,
1347
+ targetAlias: res.account.alias,
1348
+ printOnly: Boolean(flags.print),
1349
+ });
1350
+ } else {
1351
+ console.log('Open a new "agy" session to use this account (or pass --handoff to continue your current task seamlessly).');
1352
+ }
1353
+ }
1354
+
1355
+ async function handleHandoffCommand(args) {
1356
+ const { flags } = parseFlags(args);
1357
+ const state = readActiveAccountState();
1358
+ const rows = listAccountsWithQuota();
1359
+ const activeRow = state?.activeAccountId ? rows.find((r) => r.id === state.activeAccountId) : null;
1360
+ const handoff = prepareHandoff({
1361
+ cwd: process.cwd(),
1362
+ targetAlias: activeRow?.alias || null,
1363
+ });
1364
+
1365
+ if (flags.print) {
1366
+ console.log(handoff.prompt);
1367
+ return;
1368
+ }
1369
+
1370
+ const cfg = loadConfig();
1371
+ process.stderr.write(
1372
+ `agy-bar: launching fresh agy session with handoff (${handoff.hasTranscript ? 'transcript + ' : ''}${handoff.hasGit ? 'git' : 'workspace'})...\n`,
1373
+ );
1374
+ const res = await launchAgyWithProxy(['-i', handoff.prompt], {
1375
+ proxyConfig: cfg.proxy,
1376
+ syncAccount: syncActiveAccountBeforeLaunch,
1377
+ handoffSavedPath: handoff.savedPath,
1378
+ });
1379
+ if (res.exitCode) process.exitCode = res.exitCode;
1380
+ }
1381
+
1382
+ async function handleAccountCommand(args) {
1383
+ const [sub = 'ls', ...rest] = args;
1384
+
1385
+ if (sub === 'help' || sub === '--help' || sub === '-h') {
1386
+ console.log(
1387
+ [
1388
+ 'Usage: agy-bar account <subcommand> [options]',
1389
+ '',
1390
+ ' ls | status [--json] [--plain] List saved accounts, 5h/7d quotas & READY/LIMITED timers',
1391
+ ` save [alias] [--force] [--storage ${VAULT_STORAGE_MODES.join('|')}] Save current logged-in agy session into vault`,
1392
+ ` add [alias] [--force] [--storage ${VAULT_STORAGE_MODES.join('|')}] Save current account, launch agy for one-time OAuth, capture new slot`,
1393
+ ` import [path] [--from ${IMPORT_SOURCES.join('|')}] [--dry-run] [--include-disabled] [--force] Import from Cockpit Tools or JSON`,
1394
+ ' use <alias> [--handoff] [--print] Switch active agy account without opening a browser',
1395
+ ` next [--family ${ACCOUNT_FAMILIES.join('|')}] [--handoff] Auto-switch to best READY account`,
1396
+ ' rename <old> <new> Rename an account alias',
1397
+ ' rm <alias> Remove an account from the local vault',
1398
+ ' backup <file> [--passphrase <pw>] Export AES-256-GCM encrypted vault backup',
1399
+ ' restore <file> [--passphrase <pw>] [--force] Restore accounts from an encrypted backup',
1400
+ ].join('\n'),
1401
+ );
1402
+ return;
1403
+ }
1404
+
1405
+ if (sub === 'ls' || sub === 'list' || sub === 'status') {
1406
+ const { flags } = parseFlags(rest);
1407
+ const rows = listAccountsWithQuota();
1408
+ if (flags.json) {
1409
+ console.log(
1410
+ JSON.stringify(
1411
+ {
1412
+ count: rows.length,
1413
+ activeAlias: rows.find((r) => r.isActive)?.alias || null,
1414
+ accounts: rows.map(sanitizeAccountForJson),
1415
+ },
1416
+ null,
1417
+ 2,
1418
+ ),
1419
+ );
1420
+ return;
1421
+ }
1422
+ const cfg = loadConfig();
1423
+ const color = !flags.plain && !('NO_COLOR' in process.env) && cfg.theme !== 'mono';
1424
+ console.log(formatAccountTable(rows, { color, theme: cfg.theme }));
1425
+ return;
1426
+ }
1427
+
1428
+ if (sub === 'save') {
1429
+ const { flags, positional } = parseFlags(rest);
1430
+ const res = saveCurrentAccount({
1431
+ alias: positional[0] || null,
1432
+ force: Boolean(flags.force),
1433
+ storage: flags.storage || 'auto',
1434
+ });
1435
+ console.log(
1436
+ `${res.action === 'updated' ? 'Updated' : 'Saved'} account "${res.account.alias}"${res.account.maskedEmail ? ` (${res.account.maskedEmail})` : ''} [${res.account.storageBackend}, read from ${res.source}].`,
1437
+ );
1438
+ return;
1439
+ }
1440
+
1441
+ if (sub === 'add') {
1442
+ const { flags, positional } = parseFlags(rest);
1443
+ const alias = positional[0] || null;
1444
+ const { preserved } = prepareForNewAccountLogin();
1445
+ if (preserved?.alias) {
1446
+ console.log(`Preserved current account "${preserved.alias}" in vault and cleared active session.`);
1447
+ } else {
1448
+ console.log('Cleared active Antigravity session.');
1449
+ }
1450
+ console.log('Launching official "agy" for one-time browser sign-in...');
1451
+ console.log('Complete login in your browser, then press Ctrl+C or run "/exit" in agy to finish saving.');
1452
+
1453
+ const cfg = loadConfig();
1454
+ await launchAgyWithProxy([], { proxyConfig: cfg.proxy, syncAccount: null });
1455
+
1456
+ const freshCred = readActiveAgyCredential();
1457
+ if (!freshCred?.raw) {
1458
+ if (preserved?.raw) {
1459
+ restorePreservedLogin(preserved);
1460
+ console.log(`No new login detected — restored previous account${preserved.alias ? ` "${preserved.alias}"` : ''}.`);
1461
+ } else {
1462
+ console.log('No new login detected.');
1463
+ }
1464
+ return;
1465
+ }
1466
+
1467
+ const res = saveCurrentAccount({
1468
+ alias,
1469
+ force: Boolean(flags.force),
1470
+ storage: flags.storage || 'auto',
1471
+ });
1472
+ console.log(
1473
+ `Captured & activated account "${res.account.alias}"${res.account.maskedEmail ? ` (${res.account.maskedEmail})` : ''} [${res.account.storageBackend}].`,
1474
+ );
1475
+ return;
1476
+ }
1477
+
1478
+ if (sub === 'import') {
1479
+ const { flags, positional } = parseFlags(rest);
1480
+ const res = importExternalAccounts({
1481
+ targetPath: positional[0] || null,
1482
+ from: flags.from || 'auto',
1483
+ force: Boolean(flags.force),
1484
+ includeDisabled: Boolean(flags.includeDisabled),
1485
+ dryRun: Boolean(flags.dryRun),
1486
+ storage: flags.storage || 'auto',
1487
+ });
1488
+
1489
+ if (flags.json) {
1490
+ console.log(JSON.stringify(res, null, 2));
1491
+ return;
1492
+ }
1493
+
1494
+ if (res.dryRun) {
1495
+ console.log(`Dry run (${res.source}: ${res.sourcePath}): found ${res.candidates.length} importable account(s).`);
1496
+ for (const c of res.candidates) {
1497
+ console.log(
1498
+ ` + ${c.alias}${c.maskedEmail ? ` (${c.maskedEmail})` : ''}${c.tier ? ` [${c.tier}]` : ''}${c.hasQuotaSeed ? ' · quota snapshot' : ''}`,
1499
+ );
1500
+ }
1501
+ if (res.skipped.length > 0) {
1502
+ console.log(`Skipped ${res.skipped.length}:`);
1503
+ for (const s of res.skipped) {
1504
+ console.log(` - ${s.alias || s.file || 'entry'}${s.maskedEmail ? ` (${s.maskedEmail})` : ''}: ${s.reason}`);
1505
+ }
1506
+ }
1507
+ return;
1508
+ }
1509
+
1510
+ console.log(
1511
+ `Imported from ${res.source} (${res.sourcePath}): ${res.imported.length} added, ${res.updated.length} updated${res.skipped.length ? `, ${res.skipped.length} skipped` : ''}${res.seededQuotas ? `, ${res.seededQuotas} quota snapshot(s) seeded` : ''}.`,
1512
+ );
1513
+ for (const item of res.imported) {
1514
+ console.log(
1515
+ ` + ${item.alias}${item.maskedEmail ? ` (${item.maskedEmail})` : ''}${item.tier ? ` [${item.tier}]` : ''} [${item.storageBackend}]`,
1516
+ );
1517
+ }
1518
+ for (const item of res.updated) {
1519
+ console.log(
1520
+ ` ~ ${item.alias}${item.maskedEmail ? ` (${item.maskedEmail})` : ''}${item.tier ? ` [${item.tier}]` : ''} [updated]`,
1521
+ );
1522
+ }
1523
+ for (const s of res.skipped) {
1524
+ console.log(` - skipped ${s.alias || s.file || 'entry'}${s.maskedEmail ? ` (${s.maskedEmail})` : ''}: ${s.reason}`);
1525
+ }
1526
+ console.log('Run "agy-bar account ls" to inspect quotas, or "agy-bar switch" to switch without a browser.');
1527
+ return;
1528
+ }
1529
+
1530
+ if (sub === 'use') {
1531
+ const { flags, positional } = parseFlags(rest);
1532
+ if (!positional[0]) {
1533
+ throw new Error('Usage: agy-bar account use <alias> [--handoff]');
1534
+ }
1535
+ await handleSwitchCommand([positional[0], ...(flags.handoff ? ['--handoff'] : []), ...(flags.print ? ['--print'] : [])]);
1536
+ return;
1537
+ }
1538
+
1539
+ if (sub === 'next') {
1540
+ const { flags } = parseFlags(rest);
1541
+ await handleSwitchCommand([
1542
+ 'next',
1543
+ ...(flags.family ? ['--family', flags.family] : []),
1544
+ ...(flags.handoff ? ['--handoff'] : []),
1545
+ ...(flags.print ? ['--print'] : []),
1546
+ ]);
1547
+ return;
1548
+ }
1549
+
1550
+ if (sub === 'rename' || sub === 'alias') {
1551
+ const { positional } = parseFlags(rest);
1552
+ if (positional.length < 2) {
1553
+ throw new Error('Usage: agy-bar account rename <old-alias> <new-alias>');
1554
+ }
1555
+ const res = renameAccount(positional[0], positional[1]);
1556
+ console.log(`Renamed account "${res.oldAlias}" -> "${res.newAlias}".`);
1557
+ return;
1558
+ }
1559
+
1560
+ if (sub === 'rm' || sub === 'remove' || sub === 'delete') {
1561
+ const { positional } = parseFlags(rest);
1562
+ if (!positional[0]) {
1563
+ throw new Error('Usage: agy-bar account rm <alias>');
1564
+ }
1565
+ const res = removeAccount(positional[0]);
1566
+ console.log(`Removed account "${res.account.alias}" from vault (${res.remaining} remaining).`);
1567
+ return;
1568
+ }
1569
+
1570
+ if (sub === 'backup') {
1571
+ const { flags, positional } = parseFlags(rest);
1572
+ const outPath = positional[0];
1573
+ if (!outPath) {
1574
+ throw new Error('Usage: agy-bar account backup <output-file.json> [--passphrase <pw>]');
1575
+ }
1576
+ let passphrase = flags.passphrase || process.env.AGY_BAR_BACKUP_PASSPHRASE || '';
1577
+ if (!passphrase) {
1578
+ passphrase = await promptHiddenPassphrase('Enter encryption passphrase (min 4 chars): ');
1579
+ const confirm = await promptHiddenPassphrase('Confirm passphrase: ');
1580
+ if (passphrase !== confirm) {
1581
+ throw new Error('Passphrases do not match.');
1582
+ }
1583
+ }
1584
+ const envelope = exportEncryptedBackup({ passphrase });
1585
+ const absPath = resolve(outPath);
1586
+ writeFileAtomic(absPath, JSON.stringify(envelope, null, 2) + '\n', { mode: 0o600 });
1587
+ console.log(`Exported ${envelope.count} encrypted account(s) -> ${absPath} (AES-256-GCM)`);
1588
+ return;
1589
+ }
1590
+
1591
+ if (sub === 'restore') {
1592
+ const { flags, positional } = parseFlags(rest);
1593
+ const inPath = positional[0];
1594
+ if (!inPath) {
1595
+ throw new Error('Usage: agy-bar account restore <backup-file.json> [--passphrase <pw>] [--force]');
1596
+ }
1597
+ let passphrase = flags.passphrase || process.env.AGY_BAR_BACKUP_PASSPHRASE || '';
1598
+ if (!passphrase) {
1599
+ passphrase = await promptHiddenPassphrase('Enter backup passphrase: ');
1600
+ }
1601
+ const envelope = JSON.parse(readFileSync(resolve(inPath), 'utf8'));
1602
+ const res = importEncryptedBackup(envelope, {
1603
+ passphrase,
1604
+ force: Boolean(flags.force),
1605
+ storage: flags.storage || 'auto',
1606
+ });
1607
+ console.log(
1608
+ `Restored vault: ${res.imported.length} imported, ${res.updated.length} updated (${res.total} total accounts).`,
1609
+ );
1610
+ return;
1611
+ }
1612
+
1613
+ throw new Error(`Unknown account subcommand "${sub}". Run "agy-bar account --help" for usage.`);
1614
+ }
1615
+
1016
1616
  function isDirectInvocation() {
1017
1617
  if (!process.argv[1]) return false;
1018
1618
  try {