ai-battery 0.1.24 → 0.1.26

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/lib/cli.js CHANGED
@@ -17,6 +17,9 @@ import { createProcessScanner } from "./platforms/process-scanner.js";
17
17
  import { createWindowsPathIntegration } from "./platforms/windows/path-integration.js";
18
18
  import { cleanupBatteryArtifacts, isBatteryConfig } from "./core/uninstall.js";
19
19
  import { createIntegrationFiles } from "./core/integration-files.js";
20
+ import { cliError, cliText, helpText, invalidChoice, requiredValue } from "./core/cli-help.js";
21
+ import { errorText, messageText as cliMessageText } from "./core/cli-messages.js";
22
+ import { formatClaudeResult, formatDoctorResult, formatResetResult, formatSetupResult, formatVisibilityResult } from "./core/cli-output.js";
20
23
  import {
21
24
  cacheAgeSeconds,
22
25
  clamp,
@@ -58,7 +61,6 @@ const DIVIDER = "│";
58
61
  const PROVIDER_DIVIDER = "┃";
59
62
  const DEFAULT_STATUSLINE_COLUMN_GUARD = 4;
60
63
  const COMMANDS = new Set([
61
- "show",
62
64
  "setup",
63
65
  "reset",
64
66
  "teardown",
@@ -93,8 +95,9 @@ const MENU_DIM_TEXT = "#A1A1AA";
93
95
  const MENU_DIM_OUTLINE_OPACITY = "0.24";
94
96
 
95
97
  function parseArgs(argv) {
98
+ if (argv[0] === "help") argv = ["--help", ...argv.slice(1)];
96
99
  const args = {
97
- command: "show",
100
+ command: "",
98
101
  provider: "all",
99
102
  json: false,
100
103
  watch: false,
@@ -111,19 +114,20 @@ function parseArgs(argv) {
111
114
  hudState: false,
112
115
  silent: false,
113
116
  force: false,
114
- wrapCodex: true,
117
+ wrapCodex: false,
115
118
  configureCodexStatusLine: false,
116
119
  attachHud: false,
117
120
  header: true,
118
121
  usageRow: "auto",
119
- help: false,
122
+ help: argv.length === 0,
123
+ helpTopic: "",
120
124
  version: false,
121
- resetScope: null,
122
125
  targets: [],
123
126
  rest: []
124
127
  };
125
128
 
126
129
  let commandSeen = false;
130
+ let resetAliasSeen = false;
127
131
  for (let i = 0; i < argv.length; i += 1) {
128
132
  const arg = argv[i];
129
133
  if (!commandSeen && !arg.startsWith("-") && COMMANDS.has(arg)) {
@@ -131,15 +135,17 @@ function parseArgs(argv) {
131
135
  commandSeen = true;
132
136
  if (arg === "hud") {
133
137
  args.rest = argv.slice(i + 1);
138
+ args.help ||= args.rest.includes("--help") || args.rest.includes("-h");
134
139
  break;
135
140
  }
136
- } else if (!arg.startsWith("-") && args.command === "reset" && !args.resetScope) {
137
- if (!["settings", "config"].includes(arg)) throw new Error("Usage: ai-battery reset settings|config [codex|claude|hud|tmux|all]");
138
- args.resetScope = "settings";
141
+ } else if (args.command === "reset" && !resetAliasSeen && !args.targets.length && ["settings", "config"].includes(arg)) {
142
+ // Keep the previous reset settings/config syntax for existing scripts.
143
+ resetAliasSeen = true;
139
144
  } else if (!arg.startsWith("-") && ["setup", "reset", "teardown", "uninstall", "on", "off"].includes(args.command)) {
140
145
  args.targets.push(arg);
141
146
  } else if (arg === "--provider" || arg === "-p") {
142
- args.provider = argv[++i] || "all";
147
+ args.provider = requiredValue(argv, i, commandSeen ? args.command : "");
148
+ i += 1;
143
149
  } else if (arg === "--json") {
144
150
  args.json = true;
145
151
  args.style = "plain";
@@ -161,8 +167,6 @@ function parseArgs(argv) {
161
167
  args.force = true;
162
168
  } else if (arg === "--wrap-codex") {
163
169
  args.wrapCodex = true;
164
- } else if (arg === "--no-wrap-codex") {
165
- args.wrapCodex = false;
166
170
  } else if (arg === "--configure-codex-statusline") {
167
171
  args.configureCodexStatusLine = true;
168
172
  } else if (arg === "--attach-hud") {
@@ -170,20 +174,24 @@ function parseArgs(argv) {
170
174
  } else if (arg === "--watch" || arg === "-w") {
171
175
  args.watch = true;
172
176
  const maybeInterval = argv[i + 1];
173
- if (maybeInterval && !maybeInterval.startsWith("-")) {
177
+ if (maybeInterval && Number.isFinite(Number(maybeInterval)) && !maybeInterval.startsWith("-")) {
174
178
  args.interval = Math.max(1, Number(maybeInterval) || args.interval);
175
179
  i += 1;
176
180
  }
177
181
  } else if (arg === "--no-color") {
178
182
  args.style = "plain";
179
183
  } else if (arg === "--bar-width") {
180
- args.barWidth = Math.max(4, Math.min(30, Number(argv[++i]) || args.barWidth));
184
+ args.barWidth = Math.max(4, Math.min(30, Number(requiredValue(argv, i, args.command)) || args.barWidth));
185
+ i += 1;
181
186
  } else if (arg === "--max-width") {
182
- args.maxWidth = Math.max(20, Number(argv[++i]) || 0) || null;
187
+ args.maxWidth = Math.max(20, Number(requiredValue(argv, i, args.command)) || 0) || null;
188
+ i += 1;
183
189
  } else if (arg === "--left-padding") {
184
- args.leftPadding = Math.max(0, Math.min(20, Number(argv[++i]) || 0));
190
+ args.leftPadding = Math.max(0, Math.min(20, Number(requiredValue(argv, i, args.command)) || 0));
191
+ i += 1;
185
192
  } else if (arg === "--active-provider") {
186
- args.activeProvider = argv[++i] || null;
193
+ args.activeProvider = requiredValue(argv, i, args.command);
194
+ i += 1;
187
195
  } else if (arg === "--show-paths") {
188
196
  args.showPaths = true;
189
197
  } else if (arg === "--menu-bar") {
@@ -203,74 +211,36 @@ function parseArgs(argv) {
203
211
  } else if (arg === "--help" || arg === "-h") {
204
212
  args.help = true;
205
213
  } else {
206
- throw new Error(`Unknown argument: ${arg}`);
214
+ if (arg.startsWith("-")) {
215
+ throw cliError(`Unknown option: ${arg}.`, `알 수 없는 옵션: ${arg}.`, commandSeen ? args.command : "");
216
+ }
217
+ if (commandSeen) {
218
+ throw cliError(`Unexpected argument: ${arg}.`, `불필요한 인자: ${arg}.`, args.command);
219
+ }
220
+ throw cliError(`Unknown command: ${arg}.`, `알 수 없는 명령: ${arg}.`);
207
221
  }
208
222
  }
209
223
 
210
- if (args.command === "reset" && !args.resetScope && !args.help && !args.version) {
211
- throw new Error("Usage: ai-battery reset settings|config [codex|claude|hud|tmux|all]");
212
- }
224
+ args.helpTopic = commandSeen ? args.command : "";
213
225
  if (!["all", "codex", "claude"].includes(args.provider)) {
214
- throw new Error("--provider must be one of: all, codex, claude");
226
+ throw invalidChoice("--provider", "all, codex, claude", args.helpTopic);
215
227
  }
216
228
  if (args.activeProvider && !["codex", "claude"].includes(args.activeProvider)) {
217
- throw new Error("--active-provider must be one of: codex, claude");
229
+ throw invalidChoice("--active-provider", "codex, claude", args.helpTopic);
230
+ }
231
+ if (args.targets.length) {
232
+ const choices = args.command === "setup" ? [...PROVIDERS, "tmux", "all"]
233
+ : ["on", "off"].includes(args.command) ? [...PROVIDERS, "all"] : [...TEARDOWN_TARGETS, "all"];
234
+ if (args.targets.some((target) => !choices.includes(target))) {
235
+ throw invalidChoice("target", choices.join(", "), args.command);
236
+ }
218
237
  }
219
238
 
220
239
  return args;
221
240
  }
222
241
 
223
- function printHelp() {
224
- console.log(`ai-battery
225
-
226
- Usage:
227
- ai-battery [options]
228
- ai-battery setup [codex|claude] [--force] [--no-wrap-codex]
229
- ai-battery reset settings [codex|claude|hud|tmux|all]
230
- ai-battery doctor
231
- ai-battery hud [start|stop|status] [hud options]
232
- ai-battery hud autostart on|off|status
233
- ai-battery off codex|claude|all
234
- ai-battery on codex|claude|all
235
-
236
- Aliases:
237
- claudex-battery
238
- ai-battery reset config [codex|claude|hud|tmux|all]
239
-
240
- Setup enables automatic Codex usage display through a managed PATH wrapper.
241
- The original Codex executable and existing Codex configuration are preserved.
242
- Reset settings restores AI Battery's integrations and cleans its generated files.
243
- The npm package stays installed. Remove it separately: npm uninstall -g ai-battery
244
-
245
- Options:
246
- -p, --provider all|codex|claude Provider to show (default: all)
247
- --json Print machine-readable JSON
248
- --ansi Force ANSI color output
249
- --muted Use Codex-style muted status-line colors
250
- --no-header Hide Claude's extra statusLine header
251
- --no-usage-row Hide Claude's duplicated per-pane usage row
252
- -w, --watch [seconds] Refresh in place (default: 10 seconds)
253
- --bar-width N Battery bar width (default: 10)
254
- --max-width N Fit text output within N terminal columns
255
- --left-padding N Prefix status output with N spaces
256
- --active-provider codex|claude
257
- --show-paths Include source log paths in text output
258
- --menu-bar Print compact macOS menu bar text
259
- --tmux Emit tmux status-line color markup
260
- --force Replace an existing Claude statusLine
261
- --wrap-codex Enable automatic Codex usage display (default)
262
- --no-wrap-codex Use Codex without the AI Battery wrapper
263
- --configure-codex-statusline Explicitly configure Codex's own status line
264
- --no-color Disable ANSI colors
265
- -v, --version Show ai-battery version
266
- -h, --help Show this help
267
-
268
- Compatibility:
269
- ai-battery install-claude-statusline [--force]
270
- ai-battery uninstall-claude-statusline
271
- ai-battery teardown [codex|claude|hud|tmux|all]
272
- ai-battery uninstall [codex|claude|hud|tmux|all]
273
- `);
242
+ function printHelp(command) {
243
+ console.log(helpText(command, { platform: isWsl() ? "win32" : process.platform }));
274
244
  }
275
245
 
276
246
  function userHome() {
@@ -980,7 +950,7 @@ function extractExistingStatusRight(confText) {
980
950
  function tmuxStatusBlock(existingStatusRight = null) {
981
951
  // #{client_width} is expanded by tmux before running the shell command,
982
952
  // giving the responsive layout the actual terminal width to work with.
983
- const battery = `${shQuote(process.execPath)} ${shQuote(fileURLToPath(import.meta.url))} --tmux --bar-width 8 --max-width #{client_width}`;
953
+ const battery = `${shQuote(process.execPath)} ${shQuote(path.join(scriptDir(), "ai-battery.js"))} --tmux --bar-width 8 --max-width #{client_width}`;
984
954
  const batteryPart = `#(${battery})`;
985
955
  // Put the battery on the far right so tmux left-clips the existing text before
986
956
  // the bar. When the block is uninstalled, the earlier set -g status-right wins.
@@ -993,36 +963,49 @@ function tmuxStatusBlock(existingStatusRight = null) {
993
963
  "# AI Battery once per session in the tmux status bar; runners inside tmux",
994
964
  "# see AI_BATTERY_TMUX_STATUS and skip their per-pane bottom row.",
995
965
  "set-environment -g AI_BATTERY_TMUX_STATUS 1",
966
+ "set -g status on",
996
967
  "set -g status-interval 10",
997
968
  `set-option -g status-right-length ${rightLength}`,
998
- `set -g status-right "${statusRightValue}"`,
969
+ `set -g status-right "${statusRightValue.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`,
999
970
  "# <<< ai-battery tmux <<<",
1000
971
  ""
1001
972
  ].join("\n");
1002
973
  }
1003
974
 
1004
- function installTmuxStatus() {
975
+ function installTmuxStatus({ confPath = tmuxConfPath() } = {}) {
1005
976
  if (process.platform === "win32") {
1006
977
  return { skipped: true, reason: "tmux status integration applies to WSL/Linux/macOS" };
1007
978
  }
1008
- const confPath = tmuxConfPath();
1009
979
  let existing = "";
1010
980
  try {
1011
981
  existing = fs.readFileSync(confPath, "utf8");
1012
- } catch {}
982
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
1013
983
  const withoutBlock = stripOwnedBlock(confPath, existing, removeAiBatteryTmuxBlock);
1014
984
  const existingStatusRight = extractExistingStatusRight(withoutBlock);
1015
985
  const next = `${withoutBlock}${tmuxStatusBlock(existingStatusRight)}`;
1016
- if (next === existing) {
1017
- return { ok: true, confPath, changed: false };
986
+ if (next !== existing) installManagedText(confPath, next, next.slice(withoutBlock.length));
987
+ let active = false;
988
+ let error = null;
989
+ if (process.env.TMUX && !process.env.AI_BATTERY_TMUX_CONF) {
990
+ const commands = [
991
+ "set-environment", "-g", "AI_BATTERY_TMUX_STATUS", "1", ";",
992
+ "set-option", "-g", "status", "on", ";",
993
+ "set-option", "-g", "status-interval", "10", ";",
994
+ "set-option", "-g", "status-right-length", "200", ";",
995
+ "set-option", "-g", "status-right", `${existingStatusRight ? `${existingStatusRight} ` : ""}#(${shQuote(process.execPath)} ${shQuote(path.join(scriptDir(), "ai-battery.js"))} --tmux --bar-width 8 --max-width #{client_width}) `
996
+ ];
997
+ const result = spawnSync("tmux", commands, { encoding: "utf8", timeout: 4000 });
998
+ active = !result.error && result.status === 0;
999
+ if (!active) error = result.error?.message || result.stderr?.trim() || "Could not apply the tmux status bar";
1018
1000
  }
1019
- installManagedText(confPath, next, next.slice(withoutBlock.length));
1020
1001
  return {
1021
- ok: true,
1002
+ ok: !error,
1022
1003
  confPath,
1023
- changed: true,
1004
+ changed: next !== existing,
1005
+ active,
1006
+ error,
1024
1007
  updated: existing !== withoutBlock,
1025
- note: `Reload tmux to apply: tmux source-file ${confPath} (new panes then hide the per-pane battery row).`
1008
+ note: active ? null : "Start tmux to show the terminal usage bar."
1026
1009
  };
1027
1010
  }
1028
1011
 
@@ -1097,25 +1080,19 @@ function ensureShimPath(shimDir, originalCommand) {
1097
1080
  const originalDir = path.dirname(originalCommand);
1098
1081
  const originalIndex = entries.findIndex((entry) => path.resolve(entry) === path.resolve(originalDir));
1099
1082
  const activeNow = shimIndex >= 0 && (originalIndex < 0 || shimIndex < originalIndex);
1100
- if (activeNow) {
1101
- return {
1102
- changed: false,
1103
- rcPath: null,
1104
- note: `${shimDir} is already before the original codex on PATH. Plain "codex" can use AI Battery in new command lookups. If this shell already cached codex, run "hash -r" once.`
1105
- };
1106
- }
1107
-
1108
1083
  const rcPath = shellRcPath();
1109
1084
  fs.mkdirSync(path.dirname(rcPath), { recursive: true });
1110
1085
  const existing = fs.existsSync(rcPath) ? fs.readFileSync(rcPath, "utf8") : "";
1111
1086
  const withoutAiBatteryBlock = stripOwnedBlock(rcPath, existing, removeAiBatteryShellPathBlock);
1112
1087
  const separator = withoutAiBatteryBlock && !withoutAiBatteryBlock.endsWith("\n") ? "\n" : "";
1113
1088
  const next = `${withoutAiBatteryBlock}${separator}${shellPathBlock(shimDir)}`;
1114
- installManagedText(rcPath, next, next.slice(withoutAiBatteryBlock.length));
1089
+ const changed = next !== existing;
1090
+ if (changed) installManagedText(rcPath, next, next.slice(withoutAiBatteryBlock.length));
1115
1091
 
1116
1092
  return {
1117
- changed: true,
1118
- rcPath,
1093
+ changed,
1094
+ persisted: true,
1095
+ rcPath: changed || !activeNow ? rcPath : null,
1119
1096
  note: `${existing === withoutAiBatteryBlock ? "Added" : "Updated"} ${shimDir} before PATH in ${rcPath}. Open a new terminal for plain "codex" to use AI Battery.`
1120
1097
  };
1121
1098
  }
@@ -1124,6 +1101,7 @@ function codexWrapperCandidates(config = readConfig()) {
1124
1101
  const activeCodex = findCommand("codex");
1125
1102
  return uniquePaths([
1126
1103
  config.codexWrapper?.wrapperPath,
1104
+ ...(config.codexWrapper?.compatibilityWrappers || []).map(item => item.wrapperPath),
1127
1105
  process.env.AI_BATTERY_SHIM_DIR ? codexWrapperPathInDir(process.env.AI_BATTERY_SHIM_DIR) : null,
1128
1106
  codexWrapperPathInDir(defaultCodexShimDir()),
1129
1107
  legacyCodexWrapperPath(),
@@ -1152,6 +1130,7 @@ function codexTimestampBackups(wrapperPath) {
1152
1130
  function codexWrapperBackupCandidates(wrapperPath, config = readConfig()) {
1153
1131
  return uniquePaths([
1154
1132
  config.codexWrapper?.wrapperPath === wrapperPath ? config.codexWrapper?.backupPath : null,
1133
+ ...(config.codexWrapper?.compatibilityWrappers || []).filter(item => samePath(item.wrapperPath, wrapperPath)).map(item => item.backupPath),
1155
1134
  `${wrapperPath}${CODEX_PREFERRED_BACKUP_SUFFIX}`,
1156
1135
  ...codexTimestampBackups(wrapperPath)
1157
1136
  ]);
@@ -1591,6 +1570,7 @@ function canRemoveCodexWrapperWithoutBackup(wrapperPath, config = readConfig())
1591
1570
  if (samePath(wrapperPath, legacyCodexWrapperPath())) return true;
1592
1571
  const configuredWrapper = config.codexWrapper?.wrapperPath;
1593
1572
  if (configuredWrapper && samePath(wrapperPath, configuredWrapper)) return true;
1573
+ if (config.codexWrapper?.compatibilityWrappers?.some(item => item.owned && samePath(item.wrapperPath, wrapperPath))) return true;
1594
1574
  return false;
1595
1575
  }
1596
1576
 
@@ -1687,13 +1667,9 @@ function uninstallCodexWrapper() {
1687
1667
  ? removeManagedCodexBridge(configuredWrapperPath)
1688
1668
  : null;
1689
1669
 
1690
- const configuredBlocked = Boolean(
1691
- configuredWrapperPath
1692
- && (
1693
- unmanaged.some((wrapperPath) => samePath(wrapperPath, configuredWrapperPath))
1694
- || skippedWrappers.some((item) => samePath(item.wrapperPath, configuredWrapperPath))
1695
- )
1696
- );
1670
+ const recordedWrappers = [configuredWrapperPath, ...(config.codexWrapper?.compatibilityWrappers || []).map(item => item.wrapperPath)].filter(Boolean);
1671
+ const configuredBlocked = recordedWrappers.some(file => unmanaged.some(wrapperPath => samePath(wrapperPath, file))
1672
+ || skippedWrappers.some(item => samePath(item.wrapperPath, file)));
1697
1673
  const hadConfig = Boolean(config.codexWrapper);
1698
1674
  const clearedWrapperConfig = hadConfig && !configuredBlocked;
1699
1675
  const rcPaths = configuredBlocked
@@ -1745,9 +1721,13 @@ function installCodexWrapper(args) {
1745
1721
  };
1746
1722
  }
1747
1723
 
1748
- const shimSelection = selectCodexShimDir(originalCommand, originalPathForPath);
1724
+ const configuredWrapper = config.codexWrapper?.wrapperPath;
1725
+ const shimSelection = configuredWrapper && !process.env.AI_BATTERY_SHIM_DIR
1726
+ ? { shimDir: path.dirname(configuredWrapper), immediate: pathDirPrecedesOriginal(path.dirname(configuredWrapper), originalPathForPath), reason: "Existing Codex integration" }
1727
+ : selectCodexShimDir(originalCommand, originalPathForPath);
1749
1728
  const shimDir = shimSelection.shimDir;
1750
1729
  const wrapperPath = codexWrapperPathInDir(shimDir);
1730
+ const newlyInstalled = !fs.existsSync(wrapperPath);
1751
1731
 
1752
1732
  if (samePath(wrapperPath, originalCommand)) {
1753
1733
  return {
@@ -1758,7 +1738,7 @@ function installCodexWrapper(args) {
1758
1738
  }
1759
1739
 
1760
1740
  fs.mkdirSync(shimDir, { recursive: true, mode: 0o755 });
1761
- let backupPath = null;
1741
+ const backupPath = existingCodexWrapperBackup(wrapperPath, config) || null;
1762
1742
  if (fs.existsSync(wrapperPath) && !managedCodexWrapper(wrapperPath)) {
1763
1743
  return {
1764
1744
  ok: false,
@@ -1769,13 +1749,16 @@ function installCodexWrapper(args) {
1769
1749
 
1770
1750
  const bridgePath = process.platform === "win32" ? codexWrapperBridgePath(wrapperPath) : null;
1771
1751
  if (bridgePath) writeTextAtomic(bridgePath, windowsCodexWrapperBridge());
1772
- fs.writeFileSync(wrapperPath, codexWrapperScriptForPlatform(originalCommand), { mode: 0o755 });
1752
+ writeTextAtomic(wrapperPath, codexWrapperScriptForPlatform(originalCommand), 0o755);
1773
1753
 
1774
- const wrapperCleanup = [];
1775
- for (const staleWrapperPath of codexInstallSkipPaths(config)) {
1754
+ const compatibilityWrappers = [];
1755
+ for (const staleWrapperPath of codexWrapperCandidates(config)) {
1776
1756
  if (samePath(staleWrapperPath, wrapperPath)) continue;
1777
1757
  if (!fs.existsSync(staleWrapperPath) || !managedCodexWrapper(staleWrapperPath)) continue;
1778
- wrapperCleanup.push(removeOrRestoreCodexWrapper(staleWrapperPath, config));
1758
+ const previousBackup = existingCodexWrapperBackup(staleWrapperPath, config) || null;
1759
+ if (process.platform === "win32") writeTextAtomic(codexWrapperBridgePath(staleWrapperPath), windowsCodexWrapperBridge());
1760
+ writeTextAtomic(staleWrapperPath, codexWrapperScriptForPlatform(originalCommand), 0o755);
1761
+ compatibilityWrappers.push({ wrapperPath: staleWrapperPath, backupPath: previousBackup, owned: canRemoveCodexWrapperWithoutBackup(staleWrapperPath, config) });
1779
1762
  }
1780
1763
 
1781
1764
  const pathResult = ensureShimPath(shimDir, originalPathForPath || originalCommand);
@@ -1786,6 +1769,7 @@ function installCodexWrapper(args) {
1786
1769
  originalCommand,
1787
1770
  backupPath,
1788
1771
  bridgePath,
1772
+ compatibilityWrappers,
1789
1773
  pathAddedByAiBattery: process.platform === "win32"
1790
1774
  ? (pathResult.changed
1791
1775
  ? shimDir
@@ -1798,11 +1782,11 @@ function installCodexWrapper(args) {
1798
1782
  return {
1799
1783
  ok: true,
1800
1784
  wrapperPath,
1785
+ newlyInstalled,
1801
1786
  originalCommand,
1802
1787
  backupPath,
1803
1788
  bridgePath,
1804
- legacyCleanup: wrapperCleanup,
1805
- wrapperCleanup,
1789
+ preservedWrappers: compatibilityWrappers.map(item => item.wrapperPath),
1806
1790
  shimSelection,
1807
1791
  path: pathResult
1808
1792
  };
@@ -1921,10 +1905,10 @@ function diagnoseCodex() {
1921
1905
  notes.push("Codex wrapper is not installed. Run: ai-battery setup codex");
1922
1906
  }
1923
1907
  if (!statusLine.configured) {
1924
- notes.push("Codex's optional built-in status_line is not configured. Use --configure-codex-statusline with setup codex only if desired; AI Battery usage display does not require it.");
1908
+ notes.push("Codex status_line is not configured. Run: ai-battery setup codex");
1925
1909
  }
1926
1910
  if (activeIsWrapper && !wrapperInstalled) {
1927
- notes.push("Plain \"codex\" still resolves to an AI Battery wrapper outside the configured shim. Run: ai-battery reset settings codex");
1911
+ notes.push("Plain \"codex\" still resolves to an AI Battery wrapper outside the configured shim. Run: ai-battery reset codex");
1928
1912
  }
1929
1913
  if (activeWrapperBackup) {
1930
1914
  notes.push(`A Codex backup is available for restore: ${activeWrapperBackup}`);
@@ -2069,6 +2053,7 @@ async function runDoctor() {
2069
2053
  }
2070
2054
  },
2071
2055
  codex: diagnoseCodex(),
2056
+ ...(process.platform !== "win32" ? { tmux: diagnoseTmux() } : {}),
2072
2057
  claude: {
2073
2058
  providerEnabled: providerVisible("claude"),
2074
2059
  cachePath: claudeCachePath(),
@@ -2088,6 +2073,15 @@ async function runDoctor() {
2088
2073
  };
2089
2074
  }
2090
2075
 
2076
+ function diagnoseTmux() {
2077
+ const confPath = tmuxConfPath();
2078
+ let configured = false;
2079
+ let error = null;
2080
+ try { const text = fs.readFileSync(confPath, "utf8"); configured = removeAiBatteryTmuxBlock(text) !== text; }
2081
+ catch (cause) { if (cause.code !== "ENOENT") error = cause.message; }
2082
+ return { available: Boolean(findCommand("tmux")), confPath, configured, insideTmux: Boolean(process.env.TMUX), error };
2083
+ }
2084
+
2091
2085
  function windowsCscPath() {
2092
2086
  const windir = process.env.WINDIR || "C:\\Windows";
2093
2087
  const candidates = [
@@ -2256,6 +2250,19 @@ function setupTargets(targets) {
2256
2250
 
2257
2251
  function runSetup(args) {
2258
2252
  const targets = setupTargets(args.targets);
2253
+ const previous = readConfig({ strict: true });
2254
+ let tmuxRefreshPath = null;
2255
+ if ((!args.targets.length || args.targets.includes("all")) && process.platform !== "win32") {
2256
+ const confPath = tmuxConfPath();
2257
+ const recorded = Object.entries(previous.integrationFiles || {}).filter(([, record]) => record.block?.includes("# >>> ai-battery tmux >>>"));
2258
+ let configured = false;
2259
+ try { const text = fs.readFileSync(confPath, "utf8"); configured = removeAiBatteryTmuxBlock(text) !== text; }
2260
+ catch (error) { if (error.code !== "ENOENT") throw error; }
2261
+ if ((recorded.length || configured) && !targets.includes("tmux")) {
2262
+ targets.push("tmux");
2263
+ tmuxRefreshPath = configured || process.env.AI_BATTERY_TMUX_CONF ? confPath : recorded[0][0];
2264
+ }
2265
+ }
2259
2266
  const results = {};
2260
2267
  let windowsClaudeLauncher = null;
2261
2268
  if (targets.includes("claude")) {
@@ -2268,27 +2275,23 @@ function runSetup(args) {
2268
2275
  }
2269
2276
  }
2270
2277
  if (targets.includes("tmux")) {
2271
- results.tmux = installTmuxStatus();
2278
+ results.tmux = installTmuxStatus(tmuxRefreshPath ? { confPath: tmuxRefreshPath } : {});
2272
2279
  }
2273
2280
  if (targets.includes("codex")) {
2274
- const statusLine = args.wrapCodex && args.configureCodexStatusLine ? installCodexStatusLine(args) : null;
2275
- if (args.wrapCodex) {
2281
+ const wrapCodex = args.wrapCodex || Boolean(previous.codexWrapper)
2282
+ || codexWrapperCandidates(previous).some(file => managedCodexWrapper(file));
2283
+ const statusLine = args.configureCodexStatusLine ? installCodexStatusLine(args) : null;
2284
+ if (wrapCodex) {
2276
2285
  results.codex = { ...installCodexWrapper(args), statusLine };
2277
2286
  } else {
2278
- const legacyCleanup = uninstallCodexWrapper();
2279
- const failed = teardownResultFailed({ results: { codex: legacyCleanup } });
2280
2287
  results.codex = {
2281
- ok: !failed,
2282
- standalone: !failed,
2283
- skipped: failed,
2284
- legacyCleanup,
2285
- reason: failed ? "Could not safely detach the legacy Codex integration; kept recovery metadata. Run ai-battery reset settings codex for details."
2286
- : "Codex command and configuration are left under Codex's control. Use ai-battery hud or ai-battery-run -- codex for usage display."
2288
+ ok: true,
2289
+ standalone: true,
2290
+ reason: "Codex command and configuration are left under Codex's control.",
2291
+ statusLine
2287
2292
  };
2288
- // An explicit status-line request is applied after legacy restoration.
2289
- if (args.configureCodexStatusLine && !failed) results.codex.statusLine = installCodexStatusLine(args);
2290
2293
  }
2291
- if (process.platform === "win32" && args.wrapCodex) {
2294
+ if (process.platform === "win32" && wrapCodex) {
2292
2295
  results.codex.rowpty = windowsSetupNeedsRowPty()
2293
2296
  ? (windowsClaudeLauncher || installRowPtyHost())
2294
2297
  : {
@@ -2325,7 +2328,7 @@ function runHud(args) {
2325
2328
  }
2326
2329
 
2327
2330
  function desktopHudSupported() {
2328
- return process.platform === "darwin" || process.platform === "win32" || isWsl();
2331
+ return ["darwin", "win32", "linux"].includes(process.platform);
2329
2332
  }
2330
2333
 
2331
2334
  function childResult(result) {
@@ -2359,10 +2362,12 @@ function uninstallHud() {
2359
2362
 
2360
2363
  const stop = runHudCommand(["stop"]);
2361
2364
  const autostart = runHudCommand(["autostart", "off"]);
2365
+ const gnome = process.platform === "linux" && !isWsl() ? runHudCommand(["--remove-gnome"]) : null;
2362
2366
  return {
2363
2367
  changed: autostart.ok || stop.ok,
2364
2368
  autostart,
2365
- stop
2369
+ stop,
2370
+ ...(gnome ? { gnome } : {})
2366
2371
  };
2367
2372
  }
2368
2373
 
@@ -2640,6 +2645,7 @@ function teardownResultFailed(result) {
2640
2645
  || item?.statusLine?.skipped
2641
2646
  || (item?.autostart && !item.autostart.ok)
2642
2647
  || (item?.stop && !item.stop.ok)
2648
+ || (item?.gnome && !item.gnome.ok)
2643
2649
  ));
2644
2650
  }
2645
2651
 
@@ -4372,7 +4378,7 @@ function weekText(secondary) {
4372
4378
  }
4373
4379
 
4374
4380
  function formatCodex(data, args) {
4375
- if (!data.ok) return statusColorize(data, `Codex ? (${data.error})`, args);
4381
+ if (!data.ok) return statusColorize(data, `Codex ? (${cliMessageText(data.error)})`, args);
4376
4382
 
4377
4383
  const batteryColor = remainingColor(data.percentRemaining);
4378
4384
  const primary = data.primary;
@@ -4407,7 +4413,7 @@ function formatCodex(data, args) {
4407
4413
  }
4408
4414
 
4409
4415
  function formatClaude(data, args) {
4410
- if (!data.ok) return statusColorize(data, `Claude ? (${data.error})`, args);
4416
+ if (!data.ok) return statusColorize(data, `Claude ? (${cliMessageText(data.error)})`, args);
4411
4417
 
4412
4418
  if (data.sourceType === "statusline") {
4413
4419
  const batteryColor = remainingColor(data.percentRemaining);
@@ -4914,6 +4920,27 @@ function renderMenuDetailImage(snapshot) {
4914
4920
  throw new Error("Could not write macOS menu detail image");
4915
4921
  }
4916
4922
 
4923
+ function desktopHudSnapshot(provider = "all") {
4924
+ const args = parseArgs(["--provider", provider]);
4925
+ const snapshot = collect(args);
4926
+ return {
4927
+ generatedAt: snapshot.generatedAt,
4928
+ state: renderHudState(snapshot),
4929
+ panelImage: renderMenuBarImage(snapshot),
4930
+ detailImage: renderMenuDetailImage(snapshot),
4931
+ text: renderLine(snapshot, { ...args, style: "plain" }),
4932
+ rows: snapshot.results.filter(Boolean).map((result) => ({
4933
+ provider: result.provider,
4934
+ label: result.provider === "codex" ? "Codex" : "Claude",
4935
+ percent: typeof result.percentRemaining === "number" ? clamp(result.percentRemaining, 0, 100) : null,
4936
+ running: result.running === true,
4937
+ meta: result.ok ? menuDetailMetaText(result) : "unavailable",
4938
+ activity: menuDetailUsageUpdateText(result),
4939
+ error: result.error ? cliMessageText(result.error) : null
4940
+ }))
4941
+ };
4942
+ }
4943
+
4917
4944
  function applyLeftPadding(output, args) {
4918
4945
  const padding = Math.max(0, Number(args.leftPadding) || 0);
4919
4946
  if (!padding) return output;
@@ -4963,101 +4990,10 @@ function render(snapshot, args) {
4963
4990
  }
4964
4991
 
4965
4992
  function printTeardownResult(result) {
4966
- if (result.skipped) {
4967
- console.log(`Teardown skipped: ${result.reason}`);
4968
- return;
4969
- }
4970
-
4971
- const { codex, claude, hud } = result.results;
4972
- if (codex) {
4973
- if (codex.error) {
4974
- console.log(`Codex wrapper error: ${codex.error}`);
4975
- } else {
4976
- for (const restored of codex.restoredWrappers || []) {
4977
- console.log(`Restored Codex command: ${restored.wrapperPath}`);
4978
- console.log(`Restored from: ${restored.restoredFrom}`);
4979
- }
4980
- for (const wrapperPath of codex.removedWrappers || []) {
4981
- console.log(`Removed Codex wrapper: ${wrapperPath}`);
4982
- }
4983
- for (const skipped of codex.skippedWrappers || []) {
4984
- console.log(`Left Codex wrapper untouched: ${skipped.wrapperPath}`);
4985
- console.log(`Reason: ${skipped.reason}`);
4986
- }
4987
- if (!(codex.restoredWrappers?.length || codex.removedWrappers?.length || codex.skippedWrappers?.length)) {
4988
- console.log(`Codex wrapper: ${codex.reason}`);
4989
- }
4990
- }
4991
- for (const rcPath of codex.rcPaths || []) {
4992
- console.log(`Removed shell PATH block: ${rcPath}`);
4993
- }
4994
- if (codex.statusLine) {
4995
- if (codex.statusLine.error) {
4996
- console.log(`Codex status_line error: ${codex.statusLine.error}`);
4997
- } else if (codex.statusLine.restored) {
4998
- console.log(`Restored Codex status_line: ${codex.statusLine.configPath}`);
4999
- } else if (codex.statusLine.removed) {
5000
- console.log(`Removed Codex status_line: ${codex.statusLine.configPath}`);
5001
- } else if (codex.statusLine.skipped) {
5002
- console.log(`Left Codex status_line untouched: ${codex.statusLine.configPath}`);
5003
- console.log(`Reason: ${codex.statusLine.reason}`);
5004
- }
5005
- }
5006
- if (codex.configPath) console.log(`Updated ${codex.configPath}`);
5007
- for (const wrapperPath of codex.unmanaged || []) {
5008
- console.log(`Skipped unmanaged codex command: ${wrapperPath}`);
5009
- }
5010
- }
5011
-
5012
- if (claude) {
5013
- if (claude.error) {
5014
- console.log(`Claude statusLine error: ${claude.error}`);
5015
- } else if (claude.changed) {
5016
- console.log(`${claude.restored ? "Restored previous Claude statusLine" : "Removed Claude statusLine"}: ${claude.settingsPath}`);
5017
- } else {
5018
- console.log(`${claude.reason}: ${claude.settingsPath}`);
5019
- }
5020
- }
5021
-
5022
- if (hud) {
5023
- if (hud.error) {
5024
- console.log(`HUD error: ${hud.error}`);
5025
- } else if (hud.skipped) {
5026
- console.log(`HUD: ${hud.reason}`);
5027
- } else {
5028
- console.log(`HUD autostart: ${hud.autostart.ok ? "off" : "not changed"}`);
5029
- if (!hud.autostart.ok && hud.autostart.error) console.log(`HUD autostart error: ${hud.autostart.error}`);
5030
- if (!hud.autostart.ok && hud.autostart.stderr) console.log(`HUD autostart error: ${hud.autostart.stderr}`);
5031
- console.log(`HUD process: ${hud.stop.ok ? "stopped" : "not changed"}`);
5032
- if (!hud.stop.ok && hud.stop.error) console.log(`HUD stop error: ${hud.stop.error}`);
5033
- if (!hud.stop.ok && hud.stop.stderr) console.log(`HUD stop error: ${hud.stop.stderr}`);
5034
- }
5035
- }
5036
-
5037
- if (runningInsideAiBatteryCodexWrapper()) {
5038
- console.log("Current Codex session was already started through AI Battery; exit this session to remove the terminal row.");
5039
- }
5040
- const artifacts = result.results.artifacts;
5041
- for (const [name, item] of Object.entries(result.results)) {
5042
- if (["codex", "claude", "hud", "artifacts"].includes(name)) continue;
5043
- if (item.error) console.log(`${name} cleanup error: ${item.error}`);
5044
- for (const error of item.errors || []) console.log(`${name} cleanup error: ${error.path}: ${error.error}`);
5045
- for (const file of item.paths || []) console.log(`Recovery pending: ${file}`);
5046
- }
5047
- if (artifacts) {
5048
- for (const file of artifacts.removed) console.log(`Removed AI Battery artifact: ${file}`);
5049
- for (const file of artifacts.retained) console.log(`Preserved unrecognized or user-owned file: ${file}`);
5050
- for (const item of artifacts.errors) console.log(`Cleanup error: ${item.path}: ${item.error}`);
5051
- }
5052
- if (teardownResultFailed(result)) {
5053
- console.log("Settings reset incomplete; recovery metadata and npm package were preserved.");
5054
- } else {
5055
- console.log("AI Battery settings reset; npm package was left unchanged.");
5056
- console.log("To remove the package: npm uninstall -g ai-battery");
5057
- }
5058
- if (result.targets.includes("codex") && process.platform !== "win32") {
5059
- console.log("In this existing Bash terminal, run: hash -r (zsh: rehash). A child process cannot clear its parent shell's cached command paths.");
5060
- }
4993
+ console.log(formatResetResult(result, {
4994
+ failed: teardownResultFailed(result),
4995
+ wrapped: runningInsideAiBatteryCodexWrapper()
4996
+ }));
5061
4997
  }
5062
4998
 
5063
4999
  async function main() {
@@ -5067,86 +5003,29 @@ async function main() {
5067
5003
  return;
5068
5004
  }
5069
5005
  if (args.help) {
5070
- printHelp();
5006
+ printHelp(args.helpTopic || (args.watch ? "watch" : ""));
5071
5007
  return;
5072
5008
  }
5073
5009
 
5074
5010
  if (args.command === "setup") {
5075
5011
  const result = runSetup(args);
5012
+ const failed = setupResultFailed(result);
5076
5013
  if (args.json) {
5077
5014
  console.log(JSON.stringify(result, null, 2));
5078
5015
  } else {
5079
- if (result.claude) {
5080
- if (result.claude.skipped) {
5081
- console.log(`Claude statusLine skipped: ${result.claude.reason}`);
5082
- } else {
5083
- console.log(`Claude statusLine installed: ${result.claude.settingsPath}`);
5084
- if (result.claude.backedUp) console.log("Saved the pre-setup Claude statusLine state for uninstall recovery.");
5085
- if (process.platform === "win32") {
5086
- console.log("Windows note: Claude's header appears inside Claude Code; its first statusLine payload attaches the shared usage HUD to the terminal. Restart Claude Code if it was already open.");
5087
- }
5088
- }
5089
- }
5090
- if (result.codex?.standalone) {
5091
- console.log(result.codex.reason);
5092
- if (process.platform !== "win32" && result.codex.legacyCleanup.changed) {
5093
- console.log("Removed legacy Codex integration. In this existing Bash terminal run: hash -r (zsh: rehash).");
5094
- }
5095
- } else if (result.codex?.ok) {
5096
- console.log(`Codex wrapper installed: ${result.codex.wrapperPath}`);
5097
- console.log(`Original codex: ${result.codex.originalCommand}`);
5098
- if (result.codex.path?.note) console.log(result.codex.path.note);
5099
- const reloadCommand = sourcePathCommand(result.codex.path?.rcPath);
5100
- if (reloadCommand) console.log(`For this terminal now, run: ${reloadCommand}`);
5101
- } else if (result.codex?.skipped) {
5102
- console.log(`Codex wrapper skipped: ${result.codex.reason}`);
5103
- }
5104
- if (result.codex?.statusLine) {
5105
- if (result.codex.statusLine.error) {
5106
- console.log(`Codex status_line error: ${result.codex.statusLine.error}`);
5107
- } else if (result.codex.statusLine.changed) {
5108
- console.log(`Codex status_line configured: ${result.codex.statusLine.configPath}`);
5109
- if (result.codex.statusLine.backedUp) console.log("Backed up previous Codex status_line for uninstall restore.");
5110
- } else if (result.codex.statusLine.alreadyConfigured) {
5111
- console.log(`Codex status_line already configured: ${result.codex.statusLine.configPath}`);
5112
- }
5113
- }
5114
- if (result.tmux) {
5115
- if (result.tmux.ok) {
5116
- console.log(`tmux status bar ${result.tmux.changed ? "configured" : "already configured"}: ${result.tmux.confPath}`);
5117
- if (result.tmux.note) console.log(result.tmux.note);
5118
- } else if (result.tmux.skipped) {
5119
- console.log(`tmux integration skipped: ${result.tmux.reason}`);
5120
- }
5121
- }
5122
- if (result.codex?.rowpty) {
5123
- const rowpty = result.codex.rowpty;
5124
- if (rowpty.ok && !rowpty.skipped) {
5125
- console.log(`rowpty host ${rowpty.compiled ? "compiled locally from vendored source" : "already up to date"}: ${rowpty.exePath} (ConPTY: ${rowpty.conpty})`);
5126
- } else if (rowpty.error) {
5127
- console.log(`rowpty host build failed: ${rowpty.error}`);
5128
- console.log("Windows Codex TUI will use the overlay fallback until this is resolved.");
5129
- } else if (rowpty.skipped) {
5130
- console.log(`rowpty host skipped: ${rowpty.reason}`);
5131
- }
5132
- }
5133
- if (result.codex?.retainedConfig) {
5134
- console.log("Kept the Codex recovery record because the configured wrapper could not be safely removed.");
5135
- }
5136
- if (process.platform === "win32" && result.codex?.ok && !result.codex.standalone) {
5137
- console.log("Windows terminal note: Codex uses fullscreen PTY composition by default, with a private VT-capable Node runtime when needed and a native HUD fallback. Open a new cmd/PowerShell after setup.");
5138
- }
5139
- console.log("To restore settings later, run: ai-battery reset settings");
5140
- const note = codexRestartNote();
5141
- if (result.codex && note) console.log(note);
5016
+ console.log(formatSetupResult(result, {
5017
+ failed,
5018
+ reloadCommand: sourcePathCommand(result.codex?.path?.rcPath),
5019
+ restartNote: result.codex && !result.codex.standalone ? codexRestartNote() : null
5020
+ }));
5142
5021
  }
5143
- if (setupResultFailed(result)) process.exitCode = 1;
5022
+ if (failed) process.exitCode = 1;
5144
5023
  return;
5145
5024
  }
5146
5025
 
5147
5026
  if (["reset", "teardown", "uninstall"].includes(args.command)) {
5148
5027
  if (!args.silent && !args.json && args.command !== "reset") {
5149
- console.log(`\"${args.command}\" is a compatibility alias for \"reset settings\"; npm package removal is separate.`);
5028
+ console.log(cliText(`"${args.command}" is an alias for "reset".`, `"${args.command}"는 "reset"의 호환 명령입니다.`));
5150
5029
  }
5151
5030
  const result = runTeardown(args);
5152
5031
  if (args.json) {
@@ -5160,67 +5039,7 @@ async function main() {
5160
5039
 
5161
5040
  if (args.command === "doctor") {
5162
5041
  const result = await runDoctor();
5163
- if (args.json) {
5164
- console.log(JSON.stringify(result, null, 2));
5165
- } else {
5166
- console.log(`AI Battery: ${result.aiBattery.script}`);
5167
- console.log(`Version: ${result.aiBattery.version}`);
5168
- if (result.aiBattery.latestVersion) {
5169
- console.log(`npm latest: ${result.aiBattery.latestVersion}`);
5170
- if (result.aiBattery.updateAvailable) {
5171
- console.log(`Update: available (npm install -g ${result.aiBattery.packageName}@latest)`);
5172
- } else if (compareVersions(result.aiBattery.version, result.aiBattery.latestVersion) > 0) {
5173
- console.log("Update: local version is newer than npm latest");
5174
- } else {
5175
- console.log("Update: up to date");
5176
- }
5177
- } else if (result.aiBattery.updateCheck.error === "disabled") {
5178
- console.log("npm latest: skipped");
5179
- } else {
5180
- console.log(`npm latest: unavailable (${result.aiBattery.updateCheck.error || "unknown error"})`);
5181
- }
5182
- console.log(`State: ${result.aiBattery.stateDir}`);
5183
- const recovery = result.aiBattery.recovery;
5184
- const claudeRecovery = recovery.claudeStatusLine
5185
- ? `yes (${recovery.claudeOriginalKnown ? "original recorded" : "legacy original unknown"})`
5186
- : "no";
5187
- console.log(`Recovery: Codex wrapper ${recovery.codexWrapper ? "yes" : "no"}, Codex status_line ${recovery.codexStatusLine ? "yes" : "no"}, Claude statusLine ${claudeRecovery}`);
5188
- console.log("");
5189
- console.log(`Codex provider: ${result.codex.providerEnabled ? "on" : "off"}`);
5190
- console.log(`Codex on PATH: ${result.codex.activeCodex || "not found"}`);
5191
- console.log(`Codex wrapper: ${result.codex.wrapperInstalled ? "installed" : "missing"} (${result.codex.wrapperPath})`);
5192
- console.log(`Codex status_line: ${result.codex.statusLine.configured ? "configured" : "missing"} (${result.codex.statusLine.configPath})`);
5193
- console.log(`AI Battery runner: ${result.codex.runnerExists ? "found" : "missing"} (${result.codex.runnerPath})`);
5194
- if (result.codex.compositor) {
5195
- console.log(`Windows compositor: ${result.codex.compositor.available ? "ready" : "dependencies missing"}`);
5196
- console.log(` @xterm/headless: ${result.codex.compositor.headlessTerminal || "missing"}`);
5197
- console.log(` node-pty: ${result.codex.compositor.nodePty || "missing"}`);
5198
- }
5199
- if (result.codex.rowpty) {
5200
- const conptyLabel = result.codex.rowpty.bundledConptyRequested
5201
- ? (result.codex.rowpty.bundledConpty ? "bundled ConPTY requested" : "bundled ConPTY requested but missing")
5202
- : (result.codex.rowpty.bundledConpty ? "OS ConPTY default, bundled provider available" : "OS ConPTY default");
5203
- const rowptyLabel = result.codex.rowpty.installed
5204
- ? `found, ${conptyLabel} (${result.codex.rowpty.path})`
5205
- : (result.codex.rowpty.layoutRequested
5206
- ? "missing (required by the selected legacy TUI layout)"
5207
- : "not installed (not required by the default PTY compositor)");
5208
- console.log(`rowpty host: ${rowptyLabel}`);
5209
- }
5210
- console.log(`python3: ${result.codex.python3 || "not found"}`);
5211
- console.log(`PATH uses wrapper: ${result.codex.activeIsWrapper ? "yes" : "no"}`);
5212
- console.log(`Inside Codex: ${result.codex.insideCodex ? "yes" : "no"}`);
5213
- console.log(`Current Codex wrapped: ${result.codex.currentCodexWrapped ? "yes" : "no"}`);
5214
- if (result.codex.notes.length) {
5215
- console.log("");
5216
- for (const note of result.codex.notes) console.log(`- ${note}`);
5217
- }
5218
- console.log("");
5219
- console.log(`Claude provider: ${result.claude.providerEnabled ? "on" : "off"}`);
5220
- console.log(`Claude statusLine: ${result.claude.statusLine.managed ? "managed by AI Battery" : (result.claude.statusLine.configured ? "configured by another tool" : "missing")} (${result.claude.statusLine.settingsPath})`);
5221
- console.log(`Claude statusLine cache: ${result.claude.statuslineCache ? "found" : "missing"}`);
5222
- for (const note of result.claude.notes) console.log(`- ${note}`);
5223
- }
5042
+ console.log(args.json ? JSON.stringify(result, null, 2) : formatDoctorResult(result));
5224
5043
  return;
5225
5044
  }
5226
5045
 
@@ -5232,46 +5051,22 @@ async function main() {
5232
5051
  if (args.command === "on" || args.command === "off") {
5233
5052
  const visible = args.command === "on";
5234
5053
  const result = setProviderVisibility(args.targets, visible);
5235
- if (args.json) {
5236
- console.log(JSON.stringify(result, null, 2));
5237
- } else {
5238
- const state = visible ? "on" : "off";
5239
- console.log(`${result.providers.join(", ")} ${state}`);
5240
- console.log(`Updated ${result.configPath}`);
5241
- const note = visible && result.providers.includes("codex") ? codexRestartNote() : null;
5242
- if (note) console.log(note);
5243
- }
5054
+ console.log(args.json ? JSON.stringify(result, null, 2) : formatVisibilityResult(result, {
5055
+ restartNote: visible && result.providers.includes("codex") && readConfig().codexWrapper ? codexRestartNote() : null
5056
+ }));
5244
5057
  return;
5245
5058
  }
5246
5059
 
5247
5060
  if (args.command === "install-claude-statusline") {
5248
5061
  const result = installClaudeStatusline(args);
5249
- if (!args.json) {
5250
- if (result.skipped) {
5251
- console.log(`Claude statusLine skipped: ${result.reason}`);
5252
- } else {
5253
- console.log(`Installed Claude statusLine: ${result.command}`);
5254
- console.log(`Updated ${result.settingsPath}`);
5255
- if (result.backedUp) console.log("Saved the pre-setup Claude statusLine state for uninstall recovery.");
5256
- }
5257
- } else {
5258
- console.log(JSON.stringify(result, null, 2));
5259
- }
5062
+ console.log(args.json ? JSON.stringify(result, null, 2) : formatClaudeResult(result));
5260
5063
  if (result.error) process.exitCode = 1;
5261
5064
  return;
5262
5065
  }
5263
5066
 
5264
5067
  if (args.command === "uninstall-claude-statusline") {
5265
5068
  const result = uninstallClaudeStatusline();
5266
- if (!args.json) {
5267
- if (result.changed) {
5268
- console.log(`${result.restored ? "Restored previous Claude statusLine in" : "Removed Claude statusLine from"} ${result.settingsPath}`);
5269
- } else {
5270
- console.log(`${result.reason}: ${result.settingsPath}`);
5271
- }
5272
- } else {
5273
- console.log(JSON.stringify(result, null, 2));
5274
- }
5069
+ console.log(args.json ? JSON.stringify(result, null, 2) : formatClaudeResult(result, { removing: true }));
5275
5070
  if (result.error) process.exitCode = 1;
5276
5071
  return;
5277
5072
  }
@@ -5279,7 +5074,9 @@ async function main() {
5279
5074
  if (args.command === "capture-claude") {
5280
5075
  const inputText = await readStdin();
5281
5076
  if (!inputText.trim()) throw new Error("capture-claude expected Claude statusline JSON on stdin");
5282
- const input = JSON.parse(inputText);
5077
+ let input;
5078
+ try { input = JSON.parse(inputText); }
5079
+ catch { throw new Error("capture-claude received invalid JSON"); }
5283
5080
  const capturedClaude = captureClaudeStatusline(input);
5284
5081
  if (args.attachHud) {
5285
5082
  attachWindowsClaudeHud(
@@ -5373,6 +5170,7 @@ export {
5373
5170
  windowsCodexWrapperScript,
5374
5171
  windowsCodexWrapperBridge,
5375
5172
  diagnoseCodex,
5173
+ desktopHudSnapshot,
5376
5174
  compositorDiagnostic,
5377
5175
  firstPercentValue,
5378
5176
  installClaudeStatusline,
@@ -5423,7 +5221,7 @@ function isDirectRun() {
5423
5221
 
5424
5222
  if (isDirectRun()) {
5425
5223
  main().catch((error) => {
5426
- console.error(`ai-battery: ${error.message}`);
5224
+ console.error(`ai-battery: ${errorText(error)}`);
5427
5225
  process.exit(1);
5428
5226
  });
5429
5227
  }