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/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,41 @@ export function parseRunArgs(args = []) {
702
739
  return { options, agyArgs };
703
740
  }
704
741
 
742
+ export function formatPromptArgForTarget(
743
+ promptText,
744
+ { target = null, savedHandoffPath = null, platform = process.platform } = {},
745
+ ) {
746
+ const raw = String(promptText ?? '');
747
+ if (platform === 'win32' && target?.shell === true && /[\r\n&|<>^%"]/.test(raw)) {
748
+ // Windows cmd.exe (.cmd/.bat shims) breaks on newlines and shell metacharacters.
749
+ // Point the incoming session at the already-written handoff Markdown file instead.
750
+ if (savedHandoffPath) {
751
+ const safePath = String(savedHandoffPath).replace(/\\/g, '/').replace(/["&|<>^%\r\n]/g, '');
752
+ return `Continue the ongoing task using the workspace handoff saved at ${safePath}. Read that file first, briefly confirm what is done vs remaining, and resume immediately.`;
753
+ }
754
+ return raw.replace(/[\r\n]+/g, ' ').replace(/[&|<>^%"]/g, ' ').replace(/\s+/g, ' ').trim();
755
+ }
756
+ return raw;
757
+ }
758
+
759
+ export function buildHandoffResumeArgs(originalAgyArgs = [], promptText, targetOpts = {}) {
760
+ const preserved = [];
761
+ const skipValueFlags = new Set(['-r', '--resume', '--conversation', '-i', '--prompt-interactive', '-p', '--print', '--prompt']);
762
+ const skipBoolFlags = new Set(['-c', '--continue']);
763
+ for (let i = 0; i < originalAgyArgs.length; i++) {
764
+ const arg = originalAgyArgs[i];
765
+ if (skipBoolFlags.has(arg)) continue;
766
+ if (skipValueFlags.has(arg)) {
767
+ i += 1;
768
+ continue;
769
+ }
770
+ if ([...skipValueFlags].some((f) => arg.startsWith(`${f}=`))) continue;
771
+ preserved.push(arg);
772
+ }
773
+ preserved.push('-i', formatPromptArgForTarget(promptText, targetOpts));
774
+ return preserved;
775
+ }
776
+
705
777
  export async function launchAgyWithProxy(
706
778
  rawArgs = [],
707
779
  {
@@ -712,6 +784,12 @@ export async function launchAgyWithProxy(
712
784
  probePort = checkLocalPort,
713
785
  spawnFn = spawn,
714
786
  stderr = process.stderr,
787
+ syncAccount = null,
788
+ autoSwitchAccount = null,
789
+ autoHandoffHook = null,
790
+ handoffSavedPath = null,
791
+ minAutoHandoffRunMs = 3000,
792
+ maxAutoHandoffHops = 5,
715
793
  } = {},
716
794
  ) {
717
795
  if (env.AGY_BAR_PROXY_WRAPPER === '1') {
@@ -725,6 +803,35 @@ export async function launchAgyWithProxy(
725
803
  const noProxy = options.noProxy || envNoProxy;
726
804
  const executable = options.agyBin || env.AGY_BIN || 'agy';
727
805
 
806
+ // Multi-terminal drift guard: no-op (<0.1ms) unless user has activated agy-bar accounts.
807
+ if (typeof syncAccount === 'function') {
808
+ try {
809
+ const syncRes = syncAccount();
810
+ if (syncRes?.synced && !options.quiet) {
811
+ const msg = syncRes.repairedFrom
812
+ ? `agy-bar: restored active account "${syncRes.alias}" (saved refreshed token for "${syncRes.repairedFrom}")\n`
813
+ : `agy-bar: synced active account "${syncRes.alias}"\n`;
814
+ stderr.write(msg);
815
+ }
816
+ } catch {
817
+ // Never block launching agy if account sync encounters an unexpected error.
818
+ }
819
+ }
820
+
821
+ // Optional pre-launch auto-switch when active account is already LIMITED.
822
+ if (typeof autoSwitchAccount === 'function') {
823
+ try {
824
+ const swRes = autoSwitchAccount({ family: options.family || 'auto' });
825
+ if (swRes?.switched && !options.quiet) {
826
+ stderr.write(
827
+ `agy-bar: active account "${swRes.fromAlias}" is LIMITED — auto-switched -> "${swRes.toAlias}"\n`,
828
+ );
829
+ }
830
+ } catch {
831
+ // Never block launching agy due to auto-switch errors.
832
+ }
833
+ }
834
+
728
835
  const resolved = await resolveEffectiveProxy(proxyConfig, {
729
836
  overrideUrl: options.proxyUrl,
730
837
  noProxy,
@@ -769,61 +876,128 @@ export async function launchAgyWithProxy(
769
876
  const childEnv = buildProxyEnv(resolved, env, { stripExisting: noProxy });
770
877
  childEnv.AGY_BAR_PROXY_WRAPPER = '1';
771
878
  const target = resolveSpawnTarget(executable, { platform, env });
879
+ const isPrintMode = agyArgs.some((a) => a === '-p' || a === '--print' || a === '--prompt' || a.startsWith('--print=') || a.startsWith('--prompt='));
880
+
881
+ const sanitizeArgsForWinShell = (argsList, savedPath) => {
882
+ if (platform !== 'win32' || target.shell !== true) return argsList;
883
+ const out = [...argsList];
884
+ for (let idx = 0; idx < out.length - 1; idx++) {
885
+ if (out[idx] === '-i' || out[idx] === '--prompt-interactive') {
886
+ out[idx + 1] = formatPromptArgForTarget(out[idx + 1], { target, savedHandoffPath: savedPath, platform });
887
+ }
888
+ }
889
+ return out;
890
+ };
772
891
 
773
- return new Promise((resolve, reject) => {
774
- const child = spawnFn(target.command, agyArgs, {
775
- stdio: 'inherit',
776
- env: childEnv,
777
- shell: target.shell,
892
+ const spawnOnce = (currentArgs) =>
893
+ new Promise((resolveChild, rejectChild) => {
894
+ const child = spawnFn(target.command, currentArgs, {
895
+ stdio: 'inherit',
896
+ env: childEnv,
897
+ shell: target.shell,
898
+ });
899
+
900
+ // Forward termination signals; let child TUI own interactive Ctrl+C (SIGINT).
901
+ const onSigInt = () => {};
902
+ const onSigTerm = () => {
903
+ try {
904
+ child.kill('SIGTERM');
905
+ } catch {
906
+ // Ignore if already exited.
907
+ }
908
+ };
909
+ const onSigHup = () => {
910
+ try {
911
+ child.kill('SIGHUP');
912
+ } catch {
913
+ // Ignore if already exited.
914
+ }
915
+ };
916
+
917
+ process.on('SIGINT', onSigInt);
918
+ process.on('SIGTERM', onSigTerm);
919
+ if (platform !== 'win32') process.on('SIGHUP', onSigHup);
920
+
921
+ const cleanup = () => {
922
+ process.off('SIGINT', onSigInt);
923
+ process.off('SIGTERM', onSigTerm);
924
+ if (platform !== 'win32') process.off('SIGHUP', onSigHup);
925
+ };
926
+
927
+ child.once('error', (err) => {
928
+ cleanup();
929
+ if (err?.code === 'ENOENT') {
930
+ rejectChild(
931
+ new Error(
932
+ `Could not find "${executable}" in PATH. Ensure Antigravity CLI (agy) is installed or pass --agy-bin <path>.`,
933
+ ),
934
+ );
935
+ return;
936
+ }
937
+ rejectChild(err);
938
+ });
939
+
940
+ child.once('exit', (code, signal) => {
941
+ cleanup();
942
+ resolveChild({
943
+ exitCode: typeof code === 'number' ? code : signal ? 128 : 0,
944
+ signal: signal || null,
945
+ });
946
+ });
778
947
  });
779
948
 
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 = () => {
949
+ let currentArgs = sanitizeArgsForWinShell(agyArgs, handoffSavedPath);
950
+ let hops = 0;
951
+
952
+ while (true) {
953
+ const startedAt = Date.now();
954
+ const res = await spawnOnce(currentArgs);
955
+ const elapsedMs = Date.now() - startedAt;
956
+
957
+ const canAttemptHandoff =
958
+ typeof autoHandoffHook === 'function' &&
959
+ !isPrintMode &&
960
+ hops < maxAutoHandoffHops &&
961
+ elapsedMs >= minAutoHandoffRunMs &&
962
+ res.signal !== 'SIGTERM' &&
963
+ res.signal !== 'SIGHUP';
964
+
965
+ if (canAttemptHandoff) {
966
+ let nextHop = null;
790
967
  try {
791
- child.kill('SIGHUP');
968
+ nextHop = await autoHandoffHook({
969
+ exitCode: res.exitCode,
970
+ signal: res.signal,
971
+ startedAt,
972
+ elapsedMs,
973
+ hop: hops,
974
+ family: options.family || null,
975
+ });
792
976
  } catch {
793
- // Ignore if already exited.
977
+ nextHop = null;
794
978
  }
795
- };
796
979
 
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;
980
+ if (nextHop?.resume && nextHop.prompt) {
981
+ hops += 1;
982
+ if (!options.quiet) {
983
+ stderr.write(
984
+ `agy-bar: "${nextHop.fromAlias}" hit ${nextHop.family || 'quota'} limit — switched -> "${nextHop.toAlias}" and resuming with handoff (${hops}/${maxAutoHandoffHops})...\n`,
985
+ );
986
+ }
987
+ currentArgs = buildHandoffResumeArgs(agyArgs, nextHop.prompt, {
988
+ target,
989
+ savedHandoffPath: nextHop.savedPath || handoffSavedPath,
990
+ platform,
991
+ });
992
+ continue;
816
993
  }
817
- reject(err);
818
- });
994
+ }
819
995
 
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
- });
996
+ return {
997
+ exitCode: res.exitCode,
998
+ signal: res.signal,
999
+ proxy: resolved,
1000
+ hops,
1001
+ };
1002
+ }
829
1003
  }
@@ -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
 
@@ -1,6 +1,8 @@
1
1
  import { realpathSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { computeSwapHint } from './account-quota.mjs';
5
+ import { readActiveAccountState } from './account-store.mjs';
4
6
  import { classifyAgentActivity, extractNativeCostUsd } from './agent-state.mjs';
5
7
  import { sanitizeText } from './ansi.mjs';
6
8
  import { loadConfig } from './config.mjs';
@@ -30,8 +32,12 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
30
32
  const payload = JSON.parse(raw);
31
33
  const now = Date.now();
32
34
  maybeCaptureRedactedPayload(payload);
35
+ const activeAccountState = readActiveAccountState();
33
36
  const syncedQuota = payload?.quota
34
- ? syncSharedQuota(payload.quota, { now, accountKey: extractAccountKey(payload) })
37
+ ? syncSharedQuota(payload.quota, {
38
+ now,
39
+ accountKey: extractAccountKey(payload, { fallbackAccountKey: activeAccountState?.activeQuotaKey ?? null }),
40
+ })
35
41
  : null;
36
42
  const effectivePayload = syncedQuota && syncedQuota !== payload.quota ? { ...payload, quota: syncedQuota } : payload;
37
43
  const prevSession = peekSessionState(effectivePayload);
@@ -81,9 +87,9 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
81
87
  // `settings.json.title` hook is not already driving this session's title, OR as a
82
88
  // one-shot push the moment a brand-new conversation's initial summary title lands.
83
89
  let tabSync = null;
90
+ const sessionIdForTitle = deriveSessionId(effectivePayload);
91
+ const nativeActive = !plain && config.tabTitle ? isNativeTitleActive(sessionIdForTitle, { now, hostPid: process.ppid }) : false;
84
92
  if (!plain && config.tabTitle) {
85
- const sessionIdForTitle = deriveSessionId(effectivePayload);
86
- const nativeActive = isNativeTitleActive(sessionIdForTitle, { now, hostPid: process.ppid });
87
93
  const newlyDiscoveredDbTitle = Boolean(!hasPayloadTitle && !prevSession?.conversationTitle && conversationTitle && !customTitle);
88
94
  if (!nativeActive || newlyDiscoveredDbTitle) {
89
95
  tabSync = syncTabTitle(payloadForTitle, {
@@ -101,9 +107,40 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
101
107
  }
102
108
 
103
109
  const stepTiming = config.dbTiming
104
- ? await readLatestStepTiming(effectivePayload, { prevDbStamp: prevSession?.dbStamp ?? null })
110
+ ? await readLatestStepTiming(effectivePayload, {
111
+ prevDbStamp: prevSession?.dbStamp ?? null,
112
+ prevWaitingForInput: Boolean(prevSession?.dbWaitingForInput),
113
+ })
105
114
  : null;
106
- const telemetry = recordTelemetry(effectivePayload, {
115
+
116
+ // During ask_question prompts, AGY keeps agent_state="working" while steps.status=9 in local DB.
117
+ // Promote waiting_for_input on the live payload and push a one-shot tab update on transitions.
118
+ const dbWaitingNow = Boolean(stepTiming?.waitingForInput);
119
+ const dbWaitingPrev = Boolean(prevSession?.dbWaitingForInput);
120
+ const livePayload =
121
+ dbWaitingNow && effectivePayload.waiting_for_input !== true
122
+ ? { ...effectivePayload, waiting_for_input: true }
123
+ : effectivePayload;
124
+
125
+ if (!plain && config.tabTitle && dbWaitingNow !== dbWaitingPrev) {
126
+ const liveTitlePayload =
127
+ conversationTitle && !hasPayloadTitle
128
+ ? { ...livePayload, conversation_title: conversationTitle }
129
+ : livePayload;
130
+ tabSync = syncTabTitle(liveTitlePayload, {
131
+ config,
132
+ git,
133
+ customTitle,
134
+ prevTabTitle: tabSync?.title || prevSession?.lastTabTitle || null,
135
+ prevTabHostPid: tabSync?.hostPid ?? prevSession?.lastTabHostPid ?? null,
136
+ prevTabTty: (tabSync?.tty && tabSync.tty !== 'custom' ? tabSync.tty : null) || prevSession?.lastTabTty || null,
137
+ hostPidHint: process.ppid,
138
+ force: nativeActive,
139
+ resolveOpts: { env },
140
+ });
141
+ }
142
+
143
+ const telemetry = recordTelemetry(livePayload, {
107
144
  now,
108
145
  git,
109
146
  stepTiming,
@@ -114,7 +151,7 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
114
151
  enableLedger: config.ledger,
115
152
  });
116
153
 
117
- const activity = classifyAgentActivity(effectivePayload);
154
+ const activity = classifyAgentActivity(livePayload);
118
155
  let usageSummary = null;
119
156
  if (
120
157
  config.show.todayTokens ||
@@ -134,7 +171,7 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
134
171
  });
135
172
  }
136
173
 
137
- const nativeCostUsd = extractNativeCostUsd(effectivePayload);
174
+ const nativeCostUsd = extractNativeCostUsd(livePayload);
138
175
  const effectiveSessionCostUsd = Math.max(telemetry.sessionCostUsd || 0, usageSummary?.sessionCostUsd || 0, nativeCostUsd || 0);
139
176
  const effectiveTelemetry =
140
177
  effectiveSessionCostUsd !== telemetry.sessionCostUsd
@@ -145,13 +182,23 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
145
182
  maybeTriggerBackgroundPricingSync({ enabled: true, now, env });
146
183
  }
147
184
 
148
- const rendered = renderStatusline(effectivePayload, {
185
+ const swapHint =
186
+ config.swapHint !== false && activeAccountState?.activeAccountId
187
+ ? computeSwapHint({
188
+ payload: livePayload,
189
+ activeAccountId: activeAccountState.activeAccountId,
190
+ now,
191
+ })
192
+ : null;
193
+
194
+ const rendered = renderStatusline(livePayload, {
149
195
  config,
150
196
  now,
151
197
  color,
152
198
  git,
153
199
  telemetry: effectiveTelemetry,
154
200
  usageSummary,
201
+ swapHint,
155
202
  env,
156
203
  themeOptions: { env },
157
204
  });