ai-battery 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +30 -14
  2. package/bin/ai-battery-macos-rail.applescript +227 -0
  3. package/bin/ai-battery-macos-status.applescript +5 -12
  4. package/bin/ai-battery-run +701 -31
  5. package/bin/ai-battery-tmux.js +17 -0
  6. package/bin/terminal-compositor.js +111 -0
  7. package/docs/REFERENCE.md +23 -3
  8. package/docs/RELEASING.md +30 -7
  9. package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
  10. package/docs/hud-preview.svg +75 -20
  11. package/docs/terminal-vertical-preview.svg +73 -0
  12. package/lib/cli.js +1148 -240
  13. package/lib/core/atomic-rename.js +18 -0
  14. package/lib/core/cli-help.js +57 -12
  15. package/lib/core/cli-messages.js +45 -1
  16. package/lib/core/cli-output.js +277 -72
  17. package/lib/core/cli-wrappers.js +410 -0
  18. package/lib/core/config-editor.js +194 -29
  19. package/lib/core/display-config.js +45 -0
  20. package/lib/core/integration-files.js +32 -3
  21. package/lib/core/shared-bar.js +603 -0
  22. package/lib/core/statusline-git.js +179 -15
  23. package/lib/core/terminal.js +25 -7
  24. package/lib/core/tmux-status.js +172 -0
  25. package/lib/core/uninstall.js +20 -7
  26. package/lib/core/usage-store.js +85 -0
  27. package/lib/hud/launcher.js +32 -33
  28. package/lib/platforms/linux/gnome-extension/extension.js +7 -6
  29. package/lib/platforms/linux/hud.js +157 -42
  30. package/lib/platforms/linux/panel.js +16 -3
  31. package/lib/platforms/linux/rail.js +412 -0
  32. package/lib/platforms/macos/hud.js +152 -44
  33. package/lib/platforms/process-scanner.js +77 -29
  34. package/lib/platforms/windows/autostart-cleanup.js +1 -1
  35. package/lib/platforms/windows/codex-runner.js +178 -21
  36. package/lib/platforms/windows/hud/controls.ps1 +65 -15
  37. package/lib/platforms/windows/hud/main.ps1 +715 -54
  38. package/lib/platforms/windows/hud/rendering.ps1 +1284 -2
  39. package/lib/platforms/windows/hud/snapshot.ps1 +26 -46
  40. package/lib/platforms/windows/hud-launcher.js +234 -81
  41. package/lib/platforms/windows/shared-bar-platform.js +972 -0
  42. package/lib/platforms/windows/terminal-compositor.js +210 -25
  43. package/lib/platforms/windows/wt-bar.js +729 -0
  44. package/lib/platforms/windows/wt-fragment.js +665 -0
  45. package/lib/platforms/windows/wt-keybinding.js +300 -0
  46. package/lib/providers/antigravity.js +155 -8
  47. package/package.json +6 -2
  48. package/vendor/PaneContext.cs +875 -0
@@ -173,7 +173,7 @@ function Format-Parts($Result, [string]$Name) {
173
173
  $resetValue = "$resetWindow $(Get-ResetClock $Result.primary)".PadRight(8)
174
174
  $resetText = $resetValue
175
175
  }
176
- if ($Result.secondary) {
176
+ if ($Result.secondary -and $null -ne $Result.secondary.remainingPercent) {
177
177
  $weekWindow = Get-WindowText $Result.secondary.windowMinutes
178
178
  # Space plus a thin space (U+2009): a single space reads slightly tighter
179
179
  # here than the "5h <time>" gap because the digits hug their left edge,
@@ -219,50 +219,27 @@ function Copy-MissingProperty($Target, $Source, [string]$Name) {
219
219
  }
220
220
 
221
221
  function Merge-HudSnapshot($Snapshot, $CachedSnapshot) {
222
- if (-not $Snapshot -or -not $Snapshot.results) { return $CachedSnapshot }
223
- $Snapshot.results = @($Snapshot.results)
224
- $nowUtc = [datetime]::UtcNow
225
-
226
- for ($i = 0; $i -lt $Snapshot.results.Count; $i += 1) {
227
- $current = $Snapshot.results[$i]
228
- if (-not $current -or -not $current.provider) { continue }
229
-
230
- $usable = [bool]$current.ok -and $null -ne $current.percentRemaining
231
- if ($usable) {
232
- $current | Add-Member -NotePropertyName "hudCachedAt" -NotePropertyValue $nowUtc.ToString("o") -Force
233
- }
234
- # agy readings already come from a local cache; expired buckets must stay unknown.
235
- if ($current.provider -eq "antigravity") { continue }
236
-
237
- $cached = $null
238
- if ($CachedSnapshot) { $cached = Get-Provider $CachedSnapshot $current.provider }
239
- if (-not $cached -or -not $cached.ok -or $null -eq $cached.percentRemaining) { continue }
240
-
241
- if ($usable) {
242
- Copy-MissingProperty $current $cached "secondary"
243
- continue
244
- }
245
-
246
- # A transient read failure or a fallback row would flash "?"; keep the
247
- # last good reading instead, as long as it is reasonably recent.
248
- $cachedAt = $cached.hudCachedAt
249
- if (-not $cachedAt) { $cachedAt = $CachedSnapshot.generatedAt }
250
- $ageSeconds = $null
251
- try {
252
- $ageSeconds = ($nowUtc - ([datetime]$cachedAt).ToUniversalTime()).TotalSeconds
253
- } catch {
254
- $ageSeconds = $null
255
- }
256
- if ($null -eq $ageSeconds -or $ageSeconds -lt -60 -or $ageSeconds -gt 1800) { continue }
222
+ # The CLI already selects the newest shared provider data. Do not mix a
223
+ # previous quota or weekly bucket back into that authoritative snapshot.
224
+ if (-not $Snapshot -or $null -eq $Snapshot.results) { return $CachedSnapshot }
225
+ return $Snapshot
226
+ }
257
227
 
258
- $replacement = $cached | Select-Object *
259
- if ($null -ne $current.running) {
260
- $replacement | Add-Member -NotePropertyName "running" -NotePropertyValue $current.running -Force
228
+ function Get-CurrentHudSnapshot($Snapshot) {
229
+ if (-not $Snapshot -or $Snapshot.staleData) { return $Snapshot }
230
+ $age = 999999
231
+ try { $age = ([datetime]::UtcNow - ([datetime]$Snapshot.generatedAt).ToUniversalTime()).TotalSeconds } catch {}
232
+ if ($age -le [math]::Max(10, 2 * $Interval + 2)) { return $Snapshot }
233
+ $result = $Snapshot | Select-Object *
234
+ $result | Add-Member -NotePropertyName "staleData" -NotePropertyValue $true -Force
235
+ $result.results = @($Snapshot.results | ForEach-Object {
236
+ $row = $_ | Select-Object *
237
+ foreach ($pair in @(@("ok", $false), @("percentRemaining", $null), @("percentUsed", $null), @("primary", $null), @("secondary", $null))) {
238
+ $row | Add-Member -NotePropertyName $pair[0] -NotePropertyValue $pair[1] -Force
261
239
  }
262
- $Snapshot.results[$i] = $replacement
263
- }
264
-
265
- return $Snapshot
240
+ $row
241
+ })
242
+ return $result
266
243
  }
267
244
 
268
245
  function ConvertTo-HudTexts($Snapshot) {
@@ -302,6 +279,7 @@ function Get-ProviderLabel([string]$Provider) {
302
279
 
303
280
  function Get-Texts {
304
281
  $cachedSnapshot = Read-HudSnapshot
282
+ $shouldWriteSnapshot = $true
305
283
  if ($script:initialHudSnapshot) {
306
284
  $snapshot = Merge-HudSnapshot $script:initialHudSnapshot $cachedSnapshot
307
285
  $script:initialHudSnapshot = $null
@@ -310,13 +288,16 @@ function Get-Texts {
310
288
  $snapshot = Merge-HudSnapshot (Invoke-AiBatteryJson) $cachedSnapshot
311
289
  } catch {
312
290
  if ($cachedSnapshot) {
313
- $snapshot = $cachedSnapshot
291
+ $snapshot = Get-CurrentHudSnapshot $cachedSnapshot
292
+ $shouldWriteSnapshot = $false
314
293
  } else {
315
294
  throw
316
295
  }
317
296
  }
318
297
  }
319
- Write-HudSnapshot $snapshot
298
+ if ($shouldWriteSnapshot) {
299
+ Write-HudSnapshot $snapshot
300
+ }
320
301
  return ConvertTo-HudTexts $snapshot
321
302
  }
322
303
 
@@ -324,7 +305,6 @@ $script:latestSnapshot = $null
324
305
  $script:fetchPowerShell = $null
325
306
  $script:fetchHandle = $null
326
307
  $script:lastFetchStartUtc = [datetime]::MinValue
327
- $script:weeklyRetryCount = 0
328
308
 
329
309
  function Start-SnapshotFetch {
330
310
  if ($script:fetchPowerShell) { return }
@@ -2,9 +2,52 @@ import { spawnSync } from "node:child_process";
2
2
  import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import { atomicRename } from "../../core/atomic-rename.js";
5
6
  import { windowsAutostartCleanupScript } from "./autostart-cleanup.js";
6
7
  import { cliError, cliText, helpText, invalidChoice, requiredValue } from "../../core/cli-help.js";
7
8
  import { errorText } from "../../core/cli-messages.js";
9
+ import { providerId } from "../../core/display-config.js";
10
+
11
+ export function buildWindowsAutostartScript({
12
+ hudSourceDir,
13
+ batteryCommandBase64,
14
+ filteredArgs = [],
15
+ useWsl = false,
16
+ psInvocationArg
17
+ }) {
18
+ const formatArg = psInvocationArg
19
+ || ((value) => (/^-[A-Za-z][A-Za-z0-9]*$/.test(String(value)) ? String(value) : `'${String(value).replace(/'/g, "''")}'`));
20
+ const extraTokens = [];
21
+ for (let i = 0; i < filteredArgs.length; i += 1) {
22
+ const arg = filteredArgs[i];
23
+ const lower = String(arg).toLowerCase();
24
+ if (lower === "-once" || lower === "-stopexisting" || (useWsl && lower === "-usewsl")) continue;
25
+ if (lower === "-batterycommandbase64") {
26
+ i += 1;
27
+ continue;
28
+ }
29
+ extraTokens.push(formatArg(arg));
30
+ }
31
+ const extraArgsText = extraTokens.length ? ` ${extraTokens.join(" ")}` : "";
32
+ const srcDirB64 = Buffer.from(String(hudSourceDir), "utf8").toString("base64");
33
+ const extraArgsB64 = extraArgsText ? Buffer.from(extraArgsText, "utf8").toString("base64") : "";
34
+ return [
35
+ "# Generated by: ai-battery hud autostart on",
36
+ `$srcDir = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${srcDirB64}'))`,
37
+ "$hudDir = Join-Path $PSScriptRoot 'hud'",
38
+ "New-Item -ItemType Directory -Force -Path $hudDir | Out-Null",
39
+ "$hud = Join-Path $hudDir 'ai-battery-hud.ps1'",
40
+ "try { Copy-Item (Join-Path $srcDir '*.ps1') $hudDir -Force -ErrorAction Stop; Copy-Item (Join-Path $srcDir 'main.ps1') $hud -Force -ErrorAction Stop } catch { }",
41
+ `$batteryB64 = '${batteryCommandBase64}'`,
42
+ ...(extraArgsB64 ? [`$extraArgs = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${extraArgsB64}'))`] : []),
43
+ "$invoke = '& ' + \"'\" + ($hud -replace \"'\", \"''\") + \"'\" + ' -BatteryCommandBase64 ' + $batteryB64"
44
+ + (extraArgsB64 ? " + $extraArgs" : "")
45
+ + (useWsl ? " + ' -UseWsl'" : ""),
46
+ "$argList = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ('\"' + ($invoke -replace '\"', '\\\"') + '\"')) -join ' '",
47
+ "Start-Process -WindowStyle Hidden -FilePath 'powershell.exe' -ArgumentList $argList",
48
+ ""
49
+ ].join("\r\n");
50
+ }
8
51
 
9
52
  export function createWindowsHudPlatform({
10
53
  buildStartProcessCommand,
@@ -13,6 +56,7 @@ export function createWindowsHudPlatform({
13
56
  powerShellCommandArgs,
14
57
  prefetchInitialJson,
15
58
  ps1Path,
59
+ psInvocationArg,
16
60
  psSingleQuote,
17
61
  scriptDir,
18
62
  shellQuote,
@@ -47,6 +91,22 @@ function normalizeHudBackdropOption(value) {
47
91
  throw invalidChoice("--backdrop", "on, off", "hud");
48
92
  }
49
93
 
94
+ function parseWindowsScaleValue(raw, optionName) {
95
+ const named = { small: 0.85, medium: 1, default: 1, large: 1.25, xl: 1.5 };
96
+ const key = String(raw || "").trim().toLowerCase();
97
+ const value = Object.hasOwn(named, key) ? named[key] : Number(key);
98
+ if (!Number.isFinite(value) || value < 0.5 || value > 3) {
99
+ throw invalidChoice(optionName, "0.5..3.0 (or small, medium, large, xl)", "hud");
100
+ }
101
+ return Math.round(value * 100) / 100;
102
+ }
103
+
104
+ function normalizeCodexIconOption(value, optionName = "--codex-icon") {
105
+ const normalized = String(value || "").trim().toLowerCase();
106
+ if (["white", "black"].includes(normalized)) return normalized;
107
+ throw invalidChoice(optionName, "white, black", "hud");
108
+ }
109
+
50
110
  function optionValue(cliArgs, index) {
51
111
  return requiredValue(cliArgs, index, "hud");
52
112
  }
@@ -76,6 +136,19 @@ function describeWindowsHudOptions(filteredArgs) {
76
136
  } else if (option === "-transparent") {
77
137
  descriptions.push(value === "solid" ? "solid background" : "transparent background");
78
138
  i += 1;
139
+ } else if (option === "-mode") {
140
+ const m = String(value || "").toLowerCase();
141
+ if (["icon", "horizontal"].includes(m)) descriptions.push("icon panel");
142
+ else if (m === "rail") descriptions.push("vertical rail panel");
143
+ else if (m === "floating") descriptions.push("stack panel");
144
+ i += 1;
145
+ } else if (option === "-scale") {
146
+ const n = Number(value);
147
+ if (Number.isFinite(n) && n > 0) descriptions.push(`scale ${Math.round(n * 100)}%`);
148
+ i += 1;
149
+ } else if (option === "-codexicon") {
150
+ if (value === "white" || value === "black") descriptions.push(`codex icon ${value}`);
151
+ i += 1;
79
152
  }
80
153
  }
81
154
 
@@ -90,12 +163,14 @@ function hasHudOption(filteredArgs, option) {
90
163
  const HUD_PASSTHROUGH_OPTIONS_WITH_VALUE = new Set([
91
164
  "-batterycommand",
92
165
  "-batterycommandbase64",
166
+ "-codexicon",
93
167
  "-initialjsonbase64",
94
168
  "-interval",
95
169
  "-mode",
96
170
  "-opacity",
97
171
  "-position",
98
172
  "-readypath",
173
+ "-scale",
99
174
  "-width"
100
175
  ]);
101
176
 
@@ -113,6 +188,11 @@ function parseWindowsHudArgs(cliArgs) {
113
188
  let textMode = null;
114
189
  let backdropMode = null;
115
190
  let transparentMode = null;
191
+ let layoutMode = null;
192
+ let scaleValue = null;
193
+ let codexIcon = null;
194
+ let intervalValue = null;
195
+ let provider = "all";
116
196
  let foreground = false;
117
197
  let once = false;
118
198
  let stop = false;
@@ -173,6 +253,25 @@ function parseWindowsHudArgs(cliArgs) {
173
253
  autostartAction = next;
174
254
  i += 1;
175
255
  }
256
+ } else if (lowerArg === "icon" || lowerArg === "--icon" || lowerArg === "horizontal" || lowerArg === "--horizontal") {
257
+ layoutMode = "icon";
258
+ } else if (lowerArg === "rail" || lowerArg === "--rail") {
259
+ layoutMode = "rail";
260
+ } else if (lowerArg === "stack" || lowerArg === "--stack" || lowerArg === "vertical" || lowerArg === "--vertical") {
261
+ layoutMode = "floating";
262
+ } else if (lowerArg === "--layout") {
263
+ const next = String(optionValue(cliArgs, i, arg)).trim().toLowerCase();
264
+ if (["icon", "horizontal", "row", "bar"].includes(next)) layoutMode = "icon";
265
+ else if (next === "rail") layoutMode = "rail";
266
+ else if (["stack", "stacked", "vertical", "floating"].includes(next)) layoutMode = "floating";
267
+ else throw invalidChoice("--layout", "icon, rail, stack", "hud");
268
+ i += 1;
269
+ } else if (lowerArg.startsWith("--layout=")) {
270
+ const next = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
271
+ if (["icon", "horizontal", "row", "bar"].includes(next)) layoutMode = "icon";
272
+ else if (next === "rail") layoutMode = "rail";
273
+ else if (["stack", "stacked", "vertical", "floating"].includes(next)) layoutMode = "floating";
274
+ else throw invalidChoice("--layout", "icon, rail, stack", "hud");
176
275
  } else if (lowerArg === "--black" || lowerArg === "black") {
177
276
  setTextMode("black");
178
277
  } else if (lowerArg === "--white" || lowerArg === "white") {
@@ -186,6 +285,43 @@ function parseWindowsHudArgs(cliArgs) {
186
285
  i += 1;
187
286
  } else if (lowerArg.startsWith("--text=") || lowerArg.startsWith("--hud-text=")) {
188
287
  setTextMode(arg.slice(arg.indexOf("=") + 1));
288
+ } else if (lowerArg === "--scale" || lowerArg === "--size" || lowerArg === "-scale") {
289
+ scaleValue = parseWindowsScaleValue(optionValue(cliArgs, i, arg), arg);
290
+ i += 1;
291
+ } else if (lowerArg.startsWith("--scale=") || lowerArg.startsWith("--size=")) {
292
+ const eq = arg.indexOf("=");
293
+ scaleValue = parseWindowsScaleValue(arg.slice(eq + 1), arg.slice(0, eq));
294
+ } else if (lowerArg === "--codex-icon" || lowerArg === "-codexicon") {
295
+ codexIcon = normalizeCodexIconOption(optionValue(cliArgs, i, arg), arg);
296
+ i += 1;
297
+ } else if (lowerArg.startsWith("--codex-icon=")) {
298
+ codexIcon = normalizeCodexIconOption(arg.slice(arg.indexOf("=") + 1), "--codex-icon");
299
+ } else if (lowerArg === "--interval" || lowerArg === "-interval") {
300
+ const value = Number(optionValue(cliArgs, i, arg));
301
+ if (!Number.isFinite(value) || value < 1) {
302
+ throw cliError("--interval must be at least 1 second.", "--interval은 1초 이상이어야 합니다.", "hud");
303
+ }
304
+ intervalValue = Math.round(value);
305
+ i += 1;
306
+ } else if (lowerArg.startsWith("--interval=")) {
307
+ const value = Number(arg.slice(arg.indexOf("=") + 1));
308
+ if (!Number.isFinite(value) || value < 1) {
309
+ throw cliError("--interval must be at least 1 second.", "--interval은 1초 이상이어야 합니다.", "hud");
310
+ }
311
+ intervalValue = Math.round(value);
312
+ } else if (lowerArg === "--provider" || arg === "-p") {
313
+ const next = providerId(String(optionValue(cliArgs, i, arg)).trim().toLowerCase());
314
+ if (!["all", "codex", "claude", "antigravity"].includes(next)) {
315
+ throw invalidChoice(arg, "all, codex, claude, gemini", "hud");
316
+ }
317
+ provider = next;
318
+ i += 1;
319
+ } else if (lowerArg.startsWith("--provider=")) {
320
+ const next = providerId(arg.slice(arg.indexOf("=") + 1).trim().toLowerCase());
321
+ if (!["all", "codex", "claude", "antigravity"].includes(next)) {
322
+ throw invalidChoice("--provider", "all, codex, claude, gemini", "hud");
323
+ }
324
+ provider = next;
189
325
  } else if (lowerArg === "--backdrop") {
190
326
  const next = cliArgs[i + 1];
191
327
  const backdropValue = next && !String(next).startsWith("-") ? optionalBackdropValue(next) : null;
@@ -232,11 +368,11 @@ function parseWindowsHudArgs(cliArgs) {
232
368
  dockOwnerPid = Number(arg.slice(arg.indexOf("=") + 1));
233
369
  } else if (lowerArg === "--dock-provider") {
234
370
  dockProvider = String(optionValue(cliArgs, i, arg)).trim().toLowerCase();
235
- if (!["codex", "claude"].includes(dockProvider)) throw invalidChoice("--dock-provider", "codex, claude", "hud");
371
+ if (!["codex", "claude", "antigravity"].includes(dockProvider)) throw invalidChoice("--dock-provider", "codex, claude, antigravity", "hud");
236
372
  i += 1;
237
373
  } else if (lowerArg.startsWith("--dock-provider=")) {
238
374
  dockProvider = String(arg.slice(arg.indexOf("=") + 1)).trim().toLowerCase();
239
- if (!["codex", "claude"].includes(dockProvider)) throw invalidChoice("--dock-provider", "codex, claude", "hud");
375
+ if (!["codex", "claude", "antigravity"].includes(dockProvider)) throw invalidChoice("--dock-provider", "codex, claude, antigravity", "hud");
240
376
  } else if (lowerArg === "--dock-marker") {
241
377
  dockMarkerPath = String(optionValue(cliArgs, i, arg)).trim();
242
378
  i += 1;
@@ -272,6 +408,10 @@ function parseWindowsHudArgs(cliArgs) {
272
408
  }
273
409
 
274
410
  const filteredArgs = [...passthroughArgs];
411
+ if (layoutMode !== null && !hasHudOption(filteredArgs, "-Mode")) filteredArgs.push("-Mode", layoutMode);
412
+ if (scaleValue !== null && !hasHudOption(filteredArgs, "-Scale")) filteredArgs.push("-Scale", String(scaleValue));
413
+ if (codexIcon !== null && !hasHudOption(filteredArgs, "-CodexIcon")) filteredArgs.push("-CodexIcon", codexIcon);
414
+ if (intervalValue !== null && !hasHudOption(filteredArgs, "-Interval")) filteredArgs.push("-Interval", String(intervalValue));
275
415
  if (backdropMode !== null) filteredArgs.push("-Backdrop", backdropMode);
276
416
  if (textMode !== null) filteredArgs.push("-Text", textMode);
277
417
  if (transparentMode !== null) filteredArgs.push("-Transparent", transparentMode);
@@ -283,6 +423,10 @@ function parseWindowsHudArgs(cliArgs) {
283
423
  stop,
284
424
  subcommand,
285
425
  autostartAction,
426
+ provider,
427
+ scale: scaleValue,
428
+ codexIcon,
429
+ interval: intervalValue,
286
430
  dockConsole,
287
431
  dockDetach,
288
432
  dockPosition,
@@ -336,6 +480,7 @@ const {
336
480
  stop,
337
481
  subcommand,
338
482
  autostartAction,
483
+ provider = "all",
339
484
  dockConsole,
340
485
  dockDetach,
341
486
  dockPosition,
@@ -347,15 +492,18 @@ const {
347
492
  dockWindow
348
493
  } = parsedArgs;
349
494
 
350
- const hudScript = useWsl ? wslPath(windowsHudMainPath) : ps1Path;
495
+ const hudScript = useWsl ? wslPath(ps1Path) : ps1Path;
351
496
  const hudSourceDir = useWsl ? wslPath(windowsHudSourceDir) : windowsHudSourceDir;
352
497
  const nodePath = process.execPath;
353
498
  const batteryJs = path.join(scriptDir, "ai-battery.js");
354
499
  const configuredCommand = process.env.AI_BATTERY_COMMAND || process.env.CLAUDEX_BATTERY_COMMAND;
355
500
  const envPrefix = useWsl ? wslEnvPrefix() : "";
501
+ const providerCommandArgs = provider && provider !== "all"
502
+ ? (useWsl ? ` --provider ${shellQuote(provider)}` : ` --provider ${psSingleQuote(provider)}`)
503
+ : "";
356
504
  const batteryCommand = configuredCommand || (useWsl
357
- ? `${envPrefix ? `${envPrefix} ` : ""}HOME=${shellQuote(os.homedir())} ${shellQuote(nodePath)} ${shellQuote(batteryJs)} --json`
358
- : `& ${winArgQuote(nodePath)} ${winArgQuote(batteryJs)} --json`);
505
+ ? `${envPrefix ? `${envPrefix} ` : ""}HOME=${shellQuote(os.homedir())} ${shellQuote(nodePath)} ${shellQuote(batteryJs)} --json${providerCommandArgs}`
506
+ : `& ${psSingleQuote(nodePath)} ${psSingleQuote(batteryJs)} --json${providerCommandArgs}`);
359
507
  const batteryCommandBase64 = Buffer.from(batteryCommand, "utf8").toString("base64");
360
508
 
361
509
  function writeDockLauncherMarker(stage) {
@@ -380,16 +528,20 @@ function writeDockLauncherMarker(stage) {
380
528
  }
381
529
  const previousHwnd = Number(previous?.previousHwnd || previous?.hwnd) || 0;
382
530
  const tempPath = `${dockMarkerPath}.${process.pid}.${Date.now()}.tmp`;
383
- fs.writeFileSync(tempPath, `${JSON.stringify({
384
- attemptedAt: new Date().toISOString(),
385
- ownerPid: dockOwnerPid,
386
- launcherPid: process.pid,
387
- stage,
388
- ...(previousHwnd ? { previousHwnd } : {}),
389
- ...(Number(previous?.columns) > 0 ? { columns: Number(previous.columns) } : {}),
390
- ...(previous?.windowCheckedAt ? { windowCheckedAt: previous.windowCheckedAt } : {})
391
- })}\n`, "utf8");
392
- fs.renameSync(tempPath, dockMarkerPath);
531
+ try {
532
+ fs.writeFileSync(tempPath, `${JSON.stringify({
533
+ attemptedAt: new Date().toISOString(),
534
+ ownerPid: dockOwnerPid,
535
+ launcherPid: process.pid,
536
+ stage,
537
+ ...(previousHwnd ? { previousHwnd } : {}),
538
+ ...(Number(previous?.columns) > 0 ? { columns: Number(previous.columns) } : {}),
539
+ ...(previous?.windowCheckedAt ? { windowCheckedAt: previous.windowCheckedAt } : {})
540
+ })}\n`, "utf8");
541
+ atomicRename(tempPath, dockMarkerPath);
542
+ } finally {
543
+ try { fs.unlinkSync(tempPath); } catch {}
544
+ }
393
545
  } catch {
394
546
  // Provider attachment is best-effort and must not delay its statusline.
395
547
  }
@@ -625,7 +777,8 @@ function resolveDockConsoleWindow(ownerPid = 0, titleHint = "") {
625
777
  function refreshWslHudScriptCopy() {
626
778
  if (!useWsl) return null;
627
779
  const result = runPowerShell([
628
- "$dir = Join-Path $env:LOCALAPPDATA 'ai-battery\hud'",
780
+ "$ErrorActionPreference = 'Stop'",
781
+ "$dir = Join-Path $env:LOCALAPPDATA 'ai-battery\\hud'",
629
782
  "New-Item -ItemType Directory -Force -Path $dir | Out-Null",
630
783
  "$hud = Join-Path $dir 'ai-battery-hud.ps1'",
631
784
  `$srcDir = ${psSingleQuote(hudSourceDir)}`,
@@ -651,7 +804,7 @@ function hudProcessStatus() {
651
804
  " if ($hud) { $p = @($hud)[0]; $source = if ($p.CommandLine -like '*-UseWsl*') { 'WSL' } else { 'Windows' }; $status = 'running (' + $source + ', PID ' + $p.ProcessId + ')' }",
652
805
  "} catch { }",
653
806
  "if (-not $status) {",
654
- " try { $m = [System.Threading.Mutex]::OpenExisting('Local\\AiBatteryHud'); $m.Dispose(); $status = 'running (Windows, mutex)' } catch { $status = 'stopped' }",
807
+ " try { $m = [System.Threading.Mutex]::OpenExisting('Local\\AiBatteryHud'); $m.Dispose(); $status = 'running (mutex)' } catch { $status = 'stopped' }",
655
808
  "}",
656
809
  "$status"
657
810
  ].join("; ");
@@ -693,39 +846,36 @@ function autostartEnable() {
693
846
  // launches the copy so sign-in start never depends on WSL being up. The HUD
694
847
  // must run as a separate PowerShell process whose command line contains
695
848
  // ai-battery-hud.ps1: stop/status and single-instance cleanup match it.
696
- const autostartExtraArgs = filteredArgs
697
- .filter((arg) => arg !== "-Once" && arg !== "-StopExisting")
698
- .map(psSingleQuote)
699
- .join(" ");
700
- const autostartScript = [
701
- "# Generated by: ai-battery hud autostart on",
702
- `$srcDir = ${psSingleQuote(hudSourceDir)}`,
703
- "$hudDir = Join-Path $PSScriptRoot 'hud'",
704
- "New-Item -ItemType Directory -Force -Path $hudDir | Out-Null",
705
- "$hud = Join-Path $hudDir 'ai-battery-hud.ps1'",
706
- "try { Copy-Item (Join-Path $srcDir '*.ps1') $hudDir -Force -ErrorAction Stop; Copy-Item (Join-Path $srcDir 'main.ps1') $hud -Force -ErrorAction Stop } catch { }",
707
- `$battery = ${psSingleQuote(batteryCommand)}`,
708
- "$batteryB64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($battery))",
709
- "$invoke = '& ' + \"'\" + ($hud -replace \"'\", \"''\") + \"'\" + ' -BatteryCommandBase64 ' + $batteryB64"
710
- + (autostartExtraArgs ? ` + ${psSingleQuote(` ${autostartExtraArgs}`)}` : "")
711
- + (useWsl ? " + ' -UseWsl'" : ""),
712
- "$argList = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ('\"' + ($invoke -replace '\"', '\\\"') + '\"')) -join ' '",
713
- "Start-Process -WindowStyle Hidden -FilePath 'powershell.exe' -ArgumentList $argList",
714
- ""
715
- ].join("\r\n");
849
+ const autostartScript = buildWindowsAutostartScript({
850
+ hudSourceDir,
851
+ batteryCommandBase64,
852
+ filteredArgs,
853
+ useWsl,
854
+ psInvocationArg
855
+ });
716
856
  const autostartB64 = Buffer.from(autostartScript, "utf8").toString("base64");
857
+ const srcDirB64 = Buffer.from(hudSourceDir, "utf8").toString("base64");
717
858
 
718
859
  const script = [
860
+ "$ErrorActionPreference = 'Stop'",
719
861
  "$dir = Join-Path $env:LOCALAPPDATA 'ai-battery'",
720
- "New-Item -ItemType Directory -Force -Path $dir | Out-Null",
721
862
  "$auto = Join-Path $dir 'autostart.ps1'",
722
- `[System.IO.File]::WriteAllText($auto, [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${autostartB64}')))`,
723
863
  "$hudDir = Join-Path $dir 'hud'",
864
+ "foreach ($p in @($dir, $auto, $hudDir)) { if ((Test-Path -LiteralPath $p) -and ((Get-Item -Force -LiteralPath $p).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw ('Refusing to follow an autostart symlink: ' + $p) } }",
865
+ `$v = (Get-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -ErrorAction SilentlyContinue).${AUTOSTART_REG_NAME}`,
866
+ "$expected = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File \"' + $auto + '\"'",
867
+ "if ($v -and $v -ne $expected) { throw 'AiBatteryHud registry value changed; left it untouched.' }",
868
+ "if (Test-Path -LiteralPath $auto) { if (-not ([string](Get-Content -Raw -LiteralPath $auto)).StartsWith('# Generated by: ai-battery hud autostart on')) { throw 'Autostart file changed; left it and its registry value untouched.' } }",
869
+ "New-Item -ItemType Directory -Force -Path $dir | Out-Null",
870
+ "$autoTmp = $auto + '.' + $PID + '.tmp'",
871
+ `[System.IO.File]::WriteAllText($autoTmp, [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${autostartB64}')), [System.Text.UTF8Encoding]::new($false))`,
872
+ "Move-Item -LiteralPath $autoTmp -Destination $auto -Force",
724
873
  "New-Item -ItemType Directory -Force -Path $hudDir | Out-Null",
725
- `$srcDir = ${psSingleQuote(hudSourceDir)}`,
874
+ `$srcDir = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${srcDirB64}'))`,
726
875
  "Copy-Item (Join-Path $srcDir '*.ps1') $hudDir -Force",
727
876
  "Copy-Item (Join-Path $srcDir 'main.ps1') (Join-Path $hudDir 'ai-battery-hud.ps1') -Force",
728
- `Set-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -Value ('powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $auto + '"')`,
877
+ `if (-not (Test-Path -Path '${AUTOSTART_REG_PATH}')) { New-Item -Path '${AUTOSTART_REG_PATH}' -Force | Out-Null }`,
878
+ `Set-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -Value $expected`,
729
879
  "Write-Output $auto"
730
880
  ].join("; ");
731
881
  return runPowerShell(script);
@@ -921,7 +1071,9 @@ const launchHudScript = stop ? hudScript : (refreshWslHudScriptCopy() || hudScri
921
1071
  const wasRunning = (!foreground && !once && !stop && !dockWindowHandle)
922
1072
  ? hudProcessStatus().startsWith("running ")
923
1073
  : false;
924
- const initialJson = (stop || dockWindowHandle) ? null : prefetchInitialJson(batteryCommand, useWsl, batteryJs);
1074
+ const initialJson = (stop || dockWindowHandle || (configuredCommand && !useWsl))
1075
+ ? null
1076
+ : prefetchInitialJson(batteryCommand, useWsl, batteryJs, provider && provider !== "all" ? ["--provider", provider] : []);
925
1077
  const readyPath = (!useWsl && process.platform === "win32" && !foreground && !once && !stop && !dockWindowHandle)
926
1078
  ? path.join(os.tmpdir(), `ai-battery-hud-ready-${process.pid}-${Date.now()}.json`)
927
1079
  : null;
@@ -933,11 +1085,10 @@ if (dockFallbackFloating) {
933
1085
  if (!hasHudOption(effectiveFilteredArgs, "-Position")) effectiveFilteredArgs.push("-Position", "taskbar");
934
1086
  }
935
1087
 
936
- const hudScriptArgs = [
937
- "-BatteryCommandBase64",
938
- batteryCommandBase64,
939
- ...effectiveFilteredArgs
940
- ];
1088
+ const hudScriptArgs = [...effectiveFilteredArgs];
1089
+ if (!hasHudOption(hudScriptArgs, "-BatteryCommandBase64")) {
1090
+ hudScriptArgs.unshift("-BatteryCommandBase64", batteryCommandBase64);
1091
+ }
941
1092
 
942
1093
  if (dockWindowHandle) {
943
1094
  hudScriptArgs.push("-DockWindowHandle", String(dockWindowHandle));
@@ -948,15 +1099,15 @@ if (dockWindowHandle) {
948
1099
  if (dockMarkerPath) hudScriptArgs.push("-DockMarkerPath", dockMarkerPath);
949
1100
  }
950
1101
 
951
- if (readyPath) {
1102
+ if (readyPath && !hasHudOption(hudScriptArgs, "-ReadyPath")) {
952
1103
  hudScriptArgs.push("-ReadyPath", readyPath);
953
1104
  }
954
1105
 
955
- if (initialJson) {
1106
+ if (initialJson && !hasHudOption(hudScriptArgs, "-InitialJsonBase64")) {
956
1107
  hudScriptArgs.push("-InitialJsonBase64", Buffer.from(initialJson, "utf8").toString("base64"));
957
1108
  }
958
1109
 
959
- if (useWsl) {
1110
+ if (useWsl && !hasHudOption(hudScriptArgs, "-UseWsl")) {
960
1111
  hudScriptArgs.push("-UseWsl");
961
1112
  }
962
1113
 
@@ -964,37 +1115,33 @@ const psArgs = powerShellCommandArgs(launchHudScript, hudScriptArgs);
964
1115
 
965
1116
  if (foreground || once || stop) {
966
1117
  const result = spawnSync(powershell, psArgs, { stdio: "inherit", windowsHide: true });
967
- if (stop && (result.status ?? 0) === 0) {
968
- console.log("HUD: stopped");
1118
+ const ok = !result.error && result.status === 0;
1119
+ if (result.error) {
1120
+ console.error(`ai-battery-hud: ${errorText(result.error)}`);
969
1121
  }
970
- process.exit(result.status ?? 0);
971
- }
972
-
973
- if (useWsl) {
974
- const start = spawnSync(powershell, [
975
- "-NoProfile",
976
- "-ExecutionPolicy",
977
- "Bypass",
978
- "-Command",
979
- buildStartProcessCommand("powershell.exe", psArgs)
980
- ], {
981
- stdio: "ignore",
982
- windowsHide: true
983
- });
984
- if (start.status !== 0) process.exit(start.status ?? 1);
985
- } else {
986
- const start = spawnSync(powershell, [
987
- "-NoProfile",
988
- "-ExecutionPolicy",
989
- "Bypass",
990
- "-Command",
991
- buildStartProcessCommand("powershell.exe", psArgs)
992
- ], {
993
- stdio: "ignore",
994
- windowsHide: true
995
- });
996
- if (start.status !== 0) process.exit(start.status ?? 1);
1122
+ if (stop && ok) {
1123
+ console.log("HUD: stopped");
997
1124
  }
1125
+ process.exit(ok ? 0 : (result.status ?? 1));
1126
+ }
1127
+
1128
+ const start = spawnSync(powershell, [
1129
+ "-NoProfile",
1130
+ "-ExecutionPolicy",
1131
+ "Bypass",
1132
+ "-Command",
1133
+ buildStartProcessCommand("powershell.exe", psArgs)
1134
+ ], {
1135
+ encoding: "utf8",
1136
+ stdio: ["ignore", "ignore", "pipe"],
1137
+ windowsHide: true
1138
+ });
1139
+ if (start.error || start.status !== 0) {
1140
+ const detail = (start.stderr || "").trim() || (start.error ? errorText(start.error) : "");
1141
+ console.error(cliText("ai-battery-hud: could not launch the Windows HUD.", "ai-battery-hud: Windows HUD를 실행하지 못했습니다."));
1142
+ if (detail) console.error(detail);
1143
+ process.exit(start.error ? 1 : (start.status ?? 1));
1144
+ }
998
1145
 
999
1146
  if (dockWindowHandle) {
1000
1147
  hudDebugLog("hud launch dispatched (docked)");
@@ -1006,10 +1153,16 @@ if (readyPath && !waitForFile(readyPath)) {
1006
1153
  const action = wasRunning ? (detail ? "updated" : "restarted") : "started";
1007
1154
  console.log(`HUD: ${action}${detail ? ` · ${detail}` : ""}`);
1008
1155
  if (!wasRunning) {
1009
- console.log(cliText("Drag to move. Right-click to exit.", "드래그로 이동 · 우클릭으로 종료"));
1156
+ console.log(cliText("Drag to move, drag corners or right-click to resize and switch black/white.", "드래그로 이동 · 모서리·우클릭으로 크기·흑백 전환"));
1157
+ }
1158
+ }
1159
+ if (readyPath) {
1160
+ try {
1161
+ fs.rmSync(readyPath, { force: true });
1162
+ } catch {
1163
+ // Readiness file cleanup is best-effort on Windows.
1010
1164
  }
1011
1165
  }
1012
- if (readyPath) fs.rmSync(readyPath, { force: true });
1013
1166
  }
1014
1167
  return {
1015
1168
  describeWindowsHudOptions,