ai-battery 0.1.29 → 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.
- package/README.md +92 -319
- package/bin/ai-battery-macos-status.applescript +5 -12
- package/bin/ai-battery-run +708 -36
- package/bin/ai-battery-tmux.js +17 -0
- package/bin/terminal-compositor.js +111 -0
- package/docs/REFERENCE.md +98 -0
- package/docs/RELEASING.md +35 -7
- package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
- package/docs/antigravity-icon.svg +76 -0
- package/docs/claude-statusline-preview.svg +1 -2
- package/docs/hud-preview.svg +167 -0
- package/docs/terminal-preview.svg +54 -44
- package/docs/terminal-vertical-preview.svg +73 -0
- package/lib/cli.js +1105 -269
- package/lib/core/atomic-rename.js +18 -0
- package/lib/core/cli-help.js +69 -27
- package/lib/core/cli-messages.js +45 -1
- package/lib/core/cli-output.js +293 -68
- package/lib/core/cli-wrappers.js +410 -0
- package/lib/core/config-editor.js +283 -0
- package/lib/core/display-config.js +74 -0
- package/lib/core/integration-files.js +32 -3
- package/lib/core/shared-bar.js +603 -0
- package/lib/core/statusline-git.js +211 -0
- package/lib/core/terminal.js +25 -7
- package/lib/core/tmux-status.js +172 -0
- package/lib/core/uninstall.js +22 -9
- package/lib/core/usage-store.js +85 -0
- package/lib/hud/launcher.js +29 -31
- package/lib/platforms/linux/hud.js +4 -3
- package/lib/platforms/linux/panel.js +1 -1
- package/lib/platforms/macos/hud.js +8 -7
- package/lib/platforms/process-scanner.js +79 -30
- package/lib/platforms/ui-language.js +41 -0
- package/lib/platforms/windows/autostart-cleanup.js +1 -1
- package/lib/platforms/windows/codex-runner.js +184 -26
- package/lib/platforms/windows/hud/controls.ps1 +137 -81
- package/lib/platforms/windows/hud/main.ps1 +423 -97
- package/lib/platforms/windows/hud/rendering.ps1 +1232 -1
- package/lib/platforms/windows/hud/snapshot.ps1 +47 -44
- package/lib/platforms/windows/hud-launcher.js +153 -79
- package/lib/platforms/windows/shared-bar-platform.js +972 -0
- package/lib/platforms/windows/terminal-compositor.js +210 -25
- package/lib/platforms/windows/wt-bar.js +729 -0
- package/lib/platforms/windows/wt-fragment.js +665 -0
- package/lib/platforms/windows/wt-keybinding.js +300 -0
- package/lib/providers/antigravity.js +314 -0
- package/package.json +8 -3
- package/vendor/PaneContext.cs +875 -0
- package/lib/README.md +0 -23
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,8 +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 { 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
|
+
import { canEditConfig, editDisplayConfig } from "./core/config-editor.js";
|
|
26
|
+
import { installCliPositionWrappers, posixCliWrapperDir, uninstallCliPositionWrappers } from "./core/cli-wrappers.js";
|
|
27
|
+
import { branchChanges, readGitBranchFast } from "./core/statusline-git.js";
|
|
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";
|
|
24
36
|
import {
|
|
25
37
|
cacheAgeSeconds,
|
|
26
38
|
clamp,
|
|
@@ -55,36 +67,42 @@ const DEFAULT_TAIL_BYTES = 4 * 1024 * 1024;
|
|
|
55
67
|
const DEFAULT_MAX_FILES = 40;
|
|
56
68
|
const CLAUDE_LIMIT_HIT_TAIL_BYTES = 256 * 1024;
|
|
57
69
|
const CLAUDE_LIMIT_HIT_MAX_FILES = 80;
|
|
58
|
-
const CLAUDE_CODEX_CACHE_SECONDS = 60;
|
|
59
|
-
const CLAUDE_CODEX_FALLBACK_CACHE_SECONDS = 15;
|
|
60
70
|
const BACKGROUND_USAGE_RUNNING_SECONDS = 5 * 60;
|
|
61
71
|
const DIVIDER = "│";
|
|
62
72
|
const PROVIDER_DIVIDER = "┃";
|
|
63
73
|
const DEFAULT_STATUSLINE_COLUMN_GUARD = 4;
|
|
64
74
|
const COMMANDS = new Set([
|
|
65
75
|
"setup",
|
|
76
|
+
"split",
|
|
77
|
+
"bar",
|
|
66
78
|
"reset",
|
|
67
79
|
"teardown",
|
|
68
80
|
"uninstall",
|
|
69
81
|
"doctor",
|
|
82
|
+
"config",
|
|
70
83
|
"hud",
|
|
71
84
|
"on",
|
|
72
85
|
"off",
|
|
73
86
|
"capture-claude",
|
|
87
|
+
"capture-antigravity",
|
|
74
88
|
"install-claude-statusline",
|
|
75
89
|
"uninstall-claude-statusline"
|
|
76
90
|
]);
|
|
77
|
-
const
|
|
78
|
-
const TEARDOWN_TARGETS = [
|
|
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
|
+
}
|
|
79
97
|
const CODEX_WRAPPER_MARKER = "AI_BATTERY_MANAGED_CODEX_WRAPPER";
|
|
80
98
|
const CODEX_WRAPPER_BRIDGE_MARKER = "AI_BATTERY_MANAGED_CODEX_BRIDGE";
|
|
81
99
|
const CODEX_PATH_LOOKUP_MARKER = "AI_BATTERY_CODEX_PATH_LOOKUP=1";
|
|
82
100
|
const CODEX_PATH_ONLY_MARKER = "AI_BATTERY_CODEX_PATH_ONLY=1";
|
|
83
101
|
const CODEX_PREFERRED_BACKUP_SUFFIX = ".ai-battery-original-link";
|
|
84
102
|
const CODEX_TIMESTAMP_BACKUP_MARKER = ".ai-battery-backup-";
|
|
85
|
-
const CODEX_STATUS_LINE =
|
|
103
|
+
const CODEX_STATUS_LINE = STATUS_LINE_ITEMS;
|
|
86
104
|
const DEFAULT_STATUSLINE_HEADER_COLUMN_GUARD = 2;
|
|
87
|
-
const CODEX_MENU_BAR_COLOR = "#
|
|
105
|
+
const CODEX_MENU_BAR_COLOR = "#000000";
|
|
88
106
|
const CLAUDE_MENU_BAR_COLOR = "#D97706";
|
|
89
107
|
const MENU_BAR_WHITE = "#FFFFFF";
|
|
90
108
|
const MENU_DETAIL_GREEN = "#30D158";
|
|
@@ -116,13 +134,23 @@ function parseArgs(argv) {
|
|
|
116
134
|
silent: false,
|
|
117
135
|
force: false,
|
|
118
136
|
wrapCodex: true,
|
|
119
|
-
configureCodexStatusLine:
|
|
137
|
+
configureCodexStatusLine: true,
|
|
138
|
+
providerOrder: null,
|
|
139
|
+
barPosition: null,
|
|
120
140
|
attachHud: false,
|
|
141
|
+
refreshProcesses: false,
|
|
142
|
+
paneDecisionProvider: null,
|
|
143
|
+
paneCleanupProvider: null,
|
|
144
|
+
sharedBarState: null,
|
|
145
|
+
ownerPid: 0,
|
|
146
|
+
paneCols: 0,
|
|
147
|
+
paneRows: 0,
|
|
121
148
|
header: true,
|
|
122
149
|
usageRow: "auto",
|
|
123
150
|
help: argv.length === 0,
|
|
124
151
|
helpTopic: "",
|
|
125
152
|
version: false,
|
|
153
|
+
subcommand: "",
|
|
126
154
|
targets: [],
|
|
127
155
|
rest: []
|
|
128
156
|
};
|
|
@@ -142,6 +170,16 @@ function parseArgs(argv) {
|
|
|
142
170
|
} else if (args.command === "reset" && !resetAliasSeen && !args.targets.length && ["settings", "config"].includes(arg)) {
|
|
143
171
|
// Keep the previous reset settings/config syntax for existing scripts.
|
|
144
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
|
+
}
|
|
145
183
|
} else if (!arg.startsWith("-") && ["setup", "reset", "teardown", "uninstall", "on", "off"].includes(args.command)) {
|
|
146
184
|
args.targets.push(arg);
|
|
147
185
|
} else if (arg === "--provider" || arg === "-p") {
|
|
@@ -172,8 +210,42 @@ function parseArgs(argv) {
|
|
|
172
210
|
args.wrapCodex = false;
|
|
173
211
|
} else if (arg === "--configure-codex-statusline") {
|
|
174
212
|
args.configureCodexStatusLine = true;
|
|
213
|
+
} else if (arg === "--provider-order") {
|
|
214
|
+
const value = requiredValue(argv, i, args.command);
|
|
215
|
+
try { args.providerOrder = parseOrder(value, PROVIDERS, "--provider-order"); }
|
|
216
|
+
catch { throw cliError("--provider-order requires unique comma-separated tools: codex, claude, gemini.", "--provider-order에 codex, claude, gemini를 쉼표로 구분하고 중복 없이 입력하세요.", args.command); }
|
|
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;
|
|
175
227
|
} else if (arg === "--attach-hud") {
|
|
176
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;
|
|
177
249
|
} else if (arg === "--watch" || arg === "-w") {
|
|
178
250
|
args.watch = true;
|
|
179
251
|
const maybeInterval = argv[i + 1];
|
|
@@ -225,17 +297,34 @@ function parseArgs(argv) {
|
|
|
225
297
|
}
|
|
226
298
|
|
|
227
299
|
args.helpTopic = commandSeen ? args.command : "";
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
if (
|
|
232
|
-
throw invalidChoice("--
|
|
300
|
+
args.provider = providerId(args.provider);
|
|
301
|
+
args.activeProvider = providerId(args.activeProvider);
|
|
302
|
+
args.targets = args.targets.map(normalizeTarget);
|
|
303
|
+
if (!["all", ...PROVIDERS].includes(args.provider)) {
|
|
304
|
+
throw invalidChoice("--provider", "all, codex, claude, gemini", args.helpTopic);
|
|
305
|
+
}
|
|
306
|
+
if (args.activeProvider && !PROVIDERS.includes(args.activeProvider)) {
|
|
307
|
+
throw invalidChoice("--active-provider", "codex, claude, gemini", args.helpTopic);
|
|
308
|
+
}
|
|
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
|
+
}
|
|
233
318
|
}
|
|
234
319
|
if (args.targets.length) {
|
|
235
|
-
const choices = args.command === "setup" ? [...PROVIDERS, "tmux", "all"]
|
|
320
|
+
const choices = args.command === "setup" ? [...PROVIDERS, "tmux", "split", "all"]
|
|
236
321
|
: ["on", "off"].includes(args.command) ? [...PROVIDERS, "all"] : [...TEARDOWN_TARGETS, "all"];
|
|
237
322
|
if (args.targets.some((target) => !choices.includes(target))) {
|
|
238
|
-
throw invalidChoice(
|
|
323
|
+
throw invalidChoice(
|
|
324
|
+
"target",
|
|
325
|
+
choices.map(target => (target === "antigravity" ? "gemini" : target)).join(", "),
|
|
326
|
+
args.command
|
|
327
|
+
);
|
|
239
328
|
}
|
|
240
329
|
}
|
|
241
330
|
|
|
@@ -291,6 +380,12 @@ function legacyStateDir() {
|
|
|
291
380
|
return homePath(".local", "state", "claudex-battery");
|
|
292
381
|
}
|
|
293
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
|
+
|
|
294
389
|
let windowsStateDirForWslMemo;
|
|
295
390
|
function windowsStateDirForWsl() {
|
|
296
391
|
// Account usage is shared between native Windows and WSL without sharing the
|
|
@@ -300,7 +395,7 @@ function windowsStateDirForWsl() {
|
|
|
300
395
|
if (override) return override;
|
|
301
396
|
// An explicit state directory is an isolation boundary for tests, portable
|
|
302
397
|
// installs, and users who do not want state written to the Windows profile.
|
|
303
|
-
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;
|
|
304
399
|
if (windowsStateDirForWslMemo !== undefined) return windowsStateDirForWslMemo;
|
|
305
400
|
|
|
306
401
|
// Cache the resolved path: the statusline can run every second (refreshInterval)
|
|
@@ -316,7 +411,8 @@ function windowsStateDirForWsl() {
|
|
|
316
411
|
|
|
317
412
|
let resolved = null;
|
|
318
413
|
try {
|
|
319
|
-
const
|
|
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 });
|
|
320
416
|
const winHome = String(home.stdout || "").trim();
|
|
321
417
|
if (home.status === 0 && /^[A-Za-z]:\\/.test(winHome)) {
|
|
322
418
|
const conv = spawnSync("wslpath", ["-u", winHome], { encoding: "utf8", timeout: 2000 });
|
|
@@ -341,14 +437,22 @@ function windowsStateDirForWsl() {
|
|
|
341
437
|
return resolved;
|
|
342
438
|
}
|
|
343
439
|
|
|
344
|
-
function
|
|
440
|
+
function sharedStateDir() {
|
|
441
|
+
const override = String(process.env.AI_BATTERY_SHARED_USAGE_STATE_DIR || "").trim();
|
|
442
|
+
if (override) return override;
|
|
345
443
|
return windowsStateDirForWsl() || stateDir();
|
|
346
444
|
}
|
|
347
445
|
|
|
446
|
+
function claudeStateDir() {
|
|
447
|
+
return sharedStateDir();
|
|
448
|
+
}
|
|
449
|
+
|
|
348
450
|
function codexUsageStateDir() {
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
451
|
+
return sharedStateDir();
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function displayConfigPath() {
|
|
455
|
+
return path.join(sharedStateDir(), "display-config.json");
|
|
352
456
|
}
|
|
353
457
|
|
|
354
458
|
function claudeCachePath() {
|
|
@@ -376,11 +480,14 @@ function defaultConfig() {
|
|
|
376
480
|
version: 1,
|
|
377
481
|
providers: {
|
|
378
482
|
codex: true,
|
|
379
|
-
claude: true
|
|
483
|
+
claude: true,
|
|
484
|
+
antigravity: true
|
|
380
485
|
},
|
|
486
|
+
providerOrder: [...PROVIDERS],
|
|
381
487
|
codexWrapper: null,
|
|
382
488
|
codexStatusLineBackup: null,
|
|
383
|
-
claudeStatusLineBackup: null
|
|
489
|
+
claudeStatusLineBackup: null,
|
|
490
|
+
antigravityStatusLineBackup: null
|
|
384
491
|
};
|
|
385
492
|
}
|
|
386
493
|
|
|
@@ -415,13 +522,151 @@ function writeConfig(config) {
|
|
|
415
522
|
writeJsonAtomic(configPath(), config);
|
|
416
523
|
}
|
|
417
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
|
+
|
|
418
635
|
const { installManagedText, removeManagedText, stripOwnedBlock } = createIntegrationFiles({ readConfig, writeConfig, writeTextAtomic });
|
|
419
636
|
|
|
420
637
|
function providerVisible(provider) {
|
|
421
|
-
const config =
|
|
638
|
+
const config = readDisplayConfig();
|
|
422
639
|
return config.providers?.[provider] !== false;
|
|
423
640
|
}
|
|
424
641
|
|
|
642
|
+
function configuredProviderOrder() {
|
|
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
|
+
};
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function antigravityAvailable() {
|
|
667
|
+
return antigravity.available();
|
|
668
|
+
}
|
|
669
|
+
|
|
425
670
|
function providerTargets(targets) {
|
|
426
671
|
const requested = targets.length ? targets : ["all"];
|
|
427
672
|
const providers = new Set();
|
|
@@ -431,14 +676,14 @@ function providerTargets(targets) {
|
|
|
431
676
|
} else if (PROVIDERS.includes(target)) {
|
|
432
677
|
providers.add(target);
|
|
433
678
|
} else {
|
|
434
|
-
throw new Error("target must be one of: codex, claude, all");
|
|
679
|
+
throw new Error("target must be one of: codex, claude, gemini, all");
|
|
435
680
|
}
|
|
436
681
|
}
|
|
437
682
|
return [...providers];
|
|
438
683
|
}
|
|
439
684
|
|
|
440
685
|
function teardownTargets(targets) {
|
|
441
|
-
const requested = targets.length ? targets : ["all"];
|
|
686
|
+
const requested = targets.length ? targets.map(normalizeTarget) : ["all"];
|
|
442
687
|
const selected = new Set();
|
|
443
688
|
for (const target of requested) {
|
|
444
689
|
if (target === "all") {
|
|
@@ -446,7 +691,7 @@ function teardownTargets(targets) {
|
|
|
446
691
|
} else if (TEARDOWN_TARGETS.includes(target)) {
|
|
447
692
|
selected.add(target);
|
|
448
693
|
} else {
|
|
449
|
-
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");
|
|
450
695
|
}
|
|
451
696
|
}
|
|
452
697
|
return [...selected];
|
|
@@ -454,13 +699,11 @@ function teardownTargets(targets) {
|
|
|
454
699
|
|
|
455
700
|
function setProviderVisibility(targets, visible) {
|
|
456
701
|
const providers = providerTargets(targets);
|
|
457
|
-
const
|
|
458
|
-
|
|
459
|
-
config.providers[provider] = visible;
|
|
460
|
-
}
|
|
461
|
-
writeConfig(config);
|
|
702
|
+
const patch = Object.fromEntries(providers.map(provider => [provider, visible]));
|
|
703
|
+
updateDisplayConfig({ providers: patch });
|
|
462
704
|
return {
|
|
463
705
|
configPath: configPath(),
|
|
706
|
+
displayConfigPath: displayConfigPath(),
|
|
464
707
|
providers,
|
|
465
708
|
visible
|
|
466
709
|
};
|
|
@@ -897,20 +1140,80 @@ function shellRcPath() {
|
|
|
897
1140
|
|
|
898
1141
|
function shellPathBlock(shimDir) {
|
|
899
1142
|
const shell = path.basename(process.env.SHELL || "");
|
|
1143
|
+
const cliDir = posixCliWrapperDir(userHome());
|
|
1144
|
+
const dirs = samePath(cliDir, shimDir) ? [shimDir] : [cliDir, shimDir];
|
|
900
1145
|
if (shell === "fish") {
|
|
901
|
-
|
|
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
|
+
}
|
|
902
1199
|
}
|
|
903
|
-
return
|
|
1200
|
+
return result;
|
|
904
1201
|
}
|
|
905
1202
|
|
|
906
1203
|
function tmuxStatusBarActive() {
|
|
907
1204
|
const override = String(process.env.AI_BATTERY_TMUX || process.env.CLAUDEX_BATTERY_TMUX || "").toLowerCase();
|
|
908
1205
|
if (override === "row") return false;
|
|
909
1206
|
if (["status", "plain", "off"].includes(override)) return true;
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
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";
|
|
914
1217
|
}
|
|
915
1218
|
|
|
916
1219
|
function booleanEnvValue(value) {
|
|
@@ -925,12 +1228,18 @@ function claudeUsageRowVisible(args) {
|
|
|
925
1228
|
if (args.usageRow === true || args.usageRow === false) return args.usageRow;
|
|
926
1229
|
const envValue = booleanEnvValue(process.env.AI_BATTERY_CLAUDE_USAGE_ROW ?? process.env.CLAUDEX_BATTERY_CLAUDE_USAGE_ROW);
|
|
927
1230
|
if (envValue !== null) return envValue;
|
|
928
|
-
if (process.platform === "win32") return false;
|
|
1231
|
+
if (process.platform === "win32" && args.attachHud) return false;
|
|
929
1232
|
return !tmuxStatusBarActive();
|
|
930
1233
|
}
|
|
931
1234
|
|
|
932
1235
|
function tmuxConfPath() {
|
|
933
|
-
|
|
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;
|
|
934
1243
|
}
|
|
935
1244
|
|
|
936
1245
|
function removeAiBatteryTmuxBlock(text) {
|
|
@@ -950,26 +1259,12 @@ function extractExistingStatusRight(confText) {
|
|
|
950
1259
|
return last;
|
|
951
1260
|
}
|
|
952
1261
|
|
|
953
|
-
function tmuxStatusBlock(
|
|
954
|
-
|
|
955
|
-
// giving the responsive layout the actual terminal width to work with.
|
|
956
|
-
const battery = `${shQuote(process.execPath)} ${shQuote(path.join(scriptDir(), "ai-battery.js"))} --tmux --bar-width 8 --max-width #{client_width}`;
|
|
957
|
-
const batteryPart = `#(${battery})`;
|
|
958
|
-
// Put the battery on the far right so tmux left-clips the existing text before
|
|
959
|
-
// the bar. When the block is uninstalled, the earlier set -g status-right wins.
|
|
960
|
-
const statusRightValue = existingStatusRight
|
|
961
|
-
? `${existingStatusRight} ${batteryPart} `
|
|
962
|
-
: `${batteryPart} `;
|
|
963
|
-
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)}`;
|
|
964
1264
|
return [
|
|
965
1265
|
"\n# >>> ai-battery tmux >>>",
|
|
966
|
-
"#
|
|
967
|
-
|
|
968
|
-
"set-environment -g AI_BATTERY_TMUX_STATUS 1",
|
|
969
|
-
"set -g status on",
|
|
970
|
-
"set -g status-interval 10",
|
|
971
|
-
`set-option -g status-right-length ${rightLength}`,
|
|
972
|
-
`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, '\\"')}"`,
|
|
973
1268
|
"# <<< ai-battery tmux <<<",
|
|
974
1269
|
""
|
|
975
1270
|
].join("\n");
|
|
@@ -985,19 +1280,24 @@ function installTmuxStatus({ confPath = tmuxConfPath() } = {}) {
|
|
|
985
1280
|
} catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
986
1281
|
const withoutBlock = stripOwnedBlock(confPath, existing, removeAiBatteryTmuxBlock);
|
|
987
1282
|
const existingStatusRight = extractExistingStatusRight(withoutBlock);
|
|
988
|
-
const next = `${withoutBlock}${tmuxStatusBlock(
|
|
1283
|
+
const next = `${withoutBlock}${tmuxStatusBlock(confPath)}`;
|
|
989
1284
|
if (next !== existing) installManagedText(confPath, next, next.slice(withoutBlock.length));
|
|
990
1285
|
let active = false;
|
|
991
1286
|
let error = null;
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
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 });
|
|
1001
1301
|
active = !result.error && result.status === 0;
|
|
1002
1302
|
if (!active) error = result.error?.message || result.stderr?.trim() || "Could not apply the tmux status bar";
|
|
1003
1303
|
}
|
|
@@ -1017,6 +1317,8 @@ function uninstallTmuxStatus() {
|
|
|
1017
1317
|
const confPath = tmuxConfPath();
|
|
1018
1318
|
const records = readConfig({ strict: true }).integrationFiles || {};
|
|
1019
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 });
|
|
1020
1322
|
const changedPaths = paths.filter(file => removeManagedText(file, removeAiBatteryTmuxBlock));
|
|
1021
1323
|
return { changed: changedPaths.length > 0, confPath, changedPaths };
|
|
1022
1324
|
}
|
|
@@ -1369,6 +1671,13 @@ function codexStatusLineMatches(text) {
|
|
|
1369
1671
|
&& useColors === "false";
|
|
1370
1672
|
}
|
|
1371
1673
|
|
|
1674
|
+
function managedCodexStatusLineMatches(text) {
|
|
1675
|
+
if (codexStatusLineMatches(text)) return true;
|
|
1676
|
+
// Keep reset compatible with the three-item configuration installed before 0.1.29.
|
|
1677
|
+
return isDeepStrictEqual(parseTomlStringArray(tomlSectionValue(text, "tui", "status_line")), ["model-with-reasoning", "current-dir", "git-branch"])
|
|
1678
|
+
&& String(tomlSectionValue(text, "tui", "status_line_use_colors") || "").toLowerCase() === "false";
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1372
1681
|
function managedCodexStatusLineText(text) {
|
|
1373
1682
|
return upsertTomlSectionKeys(text || "", "tui", codexStatusLineSettings());
|
|
1374
1683
|
}
|
|
@@ -1469,7 +1778,7 @@ function restoreCodexStatusLine(config) {
|
|
|
1469
1778
|
}
|
|
1470
1779
|
|
|
1471
1780
|
const currentText = fs.readFileSync(configPath, "utf8");
|
|
1472
|
-
if (!
|
|
1781
|
+
if (!managedCodexStatusLineMatches(currentText) && codexStatusLineValuesMatch(currentText, backup.text)) {
|
|
1473
1782
|
config.codexStatusLineBackup = null;
|
|
1474
1783
|
return {
|
|
1475
1784
|
changed: false,
|
|
@@ -1480,7 +1789,7 @@ function restoreCodexStatusLine(config) {
|
|
|
1480
1789
|
};
|
|
1481
1790
|
}
|
|
1482
1791
|
if (backup.text === null) {
|
|
1483
|
-
if (!
|
|
1792
|
+
if (!managedCodexStatusLineMatches(currentText)) {
|
|
1484
1793
|
return {
|
|
1485
1794
|
changed: false,
|
|
1486
1795
|
skipped: true,
|
|
@@ -1503,7 +1812,7 @@ function restoreCodexStatusLine(config) {
|
|
|
1503
1812
|
};
|
|
1504
1813
|
}
|
|
1505
1814
|
|
|
1506
|
-
if (!
|
|
1815
|
+
if (!managedCodexStatusLineMatches(currentText)) {
|
|
1507
1816
|
return {
|
|
1508
1817
|
changed: false,
|
|
1509
1818
|
skipped: true,
|
|
@@ -1634,12 +1943,15 @@ function removeManagedCodexBridge(wrapperPath) {
|
|
|
1634
1943
|
return null;
|
|
1635
1944
|
}
|
|
1636
1945
|
|
|
1637
|
-
function uninstallCodexWrapper() {
|
|
1946
|
+
function uninstallCodexWrapper({ extraWindowsOwnedShimDirs = [] } = {}) {
|
|
1638
1947
|
const config = readConfig({ strict: true });
|
|
1639
1948
|
const statusLine = restoreCodexStatusLine(config);
|
|
1640
1949
|
if (statusLine.clearedBackup) writeConfig(config);
|
|
1641
1950
|
const candidates = codexWrapperCandidates(config);
|
|
1642
|
-
const windowsOwnedShimDirs =
|
|
1951
|
+
const windowsOwnedShimDirs = [...new Set([
|
|
1952
|
+
...windowsOwnedShimDirsForUninstall(config),
|
|
1953
|
+
...(Array.isArray(extraWindowsOwnedShimDirs) ? extraWindowsOwnedShimDirs : [])
|
|
1954
|
+
].filter(Boolean))];
|
|
1643
1955
|
const unmanaged = [];
|
|
1644
1956
|
const skippedWrappers = [];
|
|
1645
1957
|
const removedWrappers = [];
|
|
@@ -2013,7 +2325,7 @@ function diagnoseClaudeStatusLine() {
|
|
|
2013
2325
|
const managed = managedClaudeStatusLine(statusLine);
|
|
2014
2326
|
const needsRefresh = process.platform === "win32"
|
|
2015
2327
|
&& managed
|
|
2016
|
-
&&
|
|
2328
|
+
&& command.includes("--attach-hud");
|
|
2017
2329
|
return {
|
|
2018
2330
|
settingsPath,
|
|
2019
2331
|
configured: Boolean(statusLine),
|
|
@@ -2046,16 +2358,20 @@ async function runDoctor() {
|
|
|
2046
2358
|
},
|
|
2047
2359
|
stateDir: stateDir(),
|
|
2048
2360
|
configPath: configPath(),
|
|
2361
|
+
displayConfigPath: displayConfigPath(),
|
|
2049
2362
|
recovery: {
|
|
2050
2363
|
codexWrapper: Boolean(recoveryConfig.codexWrapper),
|
|
2051
2364
|
codexStatusLine: Boolean(recoveryConfig.codexStatusLineBackup),
|
|
2052
2365
|
claudeStatusLine: Boolean(recoveryConfig.claudeStatusLineBackup),
|
|
2366
|
+
antigravityStatusLine: Boolean(recoveryConfig.antigravityStatusLineBackup),
|
|
2053
2367
|
claudeOriginalKnown: recoveryConfig.claudeStatusLineBackup
|
|
2054
2368
|
? !recoveryConfig.claudeStatusLineBackup.legacyOriginalUnknown
|
|
2055
2369
|
: null
|
|
2056
2370
|
}
|
|
2057
2371
|
},
|
|
2372
|
+
...((process.platform === "win32" || isWsl()) ? { split: diagnoseSharedBar() } : {}),
|
|
2058
2373
|
codex: diagnoseCodex(),
|
|
2374
|
+
antigravity: antigravity.diagnose(),
|
|
2059
2375
|
...(process.platform !== "win32" ? { tmux: diagnoseTmux() } : {}),
|
|
2060
2376
|
claude: {
|
|
2061
2377
|
providerEnabled: providerVisible("claude"),
|
|
@@ -2237,22 +2553,32 @@ function uninstallRowPtyHost() {
|
|
|
2237
2553
|
}
|
|
2238
2554
|
|
|
2239
2555
|
function setupTargets(targets) {
|
|
2240
|
-
const requested = targets.length ? targets : ["all"];
|
|
2556
|
+
const requested = targets.length ? targets.map(normalizeTarget) : ["all"];
|
|
2241
2557
|
const selected = new Set();
|
|
2242
2558
|
for (const target of requested) {
|
|
2243
2559
|
if (target === "all") {
|
|
2244
|
-
//
|
|
2560
|
+
// Prepare native split integration where reachable. tmux remains opt-in.
|
|
2245
2561
|
PROVIDERS.forEach((provider) => selected.add(provider));
|
|
2246
|
-
|
|
2562
|
+
if (process.platform === "win32" || isWslWtContext()) selected.add("split");
|
|
2563
|
+
} else if (PROVIDERS.includes(target) || ["tmux", "split"].includes(target)) {
|
|
2247
2564
|
selected.add(target);
|
|
2248
2565
|
} else {
|
|
2249
|
-
throw new Error("target must be one of: codex, claude, tmux, all");
|
|
2566
|
+
throw new Error("target must be one of: codex, claude, gemini, tmux, split, all");
|
|
2250
2567
|
}
|
|
2251
2568
|
}
|
|
2252
2569
|
return [...selected];
|
|
2253
2570
|
}
|
|
2254
2571
|
|
|
2255
2572
|
function runSetup(args) {
|
|
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
|
+
}
|
|
2581
|
+
}
|
|
2256
2582
|
const targets = setupTargets(args.targets);
|
|
2257
2583
|
const previous = readConfig({ strict: true });
|
|
2258
2584
|
let tmuxRefreshPath = null;
|
|
@@ -2268,19 +2594,68 @@ function runSetup(args) {
|
|
|
2268
2594
|
}
|
|
2269
2595
|
}
|
|
2270
2596
|
const results = {};
|
|
2271
|
-
let windowsClaudeLauncher = null;
|
|
2272
2597
|
if (targets.includes("claude")) {
|
|
2273
2598
|
const statusLine = installClaudeStatusline(args);
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
}
|
|
2599
|
+
results.claude = statusLine;
|
|
2600
|
+
}
|
|
2601
|
+
if (targets.includes("antigravity")) results.antigravity = antigravity.install(args);
|
|
2602
|
+
if (targets.includes("claude") || targets.includes("antigravity")) {
|
|
2603
|
+
ensureCliPositionWrappers(targets, { updateShellPath: true });
|
|
2280
2604
|
}
|
|
2281
2605
|
if (targets.includes("tmux")) {
|
|
2282
2606
|
results.tmux = installTmuxStatus(tmuxRefreshPath ? { confPath: tmuxRefreshPath } : {});
|
|
2283
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
|
+
}
|
|
2284
2659
|
if (targets.includes("codex")) {
|
|
2285
2660
|
const wrapCodex = args.wrapCodex;
|
|
2286
2661
|
const statusLine = args.configureCodexStatusLine ? installCodexStatusLine(args) : null;
|
|
@@ -2300,13 +2675,11 @@ function runSetup(args) {
|
|
|
2300
2675
|
results.codex.providerEnabled = providerVisible("codex");
|
|
2301
2676
|
if (process.platform === "win32" && wrapCodex) {
|
|
2302
2677
|
results.codex.rowpty = windowsSetupNeedsRowPty()
|
|
2303
|
-
?
|
|
2678
|
+
? installRowPtyHost()
|
|
2304
2679
|
: {
|
|
2305
2680
|
ok: true,
|
|
2306
2681
|
skipped: true,
|
|
2307
|
-
reason:
|
|
2308
|
-
? "Installed with the Windows Claude HUD launcher; not required by the current Codex layout"
|
|
2309
|
-
: "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"
|
|
2310
2683
|
};
|
|
2311
2684
|
}
|
|
2312
2685
|
}
|
|
@@ -2316,6 +2689,7 @@ function runSetup(args) {
|
|
|
2316
2689
|
function setupResultFailed(result) {
|
|
2317
2690
|
return Boolean(
|
|
2318
2691
|
result.claude?.error
|
|
2692
|
+
|| result.antigravity?.error
|
|
2319
2693
|
|| result.claude?.launcher?.error
|
|
2320
2694
|
|| (result.claude?.launcher && result.claude.launcher.ok === false)
|
|
2321
2695
|
|| (result.codex && result.codex.ok === false)
|
|
@@ -2324,6 +2698,7 @@ function setupResultFailed(result) {
|
|
|
2324
2698
|
|| result.codex?.statusLine?.error
|
|
2325
2699
|
|| result.codex?.rowpty?.error
|
|
2326
2700
|
|| (result.codex?.rowpty && result.codex.rowpty.ok === false)
|
|
2701
|
+
|| (result.split && result.split.ok === false)
|
|
2327
2702
|
|| (result.tmux && result.tmux.ok === false && !result.tmux.skipped)
|
|
2328
2703
|
);
|
|
2329
2704
|
}
|
|
@@ -2395,15 +2770,42 @@ function runTeardown(args) {
|
|
|
2395
2770
|
}
|
|
2396
2771
|
};
|
|
2397
2772
|
|
|
2773
|
+
let removedWinCliWrappers = false;
|
|
2398
2774
|
if (targets.includes("claude")) {
|
|
2399
|
-
runStep("claude", () =>
|
|
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
|
+
});
|
|
2400
2787
|
}
|
|
2401
2788
|
if (targets.includes("codex")) {
|
|
2402
|
-
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. */ }
|
|
2403
2801
|
}
|
|
2404
2802
|
if (targets.includes("tmux")) {
|
|
2405
2803
|
runStep("tmux", uninstallTmuxStatus);
|
|
2406
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
|
+
}
|
|
2407
2809
|
if (targets.includes("hud")) {
|
|
2408
2810
|
runStep("hud", uninstallHud);
|
|
2409
2811
|
}
|
|
@@ -2416,11 +2818,14 @@ function runTeardown(args) {
|
|
|
2416
2818
|
return { targets, fullReset, results };
|
|
2417
2819
|
}
|
|
2418
2820
|
const roots = [stateDir(), dataDir(), path.join(os.tmpdir(), "ai-battery")];
|
|
2419
|
-
if (process.platform === "win32" && process.env.LOCALAPPDATA
|
|
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
|
+
}
|
|
2420
2825
|
results.artifacts = cleanupBatteryArtifacts({
|
|
2421
2826
|
roots,
|
|
2422
2827
|
home: userHome(),
|
|
2423
|
-
protectedRoots: [codexRuntimeHome(), homePath(".claude"), path.resolve(scriptDir(), "..")]
|
|
2828
|
+
protectedRoots: [codexRuntimeHome(), homePath(".claude"), homePath(".gemini"), path.resolve(scriptDir(), "..")]
|
|
2424
2829
|
});
|
|
2425
2830
|
}
|
|
2426
2831
|
return {
|
|
@@ -2497,10 +2902,18 @@ function readHead(filePath, bytes = 32 * 1024) {
|
|
|
2497
2902
|
}
|
|
2498
2903
|
}
|
|
2499
2904
|
|
|
2500
|
-
function latestMatchingJsonLine(files, predicate, acceptParsed = null) {
|
|
2905
|
+
function latestMatchingJsonLine(files, predicate, acceptParsed = null, newestTimestamp = false) {
|
|
2501
2906
|
let fallback = null;
|
|
2907
|
+
let newest = null;
|
|
2908
|
+
let newestMs = 0;
|
|
2502
2909
|
|
|
2503
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
|
+
}
|
|
2504
2917
|
const text = readTail(file.path);
|
|
2505
2918
|
const lines = text.split("\n");
|
|
2506
2919
|
|
|
@@ -2511,14 +2924,21 @@ function latestMatchingJsonLine(files, predicate, acceptParsed = null) {
|
|
|
2511
2924
|
try {
|
|
2512
2925
|
const json = JSON.parse(line);
|
|
2513
2926
|
if (acceptParsed && !acceptParsed(json)) continue;
|
|
2514
|
-
|
|
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;
|
|
2515
2935
|
} catch {
|
|
2516
2936
|
fallback = fallback || { error: "Found a matching line but could not parse it", file: file.path };
|
|
2517
2937
|
}
|
|
2518
2938
|
}
|
|
2519
2939
|
}
|
|
2520
2940
|
|
|
2521
|
-
return fallback;
|
|
2941
|
+
return newest || fallback;
|
|
2522
2942
|
}
|
|
2523
2943
|
|
|
2524
2944
|
function codexSessionMeta(filePath) {
|
|
@@ -2607,7 +3027,7 @@ function writeJsonAtomic(filePath, data, mode = 0o600) {
|
|
|
2607
3027
|
const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
2608
3028
|
try {
|
|
2609
3029
|
fs.writeFileSync(tempPath, `${JSON.stringify(data, null, 2)}\n`, { mode });
|
|
2610
|
-
|
|
3030
|
+
atomicRename(tempPath, targetPath);
|
|
2611
3031
|
} catch (error) {
|
|
2612
3032
|
try {
|
|
2613
3033
|
fs.rmSync(tempPath, { force: true });
|
|
@@ -2624,7 +3044,7 @@ function writeTextAtomic(filePath, text, mode = 0o600) {
|
|
|
2624
3044
|
const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
2625
3045
|
try {
|
|
2626
3046
|
fs.writeFileSync(tempPath, text, { mode });
|
|
2627
|
-
|
|
3047
|
+
atomicRename(tempPath, targetPath);
|
|
2628
3048
|
} catch (error) {
|
|
2629
3049
|
try {
|
|
2630
3050
|
fs.rmSync(tempPath, { force: true });
|
|
@@ -2646,7 +3066,9 @@ function readJson(filePath) {
|
|
|
2646
3066
|
function teardownResultFailed(result) {
|
|
2647
3067
|
return Object.values(result.results || {}).some((item) => Boolean(
|
|
2648
3068
|
item?.error
|
|
3069
|
+
|| item?.ok === false
|
|
2649
3070
|
|| item?.errors?.length
|
|
3071
|
+
|| item?.retained === true
|
|
2650
3072
|
|| item?.retainedConfig
|
|
2651
3073
|
|| item?.retainedBackup
|
|
2652
3074
|
|| item?.skippedWrappers?.length
|
|
@@ -2747,6 +3169,11 @@ const {
|
|
|
2747
3169
|
scanCacheSeconds,
|
|
2748
3170
|
writeScanCache
|
|
2749
3171
|
});
|
|
3172
|
+
const antigravity = createAntigravityIntegration({
|
|
3173
|
+
homePath, stateDir, usageStateDir: codexUsageStateDir, readJson, readUserJsonObject, readConfig, writeConfig,
|
|
3174
|
+
writeJsonAtomic, samePath, shellArg, scriptDir, isProviderRunning, providerVisible
|
|
3175
|
+
});
|
|
3176
|
+
|
|
2750
3177
|
function readStdin() {
|
|
2751
3178
|
return new Promise((resolve, reject) => {
|
|
2752
3179
|
let input = "";
|
|
@@ -2799,6 +3226,12 @@ function normalizeClaudeCachedLimit(limit, options = {}) {
|
|
|
2799
3226
|
});
|
|
2800
3227
|
}
|
|
2801
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
|
+
|
|
2802
3235
|
function claudeCanonicalLimit(candidate, previous) {
|
|
2803
3236
|
if (!candidate) return previous ?? null;
|
|
2804
3237
|
if (!previous) return candidate;
|
|
@@ -2808,9 +3241,23 @@ function claudeCanonicalLimit(candidate, previous) {
|
|
|
2808
3241
|
if (!candidateNorm) return previous;
|
|
2809
3242
|
if (!previousNorm) return candidate;
|
|
2810
3243
|
|
|
3244
|
+
const winMin = candidateNorm.windowMinutes ?? previousNorm.windowMinutes ?? 10080;
|
|
2811
3245
|
const candidateReset = resetEpochSeconds(candidate.resets_at ?? candidate.resetsAt ?? candidate.reset_at ?? candidate.resetAt);
|
|
2812
3246
|
const previousReset = resetEpochSeconds(previous.resets_at ?? previous.resetsAt ?? previous.reset_at ?? previous.resetAt);
|
|
2813
|
-
|
|
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;
|
|
2814
3261
|
return candidateReset > previousReset ? candidate : previous;
|
|
2815
3262
|
}
|
|
2816
3263
|
|
|
@@ -3022,14 +3469,31 @@ function scanClaudeRateLimitHit() {
|
|
|
3022
3469
|
|
|
3023
3470
|
let claudeRateLimitHitMemo = null;
|
|
3024
3471
|
|
|
3472
|
+
function sharedClaudeRateLimitHitPath() {
|
|
3473
|
+
return path.join(sharedStateDir(), "claude-rate-limit-hit.json");
|
|
3474
|
+
}
|
|
3475
|
+
|
|
3025
3476
|
function latestClaudeRateLimitHit() {
|
|
3026
3477
|
if (claudeRateLimitHitMemo && Date.now() - claudeRateLimitHitMemo.at < 5000) {
|
|
3027
3478
|
return claudeRateLimitHitMemo.value;
|
|
3028
3479
|
}
|
|
3029
3480
|
|
|
3030
|
-
const cached = readScanCache("claude-rate-limit-hit", scanCacheSeconds(
|
|
3031
|
-
|
|
3032
|
-
if (!cached)
|
|
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
|
+
}
|
|
3033
3497
|
claudeRateLimitHitMemo = { at: Date.now(), value };
|
|
3034
3498
|
return value;
|
|
3035
3499
|
}
|
|
@@ -3060,11 +3524,11 @@ function applyClaudeRateLimitHit(limit, hit, window) {
|
|
|
3060
3524
|
function captureClaudeStatusline(input) {
|
|
3061
3525
|
const rateLimits = claudeRateLimitsFromStatusline(input);
|
|
3062
3526
|
const sessionId = input.session_id ?? input.sessionId ?? null;
|
|
3063
|
-
const
|
|
3064
|
-
const
|
|
3527
|
+
const globalPath = claudeCachePath();
|
|
3528
|
+
const previousSession = sessionId ? readJson(claudeSessionCachePath(sessionId)) : null;
|
|
3065
3529
|
const sessionKind = claudeStatuslineSessionKind(input);
|
|
3066
3530
|
const contextWindow = claudeContextWindowFromStatusline(input);
|
|
3067
|
-
|
|
3531
|
+
const baseSnapshot = {
|
|
3068
3532
|
version: 1,
|
|
3069
3533
|
provider: "claude",
|
|
3070
3534
|
sourceType: "statusline",
|
|
@@ -3090,26 +3554,66 @@ function captureClaudeStatusline(input) {
|
|
|
3090
3554
|
contextWindow
|
|
3091
3555
|
};
|
|
3092
3556
|
|
|
3093
|
-
|
|
3094
|
-
const
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
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
|
+
}
|
|
3100
3574
|
}
|
|
3101
|
-
|
|
3102
|
-
|
|
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
|
+
}
|
|
3103
3607
|
}
|
|
3608
|
+
} else {
|
|
3609
|
+
snapshot = mergeWithGlobal(readJson(globalPath));
|
|
3104
3610
|
}
|
|
3105
3611
|
|
|
3106
|
-
snapshot = claudeCanonicalStatuslineSnapshot(snapshot, previousGlobal);
|
|
3107
|
-
|
|
3108
3612
|
if (snapshot.sessionId) {
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
|
|
3112
|
-
|
|
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
|
+
}
|
|
3113
3617
|
}
|
|
3114
3618
|
return snapshot;
|
|
3115
3619
|
}
|
|
@@ -3188,19 +3692,35 @@ function readClaudeStatuslineCacheFrom(root) {
|
|
|
3188
3692
|
return [globalCachePath, ...sessionCachePaths].some((cachePath) => fs.existsSync(cachePath)) ? null : undefined;
|
|
3189
3693
|
}
|
|
3190
3694
|
|
|
3191
|
-
function
|
|
3192
|
-
const
|
|
3193
|
-
|
|
3194
|
-
|
|
3195
|
-
|
|
3196
|
-
|
|
3197
|
-
|
|
3198
|
-
const
|
|
3199
|
-
|
|
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
|
+
}
|
|
3200
3716
|
}
|
|
3717
|
+
return (Date.parse(b?.timestamp || "") || 0) - (Date.parse(a?.timestamp || "") || 0);
|
|
3718
|
+
}
|
|
3201
3719
|
|
|
3202
|
-
|
|
3203
|
-
|
|
3720
|
+
function readClaudeStatuslineCache() {
|
|
3721
|
+
const readings = uniquePaths([claudeStateDir(), stateDir(), legacyStateDir()])
|
|
3722
|
+
.map(root => readClaudeStatuslineCacheFrom(root)).filter(Boolean);
|
|
3723
|
+
return readings.sort(claudeReadingCompare)[0] ?? null;
|
|
3204
3724
|
}
|
|
3205
3725
|
|
|
3206
3726
|
function claudeStatuslineRefreshInterval() {
|
|
@@ -3230,9 +3750,9 @@ function installClaudeStatusline(args) {
|
|
|
3230
3750
|
"--left-padding",
|
|
3231
3751
|
"1"
|
|
3232
3752
|
];
|
|
3233
|
-
if (args.
|
|
3753
|
+
if (args.header === false) commandParts.push("--no-header");
|
|
3754
|
+
if (args.usageRow === false) commandParts.push("--no-usage-row");
|
|
3234
3755
|
if (args.usageRow === true) commandParts.push("--usage-row");
|
|
3235
|
-
if (process.platform === "win32") commandParts.push("--attach-hud");
|
|
3236
3756
|
const command = commandParts.join(" ");
|
|
3237
3757
|
const installedByAiBattery = managedClaudeStatusLine(existing.statusLine);
|
|
3238
3758
|
const config = readConfig({ strict: true });
|
|
@@ -3355,7 +3875,7 @@ function codexSharedLimit(limit) {
|
|
|
3355
3875
|
|
|
3356
3876
|
function codexAccountUsageSnapshot(scan) {
|
|
3357
3877
|
if (!scan?.ok || codexUsageTimestamp(scan) === null) return null;
|
|
3358
|
-
if (![scan.percentRemaining, scan.primary?.
|
|
3878
|
+
if (![scan.percentRemaining, scan.primary?.remainingPercent, scan.secondary?.remainingPercent].some(Number.isFinite)) return null;
|
|
3359
3879
|
return {
|
|
3360
3880
|
timestamp: scan.timestamp,
|
|
3361
3881
|
planType: scan.planType ?? null,
|
|
@@ -3377,33 +3897,33 @@ function readCodexAccountUsage() {
|
|
|
3377
3897
|
function writeCodexAccountUsage(scan) {
|
|
3378
3898
|
const usage = codexAccountUsageSnapshot(scan);
|
|
3379
3899
|
if (!usage) return false;
|
|
3380
|
-
|
|
3381
|
-
const existingTimestamp = codexUsageTimestamp(existing);
|
|
3382
|
-
const usageTimestamp = codexUsageTimestamp(usage);
|
|
3383
|
-
if (existingTimestamp > usageTimestamp) return false;
|
|
3384
|
-
if (existingTimestamp === usageTimestamp && isDeepStrictEqual(existing, usage)) return false;
|
|
3385
|
-
try {
|
|
3386
|
-
writeJsonAtomic(codexAccountUsagePath(), {
|
|
3900
|
+
return publishNewest(codexAccountUsagePath(), {
|
|
3387
3901
|
version: CODEX_ACCOUNT_USAGE_VERSION,
|
|
3388
3902
|
capturedAt: new Date().toISOString(),
|
|
3389
3903
|
usage
|
|
3390
|
-
});
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
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)) };
|
|
3395
3912
|
}
|
|
3396
3913
|
|
|
3397
3914
|
function mergeCodexAccountUsage(scan, sharedUsage) {
|
|
3398
3915
|
if (!sharedUsage || codexUsageTimestamp(sharedUsage) === null) return scan;
|
|
3399
3916
|
const localTimestamp = codexUsageTimestamp(scan);
|
|
3400
|
-
if (scan?.ok && localTimestamp !== null && localTimestamp
|
|
3917
|
+
if (scan?.ok && localTimestamp !== null && localTimestamp > codexUsageTimestamp(sharedUsage)) return scan;
|
|
3918
|
+
if (scan?.ok && localTimestamp === codexUsageTimestamp(sharedUsage) && isDeepStrictEqual(codexAccountUsageSnapshot(scan), sharedUsage)) return scan;
|
|
3401
3919
|
|
|
3402
3920
|
const result = {
|
|
3403
3921
|
...(scan && typeof scan === "object" ? scan : {}),
|
|
3404
3922
|
provider: "codex",
|
|
3405
3923
|
ok: true,
|
|
3406
3924
|
...sharedUsage,
|
|
3925
|
+
primary: codexLimitWithResetsIn(sharedUsage.primary),
|
|
3926
|
+
secondary: codexLimitWithResetsIn(sharedUsage.secondary),
|
|
3407
3927
|
sharedUsage: true,
|
|
3408
3928
|
usageUpdate: {
|
|
3409
3929
|
timestamp: sharedUsage.timestamp,
|
|
@@ -3560,17 +4080,20 @@ function readCodex(options = {}) {
|
|
|
3560
4080
|
.digest("hex");
|
|
3561
4081
|
// Changed usage logs must be visible on the next poll, even within the TTL.
|
|
3562
4082
|
let scan = cached?.value;
|
|
3563
|
-
|
|
3564
|
-
|
|
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;
|
|
3565
4088
|
if (!scan || typeof scan !== "object") {
|
|
3566
4089
|
if (options.cachedOnly) return null;
|
|
3567
4090
|
scan = scanCodexStatus(files, roots);
|
|
3568
|
-
writeScanCache("codex-status", scan, { inputFingerprint });
|
|
4091
|
+
writeScanCache("codex-status", scan, { inputFingerprint, usageEventOrder: "timestamp" });
|
|
3569
4092
|
}
|
|
3570
4093
|
writeCodexAccountUsage(scan);
|
|
3571
4094
|
scan = mergeCodexAccountUsage(scan, readCodexAccountUsage());
|
|
3572
4095
|
|
|
3573
|
-
const processes = options.includeRunning === false ? null : scanProcessCommands();
|
|
4096
|
+
const processes = options.includeRunning === false ? null : scanProcessCommands(options.processOptions);
|
|
3574
4097
|
const running = typeof options.runningOverride === "boolean"
|
|
3575
4098
|
? options.runningOverride
|
|
3576
4099
|
: (
|
|
@@ -3582,22 +4105,48 @@ function readCodex(options = {}) {
|
|
|
3582
4105
|
? codexBackgroundReadyInProcesses(processes)
|
|
3583
4106
|
: Boolean(scan.backgroundReady);
|
|
3584
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
|
+
}
|
|
3585
4126
|
if (result.ok) result.ageSeconds = cacheAgeSeconds(result.timestamp ?? null);
|
|
3586
4127
|
return result;
|
|
3587
4128
|
}
|
|
3588
4129
|
|
|
3589
|
-
function
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
|
|
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
|
+
}
|
|
3597
4147
|
|
|
3598
|
-
|
|
3599
|
-
|
|
3600
|
-
});
|
|
4148
|
+
function readCodexForClaudeCapture(options = {}) {
|
|
4149
|
+
return readCodex(options);
|
|
3601
4150
|
}
|
|
3602
4151
|
|
|
3603
4152
|
function codexSessionFiles(roots) {
|
|
@@ -3627,11 +4176,11 @@ function scanCodexStatus(files, roots) {
|
|
|
3627
4176
|
const usageMatch = latestMatchingJsonLine(files, isRateLimitLine, (json) => {
|
|
3628
4177
|
if (!isCodexRateLimit(json)) return false;
|
|
3629
4178
|
const limits = json.payload.rate_limits;
|
|
3630
|
-
return Boolean(normalizeLimit(limits.primary) || normalizeLimit(limits.secondary));
|
|
3631
|
-
});
|
|
4179
|
+
return Boolean(normalizeLimit(limits.primary, { inferResetPassed: false }) || normalizeLimit(limits.secondary, { inferResetPassed: false }));
|
|
4180
|
+
}, true);
|
|
3632
4181
|
// Preserve a metadata-only snapshot when percentages have never been seen;
|
|
3633
4182
|
// the renderer will show an unknown value rather than inventing a number.
|
|
3634
|
-
const match = usageMatch?.json ? usageMatch : latestMatchingJsonLine(files, isRateLimitLine, isCodexRateLimit);
|
|
4183
|
+
const match = usageMatch?.json ? usageMatch : latestMatchingJsonLine(files, isRateLimitLine, isCodexRateLimit, true);
|
|
3635
4184
|
const rateLimits = match?.json?.payload?.rate_limits;
|
|
3636
4185
|
|
|
3637
4186
|
if (!rateLimits) {
|
|
@@ -3643,16 +4192,15 @@ function scanCodexStatus(files, roots) {
|
|
|
3643
4192
|
};
|
|
3644
4193
|
}
|
|
3645
4194
|
|
|
3646
|
-
//
|
|
3647
|
-
//
|
|
3648
|
-
const
|
|
3649
|
-
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\""));
|
|
3650
4198
|
const turnContext = contextMatch?.json?.payload ?? null;
|
|
3651
4199
|
const approvalPolicy = turnContext?.approval_policy ?? null;
|
|
3652
4200
|
const sandboxMode = turnContext?.sandbox_policy?.type ?? null;
|
|
3653
4201
|
const collaborationMode = turnContext?.collaboration_mode?.mode ?? null;
|
|
3654
|
-
const primary = normalizeLimit(rateLimits.primary);
|
|
3655
|
-
const secondary = normalizeLimit(rateLimits.secondary);
|
|
4202
|
+
const primary = normalizeLimit(rateLimits.primary, { inferResetPassed: false });
|
|
4203
|
+
const secondary = normalizeLimit(rateLimits.secondary, { inferResetPassed: false });
|
|
3656
4204
|
const sessionMeta = codexSessionMeta(match.file);
|
|
3657
4205
|
const timestamp = match.json.timestamp ?? null;
|
|
3658
4206
|
|
|
@@ -4109,7 +4657,11 @@ function usageTotal(usage) {
|
|
|
4109
4657
|
function readClaude(options = {}) {
|
|
4110
4658
|
const running = typeof options.runningOverride === "boolean"
|
|
4111
4659
|
? options.runningOverride
|
|
4112
|
-
: 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
|
+
}
|
|
4113
4665
|
const statuslineCache = readClaudeStatuslineCache();
|
|
4114
4666
|
if (statuslineCache) return { ...statuslineCache, running };
|
|
4115
4667
|
|
|
@@ -4176,8 +4728,11 @@ function readClaude(options = {}) {
|
|
|
4176
4728
|
};
|
|
4177
4729
|
}
|
|
4178
4730
|
|
|
4731
|
+
let sttyColumnsMemo;
|
|
4732
|
+
|
|
4179
4733
|
function sttyColumns() {
|
|
4180
4734
|
if (process.platform === "win32") return null;
|
|
4735
|
+
if (sttyColumnsMemo !== undefined) return sttyColumnsMemo;
|
|
4181
4736
|
|
|
4182
4737
|
let ttyFd = null;
|
|
4183
4738
|
try {
|
|
@@ -4188,8 +4743,10 @@ function sttyColumns() {
|
|
|
4188
4743
|
timeout: 100
|
|
4189
4744
|
}).trim();
|
|
4190
4745
|
const [, columns] = output.split(/\s+/).map((part) => Number(part));
|
|
4191
|
-
|
|
4746
|
+
sttyColumnsMemo = numericColumn(columns);
|
|
4747
|
+
return sttyColumnsMemo;
|
|
4192
4748
|
} catch {
|
|
4749
|
+
sttyColumnsMemo = null;
|
|
4193
4750
|
return null;
|
|
4194
4751
|
} finally {
|
|
4195
4752
|
if (ttyFd !== null) {
|
|
@@ -4206,12 +4763,12 @@ function runtimeTerminalColumns() {
|
|
|
4206
4763
|
return numericColumn(process.stdout.columns) ?? sttyColumns();
|
|
4207
4764
|
}
|
|
4208
4765
|
|
|
4209
|
-
function statusLineColumns(input) {
|
|
4766
|
+
function statusLineColumns(input, observedColumns = null) {
|
|
4210
4767
|
const explicitColumns = numericColumn(process.env.AI_BATTERY_COLUMNS)
|
|
4211
4768
|
?? numericColumn(process.env.CLAUDEX_BATTERY_COLUMNS);
|
|
4212
4769
|
if (explicitColumns) return explicitColumns;
|
|
4213
4770
|
|
|
4214
|
-
const runtimeColumns = runtimeTerminalColumns();
|
|
4771
|
+
const runtimeColumns = runtimeTerminalColumns() ?? numericColumn(observedColumns);
|
|
4215
4772
|
const payloadCandidates = [
|
|
4216
4773
|
input.terminal?.columns,
|
|
4217
4774
|
input.terminal?.cols,
|
|
@@ -4240,18 +4797,18 @@ function statusLineColumns(input) {
|
|
|
4240
4797
|
return 80;
|
|
4241
4798
|
}
|
|
4242
4799
|
|
|
4243
|
-
function statusLineHeaderColumns(input, args) {
|
|
4800
|
+
function statusLineHeaderColumns(input, args, observedColumns = null) {
|
|
4244
4801
|
const guard = numericGuard(process.env.AI_BATTERY_HEADER_COLUMN_GUARD)
|
|
4245
4802
|
?? numericGuard(process.env.CLAUDEX_BATTERY_HEADER_COLUMN_GUARD)
|
|
4246
4803
|
?? DEFAULT_STATUSLINE_HEADER_COLUMN_GUARD;
|
|
4247
|
-
return Math.max(20, statusLineColumns(input) - guard - (Number(args.leftPadding) || 0));
|
|
4804
|
+
return Math.max(20, statusLineColumns(input, observedColumns) - guard - (Number(args.leftPadding) || 0));
|
|
4248
4805
|
}
|
|
4249
4806
|
|
|
4250
|
-
function statusLineUsableColumns(input) {
|
|
4807
|
+
function statusLineUsableColumns(input, observedColumns = null) {
|
|
4251
4808
|
const guard = numericGuard(process.env.AI_BATTERY_COLUMN_GUARD)
|
|
4252
4809
|
?? numericGuard(process.env.CLAUDEX_BATTERY_COLUMN_GUARD)
|
|
4253
4810
|
?? DEFAULT_STATUSLINE_COLUMN_GUARD;
|
|
4254
|
-
return Math.max(20, statusLineColumns(input) - guard);
|
|
4811
|
+
return Math.max(20, statusLineColumns(input, observedColumns) - guard);
|
|
4255
4812
|
}
|
|
4256
4813
|
|
|
4257
4814
|
function contextRemainingPercent(input, fallbackContext = null) {
|
|
@@ -4270,19 +4827,6 @@ function contextLeftText(input, fallbackContext = null) {
|
|
|
4270
4827
|
return `${remaining}% context left`;
|
|
4271
4828
|
}
|
|
4272
4829
|
|
|
4273
|
-
function alignHeader(left, right, columns) {
|
|
4274
|
-
if (!right) return left;
|
|
4275
|
-
|
|
4276
|
-
const gap = 2;
|
|
4277
|
-
const rightWidth = visibleWidth(right);
|
|
4278
|
-
if (!columns || columns <= rightWidth + gap) return `${left} ${right}`;
|
|
4279
|
-
|
|
4280
|
-
const leftBudget = columns - rightWidth - gap;
|
|
4281
|
-
const fittedLeft = truncateMiddleVisible(left, leftBudget);
|
|
4282
|
-
const spaces = Math.max(gap, columns - visibleWidth(fittedLeft) - rightWidth);
|
|
4283
|
-
return `${fittedLeft}${" ".repeat(spaces)}${right}`;
|
|
4284
|
-
}
|
|
4285
|
-
|
|
4286
4830
|
function displayPath(dir) {
|
|
4287
4831
|
if (!dir) return "~";
|
|
4288
4832
|
const home = userHome();
|
|
@@ -4293,11 +4837,14 @@ function displayPath(dir) {
|
|
|
4293
4837
|
|
|
4294
4838
|
function gitBranchFromDir(dir) {
|
|
4295
4839
|
if (!dir) return null;
|
|
4840
|
+
const fast = readGitBranchFast(dir);
|
|
4841
|
+
if (fast) return fast;
|
|
4296
4842
|
try {
|
|
4297
4843
|
const branch = execFileSync("git", ["-C", dir, "branch", "--show-current"], {
|
|
4298
4844
|
encoding: "utf8",
|
|
4299
4845
|
stdio: ["ignore", "pipe", "ignore"],
|
|
4300
|
-
timeout: 500
|
|
4846
|
+
timeout: 500,
|
|
4847
|
+
windowsHide: true
|
|
4301
4848
|
}).trim();
|
|
4302
4849
|
return branch || null;
|
|
4303
4850
|
} catch {
|
|
@@ -4316,7 +4863,7 @@ function statuslineGitBranch(input) {
|
|
|
4316
4863
|
|| null;
|
|
4317
4864
|
if (explicit) return explicit;
|
|
4318
4865
|
|
|
4319
|
-
const dirs = [
|
|
4866
|
+
const dirs = uniquePaths([
|
|
4320
4867
|
input.workspace?.current_dir,
|
|
4321
4868
|
input.workspace?.currentDir,
|
|
4322
4869
|
input.cwd,
|
|
@@ -4324,7 +4871,7 @@ function statuslineGitBranch(input) {
|
|
|
4324
4871
|
input.currentDir,
|
|
4325
4872
|
input.workspace?.project_dir,
|
|
4326
4873
|
input.workspace?.projectDir
|
|
4327
|
-
].filter(Boolean);
|
|
4874
|
+
].filter(Boolean));
|
|
4328
4875
|
|
|
4329
4876
|
for (const dir of dirs) {
|
|
4330
4877
|
const branch = gitBranchFromDir(dir);
|
|
@@ -4333,18 +4880,18 @@ function statuslineGitBranch(input) {
|
|
|
4333
4880
|
return null;
|
|
4334
4881
|
}
|
|
4335
4882
|
|
|
4336
|
-
function claudeHeader(input, args, capturedClaude = null) {
|
|
4883
|
+
function claudeHeader(input, args, capturedClaude = null, observedColumns = null) {
|
|
4337
4884
|
const model = typeof input.model === "string"
|
|
4338
4885
|
? input.model
|
|
4339
|
-
: input.model?.display_name || input.model?.displayName || input.model?.id || "Claude";
|
|
4340
|
-
const effort = input.effort?.level || input.effortLevel || null;
|
|
4341
|
-
const workspaceRoot = input.workspace?.
|
|
4342
|
-
|| input.workspace?.
|
|
4886
|
+
: input.model?.display_name || input.model?.displayName || input.model?.id || (input.product === "antigravity" ? providerLabel("antigravity") : "Claude");
|
|
4887
|
+
const effort = input.model?.effort || (typeof input.effort === "string" ? input.effort : input.effort?.level) || input.effortLevel || null;
|
|
4888
|
+
const workspaceRoot = input.workspace?.current_dir
|
|
4889
|
+
|| input.workspace?.currentDir
|
|
4343
4890
|
|| input.cwd
|
|
4344
4891
|
|| input.current_dir
|
|
4345
4892
|
|| input.currentDir
|
|
4346
|
-
|| input.workspace?.
|
|
4347
|
-
|| input.workspace?.
|
|
4893
|
+
|| input.workspace?.project_dir
|
|
4894
|
+
|| input.workspace?.projectDir
|
|
4348
4895
|
|| "";
|
|
4349
4896
|
const gitBranch = statuslineGitBranch(input);
|
|
4350
4897
|
const parts = [model];
|
|
@@ -4355,10 +4902,12 @@ function claudeHeader(input, args, capturedClaude = null) {
|
|
|
4355
4902
|
parts.push("·");
|
|
4356
4903
|
parts.push(gitBranch);
|
|
4357
4904
|
}
|
|
4358
|
-
const
|
|
4359
|
-
|
|
4360
|
-
const
|
|
4361
|
-
|
|
4905
|
+
const changes = branchChanges(workspaceRoot);
|
|
4906
|
+
if (changes) parts.push("·", changes);
|
|
4907
|
+
const context = contextLeftText(input, capturedClaude?.contextWindow ?? null);
|
|
4908
|
+
if (context) parts.push("·", context);
|
|
4909
|
+
const columns = statusLineHeaderColumns(input, args, observedColumns);
|
|
4910
|
+
const header = truncateMiddleVisible(parts.join(" "), columns);
|
|
4362
4911
|
return statusColorize({ running: false }, header, args);
|
|
4363
4912
|
}
|
|
4364
4913
|
|
|
@@ -4387,8 +4936,19 @@ function weekText(secondary) {
|
|
|
4387
4936
|
}
|
|
4388
4937
|
|
|
4389
4938
|
function formatCodex(data, args) {
|
|
4390
|
-
if (!data.ok)
|
|
4391
|
-
|
|
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
|
+
}
|
|
4392
4952
|
|
|
4393
4953
|
const batteryColor = remainingColor(data.percentRemaining);
|
|
4394
4954
|
const primary = data.primary;
|
|
@@ -4397,18 +4957,16 @@ function formatCodex(data, args) {
|
|
|
4397
4957
|
`${statusColorize(data, "Codex ", args)}${bar(data.percentRemaining, args.barWidth, batteryColor, args.style)}${statusColorize(data, ` ${Number.isFinite(data.percentRemaining) ? data.percentRemaining : "--"}%`, args)}`
|
|
4398
4958
|
];
|
|
4399
4959
|
|
|
4400
|
-
|
|
4401
|
-
// terminal too narrow to hold both providers in full (see render()).
|
|
4402
|
-
if (!args.compact) {
|
|
4960
|
+
if (args.showPrimary !== false) {
|
|
4403
4961
|
const primaryReset = limitResetText(primary);
|
|
4404
4962
|
if (primaryReset) {
|
|
4405
4963
|
bits.push(divider(args));
|
|
4406
4964
|
bits.push(statusColorize(data, primaryReset, args));
|
|
4407
4965
|
}
|
|
4408
|
-
|
|
4409
|
-
|
|
4410
|
-
|
|
4411
|
-
|
|
4966
|
+
}
|
|
4967
|
+
if (args.showSecondary !== false && secondary) {
|
|
4968
|
+
bits.push(divider(args));
|
|
4969
|
+
bits.push(statusColorize(data, weekText(secondary), args));
|
|
4412
4970
|
}
|
|
4413
4971
|
if (data.reachedType) {
|
|
4414
4972
|
bits.push(statusColorize(data, `limit ${data.reachedType}`, args));
|
|
@@ -4429,18 +4987,18 @@ function formatClaude(data, args) {
|
|
|
4429
4987
|
if (data.sourceType === "statusline") {
|
|
4430
4988
|
const batteryColor = remainingColor(data.percentRemaining);
|
|
4431
4989
|
const bits = [
|
|
4432
|
-
`${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)}`
|
|
4433
4991
|
];
|
|
4434
|
-
if (
|
|
4992
|
+
if (args.showPrimary !== false) {
|
|
4435
4993
|
const primaryReset = limitResetText(data.primary);
|
|
4436
4994
|
if (primaryReset) {
|
|
4437
4995
|
bits.push(divider(args));
|
|
4438
4996
|
bits.push(statusColorize(data, primaryReset, args));
|
|
4439
4997
|
}
|
|
4440
|
-
|
|
4441
|
-
|
|
4442
|
-
|
|
4443
|
-
|
|
4998
|
+
}
|
|
4999
|
+
if (args.showSecondary !== false && data.secondary) {
|
|
5000
|
+
bits.push(divider(args));
|
|
5001
|
+
bits.push(statusColorize(data, weekText(data.secondary), args));
|
|
4444
5002
|
}
|
|
4445
5003
|
if (args.showPaths) {
|
|
4446
5004
|
const seen = ageText(data.ageSeconds);
|
|
@@ -4453,8 +5011,10 @@ function formatClaude(data, args) {
|
|
|
4453
5011
|
const bits = [
|
|
4454
5012
|
`${statusColorize(data, "Claude ", args)}${bar(null, args.barWidth, "gray", args.style)}${statusColorize(data, " --%", args)}`
|
|
4455
5013
|
];
|
|
4456
|
-
if (
|
|
5014
|
+
if (args.showPrimary !== false) {
|
|
4457
5015
|
bits.push(divider(args), statusColorize(data, "5h --:--", args));
|
|
5016
|
+
}
|
|
5017
|
+
if (args.showSecondary !== false) {
|
|
4458
5018
|
bits.push(divider(args), statusColorize(data, "7d ---%", args));
|
|
4459
5019
|
}
|
|
4460
5020
|
|
|
@@ -4462,6 +5022,23 @@ function formatClaude(data, args) {
|
|
|
4462
5022
|
return bits.join(" ");
|
|
4463
5023
|
}
|
|
4464
5024
|
|
|
5025
|
+
function formatAntigravity(data, args) {
|
|
5026
|
+
const name = providerLabel("antigravity");
|
|
5027
|
+
if (!data.ok || typeof data.percentRemaining !== "number") {
|
|
5028
|
+
const amounts = data.quotas?.filter(quota => quota.remainingAmount != null)
|
|
5029
|
+
.map(quota => `${quota.id} ${quota.remainingAmount}`).join(" · ");
|
|
5030
|
+
return statusColorize(data, amounts && args.showSecondary !== false ? `${name} ${amounts}` : `${name} --%`, args);
|
|
5031
|
+
}
|
|
5032
|
+
const bits = [`${statusColorize(data, `${name} `, args)}${bar(data.percentRemaining, args.barWidth, remainingColor(data.percentRemaining), args.style)}${statusColorize(data, ` ${data.percentRemaining}%`, args)}`];
|
|
5033
|
+
if (args.showPrimary !== false && data.primary) {
|
|
5034
|
+
const label = data.primary.windowMinutes ? shortWindow(data.primary.windowMinutes) : data.primary.id;
|
|
5035
|
+
bits.push(divider(args), statusColorize(data, `${label} ${resetClock(data.primary)}`, args));
|
|
5036
|
+
}
|
|
5037
|
+
if (args.showSecondary !== false && data.secondary) bits.push(divider(args), statusColorize(data, weekText(data.secondary), args));
|
|
5038
|
+
if (args.showPaths) bits.push(statusColorize(data, data.source || antigravity.cachePath(), args));
|
|
5039
|
+
return bits.join(" ");
|
|
5040
|
+
}
|
|
5041
|
+
|
|
4465
5042
|
function compactNumber(value) {
|
|
4466
5043
|
const number = Number(value) || 0;
|
|
4467
5044
|
if (number >= 1_000_000) return `${(number / 1_000_000).toFixed(1)}M`;
|
|
@@ -4470,25 +5047,34 @@ function compactNumber(value) {
|
|
|
4470
5047
|
}
|
|
4471
5048
|
|
|
4472
5049
|
function runningOverrideForProvider(args, provider) {
|
|
5050
|
+
if (args.runningProviders instanceof Set) return args.runningProviders.has(provider);
|
|
4473
5051
|
if (args.activeProvider === provider) return true;
|
|
4474
5052
|
return null;
|
|
4475
5053
|
}
|
|
4476
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
|
+
|
|
4477
5060
|
function collect(args) {
|
|
4478
5061
|
const results = [];
|
|
4479
5062
|
const includeHidden = args.provider !== "all";
|
|
4480
5063
|
if ((args.provider === "all" || args.provider === "codex") && (includeHidden || providerVisible("codex"))) {
|
|
4481
5064
|
results.push(readCodex({
|
|
4482
5065
|
runningOverride: runningOverrideForProvider(args, "codex"),
|
|
4483
|
-
includeRunning: args.activeProvider !== "codex"
|
|
5066
|
+
includeRunning: !(args.runningProviders instanceof Set) && args.activeProvider !== "codex"
|
|
4484
5067
|
}));
|
|
4485
5068
|
}
|
|
4486
5069
|
if ((args.provider === "all" || args.provider === "claude") && (includeHidden || providerVisible("claude"))) {
|
|
4487
5070
|
results.push(readClaude({ runningOverride: runningOverrideForProvider(args, "claude") }));
|
|
4488
5071
|
}
|
|
5072
|
+
if ((args.provider === "antigravity" || (args.provider === "all" && providerVisible("antigravity") && antigravityAvailable()))) {
|
|
5073
|
+
results.push(antigravity.read({ runningOverride: runningOverrideForProvider(args, "antigravity") }));
|
|
5074
|
+
}
|
|
4489
5075
|
return {
|
|
4490
5076
|
generatedAt: new Date().toISOString(),
|
|
4491
|
-
results
|
|
5077
|
+
results: orderResults(results, configuredProviderOrder())
|
|
4492
5078
|
};
|
|
4493
5079
|
}
|
|
4494
5080
|
|
|
@@ -4498,6 +5084,7 @@ function renderLine(snapshot, args) {
|
|
|
4498
5084
|
.map((result) => {
|
|
4499
5085
|
if (result.provider === "codex") return formatCodex(result, args);
|
|
4500
5086
|
if (result.provider === "claude") return formatClaude(result, args);
|
|
5087
|
+
if (result.provider === "antigravity") return formatAntigravity(result, args);
|
|
4501
5088
|
return `${result.provider} ?`;
|
|
4502
5089
|
})
|
|
4503
5090
|
.join(providerDivider);
|
|
@@ -4506,7 +5093,8 @@ function renderLine(snapshot, args) {
|
|
|
4506
5093
|
function renderMenuBar(snapshot) {
|
|
4507
5094
|
const marks = {
|
|
4508
5095
|
codex: "◎",
|
|
4509
|
-
claude: "✳"
|
|
5096
|
+
claude: "✳",
|
|
5097
|
+
antigravity: "△"
|
|
4510
5098
|
};
|
|
4511
5099
|
const meter = (percent) => {
|
|
4512
5100
|
if (typeof percent !== "number") return "";
|
|
@@ -4517,7 +5105,7 @@ function renderMenuBar(snapshot) {
|
|
|
4517
5105
|
return `${"▰".repeat(full)}${"▱".repeat(width - full)}`;
|
|
4518
5106
|
};
|
|
4519
5107
|
|
|
4520
|
-
const parts = snapshot.results
|
|
5108
|
+
const parts = orderResults(snapshot.results, configuredProviderOrder())
|
|
4521
5109
|
.map((result) => {
|
|
4522
5110
|
const mark = marks[result.provider] || "?";
|
|
4523
5111
|
if (!result.ok || typeof result.percentRemaining !== "number") return `${mark} --`;
|
|
@@ -4739,6 +5327,10 @@ function renderMenuBarSvgIcon(icon, x, y, height) {
|
|
|
4739
5327
|
}
|
|
4740
5328
|
|
|
4741
5329
|
function menuBarImageIcon(provider, x, y) {
|
|
5330
|
+
if (provider === "antigravity") {
|
|
5331
|
+
const svg = fs.readFileSync(path.join(scriptDir(), "..", "docs", "antigravity-icon.svg"), "utf8");
|
|
5332
|
+
return svg.replace(/<svg\b[^>]*>/, `<svg x="${x}" y="${y}" width="19" height="19" viewBox="0 0 180 180" fill="none" xmlns="http://www.w3.org/2000/svg">`);
|
|
5333
|
+
}
|
|
4742
5334
|
const height = provider === "codex" ? 19 : 17;
|
|
4743
5335
|
const iconY = provider === "codex" ? y - 0.5 : y;
|
|
4744
5336
|
if (provider === "codex") {
|
|
@@ -4760,7 +5352,7 @@ function renderMenuBarImage(snapshot) {
|
|
|
4760
5352
|
const providerWidth = 56;
|
|
4761
5353
|
const providerContentWidth = 48;
|
|
4762
5354
|
const height = 24;
|
|
4763
|
-
const visibleResults = snapshot.results.filter(Boolean);
|
|
5355
|
+
const visibleResults = orderResults(snapshot.results.filter(Boolean), configuredProviderOrder());
|
|
4764
5356
|
const width = visibleResults.length
|
|
4765
5357
|
? startX + ((visibleResults.length - 1) * providerWidth) + providerContentWidth + endPadding
|
|
4766
5358
|
: 54;
|
|
@@ -4820,7 +5412,7 @@ function renderMenuBarImage(snapshot) {
|
|
|
4820
5412
|
|
|
4821
5413
|
function menuDetailLimitText(limit) {
|
|
4822
5414
|
if (!limit) return null;
|
|
4823
|
-
const label = shortWindow(limit.windowMinutes);
|
|
5415
|
+
const label = limit.windowMinutes ? shortWindow(limit.windowMinutes) : limit.id || "?";
|
|
4824
5416
|
if (label === "5h") return `${label} ${resetClock(limit)}`;
|
|
4825
5417
|
if (typeof limit.remainingPercent === "number") return `${label} ${limit.remainingPercent}%`;
|
|
4826
5418
|
return `${label} ${resetClock(limit)}`;
|
|
@@ -4866,9 +5458,9 @@ function menuDetailUsageUpdateText(result) {
|
|
|
4866
5458
|
}
|
|
4867
5459
|
|
|
4868
5460
|
function renderMenuDetailImage(snapshot) {
|
|
4869
|
-
const visibleResults = snapshot.results.filter(Boolean);
|
|
5461
|
+
const visibleResults = orderResults(snapshot.results.filter(Boolean), configuredProviderOrder());
|
|
4870
5462
|
const rows = visibleResults.length ? visibleResults : [{ provider: "ai", ok: false }];
|
|
4871
|
-
const width = 392;
|
|
5463
|
+
const width = rows.some(row => row.provider === "antigravity") ? 420 : 392;
|
|
4872
5464
|
const usageTexts = rows.map(menuDetailUsageUpdateText);
|
|
4873
5465
|
const hasUsageText = usageTexts.some(Boolean);
|
|
4874
5466
|
const rowHeight = hasUsageText ? 46 : 36;
|
|
@@ -4884,13 +5476,13 @@ function renderMenuDetailImage(snapshot) {
|
|
|
4884
5476
|
const baseline = y + (hasUsageText ? 19 : 22);
|
|
4885
5477
|
const usageBaseline = y + 38;
|
|
4886
5478
|
const usageText = usageTexts[index];
|
|
4887
|
-
const provider = result.provider
|
|
5479
|
+
const provider = providerLabel(result.provider);
|
|
4888
5480
|
const running = result.running === true;
|
|
4889
5481
|
const percent = typeof result.percentRemaining === "number" ? clamp(result.percentRemaining, 0, 100) : null;
|
|
4890
5482
|
const fillWidth = percent === null ? 0 : Math.max(percent > 0 ? 3 : 0, Math.round((percent / 100) * barWidth));
|
|
4891
5483
|
const fill = menuBatteryColor(percent, running);
|
|
4892
5484
|
const percentText = percent === null ? "--%" : `${Math.round(percent)}%`;
|
|
4893
|
-
const metaText = result.ok ? menuDetailMetaText(result) : "unavailable";
|
|
5485
|
+
const metaText = truncateMiddleVisible(result.ok ? menuDetailMetaText(result) : "unavailable", 20);
|
|
4894
5486
|
const barY = baseline - barHeight;
|
|
4895
5487
|
const primaryFill = running ? "#F5F5F7" : MENU_DIM_TEXT;
|
|
4896
5488
|
const metaFill = running ? MENU_DIM_TEXT : "#8E8E93";
|
|
@@ -4942,7 +5534,7 @@ function desktopHudSnapshot(provider = "all") {
|
|
|
4942
5534
|
text: renderLine(snapshot, { ...args, style: "plain" }),
|
|
4943
5535
|
rows: snapshot.results.filter(Boolean).map((result) => ({
|
|
4944
5536
|
provider: result.provider,
|
|
4945
|
-
label: result.provider
|
|
5537
|
+
label: providerLabel(result.provider),
|
|
4946
5538
|
percent: typeof result.percentRemaining === "number" ? clamp(result.percentRemaining, 0, 100) : null,
|
|
4947
5539
|
running: result.running === true,
|
|
4948
5540
|
meta: result.ok ? menuDetailMetaText(result) : "unavailable",
|
|
@@ -4963,6 +5555,7 @@ function applyLeftPadding(output, args) {
|
|
|
4963
5555
|
}
|
|
4964
5556
|
|
|
4965
5557
|
function render(snapshot, args) {
|
|
5558
|
+
snapshot = { ...snapshot, results: orderResults(snapshot.results, configuredProviderOrder()) };
|
|
4966
5559
|
if (args.json) return JSON.stringify(snapshot, null, 2);
|
|
4967
5560
|
if (args.hudState) return renderHudState(snapshot);
|
|
4968
5561
|
if (args.menuBarImage) return renderMenuBarImage(snapshot);
|
|
@@ -4970,28 +5563,32 @@ function render(snapshot, args) {
|
|
|
4970
5563
|
if (args.menuBar) return renderMenuBar(snapshot);
|
|
4971
5564
|
|
|
4972
5565
|
const maxWidth = args.maxWidth
|
|
4973
|
-
? Math.max(
|
|
5566
|
+
? Math.max(1, args.maxWidth - (Number(args.leftPadding) || 0))
|
|
4974
5567
|
: null;
|
|
4975
5568
|
|
|
4976
5569
|
if (args.maxWidth) {
|
|
4977
|
-
//
|
|
4978
|
-
//
|
|
4979
|
-
|
|
4980
|
-
|
|
4981
|
-
|
|
4982
|
-
|
|
4983
|
-
|
|
4984
|
-
|
|
4985
|
-
|
|
4986
|
-
|
|
4987
|
-
}
|
|
5570
|
+
// Use exact 10%, 20% or 25% steps. Keep 5h reset times after dropping
|
|
5571
|
+
// weekly detail, before spending the available space on longer bars.
|
|
5572
|
+
const barWidth = Math.max(4, Number(args.barWidth) || 10);
|
|
5573
|
+
const widths = [10, 5, 4].filter(width => width <= barWidth);
|
|
5574
|
+
const fullWidth = widths[0];
|
|
5575
|
+
const shortWidth = widths.find(width => width <= 5);
|
|
5576
|
+
const candidates = [
|
|
5577
|
+
{ barWidth: fullWidth, showPrimary: true, showSecondary: true },
|
|
5578
|
+
...(fullWidth !== shortWidth ? [{ barWidth: shortWidth, showPrimary: true, showSecondary: true }] : []),
|
|
5579
|
+
{ barWidth: shortWidth, showPrimary: true, showSecondary: false },
|
|
5580
|
+
...widths.map(barWidth => ({ barWidth, showPrimary: false, showSecondary: false }))
|
|
5581
|
+
];
|
|
5582
|
+
for (const candidate of candidates) {
|
|
5583
|
+
const line = renderLine(snapshot, { ...args, ...candidate });
|
|
5584
|
+
if (visibleWidth(line) <= maxWidth) return applyLeftPadding(line, args);
|
|
4988
5585
|
}
|
|
4989
5586
|
// A split pane can be too narrow even for the minimum bars. Retain both
|
|
4990
5587
|
// names and readings rather than letting the one-row terminal wrap away
|
|
4991
5588
|
// a provider. Detailed errors remain available in diagnostics.
|
|
4992
5589
|
const readings = snapshot.results.map((result) => {
|
|
4993
|
-
const percent =
|
|
4994
|
-
const name = result.provider
|
|
5590
|
+
const percent = result.ok && Number.isFinite(result.percentRemaining) ? `${result.percentRemaining}%` : "--%";
|
|
5591
|
+
const name = providerLabel(result.provider);
|
|
4995
5592
|
return statusColorize(result, `${name} ${percent}`, args);
|
|
4996
5593
|
}).join(` ${colorize(PROVIDER_DIVIDER, "gray", args.style)} `);
|
|
4997
5594
|
return applyLeftPadding(readings, args);
|
|
@@ -5034,6 +5631,75 @@ async function main() {
|
|
|
5034
5631
|
return;
|
|
5035
5632
|
}
|
|
5036
5633
|
|
|
5634
|
+
if (args.command === "config") {
|
|
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") });
|
|
5638
|
+
if (!edited) {
|
|
5639
|
+
console.log(cliText("Configuration cancelled.", "설정을 취소했습니다."));
|
|
5640
|
+
return;
|
|
5641
|
+
}
|
|
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
|
+
}
|
|
5659
|
+
const visible = latest.providerOrder.filter(provider => latest.providers[provider] !== false).map(providerLabel);
|
|
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})` : ""}`);
|
|
5668
|
+
return;
|
|
5669
|
+
}
|
|
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
|
+
};
|
|
5691
|
+
if (args.json) console.log(JSON.stringify(result, null, 2));
|
|
5692
|
+
else {
|
|
5693
|
+
console.log(`${cliText("Display settings", "표시 설정")}: ${result.providerOrder.map(provider => `${providerLabel(provider)}${result.providers[provider] ? "" : cliText(" (hidden)", " (숨김)")}`).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}`);
|
|
5698
|
+
}
|
|
5699
|
+
}
|
|
5700
|
+
return;
|
|
5701
|
+
}
|
|
5702
|
+
|
|
5037
5703
|
if (["reset", "teardown", "uninstall"].includes(args.command)) {
|
|
5038
5704
|
if (!args.silent && !args.json && args.command !== "reset") {
|
|
5039
5705
|
console.log(cliText(`"${args.command}" is an alias for "reset".`, `"${args.command}"는 "reset"의 호환 명령입니다.`));
|
|
@@ -5059,6 +5725,146 @@ async function main() {
|
|
|
5059
5725
|
process.exit(result.status ?? 0);
|
|
5060
5726
|
}
|
|
5061
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
|
+
|
|
5062
5868
|
if (args.command === "on" || args.command === "off") {
|
|
5063
5869
|
const visible = args.command === "on";
|
|
5064
5870
|
const result = setProviderVisibility(args.targets, visible);
|
|
@@ -5082,14 +5888,16 @@ async function main() {
|
|
|
5082
5888
|
return;
|
|
5083
5889
|
}
|
|
5084
5890
|
|
|
5085
|
-
if (args.command === "capture-claude") {
|
|
5891
|
+
if (args.command === "capture-claude" || args.command === "capture-antigravity") {
|
|
5892
|
+
const activeProvider = args.command === "capture-antigravity" ? "antigravity" : "claude";
|
|
5086
5893
|
const inputText = await readStdin();
|
|
5087
|
-
if (!inputText.trim()) throw new Error("capture-claude expected Claude statusline JSON on stdin");
|
|
5894
|
+
if (!inputText.trim()) throw new Error(activeProvider === "claude" ? "capture-claude expected Claude statusline JSON on stdin" : "capture-antigravity expected statusline JSON on stdin");
|
|
5088
5895
|
let input;
|
|
5089
5896
|
try { input = JSON.parse(inputText); }
|
|
5090
|
-
catch { throw new Error(
|
|
5091
|
-
|
|
5092
|
-
|
|
5897
|
+
catch { throw new Error(`${args.command} received invalid JSON`); }
|
|
5898
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error(`${args.command} expected a JSON object`);
|
|
5899
|
+
const capturedClaude = activeProvider === "antigravity" ? antigravity.capture(input) : captureClaudeStatusline(input);
|
|
5900
|
+
if (args.attachHud && activeProvider === "claude") {
|
|
5093
5901
|
attachWindowsClaudeHud(
|
|
5094
5902
|
capturedClaude.sessionId,
|
|
5095
5903
|
capturedClaude.workspace?.currentDir || capturedClaude.workspace?.projectDir || process.cwd(),
|
|
@@ -5097,35 +5905,59 @@ async function main() {
|
|
|
5097
5905
|
);
|
|
5098
5906
|
}
|
|
5099
5907
|
if (!args.silent) {
|
|
5100
|
-
const
|
|
5101
|
-
|
|
5102
|
-
|
|
5103
|
-
|
|
5104
|
-
|
|
5908
|
+
const usageRowRequested = activeProvider === "antigravity"
|
|
5909
|
+
? (typeof args.usageRow === "boolean" ? args.usageRow : booleanEnvValue(process.env.AI_BATTERY_ANTIGRAVITY_USAGE_ROW) ?? !tmuxStatusBarActive())
|
|
5910
|
+
: claudeUsageRowVisible(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));
|
|
5105
5924
|
return;
|
|
5106
5925
|
}
|
|
5926
|
+
const hookProcessOptions = {
|
|
5927
|
+
nonBlocking: true,
|
|
5928
|
+
triggerBackgroundRefresh: scheduleBackgroundProcessRefresh
|
|
5929
|
+
};
|
|
5107
5930
|
const results = [];
|
|
5108
5931
|
if ((args.provider === "all" || args.provider === "codex") && providerVisible("codex")) {
|
|
5109
|
-
const codexData = readCodexForClaudeCapture();
|
|
5932
|
+
const codexData = readCodexForClaudeCapture({ processOptions: hookProcessOptions });
|
|
5110
5933
|
if (codexData) results.push(codexData);
|
|
5111
5934
|
}
|
|
5112
5935
|
if ((args.provider === "all" || args.provider === "claude") && providerVisible("claude")) {
|
|
5113
|
-
|
|
5114
|
-
|
|
5115
|
-
:
|
|
5116
|
-
|
|
5117
|
-
|
|
5936
|
+
if (activeProvider === "claude") {
|
|
5937
|
+
const claudeData = readClaude({ runningOverride: true, capturedSnapshot: capturedClaude });
|
|
5938
|
+
results.push({ ...claudeData, running: true });
|
|
5939
|
+
} else results.push(readClaude({ processOptions: hookProcessOptions }));
|
|
5940
|
+
}
|
|
5941
|
+
if ((args.provider === "all" || args.provider === "antigravity") && providerVisible("antigravity") && (activeProvider === "antigravity" || antigravityAvailable())) {
|
|
5942
|
+
results.push(antigravity.read({
|
|
5943
|
+
runningOverride: activeProvider === "antigravity" ? true : null,
|
|
5944
|
+
processOptions: hookProcessOptions
|
|
5945
|
+
}));
|
|
5118
5946
|
}
|
|
5119
5947
|
const usage = render({
|
|
5120
5948
|
generatedAt: new Date().toISOString(),
|
|
5121
5949
|
results
|
|
5122
|
-
}, { ...args, activeProvider
|
|
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
|
+
}
|
|
5123
5957
|
// Inside tmux with the status-bar integration, the battery already shows
|
|
5124
5958
|
// in tmux's own bar; keep the statusline to the one line tmux can't show.
|
|
5125
|
-
const text =
|
|
5126
|
-
|
|
5127
|
-
: (header && usage ? `${header}\n${usage}` : (usage || header));
|
|
5128
|
-
console.log(applyLeftPadding(text, args));
|
|
5959
|
+
const text = header && usage ? `${header}\n${usage}` : (usage || header);
|
|
5960
|
+
if (text) console.log(applyLeftPadding(text, args));
|
|
5129
5961
|
}
|
|
5130
5962
|
return;
|
|
5131
5963
|
}
|
|
@@ -5167,6 +5999,7 @@ async function main() {
|
|
|
5167
5999
|
export {
|
|
5168
6000
|
bar,
|
|
5169
6001
|
claudeHeader,
|
|
6002
|
+
configuredProviderOrder,
|
|
5170
6003
|
claudeNativeSessionOwnerPid,
|
|
5171
6004
|
claudeStateDir,
|
|
5172
6005
|
commandMatchesProvider,
|
|
@@ -5200,11 +6033,14 @@ export {
|
|
|
5200
6033
|
removeAiBatteryShellPathBlock,
|
|
5201
6034
|
percentValue,
|
|
5202
6035
|
providerRunningInProcesses,
|
|
6036
|
+
render,
|
|
6037
|
+
renderTmuxUsage,
|
|
5203
6038
|
renderHudState,
|
|
5204
6039
|
renderMenuBarImage,
|
|
5205
6040
|
renderMenuDetailImage,
|
|
5206
6041
|
rowptyDiagnostic,
|
|
5207
6042
|
sameFilePath,
|
|
6043
|
+
teardownResultFailed,
|
|
5208
6044
|
visibleWidth,
|
|
5209
6045
|
uninstallClaudeStatusline,
|
|
5210
6046
|
uninstallCodexWrapper,
|