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
@@ -10,8 +10,26 @@ function sleepSync(ms) {
10
10
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
11
11
  }
12
12
 
13
- export function createMacHudPlatform({ macStatusPath, relevantEnvPrefix, scriptDir, shellQuote,
13
+ export function createMacHudPlatform({ macStatusPath, macRailPath, relevantEnvPrefix, scriptDir, shellQuote,
14
14
  home = os.homedir(), runLaunchctl = args => spawnSync("launchctl", args, { stdio: "ignore" }) }) {
15
+ const resolvedMacRailPath = macRailPath || (macStatusPath ? path.join(path.dirname(macStatusPath), "ai-battery-macos-rail.applescript") : "");
16
+ function parseMacScaleValue(raw, optionName) {
17
+ const named = { small: 0.85, medium: 1, default: 1, large: 1.25, xl: 1.5 };
18
+ const key = String(raw || "").trim().toLowerCase();
19
+ const value = Object.hasOwn(named, key) ? named[key] : Number(key);
20
+ if (!Number.isFinite(value) || value < 0.5 || value > 3) {
21
+ throw invalidChoice(optionName, "0.5..3.0 (or small, medium, large, xl)", "hud");
22
+ }
23
+ return Math.round(value * 100) / 100;
24
+ }
25
+
26
+ function parseMacRailText(raw) {
27
+ const v = String(raw || "").trim().toLowerCase();
28
+ if (["black", "dark", "ink"].includes(v)) return "black";
29
+ if (["white", "light", "bright"].includes(v)) return "white";
30
+ throw invalidChoice("--text", "black, white", "hud");
31
+ }
32
+
15
33
  function parseMacHudArgs(cliArgs) {
16
34
  const options = {
17
35
  foreground: false,
@@ -19,8 +37,13 @@ function parseMacHudArgs(cliArgs) {
19
37
  stop: false,
20
38
  subcommand: null,
21
39
  autostartAction: "status",
22
- interval: 10,
23
- provider: "all"
40
+ interval: 2,
41
+ provider: "all",
42
+ layout: "menu-bar",
43
+ layoutExplicit: false,
44
+ scale: 1,
45
+ codexIcon: "white",
46
+ railText: "white"
24
47
  };
25
48
 
26
49
  for (let i = 0; i < cliArgs.length; i += 1) {
@@ -33,6 +56,47 @@ function parseMacHudArgs(cliArgs) {
33
56
  options.stop = true;
34
57
  } else if (arg === "start") {
35
58
  // Starting is the default action.
59
+ } else if (arg === "rail" || arg === "--rail") {
60
+ options.layout = "rail";
61
+ options.layoutExplicit = true;
62
+ } else if (arg === "menu-bar" || arg === "--menu-bar") {
63
+ options.layout = "menu-bar";
64
+ options.layoutExplicit = true;
65
+ } else if (arg === "--layout") {
66
+ const next = String(requiredValue(cliArgs, i, "hud")).trim().toLowerCase();
67
+ if (!["menu-bar", "rail"].includes(next)) throw invalidChoice(arg, "menu-bar, rail", "hud");
68
+ options.layout = next;
69
+ options.layoutExplicit = true;
70
+ i += 1;
71
+ } else if (arg.startsWith("--layout=")) {
72
+ const next = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
73
+ if (!["menu-bar", "rail"].includes(next)) throw invalidChoice("--layout", "menu-bar, rail", "hud");
74
+ options.layout = next;
75
+ options.layoutExplicit = true;
76
+ } else if (arg === "--scale" || arg === "--size") {
77
+ options.scale = parseMacScaleValue(requiredValue(cliArgs, i, "hud"), arg);
78
+ i += 1;
79
+ } else if (arg.startsWith("--scale=") || arg.startsWith("--size=")) {
80
+ const eq = arg.indexOf("=");
81
+ options.scale = parseMacScaleValue(arg.slice(eq + 1), arg.slice(0, eq));
82
+ } else if (arg === "--codex-icon") {
83
+ const next = String(requiredValue(cliArgs, i, "hud")).trim().toLowerCase();
84
+ if (!["white", "black"].includes(next)) throw invalidChoice(arg, "white, black", "hud");
85
+ options.codexIcon = next;
86
+ i += 1;
87
+ } else if (arg.startsWith("--codex-icon=")) {
88
+ const next = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
89
+ if (!["white", "black"].includes(next)) throw invalidChoice("--codex-icon", "white, black", "hud");
90
+ options.codexIcon = next;
91
+ } else if (arg === "black" || arg === "--black" || arg === "light" || arg === "--light") {
92
+ options.railText = "black";
93
+ } else if (arg === "white" || arg === "--white" || arg === "dark" || arg === "--dark") {
94
+ options.railText = "white";
95
+ } else if (arg === "--text" || arg === "--hud-text") {
96
+ options.railText = parseMacRailText(requiredValue(cliArgs, i, "hud"));
97
+ i += 1;
98
+ } else if (arg.startsWith("--text=") || arg.startsWith("--hud-text=")) {
99
+ options.railText = parseMacRailText(arg.slice(arg.indexOf("=") + 1));
36
100
  } else if (arg === "status") {
37
101
  options.subcommand = "status";
38
102
  } else if (arg === "autostart") {
@@ -66,32 +130,41 @@ function macCommands(options) {
66
130
  const node = shellQuote(process.execPath);
67
131
  const batteryJs = shellQuote(path.join(scriptDir, "ai-battery.js"));
68
132
  const providerArgs = macProviderArgs(options.provider);
133
+ const codexIconArgs = options.codexIcon === "black" ? " --codex-icon black" : "";
134
+ const panelTextArgs = options.railText === "black" ? " --panel-text black" : "";
135
+ const railTextArgs = options.railText === "black" ? " --rail-text black" : "";
69
136
  const envPrefix = relevantEnvPrefix();
70
137
  return {
71
- title: `${envPrefix} ${node} ${batteryJs} --menu-bar-image${providerArgs} 2>/dev/null`,
138
+ title: `${envPrefix} ${node} ${batteryJs} --menu-bar-image${providerArgs}${codexIconArgs}${panelTextArgs} 2>/dev/null`,
72
139
  detailImage: `${envPrefix} ${node} ${batteryJs} --menu-detail-image${providerArgs} 2>/dev/null`,
140
+ railImage: `${envPrefix} ${node} ${batteryJs} --rail-image${providerArgs}${railTextArgs} 2>/dev/null`,
73
141
  detail: `${envPrefix} ${node} ${batteryJs} --no-color${providerArgs} 2>/dev/null`,
74
142
  state: `${envPrefix} ${node} ${batteryJs} --hud-state${providerArgs} 2>/dev/null`
75
143
  };
76
144
  }
77
145
 
78
- function macHudPids() {
146
+ function macHudPids(layout = "all") {
79
147
  const result = spawnSync("ps", ["-axo", "pid=,args="], {
80
148
  encoding: "utf8",
81
149
  stdio: ["ignore", "pipe", "ignore"]
82
150
  });
83
151
  if (result.status !== 0) return [];
84
- return macHudPidsFromPsOutput(result.stdout, process.pid);
152
+ return macHudPidsFromPsOutput(result.stdout, process.pid, layout);
85
153
  }
86
154
 
87
- function macHudCommandMatches(cmdline) {
155
+ function macHudCommandMatches(cmdline, layout = "all") {
88
156
  const text = String(cmdline || "").trim();
89
- if (!text.includes("ai-battery-macos-status.applescript")) return false;
90
- if (!text.includes("--menu-bar-image") || !text.includes("--menu-detail-image")) return false;
91
- return path.basename(text.split(/\s+/, 1)[0] || "") === "osascript";
157
+ if (path.basename(text.split(/\s+/, 1)[0] || "") !== "osascript") return false;
158
+ if (layout !== "rail" && text.includes("ai-battery-macos-status.applescript")) {
159
+ return text.includes("--menu-bar-image") && text.includes("--menu-detail-image");
160
+ }
161
+ if (layout !== "menu-bar" && text.includes("ai-battery-macos-rail.applescript")) {
162
+ return text.includes("--rail-image");
163
+ }
164
+ return false;
92
165
  }
93
166
 
94
- function macHudPidsFromPsOutput(output, ownPid = process.pid) {
167
+ function macHudPidsFromPsOutput(output, ownPid = process.pid, layout = "all") {
95
168
  return String(output || "")
96
169
  .split(/\r?\n/)
97
170
  .map((line) => {
@@ -103,12 +176,16 @@ function macHudPidsFromPsOutput(output, ownPid = process.pid) {
103
176
  && Number.isInteger(proc.pid)
104
177
  && proc.pid > 0
105
178
  && proc.pid !== ownPid
106
- && macHudCommandMatches(proc.cmdline))
179
+ && macHudCommandMatches(proc.cmdline, layout))
107
180
  .map((proc) => proc.pid);
108
181
  }
109
182
 
110
- function macLaunchAgentPath() {
111
- return path.join(home, "Library", "LaunchAgents", "com.ai-battery.hud.plist");
183
+ function macLaunchAgentLabel(layout = "menu-bar") {
184
+ return layout === "rail" ? "com.ai-battery.hud.rail" : "com.ai-battery.hud";
185
+ }
186
+
187
+ function macLaunchAgentPath(layout = "menu-bar") {
188
+ return path.join(home, "Library", "LaunchAgents", `${macLaunchAgentLabel(layout)}.plist`);
112
189
  }
113
190
 
114
191
  function macLaunchctlDomain() {
@@ -128,14 +205,21 @@ function plistString(value) {
128
205
  }
129
206
 
130
207
  function macAutostartPlist(options) {
208
+ const layout = options.layout === "rail" ? "rail" : "menu-bar";
131
209
  const args = [process.execPath, path.join(scriptDir, "ai-battery-hud.js"), "start", "--interval", String(options.interval)];
132
210
  if (options.provider !== "all") args.push("--provider", options.provider);
211
+ if (options.codexIcon === "black") args.push("--codex-icon", "black");
212
+ if (options.railText === "black") args.push("--text", "black");
213
+ if (layout === "rail") {
214
+ args.push("--layout", "rail");
215
+ if (options.scale && options.scale !== 1) args.push("--scale", String(options.scale));
216
+ }
133
217
  return `<?xml version="1.0" encoding="UTF-8"?>
134
218
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
135
219
  <plist version="1.0">
136
220
  <dict>
137
221
  <key>Label</key>
138
- <string>com.ai-battery.hud</string>
222
+ <string>${macLaunchAgentLabel(layout)}</string>
139
223
  <key>ProgramArguments</key>
140
224
  <array>
141
225
  ${args.map(plistString).join("\n")}
@@ -147,18 +231,19 @@ ${args.map(plistString).join("\n")}
147
231
  `;
148
232
  }
149
233
 
150
- function macAutostartStatus() {
151
- const filePath = macLaunchAgentPath();
234
+ function macAutostartStatus(layout = "menu-bar") {
235
+ const filePath = macLaunchAgentPath(layout);
152
236
  return { enabled: fs.existsSync(filePath), filePath };
153
237
  }
154
238
 
155
- function verifyMacAutostartOwnership(filePath) {
239
+ function verifyMacAutostartOwnership(filePath, layout = "menu-bar") {
156
240
  let stat;
157
241
  try { stat = fs.lstatSync(filePath); } catch (error) { if (error.code === "ENOENT") return false; throw error; }
158
242
  const text = stat.isFile() && !stat.isSymbolicLink() ? fs.readFileSync(filePath, "utf8") : "";
159
243
  const args = text.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1];
160
244
  const values = [...(args || "").matchAll(/<string>([^<]*)<\/string>/g)].map(match => match[1]);
161
- if (!/<key>Label<\/key>\s*<string>com\.ai-battery\.hud<\/string>/.test(text)
245
+ const expectedLabel = macLaunchAgentLabel(layout).replace(/\./g, "\\.");
246
+ if (!new RegExp(`<key>Label<\\/key>\\s*<string>${expectedLabel}<\\/string>`).test(text)
162
247
  || !/[\\/]ai-battery-hud\.js$/.test(values[1] || "") || values[2] !== "start") {
163
248
  throw new Error(`LaunchAgent ownership could not be verified; left untouched: ${filePath}`);
164
249
  }
@@ -166,17 +251,18 @@ function verifyMacAutostartOwnership(filePath) {
166
251
  }
167
252
 
168
253
  function macAutostartEnable(options) {
169
- const filePath = macLaunchAgentPath();
170
- verifyMacAutostartOwnership(filePath);
254
+ const layout = options.layout === "rail" ? "rail" : "menu-bar";
255
+ const filePath = macLaunchAgentPath(layout);
256
+ verifyMacAutostartOwnership(filePath, layout);
171
257
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
172
258
  fs.writeFileSync(filePath, macAutostartPlist(options), "utf8");
173
259
  runLaunchctl(["bootstrap", macLaunchctlDomain(), filePath]);
174
260
  return filePath;
175
261
  }
176
262
 
177
- function macAutostartDisable() {
178
- const filePath = macLaunchAgentPath();
179
- if (!verifyMacAutostartOwnership(filePath)) return filePath;
263
+ function macAutostartDisable(layout = "menu-bar") {
264
+ const filePath = macLaunchAgentPath(layout);
265
+ if (!verifyMacAutostartOwnership(filePath, layout)) return filePath;
180
266
  runLaunchctl(["bootout", macLaunchctlDomain(), filePath]);
181
267
  fs.rmSync(filePath, { force: true });
182
268
  return filePath;
@@ -204,26 +290,36 @@ function runMacHud(cliArgs) {
204
290
  ...(options.provider === "all" ? [] : ["--provider", options.provider])
205
291
  ], { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] });
206
292
  if (result.stdout) process.stdout.write(result.stdout);
207
- process.exit(result.status ?? 0);
293
+ process.exit(result.error ? 1 : (result.status ?? 1));
208
294
  }
209
295
 
210
296
  if (options.subcommand === "status") {
211
- const pids = macHudPids();
212
- const auto = macAutostartStatus();
297
+ const pids = macHudPids("menu-bar");
298
+ const railPids = macHudPids("rail");
299
+ const auto = macAutostartStatus("menu-bar");
300
+ const railAuto = macAutostartStatus("rail");
213
301
  console.log(`HUD: ${pids.length ? `running (PID ${pids[0]})` : "stopped"}`);
302
+ if (railPids.length || (options.layoutExplicit && options.layout === "rail")) {
303
+ console.log(`HUD Rail: ${railPids.length ? `running (PID ${railPids[0]})` : "stopped"}`);
304
+ }
214
305
  console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
215
306
  if (auto.enabled) console.log(` ${auto.filePath}`);
307
+ if (railAuto.enabled) {
308
+ console.log("Autostart Rail: on");
309
+ console.log(` ${railAuto.filePath}`);
310
+ }
216
311
  process.exit(0);
217
312
  }
218
313
 
219
314
  if (options.subcommand === "autostart") {
315
+ const layout = options.layout === "rail" ? "rail" : "menu-bar";
220
316
  if (options.autostartAction === "on") {
221
317
  console.log(`Autostart: on · ${macAutostartEnable(options)}`);
222
318
  console.log(cliText("Starts at macOS login.", "macOS 로그인 시 실행합니다."));
223
319
  } else if (options.autostartAction === "off") {
224
- console.log(`Autostart: off · ${macAutostartDisable()}`);
320
+ console.log(`Autostart: off · ${macAutostartDisable(layout)}`);
225
321
  } else {
226
- const auto = macAutostartStatus();
322
+ const auto = macAutostartStatus(layout);
227
323
  console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
228
324
  if (auto.enabled) console.log(` ${auto.filePath}`);
229
325
  }
@@ -231,34 +327,44 @@ function runMacHud(cliArgs) {
231
327
  }
232
328
 
233
329
  if (options.stop) {
234
- const pids = macHudPids();
330
+ const pids = macHudPids(options.layoutExplicit ? options.layout : "all");
235
331
  if (!pids.length) {
236
332
  console.log("HUD: stopped");
237
333
  process.exit(0);
238
334
  }
239
335
  const result = spawnSync("kill", pids.map(String), { stdio: "inherit" });
240
- if ((result.status ?? 0) === 0) console.log("HUD: stopped");
241
- process.exit(result.status ?? 0);
336
+ if (!result.error && result.status === 0) console.log("HUD: stopped");
337
+ process.exit(result.error ? 1 : (result.status ?? 1));
242
338
  }
243
339
 
244
- const existingPids = macHudPids();
340
+ const existingPids = macHudPids(options.layout);
245
341
  if (existingPids.length) {
246
342
  spawnSync("kill", existingPids.map(String), { stdio: "ignore" });
247
343
  sleepSync(400);
248
344
  }
249
345
 
250
- const osascriptArgs = [
251
- macStatusPath,
252
- commands.title,
253
- commands.detailImage,
254
- commands.detail,
255
- String(options.interval),
256
- commands.state
257
- ];
346
+ const isRail = options.layout === "rail";
347
+ const osascriptArgs = isRail
348
+ ? [
349
+ resolvedMacRailPath,
350
+ commands.railImage,
351
+ commands.detail,
352
+ String(options.interval),
353
+ commands.state,
354
+ String(options.scale)
355
+ ]
356
+ : [
357
+ macStatusPath,
358
+ commands.title,
359
+ commands.detailImage,
360
+ commands.detail,
361
+ String(options.interval),
362
+ commands.state
363
+ ];
258
364
 
259
365
  if (options.foreground) {
260
366
  const result = spawnSync("osascript", osascriptArgs, { stdio: "inherit" });
261
- process.exit(result.status ?? 0);
367
+ process.exit(result.error ? 1 : (result.status ?? 1));
262
368
  }
263
369
 
264
370
  const child = spawn("osascript", osascriptArgs, {
@@ -266,8 +372,10 @@ function runMacHud(cliArgs) {
266
372
  stdio: "ignore"
267
373
  });
268
374
  child.unref();
269
- console.log(`HUD: ${existingPids.length ? "restarted" : "started"} · menu bar`);
270
- console.log(cliText("Click for details. Stop: ai-battery hud stop", "클릭하면 상세 정보가 표시됩니다. 종료: ai-battery hud stop"));
375
+ console.log(`HUD: ${existingPids.length ? "restarted" : "started"} · ${isRail ? "rail" : "menu bar"}`);
376
+ console.log(isRail
377
+ ? cliText("Drag to move, right-click to resize. Stop: ai-battery hud stop rail", "드래그로 이동하고 우클릭으로 크기를 조절합니다. 종료: ai-battery hud stop rail")
378
+ : cliText("Click for details. Stop: ai-battery hud stop", "클릭하면 상세 정보가 표시됩니다. 종료: ai-battery hud stop"));
271
379
  process.exit(0);
272
380
  }
273
381
 
@@ -3,6 +3,7 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
 
5
5
  export function createProcessScanner({
6
+ execFileSync: runExecFileSync = execFileSync,
6
7
  isWsl,
7
8
  readJson,
8
9
  readScanCache,
@@ -48,7 +49,7 @@ function codexCommandIsBackground(cmdline) {
48
49
  const firstBase = commandTokenBasename(tokens[0]).toLowerCase();
49
50
  if (tokenMatchesProviderExecutable(tokens[0], "codex")) {
50
51
  commandIndex = 0;
51
- } else if (/^node(?:\.exe)?$/i.test(firstBase) && tokenMatchesProviderExecutable(tokens[1], "codex")) {
52
+ } else if (/^(?:node(?:\.exe)?|python(?:\d+(?:\.\d+)*)?|(?:ba|z)?sh)$/i.test(firstBase) && tokenMatchesProviderExecutable(tokens[1], "codex")) {
52
53
  commandIndex = 1;
53
54
  }
54
55
 
@@ -124,7 +125,7 @@ function commandMatchesProvider(cmdline, provider) {
124
125
 
125
126
  const firstBase = commandTokenBasename(tokens[0]).toLowerCase();
126
127
  if (tokenMatchesProviderExecutable(tokens[0], provider)) return true;
127
- if (/^node(?:\.exe)?$/i.test(firstBase) && tokenMatchesProviderExecutable(tokens[1], provider)) return true;
128
+ if (/^(?:node(?:\.exe)?|python(?:\d+(?:\.\d+)*)?|(?:ba|z)?sh)$/i.test(firstBase) && tokenMatchesProviderExecutable(tokens[1], provider)) return true;
128
129
 
129
130
  const runnerCommand = commandInvokesAiBatteryRunner(tokens)
130
131
  ? aiBatteryRunnerCommandTokens(tokens)
@@ -166,14 +167,17 @@ function processHasControllingTty(pid) {
166
167
 
167
168
  function listWindowsProcessCommands() {
168
169
  try {
169
- const output = execFileSync("powershell.exe", [
170
+ const psExe = process.platform !== "win32" && fs.existsSync("/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe")
171
+ ? "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe"
172
+ : "powershell.exe";
173
+ const output = runExecFileSync(psExe, [
170
174
  "-NoProfile",
171
175
  "-Command",
172
176
  "Get-CimInstance Win32_Process | ForEach-Object { $_.CommandLine }"
173
177
  ], {
174
178
  encoding: "utf8",
175
179
  stdio: ["ignore", "pipe", "ignore"],
176
- timeout: 2000,
180
+ timeout: 3000,
177
181
  windowsHide: true,
178
182
  maxBuffer: 2 * 1024 * 1024
179
183
  });
@@ -188,9 +192,12 @@ function listWindowsProcessCommands() {
188
192
  }
189
193
 
190
194
  function decodeCommandOutput(buffer) {
191
- return Buffer.from(buffer || "")
192
- .toString("utf8")
193
- .replace(/\0/g, "");
195
+ if (typeof buffer === "string") return buffer.replace(/^\uFEFF/, "").replace(/\0/g, "");
196
+ const raw = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer || "");
197
+ const hasUtf16LeBom = raw.length >= 2 && raw[0] === 0xff && raw[1] === 0xfe;
198
+ const looksUtf16Le = hasUtf16LeBom || (raw.length >= 2 && raw.length % 2 === 0 && raw.includes(0));
199
+ const text = looksUtf16Le ? raw.toString("utf16le") : raw.toString("utf8");
200
+ return text.replace(/^\uFEFF/, "").replace(/\0/g, "");
194
201
  }
195
202
 
196
203
  function parseTtyProcessListOutput(output, source = null) {
@@ -203,7 +210,7 @@ function parseTtyProcessListOutput(output, source = null) {
203
210
  const tty = trimmed.slice(0, space);
204
211
  const cmdline = trimmed.slice(space + 1).trim();
205
212
  if (!cmdline) return null;
206
- const proc = { cmdline, hasTty: tty !== "??" && tty !== "-" };
213
+ const proc = { cmdline, hasTty: tty !== "?" && tty !== "??" && tty !== "-" };
207
214
  if (source) proc.source = source;
208
215
  return proc;
209
216
  })
@@ -212,7 +219,7 @@ function parseTtyProcessListOutput(output, source = null) {
212
219
 
213
220
  function listDarwinProcessCommands() {
214
221
  try {
215
- const output = execFileSync("ps", ["-axo", "tty=,args="], {
222
+ const output = runExecFileSync("ps", ["-axo", "tty=,args="], {
216
223
  encoding: "utf8",
217
224
  stdio: ["ignore", "pipe", "ignore"],
218
225
  timeout: 1500,
@@ -227,13 +234,13 @@ function listDarwinProcessCommands() {
227
234
  function runningWslDistros() {
228
235
  if (process.platform !== "win32") return [];
229
236
  try {
230
- const output = decodeCommandOutput(execFileSync("wsl.exe", [
237
+ const output = decodeCommandOutput(runExecFileSync("wsl.exe", [
231
238
  "--list",
232
239
  "--running",
233
240
  "--quiet"
234
241
  ], {
235
242
  stdio: ["ignore", "pipe", "ignore"],
236
- timeout: 1000,
243
+ timeout: 2500,
237
244
  maxBuffer: 256 * 1024,
238
245
  windowsHide: true
239
246
  }));
@@ -242,34 +249,38 @@ function runningWslDistros() {
242
249
  .map((line) => line.trim())
243
250
  .filter(Boolean);
244
251
  } catch {
245
- return [];
252
+ return null;
246
253
  }
247
254
  }
248
255
 
249
256
  function listWslProcessCommands() {
250
257
  const distros = runningWslDistros();
258
+ if (distros === null) return null;
251
259
  if (!distros.length) return [];
252
260
 
253
261
  const commands = [];
262
+ let hadFailure = false;
254
263
  for (const distro of distros) {
255
264
  try {
256
- const output = decodeCommandOutput(execFileSync("wsl.exe", [
265
+ const output = decodeCommandOutput(runExecFileSync("wsl.exe", [
257
266
  "--distribution",
258
267
  distro,
259
- "bash",
260
- "-lc",
261
- "ps -axo tty=,args="
268
+ "--exec",
269
+ "ps",
270
+ "-axo",
271
+ "tty=,args="
262
272
  ], {
263
273
  stdio: ["ignore", "pipe", "ignore"],
264
- timeout: 1500,
274
+ timeout: 2500,
265
275
  maxBuffer: 4 * 1024 * 1024,
266
276
  windowsHide: true
267
277
  }));
268
278
  commands.push(...parseTtyProcessListOutput(output, "wsl"));
269
279
  } catch {
270
- // A distro can exit between --list --running and the process query.
280
+ hadFailure = true;
271
281
  }
272
282
  }
283
+ if (hadFailure && !commands.length) return null;
273
284
  return commands;
274
285
  }
275
286
 
@@ -302,31 +313,57 @@ function listProcProcessCommands() {
302
313
  }
303
314
 
304
315
  const PROCESS_SCAN_TTL_MS = 2000;
316
+ const ERROR_FALLBACK_MAX_AGE_SECONDS = 30;
317
+ const NONBLOCKING_STALE_MAX_AGE_SECONDS = 60;
305
318
  let processScanMemo = null;
306
319
 
307
- function scanProcessCommands() {
308
- if (processScanMemo && Date.now() - processScanMemo.at < PROCESS_SCAN_TTL_MS) {
320
+ function readBoundedFallbackCache(name, maxAgeSeconds) {
321
+ const cached = readScanCache(name, maxAgeSeconds);
322
+ if (cached && Array.isArray(cached.value)) return cached.value;
323
+ const raw = readJson(scanCachePath(name));
324
+ if (!raw || !Array.isArray(raw.value)) return [];
325
+ const savedMs = Date.parse(raw.capturedAt || raw.savedAt || raw.timestamp || "");
326
+ if (Number.isFinite(savedMs) && Date.now() - savedMs <= maxAgeSeconds * 1000) {
327
+ return raw.value;
328
+ }
329
+ return [];
330
+ }
331
+
332
+ function scanProcessCommands(options = {}) {
333
+ const nonBlocking = Boolean(options?.nonBlocking);
334
+ const triggerBackgroundRefresh = typeof options?.triggerBackgroundRefresh === "function"
335
+ ? options.triggerBackgroundRefresh
336
+ : null;
337
+ if (!options?.forceRefresh && processScanMemo && Date.now() - processScanMemo.at < PROCESS_SCAN_TTL_MS && (!processScanMemo.nonBlocking || nonBlocking)) {
309
338
  return processScanMemo.commands;
310
339
  }
311
340
 
312
341
  let commands;
342
+ const ttlSeconds = scanCacheSeconds(10);
313
343
  if (process.platform === "win32") {
314
344
  // Spawning PowerShell for the process list is the slow part on Windows, so
315
345
  // share one recent scan between the HUD, statusline, and watch invocations.
316
346
  // Windows and WSL draw on the same desktop, so include running WSL distros
317
347
  // when they are already up; --list --running avoids starting WSL just to
318
348
  // satisfy a HUD refresh.
319
- const cached = readScanCache("windows-processes", scanCacheSeconds(3));
349
+ const cached = !options?.forceRefresh ? readScanCache("windows-processes", ttlSeconds) : null;
320
350
  if (cached) {
321
351
  commands = Array.isArray(cached.value) ? cached.value : [];
352
+ } else if (nonBlocking) {
353
+ commands = readBoundedFallbackCache("windows-processes", NONBLOCKING_STALE_MAX_AGE_SECONDS);
354
+ triggerBackgroundRefresh?.();
322
355
  } else {
323
356
  const windowsCommands = listWindowsProcessCommands();
324
357
  if (windowsCommands === null) {
325
- commands = readJson(scanCachePath("windows-processes"))?.value ?? [];
358
+ commands = readBoundedFallbackCache("windows-processes", ERROR_FALLBACK_MAX_AGE_SECONDS);
326
359
  } else {
360
+ const wslCommands = listWslProcessCommands();
361
+ const resolvedWsl = wslCommands === null
362
+ ? readBoundedFallbackCache("windows-processes", ERROR_FALLBACK_MAX_AGE_SECONDS).filter(item => item?.source === "wsl")
363
+ : wslCommands;
327
364
  commands = [
328
365
  ...windowsCommands,
329
- ...listWslProcessCommands()
366
+ ...resolvedWsl
330
367
  ];
331
368
  writeScanCache("windows-processes", commands);
332
369
  }
@@ -339,17 +376,27 @@ function scanProcessCommands() {
339
376
  // WSL shares a visible desktop with native Windows apps. Pull in the
340
377
  // Windows process list too, while keeping the Linux /proc scan as the
341
378
  // source for WSL TTY ownership.
342
- const cached = readScanCache("wsl-windows-processes", scanCacheSeconds(3));
379
+ const cached = !options?.forceRefresh ? readScanCache("wsl-windows-processes", ttlSeconds) : null;
343
380
  let windowsCommands = cached?.value;
344
381
  if (!Array.isArray(windowsCommands)) {
345
- windowsCommands = listWindowsProcessCommands() || [];
346
- writeScanCache("wsl-windows-processes", windowsCommands);
382
+ if (nonBlocking) {
383
+ windowsCommands = readBoundedFallbackCache("wsl-windows-processes", NONBLOCKING_STALE_MAX_AGE_SECONDS);
384
+ triggerBackgroundRefresh?.();
385
+ } else {
386
+ const scanned = listWindowsProcessCommands();
387
+ if (scanned === null) {
388
+ windowsCommands = readBoundedFallbackCache("wsl-windows-processes", ERROR_FALLBACK_MAX_AGE_SECONDS);
389
+ } else {
390
+ windowsCommands = scanned;
391
+ writeScanCache("wsl-windows-processes", windowsCommands);
392
+ }
393
+ }
347
394
  }
348
395
  commands = [...commands, ...windowsCommands];
349
396
  }
350
397
  }
351
398
 
352
- processScanMemo = { at: Date.now(), commands };
399
+ processScanMemo = { at: Date.now(), commands, nonBlocking };
353
400
  return commands;
354
401
  }
355
402
 
@@ -364,8 +411,8 @@ function providerRunningInProcesses(provider, processes, platform = process.plat
364
411
  });
365
412
  }
366
413
 
367
- function isProviderRunning(provider) {
368
- return providerRunningInProcesses(provider, scanProcessCommands());
414
+ function isProviderRunning(provider, options = {}) {
415
+ return providerRunningInProcesses(provider, scanProcessCommands(options));
369
416
  }
370
417
 
371
418
  function codexBackgroundReadyInProcesses(processes) {
@@ -374,6 +421,7 @@ function codexBackgroundReadyInProcesses(processes) {
374
421
  return {
375
422
  codexBackgroundReadyInProcesses,
376
423
  commandMatchesProvider,
424
+ decodeCommandOutput,
377
425
  isProviderRunning,
378
426
  parseTtyProcessListOutput,
379
427
  providerRunningInProcesses,
@@ -13,7 +13,7 @@ export function windowsAutostartCleanupScript({ registryPath, registryName }) {
13
13
  "if ($v -and $v -ne $expected) { throw 'AiBatteryHud registry value changed; left it untouched.' }",
14
14
  "$ownedFile = $false",
15
15
  "if (Test-Path -LiteralPath $auto) {",
16
- " $ownedFile = (Get-Content -Raw -LiteralPath $auto).StartsWith('# Generated by: ai-battery hud autostart on')",
16
+ " $ownedFile = ([string](Get-Content -Raw -LiteralPath $auto)).StartsWith('# Generated by: ai-battery hud autostart on')",
17
17
  " if (-not $ownedFile) { throw 'Autostart file changed; left it and its registry value untouched.' }",
18
18
  "}",
19
19
  `if ($v) { Remove-ItemProperty -Path ${quote(registryPath)} -Name ${quote(registryName)} }`,