ai-battery 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +30 -14
  2. package/bin/ai-battery-macos-status.applescript +5 -12
  3. package/bin/ai-battery-run +701 -31
  4. package/bin/ai-battery-tmux.js +17 -0
  5. package/bin/terminal-compositor.js +111 -0
  6. package/docs/REFERENCE.md +23 -3
  7. package/docs/RELEASING.md +24 -7
  8. package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
  9. package/docs/hud-preview.svg +43 -20
  10. package/docs/terminal-vertical-preview.svg +73 -0
  11. package/lib/cli.js +945 -219
  12. package/lib/core/atomic-rename.js +18 -0
  13. package/lib/core/cli-help.js +35 -7
  14. package/lib/core/cli-messages.js +45 -1
  15. package/lib/core/cli-output.js +277 -72
  16. package/lib/core/cli-wrappers.js +410 -0
  17. package/lib/core/config-editor.js +177 -29
  18. package/lib/core/display-config.js +45 -0
  19. package/lib/core/integration-files.js +32 -3
  20. package/lib/core/shared-bar.js +603 -0
  21. package/lib/core/statusline-git.js +179 -15
  22. package/lib/core/terminal.js +25 -7
  23. package/lib/core/tmux-status.js +172 -0
  24. package/lib/core/uninstall.js +20 -7
  25. package/lib/core/usage-store.js +85 -0
  26. package/lib/hud/launcher.js +29 -31
  27. package/lib/platforms/linux/hud.js +1 -1
  28. package/lib/platforms/linux/panel.js +1 -1
  29. package/lib/platforms/macos/hud.js +5 -5
  30. package/lib/platforms/process-scanner.js +77 -29
  31. package/lib/platforms/windows/autostart-cleanup.js +1 -1
  32. package/lib/platforms/windows/codex-runner.js +178 -21
  33. package/lib/platforms/windows/hud/controls.ps1 +44 -10
  34. package/lib/platforms/windows/hud/main.ps1 +350 -43
  35. package/lib/platforms/windows/hud/rendering.ps1 +1227 -1
  36. package/lib/platforms/windows/hud/snapshot.ps1 +26 -46
  37. package/lib/platforms/windows/hud-launcher.js +153 -79
  38. package/lib/platforms/windows/shared-bar-platform.js +972 -0
  39. package/lib/platforms/windows/terminal-compositor.js +210 -25
  40. package/lib/platforms/windows/wt-bar.js +729 -0
  41. package/lib/platforms/windows/wt-fragment.js +665 -0
  42. package/lib/platforms/windows/wt-keybinding.js +300 -0
  43. package/lib/providers/antigravity.js +155 -8
  44. package/package.json +5 -2
  45. package/vendor/PaneContext.cs +875 -0
@@ -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,10 +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";
8
9
 
10
+ export function buildWindowsAutostartScript({
11
+ hudSourceDir,
12
+ batteryCommandBase64,
13
+ filteredArgs = [],
14
+ useWsl = false,
15
+ psInvocationArg
16
+ }) {
17
+ const formatArg = psInvocationArg
18
+ || ((value) => (/^-[A-Za-z][A-Za-z0-9]*$/.test(String(value)) ? String(value) : `'${String(value).replace(/'/g, "''")}'`));
19
+ const extraTokens = [];
20
+ for (let i = 0; i < filteredArgs.length; i += 1) {
21
+ const arg = filteredArgs[i];
22
+ const lower = String(arg).toLowerCase();
23
+ if (lower === "-once" || lower === "-stopexisting" || (useWsl && lower === "-usewsl")) continue;
24
+ if (lower === "-batterycommandbase64") {
25
+ i += 1;
26
+ continue;
27
+ }
28
+ extraTokens.push(formatArg(arg));
29
+ }
30
+ const extraArgsText = extraTokens.length ? ` ${extraTokens.join(" ")}` : "";
31
+ const srcDirB64 = Buffer.from(String(hudSourceDir), "utf8").toString("base64");
32
+ const extraArgsB64 = extraArgsText ? Buffer.from(extraArgsText, "utf8").toString("base64") : "";
33
+ return [
34
+ "# Generated by: ai-battery hud autostart on",
35
+ `$srcDir = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${srcDirB64}'))`,
36
+ "$hudDir = Join-Path $PSScriptRoot 'hud'",
37
+ "New-Item -ItemType Directory -Force -Path $hudDir | Out-Null",
38
+ "$hud = Join-Path $hudDir 'ai-battery-hud.ps1'",
39
+ "try { Copy-Item (Join-Path $srcDir '*.ps1') $hudDir -Force -ErrorAction Stop; Copy-Item (Join-Path $srcDir 'main.ps1') $hud -Force -ErrorAction Stop } catch { }",
40
+ `$batteryB64 = '${batteryCommandBase64}'`,
41
+ ...(extraArgsB64 ? [`$extraArgs = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${extraArgsB64}'))`] : []),
42
+ "$invoke = '& ' + \"'\" + ($hud -replace \"'\", \"''\") + \"'\" + ' -BatteryCommandBase64 ' + $batteryB64"
43
+ + (extraArgsB64 ? " + $extraArgs" : "")
44
+ + (useWsl ? " + ' -UseWsl'" : ""),
45
+ "$argList = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ('\"' + ($invoke -replace '\"', '\\\"') + '\"')) -join ' '",
46
+ "Start-Process -WindowStyle Hidden -FilePath 'powershell.exe' -ArgumentList $argList",
47
+ ""
48
+ ].join("\r\n");
49
+ }
50
+
9
51
  export function createWindowsHudPlatform({
10
52
  buildStartProcessCommand,
11
53
  commandExists,
@@ -13,6 +55,7 @@ export function createWindowsHudPlatform({
13
55
  powerShellCommandArgs,
14
56
  prefetchInitialJson,
15
57
  ps1Path,
58
+ psInvocationArg,
16
59
  psSingleQuote,
17
60
  scriptDir,
18
61
  shellQuote,
@@ -76,6 +119,11 @@ function describeWindowsHudOptions(filteredArgs) {
76
119
  } else if (option === "-transparent") {
77
120
  descriptions.push(value === "solid" ? "solid background" : "transparent background");
78
121
  i += 1;
122
+ } else if (option === "-mode") {
123
+ const m = String(value || "").toLowerCase();
124
+ if (["icon", "horizontal"].includes(m)) descriptions.push("icon panel");
125
+ else if (m === "rail") descriptions.push("vertical rail panel");
126
+ i += 1;
79
127
  }
80
128
  }
81
129
 
@@ -113,6 +161,7 @@ function parseWindowsHudArgs(cliArgs) {
113
161
  let textMode = null;
114
162
  let backdropMode = null;
115
163
  let transparentMode = null;
164
+ let layoutMode = null;
116
165
  let foreground = false;
117
166
  let once = false;
118
167
  let stop = false;
@@ -173,6 +222,25 @@ function parseWindowsHudArgs(cliArgs) {
173
222
  autostartAction = next;
174
223
  i += 1;
175
224
  }
225
+ } else if (lowerArg === "icon" || lowerArg === "--icon" || lowerArg === "horizontal" || lowerArg === "--horizontal") {
226
+ layoutMode = "icon";
227
+ } else if (lowerArg === "rail" || lowerArg === "--rail") {
228
+ layoutMode = "rail";
229
+ } else if (lowerArg === "stack" || lowerArg === "--stack" || lowerArg === "vertical" || lowerArg === "--vertical") {
230
+ layoutMode = "floating";
231
+ } else if (lowerArg === "--layout") {
232
+ const next = String(optionValue(cliArgs, i, arg)).trim().toLowerCase();
233
+ if (["icon", "horizontal", "row", "bar"].includes(next)) layoutMode = "icon";
234
+ else if (next === "rail") layoutMode = "rail";
235
+ else if (["stack", "stacked", "vertical", "floating"].includes(next)) layoutMode = "floating";
236
+ else throw invalidChoice("--layout", "icon, rail, stack", "hud");
237
+ i += 1;
238
+ } else if (lowerArg.startsWith("--layout=")) {
239
+ const next = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
240
+ if (["icon", "horizontal", "row", "bar"].includes(next)) layoutMode = "icon";
241
+ else if (next === "rail") layoutMode = "rail";
242
+ else if (["stack", "stacked", "vertical", "floating"].includes(next)) layoutMode = "floating";
243
+ else throw invalidChoice("--layout", "icon, rail, stack", "hud");
176
244
  } else if (lowerArg === "--black" || lowerArg === "black") {
177
245
  setTextMode("black");
178
246
  } else if (lowerArg === "--white" || lowerArg === "white") {
@@ -232,11 +300,11 @@ function parseWindowsHudArgs(cliArgs) {
232
300
  dockOwnerPid = Number(arg.slice(arg.indexOf("=") + 1));
233
301
  } else if (lowerArg === "--dock-provider") {
234
302
  dockProvider = String(optionValue(cliArgs, i, arg)).trim().toLowerCase();
235
- if (!["codex", "claude"].includes(dockProvider)) throw invalidChoice("--dock-provider", "codex, claude", "hud");
303
+ if (!["codex", "claude", "antigravity"].includes(dockProvider)) throw invalidChoice("--dock-provider", "codex, claude, antigravity", "hud");
236
304
  i += 1;
237
305
  } else if (lowerArg.startsWith("--dock-provider=")) {
238
306
  dockProvider = String(arg.slice(arg.indexOf("=") + 1)).trim().toLowerCase();
239
- if (!["codex", "claude"].includes(dockProvider)) throw invalidChoice("--dock-provider", "codex, claude", "hud");
307
+ if (!["codex", "claude", "antigravity"].includes(dockProvider)) throw invalidChoice("--dock-provider", "codex, claude, antigravity", "hud");
240
308
  } else if (lowerArg === "--dock-marker") {
241
309
  dockMarkerPath = String(optionValue(cliArgs, i, arg)).trim();
242
310
  i += 1;
@@ -272,6 +340,7 @@ function parseWindowsHudArgs(cliArgs) {
272
340
  }
273
341
 
274
342
  const filteredArgs = [...passthroughArgs];
343
+ if (layoutMode !== null && !hasHudOption(filteredArgs, "-Mode")) filteredArgs.push("-Mode", layoutMode);
275
344
  if (backdropMode !== null) filteredArgs.push("-Backdrop", backdropMode);
276
345
  if (textMode !== null) filteredArgs.push("-Text", textMode);
277
346
  if (transparentMode !== null) filteredArgs.push("-Transparent", transparentMode);
@@ -347,7 +416,7 @@ const {
347
416
  dockWindow
348
417
  } = parsedArgs;
349
418
 
350
- const hudScript = useWsl ? wslPath(windowsHudMainPath) : ps1Path;
419
+ const hudScript = useWsl ? wslPath(ps1Path) : ps1Path;
351
420
  const hudSourceDir = useWsl ? wslPath(windowsHudSourceDir) : windowsHudSourceDir;
352
421
  const nodePath = process.execPath;
353
422
  const batteryJs = path.join(scriptDir, "ai-battery.js");
@@ -355,7 +424,7 @@ const configuredCommand = process.env.AI_BATTERY_COMMAND || process.env.CLAUDEX_
355
424
  const envPrefix = useWsl ? wslEnvPrefix() : "";
356
425
  const batteryCommand = configuredCommand || (useWsl
357
426
  ? `${envPrefix ? `${envPrefix} ` : ""}HOME=${shellQuote(os.homedir())} ${shellQuote(nodePath)} ${shellQuote(batteryJs)} --json`
358
- : `& ${winArgQuote(nodePath)} ${winArgQuote(batteryJs)} --json`);
427
+ : `& ${psSingleQuote(nodePath)} ${psSingleQuote(batteryJs)} --json`);
359
428
  const batteryCommandBase64 = Buffer.from(batteryCommand, "utf8").toString("base64");
360
429
 
361
430
  function writeDockLauncherMarker(stage) {
@@ -380,16 +449,20 @@ function writeDockLauncherMarker(stage) {
380
449
  }
381
450
  const previousHwnd = Number(previous?.previousHwnd || previous?.hwnd) || 0;
382
451
  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);
452
+ try {
453
+ fs.writeFileSync(tempPath, `${JSON.stringify({
454
+ attemptedAt: new Date().toISOString(),
455
+ ownerPid: dockOwnerPid,
456
+ launcherPid: process.pid,
457
+ stage,
458
+ ...(previousHwnd ? { previousHwnd } : {}),
459
+ ...(Number(previous?.columns) > 0 ? { columns: Number(previous.columns) } : {}),
460
+ ...(previous?.windowCheckedAt ? { windowCheckedAt: previous.windowCheckedAt } : {})
461
+ })}\n`, "utf8");
462
+ atomicRename(tempPath, dockMarkerPath);
463
+ } finally {
464
+ try { fs.unlinkSync(tempPath); } catch {}
465
+ }
393
466
  } catch {
394
467
  // Provider attachment is best-effort and must not delay its statusline.
395
468
  }
@@ -625,7 +698,8 @@ function resolveDockConsoleWindow(ownerPid = 0, titleHint = "") {
625
698
  function refreshWslHudScriptCopy() {
626
699
  if (!useWsl) return null;
627
700
  const result = runPowerShell([
628
- "$dir = Join-Path $env:LOCALAPPDATA 'ai-battery\hud'",
701
+ "$ErrorActionPreference = 'Stop'",
702
+ "$dir = Join-Path $env:LOCALAPPDATA 'ai-battery\\hud'",
629
703
  "New-Item -ItemType Directory -Force -Path $dir | Out-Null",
630
704
  "$hud = Join-Path $dir 'ai-battery-hud.ps1'",
631
705
  `$srcDir = ${psSingleQuote(hudSourceDir)}`,
@@ -651,7 +725,7 @@ function hudProcessStatus() {
651
725
  " if ($hud) { $p = @($hud)[0]; $source = if ($p.CommandLine -like '*-UseWsl*') { 'WSL' } else { 'Windows' }; $status = 'running (' + $source + ', PID ' + $p.ProcessId + ')' }",
652
726
  "} catch { }",
653
727
  "if (-not $status) {",
654
- " try { $m = [System.Threading.Mutex]::OpenExisting('Local\\AiBatteryHud'); $m.Dispose(); $status = 'running (Windows, mutex)' } catch { $status = 'stopped' }",
728
+ " try { $m = [System.Threading.Mutex]::OpenExisting('Local\\AiBatteryHud'); $m.Dispose(); $status = 'running (mutex)' } catch { $status = 'stopped' }",
655
729
  "}",
656
730
  "$status"
657
731
  ].join("; ");
@@ -693,39 +767,36 @@ function autostartEnable() {
693
767
  // launches the copy so sign-in start never depends on WSL being up. The HUD
694
768
  // must run as a separate PowerShell process whose command line contains
695
769
  // 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");
770
+ const autostartScript = buildWindowsAutostartScript({
771
+ hudSourceDir,
772
+ batteryCommandBase64,
773
+ filteredArgs,
774
+ useWsl,
775
+ psInvocationArg
776
+ });
716
777
  const autostartB64 = Buffer.from(autostartScript, "utf8").toString("base64");
778
+ const srcDirB64 = Buffer.from(hudSourceDir, "utf8").toString("base64");
717
779
 
718
780
  const script = [
781
+ "$ErrorActionPreference = 'Stop'",
719
782
  "$dir = Join-Path $env:LOCALAPPDATA 'ai-battery'",
720
- "New-Item -ItemType Directory -Force -Path $dir | Out-Null",
721
783
  "$auto = Join-Path $dir 'autostart.ps1'",
722
- `[System.IO.File]::WriteAllText($auto, [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${autostartB64}')))`,
723
784
  "$hudDir = Join-Path $dir 'hud'",
785
+ "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) } }",
786
+ `$v = (Get-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -ErrorAction SilentlyContinue).${AUTOSTART_REG_NAME}`,
787
+ "$expected = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File \"' + $auto + '\"'",
788
+ "if ($v -and $v -ne $expected) { throw 'AiBatteryHud registry value changed; left it untouched.' }",
789
+ "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.' } }",
790
+ "New-Item -ItemType Directory -Force -Path $dir | Out-Null",
791
+ "$autoTmp = $auto + '.' + $PID + '.tmp'",
792
+ `[System.IO.File]::WriteAllText($autoTmp, [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${autostartB64}')), [System.Text.UTF8Encoding]::new($false))`,
793
+ "Move-Item -LiteralPath $autoTmp -Destination $auto -Force",
724
794
  "New-Item -ItemType Directory -Force -Path $hudDir | Out-Null",
725
- `$srcDir = ${psSingleQuote(hudSourceDir)}`,
795
+ `$srcDir = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${srcDirB64}'))`,
726
796
  "Copy-Item (Join-Path $srcDir '*.ps1') $hudDir -Force",
727
797
  "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 + '"')`,
798
+ `if (-not (Test-Path -Path '${AUTOSTART_REG_PATH}')) { New-Item -Path '${AUTOSTART_REG_PATH}' -Force | Out-Null }`,
799
+ `Set-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -Value $expected`,
729
800
  "Write-Output $auto"
730
801
  ].join("; ");
731
802
  return runPowerShell(script);
@@ -921,7 +992,9 @@ const launchHudScript = stop ? hudScript : (refreshWslHudScriptCopy() || hudScri
921
992
  const wasRunning = (!foreground && !once && !stop && !dockWindowHandle)
922
993
  ? hudProcessStatus().startsWith("running ")
923
994
  : false;
924
- const initialJson = (stop || dockWindowHandle) ? null : prefetchInitialJson(batteryCommand, useWsl, batteryJs);
995
+ const initialJson = (stop || dockWindowHandle || (configuredCommand && !useWsl))
996
+ ? null
997
+ : prefetchInitialJson(batteryCommand, useWsl, batteryJs);
925
998
  const readyPath = (!useWsl && process.platform === "win32" && !foreground && !once && !stop && !dockWindowHandle)
926
999
  ? path.join(os.tmpdir(), `ai-battery-hud-ready-${process.pid}-${Date.now()}.json`)
927
1000
  : null;
@@ -933,11 +1006,10 @@ if (dockFallbackFloating) {
933
1006
  if (!hasHudOption(effectiveFilteredArgs, "-Position")) effectiveFilteredArgs.push("-Position", "taskbar");
934
1007
  }
935
1008
 
936
- const hudScriptArgs = [
937
- "-BatteryCommandBase64",
938
- batteryCommandBase64,
939
- ...effectiveFilteredArgs
940
- ];
1009
+ const hudScriptArgs = [...effectiveFilteredArgs];
1010
+ if (!hasHudOption(hudScriptArgs, "-BatteryCommandBase64")) {
1011
+ hudScriptArgs.unshift("-BatteryCommandBase64", batteryCommandBase64);
1012
+ }
941
1013
 
942
1014
  if (dockWindowHandle) {
943
1015
  hudScriptArgs.push("-DockWindowHandle", String(dockWindowHandle));
@@ -948,15 +1020,15 @@ if (dockWindowHandle) {
948
1020
  if (dockMarkerPath) hudScriptArgs.push("-DockMarkerPath", dockMarkerPath);
949
1021
  }
950
1022
 
951
- if (readyPath) {
1023
+ if (readyPath && !hasHudOption(hudScriptArgs, "-ReadyPath")) {
952
1024
  hudScriptArgs.push("-ReadyPath", readyPath);
953
1025
  }
954
1026
 
955
- if (initialJson) {
1027
+ if (initialJson && !hasHudOption(hudScriptArgs, "-InitialJsonBase64")) {
956
1028
  hudScriptArgs.push("-InitialJsonBase64", Buffer.from(initialJson, "utf8").toString("base64"));
957
1029
  }
958
1030
 
959
- if (useWsl) {
1031
+ if (useWsl && !hasHudOption(hudScriptArgs, "-UseWsl")) {
960
1032
  hudScriptArgs.push("-UseWsl");
961
1033
  }
962
1034
 
@@ -964,37 +1036,33 @@ const psArgs = powerShellCommandArgs(launchHudScript, hudScriptArgs);
964
1036
 
965
1037
  if (foreground || once || stop) {
966
1038
  const result = spawnSync(powershell, psArgs, { stdio: "inherit", windowsHide: true });
967
- if (stop && (result.status ?? 0) === 0) {
968
- console.log("HUD: stopped");
1039
+ const ok = !result.error && result.status === 0;
1040
+ if (result.error) {
1041
+ console.error(`ai-battery-hud: ${errorText(result.error)}`);
969
1042
  }
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);
1043
+ if (stop && ok) {
1044
+ console.log("HUD: stopped");
997
1045
  }
1046
+ process.exit(ok ? 0 : (result.status ?? 1));
1047
+ }
1048
+
1049
+ const start = spawnSync(powershell, [
1050
+ "-NoProfile",
1051
+ "-ExecutionPolicy",
1052
+ "Bypass",
1053
+ "-Command",
1054
+ buildStartProcessCommand("powershell.exe", psArgs)
1055
+ ], {
1056
+ encoding: "utf8",
1057
+ stdio: ["ignore", "ignore", "pipe"],
1058
+ windowsHide: true
1059
+ });
1060
+ if (start.error || start.status !== 0) {
1061
+ const detail = (start.stderr || "").trim() || (start.error ? errorText(start.error) : "");
1062
+ console.error(cliText("ai-battery-hud: could not launch the Windows HUD.", "ai-battery-hud: Windows HUD를 실행하지 못했습니다."));
1063
+ if (detail) console.error(detail);
1064
+ process.exit(start.error ? 1 : (start.status ?? 1));
1065
+ }
998
1066
 
999
1067
  if (dockWindowHandle) {
1000
1068
  hudDebugLog("hud launch dispatched (docked)");
@@ -1009,7 +1077,13 @@ if (readyPath && !waitForFile(readyPath)) {
1009
1077
  console.log(cliText("Drag to move. Right-click to exit.", "드래그로 이동 · 우클릭으로 종료"));
1010
1078
  }
1011
1079
  }
1012
- if (readyPath) fs.rmSync(readyPath, { force: true });
1080
+ if (readyPath) {
1081
+ try {
1082
+ fs.rmSync(readyPath, { force: true });
1083
+ } catch {
1084
+ // Readiness file cleanup is best-effort on Windows.
1085
+ }
1086
+ }
1013
1087
  }
1014
1088
  return {
1015
1089
  describeWindowsHudOptions,