agy-bar 1.0.0 → 1.1.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.
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,
@@ -64,6 +91,7 @@ import {
64
91
  } from '../src/shell-hook.mjs';
65
92
  import { aggregateStats, formatStatsReport, HEATMAP_PALETTE_NAMES, PERIOD_NAMES, readLedger, SOURCE_NAMES } from '../src/stats.mjs';
66
93
  import { runStatusline } from '../src/statusline.mjs';
94
+ import { readConversationSummaryTitle } from '../src/step-timing.mjs';
67
95
  import { buildTabTitle, resolveTerminalTarget, writeOscTitle } from '../src/tab-title.mjs';
68
96
  import {
69
97
  armPayloadCapture,
@@ -99,6 +127,9 @@ export const HELP_TEXT = [
99
127
  ' run [opts] [agy args..] Launch agy through your local proxy without TUN mode',
100
128
  ' --proxy <url> Override proxy URL for this session (e.g. 127.0.0.1:7897)',
101
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(' | ')})`,
102
133
  ' --agy-bin <path> Explicit path to the agy executable',
103
134
  ' -q, --quiet Suppress the one-line launch banner on stderr',
104
135
  ' -- Stop agy-bar option parsing; forward all remaining args to agy',
@@ -115,6 +146,25 @@ export const HELP_TEXT = [
115
146
  ' env [--sh|--fish|--pwsh] Print shell export commands (e.g. eval "$(agy-bar proxy env)")',
116
147
  ' clear Reset proxy settings back to default auto-detect mode',
117
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
+ '',
118
168
  ' uninstall [options] Remove agy-bar, shell hook & restore previous statusLine setting',
119
169
  ' --remove-skill Also remove the managed /agy-bar skill',
120
170
  ' --purge Also remove ~/.gemini/config/agy-bar/config.json & telemetry',
@@ -127,7 +177,7 @@ export const HELP_TEXT = [
127
177
  ` bar-style <style> Switch bar style (${BAR_STYLE_NAMES.join(' | ')})`,
128
178
  ' enable <items...> Enable items (ttft, speed, dir, vim, cost, session, contextDelta, ...)',
129
179
  ' disable <items...> Disable items',
130
- ` 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`,
131
181
  ' reset Restore default settings',
132
182
  '',
133
183
  ' stats [period] [opts] Full-history token dashboard, terminal heatmap & API cost estimate',
@@ -201,10 +251,33 @@ function parseFlags(args) {
201
251
  else if (arg === '--cache') flags.cache = true;
202
252
  else if (arg === '--force') flags.force = true;
203
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;
204
258
  else if (arg === '--sh') flags.shell = 'sh';
205
259
  else if (arg === '--fish') flags.shell = 'fish';
206
260
  else if (arg === '--pwsh') flags.shell = 'pwsh';
207
- 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
+ ) {
208
281
  const value = args[++i];
209
282
  if (!value) throw new Error(`Missing value for ${arg}`);
210
283
  const key = arg.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
@@ -237,8 +310,7 @@ export async function main(argv = process.argv.slice(2)) {
237
310
  }
238
311
 
239
312
  if (command === 'run') {
240
- const cfg = loadConfig();
241
- const res = await launchAgyWithProxy(rest, { proxyConfig: cfg.proxy });
313
+ const res = await runManagedAgy(rest);
242
314
  if (res.exitCode) process.exitCode = res.exitCode;
243
315
  return;
244
316
  }
@@ -248,6 +320,21 @@ export async function main(argv = process.argv.slice(2)) {
248
320
  return;
249
321
  }
250
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
+
251
338
  if (command === 'pricing') {
252
339
  await handlePricingCommand(rest);
253
340
  return;
@@ -452,13 +539,23 @@ export async function main(argv = process.argv.slice(2)) {
452
539
  return;
453
540
  }
454
541
  const nativeTitleActive = isNativeTitleActive(target.sessionId, { hostPid: hostPid ?? process.ppid });
542
+ const resolvedConvTitle =
543
+ target.conversationTitle ||
544
+ (cfg.dbTiming !== false
545
+ ? readConversationSummaryTitle(target.sessionId, {
546
+ prevDbStamp: target.summaryDbStamp ?? null,
547
+ prevTitle: target.conversationTitle ?? null,
548
+ recheckIntervalMs: 0,
549
+ })?.title || null
550
+ : null);
455
551
  const computedTitle = buildTabTitle(
456
552
  {
457
553
  agent_state: target.agentState,
458
554
  subagents: target.runningSubagents || 0,
459
555
  task_count: target.runningTasks || 0,
460
556
  tool_confirmation_pending: Boolean(target.toolConfirmationPending),
461
- conversation_title: target.conversationTitle,
557
+ waiting_for_input: Boolean(target.dbWaitingForInput),
558
+ conversation_title: resolvedConvTitle,
462
559
  cwd: target.cwd,
463
560
  },
464
561
  {
@@ -475,7 +572,7 @@ export async function main(argv = process.argv.slice(2)) {
475
572
  nativeTitleActive,
476
573
  source: cfg.tabTitleSource,
477
574
  customTitle: target.customTitle || null,
478
- conversationTitle: target.conversationTitle || null,
575
+ conversationTitle: resolvedConvTitle,
479
576
  activeTabTitle: (nativeTitleActive ? computedTitle : target.lastTabTitle || computedTitle) || null,
480
577
  },
481
578
  null,
@@ -491,13 +588,22 @@ export async function main(argv = process.argv.slice(2)) {
491
588
  hostPid,
492
589
  clear: Boolean(flags.clear),
493
590
  });
591
+ const resolvedConvTitle =
592
+ updated.conversationTitle ||
593
+ (cfg.dbTiming !== false
594
+ ? readConversationSummaryTitle(updated.sessionId, {
595
+ prevDbStamp: updated.summaryDbStamp ?? null,
596
+ prevTitle: updated.conversationTitle ?? null,
597
+ recheckIntervalMs: 0,
598
+ })?.title || null
599
+ : null);
494
600
  const renderedTitle = buildTabTitle(
495
601
  {
496
602
  agent_state: updated.agentState,
497
603
  subagents: updated.runningSubagents || 0,
498
604
  task_count: updated.runningTasks || 0,
499
605
  tool_confirmation_pending: Boolean(updated.toolConfirmationPending),
500
- conversation_title: updated.conversationTitle,
606
+ conversation_title: resolvedConvTitle,
501
607
  cwd: updated.cwd,
502
608
  },
503
609
  {
@@ -588,8 +694,7 @@ async function handleProxyCommand(args) {
588
694
  const [sub = 'status', ...rest] = args;
589
695
 
590
696
  if (sub === 'run') {
591
- const cfg = loadConfig();
592
- const res = await launchAgyWithProxy(rest, { proxyConfig: cfg.proxy });
697
+ const res = await runManagedAgy(rest);
593
698
  if (res.exitCode) process.exitCode = res.exitCode;
594
699
  return;
595
700
  }
@@ -994,6 +1099,517 @@ async function handlePricingCommand(args) {
994
1099
  throw new Error(`Unknown pricing subcommand "${sub}". Run "agy-bar pricing --help" for usage.`);
995
1100
  }
996
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
+ fromAlias: sw.fromAlias,
1274
+ toAlias: sw.toAlias,
1275
+ family: effectiveFamily,
1276
+ };
1277
+ }
1278
+ : null;
1279
+
1280
+ return launchAgyWithProxy(rawArgs, {
1281
+ proxyConfig: cfg.proxy,
1282
+ syncAccount: syncActiveAccountBeforeLaunch,
1283
+ autoSwitchAccount,
1284
+ autoHandoffHook,
1285
+ });
1286
+ }
1287
+
1288
+ async function runPostSwitchHandoff({ fromAlias, targetAlias, printOnly = false }) {
1289
+ const handoff = prepareHandoff({ cwd: process.cwd(), fromAlias, targetAlias });
1290
+ if (printOnly) {
1291
+ console.log(handoff.prompt);
1292
+ return;
1293
+ }
1294
+ const cfg = loadConfig();
1295
+ const summaryBits = [
1296
+ handoff.artifactCount ? `${handoff.artifactCount} artifact(s)` : null,
1297
+ handoff.hasTranscript ? 'transcript' : null,
1298
+ handoff.hasGit ? 'git' : null,
1299
+ ]
1300
+ .filter(Boolean)
1301
+ .join(' + ');
1302
+ process.stderr.write(
1303
+ `agy-bar: launching fresh agy session on "${targetAlias}" with workspace handoff (${summaryBits || 'workspace'})...\n`,
1304
+ );
1305
+ const res = await launchAgyWithProxy(['-i', handoff.prompt], {
1306
+ proxyConfig: cfg.proxy,
1307
+ syncAccount: syncActiveAccountBeforeLaunch,
1308
+ });
1309
+ if (res.exitCode) process.exitCode = res.exitCode;
1310
+ }
1311
+
1312
+ async function handleSwitchCommand(args) {
1313
+ const { flags, positional } = parseFlags(args);
1314
+ const targetArg = positional[0] || null;
1315
+ const rows = listAccountsWithQuota();
1316
+ if (rows.length === 0) {
1317
+ throw new Error('No saved accounts yet. Run "agy-bar account save <alias>" first.');
1318
+ }
1319
+
1320
+ let targetAlias = targetArg;
1321
+ let pickedInfo = null;
1322
+ if (!targetAlias) {
1323
+ const chosen = await promptAccountPicker(rows);
1324
+ targetAlias = chosen.alias;
1325
+ } else if (targetAlias.toLowerCase() === 'next') {
1326
+ const state = readActiveAccountState();
1327
+ pickedInfo = pickNextBestAccount(rows, {
1328
+ currentId: state?.activeAccountId || null,
1329
+ family: flags.family || 'auto',
1330
+ });
1331
+ targetAlias = pickedInfo.account.alias;
1332
+ }
1333
+
1334
+ const res = switchToAccount(targetAlias);
1335
+ const writebackNote = res.wroteBackOutgoing && res.fromAlias ? ` (saved refreshed token for "${res.fromAlias}")` : '';
1336
+ const limitedNote = pickedInfo?.allLimited
1337
+ ? ' [all accounts currently LIMITED — picked earliest reset]'
1338
+ : '';
1339
+ console.log(
1340
+ `Switched active account -> ${res.account.alias}${res.account.maskedEmail ? ` (${res.account.maskedEmail})` : ''}${writebackNote}${limitedNote}`,
1341
+ );
1342
+ if (flags.handoff) {
1343
+ await runPostSwitchHandoff({
1344
+ fromAlias: res.fromAlias,
1345
+ targetAlias: res.account.alias,
1346
+ printOnly: Boolean(flags.print),
1347
+ });
1348
+ } else {
1349
+ console.log('Open a new "agy" session to use this account (or pass --handoff to continue your current task seamlessly).');
1350
+ }
1351
+ }
1352
+
1353
+ async function handleHandoffCommand(args) {
1354
+ const { flags } = parseFlags(args);
1355
+ const state = readActiveAccountState();
1356
+ const rows = listAccountsWithQuota();
1357
+ const activeRow = state?.activeAccountId ? rows.find((r) => r.id === state.activeAccountId) : null;
1358
+ const handoff = prepareHandoff({
1359
+ cwd: process.cwd(),
1360
+ targetAlias: activeRow?.alias || null,
1361
+ });
1362
+
1363
+ if (flags.print) {
1364
+ console.log(handoff.prompt);
1365
+ return;
1366
+ }
1367
+
1368
+ const cfg = loadConfig();
1369
+ process.stderr.write(
1370
+ `agy-bar: launching fresh agy session with handoff (${handoff.hasTranscript ? 'transcript + ' : ''}${handoff.hasGit ? 'git' : 'workspace'})...\n`,
1371
+ );
1372
+ const res = await launchAgyWithProxy(['-i', handoff.prompt], {
1373
+ proxyConfig: cfg.proxy,
1374
+ syncAccount: syncActiveAccountBeforeLaunch,
1375
+ });
1376
+ if (res.exitCode) process.exitCode = res.exitCode;
1377
+ }
1378
+
1379
+ async function handleAccountCommand(args) {
1380
+ const [sub = 'ls', ...rest] = args;
1381
+
1382
+ if (sub === 'help' || sub === '--help' || sub === '-h') {
1383
+ console.log(
1384
+ [
1385
+ 'Usage: agy-bar account <subcommand> [options]',
1386
+ '',
1387
+ ' ls | status [--json] [--plain] List saved accounts, 5h/7d quotas & READY/LIMITED timers',
1388
+ ` save [alias] [--force] [--storage ${VAULT_STORAGE_MODES.join('|')}] Save current logged-in agy session into vault`,
1389
+ ` add [alias] [--force] [--storage ${VAULT_STORAGE_MODES.join('|')}] Save current account, launch agy for one-time OAuth, capture new slot`,
1390
+ ` import [path] [--from ${IMPORT_SOURCES.join('|')}] [--dry-run] [--include-disabled] [--force] Import from Cockpit Tools or JSON`,
1391
+ ' use <alias> [--handoff] [--print] Switch active agy account without opening a browser',
1392
+ ` next [--family ${ACCOUNT_FAMILIES.join('|')}] [--handoff] Auto-switch to best READY account`,
1393
+ ' rename <old> <new> Rename an account alias',
1394
+ ' rm <alias> Remove an account from the local vault',
1395
+ ' backup <file> [--passphrase <pw>] Export AES-256-GCM encrypted vault backup',
1396
+ ' restore <file> [--passphrase <pw>] [--force] Restore accounts from an encrypted backup',
1397
+ ].join('\n'),
1398
+ );
1399
+ return;
1400
+ }
1401
+
1402
+ if (sub === 'ls' || sub === 'list' || sub === 'status') {
1403
+ const { flags } = parseFlags(rest);
1404
+ const rows = listAccountsWithQuota();
1405
+ if (flags.json) {
1406
+ console.log(
1407
+ JSON.stringify(
1408
+ {
1409
+ count: rows.length,
1410
+ activeAlias: rows.find((r) => r.isActive)?.alias || null,
1411
+ accounts: rows.map(sanitizeAccountForJson),
1412
+ },
1413
+ null,
1414
+ 2,
1415
+ ),
1416
+ );
1417
+ return;
1418
+ }
1419
+ const cfg = loadConfig();
1420
+ const color = !flags.plain && !('NO_COLOR' in process.env) && cfg.theme !== 'mono';
1421
+ console.log(formatAccountTable(rows, { color, theme: cfg.theme }));
1422
+ return;
1423
+ }
1424
+
1425
+ if (sub === 'save') {
1426
+ const { flags, positional } = parseFlags(rest);
1427
+ const res = saveCurrentAccount({
1428
+ alias: positional[0] || null,
1429
+ force: Boolean(flags.force),
1430
+ storage: flags.storage || 'auto',
1431
+ });
1432
+ console.log(
1433
+ `${res.action === 'updated' ? 'Updated' : 'Saved'} account "${res.account.alias}"${res.account.maskedEmail ? ` (${res.account.maskedEmail})` : ''} [${res.account.storageBackend}, read from ${res.source}].`,
1434
+ );
1435
+ return;
1436
+ }
1437
+
1438
+ if (sub === 'add') {
1439
+ const { flags, positional } = parseFlags(rest);
1440
+ const alias = positional[0] || null;
1441
+ const { preserved } = prepareForNewAccountLogin();
1442
+ if (preserved?.alias) {
1443
+ console.log(`Preserved current account "${preserved.alias}" in vault and cleared active session.`);
1444
+ } else {
1445
+ console.log('Cleared active Antigravity session.');
1446
+ }
1447
+ console.log('Launching official "agy" for one-time browser sign-in...');
1448
+ console.log('Complete login in your browser, then press Ctrl+C or run "/exit" in agy to finish saving.');
1449
+
1450
+ const cfg = loadConfig();
1451
+ await launchAgyWithProxy([], { proxyConfig: cfg.proxy, syncAccount: null });
1452
+
1453
+ const freshCred = readActiveAgyCredential();
1454
+ if (!freshCred?.raw) {
1455
+ if (preserved?.raw) {
1456
+ restorePreservedLogin(preserved);
1457
+ console.log(`No new login detected — restored previous account${preserved.alias ? ` "${preserved.alias}"` : ''}.`);
1458
+ } else {
1459
+ console.log('No new login detected.');
1460
+ }
1461
+ return;
1462
+ }
1463
+
1464
+ const res = saveCurrentAccount({
1465
+ alias,
1466
+ force: Boolean(flags.force),
1467
+ storage: flags.storage || 'auto',
1468
+ });
1469
+ console.log(
1470
+ `Captured & activated account "${res.account.alias}"${res.account.maskedEmail ? ` (${res.account.maskedEmail})` : ''} [${res.account.storageBackend}].`,
1471
+ );
1472
+ return;
1473
+ }
1474
+
1475
+ if (sub === 'import') {
1476
+ const { flags, positional } = parseFlags(rest);
1477
+ const res = importExternalAccounts({
1478
+ targetPath: positional[0] || null,
1479
+ from: flags.from || 'auto',
1480
+ force: Boolean(flags.force),
1481
+ includeDisabled: Boolean(flags.includeDisabled),
1482
+ dryRun: Boolean(flags.dryRun),
1483
+ storage: flags.storage || 'auto',
1484
+ });
1485
+
1486
+ if (flags.json) {
1487
+ console.log(JSON.stringify(res, null, 2));
1488
+ return;
1489
+ }
1490
+
1491
+ if (res.dryRun) {
1492
+ console.log(`Dry run (${res.source}: ${res.sourcePath}): found ${res.candidates.length} importable account(s).`);
1493
+ for (const c of res.candidates) {
1494
+ console.log(
1495
+ ` + ${c.alias}${c.maskedEmail ? ` (${c.maskedEmail})` : ''}${c.tier ? ` [${c.tier}]` : ''}${c.hasQuotaSeed ? ' · quota snapshot' : ''}`,
1496
+ );
1497
+ }
1498
+ if (res.skipped.length > 0) {
1499
+ console.log(`Skipped ${res.skipped.length}:`);
1500
+ for (const s of res.skipped) {
1501
+ console.log(` - ${s.alias || s.file || 'entry'}${s.maskedEmail ? ` (${s.maskedEmail})` : ''}: ${s.reason}`);
1502
+ }
1503
+ }
1504
+ return;
1505
+ }
1506
+
1507
+ console.log(
1508
+ `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` : ''}.`,
1509
+ );
1510
+ for (const item of res.imported) {
1511
+ console.log(
1512
+ ` + ${item.alias}${item.maskedEmail ? ` (${item.maskedEmail})` : ''}${item.tier ? ` [${item.tier}]` : ''} [${item.storageBackend}]`,
1513
+ );
1514
+ }
1515
+ for (const item of res.updated) {
1516
+ console.log(
1517
+ ` ~ ${item.alias}${item.maskedEmail ? ` (${item.maskedEmail})` : ''}${item.tier ? ` [${item.tier}]` : ''} [updated]`,
1518
+ );
1519
+ }
1520
+ for (const s of res.skipped) {
1521
+ console.log(` - skipped ${s.alias || s.file || 'entry'}${s.maskedEmail ? ` (${s.maskedEmail})` : ''}: ${s.reason}`);
1522
+ }
1523
+ console.log('Run "agy-bar account ls" to inspect quotas, or "agy-bar switch" to switch without a browser.');
1524
+ return;
1525
+ }
1526
+
1527
+ if (sub === 'use') {
1528
+ const { flags, positional } = parseFlags(rest);
1529
+ if (!positional[0]) {
1530
+ throw new Error('Usage: agy-bar account use <alias> [--handoff]');
1531
+ }
1532
+ await handleSwitchCommand([positional[0], ...(flags.handoff ? ['--handoff'] : []), ...(flags.print ? ['--print'] : [])]);
1533
+ return;
1534
+ }
1535
+
1536
+ if (sub === 'next') {
1537
+ const { flags } = parseFlags(rest);
1538
+ await handleSwitchCommand([
1539
+ 'next',
1540
+ ...(flags.family ? ['--family', flags.family] : []),
1541
+ ...(flags.handoff ? ['--handoff'] : []),
1542
+ ...(flags.print ? ['--print'] : []),
1543
+ ]);
1544
+ return;
1545
+ }
1546
+
1547
+ if (sub === 'rename' || sub === 'alias') {
1548
+ const { positional } = parseFlags(rest);
1549
+ if (positional.length < 2) {
1550
+ throw new Error('Usage: agy-bar account rename <old-alias> <new-alias>');
1551
+ }
1552
+ const res = renameAccount(positional[0], positional[1]);
1553
+ console.log(`Renamed account "${res.oldAlias}" -> "${res.newAlias}".`);
1554
+ return;
1555
+ }
1556
+
1557
+ if (sub === 'rm' || sub === 'remove' || sub === 'delete') {
1558
+ const { positional } = parseFlags(rest);
1559
+ if (!positional[0]) {
1560
+ throw new Error('Usage: agy-bar account rm <alias>');
1561
+ }
1562
+ const res = removeAccount(positional[0]);
1563
+ console.log(`Removed account "${res.account.alias}" from vault (${res.remaining} remaining).`);
1564
+ return;
1565
+ }
1566
+
1567
+ if (sub === 'backup') {
1568
+ const { flags, positional } = parseFlags(rest);
1569
+ const outPath = positional[0];
1570
+ if (!outPath) {
1571
+ throw new Error('Usage: agy-bar account backup <output-file.json> [--passphrase <pw>]');
1572
+ }
1573
+ let passphrase = flags.passphrase || process.env.AGY_BAR_BACKUP_PASSPHRASE || '';
1574
+ if (!passphrase) {
1575
+ passphrase = await promptHiddenPassphrase('Enter encryption passphrase (min 4 chars): ');
1576
+ const confirm = await promptHiddenPassphrase('Confirm passphrase: ');
1577
+ if (passphrase !== confirm) {
1578
+ throw new Error('Passphrases do not match.');
1579
+ }
1580
+ }
1581
+ const envelope = exportEncryptedBackup({ passphrase });
1582
+ const absPath = resolve(outPath);
1583
+ writeFileAtomic(absPath, JSON.stringify(envelope, null, 2) + '\n', { mode: 0o600 });
1584
+ console.log(`Exported ${envelope.count} encrypted account(s) -> ${absPath} (AES-256-GCM)`);
1585
+ return;
1586
+ }
1587
+
1588
+ if (sub === 'restore') {
1589
+ const { flags, positional } = parseFlags(rest);
1590
+ const inPath = positional[0];
1591
+ if (!inPath) {
1592
+ throw new Error('Usage: agy-bar account restore <backup-file.json> [--passphrase <pw>] [--force]');
1593
+ }
1594
+ let passphrase = flags.passphrase || process.env.AGY_BAR_BACKUP_PASSPHRASE || '';
1595
+ if (!passphrase) {
1596
+ passphrase = await promptHiddenPassphrase('Enter backup passphrase: ');
1597
+ }
1598
+ const envelope = JSON.parse(readFileSync(resolve(inPath), 'utf8'));
1599
+ const res = importEncryptedBackup(envelope, {
1600
+ passphrase,
1601
+ force: Boolean(flags.force),
1602
+ storage: flags.storage || 'auto',
1603
+ });
1604
+ console.log(
1605
+ `Restored vault: ${res.imported.length} imported, ${res.updated.length} updated (${res.total} total accounts).`,
1606
+ );
1607
+ return;
1608
+ }
1609
+
1610
+ throw new Error(`Unknown account subcommand "${sub}". Run "agy-bar account --help" for usage.`);
1611
+ }
1612
+
997
1613
  function isDirectInvocation() {
998
1614
  if (!process.argv[1]) return false;
999
1615
  try {