ai-battery 0.2.0 → 0.2.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.
Files changed (45) hide show
  1. package/README.md +30 -14
  2. package/bin/ai-battery-macos-status.applescript +5 -12
  3. package/bin/ai-battery-run +701 -31
  4. package/bin/ai-battery-tmux.js +17 -0
  5. package/bin/terminal-compositor.js +111 -0
  6. package/docs/REFERENCE.md +23 -3
  7. package/docs/RELEASING.md +24 -7
  8. package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
  9. package/docs/hud-preview.svg +43 -20
  10. package/docs/terminal-vertical-preview.svg +73 -0
  11. package/lib/cli.js +945 -219
  12. package/lib/core/atomic-rename.js +18 -0
  13. package/lib/core/cli-help.js +35 -7
  14. package/lib/core/cli-messages.js +45 -1
  15. package/lib/core/cli-output.js +277 -72
  16. package/lib/core/cli-wrappers.js +410 -0
  17. package/lib/core/config-editor.js +177 -29
  18. package/lib/core/display-config.js +45 -0
  19. package/lib/core/integration-files.js +32 -3
  20. package/lib/core/shared-bar.js +603 -0
  21. package/lib/core/statusline-git.js +179 -15
  22. package/lib/core/terminal.js +25 -7
  23. package/lib/core/tmux-status.js +172 -0
  24. package/lib/core/uninstall.js +20 -7
  25. package/lib/core/usage-store.js +85 -0
  26. package/lib/hud/launcher.js +29 -31
  27. package/lib/platforms/linux/hud.js +1 -1
  28. package/lib/platforms/linux/panel.js +1 -1
  29. package/lib/platforms/macos/hud.js +5 -5
  30. package/lib/platforms/process-scanner.js +77 -29
  31. package/lib/platforms/windows/autostart-cleanup.js +1 -1
  32. package/lib/platforms/windows/codex-runner.js +178 -21
  33. package/lib/platforms/windows/hud/controls.ps1 +44 -10
  34. package/lib/platforms/windows/hud/main.ps1 +350 -43
  35. package/lib/platforms/windows/hud/rendering.ps1 +1227 -1
  36. package/lib/platforms/windows/hud/snapshot.ps1 +26 -46
  37. package/lib/platforms/windows/hud-launcher.js +153 -79
  38. package/lib/platforms/windows/shared-bar-platform.js +972 -0
  39. package/lib/platforms/windows/terminal-compositor.js +210 -25
  40. package/lib/platforms/windows/wt-bar.js +729 -0
  41. package/lib/platforms/windows/wt-fragment.js +665 -0
  42. package/lib/platforms/windows/wt-keybinding.js +300 -0
  43. package/lib/providers/antigravity.js +155 -8
  44. package/package.json +5 -2
  45. package/vendor/PaneContext.cs +875 -0
package/lib/cli.js CHANGED
@@ -6,7 +6,7 @@ import windowsLauncher from "../bin/codex-wrapper-win.cjs";
6
6
  import https from "node:https";
7
7
  import os from "node:os";
8
8
  import path from "node:path";
9
- import { execFileSync, spawnSync } from "node:child_process";
9
+ import { execFileSync, spawn, spawnSync } from "node:child_process";
10
10
  import { createRequire } from "node:module";
11
11
  import { fileURLToPath, pathToFileURL } from "node:url";
12
12
  import { isDeepStrictEqual } from "node:util";
@@ -19,12 +19,20 @@ import { cleanupBatteryArtifacts, isBatteryConfig } from "./core/uninstall.js";
19
19
  import { createIntegrationFiles } from "./core/integration-files.js";
20
20
  import { cliError, cliText, helpText, invalidChoice, requiredValue } from "./core/cli-help.js";
21
21
  import { errorText, messageText as cliMessageText } from "./core/cli-messages.js";
22
- import { formatClaudeResult, formatDoctorResult, formatResetResult, formatSetupResult, formatVisibilityResult } from "./core/cli-output.js";
22
+ import { formatClaudeResult, formatDoctorResult, formatResetResult, formatSetupResult, formatSplitBarModeResult, formatSplitBarStatus, formatVisibilityResult } from "./core/cli-output.js";
23
23
  import { codexTerminalDisplay, claudeTerminalDisplay } from "./core/diagnostics.js";
24
- import { PROVIDERS, STATUS_LINE_ITEMS, normalizeOrder, parseOrder, orderResults, providerId, providerLabel } from "./core/display-config.js";
24
+ import { BAR_POSITIONS, DEFAULT_SIDEBAR_WIDTH, PROVIDERS, SPLIT_BAR_MODES, STATUS_LINE_ITEMS, defaultDisplayConfig, isDisplayConfig, normalizeBarPosition, normalizeOrder, normalizeSidebarWidth, normalizeSplitBarMode, parseOrder, orderResults, providerId, providerLabel } from "./core/display-config.js";
25
25
  import { canEditConfig, editDisplayConfig } from "./core/config-editor.js";
26
- import { branchChanges } from "./core/statusline-git.js";
26
+ import { installCliPositionWrappers, posixCliWrapperDir, uninstallCliPositionWrappers } from "./core/cli-wrappers.js";
27
+ import { branchChanges, readGitBranchFast } from "./core/statusline-git.js";
27
28
  import { createAntigravityIntegration } from "./providers/antigravity.js";
29
+ import { cleanupPaneAiSession, createCrossOsSessionAlive, diagnosePaneContextHelper, isPaneSharedBarActive, isWslWtContext, paneUsageDecision, preparePaneContextHelper, readConfiguredBarPosition, readConfiguredSplitBarPosition, resolveSplitBarMode } from "./platforms/windows/shared-bar-platform.js";
30
+ import { listActiveAiSessions, sharedBarLeasePath, validBarContext } from "./core/shared-bar.js";
31
+ import { installWtFragment, removeWtFragment, diagnoseWtFragment, updateWtFragmentPosition } from "./platforms/windows/wt-fragment.js";
32
+ import { runSharedBar } from "./platforms/windows/wt-bar.js";
33
+ import { tmuxSocket } from "./core/tmux-status.js";
34
+ import { publishNewest, withFileLock } from "./core/usage-store.js";
35
+ import { atomicRename } from "./core/atomic-rename.js";
28
36
  import {
29
37
  cacheAgeSeconds,
30
38
  clamp,
@@ -59,14 +67,14 @@ const DEFAULT_TAIL_BYTES = 4 * 1024 * 1024;
59
67
  const DEFAULT_MAX_FILES = 40;
60
68
  const CLAUDE_LIMIT_HIT_TAIL_BYTES = 256 * 1024;
61
69
  const CLAUDE_LIMIT_HIT_MAX_FILES = 80;
62
- const CLAUDE_CODEX_CACHE_SECONDS = 60;
63
- const CLAUDE_CODEX_FALLBACK_CACHE_SECONDS = 15;
64
70
  const BACKGROUND_USAGE_RUNNING_SECONDS = 5 * 60;
65
71
  const DIVIDER = "│";
66
72
  const PROVIDER_DIVIDER = "┃";
67
73
  const DEFAULT_STATUSLINE_COLUMN_GUARD = 4;
68
74
  const COMMANDS = new Set([
69
75
  "setup",
76
+ "split",
77
+ "bar",
70
78
  "reset",
71
79
  "teardown",
72
80
  "uninstall",
@@ -80,7 +88,12 @@ const COMMANDS = new Set([
80
88
  "install-claude-statusline",
81
89
  "uninstall-claude-statusline"
82
90
  ]);
83
- const TEARDOWN_TARGETS = [...PROVIDERS, "hud", "tmux"];
91
+ const SPLIT_SUBCOMMANDS = ["status", "on", "auto", "manual", "off", "bottom", "top", "left", "right", "position"];
92
+ const TEARDOWN_TARGETS = [...PROVIDERS, "hud", "tmux", "split"];
93
+
94
+ function normalizeTarget(value) {
95
+ return providerId(value);
96
+ }
84
97
  const CODEX_WRAPPER_MARKER = "AI_BATTERY_MANAGED_CODEX_WRAPPER";
85
98
  const CODEX_WRAPPER_BRIDGE_MARKER = "AI_BATTERY_MANAGED_CODEX_BRIDGE";
86
99
  const CODEX_PATH_LOOKUP_MARKER = "AI_BATTERY_CODEX_PATH_LOOKUP=1";
@@ -123,12 +136,21 @@ function parseArgs(argv) {
123
136
  wrapCodex: true,
124
137
  configureCodexStatusLine: true,
125
138
  providerOrder: null,
139
+ barPosition: null,
126
140
  attachHud: false,
141
+ refreshProcesses: false,
142
+ paneDecisionProvider: null,
143
+ paneCleanupProvider: null,
144
+ sharedBarState: null,
145
+ ownerPid: 0,
146
+ paneCols: 0,
147
+ paneRows: 0,
127
148
  header: true,
128
149
  usageRow: "auto",
129
150
  help: argv.length === 0,
130
151
  helpTopic: "",
131
152
  version: false,
153
+ subcommand: "",
132
154
  targets: [],
133
155
  rest: []
134
156
  };
@@ -148,6 +170,16 @@ function parseArgs(argv) {
148
170
  } else if (args.command === "reset" && !resetAliasSeen && !args.targets.length && ["settings", "config"].includes(arg)) {
149
171
  // Keep the previous reset settings/config syntax for existing scripts.
150
172
  resetAliasSeen = true;
173
+ } else if (!arg.startsWith("-") && args.command === "split") {
174
+ if (args.subcommand === "position" && !args.barPosition) {
175
+ const nextPos = normalizeBarPosition(arg, null);
176
+ if (!nextPos) throw invalidChoice("position", BAR_POSITIONS.join(", "), "split");
177
+ args.barPosition = nextPos;
178
+ } else if (args.subcommand) {
179
+ throw cliError(`Unexpected argument: ${arg}.`, `불필요한 인자: ${arg}.`, "split");
180
+ } else {
181
+ args.subcommand = arg;
182
+ }
151
183
  } else if (!arg.startsWith("-") && ["setup", "reset", "teardown", "uninstall", "on", "off"].includes(args.command)) {
152
184
  args.targets.push(arg);
153
185
  } else if (arg === "--provider" || arg === "-p") {
@@ -183,8 +215,37 @@ function parseArgs(argv) {
183
215
  try { args.providerOrder = parseOrder(value, PROVIDERS, "--provider-order"); }
184
216
  catch { throw cliError("--provider-order requires unique comma-separated tools: codex, claude, gemini.", "--provider-order에 codex, claude, gemini를 쉼표로 구분하고 중복 없이 입력하세요.", args.command); }
185
217
  i += 1;
218
+ } else if (arg === "--position") {
219
+ const value = requiredValue(argv, i, args.command);
220
+ const nextPos = normalizeBarPosition(value, null);
221
+ if (!nextPos) throw invalidChoice("--position", BAR_POSITIONS.join(", "), args.command);
222
+ args.barPosition = nextPos;
223
+ i += 1;
224
+ } else if (arg === "--interval") {
225
+ args.interval = Math.max(1, Number(requiredValue(argv, i, args.command)) || 2);
226
+ i += 1;
186
227
  } else if (arg === "--attach-hud") {
187
228
  args.attachHud = true;
229
+ } else if (arg === "--refresh-processes") {
230
+ args.refreshProcesses = true;
231
+ } else if (arg === "--pane-decision") {
232
+ args.paneDecisionProvider = requiredValue(argv, i, args.command);
233
+ i += 1;
234
+ } else if (arg === "--pane-cleanup") {
235
+ args.paneCleanupProvider = requiredValue(argv, i, args.command);
236
+ i += 1;
237
+ } else if (arg === "--shared-bar-state") {
238
+ args.sharedBarState = requiredValue(argv, i, args.command);
239
+ i += 1;
240
+ } else if (arg === "--owner-pid") {
241
+ args.ownerPid = Math.max(0, Math.trunc(Number(requiredValue(argv, i, args.command)) || 0));
242
+ i += 1;
243
+ } else if (arg === "--cols") {
244
+ args.paneCols = Math.max(0, Math.trunc(Number(requiredValue(argv, i, args.command)) || 0));
245
+ i += 1;
246
+ } else if (arg === "--rows") {
247
+ args.paneRows = Math.max(0, Math.trunc(Number(requiredValue(argv, i, args.command)) || 0));
248
+ i += 1;
188
249
  } else if (arg === "--watch" || arg === "-w") {
189
250
  args.watch = true;
190
251
  const maybeInterval = argv[i + 1];
@@ -238,7 +299,7 @@ function parseArgs(argv) {
238
299
  args.helpTopic = commandSeen ? args.command : "";
239
300
  args.provider = providerId(args.provider);
240
301
  args.activeProvider = providerId(args.activeProvider);
241
- args.targets = args.targets.map(providerId);
302
+ args.targets = args.targets.map(normalizeTarget);
242
303
  if (!["all", ...PROVIDERS].includes(args.provider)) {
243
304
  throw invalidChoice("--provider", "all, codex, claude, gemini", args.helpTopic);
244
305
  }
@@ -246,11 +307,24 @@ function parseArgs(argv) {
246
307
  throw invalidChoice("--active-provider", "codex, claude, gemini", args.helpTopic);
247
308
  }
248
309
  if (args.providerOrder && !["config", "setup"].includes(args.command)) throw cliError("--provider-order requires config or setup.", "--provider-order는 config 또는 setup에서 사용하세요.", args.helpTopic);
310
+ if (args.barPosition && !["config", "setup", "split"].includes(args.command)) throw cliError("--position requires config, setup, or split.", "--position은 config, setup 또는 split에서 사용하세요.", args.helpTopic);
311
+ if (args.command === "split") {
312
+ if (args.subcommand && !SPLIT_SUBCOMMANDS.includes(args.subcommand)) {
313
+ throw invalidChoice("subcommand", SPLIT_SUBCOMMANDS.join(", "), "split");
314
+ }
315
+ if (args.subcommand === "position" && !args.barPosition) {
316
+ throw invalidChoice("position", BAR_POSITIONS.join(", "), "split");
317
+ }
318
+ }
249
319
  if (args.targets.length) {
250
- const choices = args.command === "setup" ? [...PROVIDERS, "tmux", "all"]
320
+ const choices = args.command === "setup" ? [...PROVIDERS, "tmux", "split", "all"]
251
321
  : ["on", "off"].includes(args.command) ? [...PROVIDERS, "all"] : [...TEARDOWN_TARGETS, "all"];
252
322
  if (args.targets.some((target) => !choices.includes(target))) {
253
- throw invalidChoice("target", choices.map(target => target === "antigravity" ? "gemini" : target).join(", "), args.command);
323
+ throw invalidChoice(
324
+ "target",
325
+ choices.map(target => (target === "antigravity" ? "gemini" : target)).join(", "),
326
+ args.command
327
+ );
254
328
  }
255
329
  }
256
330
 
@@ -306,6 +380,12 @@ function legacyStateDir() {
306
380
  return homePath(".local", "state", "claudex-battery");
307
381
  }
308
382
 
383
+ function hasCustomXdgStateHome() {
384
+ const xdg = String(process.env.XDG_STATE_HOME || "").trim();
385
+ if (!xdg) return false;
386
+ return path.resolve(xdg) !== path.resolve(userHome(), ".local", "state");
387
+ }
388
+
309
389
  let windowsStateDirForWslMemo;
310
390
  function windowsStateDirForWsl() {
311
391
  // Account usage is shared between native Windows and WSL without sharing the
@@ -315,7 +395,7 @@ function windowsStateDirForWsl() {
315
395
  if (override) return override;
316
396
  // An explicit state directory is an isolation boundary for tests, portable
317
397
  // installs, and users who do not want state written to the Windows profile.
318
- if (process.env.AI_BATTERY_STATE_DIR || process.env.CLAUDEX_BATTERY_STATE_DIR) return null;
398
+ if (process.env.AI_BATTERY_STATE_DIR || process.env.CLAUDEX_BATTERY_STATE_DIR || hasCustomXdgStateHome()) return null;
319
399
  if (windowsStateDirForWslMemo !== undefined) return windowsStateDirForWslMemo;
320
400
 
321
401
  // Cache the resolved path: the statusline can run every second (refreshInterval)
@@ -331,7 +411,8 @@ function windowsStateDirForWsl() {
331
411
 
332
412
  let resolved = null;
333
413
  try {
334
- const home = spawnSync("cmd.exe", ["/c", "echo %USERPROFILE%"], { encoding: "utf8", timeout: 2000 });
414
+ const cmdExe = fs.existsSync("/mnt/c/Windows/System32/cmd.exe") ? "/mnt/c/Windows/System32/cmd.exe" : "cmd.exe";
415
+ const home = spawnSync(cmdExe, ["/c", "echo %USERPROFILE%"], { encoding: "utf8", timeout: 2000 });
335
416
  const winHome = String(home.stdout || "").trim();
336
417
  if (home.status === 0 && /^[A-Za-z]:\\/.test(winHome)) {
337
418
  const conv = spawnSync("wslpath", ["-u", winHome], { encoding: "utf8", timeout: 2000 });
@@ -356,14 +437,22 @@ function windowsStateDirForWsl() {
356
437
  return resolved;
357
438
  }
358
439
 
359
- function claudeStateDir() {
440
+ function sharedStateDir() {
441
+ const override = String(process.env.AI_BATTERY_SHARED_USAGE_STATE_DIR || "").trim();
442
+ if (override) return override;
360
443
  return windowsStateDirForWsl() || stateDir();
361
444
  }
362
445
 
446
+ function claudeStateDir() {
447
+ return sharedStateDir();
448
+ }
449
+
363
450
  function codexUsageStateDir() {
364
- const override = String(process.env.AI_BATTERY_SHARED_USAGE_STATE_DIR || "").trim();
365
- if (override) return override;
366
- return windowsStateDirForWsl() || stateDir();
451
+ return sharedStateDir();
452
+ }
453
+
454
+ function displayConfigPath() {
455
+ return path.join(sharedStateDir(), "display-config.json");
367
456
  }
368
457
 
369
458
  function claudeCachePath() {
@@ -433,19 +522,149 @@ function writeConfig(config) {
433
522
  writeJsonAtomic(configPath(), config);
434
523
  }
435
524
 
525
+ function normalizeDisplayConfig(stored) {
526
+ const defaults = defaultDisplayConfig();
527
+ return {
528
+ version: 1,
529
+ providers: Object.fromEntries(PROVIDERS.map(provider => [provider, stored?.providers?.[provider] !== false])),
530
+ providerOrder: normalizeOrder(stored?.providerOrder, defaults.providerOrder),
531
+ splitBar: normalizeSplitBarMode(stored?.splitBar, defaults.splitBar),
532
+ barPosition: normalizeBarPosition(stored?.barPosition, defaults.barPosition),
533
+ splitBarPosition: stored?.splitBarPosition ? normalizeBarPosition(stored.splitBarPosition, null) : null,
534
+ sidebarWidth: normalizeSidebarWidth(stored?.sidebarWidth, defaults.sidebarWidth)
535
+ };
536
+ }
537
+
538
+ function readDisplayConfig(options = {}) {
539
+ const target = displayConfigPath();
540
+ if (fs.existsSync(target)) {
541
+ const parsed = readJson(target);
542
+ if (options.strict) {
543
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
544
+ throw new Error(`AI Battery display config is invalid and was left untouched: ${target}`);
545
+ }
546
+ if (!isDisplayConfig(parsed)) {
547
+ throw new Error(`AI Battery display config ownership could not be verified; file was left untouched: ${target}`);
548
+ }
549
+ if (parsed.providers !== undefined
550
+ && (!parsed.providers || typeof parsed.providers !== "object" || Array.isArray(parsed.providers))) {
551
+ throw new Error(`AI Battery display config providers must be a JSON object: ${target}`);
552
+ }
553
+ if (parsed.providerOrder !== undefined && !Array.isArray(parsed.providerOrder)) {
554
+ throw new Error(`AI Battery display config providerOrder must be a JSON array: ${target}`);
555
+ }
556
+ if (parsed.splitBar !== undefined && !SPLIT_BAR_MODES.includes(parsed.splitBar)) {
557
+ throw new Error(`AI Battery display config splitBar must be one of auto, manual, off: ${target}`);
558
+ }
559
+ }
560
+ if (isDisplayConfig(parsed)) return normalizeDisplayConfig(parsed);
561
+ return defaultDisplayConfig();
562
+ }
563
+
564
+ const localPath = configPath();
565
+ const sharedLocalPath = path.join(sharedStateDir(), "config.json");
566
+ if (!samePath(sharedLocalPath, localPath) && fs.existsSync(sharedLocalPath)) {
567
+ const sharedConfig = readJson(sharedLocalPath);
568
+ if (isBatteryConfig(sharedConfig)) return normalizeDisplayConfig(sharedConfig);
569
+ }
570
+ if (fs.existsSync(localPath)) {
571
+ return normalizeDisplayConfig(readConfig({ strict: Boolean(options.strict) }));
572
+ }
573
+ return defaultDisplayConfig();
574
+ }
575
+
576
+ function updateDisplayConfig({ providerOrder, providers, splitBar, barPosition, splitBarPosition, sidebarWidth } = {}) {
577
+ // Always validate local config ownership/syntax before mutating display config.
578
+ readConfig({ strict: true });
579
+ const target = displayConfigPath();
580
+ const merged = withFileLock(`${target}.lock`, () => {
581
+ const latest = readDisplayConfig({ strict: true });
582
+ const next = {
583
+ version: 1,
584
+ providers: {
585
+ ...latest.providers,
586
+ ...(providers && typeof providers === "object" ? providers : {})
587
+ },
588
+ providerOrder: providerOrder !== undefined
589
+ ? normalizeOrder(providerOrder, PROVIDERS)
590
+ : latest.providerOrder,
591
+ splitBar: splitBar !== undefined
592
+ ? normalizeSplitBarMode(splitBar, latest.splitBar)
593
+ : latest.splitBar,
594
+ barPosition: barPosition !== undefined
595
+ ? normalizeBarPosition(barPosition, latest.barPosition)
596
+ : latest.barPosition,
597
+ splitBarPosition: splitBarPosition !== undefined
598
+ ? (splitBarPosition === null ? null : normalizeBarPosition(splitBarPosition, latest.splitBarPosition || latest.barPosition))
599
+ : latest.splitBarPosition,
600
+ sidebarWidth: sidebarWidth !== undefined
601
+ ? normalizeSidebarWidth(sidebarWidth, latest.sidebarWidth)
602
+ : latest.sidebarWidth
603
+ };
604
+ writeJsonAtomic(target, next);
605
+ return next;
606
+ }, { timeoutMs: 3000 });
607
+
608
+ // Mirror only display fields into an existing local config.json so local
609
+ // recovery metadata and extra fields remain intact and compatible with tools/tests.
610
+ const localPath = configPath();
611
+ if (fs.existsSync(localPath)) {
612
+ withFileLock(`${localPath}.lock`, () => {
613
+ if (!fs.existsSync(localPath)) return;
614
+ const local = readConfig({ strict: true });
615
+ local.providerOrder = merged.providerOrder;
616
+ local.providers = { ...local.providers, ...merged.providers };
617
+ if (splitBar !== undefined || local.splitBar !== undefined) {
618
+ local.splitBar = merged.splitBar;
619
+ }
620
+ if (barPosition !== undefined || local.barPosition !== undefined) {
621
+ local.barPosition = merged.barPosition;
622
+ }
623
+ if (splitBarPosition !== undefined || local.splitBarPosition !== undefined) {
624
+ local.splitBarPosition = merged.splitBarPosition;
625
+ }
626
+ if (sidebarWidth !== undefined || local.sidebarWidth !== undefined) {
627
+ local.sidebarWidth = merged.sidebarWidth;
628
+ }
629
+ writeConfig(local);
630
+ }, { timeoutMs: 3000 });
631
+ }
632
+ return merged;
633
+ }
634
+
436
635
  const { installManagedText, removeManagedText, stripOwnedBlock } = createIntegrationFiles({ readConfig, writeConfig, writeTextAtomic });
437
636
 
438
637
  function providerVisible(provider) {
439
- const config = readConfig();
638
+ const config = readDisplayConfig();
440
639
  return config.providers?.[provider] !== false;
441
640
  }
442
641
 
443
642
  function configuredProviderOrder() {
444
- return normalizeOrder(readConfig().providerOrder, PROVIDERS);
643
+ return normalizeOrder(readDisplayConfig().providerOrder, PROVIDERS);
644
+ }
645
+
646
+ function diagnoseSharedBar() {
647
+ const fragment = diagnoseWtFragment();
648
+ const helper = diagnosePaneContextHelper();
649
+ const splitBar = resolveSplitBarMode(process.env, { configuredMode: readDisplayConfig().splitBar });
650
+ const backendOverride = String(process.env.AI_BATTERY_SPLIT_BACKEND || "").trim().toLowerCase();
651
+ const usesWtPane = backendOverride !== "in-terminal";
652
+ return {
653
+ ...fragment,
654
+ backend: usesWtPane ? "wt-pane" : "in-terminal",
655
+ mode: splitBar.mode,
656
+ configuredMode: splitBar.configuredMode,
657
+ ...(splitBar.envOverride ? { envOverride: splitBar.envOverride } : {}),
658
+ triggerConfigured: Boolean(fragment.autoAttach),
659
+ helperReady: helper.ready,
660
+ helperPath: helper.path,
661
+ helperError: helper.ready ? null : helper.reason,
662
+ autoAttach: Boolean(splitBar.mode === "auto" && helper.ready && (!usesWtPane || fragment.autoAttach))
663
+ };
445
664
  }
446
665
 
447
666
  function antigravityAvailable() {
448
- return fs.existsSync(antigravity.cachePath()) || fs.existsSync(antigravity.settingsPath());
667
+ return antigravity.available();
449
668
  }
450
669
 
451
670
  function providerTargets(targets) {
@@ -457,14 +676,14 @@ function providerTargets(targets) {
457
676
  } else if (PROVIDERS.includes(target)) {
458
677
  providers.add(target);
459
678
  } else {
460
- throw new Error("target must be one of: codex, claude, all");
679
+ throw new Error("target must be one of: codex, claude, gemini, all");
461
680
  }
462
681
  }
463
682
  return [...providers];
464
683
  }
465
684
 
466
685
  function teardownTargets(targets) {
467
- const requested = targets.length ? targets : ["all"];
686
+ const requested = targets.length ? targets.map(normalizeTarget) : ["all"];
468
687
  const selected = new Set();
469
688
  for (const target of requested) {
470
689
  if (target === "all") {
@@ -472,7 +691,7 @@ function teardownTargets(targets) {
472
691
  } else if (TEARDOWN_TARGETS.includes(target)) {
473
692
  selected.add(target);
474
693
  } else {
475
- throw new Error("target must be one of: codex, claude, hud, tmux, all");
694
+ throw new Error("target must be one of: codex, claude, gemini, hud, tmux, split-bar, all");
476
695
  }
477
696
  }
478
697
  return [...selected];
@@ -480,13 +699,11 @@ function teardownTargets(targets) {
480
699
 
481
700
  function setProviderVisibility(targets, visible) {
482
701
  const providers = providerTargets(targets);
483
- const config = readConfig({ strict: true });
484
- for (const provider of providers) {
485
- config.providers[provider] = visible;
486
- }
487
- writeConfig(config);
702
+ const patch = Object.fromEntries(providers.map(provider => [provider, visible]));
703
+ updateDisplayConfig({ providers: patch });
488
704
  return {
489
705
  configPath: configPath(),
706
+ displayConfigPath: displayConfigPath(),
490
707
  providers,
491
708
  visible
492
709
  };
@@ -923,20 +1140,80 @@ function shellRcPath() {
923
1140
 
924
1141
  function shellPathBlock(shimDir) {
925
1142
  const shell = path.basename(process.env.SHELL || "");
1143
+ const cliDir = posixCliWrapperDir(userHome());
1144
+ const dirs = samePath(cliDir, shimDir) ? [shimDir] : [cliDir, shimDir];
926
1145
  if (shell === "fish") {
927
- return `\n# >>> ai-battery setup >>>\nfish_add_path -p ${shQuote(shimDir)}\n# <<< ai-battery setup <<<\n`;
1146
+ // fish_add_path -p prepends each call, so reverse order keeps cliDir first.
1147
+ return `\n# >>> ai-battery setup >>>\n${[...dirs].reverse().map(dir => `fish_add_path -p ${shQuote(dir)}`).join("\n")}\n# <<< ai-battery setup <<<\n`;
1148
+ }
1149
+ return `\n# >>> ai-battery setup >>>\nexport PATH=${dirs.map(shQuote).join(":")}` + ':"$PATH"\n# <<< ai-battery setup <<<\n';
1150
+ }
1151
+
1152
+ function updatePosixShellPathFile(rcPath, shimDir) {
1153
+ fs.mkdirSync(path.dirname(rcPath), { recursive: true });
1154
+ const existing = fs.existsSync(rcPath) ? fs.readFileSync(rcPath, "utf8") : "";
1155
+ const withoutAiBatteryBlock = stripOwnedBlock(rcPath, existing, removeAiBatteryShellPathBlock);
1156
+ const separator = withoutAiBatteryBlock && !withoutAiBatteryBlock.endsWith("\n") ? "\n" : "";
1157
+ const next = `${withoutAiBatteryBlock}${separator}${shellPathBlock(shimDir)}`;
1158
+ const changed = next !== existing;
1159
+ if (changed) installManagedText(rcPath, next, next.slice(withoutAiBatteryBlock.length));
1160
+ return { changed, existing, withoutAiBatteryBlock };
1161
+ }
1162
+
1163
+ function ensureCliPositionWrappers(targets = ["claude", "antigravity"], { updateShellPath = false } = {}) {
1164
+ const names = [];
1165
+ if (targets.includes("claude")) names.push("claude");
1166
+ if (targets.includes("antigravity")) names.push("agy");
1167
+ if (!names.length || !codexRunnerExists()) return null;
1168
+ const winShimDir = process.platform === "win32" ? defaultCodexShimDir() : null;
1169
+ const result = installCliPositionWrappers({
1170
+ names,
1171
+ runnerPath: codexRunnerPath(),
1172
+ homeDir: userHome(),
1173
+ platform: process.platform,
1174
+ nodePath: process.execPath,
1175
+ windowsDir: winShimDir,
1176
+ env: process.env
1177
+ });
1178
+ if (updateShellPath && process.platform === "win32" && winShimDir) {
1179
+ try {
1180
+ ensureWindowsShimPath(winShimDir, path.join(homePath(".local", "bin"), "claude.exe"));
1181
+ } catch { /* Best-effort Windows PATH update. */ }
1182
+ } else if (updateShellPath && process.platform !== "win32") {
1183
+ let existingCodexDir = null;
1184
+ try {
1185
+ const configuredWrapper = readConfig().codexWrapper?.wrapperPath;
1186
+ if (configuredWrapper) existingCodexDir = path.dirname(configuredWrapper);
1187
+ } catch {}
1188
+ const shimDir = existingCodexDir || homePath(".local", "bin");
1189
+ const rcTargets = [shellRcPath()];
1190
+ const profilePath = homePath(".profile");
1191
+ if (!process.env.AI_BATTERY_RC && path.basename(process.env.SHELL || "") === "bash" && fs.existsSync(profilePath) && !samePath(rcTargets[0], profilePath)) {
1192
+ rcTargets.push(profilePath);
1193
+ }
1194
+ for (const rcPath of rcTargets) {
1195
+ try {
1196
+ updatePosixShellPathFile(rcPath, shimDir);
1197
+ } catch { /* Best-effort PATH update. */ }
1198
+ }
928
1199
  }
929
- return `\n# >>> ai-battery setup >>>\nexport PATH=${shQuote(shimDir)}:"$PATH"\n# <<< ai-battery setup <<<\n`;
1200
+ return result;
930
1201
  }
931
1202
 
932
1203
  function tmuxStatusBarActive() {
933
1204
  const override = String(process.env.AI_BATTERY_TMUX || process.env.CLAUDEX_BATTERY_TMUX || "").toLowerCase();
934
1205
  if (override === "row") return false;
935
1206
  if (["status", "plain", "off"].includes(override)) return true;
936
- // AI_BATTERY_TMUX_STATUS=1 is set by "ai-battery setup tmux" via tmux set-environment -g.
937
- // Trust it even when TMUX socket path isn't propagated to Claude Code's statusline subprocess.
938
- if ((process.env.AI_BATTERY_TMUX_STATUS || process.env.CLAUDEX_BATTERY_TMUX_STATUS) === "1") return true;
939
- return false;
1207
+ if (process.env.TMUX) {
1208
+ const target = process.env.TMUX_PANE ? ["-t", process.env.TMUX_PANE] : [];
1209
+ const result = spawnSync("tmux", ["display-message", "-p", ...target, "#{AI_BATTERY_TMUX_STATUS}\t#{status}\t#{?@ai_battery_tmux_saved,1,0}\t#{?@ai_battery_tmux_paused,1,0}"], { encoding: "utf8", timeout: 1000 });
1210
+ if (result.status === 0) {
1211
+ const [enabled, height, managed, paused] = result.stdout.trim().split("\t");
1212
+ return enabled === "1" && paused !== "1" && height !== "off" && (height !== "5" || managed === "1");
1213
+ }
1214
+ }
1215
+ // Hooks may retain the integration flag while omitting the TMUX socket.
1216
+ return (process.env.AI_BATTERY_TMUX_STATUS || process.env.CLAUDEX_BATTERY_TMUX_STATUS) === "1";
940
1217
  }
941
1218
 
942
1219
  function booleanEnvValue(value) {
@@ -951,12 +1228,18 @@ function claudeUsageRowVisible(args) {
951
1228
  if (args.usageRow === true || args.usageRow === false) return args.usageRow;
952
1229
  const envValue = booleanEnvValue(process.env.AI_BATTERY_CLAUDE_USAGE_ROW ?? process.env.CLAUDEX_BATTERY_CLAUDE_USAGE_ROW);
953
1230
  if (envValue !== null) return envValue;
954
- if (process.platform === "win32") return false;
1231
+ if (process.platform === "win32" && args.attachHud) return false;
955
1232
  return !tmuxStatusBarActive();
956
1233
  }
957
1234
 
958
1235
  function tmuxConfPath() {
959
- return process.env.AI_BATTERY_TMUX_CONF || homePath(".tmux.conf");
1236
+ if (process.env.AI_BATTERY_TMUX_CONF) return process.env.AI_BATTERY_TMUX_CONF;
1237
+ const legacy = homePath(".tmux.conf");
1238
+ if (fs.existsSync(legacy)) return legacy;
1239
+ const xdgBase = process.env.XDG_CONFIG_HOME || homePath(".config");
1240
+ const xdg = path.join(xdgBase, "tmux", "tmux.conf");
1241
+ if (fs.existsSync(xdg)) return xdg;
1242
+ return legacy;
960
1243
  }
961
1244
 
962
1245
  function removeAiBatteryTmuxBlock(text) {
@@ -976,26 +1259,12 @@ function extractExistingStatusRight(confText) {
976
1259
  return last;
977
1260
  }
978
1261
 
979
- function tmuxStatusBlock(existingStatusRight = null) {
980
- // #{client_width} is expanded by tmux before running the shell command,
981
- // giving the responsive layout the actual terminal width to work with.
982
- const battery = `${shQuote(process.execPath)} ${shQuote(path.join(scriptDir(), "ai-battery.js"))} --tmux --bar-width 8 --max-width #{client_width}`;
983
- const batteryPart = `#(${battery})`;
984
- // Put the battery on the far right so tmux left-clips the existing text before
985
- // the bar. When the block is uninstalled, the earlier set -g status-right wins.
986
- const statusRightValue = existingStatusRight
987
- ? `${existingStatusRight} ${batteryPart} `
988
- : `${batteryPart} `;
989
- const rightLength = 200;
1262
+ function tmuxStatusBlock(confPath = tmuxConfPath()) {
1263
+ const command = `${shQuote(process.execPath)} ${shQuote(path.join(scriptDir(), "ai-battery-tmux.js"))} start --socket #{q:socket_path} --config ${shQuote(confPath)}`;
990
1264
  return [
991
1265
  "\n# >>> ai-battery tmux >>>",
992
- "# AI Battery once per session in the tmux status bar; runners inside tmux",
993
- "# see AI_BATTERY_TMUX_STATUS and skip their per-pane bottom row.",
994
- "set-environment -g AI_BATTERY_TMUX_STATUS 1",
995
- "set -g status on",
996
- "set -g status-interval 10",
997
- `set-option -g status-right-length ${rightLength}`,
998
- `set -g status-right "${statusRightValue.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`,
1266
+ "# Keep the existing status row; append usage only while an AI runs in this session.",
1267
+ `run-shell -b "${command.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`,
999
1268
  "# <<< ai-battery tmux <<<",
1000
1269
  ""
1001
1270
  ].join("\n");
@@ -1011,19 +1280,24 @@ function installTmuxStatus({ confPath = tmuxConfPath() } = {}) {
1011
1280
  } catch (error) { if (error.code !== "ENOENT") throw error; }
1012
1281
  const withoutBlock = stripOwnedBlock(confPath, existing, removeAiBatteryTmuxBlock);
1013
1282
  const existingStatusRight = extractExistingStatusRight(withoutBlock);
1014
- const next = `${withoutBlock}${tmuxStatusBlock(existingStatusRight)}`;
1283
+ const next = `${withoutBlock}${tmuxStatusBlock(confPath)}`;
1015
1284
  if (next !== existing) installManagedText(confPath, next, next.slice(withoutBlock.length));
1016
1285
  let active = false;
1017
1286
  let error = null;
1018
- if (process.env.TMUX && !process.env.AI_BATTERY_TMUX_CONF) {
1019
- const commands = [
1020
- "set-environment", "-g", "AI_BATTERY_TMUX_STATUS", "1", ";",
1021
- "set-option", "-g", "status", "on", ";",
1022
- "set-option", "-g", "status-interval", "10", ";",
1023
- "set-option", "-g", "status-right-length", "200", ";",
1024
- "set-option", "-g", "status-right", `${existingStatusRight ? `${existingStatusRight} ` : ""}#(${shQuote(process.execPath)} ${shQuote(path.join(scriptDir(), "ai-battery.js"))} --tmux --bar-width 8 --max-width #{client_width}) `
1025
- ];
1026
- const result = spawnSync("tmux", commands, { encoding: "utf8", timeout: 4000 });
1287
+ const socket = !process.env.AI_BATTERY_TMUX_CONF ? tmuxSocket() : null;
1288
+ if (socket) {
1289
+ // Migrate only the old options we still recognize as our status-right block.
1290
+ const right = spawnSync("tmux", ["-S", socket, "show-options", "-gv", "status-right"], { encoding: "utf8", timeout: 1500 });
1291
+ if (right.stdout?.includes("ai-battery.js") && right.stdout.includes("--tmux")) {
1292
+ for (const option of ["status-right", "status-right-length", "status-interval", "status"]) {
1293
+ const pattern = new RegExp("^[ \\t]*set(?:-option)?(?:[ \\t]+-(?!t\\b|u\\b|w\\b|a\\b)\\w+)*[ \\t]+" + option + "[ \\t]+(?:\"((?:[^\"\\\\]|\\\\.)*)\"|'((?:[^'\\\\]|\\\\.)*)'|([^#\\r\\n]+?))(?:[ \\t]+#.*)?$", "gm");
1294
+ const match = [...withoutBlock.matchAll(pattern)].at(-1);
1295
+ const rawValue = match ? (match[1] ?? match[2] ?? match[3]?.trim()) : null;
1296
+ const value = option === "status-right" ? existingStatusRight : rawValue;
1297
+ spawnSync("tmux", ["-S", socket, "set-option", value == null ? "-gu" : "-g", option, ...(value == null ? [] : [value])], { timeout: 1500 });
1298
+ }
1299
+ }
1300
+ const result = spawnSync(process.execPath, [path.join(scriptDir(), "ai-battery-tmux.js"), "start", "--socket", socket, "--config", confPath], { encoding: "utf8", timeout: 8000 });
1027
1301
  active = !result.error && result.status === 0;
1028
1302
  if (!active) error = result.error?.message || result.stderr?.trim() || "Could not apply the tmux status bar";
1029
1303
  }
@@ -1043,6 +1317,8 @@ function uninstallTmuxStatus() {
1043
1317
  const confPath = tmuxConfPath();
1044
1318
  const records = readConfig({ strict: true }).integrationFiles || {};
1045
1319
  const paths = uniquePaths([confPath, ...Object.keys(records).filter(file => records[file]?.block?.includes("# >>> ai-battery tmux >>>"))]);
1320
+ const socket = tmuxSocket();
1321
+ if (socket) for (const file of paths) spawnSync(process.execPath, [path.join(scriptDir(), "ai-battery-tmux.js"), "stop", "--socket", socket, "--config", file], { timeout: 5000 });
1046
1322
  const changedPaths = paths.filter(file => removeManagedText(file, removeAiBatteryTmuxBlock));
1047
1323
  return { changed: changedPaths.length > 0, confPath, changedPaths };
1048
1324
  }
@@ -1667,12 +1943,15 @@ function removeManagedCodexBridge(wrapperPath) {
1667
1943
  return null;
1668
1944
  }
1669
1945
 
1670
- function uninstallCodexWrapper() {
1946
+ function uninstallCodexWrapper({ extraWindowsOwnedShimDirs = [] } = {}) {
1671
1947
  const config = readConfig({ strict: true });
1672
1948
  const statusLine = restoreCodexStatusLine(config);
1673
1949
  if (statusLine.clearedBackup) writeConfig(config);
1674
1950
  const candidates = codexWrapperCandidates(config);
1675
- const windowsOwnedShimDirs = windowsOwnedShimDirsForUninstall(config);
1951
+ const windowsOwnedShimDirs = [...new Set([
1952
+ ...windowsOwnedShimDirsForUninstall(config),
1953
+ ...(Array.isArray(extraWindowsOwnedShimDirs) ? extraWindowsOwnedShimDirs : [])
1954
+ ].filter(Boolean))];
1676
1955
  const unmanaged = [];
1677
1956
  const skippedWrappers = [];
1678
1957
  const removedWrappers = [];
@@ -2046,7 +2325,7 @@ function diagnoseClaudeStatusLine() {
2046
2325
  const managed = managedClaudeStatusLine(statusLine);
2047
2326
  const needsRefresh = process.platform === "win32"
2048
2327
  && managed
2049
- && (!command.includes("--attach-hud") || !command.includes("--no-usage-row"));
2328
+ && command.includes("--attach-hud");
2050
2329
  return {
2051
2330
  settingsPath,
2052
2331
  configured: Boolean(statusLine),
@@ -2079,6 +2358,7 @@ async function runDoctor() {
2079
2358
  },
2080
2359
  stateDir: stateDir(),
2081
2360
  configPath: configPath(),
2361
+ displayConfigPath: displayConfigPath(),
2082
2362
  recovery: {
2083
2363
  codexWrapper: Boolean(recoveryConfig.codexWrapper),
2084
2364
  codexStatusLine: Boolean(recoveryConfig.codexStatusLineBackup),
@@ -2089,6 +2369,7 @@ async function runDoctor() {
2089
2369
  : null
2090
2370
  }
2091
2371
  },
2372
+ ...((process.platform === "win32" || isWsl()) ? { split: diagnoseSharedBar() } : {}),
2092
2373
  codex: diagnoseCodex(),
2093
2374
  antigravity: antigravity.diagnose(),
2094
2375
  ...(process.platform !== "win32" ? { tmux: diagnoseTmux() } : {}),
@@ -2272,26 +2553,31 @@ function uninstallRowPtyHost() {
2272
2553
  }
2273
2554
 
2274
2555
  function setupTargets(targets) {
2275
- const requested = targets.length ? targets : ["all"];
2556
+ const requested = targets.length ? targets.map(normalizeTarget) : ["all"];
2276
2557
  const selected = new Set();
2277
2558
  for (const target of requested) {
2278
2559
  if (target === "all") {
2279
- // "all" keeps tmux opt-in: its block overrides the user's status-right.
2560
+ // Prepare native split integration where reachable. tmux remains opt-in.
2280
2561
  PROVIDERS.forEach((provider) => selected.add(provider));
2281
- } else if (PROVIDERS.includes(target) || target === "tmux") {
2562
+ if (process.platform === "win32" || isWslWtContext()) selected.add("split");
2563
+ } else if (PROVIDERS.includes(target) || ["tmux", "split"].includes(target)) {
2282
2564
  selected.add(target);
2283
2565
  } else {
2284
- throw new Error("target must be one of: codex, claude, gemini, tmux, all");
2566
+ throw new Error("target must be one of: codex, claude, gemini, tmux, split, all");
2285
2567
  }
2286
2568
  }
2287
2569
  return [...selected];
2288
2570
  }
2289
2571
 
2290
2572
  function runSetup(args) {
2291
- if (args.providerOrder) {
2292
- const config = readConfig({ strict: true });
2293
- config.providerOrder = args.providerOrder;
2294
- writeConfig(config);
2573
+ if (args.providerOrder || args.barPosition) {
2574
+ const updatedDisplay = updateDisplayConfig({
2575
+ ...(args.providerOrder ? { providerOrder: args.providerOrder } : {}),
2576
+ ...(args.barPosition ? { barPosition: args.barPosition } : {})
2577
+ });
2578
+ if (args.barPosition && !updatedDisplay.splitBarPosition && (process.platform === "win32" || isWsl())) {
2579
+ updateWtFragmentPosition({ position: updatedDisplay.barPosition, sidebarWidth: updatedDisplay.sidebarWidth });
2580
+ }
2295
2581
  }
2296
2582
  const targets = setupTargets(args.targets);
2297
2583
  const previous = readConfig({ strict: true });
@@ -2308,20 +2594,68 @@ function runSetup(args) {
2308
2594
  }
2309
2595
  }
2310
2596
  const results = {};
2311
- let windowsClaudeLauncher = null;
2312
2597
  if (targets.includes("claude")) {
2313
2598
  const statusLine = installClaudeStatusline(args);
2314
- if (process.platform === "win32") {
2315
- windowsClaudeLauncher = installRowPtyHost();
2316
- results.claude = { ...statusLine, launcher: windowsClaudeLauncher };
2317
- } else {
2318
- results.claude = statusLine;
2319
- }
2599
+ results.claude = statusLine;
2320
2600
  }
2321
2601
  if (targets.includes("antigravity")) results.antigravity = antigravity.install(args);
2602
+ if (targets.includes("claude") || targets.includes("antigravity")) {
2603
+ ensureCliPositionWrappers(targets, { updateShellPath: true });
2604
+ }
2322
2605
  if (targets.includes("tmux")) {
2323
2606
  results.tmux = installTmuxStatus(tmuxRefreshPath ? { confPath: tmuxRefreshPath } : {});
2324
2607
  }
2608
+ let paneContextHelper = null;
2609
+ if ((process.platform === "win32" || isWsl()) && targets.some(target => target === "split" || PROVIDERS.includes(target))) {
2610
+ paneContextHelper = preparePaneContextHelper();
2611
+ }
2612
+ if (targets.includes("split")) {
2613
+ if (process.platform === "win32") {
2614
+ const backendOverride = String(process.env.AI_BATTERY_SPLIT_BACKEND || "").trim().toLowerCase();
2615
+ const splitPosition = readConfiguredSplitBarPosition();
2616
+ const usesWtPane = backendOverride !== "in-terminal";
2617
+ const fragment = installWtFragment({
2618
+ cliPath: path.join(scriptDir(), "ai-battery.js"),
2619
+ position: splitPosition,
2620
+ sidebarWidth: readDisplayConfig().sidebarWidth,
2621
+ bindAutoTrigger: usesWtPane
2622
+ });
2623
+ const helper = paneContextHelper || preparePaneContextHelper();
2624
+ results.split = (fragment.ok || !usesWtPane) ? {
2625
+ ...fragment,
2626
+ ok: usesWtPane ? fragment.ok : helper.ready,
2627
+ backend: usesWtPane ? "wt-pane" : "in-terminal",
2628
+ triggerConfigured: Boolean(fragment.autoAttach),
2629
+ helperReady: helper.ready,
2630
+ helperBuilt: helper.built,
2631
+ helperPath: helper.path,
2632
+ helperError: helper.ready ? null : helper.reason,
2633
+ autoAttach: Boolean(helper.ready && (!usesWtPane || fragment.autoAttach)),
2634
+ autoAttachNote: (usesWtPane && fragment.autoAttachNote) || (helper.ready ? null : helper.reason)
2635
+ } : fragment;
2636
+ } else {
2637
+ if (isWsl()) {
2638
+ const helper = paneContextHelper || preparePaneContextHelper();
2639
+ const backendOverride = String(process.env.AI_BATTERY_SPLIT_BACKEND || "").trim().toLowerCase();
2640
+ const usesWtPane = backendOverride !== "in-terminal";
2641
+ const fragment = diagnoseWtFragment();
2642
+ results.split = {
2643
+ ok: helper.ready,
2644
+ backend: usesWtPane ? "wt-pane" : "in-terminal",
2645
+ triggerConfigured: Boolean(fragment.autoAttach),
2646
+ helperReady: helper.ready,
2647
+ helperBuilt: helper.built,
2648
+ helperPath: helper.path,
2649
+ helperError: helper.ready ? null : helper.reason,
2650
+ autoAttach: Boolean(helper.ready && (!usesWtPane || fragment.autoAttach)),
2651
+ autoAttachNote: (usesWtPane && !fragment.autoAttach ? "Run Windows setup once to install the Windows Terminal bar fragment and shortcut." : null),
2652
+ ...(helper.ready ? {} : { reason: helper.reason })
2653
+ };
2654
+ } else {
2655
+ results.split = { ok: true, skipped: true, reason: "Run ai-battery setup split from Windows PowerShell." };
2656
+ }
2657
+ }
2658
+ }
2325
2659
  if (targets.includes("codex")) {
2326
2660
  const wrapCodex = args.wrapCodex;
2327
2661
  const statusLine = args.configureCodexStatusLine ? installCodexStatusLine(args) : null;
@@ -2341,13 +2675,11 @@ function runSetup(args) {
2341
2675
  results.codex.providerEnabled = providerVisible("codex");
2342
2676
  if (process.platform === "win32" && wrapCodex) {
2343
2677
  results.codex.rowpty = windowsSetupNeedsRowPty()
2344
- ? (windowsClaudeLauncher || installRowPtyHost())
2678
+ ? installRowPtyHost()
2345
2679
  : {
2346
2680
  ok: true,
2347
2681
  skipped: true,
2348
- reason: windowsClaudeLauncher?.ok
2349
- ? "Installed with the Windows Claude HUD launcher; not required by the current Codex layout"
2350
- : "Not required by the default PTY compositor; set AI_BATTERY_WIN_LAYOUT=tui and run setup codex to install it"
2682
+ reason: "Not required by the default PTY compositor; set AI_BATTERY_WIN_LAYOUT=tui and run setup codex to install it"
2351
2683
  };
2352
2684
  }
2353
2685
  }
@@ -2366,6 +2698,7 @@ function setupResultFailed(result) {
2366
2698
  || result.codex?.statusLine?.error
2367
2699
  || result.codex?.rowpty?.error
2368
2700
  || (result.codex?.rowpty && result.codex.rowpty.ok === false)
2701
+ || (result.split && result.split.ok === false)
2369
2702
  || (result.tmux && result.tmux.ok === false && !result.tmux.skipped)
2370
2703
  );
2371
2704
  }
@@ -2437,16 +2770,42 @@ function runTeardown(args) {
2437
2770
  }
2438
2771
  };
2439
2772
 
2773
+ let removedWinCliWrappers = false;
2440
2774
  if (targets.includes("claude")) {
2441
- runStep("claude", () => uninstallClaudeStatusline({ strict: false }));
2775
+ runStep("claude", () => {
2776
+ const removed = uninstallCliPositionWrappers({ names: ["claude"], homeDir: userHome(), platform: process.platform, windowsDir: process.platform === "win32" ? defaultCodexShimDir() : null, env: process.env });
2777
+ if (process.platform === "win32" && removed.removed?.length) removedWinCliWrappers = true;
2778
+ return uninstallClaudeStatusline({ strict: false });
2779
+ });
2780
+ }
2781
+ if (targets.includes("antigravity")) {
2782
+ runStep("antigravity", () => {
2783
+ const removed = uninstallCliPositionWrappers({ names: ["agy"], homeDir: userHome(), platform: process.platform, windowsDir: process.platform === "win32" ? defaultCodexShimDir() : null, env: process.env });
2784
+ if (process.platform === "win32" && removed.removed?.length) removedWinCliWrappers = true;
2785
+ return antigravity.uninstall();
2786
+ });
2442
2787
  }
2443
- if (targets.includes("antigravity")) runStep("antigravity", antigravity.uninstall);
2444
2788
  if (targets.includes("codex")) {
2445
- runStep("codex", uninstallCodexWrapper);
2789
+ runStep("codex", () => uninstallCodexWrapper({
2790
+ extraWindowsOwnedShimDirs: removedWinCliWrappers ? [defaultCodexShimDir()] : []
2791
+ }));
2792
+ } else if (targets.includes("claude") || targets.includes("antigravity")) {
2793
+ try {
2794
+ const cfg = readConfig({ strict: true });
2795
+ const cliDir = process.platform === "win32" ? defaultCodexShimDir() : posixCliWrapperDir(userHome());
2796
+ const anyWrapperLeft = ["claude", "agy"].some(name => fs.existsSync(path.join(cliDir, process.platform === "win32" ? `${name}.cmd` : name)));
2797
+ if (!cfg.codexWrapper && !anyWrapperLeft) {
2798
+ removeShellPathBlocks([], { windowsOwnedShimDirs: process.platform === "win32" ? [defaultCodexShimDir()] : [] });
2799
+ }
2800
+ } catch { /* Best-effort PATH cleanup when no codex wrapper exists. */ }
2446
2801
  }
2447
2802
  if (targets.includes("tmux")) {
2448
2803
  runStep("tmux", uninstallTmuxStatus);
2449
2804
  }
2805
+ if (targets.includes("split")) {
2806
+ if (process.platform === "win32") runStep("split", removeWtFragment);
2807
+ else if (args.targets.includes("split")) results.split = { changed: false, skipped: true, reason: "Run ai-battery reset split from Windows PowerShell." };
2808
+ }
2450
2809
  if (targets.includes("hud")) {
2451
2810
  runStep("hud", uninstallHud);
2452
2811
  }
@@ -2459,7 +2818,10 @@ function runTeardown(args) {
2459
2818
  return { targets, fullReset, results };
2460
2819
  }
2461
2820
  const roots = [stateDir(), dataDir(), path.join(os.tmpdir(), "ai-battery")];
2462
- if (process.platform === "win32" && process.env.LOCALAPPDATA) roots.push(path.join(process.env.LOCALAPPDATA, "ai-battery"));
2821
+ if (process.platform === "win32" && process.env.LOCALAPPDATA
2822
+ && !process.env.AI_BATTERY_DATA_DIR && !process.env.AI_BATTERY_STATE_DIR && !process.env.CLAUDEX_BATTERY_STATE_DIR) {
2823
+ roots.push(path.join(process.env.LOCALAPPDATA, "ai-battery"));
2824
+ }
2463
2825
  results.artifacts = cleanupBatteryArtifacts({
2464
2826
  roots,
2465
2827
  home: userHome(),
@@ -2540,10 +2902,18 @@ function readHead(filePath, bytes = 32 * 1024) {
2540
2902
  }
2541
2903
  }
2542
2904
 
2543
- function latestMatchingJsonLine(files, predicate, acceptParsed = null) {
2905
+ function latestMatchingJsonLine(files, predicate, acceptParsed = null, newestTimestamp = false) {
2544
2906
  let fallback = null;
2907
+ let newest = null;
2908
+ let newestMs = 0;
2545
2909
 
2546
2910
  for (const file of files) {
2911
+ // Files are sorted by mtimeMs desc; once we have a newer event than this
2912
+ // file's last modification time (minus a small clock-skew margin), older
2913
+ // files cannot contain a newer event.
2914
+ if (newestTimestamp && newest && Number.isFinite(file.mtimeMs) && file.mtimeMs < newestMs - 5000) {
2915
+ break;
2916
+ }
2547
2917
  const text = readTail(file.path);
2548
2918
  const lines = text.split("\n");
2549
2919
 
@@ -2554,14 +2924,21 @@ function latestMatchingJsonLine(files, predicate, acceptParsed = null) {
2554
2924
  try {
2555
2925
  const json = JSON.parse(line);
2556
2926
  if (acceptParsed && !acceptParsed(json)) continue;
2557
- return { json, file: file.path };
2927
+ const result = { json, file: file.path };
2928
+ if (!newestTimestamp) return result;
2929
+ const ts = Date.parse(json.timestamp || "") || 0;
2930
+ if (!newest || ts > newestMs) {
2931
+ newest = result;
2932
+ newestMs = ts;
2933
+ }
2934
+ break;
2558
2935
  } catch {
2559
2936
  fallback = fallback || { error: "Found a matching line but could not parse it", file: file.path };
2560
2937
  }
2561
2938
  }
2562
2939
  }
2563
2940
 
2564
- return fallback;
2941
+ return newest || fallback;
2565
2942
  }
2566
2943
 
2567
2944
  function codexSessionMeta(filePath) {
@@ -2650,7 +3027,7 @@ function writeJsonAtomic(filePath, data, mode = 0o600) {
2650
3027
  const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
2651
3028
  try {
2652
3029
  fs.writeFileSync(tempPath, `${JSON.stringify(data, null, 2)}\n`, { mode });
2653
- fs.renameSync(tempPath, targetPath);
3030
+ atomicRename(tempPath, targetPath);
2654
3031
  } catch (error) {
2655
3032
  try {
2656
3033
  fs.rmSync(tempPath, { force: true });
@@ -2667,7 +3044,7 @@ function writeTextAtomic(filePath, text, mode = 0o600) {
2667
3044
  const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
2668
3045
  try {
2669
3046
  fs.writeFileSync(tempPath, text, { mode });
2670
- fs.renameSync(tempPath, targetPath);
3047
+ atomicRename(tempPath, targetPath);
2671
3048
  } catch (error) {
2672
3049
  try {
2673
3050
  fs.rmSync(tempPath, { force: true });
@@ -2689,7 +3066,9 @@ function readJson(filePath) {
2689
3066
  function teardownResultFailed(result) {
2690
3067
  return Object.values(result.results || {}).some((item) => Boolean(
2691
3068
  item?.error
3069
+ || item?.ok === false
2692
3070
  || item?.errors?.length
3071
+ || item?.retained === true
2693
3072
  || item?.retainedConfig
2694
3073
  || item?.retainedBackup
2695
3074
  || item?.skippedWrappers?.length
@@ -2791,8 +3170,8 @@ const {
2791
3170
  writeScanCache
2792
3171
  });
2793
3172
  const antigravity = createAntigravityIntegration({
2794
- homePath, stateDir, readJson, readUserJsonObject, readConfig, writeConfig,
2795
- writeJsonAtomic, samePath, shellArg, scriptDir, isProviderRunning
3173
+ homePath, stateDir, usageStateDir: codexUsageStateDir, readJson, readUserJsonObject, readConfig, writeConfig,
3174
+ writeJsonAtomic, samePath, shellArg, scriptDir, isProviderRunning, providerVisible
2796
3175
  });
2797
3176
 
2798
3177
  function readStdin() {
@@ -2847,6 +3226,12 @@ function normalizeClaudeCachedLimit(limit, options = {}) {
2847
3226
  });
2848
3227
  }
2849
3228
 
3229
+ function isPlausibleResetEpoch(epochSec, windowMinutes = 10080) {
3230
+ if (!Number.isFinite(epochSec) || epochSec <= 0) return false;
3231
+ const maxFutureSec = (Date.now() / 1000) + Math.max((Number(windowMinutes) || 10080) * 60, 7 * 86400) + (7 * 86400);
3232
+ return epochSec <= maxFutureSec;
3233
+ }
3234
+
2850
3235
  function claudeCanonicalLimit(candidate, previous) {
2851
3236
  if (!candidate) return previous ?? null;
2852
3237
  if (!previous) return candidate;
@@ -2856,9 +3241,23 @@ function claudeCanonicalLimit(candidate, previous) {
2856
3241
  if (!candidateNorm) return previous;
2857
3242
  if (!previousNorm) return candidate;
2858
3243
 
3244
+ const winMin = candidateNorm.windowMinutes ?? previousNorm.windowMinutes ?? 10080;
2859
3245
  const candidateReset = resetEpochSeconds(candidate.resets_at ?? candidate.resetsAt ?? candidate.reset_at ?? candidate.resetAt);
2860
3246
  const previousReset = resetEpochSeconds(previous.resets_at ?? previous.resetsAt ?? previous.reset_at ?? previous.resetAt);
2861
- if (Number.isFinite(candidateReset) && Number.isFinite(previousReset) && Math.abs(candidateReset - previousReset) > 60) {
3247
+ const candidatePlausible = isPlausibleResetEpoch(candidateReset, winMin);
3248
+ const previousPlausible = isPlausibleResetEpoch(previousReset, winMin);
3249
+ if (candidatePlausible && !previousPlausible) return candidate;
3250
+ if (!candidatePlausible && previousPlausible) return previous;
3251
+ const nowSec = Date.now() / 1000;
3252
+ const candidateExpired = candidateReset > 0 && candidateReset <= nowSec;
3253
+ const previousExpired = previousReset > 0 && previousReset <= nowSec;
3254
+ if (previousExpired && !candidateExpired) return candidate;
3255
+ if (!previousExpired && candidateExpired) return previous;
3256
+ if (candidatePlausible && previousPlausible && Math.abs(candidateReset - previousReset) > 60) {
3257
+ const candidateUnused = candidateNorm.remainingPercent === 100 || candidateNorm.usedPercent === 0;
3258
+ const previousUnused = previousNorm.remainingPercent === 100 || previousNorm.usedPercent === 0;
3259
+ if (previousUnused && !candidateUnused) return candidate;
3260
+ if (!previousUnused && candidateUnused) return previous;
2862
3261
  return candidateReset > previousReset ? candidate : previous;
2863
3262
  }
2864
3263
 
@@ -3070,14 +3469,31 @@ function scanClaudeRateLimitHit() {
3070
3469
 
3071
3470
  let claudeRateLimitHitMemo = null;
3072
3471
 
3472
+ function sharedClaudeRateLimitHitPath() {
3473
+ return path.join(sharedStateDir(), "claude-rate-limit-hit.json");
3474
+ }
3475
+
3073
3476
  function latestClaudeRateLimitHit() {
3074
3477
  if (claudeRateLimitHitMemo && Date.now() - claudeRateLimitHitMemo.at < 5000) {
3075
3478
  return claudeRateLimitHitMemo.value;
3076
3479
  }
3077
3480
 
3078
- const cached = readScanCache("claude-rate-limit-hit", scanCacheSeconds(10));
3079
- const value = cached ? cached.value ?? null : scanClaudeRateLimitHit();
3080
- if (!cached) writeScanCache("claude-rate-limit-hit", value);
3481
+ const cached = readScanCache("claude-rate-limit-hit", scanCacheSeconds(30));
3482
+ let value = cached ? cached.value ?? null : scanClaudeRateLimitHit();
3483
+ if (!cached) {
3484
+ writeScanCache("claude-rate-limit-hit", value);
3485
+ if (value?.timestamp) {
3486
+ publishNewest(sharedClaudeRateLimitHitPath(), value, {
3487
+ read: readJson,
3488
+ write: writeJsonAtomic,
3489
+ timestamp: item => item?.timestamp
3490
+ });
3491
+ }
3492
+ }
3493
+ const sharedHit = readJson(sharedClaudeRateLimitHitPath());
3494
+ if (sharedHit?.timestamp && (!value?.timestamp || (Date.parse(sharedHit.timestamp) || 0) > (Date.parse(value.timestamp) || 0))) {
3495
+ value = sharedHit;
3496
+ }
3081
3497
  claudeRateLimitHitMemo = { at: Date.now(), value };
3082
3498
  return value;
3083
3499
  }
@@ -3108,11 +3524,11 @@ function applyClaudeRateLimitHit(limit, hit, window) {
3108
3524
  function captureClaudeStatusline(input) {
3109
3525
  const rateLimits = claudeRateLimitsFromStatusline(input);
3110
3526
  const sessionId = input.session_id ?? input.sessionId ?? null;
3111
- const previousGlobal = readJson(claudeCachePath());
3112
- const previous = (sessionId ? readJson(claudeSessionCachePath(sessionId)) : null) ?? previousGlobal;
3527
+ const globalPath = claudeCachePath();
3528
+ const previousSession = sessionId ? readJson(claudeSessionCachePath(sessionId)) : null;
3113
3529
  const sessionKind = claudeStatuslineSessionKind(input);
3114
3530
  const contextWindow = claudeContextWindowFromStatusline(input);
3115
- let snapshot = {
3531
+ const baseSnapshot = {
3116
3532
  version: 1,
3117
3533
  provider: "claude",
3118
3534
  sourceType: "statusline",
@@ -3138,26 +3554,66 @@ function captureClaudeStatusline(input) {
3138
3554
  contextWindow
3139
3555
  };
3140
3556
 
3141
- if (previous?.provider === "claude" && previous?.sourceType === "statusline") {
3142
- const sameSession = previous.sessionId && snapshot.sessionId && previous.sessionId === snapshot.sessionId;
3143
- if (!snapshot.rateLimits.fiveHour) {
3144
- snapshot.rateLimits.fiveHour = previous.rateLimits?.fiveHour ?? null;
3145
- }
3146
- if (!snapshot.rateLimits.sevenDay) {
3147
- snapshot.rateLimits.sevenDay = previous.rateLimits?.sevenDay ?? null;
3557
+ const mergeWithGlobal = (currentGlobal) => {
3558
+ const previous = previousSession ?? currentGlobal;
3559
+ const candidate = {
3560
+ ...baseSnapshot,
3561
+ rateLimits: { ...baseSnapshot.rateLimits }
3562
+ };
3563
+ if (previous?.provider === "claude" && previous?.sourceType === "statusline") {
3564
+ const sameSession = previous.sessionId && candidate.sessionId && previous.sessionId === candidate.sessionId;
3565
+ if (!candidate.rateLimits.fiveHour) {
3566
+ candidate.rateLimits.fiveHour = previous.rateLimits?.fiveHour ?? null;
3567
+ }
3568
+ if (!candidate.rateLimits.sevenDay) {
3569
+ candidate.rateLimits.sevenDay = previous.rateLimits?.sevenDay ?? null;
3570
+ }
3571
+ if (sameSession && !candidate.contextWindow) {
3572
+ candidate.contextWindow = previous.contextWindow ?? null;
3573
+ }
3148
3574
  }
3149
- if (sameSession && !snapshot.contextWindow) {
3150
- snapshot.contextWindow = previous.contextWindow ?? null;
3575
+ return claudeCanonicalStatuslineSnapshot(candidate, currentGlobal);
3576
+ };
3577
+
3578
+ const sameSemanticSnapshot = (left, right) => Boolean(
3579
+ left && right
3580
+ && left.sessionId === right.sessionId
3581
+ && left.sessionKind === right.sessionKind
3582
+ && isDeepStrictEqual(left.rateLimits, right.rateLimits)
3583
+ && isDeepStrictEqual(left.contextWindow, right.contextWindow)
3584
+ && isDeepStrictEqual(left.model, right.model)
3585
+ && isDeepStrictEqual(left.workspace, right.workspace)
3586
+ );
3587
+
3588
+ let snapshot;
3589
+ if (sessionKind !== "bg") {
3590
+ const existingGlobal = readJson(globalPath);
3591
+ const preview = mergeWithGlobal(existingGlobal);
3592
+ const globalAgeMs = existingGlobal?.capturedAt ? Date.now() - (Date.parse(existingGlobal.capturedAt) || 0) : Infinity;
3593
+ if (existingGlobal && sameSemanticSnapshot(preview, existingGlobal) && globalAgeMs >= 0 && globalAgeMs < 5000) {
3594
+ snapshot = existingGlobal;
3595
+ } else {
3596
+ try {
3597
+ snapshot = withFileLock(`${globalPath}.lock`, () => {
3598
+ const currentGlobal = readJson(globalPath);
3599
+ const canonical = mergeWithGlobal(currentGlobal);
3600
+ writeJsonAtomic(globalPath, canonical);
3601
+ return canonical;
3602
+ }, { timeoutMs: 1000 });
3603
+ } catch {
3604
+ // Lock unavailable or timed out: compute canonical snapshot in-memory without an unlocked write.
3605
+ snapshot = mergeWithGlobal(readJson(globalPath));
3606
+ }
3151
3607
  }
3608
+ } else {
3609
+ snapshot = mergeWithGlobal(readJson(globalPath));
3152
3610
  }
3153
3611
 
3154
- snapshot = claudeCanonicalStatuslineSnapshot(snapshot, previousGlobal);
3155
-
3156
3612
  if (snapshot.sessionId) {
3157
- writeJsonAtomic(claudeSessionCachePath(snapshot.sessionId), snapshot);
3158
- }
3159
- if (sessionKind !== "bg") {
3160
- writeJsonAtomic(claudeCachePath(), snapshot);
3613
+ const sessionAgeMs = previousSession?.capturedAt ? Date.now() - (Date.parse(previousSession.capturedAt) || 0) : Infinity;
3614
+ if (!previousSession || !sameSemanticSnapshot(snapshot, previousSession) || sessionAgeMs < 0 || sessionAgeMs >= 5000) {
3615
+ writeJsonAtomic(claudeSessionCachePath(snapshot.sessionId), snapshot);
3616
+ }
3161
3617
  }
3162
3618
  return snapshot;
3163
3619
  }
@@ -3236,19 +3692,35 @@ function readClaudeStatuslineCacheFrom(root) {
3236
3692
  return [globalCachePath, ...sessionCachePaths].some((cachePath) => fs.existsSync(cachePath)) ? null : undefined;
3237
3693
  }
3238
3694
 
3239
- function readClaudeStatuslineCache() {
3240
- const shared = readClaudeStatuslineCacheFrom(claudeStateDir());
3241
- if (shared !== undefined) return shared;
3242
-
3243
- // Under WSL the shared Windows cache may be empty on first use; fall back to
3244
- // the WSL-local state dir before the legacy directory.
3245
- if (path.resolve(claudeStateDir()) !== path.resolve(stateDir())) {
3246
- const local = readClaudeStatuslineCacheFrom(stateDir());
3247
- if (local !== undefined) return local;
3695
+ function claudeReadingCompare(a, b) {
3696
+ for (const key of ["primary", "secondary"]) {
3697
+ const left = a?.[key];
3698
+ const right = b?.[key];
3699
+ if (!left || !right) continue;
3700
+ const winMin = left.windowMinutes ?? right.windowMinutes ?? (key === "primary" ? 300 : 10080);
3701
+ const leftReset = resetEpochSeconds(left.resetsAt);
3702
+ const rightReset = resetEpochSeconds(right.resetsAt);
3703
+ const leftPlausible = isPlausibleResetEpoch(leftReset, winMin);
3704
+ const rightPlausible = isPlausibleResetEpoch(rightReset, winMin);
3705
+ if (leftPlausible && !rightPlausible) return -1;
3706
+ if (!leftPlausible && rightPlausible) return 1;
3707
+ if (leftPlausible && rightPlausible && Math.abs(leftReset - rightReset) > 60) {
3708
+ return rightReset - leftReset;
3709
+ }
3710
+ if (Number.isFinite(left.usedPercent) && Number.isFinite(right.usedPercent) && left.usedPercent !== right.usedPercent) {
3711
+ return right.usedPercent - left.usedPercent;
3712
+ }
3713
+ if (Number.isFinite(left.remainingPercent) && Number.isFinite(right.remainingPercent) && left.remainingPercent !== right.remainingPercent) {
3714
+ return left.remainingPercent - right.remainingPercent;
3715
+ }
3248
3716
  }
3717
+ return (Date.parse(b?.timestamp || "") || 0) - (Date.parse(a?.timestamp || "") || 0);
3718
+ }
3249
3719
 
3250
- if (path.resolve(legacyStateDir()) === path.resolve(stateDir())) return null;
3251
- return readClaudeStatuslineCacheFrom(legacyStateDir()) ?? null;
3720
+ function readClaudeStatuslineCache() {
3721
+ const readings = uniquePaths([claudeStateDir(), stateDir(), legacyStateDir()])
3722
+ .map(root => readClaudeStatuslineCacheFrom(root)).filter(Boolean);
3723
+ return readings.sort(claudeReadingCompare)[0] ?? null;
3252
3724
  }
3253
3725
 
3254
3726
  function claudeStatuslineRefreshInterval() {
@@ -3279,9 +3751,8 @@ function installClaudeStatusline(args) {
3279
3751
  "1"
3280
3752
  ];
3281
3753
  if (args.header === false) commandParts.push("--no-header");
3282
- if (args.usageRow === false || (process.platform === "win32" && args.usageRow !== true)) commandParts.push("--no-usage-row");
3754
+ if (args.usageRow === false) commandParts.push("--no-usage-row");
3283
3755
  if (args.usageRow === true) commandParts.push("--usage-row");
3284
- if (process.platform === "win32") commandParts.push("--attach-hud");
3285
3756
  const command = commandParts.join(" ");
3286
3757
  const installedByAiBattery = managedClaudeStatusLine(existing.statusLine);
3287
3758
  const config = readConfig({ strict: true });
@@ -3404,7 +3875,7 @@ function codexSharedLimit(limit) {
3404
3875
 
3405
3876
  function codexAccountUsageSnapshot(scan) {
3406
3877
  if (!scan?.ok || codexUsageTimestamp(scan) === null) return null;
3407
- if (![scan.percentRemaining, scan.primary?.percentRemaining, scan.secondary?.percentRemaining].some(Number.isFinite)) return null;
3878
+ if (![scan.percentRemaining, scan.primary?.remainingPercent, scan.secondary?.remainingPercent].some(Number.isFinite)) return null;
3408
3879
  return {
3409
3880
  timestamp: scan.timestamp,
3410
3881
  planType: scan.planType ?? null,
@@ -3426,33 +3897,33 @@ function readCodexAccountUsage() {
3426
3897
  function writeCodexAccountUsage(scan) {
3427
3898
  const usage = codexAccountUsageSnapshot(scan);
3428
3899
  if (!usage) return false;
3429
- const existing = readCodexAccountUsage();
3430
- const existingTimestamp = codexUsageTimestamp(existing);
3431
- const usageTimestamp = codexUsageTimestamp(usage);
3432
- if (existingTimestamp > usageTimestamp) return false;
3433
- if (existingTimestamp === usageTimestamp && isDeepStrictEqual(existing, usage)) return false;
3434
- try {
3435
- writeJsonAtomic(codexAccountUsagePath(), {
3900
+ return publishNewest(codexAccountUsagePath(), {
3436
3901
  version: CODEX_ACCOUNT_USAGE_VERSION,
3437
3902
  capturedAt: new Date().toISOString(),
3438
3903
  usage
3439
- });
3440
- return true;
3441
- } catch {
3442
- return false;
3443
- }
3904
+ }, { read: readJson, write: writeJsonAtomic, timestamp: value => value?.usage?.timestamp }).changed;
3905
+ }
3906
+
3907
+ function codexLimitWithResetsIn(limit) {
3908
+ if (!limit || typeof limit !== "object") return limit;
3909
+ const resetSec = resetEpochSeconds(limit.resetsAt);
3910
+ if (!Number.isFinite(resetSec) || resetSec <= 0) return limit;
3911
+ return { ...limit, resetsInSeconds: Math.max(0, Math.round(resetSec - Date.now() / 1000)) };
3444
3912
  }
3445
3913
 
3446
3914
  function mergeCodexAccountUsage(scan, sharedUsage) {
3447
3915
  if (!sharedUsage || codexUsageTimestamp(sharedUsage) === null) return scan;
3448
3916
  const localTimestamp = codexUsageTimestamp(scan);
3449
- if (scan?.ok && localTimestamp !== null && localTimestamp >= codexUsageTimestamp(sharedUsage)) return scan;
3917
+ if (scan?.ok && localTimestamp !== null && localTimestamp > codexUsageTimestamp(sharedUsage)) return scan;
3918
+ if (scan?.ok && localTimestamp === codexUsageTimestamp(sharedUsage) && isDeepStrictEqual(codexAccountUsageSnapshot(scan), sharedUsage)) return scan;
3450
3919
 
3451
3920
  const result = {
3452
3921
  ...(scan && typeof scan === "object" ? scan : {}),
3453
3922
  provider: "codex",
3454
3923
  ok: true,
3455
3924
  ...sharedUsage,
3925
+ primary: codexLimitWithResetsIn(sharedUsage.primary),
3926
+ secondary: codexLimitWithResetsIn(sharedUsage.secondary),
3456
3927
  sharedUsage: true,
3457
3928
  usageUpdate: {
3458
3929
  timestamp: sharedUsage.timestamp,
@@ -3609,17 +4080,20 @@ function readCodex(options = {}) {
3609
4080
  .digest("hex");
3610
4081
  // Changed usage logs must be visible on the next poll, even within the TTL.
3611
4082
  let scan = cached?.value;
3612
- if (cached?.inputFingerprint && cached.inputFingerprint !== inputFingerprint) scan = null;
3613
- if (!options.cachedOnly && cached?.inputFingerprint !== inputFingerprint) scan = null;
4083
+ // Backfill legacy scan caches (lacking usageEventOrder/inputFingerprint) into
4084
+ // shared account usage; publishNewest() keeps this a no-op when already current.
4085
+ if (scan?.ok) writeCodexAccountUsage(scan);
4086
+ if (cached?.usageEventOrder !== "timestamp") scan = null;
4087
+ if (cached?.inputFingerprint !== inputFingerprint) scan = null;
3614
4088
  if (!scan || typeof scan !== "object") {
3615
4089
  if (options.cachedOnly) return null;
3616
4090
  scan = scanCodexStatus(files, roots);
3617
- writeScanCache("codex-status", scan, { inputFingerprint });
4091
+ writeScanCache("codex-status", scan, { inputFingerprint, usageEventOrder: "timestamp" });
3618
4092
  }
3619
4093
  writeCodexAccountUsage(scan);
3620
4094
  scan = mergeCodexAccountUsage(scan, readCodexAccountUsage());
3621
4095
 
3622
- const processes = options.includeRunning === false ? null : scanProcessCommands();
4096
+ const processes = options.includeRunning === false ? null : scanProcessCommands(options.processOptions);
3623
4097
  const running = typeof options.runningOverride === "boolean"
3624
4098
  ? options.runningOverride
3625
4099
  : (
@@ -3631,22 +4105,48 @@ function readCodex(options = {}) {
3631
4105
  ? codexBackgroundReadyInProcesses(processes)
3632
4106
  : Boolean(scan.backgroundReady);
3633
4107
  const result = { ...scan, running, backgroundReady };
4108
+ for (const window of ["primary", "secondary"]) {
4109
+ const reset = resetEpochSeconds(result[window]?.resetsAt);
4110
+ if (reset > 0 && reset <= Date.now() / 1000) {
4111
+ result[window] = {
4112
+ ...result[window],
4113
+ remainingPercent: 100,
4114
+ usedPercent: 0,
4115
+ resetsInSeconds: 0,
4116
+ resetPassed: true
4117
+ };
4118
+ if (window === "primary") {
4119
+ result.ok = true;
4120
+ result.percentRemaining = 100;
4121
+ result.percentUsed = 0;
4122
+ result.error = null;
4123
+ }
4124
+ }
4125
+ }
3634
4126
  if (result.ok) result.ageSeconds = cacheAgeSeconds(result.timestamp ?? null);
3635
4127
  return result;
3636
4128
  }
3637
4129
 
3638
- function readCodexForClaudeCapture() {
3639
- if (process.platform !== "win32") return readCodex();
3640
-
3641
- const cached = readCodex({
3642
- cachedOnly: true,
3643
- maxAgeSeconds: CLAUDE_CODEX_CACHE_SECONDS
3644
- });
3645
- if (cached) return cached;
4130
+ function scheduleBackgroundProcessRefresh() {
4131
+ try {
4132
+ const marker = path.join(stateDir(), "process-refresh.stamp");
4133
+ const stat = safeStat(marker);
4134
+ if (stat && Date.now() - stat.mtimeMs < 5000) return;
4135
+ fs.mkdirSync(path.dirname(marker), { recursive: true });
4136
+ fs.writeFileSync(marker, `${process.pid}\n`);
4137
+ const child = spawn(process.execPath, [path.join(scriptDir(), "ai-battery.js"), "--refresh-processes"], {
4138
+ cwd: os.tmpdir(),
4139
+ stdio: "ignore",
4140
+ detached: true,
4141
+ windowsHide: true
4142
+ });
4143
+ child.on("error", () => {});
4144
+ child.unref();
4145
+ } catch { /* Best-effort background refresh. */ }
4146
+ }
3646
4147
 
3647
- return readCodex({
3648
- maxAgeSeconds: CLAUDE_CODEX_FALLBACK_CACHE_SECONDS
3649
- });
4148
+ function readCodexForClaudeCapture(options = {}) {
4149
+ return readCodex(options);
3650
4150
  }
3651
4151
 
3652
4152
  function codexSessionFiles(roots) {
@@ -3676,11 +4176,11 @@ function scanCodexStatus(files, roots) {
3676
4176
  const usageMatch = latestMatchingJsonLine(files, isRateLimitLine, (json) => {
3677
4177
  if (!isCodexRateLimit(json)) return false;
3678
4178
  const limits = json.payload.rate_limits;
3679
- return Boolean(normalizeLimit(limits.primary) || normalizeLimit(limits.secondary));
3680
- });
4179
+ return Boolean(normalizeLimit(limits.primary, { inferResetPassed: false }) || normalizeLimit(limits.secondary, { inferResetPassed: false }));
4180
+ }, true);
3681
4181
  // Preserve a metadata-only snapshot when percentages have never been seen;
3682
4182
  // the renderer will show an unknown value rather than inventing a number.
3683
- const match = usageMatch?.json ? usageMatch : latestMatchingJsonLine(files, isRateLimitLine, isCodexRateLimit);
4183
+ const match = usageMatch?.json ? usageMatch : latestMatchingJsonLine(files, isRateLimitLine, isCodexRateLimit, true);
3684
4184
  const rateLimits = match?.json?.payload?.rate_limits;
3685
4185
 
3686
4186
  if (!rateLimits) {
@@ -3692,16 +4192,15 @@ function scanCodexStatus(files, roots) {
3692
4192
  };
3693
4193
  }
3694
4194
 
3695
- // The approval mode lives in turn_context events of the same session, so
3696
- // only that file needs a second look.
3697
- const sessionFiles = files.filter((file) => file.path === match.file);
3698
- const contextMatch = latestMatchingJsonLine(sessionFiles, (line) => line.includes("\"turn_context\""));
4195
+ // Usage is account-wide; runtime mode still belongs to the locally
4196
+ // prioritized session, even when a background session reports newer usage.
4197
+ const contextMatch = latestMatchingJsonLine(files, (line) => line.includes("\"turn_context\""));
3699
4198
  const turnContext = contextMatch?.json?.payload ?? null;
3700
4199
  const approvalPolicy = turnContext?.approval_policy ?? null;
3701
4200
  const sandboxMode = turnContext?.sandbox_policy?.type ?? null;
3702
4201
  const collaborationMode = turnContext?.collaboration_mode?.mode ?? null;
3703
- const primary = normalizeLimit(rateLimits.primary);
3704
- const secondary = normalizeLimit(rateLimits.secondary);
4202
+ const primary = normalizeLimit(rateLimits.primary, { inferResetPassed: false });
4203
+ const secondary = normalizeLimit(rateLimits.secondary, { inferResetPassed: false });
3705
4204
  const sessionMeta = codexSessionMeta(match.file);
3706
4205
  const timestamp = match.json.timestamp ?? null;
3707
4206
 
@@ -4158,7 +4657,11 @@ function usageTotal(usage) {
4158
4657
  function readClaude(options = {}) {
4159
4658
  const running = typeof options.runningOverride === "boolean"
4160
4659
  ? options.runningOverride
4161
- : isProviderRunning("claude");
4660
+ : isProviderRunning("claude", options.processOptions);
4661
+ if (options.capturedSnapshot) {
4662
+ const inMemory = claudeStatuslineResultFromCache(options.capturedSnapshot, claudeCachePath());
4663
+ if (inMemory) return { ...inMemory, running };
4664
+ }
4162
4665
  const statuslineCache = readClaudeStatuslineCache();
4163
4666
  if (statuslineCache) return { ...statuslineCache, running };
4164
4667
 
@@ -4225,8 +4728,11 @@ function readClaude(options = {}) {
4225
4728
  };
4226
4729
  }
4227
4730
 
4731
+ let sttyColumnsMemo;
4732
+
4228
4733
  function sttyColumns() {
4229
4734
  if (process.platform === "win32") return null;
4735
+ if (sttyColumnsMemo !== undefined) return sttyColumnsMemo;
4230
4736
 
4231
4737
  let ttyFd = null;
4232
4738
  try {
@@ -4237,8 +4743,10 @@ function sttyColumns() {
4237
4743
  timeout: 100
4238
4744
  }).trim();
4239
4745
  const [, columns] = output.split(/\s+/).map((part) => Number(part));
4240
- return numericColumn(columns);
4746
+ sttyColumnsMemo = numericColumn(columns);
4747
+ return sttyColumnsMemo;
4241
4748
  } catch {
4749
+ sttyColumnsMemo = null;
4242
4750
  return null;
4243
4751
  } finally {
4244
4752
  if (ttyFd !== null) {
@@ -4255,12 +4763,12 @@ function runtimeTerminalColumns() {
4255
4763
  return numericColumn(process.stdout.columns) ?? sttyColumns();
4256
4764
  }
4257
4765
 
4258
- function statusLineColumns(input) {
4766
+ function statusLineColumns(input, observedColumns = null) {
4259
4767
  const explicitColumns = numericColumn(process.env.AI_BATTERY_COLUMNS)
4260
4768
  ?? numericColumn(process.env.CLAUDEX_BATTERY_COLUMNS);
4261
4769
  if (explicitColumns) return explicitColumns;
4262
4770
 
4263
- const runtimeColumns = runtimeTerminalColumns();
4771
+ const runtimeColumns = runtimeTerminalColumns() ?? numericColumn(observedColumns);
4264
4772
  const payloadCandidates = [
4265
4773
  input.terminal?.columns,
4266
4774
  input.terminal?.cols,
@@ -4289,18 +4797,18 @@ function statusLineColumns(input) {
4289
4797
  return 80;
4290
4798
  }
4291
4799
 
4292
- function statusLineHeaderColumns(input, args) {
4800
+ function statusLineHeaderColumns(input, args, observedColumns = null) {
4293
4801
  const guard = numericGuard(process.env.AI_BATTERY_HEADER_COLUMN_GUARD)
4294
4802
  ?? numericGuard(process.env.CLAUDEX_BATTERY_HEADER_COLUMN_GUARD)
4295
4803
  ?? DEFAULT_STATUSLINE_HEADER_COLUMN_GUARD;
4296
- return Math.max(20, statusLineColumns(input) - guard - (Number(args.leftPadding) || 0));
4804
+ return Math.max(20, statusLineColumns(input, observedColumns) - guard - (Number(args.leftPadding) || 0));
4297
4805
  }
4298
4806
 
4299
- function statusLineUsableColumns(input) {
4807
+ function statusLineUsableColumns(input, observedColumns = null) {
4300
4808
  const guard = numericGuard(process.env.AI_BATTERY_COLUMN_GUARD)
4301
4809
  ?? numericGuard(process.env.CLAUDEX_BATTERY_COLUMN_GUARD)
4302
4810
  ?? DEFAULT_STATUSLINE_COLUMN_GUARD;
4303
- return Math.max(20, statusLineColumns(input) - guard);
4811
+ return Math.max(20, statusLineColumns(input, observedColumns) - guard);
4304
4812
  }
4305
4813
 
4306
4814
  function contextRemainingPercent(input, fallbackContext = null) {
@@ -4329,11 +4837,14 @@ function displayPath(dir) {
4329
4837
 
4330
4838
  function gitBranchFromDir(dir) {
4331
4839
  if (!dir) return null;
4840
+ const fast = readGitBranchFast(dir);
4841
+ if (fast) return fast;
4332
4842
  try {
4333
4843
  const branch = execFileSync("git", ["-C", dir, "branch", "--show-current"], {
4334
4844
  encoding: "utf8",
4335
4845
  stdio: ["ignore", "pipe", "ignore"],
4336
- timeout: 500
4846
+ timeout: 500,
4847
+ windowsHide: true
4337
4848
  }).trim();
4338
4849
  return branch || null;
4339
4850
  } catch {
@@ -4352,7 +4863,7 @@ function statuslineGitBranch(input) {
4352
4863
  || null;
4353
4864
  if (explicit) return explicit;
4354
4865
 
4355
- const dirs = [
4866
+ const dirs = uniquePaths([
4356
4867
  input.workspace?.current_dir,
4357
4868
  input.workspace?.currentDir,
4358
4869
  input.cwd,
@@ -4360,7 +4871,7 @@ function statuslineGitBranch(input) {
4360
4871
  input.currentDir,
4361
4872
  input.workspace?.project_dir,
4362
4873
  input.workspace?.projectDir
4363
- ].filter(Boolean);
4874
+ ].filter(Boolean));
4364
4875
 
4365
4876
  for (const dir of dirs) {
4366
4877
  const branch = gitBranchFromDir(dir);
@@ -4369,7 +4880,7 @@ function statuslineGitBranch(input) {
4369
4880
  return null;
4370
4881
  }
4371
4882
 
4372
- function claudeHeader(input, args, capturedClaude = null) {
4883
+ function claudeHeader(input, args, capturedClaude = null, observedColumns = null) {
4373
4884
  const model = typeof input.model === "string"
4374
4885
  ? input.model
4375
4886
  : input.model?.display_name || input.model?.displayName || input.model?.id || (input.product === "antigravity" ? providerLabel("antigravity") : "Claude");
@@ -4395,7 +4906,7 @@ function claudeHeader(input, args, capturedClaude = null) {
4395
4906
  if (changes) parts.push("·", changes);
4396
4907
  const context = contextLeftText(input, capturedClaude?.contextWindow ?? null);
4397
4908
  if (context) parts.push("·", context);
4398
- const columns = statusLineHeaderColumns(input, args);
4909
+ const columns = statusLineHeaderColumns(input, args, observedColumns);
4399
4910
  const header = truncateMiddleVisible(parts.join(" "), columns);
4400
4911
  return statusColorize({ running: false }, header, args);
4401
4912
  }
@@ -4425,8 +4936,19 @@ function weekText(secondary) {
4425
4936
  }
4426
4937
 
4427
4938
  function formatCodex(data, args) {
4428
- if (!data.ok) return statusColorize(data, args.maxWidth && !args.showPaths
4429
- ? "Codex --%" : `Codex ? (${cliMessageText(data.error)})`, args);
4939
+ if (!data.ok) {
4940
+ if (args.maxWidth && !args.showPaths) {
4941
+ const hasValidSecondary = args.showSecondary !== false
4942
+ && data.secondary
4943
+ && Number.isFinite(data.secondary.remainingPercent)
4944
+ && !data.secondary.resetPassed;
4945
+ if (hasValidSecondary) {
4946
+ return `${statusColorize(data, "Codex --%", args)} ${divider(args)} ${statusColorize(data, weekText(data.secondary), args)}`;
4947
+ }
4948
+ return statusColorize(data, "Codex --%", args);
4949
+ }
4950
+ return statusColorize(data, `Codex ? (${cliMessageText(data.error)})`, args);
4951
+ }
4430
4952
 
4431
4953
  const batteryColor = remainingColor(data.percentRemaining);
4432
4954
  const primary = data.primary;
@@ -4465,7 +4987,7 @@ function formatClaude(data, args) {
4465
4987
  if (data.sourceType === "statusline") {
4466
4988
  const batteryColor = remainingColor(data.percentRemaining);
4467
4989
  const bits = [
4468
- `${statusColorize(data, "Claude ", args)}${bar(data.percentRemaining, args.barWidth, batteryColor, args.style)}${statusColorize(data, ` ${data.percentRemaining}%`, args)}`
4990
+ `${statusColorize(data, "Claude ", args)}${bar(data.percentRemaining, args.barWidth, batteryColor, args.style)}${statusColorize(data, ` ${Number.isFinite(data.percentRemaining) ? data.percentRemaining : "--"}%`, args)}`
4469
4991
  ];
4470
4992
  if (args.showPrimary !== false) {
4471
4993
  const primaryReset = limitResetText(data.primary);
@@ -4503,7 +5025,7 @@ function formatClaude(data, args) {
4503
5025
  function formatAntigravity(data, args) {
4504
5026
  const name = providerLabel("antigravity");
4505
5027
  if (!data.ok || typeof data.percentRemaining !== "number") {
4506
- const amounts = data.quotas?.filter(quota => quota.remainingAmount !== null)
5028
+ const amounts = data.quotas?.filter(quota => quota.remainingAmount != null)
4507
5029
  .map(quota => `${quota.id} ${quota.remainingAmount}`).join(" · ");
4508
5030
  return statusColorize(data, amounts && args.showSecondary !== false ? `${name} ${amounts}` : `${name} --%`, args);
4509
5031
  }
@@ -4525,17 +5047,23 @@ function compactNumber(value) {
4525
5047
  }
4526
5048
 
4527
5049
  function runningOverrideForProvider(args, provider) {
5050
+ if (args.runningProviders instanceof Set) return args.runningProviders.has(provider);
4528
5051
  if (args.activeProvider === provider) return true;
4529
5052
  return null;
4530
5053
  }
4531
5054
 
5055
+ function renderTmuxUsage(runningProviders, maxWidth) {
5056
+ const args = { provider: "all", runningProviders, style: "tmux", barWidth: 10, maxWidth, leftPadding: 0 };
5057
+ return render(collect(args), args);
5058
+ }
5059
+
4532
5060
  function collect(args) {
4533
5061
  const results = [];
4534
5062
  const includeHidden = args.provider !== "all";
4535
5063
  if ((args.provider === "all" || args.provider === "codex") && (includeHidden || providerVisible("codex"))) {
4536
5064
  results.push(readCodex({
4537
5065
  runningOverride: runningOverrideForProvider(args, "codex"),
4538
- includeRunning: args.activeProvider !== "codex"
5066
+ includeRunning: !(args.runningProviders instanceof Set) && args.activeProvider !== "codex"
4539
5067
  }));
4540
5068
  }
4541
5069
  if ((args.provider === "all" || args.provider === "claude") && (includeHidden || providerVisible("claude"))) {
@@ -5041,7 +5569,8 @@ function render(snapshot, args) {
5041
5569
  if (args.maxWidth) {
5042
5570
  // Use exact 10%, 20% or 25% steps. Keep 5h reset times after dropping
5043
5571
  // weekly detail, before spending the available space on longer bars.
5044
- const widths = [10, 5, 4].filter(width => width <= args.barWidth);
5572
+ const barWidth = Math.max(4, Number(args.barWidth) || 10);
5573
+ const widths = [10, 5, 4].filter(width => width <= barWidth);
5045
5574
  const fullWidth = widths[0];
5046
5575
  const shortWidth = widths.find(width => width <= 5);
5047
5576
  const candidates = [
@@ -5058,7 +5587,7 @@ function render(snapshot, args) {
5058
5587
  // names and readings rather than letting the one-row terminal wrap away
5059
5588
  // a provider. Detailed errors remain available in diagnostics.
5060
5589
  const readings = snapshot.results.map((result) => {
5061
- const percent = typeof result.percentRemaining === "number" ? `${result.percentRemaining}%` : "--%";
5590
+ const percent = result.ok && Number.isFinite(result.percentRemaining) ? `${result.percentRemaining}%` : "--%";
5062
5591
  const name = providerLabel(result.provider);
5063
5592
  return statusColorize(result, `${name} ${percent}`, args);
5064
5593
  }).join(` ${colorize(PROVIDER_DIVIDER, "gray", args.style)} `);
@@ -5103,31 +5632,69 @@ async function main() {
5103
5632
  }
5104
5633
 
5105
5634
  if (args.command === "config") {
5106
- const config = readConfig({ strict: true });
5107
- if (!args.providerOrder && !args.json && canEditConfig()) {
5108
- const edited = await editDisplayConfig(config, { color: args.style !== "plain" && !Object.hasOwn(process.env, "NO_COLOR") });
5635
+ const display = readDisplayConfig({ strict: true });
5636
+ if (!args.providerOrder && !args.barPosition && !args.json && canEditConfig()) {
5637
+ const edited = await editDisplayConfig(display, { color: args.style !== "plain" && !Object.hasOwn(process.env, "NO_COLOR") });
5109
5638
  if (!edited) {
5110
5639
  console.log(cliText("Configuration cancelled.", "설정을 취소했습니다."));
5111
5640
  return;
5112
5641
  }
5113
- // Merge with the latest settings so another process's changes survive the editor.
5114
- const latest = readConfig({ strict: true });
5115
- latest.providerOrder = edited.providerOrder;
5116
- Object.assign(latest.providers, edited.providerChanges);
5117
- writeConfig(latest);
5642
+ // Merge only changed fields inside the lock so concurrent edits survive.
5643
+ const saveBarPosition = edited.barPositionChanged || edited.positionTabVisited;
5644
+ const latest = updateDisplayConfig({
5645
+ ...(edited.orderChanged ? { providerOrder: edited.providerOrder } : {}),
5646
+ providers: edited.providerChanges,
5647
+ ...(saveBarPosition ? { barPosition: edited.barPosition } : {}),
5648
+ ...(edited.sidebarWidthChanged ? { sidebarWidth: edited.sidebarWidth } : {})
5649
+ });
5650
+ if ((saveBarPosition || edited.sidebarWidthChanged) && (process.platform === "win32" || isWsl())) {
5651
+ const effectiveWtPos = latest.splitBarPosition || latest.barPosition;
5652
+ if (!latest.splitBarPosition || edited.sidebarWidthChanged) {
5653
+ updateWtFragmentPosition({ position: effectiveWtPos, sidebarWidth: latest.sidebarWidth });
5654
+ }
5655
+ }
5656
+ if (latest.barPosition !== "bottom") {
5657
+ ensureCliPositionWrappers(["claude", "antigravity"], { updateShellPath: true });
5658
+ }
5118
5659
  const visible = latest.providerOrder.filter(provider => latest.providers[provider] !== false).map(providerLabel);
5119
5660
  console.log(`${cliText("Display settings saved", "표시 설정 저장")}: ${visible.join(" → ") || cliText("All hidden", "모두 숨김")}`);
5661
+ const posLabel = ({
5662
+ bottom: cliText("bottom", "하단 (bottom)"),
5663
+ top: cliText("top", "상단 (top)"),
5664
+ left: cliText("left", "좌측 (left)"),
5665
+ right: cliText("right", "우측 (right)")
5666
+ })[latest.barPosition] || latest.barPosition;
5667
+ console.log(`${cliText("Bar position", "상태바 위치")}: ${posLabel}${latest.splitBarPosition && latest.splitBarPosition !== latest.barPosition ? ` (${cliText("split", "통합 바")}: ${latest.splitBarPosition})` : ""}`);
5120
5668
  return;
5121
5669
  }
5122
- if (args.providerOrder) { config.providerOrder = args.providerOrder; writeConfig(config); }
5123
- const result = { configPath: configPath(), providerOrder: normalizeOrder(config.providerOrder, PROVIDERS),
5124
- providers: Object.fromEntries(PROVIDERS.map(provider => [provider, config.providers[provider] !== false])) };
5670
+ const current = (args.providerOrder || args.barPosition)
5671
+ ? updateDisplayConfig({
5672
+ ...(args.providerOrder ? { providerOrder: args.providerOrder } : {}),
5673
+ ...(args.barPosition ? { barPosition: args.barPosition } : {})
5674
+ })
5675
+ : display;
5676
+ if (args.barPosition && !current.splitBarPosition && (process.platform === "win32" || isWsl())) {
5677
+ updateWtFragmentPosition({ position: current.barPosition, sidebarWidth: current.sidebarWidth });
5678
+ }
5679
+ if (args.barPosition && current.barPosition !== "bottom") {
5680
+ ensureCliPositionWrappers(["claude", "antigravity"], { updateShellPath: true });
5681
+ }
5682
+ const result = {
5683
+ configPath: configPath(),
5684
+ displayConfigPath: displayConfigPath(),
5685
+ providerOrder: normalizeOrder(current.providerOrder, PROVIDERS),
5686
+ providers: Object.fromEntries(PROVIDERS.map(provider => [provider, current.providers[provider] !== false])),
5687
+ barPosition: current.barPosition,
5688
+ splitBarPosition: current.splitBarPosition || current.barPosition,
5689
+ sidebarWidth: current.sidebarWidth
5690
+ };
5125
5691
  if (args.json) console.log(JSON.stringify(result, null, 2));
5126
5692
  else {
5127
5693
  console.log(`${cliText("Display settings", "표시 설정")}: ${result.providerOrder.map(provider => `${providerLabel(provider)}${result.providers[provider] ? "" : cliText(" (hidden)", " (숨김)")}`).join(" → ")}`);
5128
- if (!args.providerOrder) {
5129
- console.log(cliText("Run ai-battery config in a terminal: arrows reorder, Space shows/hides, Enter saves, Esc cancels.", "터미널에서 ai-battery config를 실행하세요: 방향키 순서 이동 · Space 표시/숨김 · Enter 저장 · Esc 취소"));
5130
- console.log(`${cliText("Or use", "명령으로 변경")}: ai-battery config --provider-order ${result.providerOrder.map(provider => provider === "antigravity" ? "gemini" : provider).join(",")}`);
5694
+ console.log(`${cliText("Bar position", "상태바 위치")}: ${result.barPosition}${current.splitBarPosition && current.splitBarPosition !== result.barPosition ? ` (${cliText("split", "통합 바")}: ${current.splitBarPosition})` : ""}`);
5695
+ if (!args.providerOrder && !args.barPosition) {
5696
+ console.log(cliText("Run ai-battery config in a terminal: arrows reorder, Space shows/hides, Tab switches to bar position, Enter saves, Esc cancels.", "터미널에서 ai-battery config를 실행하세요: 방향키 순서 이동 · Space 표시/숨김 · Tab 상태바 위치 전환 · Enter 저장 · Esc 취소"));
5697
+ console.log(`${cliText("Or use", "명령으로 변경")}: ai-battery config --provider-order ${result.providerOrder.map(provider => provider === "antigravity" ? "gemini" : provider).join(",")} --position ${result.barPosition}`);
5131
5698
  }
5132
5699
  }
5133
5700
  return;
@@ -5158,6 +5725,146 @@ async function main() {
5158
5725
  process.exit(result.status ?? 0);
5159
5726
  }
5160
5727
 
5728
+ if (args.refreshProcesses) {
5729
+ scanProcessCommands({ forceRefresh: true });
5730
+ return;
5731
+ }
5732
+
5733
+ if (args.sharedBarState) {
5734
+ const { root, context } = JSON.parse(Buffer.from(args.sharedBarState, "base64").toString("utf8"));
5735
+ if (!root || !validBarContext(context)) throw new Error("Invalid shared bar context");
5736
+ const isAlive = createCrossOsSessionAlive({ root, context });
5737
+ const sessions = listActiveAiSessions({ root, context, isAlive });
5738
+ const runningProviders = new Set(sessions.map(session => session.provider));
5739
+ console.log(JSON.stringify({
5740
+ ...collect({ ...args, runningProviders }),
5741
+ sharedBar: {
5742
+ sessionCount: sessions.length,
5743
+ mode: resolveSplitBarMode().mode,
5744
+ position: readConfiguredSplitBarPosition()
5745
+ }
5746
+ }));
5747
+ return;
5748
+ }
5749
+
5750
+ if (args.paneDecisionProvider) {
5751
+ const provider = providerId(args.paneDecisionProvider) || "codex";
5752
+ const decision = paneUsageDecision(provider, {
5753
+ ownerPid: args.ownerPid,
5754
+ cols: args.paneCols,
5755
+ rows: args.paneRows
5756
+ });
5757
+ const effectiveShow = Boolean(decision.showUsage) && !decision.attaching;
5758
+ if (provider === "codex" && !effectiveShow) {
5759
+ // Keep shared Codex account usage fresh for the Windows shared bar even
5760
+ // while the WSL runner hides its own per-pane bottom row.
5761
+ try { readCodex({ includeRunning: false }); } catch {}
5762
+ }
5763
+ const leasePath = decision.root && decision.context?.window && decision.context?.tab
5764
+ ? sharedBarLeasePath(decision.root, decision.context)
5765
+ : null;
5766
+ console.log(JSON.stringify({
5767
+ showUsage: effectiveShow,
5768
+ sharedBar: Boolean(decision.sharedBar),
5769
+ attaching: Boolean(decision.attaching),
5770
+ barSlice: decision.barSlice || null,
5771
+ barLeasePath: leasePath,
5772
+ columns: decision.columns ?? null
5773
+ }));
5774
+ return;
5775
+ }
5776
+
5777
+ if (args.paneCleanupProvider) {
5778
+ const provider = providerId(args.paneCleanupProvider) || "codex";
5779
+ cleanupPaneAiSession(provider, { ownerPid: args.ownerPid });
5780
+ return;
5781
+ }
5782
+
5783
+ if (args.command === "bar") {
5784
+ if (process.platform !== "win32" || !process.stdout.isTTY) {
5785
+ throw cliError("Run the shared bar in a native Windows Terminal pane.", "통합 바는 Windows Terminal의 전용 pane에서 실행하세요.", "bar");
5786
+ }
5787
+ await runSharedBar({
5788
+ intervalSeconds: process.argv.includes("--interval") ? args.interval : 2,
5789
+ renderLine: (columns, opts = {}) => render(collect(args), {
5790
+ ...args,
5791
+ ...(opts.barWidth ? { barWidth: opts.barWidth } : {}),
5792
+ style: args.style === "plain" ? "muted" : args.style,
5793
+ maxWidth: Math.max(20, columns - 1)
5794
+ })
5795
+ });
5796
+ return;
5797
+ }
5798
+
5799
+ if (args.command === "split") {
5800
+ const action = args.subcommand || (args.barPosition ? "position" : "status");
5801
+ if (BAR_POSITIONS.includes(action) || action === "position") {
5802
+ const targetPos = action === "position" ? args.barPosition : normalizeBarPosition(action);
5803
+ const updated = updateDisplayConfig({ splitBarPosition: targetPos });
5804
+ const fragmentUpdate = (process.platform === "win32" || isWsl())
5805
+ ? updateWtFragmentPosition({ position: targetPos, sidebarWidth: updated.sidebarWidth })
5806
+ : { ok: false, updated: false };
5807
+ const result = {
5808
+ ok: true,
5809
+ action: "position",
5810
+ position: targetPos,
5811
+ barPosition: updated.barPosition,
5812
+ splitBarPosition: updated.splitBarPosition,
5813
+ fragmentUpdated: Boolean(fragmentUpdate.updated),
5814
+ displayConfigPath: displayConfigPath()
5815
+ };
5816
+ if (args.json) console.log(JSON.stringify(result, null, 2));
5817
+ else {
5818
+ console.log(`${cliText("Split bar position", "통합 바 위치")}: ${targetPos}`);
5819
+ if (fragmentUpdate.ok) {
5820
+ console.log(cliText("Windows Terminal fragment updated.", "Windows Terminal 설정을 반영했습니다."));
5821
+ }
5822
+ }
5823
+ return;
5824
+ }
5825
+ if (["on", "auto", "manual", "off"].includes(action)) {
5826
+ const targetMode = normalizeSplitBarMode(action);
5827
+ const updated = updateDisplayConfig({
5828
+ splitBar: targetMode,
5829
+ ...(args.barPosition ? { splitBarPosition: args.barPosition } : {})
5830
+ });
5831
+ if (args.barPosition && (process.platform === "win32" || isWsl())) {
5832
+ updateWtFragmentPosition({ position: args.barPosition, sidebarWidth: updated.sidebarWidth });
5833
+ }
5834
+ const resolved = resolveSplitBarMode(process.env, { configuredMode: updated.splitBar });
5835
+ const result = {
5836
+ ok: true,
5837
+ action,
5838
+ mode: resolved.mode,
5839
+ configuredMode: updated.splitBar,
5840
+ position: updated.splitBarPosition || updated.barPosition,
5841
+ envOverride: resolved.envOverride,
5842
+ displayConfigPath: displayConfigPath()
5843
+ };
5844
+ console.log(args.json ? JSON.stringify(result, null, 2) : formatSplitBarModeResult(result));
5845
+ return;
5846
+ }
5847
+ if (action === "status") {
5848
+ const display = readDisplayConfig({ strict: true });
5849
+ const resolved = resolveSplitBarMode(process.env, { configuredMode: display.splitBar });
5850
+ const position = readConfiguredSplitBarPosition(process.env);
5851
+ const splitInfo = (process.platform === "win32" || isWsl()) ? diagnoseSharedBar() : null;
5852
+ const result = {
5853
+ ok: true,
5854
+ action: "status",
5855
+ mode: resolved.mode,
5856
+ configuredMode: resolved.configuredMode,
5857
+ position,
5858
+ envOverride: resolved.envOverride,
5859
+ displayConfigPath: displayConfigPath(),
5860
+ platform: process.platform,
5861
+ ...(splitInfo ? { split: splitInfo } : {})
5862
+ };
5863
+ console.log(args.json ? JSON.stringify(result, null, 2) : formatSplitBarStatus(result));
5864
+ return;
5865
+ }
5866
+ }
5867
+
5161
5868
  if (args.command === "on" || args.command === "off") {
5162
5869
  const visible = args.command === "on";
5163
5870
  const result = setProviderVisibility(args.targets, visible);
@@ -5198,42 +5905,59 @@ async function main() {
5198
5905
  );
5199
5906
  }
5200
5907
  if (!args.silent) {
5201
- const contentWidth = Math.max(20, statusLineUsableColumns(input) - (Number(args.leftPadding) || 0));
5202
- const header = args.header ? claudeHeader(activeProvider === "antigravity" ? { ...input, product: "antigravity" } : input, args, capturedClaude) : "";
5203
- const usageRowVisible = activeProvider === "antigravity"
5908
+ const usageRowRequested = activeProvider === "antigravity"
5204
5909
  ? (typeof args.usageRow === "boolean" ? args.usageRow : booleanEnvValue(process.env.AI_BATTERY_ANTIGRAVITY_USAGE_ROW) ?? !tmuxStatusBarActive())
5205
5910
  : claudeUsageRowVisible(args);
5206
- if (!usageRowVisible && header) {
5207
- console.log(applyLeftPadding(header, args));
5911
+ const externalBarActive = process.env.AI_BATTERY_EXTERNAL_BAR === "1";
5912
+ const participate = usageRowRequested && !args.attachHud && !externalBarActive;
5913
+ const sharingOptions = {
5914
+ ownerPid: participate && process.platform === "win32" && activeProvider === "claude"
5915
+ ? claudeNativeSessionOwnerPid(capturedClaude.sessionId, capturedClaude.workspace?.currentDir || "") : 0,
5916
+ participate
5917
+ };
5918
+ const sharing = capturedClaude.sessionKind === "bg" ? { showUsage: false, columns: null } : paneUsageDecision(activeProvider, sharingOptions);
5919
+ const contentWidth = Math.max(20, statusLineUsableColumns(input, sharing.columns) - (Number(args.leftPadding) || 0));
5920
+ const header = args.header ? claudeHeader(activeProvider === "antigravity" ? { ...input, product: "antigravity" } : input, args, capturedClaude, sharing.columns) : "";
5921
+ const usageRowVisible = usageRowRequested && sharing.showUsage && !externalBarActive;
5922
+ if (!usageRowVisible) {
5923
+ if (header) console.log(applyLeftPadding(header, args));
5208
5924
  return;
5209
5925
  }
5926
+ const hookProcessOptions = {
5927
+ nonBlocking: true,
5928
+ triggerBackgroundRefresh: scheduleBackgroundProcessRefresh
5929
+ };
5210
5930
  const results = [];
5211
5931
  if ((args.provider === "all" || args.provider === "codex") && providerVisible("codex")) {
5212
- const codexData = readCodexForClaudeCapture();
5932
+ const codexData = readCodexForClaudeCapture({ processOptions: hookProcessOptions });
5213
5933
  if (codexData) results.push(codexData);
5214
5934
  }
5215
5935
  if ((args.provider === "all" || args.provider === "claude") && providerVisible("claude")) {
5216
5936
  if (activeProvider === "claude") {
5217
- const capturedSource = capturedClaude.sessionKind === "bg" && capturedClaude.sessionId
5218
- ? claudeSessionCachePath(capturedClaude.sessionId)
5219
- : claudeCachePath();
5220
- const claudeData = claudeStatuslineResultFromCache(capturedClaude, capturedSource, { includeBackground: true }) ?? readClaude();
5937
+ const claudeData = readClaude({ runningOverride: true, capturedSnapshot: capturedClaude });
5221
5938
  results.push({ ...claudeData, running: true });
5222
- } else results.push(readClaude());
5939
+ } else results.push(readClaude({ processOptions: hookProcessOptions }));
5223
5940
  }
5224
5941
  if ((args.provider === "all" || args.provider === "antigravity") && providerVisible("antigravity") && (activeProvider === "antigravity" || antigravityAvailable())) {
5225
- results.push(antigravity.read({ runningOverride: activeProvider === "antigravity" ? true : null }));
5942
+ results.push(antigravity.read({
5943
+ runningOverride: activeProvider === "antigravity" ? true : null,
5944
+ processOptions: hookProcessOptions
5945
+ }));
5226
5946
  }
5227
5947
  const usage = render({
5228
5948
  generatedAt: new Date().toISOString(),
5229
5949
  results
5230
5950
  }, { ...args, activeProvider, leftPadding: 0, maxWidth: contentWidth });
5951
+ // A bar may become ready while quota/log collection runs. Recheck lease only
5952
+ // so an event-driven hook never leaves a stale duplicate usage row.
5953
+ if (isPaneSharedBarActive(sharing, { includePendingAttach: true })) {
5954
+ if (header) console.log(applyLeftPadding(header, args));
5955
+ return;
5956
+ }
5231
5957
  // Inside tmux with the status-bar integration, the battery already shows
5232
5958
  // in tmux's own bar; keep the statusline to the one line tmux can't show.
5233
- const text = !usageRowVisible
5234
- ? (header || usage)
5235
- : (header && usage ? `${header}\n${usage}` : (usage || header));
5236
- console.log(applyLeftPadding(text, args));
5959
+ const text = header && usage ? `${header}\n${usage}` : (usage || header);
5960
+ if (text) console.log(applyLeftPadding(text, args));
5237
5961
  }
5238
5962
  return;
5239
5963
  }
@@ -5310,11 +6034,13 @@ export {
5310
6034
  percentValue,
5311
6035
  providerRunningInProcesses,
5312
6036
  render,
6037
+ renderTmuxUsage,
5313
6038
  renderHudState,
5314
6039
  renderMenuBarImage,
5315
6040
  renderMenuDetailImage,
5316
6041
  rowptyDiagnostic,
5317
6042
  sameFilePath,
6043
+ teardownResultFailed,
5318
6044
  visibleWidth,
5319
6045
  uninstallClaudeStatusline,
5320
6046
  uninstallCodexWrapper,