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/src/proxy.mjs CHANGED
@@ -640,6 +640,9 @@ export function parseRunArgs(args = []) {
640
640
  agyBin: null,
641
641
  quiet: false,
642
642
  fromHook: false,
643
+ autoSwitch: null,
644
+ autoHandoff: null,
645
+ family: null,
643
646
  };
644
647
  const agyArgs = [];
645
648
 
@@ -665,6 +668,40 @@ export function parseRunArgs(args = []) {
665
668
  i += 1;
666
669
  continue;
667
670
  }
671
+ if (arg === '--auto-switch') {
672
+ options.autoSwitch = true;
673
+ i += 1;
674
+ continue;
675
+ }
676
+ if (arg === '--no-auto-switch') {
677
+ options.autoSwitch = false;
678
+ i += 1;
679
+ continue;
680
+ }
681
+ if (arg === '--auto-handoff') {
682
+ options.autoHandoff = true;
683
+ i += 1;
684
+ continue;
685
+ }
686
+ if (arg === '--no-auto-handoff') {
687
+ options.autoHandoff = false;
688
+ i += 1;
689
+ continue;
690
+ }
691
+ if (arg === '--family') {
692
+ const value = args[i + 1];
693
+ if (!value) throw new Error('Missing value for --family (auto | gemini | claude)');
694
+ options.family = value.toLowerCase();
695
+ i += 2;
696
+ continue;
697
+ }
698
+ if (arg.startsWith('--family=')) {
699
+ const value = arg.slice('--family='.length);
700
+ if (!value) throw new Error('Missing value for --family=');
701
+ options.family = value.toLowerCase();
702
+ i += 1;
703
+ continue;
704
+ }
668
705
  if (arg === '--proxy') {
669
706
  const value = args[i + 1];
670
707
  if (!value) throw new Error('Missing value for --proxy. Example: agy-bar run --proxy http://127.0.0.1:7897');
@@ -702,6 +739,24 @@ export function parseRunArgs(args = []) {
702
739
  return { options, agyArgs };
703
740
  }
704
741
 
742
+ export function buildHandoffResumeArgs(originalAgyArgs = [], promptText) {
743
+ const preserved = [];
744
+ const skipValueFlags = new Set(['-r', '--resume', '--conversation', '-i', '--prompt-interactive', '-p', '--print', '--prompt']);
745
+ const skipBoolFlags = new Set(['-c', '--continue']);
746
+ for (let i = 0; i < originalAgyArgs.length; i++) {
747
+ const arg = originalAgyArgs[i];
748
+ if (skipBoolFlags.has(arg)) continue;
749
+ if (skipValueFlags.has(arg)) {
750
+ i += 1;
751
+ continue;
752
+ }
753
+ if ([...skipValueFlags].some((f) => arg.startsWith(`${f}=`))) continue;
754
+ preserved.push(arg);
755
+ }
756
+ preserved.push('-i', promptText);
757
+ return preserved;
758
+ }
759
+
705
760
  export async function launchAgyWithProxy(
706
761
  rawArgs = [],
707
762
  {
@@ -712,6 +767,11 @@ export async function launchAgyWithProxy(
712
767
  probePort = checkLocalPort,
713
768
  spawnFn = spawn,
714
769
  stderr = process.stderr,
770
+ syncAccount = null,
771
+ autoSwitchAccount = null,
772
+ autoHandoffHook = null,
773
+ minAutoHandoffRunMs = 3000,
774
+ maxAutoHandoffHops = 5,
715
775
  } = {},
716
776
  ) {
717
777
  if (env.AGY_BAR_PROXY_WRAPPER === '1') {
@@ -725,6 +785,35 @@ export async function launchAgyWithProxy(
725
785
  const noProxy = options.noProxy || envNoProxy;
726
786
  const executable = options.agyBin || env.AGY_BIN || 'agy';
727
787
 
788
+ // Multi-terminal drift guard: no-op (<0.1ms) unless user has activated agy-bar accounts.
789
+ if (typeof syncAccount === 'function') {
790
+ try {
791
+ const syncRes = syncAccount();
792
+ if (syncRes?.synced && !options.quiet) {
793
+ const msg = syncRes.repairedFrom
794
+ ? `agy-bar: restored active account "${syncRes.alias}" (saved refreshed token for "${syncRes.repairedFrom}")\n`
795
+ : `agy-bar: synced active account "${syncRes.alias}"\n`;
796
+ stderr.write(msg);
797
+ }
798
+ } catch {
799
+ // Never block launching agy if account sync encounters an unexpected error.
800
+ }
801
+ }
802
+
803
+ // Optional pre-launch auto-switch when active account is already LIMITED.
804
+ if (typeof autoSwitchAccount === 'function') {
805
+ try {
806
+ const swRes = autoSwitchAccount({ family: options.family || 'auto' });
807
+ if (swRes?.switched && !options.quiet) {
808
+ stderr.write(
809
+ `agy-bar: active account "${swRes.fromAlias}" is LIMITED — auto-switched -> "${swRes.toAlias}"\n`,
810
+ );
811
+ }
812
+ } catch {
813
+ // Never block launching agy due to auto-switch errors.
814
+ }
815
+ }
816
+
728
817
  const resolved = await resolveEffectiveProxy(proxyConfig, {
729
818
  overrideUrl: options.proxyUrl,
730
819
  noProxy,
@@ -769,61 +858,113 @@ export async function launchAgyWithProxy(
769
858
  const childEnv = buildProxyEnv(resolved, env, { stripExisting: noProxy });
770
859
  childEnv.AGY_BAR_PROXY_WRAPPER = '1';
771
860
  const target = resolveSpawnTarget(executable, { platform, env });
861
+ const isPrintMode = agyArgs.some((a) => a === '-p' || a === '--print' || a === '--prompt' || a.startsWith('--print=') || a.startsWith('--prompt='));
862
+
863
+ const spawnOnce = (currentArgs) =>
864
+ new Promise((resolveChild, rejectChild) => {
865
+ const child = spawnFn(target.command, currentArgs, {
866
+ stdio: 'inherit',
867
+ env: childEnv,
868
+ shell: target.shell,
869
+ });
870
+
871
+ // Forward termination signals; let child TUI own interactive Ctrl+C (SIGINT).
872
+ const onSigInt = () => {};
873
+ const onSigTerm = () => {
874
+ try {
875
+ child.kill('SIGTERM');
876
+ } catch {
877
+ // Ignore if already exited.
878
+ }
879
+ };
880
+ const onSigHup = () => {
881
+ try {
882
+ child.kill('SIGHUP');
883
+ } catch {
884
+ // Ignore if already exited.
885
+ }
886
+ };
887
+
888
+ process.on('SIGINT', onSigInt);
889
+ process.on('SIGTERM', onSigTerm);
890
+ if (platform !== 'win32') process.on('SIGHUP', onSigHup);
891
+
892
+ const cleanup = () => {
893
+ process.off('SIGINT', onSigInt);
894
+ process.off('SIGTERM', onSigTerm);
895
+ if (platform !== 'win32') process.off('SIGHUP', onSigHup);
896
+ };
772
897
 
773
- return new Promise((resolve, reject) => {
774
- const child = spawnFn(target.command, agyArgs, {
775
- stdio: 'inherit',
776
- env: childEnv,
777
- shell: target.shell,
898
+ child.once('error', (err) => {
899
+ cleanup();
900
+ if (err?.code === 'ENOENT') {
901
+ rejectChild(
902
+ new Error(
903
+ `Could not find "${executable}" in PATH. Ensure Antigravity CLI (agy) is installed or pass --agy-bin <path>.`,
904
+ ),
905
+ );
906
+ return;
907
+ }
908
+ rejectChild(err);
909
+ });
910
+
911
+ child.once('exit', (code, signal) => {
912
+ cleanup();
913
+ resolveChild({
914
+ exitCode: typeof code === 'number' ? code : signal ? 128 : 0,
915
+ signal: signal || null,
916
+ });
917
+ });
778
918
  });
779
919
 
780
- // Forward termination signals; let child TUI own interactive Ctrl+C (SIGINT).
781
- const onSigInt = () => {};
782
- const onSigTerm = () => {
783
- try {
784
- child.kill('SIGTERM');
785
- } catch {
786
- // Ignore if already exited.
787
- }
788
- };
789
- const onSigHup = () => {
920
+ let currentArgs = agyArgs;
921
+ let hops = 0;
922
+
923
+ while (true) {
924
+ const startedAt = Date.now();
925
+ const res = await spawnOnce(currentArgs);
926
+ const elapsedMs = Date.now() - startedAt;
927
+
928
+ const canAttemptHandoff =
929
+ typeof autoHandoffHook === 'function' &&
930
+ !isPrintMode &&
931
+ hops < maxAutoHandoffHops &&
932
+ elapsedMs >= minAutoHandoffRunMs &&
933
+ res.signal !== 'SIGTERM' &&
934
+ res.signal !== 'SIGHUP';
935
+
936
+ if (canAttemptHandoff) {
937
+ let nextHop = null;
790
938
  try {
791
- child.kill('SIGHUP');
939
+ nextHop = await autoHandoffHook({
940
+ exitCode: res.exitCode,
941
+ signal: res.signal,
942
+ startedAt,
943
+ elapsedMs,
944
+ hop: hops,
945
+ family: options.family || null,
946
+ });
792
947
  } catch {
793
- // Ignore if already exited.
948
+ nextHop = null;
794
949
  }
795
- };
796
950
 
797
- process.on('SIGINT', onSigInt);
798
- process.on('SIGTERM', onSigTerm);
799
- if (platform !== 'win32') process.on('SIGHUP', onSigHup);
800
-
801
- const cleanup = () => {
802
- process.off('SIGINT', onSigInt);
803
- process.off('SIGTERM', onSigTerm);
804
- if (platform !== 'win32') process.off('SIGHUP', onSigHup);
805
- };
806
-
807
- child.once('error', (err) => {
808
- cleanup();
809
- if (err?.code === 'ENOENT') {
810
- reject(
811
- new Error(
812
- `Could not find "${executable}" in PATH. Ensure Antigravity CLI (agy) is installed or pass --agy-bin <path>.`,
813
- ),
814
- );
815
- return;
951
+ if (nextHop?.resume && nextHop.prompt) {
952
+ hops += 1;
953
+ if (!options.quiet) {
954
+ stderr.write(
955
+ `agy-bar: "${nextHop.fromAlias}" hit ${nextHop.family || 'quota'} limit — switched -> "${nextHop.toAlias}" and resuming with handoff (${hops}/${maxAutoHandoffHops})...\n`,
956
+ );
957
+ }
958
+ currentArgs = buildHandoffResumeArgs(agyArgs, nextHop.prompt);
959
+ continue;
816
960
  }
817
- reject(err);
818
- });
961
+ }
819
962
 
820
- child.once('exit', (code, signal) => {
821
- cleanup();
822
- resolve({
823
- exitCode: typeof code === 'number' ? code : signal ? 128 : 0,
824
- signal: signal || null,
825
- proxy: resolved,
826
- });
827
- });
828
- });
963
+ return {
964
+ exitCode: res.exitCode,
965
+ signal: res.signal,
966
+ proxy: resolved,
967
+ hops,
968
+ };
969
+ }
829
970
  }
@@ -9,6 +9,7 @@ import { writeFileAtomic } from './fs-atomic.mjs';
9
9
  export const EPOCH_SENTINEL_MS = 86_400_000;
10
10
  export const RESET_TOLERANCE_MS = 5_000;
11
11
  export const MAX_CACHE_AGE_MS = 6 * 60 * 60 * 1000;
12
+ export const MAX_ACCOUNT_QUOTA_RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
12
13
  const FRACTION_EPSILON = 1e-6;
13
14
 
14
15
  const WEEKLY_SIBLING_BUCKET = Object.freeze({
@@ -61,7 +62,13 @@ export function isWeeklyBucketBlocking(bucketId, quotaMap, now = Date.now()) {
61
62
  return !isBucketResetDue(weekly, now);
62
63
  }
63
64
 
64
- export function extractAccountKey(payload) {
65
+ export function hashAccountIdentifier(raw) {
66
+ const cleaned = typeof raw === 'string' ? raw.trim().toLowerCase() : '';
67
+ if (!cleaned) return null;
68
+ return createHash('sha1').update(cleaned).digest('hex').slice(0, 12);
69
+ }
70
+
71
+ export function extractAccountKey(payload, { fallbackAccountKey = null } = {}) {
65
72
  const raw =
66
73
  payload?.email ||
67
74
  payload?.account?.email ||
@@ -70,9 +77,12 @@ export function extractAccountKey(payload) {
70
77
  payload?.account_id ||
71
78
  payload?.user_id ||
72
79
  '';
73
- const cleaned = typeof raw === 'string' ? raw.trim().toLowerCase() : '';
74
- if (!cleaned) return 'default';
75
- return createHash('sha1').update(cleaned).digest('hex').slice(0, 12);
80
+ const hashed = hashAccountIdentifier(raw);
81
+ if (hashed) return hashed;
82
+ if (typeof fallbackAccountKey === 'string' && fallbackAccountKey.trim()) {
83
+ return fallbackAccountKey.trim();
84
+ }
85
+ return 'default';
76
86
  }
77
87
 
78
88
  export function normalizeQuotaBucket(raw, observedAt = Date.now()) {
@@ -196,31 +206,87 @@ function materializeBucket(baseRaw, winner, now) {
196
206
  return out;
197
207
  }
198
208
 
199
- export function readSharedQuota({ baseDir = configDir(homedir()), now = Date.now(), accountKey = 'default' } = {}) {
200
- const filePath = quotaCachePath(baseDir);
209
+ function readRawQuotaCache(filePath) {
201
210
  if (!existsSync(filePath)) return null;
202
211
  try {
203
212
  const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
204
- if (!parsed || typeof parsed !== 'object' || !parsed.buckets || typeof parsed.buckets !== 'object') return null;
205
- const cachedAccount = typeof parsed.accountKey === 'string' ? parsed.accountKey : 'default';
206
- if (accountKey !== 'default' && cachedAccount !== 'default' && cachedAccount !== accountKey) {
207
- return null;
213
+ return parsed && typeof parsed === 'object' ? parsed : null;
214
+ } catch {
215
+ return null;
216
+ }
217
+ }
218
+
219
+ function normalizeAccountBucketMap(rawBuckets, fallbackObservedAt, now, maxAgeMs) {
220
+ const buckets = {};
221
+ if (!rawBuckets || typeof rawBuckets !== 'object') return buckets;
222
+ for (const [id, raw] of Object.entries(rawBuckets)) {
223
+ const norm = normalizeQuotaBucket(raw, fallbackObservedAt);
224
+ if (norm && now - norm.observedAt <= maxAgeMs) {
225
+ buckets[id] = norm;
208
226
  }
209
- const buckets = {};
210
- for (const [id, raw] of Object.entries(parsed.buckets)) {
211
- const norm = normalizeQuotaBucket(raw, nonNeg(parsed.updatedAt) ?? now);
212
- if (norm && now - norm.observedAt <= MAX_CACHE_AGE_MS) {
213
- buckets[id] = norm;
227
+ }
228
+ return buckets;
229
+ }
230
+
231
+ export function readAllAccountQuotas({ baseDir = configDir(homedir()), now = Date.now(), maxAgeMs = MAX_ACCOUNT_QUOTA_RETENTION_MS } = {}) {
232
+ const parsed = readRawQuotaCache(quotaCachePath(baseDir));
233
+ if (!parsed) return {};
234
+
235
+ const out = {};
236
+ if (parsed.accounts && typeof parsed.accounts === 'object') {
237
+ for (const [key, entry] of Object.entries(parsed.accounts)) {
238
+ if (!entry || typeof entry !== 'object') continue;
239
+ const updatedAt = nonNeg(entry.updatedAt) ?? nonNeg(parsed.updatedAt) ?? now;
240
+ const buckets = normalizeAccountBucketMap(entry.buckets, updatedAt, now, maxAgeMs);
241
+ if (Object.keys(buckets).length > 0) {
242
+ out[key] = { accountKey: key, updatedAt, buckets };
214
243
  }
215
244
  }
245
+ }
246
+
247
+ // Backward compatibility: include legacy top-level buckets if absent from accounts map.
248
+ if (parsed.buckets && typeof parsed.buckets === 'object') {
249
+ const topKey = typeof parsed.accountKey === 'string' && parsed.accountKey.trim() ? parsed.accountKey.trim() : 'default';
250
+ if (!out[topKey]) {
251
+ const updatedAt = nonNeg(parsed.updatedAt) ?? now;
252
+ const buckets = normalizeAccountBucketMap(parsed.buckets, updatedAt, now, maxAgeMs);
253
+ if (Object.keys(buckets).length > 0) {
254
+ out[topKey] = { accountKey: topKey, updatedAt, buckets };
255
+ }
256
+ }
257
+ }
258
+
259
+ return out;
260
+ }
261
+
262
+ export function readSharedQuota({ baseDir = configDir(homedir()), now = Date.now(), accountKey = 'default' } = {}) {
263
+ const parsed = readRawQuotaCache(quotaCachePath(baseDir));
264
+ if (!parsed) return null;
265
+
266
+ // Prefer explicit per-account cache entry when present (multi-account safe).
267
+ const accountEntry = parsed.accounts && typeof parsed.accounts === 'object' ? parsed.accounts[accountKey] : null;
268
+ if (accountEntry && typeof accountEntry === 'object' && accountEntry.buckets && typeof accountEntry.buckets === 'object') {
269
+ const updatedAt = nonNeg(accountEntry.updatedAt) ?? nonNeg(parsed.updatedAt) ?? now;
270
+ const buckets = normalizeAccountBucketMap(accountEntry.buckets, updatedAt, now, MAX_CACHE_AGE_MS);
216
271
  return {
217
- accountKey: cachedAccount,
218
- updatedAt: nonNeg(parsed.updatedAt) ?? now,
272
+ accountKey,
273
+ updatedAt,
219
274
  buckets,
220
275
  };
221
- } catch {
276
+ }
277
+
278
+ if (!parsed.buckets || typeof parsed.buckets !== 'object') return null;
279
+ const cachedAccount = typeof parsed.accountKey === 'string' ? parsed.accountKey : 'default';
280
+ if (accountKey !== 'default' && cachedAccount !== 'default' && cachedAccount !== accountKey) {
222
281
  return null;
223
282
  }
283
+ const updatedAt = nonNeg(parsed.updatedAt) ?? now;
284
+ const buckets = normalizeAccountBucketMap(parsed.buckets, updatedAt, now, MAX_CACHE_AGE_MS);
285
+ return {
286
+ accountKey: cachedAccount,
287
+ updatedAt,
288
+ buckets,
289
+ };
224
290
  }
225
291
 
226
292
  export function mergeQuotaSnapshots(snapshots = [], now = Date.now()) {
@@ -275,11 +341,25 @@ export function syncSharedQuota(
275
341
 
276
342
  if (cacheDirty && Object.keys(nextCacheBuckets).length > 0) {
277
343
  try {
344
+ const resolvedKey = accountKey !== 'default' ? accountKey : existingCache?.accountKey || 'default';
345
+ const existingAccounts = readAllAccountQuotas({ baseDir, now });
346
+ const accounts = {};
347
+ for (const [k, entry] of Object.entries(existingAccounts)) {
348
+ accounts[k] = {
349
+ updatedAt: entry.updatedAt,
350
+ buckets: entry.buckets,
351
+ };
352
+ }
353
+ accounts[resolvedKey] = {
354
+ updatedAt: now,
355
+ buckets: nextCacheBuckets,
356
+ };
278
357
  const payload = {
279
- version: 1,
280
- accountKey: accountKey !== 'default' ? accountKey : existingCache?.accountKey || 'default',
358
+ version: 2,
359
+ accountKey: resolvedKey,
281
360
  updatedAt: now,
282
361
  buckets: nextCacheBuckets,
362
+ accounts,
283
363
  };
284
364
  writeFileAtomic(quotaCachePath(baseDir), JSON.stringify(payload) + '\n');
285
365
  } catch {
package/src/render.mjs CHANGED
@@ -666,7 +666,7 @@ function buildSessionSegment(opts, config, palette, color, telemetry) {
666
666
  return fg(parts.join('·'), palette.muted, color);
667
667
  }
668
668
 
669
- function buildQuotaSegment(entries, opts, config, palette, color, now, rawQuota = null) {
669
+ function buildQuotaSegment(entries, opts, config, palette, color, now, rawQuota = null, swapHint = null) {
670
670
  if (!entries.length) return '';
671
671
  const { show, barStyle, barWidth, quotaWarn, quotaDanger } = config;
672
672
  const quotaMap = rawQuota && typeof rawQuota === 'object' ? rawQuota : Object.fromEntries(entries.map((e) => [e.id, e.bucket]));
@@ -712,6 +712,10 @@ function buildQuotaSegment(entries, opts, config, palette, color, now, rawQuota
712
712
  return pieces.join(' ');
713
713
  });
714
714
 
715
+ if (swapHint?.alias && config.swapHint !== false && !opts.tight) {
716
+ parts.push(bold(fg(`SWAP→${swapHint.alias}`, palette.accent, color), color));
717
+ }
718
+
715
719
  return joinWithSep(parts, opts.tight ? ' ' : ' │ ', palette, color);
716
720
  }
717
721
 
@@ -722,7 +726,7 @@ function renderMetricsRow(
722
726
  palette,
723
727
  color,
724
728
  now,
725
- { includePrefix = false, git = null, telemetry = null } = {},
729
+ { includePrefix = false, git = null, telemetry = null, swapHint = null } = {},
726
730
  ) {
727
731
  const context = payload?.context_window || {};
728
732
  const quotaEntries = selectQuotaEntries(payload?.quota, payload?.model, config.show);
@@ -770,7 +774,7 @@ function renderMetricsRow(
770
774
  if (sessionSeg) leftParts.push(sessionSeg);
771
775
 
772
776
  const left = joinWithSep(leftParts, stage.tight ? ' ' : sep, palette, color);
773
- const right = buildQuotaSegment(quotaEntries, stage, config, palette, color, now, payload?.quota);
777
+ const right = buildQuotaSegment(quotaEntries, stage, config, palette, color, now, payload?.quota, swapHint);
774
778
  const minGap = left && right ? 2 : 0;
775
779
  chosenLeft = left;
776
780
  chosenRight = right;
@@ -801,6 +805,7 @@ export function renderStatusline(
801
805
  git = null,
802
806
  telemetry = null,
803
807
  usageSummary = null,
808
+ swapHint = null,
804
809
  env = {},
805
810
  home = homedir(),
806
811
  themeOptions = {},
@@ -819,6 +824,7 @@ export function renderStatusline(
819
824
  includePrefix: true,
820
825
  git,
821
826
  telemetry,
827
+ swapHint,
822
828
  });
823
829
  return row || renderFallback(cfg, { color: useColor, theme: resolved.name });
824
830
  }
@@ -828,6 +834,7 @@ export function renderStatusline(
828
834
  includePrefix: false,
829
835
  git: null,
830
836
  telemetry,
837
+ swapHint,
831
838
  });
832
839
  return row || renderFallback(cfg, { color: useColor, theme: resolved.name });
833
840
  }
@@ -856,6 +863,7 @@ export function renderStatusline(
856
863
  includePrefix: false,
857
864
  git: null,
858
865
  telemetry,
866
+ swapHint,
859
867
  });
860
868
  if (metrics) lines.push(metrics);
861
869