ai-battery 0.1.11 → 0.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +331 -331
- package/bin/ai-battery-hud +21 -21
- package/bin/ai-battery-hud.js +593 -593
- package/bin/ai-battery-hud.ps1 +2064 -2064
- package/bin/ai-battery-macos-status.applescript +134 -134
- package/bin/ai-battery-run +378 -378
- package/bin/ai-battery-run-win.js +696 -686
- package/bin/ai-battery.js +4437 -4323
- package/docs/claude-statusline-preview.svg +37 -37
- package/docs/terminal-preview.svg +44 -44
- package/package.json +57 -57
package/bin/ai-battery-hud.js
CHANGED
|
@@ -1,598 +1,598 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
import { spawn, spawnSync } from "node:child_process";
|
|
4
|
-
import fs from "node:fs";
|
|
5
|
-
import os from "node:os";
|
|
6
|
-
import path from "node:path";
|
|
7
|
-
import { fileURLToPath } from "node:url";
|
|
8
|
-
|
|
9
|
-
const scriptPath = fs.realpathSync(fileURLToPath(import.meta.url));
|
|
10
|
-
const scriptDir = path.dirname(scriptPath);
|
|
11
|
-
const ps1Path = path.join(scriptDir, "ai-battery-hud.ps1");
|
|
12
|
-
const macStatusPath = path.join(scriptDir, "ai-battery-macos-status.applescript");
|
|
13
|
-
|
|
14
|
-
function isWsl() {
|
|
15
|
-
if (process.platform !== "linux") return false;
|
|
16
|
-
if (process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP) return true;
|
|
17
|
-
try {
|
|
18
|
-
return fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft");
|
|
19
|
-
} catch {
|
|
20
|
-
return false;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function commandExists(command) {
|
|
25
|
-
const result = spawnSync(command, ["-NoProfile", "-Command", "$PSVersionTable.PSVersion.Major"], {
|
|
26
|
-
encoding: "utf8",
|
|
27
|
-
stdio: "ignore",
|
|
28
|
-
windowsHide: true
|
|
29
|
-
});
|
|
30
|
-
return result.status === 0;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function wslPath(filePath) {
|
|
34
|
-
const result = spawnSync("wslpath", ["-w", filePath], {
|
|
35
|
-
encoding: "utf8",
|
|
36
|
-
stdio: ["ignore", "pipe", "ignore"]
|
|
37
|
-
});
|
|
38
|
-
if (result.status !== 0 || !result.stdout.trim()) {
|
|
39
|
-
throw new Error("wslpath failed while resolving the HUD PowerShell script path");
|
|
40
|
-
}
|
|
41
|
-
return result.stdout.trim();
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function shellQuote(value) {
|
|
45
|
-
return `'${String(value).replace(/'/g, "'\\''")}'`;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function wslEnvPrefix() {
|
|
49
|
-
const names = [
|
|
50
|
-
"AI_BATTERY_STATE_DIR",
|
|
51
|
-
"CLAUDEX_BATTERY_STATE_DIR",
|
|
52
|
-
"AI_BATTERY_COLUMNS",
|
|
53
|
-
"CLAUDEX_BATTERY_COLUMNS",
|
|
54
|
-
"AI_BATTERY_COLUMN_GUARD",
|
|
55
|
-
"CLAUDEX_BATTERY_COLUMN_GUARD",
|
|
56
|
-
"CODEX_HOME"
|
|
57
|
-
];
|
|
58
|
-
return names
|
|
59
|
-
.filter((name) => process.env[name])
|
|
60
|
-
.map((name) => `${name}=${shellQuote(process.env[name])}`)
|
|
61
|
-
.join(" ");
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function psSingleQuote(value) {
|
|
65
|
-
return `'${String(value).replace(/'/g, "''")}'`;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
function winArgQuote(value) {
|
|
69
|
-
return `"${String(value).replace(/"/g, '\\"')}"`;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function buildStartProcessCommand(filePath, args) {
|
|
73
|
-
const commandLine = args.map(winArgQuote).join(" ");
|
|
74
|
-
return `Start-Process -WindowStyle Hidden -FilePath ${psSingleQuote(filePath)} -ArgumentList ${psSingleQuote(commandLine)}`;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function psInvocationArg(value) {
|
|
78
|
-
const text = String(value);
|
|
79
|
-
if (/^-[A-Za-z][A-Za-z0-9]*$/.test(text)) return text;
|
|
80
|
-
return psSingleQuote(text);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function powerShellCommandArgs(scriptPath, scriptArgs) {
|
|
84
|
-
const invocation = `& ${psSingleQuote(scriptPath)} ${scriptArgs.map(psInvocationArg).join(" ")}`;
|
|
85
|
-
return [
|
|
86
|
-
"-NoProfile",
|
|
87
|
-
"-ExecutionPolicy",
|
|
88
|
-
"Bypass",
|
|
89
|
-
"-Command",
|
|
90
|
-
invocation
|
|
91
|
-
];
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function sleepSync(ms) {
|
|
95
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
function waitForFile(filePath, timeoutMs = 3500) {
|
|
99
|
-
const start = Date.now();
|
|
100
|
-
while (Date.now() - start < timeoutMs) {
|
|
101
|
-
if (fs.existsSync(filePath)) return true;
|
|
102
|
-
sleepSync(100);
|
|
103
|
-
}
|
|
104
|
-
return false;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
function snapshotHasWeekly(jsonText) {
|
|
108
|
-
try {
|
|
109
|
-
const snapshot = JSON.parse(jsonText);
|
|
110
|
-
if (!Array.isArray(snapshot.results)) return false;
|
|
111
|
-
const usageResults = snapshot.results.filter((result) => {
|
|
112
|
-
return result
|
|
113
|
-
&& result.ok
|
|
114
|
-
&& ["codex", "claude"].includes(result.provider)
|
|
115
|
-
&& typeof result.percentRemaining === "number";
|
|
116
|
-
});
|
|
117
|
-
return usageResults.length > 0 && usageResults.every((result) => result.secondary);
|
|
118
|
-
} catch {
|
|
119
|
-
return false;
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
function prefetchInitialJson(command, useWslCommand) {
|
|
124
|
-
if (process.env.AI_BATTERY_HUD_NO_PREFETCH) return null;
|
|
125
|
-
|
|
126
|
-
const attempts = 8;
|
|
127
|
-
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
128
|
-
const result = useWslCommand
|
|
129
|
-
? spawnSync("bash", ["-lc", command], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000 })
|
|
130
|
-
: spawnSync(process.execPath, [batteryJs, "--json"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000 });
|
|
131
|
-
|
|
132
|
-
const text = result.stdout?.trim();
|
|
133
|
-
if (result.status === 0 && text) {
|
|
134
|
-
if (snapshotHasWeekly(text) || attempt === attempts - 1) return text;
|
|
135
|
-
}
|
|
136
|
-
sleepSync(180);
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
return null;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
function relevantEnvPrefix() {
|
|
143
|
-
const names = [
|
|
144
|
-
"AI_BATTERY_STATE_DIR",
|
|
145
|
-
"CLAUDEX_BATTERY_STATE_DIR",
|
|
146
|
-
"AI_BATTERY_COLUMNS",
|
|
147
|
-
"CLAUDEX_BATTERY_COLUMNS",
|
|
148
|
-
"AI_BATTERY_COLUMN_GUARD",
|
|
149
|
-
"CLAUDEX_BATTERY_COLUMN_GUARD",
|
|
150
|
-
"CODEX_HOME"
|
|
151
|
-
];
|
|
152
|
-
const pairs = [`HOME=${shellQuote(os.homedir())}`];
|
|
153
|
-
for (const name of names) {
|
|
154
|
-
if (process.env[name]) pairs.push(`${name}=${shellQuote(process.env[name])}`);
|
|
155
|
-
}
|
|
156
|
-
return pairs.join(" ");
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
function parseMacHudArgs(cliArgs) {
|
|
160
|
-
const options = {
|
|
161
|
-
foreground: false,
|
|
162
|
-
once: false,
|
|
163
|
-
stop: false,
|
|
164
|
-
subcommand: null,
|
|
165
|
-
autostartAction: "status",
|
|
166
|
-
interval: 10,
|
|
167
|
-
provider: "all"
|
|
168
|
-
};
|
|
169
|
-
|
|
170
|
-
for (let i = 0; i < cliArgs.length; i += 1) {
|
|
171
|
-
const arg = cliArgs[i];
|
|
172
|
-
if (arg === "-Foreground" || arg === "--foreground") {
|
|
173
|
-
options.foreground = true;
|
|
174
|
-
} else if (arg === "-Once" || arg === "--once") {
|
|
175
|
-
options.once = true;
|
|
176
|
-
} else if (arg === "-Stop" || arg === "--stop" || arg === "stop") {
|
|
177
|
-
options.stop = true;
|
|
178
|
-
} else if (arg === "start") {
|
|
179
|
-
// Starting is the default action.
|
|
180
|
-
} else if (arg === "status") {
|
|
181
|
-
options.subcommand = "status";
|
|
182
|
-
} else if (arg === "autostart") {
|
|
183
|
-
options.subcommand = "autostart";
|
|
184
|
-
const next = cliArgs[i + 1];
|
|
185
|
-
if (next === "on" || next === "off" || next === "status") {
|
|
186
|
-
options.autostartAction = next;
|
|
187
|
-
i += 1;
|
|
188
|
-
}
|
|
189
|
-
} else if (arg === "-Interval" || arg === "--interval") {
|
|
190
|
-
const next = cliArgs[i + 1];
|
|
191
|
-
if (next && !next.startsWith("-")) {
|
|
192
|
-
options.interval = Math.max(1, Number(next) || options.interval);
|
|
193
|
-
i += 1;
|
|
194
|
-
}
|
|
195
|
-
} else if (arg === "--provider" || arg === "-p") {
|
|
196
|
-
const next = cliArgs[i + 1];
|
|
197
|
-
if (["all", "codex", "claude"].includes(next)) {
|
|
198
|
-
options.provider = next;
|
|
199
|
-
i += 1;
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
return options;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
function macProviderArgs(provider) {
|
|
208
|
-
return provider === "all" ? "" : ` --provider ${shellQuote(provider)}`;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
function macCommands(options) {
|
|
212
|
-
const node = shellQuote(process.execPath);
|
|
213
|
-
const batteryJs = shellQuote(path.join(scriptDir, "ai-battery.js"));
|
|
214
|
-
const providerArgs = macProviderArgs(options.provider);
|
|
215
|
-
const envPrefix = relevantEnvPrefix();
|
|
216
|
-
return {
|
|
217
|
-
title: `${envPrefix} ${node} ${batteryJs} --menu-bar-image${providerArgs} 2>/dev/null`,
|
|
218
|
-
detailImage: `${envPrefix} ${node} ${batteryJs} --menu-detail-image${providerArgs} 2>/dev/null`,
|
|
219
|
-
detail: `${envPrefix} ${node} ${batteryJs} --no-color${providerArgs} 2>/dev/null`
|
|
220
|
-
};
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
function macHudPids() {
|
|
224
|
-
const result = spawnSync("pgrep", ["-f", macStatusPath], {
|
|
225
|
-
encoding: "utf8",
|
|
226
|
-
stdio: ["ignore", "pipe", "ignore"]
|
|
227
|
-
});
|
|
228
|
-
if (result.status !== 0) return [];
|
|
229
|
-
return (result.stdout || "")
|
|
230
|
-
.trim()
|
|
231
|
-
.split(/\s+/)
|
|
232
|
-
.map((pid) => Number(pid))
|
|
233
|
-
.filter((pid) => Number.isInteger(pid) && pid > 0 && pid !== process.pid);
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
function macLaunchAgentPath() {
|
|
237
|
-
return path.join(os.homedir(), "Library", "LaunchAgents", "com.ai-battery.hud.plist");
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
function macLaunchctlDomain() {
|
|
241
|
-
return `gui/${typeof process.getuid === "function" ? process.getuid() : ""}`;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
function xmlEscape(value) {
|
|
245
|
-
return String(value)
|
|
246
|
-
.replace(/&/g, "&")
|
|
247
|
-
.replace(/</g, "<")
|
|
248
|
-
.replace(/>/g, ">")
|
|
249
|
-
.replace(/"/g, """);
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
function plistString(value) {
|
|
253
|
-
return ` <string>${xmlEscape(value)}</string>`;
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
function macAutostartPlist(options) {
|
|
257
|
-
const args = [process.execPath, scriptPath, "start", "--interval", String(options.interval)];
|
|
258
|
-
if (options.provider !== "all") args.push("--provider", options.provider);
|
|
259
|
-
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
260
|
-
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
261
|
-
<plist version="1.0">
|
|
262
|
-
<dict>
|
|
263
|
-
<key>Label</key>
|
|
264
|
-
<string>com.ai-battery.hud</string>
|
|
265
|
-
<key>ProgramArguments</key>
|
|
266
|
-
<array>
|
|
267
|
-
${args.map(plistString).join("\n")}
|
|
268
|
-
</array>
|
|
269
|
-
<key>RunAtLoad</key>
|
|
270
|
-
<true/>
|
|
271
|
-
</dict>
|
|
272
|
-
</plist>
|
|
273
|
-
`;
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
function macAutostartStatus() {
|
|
277
|
-
const filePath = macLaunchAgentPath();
|
|
278
|
-
return { enabled: fs.existsSync(filePath), filePath };
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
function macAutostartEnable(options) {
|
|
282
|
-
const filePath = macLaunchAgentPath();
|
|
283
|
-
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
284
|
-
fs.writeFileSync(filePath, macAutostartPlist(options), "utf8");
|
|
285
|
-
spawnSync("launchctl", ["bootstrap", macLaunchctlDomain(), filePath], { stdio: "ignore" });
|
|
286
|
-
return filePath;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
function macAutostartDisable() {
|
|
290
|
-
const filePath = macLaunchAgentPath();
|
|
291
|
-
spawnSync("launchctl", ["bootout", macLaunchctlDomain(), filePath], { stdio: "ignore" });
|
|
292
|
-
fs.rmSync(filePath, { force: true });
|
|
293
|
-
return filePath;
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
function runMacHud(cliArgs) {
|
|
297
|
-
const options = parseMacHudArgs(cliArgs);
|
|
298
|
-
const commands = macCommands(options);
|
|
299
|
-
|
|
300
|
-
if (options.once) {
|
|
301
|
-
const result = spawnSync(process.execPath, [
|
|
302
|
-
path.join(scriptDir, "ai-battery.js"),
|
|
303
|
-
"--menu-bar",
|
|
304
|
-
...(options.provider === "all" ? [] : ["--provider", options.provider])
|
|
305
|
-
], { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] });
|
|
306
|
-
if (result.stdout) process.stdout.write(result.stdout);
|
|
307
|
-
process.exit(result.status ?? 0);
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
if (options.subcommand === "status") {
|
|
311
|
-
const pids = macHudPids();
|
|
312
|
-
const auto = macAutostartStatus();
|
|
313
|
-
console.log(`HUD: ${pids.length ? `running (PID ${pids[0]})` : "stopped"}`);
|
|
314
|
-
console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
|
|
315
|
-
if (auto.enabled) console.log(` ${auto.filePath}`);
|
|
316
|
-
process.exit(0);
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
if (options.subcommand === "autostart") {
|
|
320
|
-
if (options.autostartAction === "on") {
|
|
321
|
-
console.log(`HUD autostart enabled: ${macAutostartEnable(options)}`);
|
|
322
|
-
} else if (options.autostartAction === "off") {
|
|
323
|
-
console.log(`HUD autostart disabled: ${macAutostartDisable()}`);
|
|
324
|
-
} else {
|
|
325
|
-
const auto = macAutostartStatus();
|
|
326
|
-
console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
|
|
327
|
-
if (auto.enabled) console.log(` ${auto.filePath}`);
|
|
328
|
-
}
|
|
329
|
-
process.exit(0);
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
if (options.stop) {
|
|
333
|
-
const pids = macHudPids();
|
|
334
|
-
if (!pids.length) {
|
|
335
|
-
console.log("AI Battery menu bar is not running.");
|
|
336
|
-
process.exit(0);
|
|
337
|
-
}
|
|
338
|
-
const result = spawnSync("kill", pids.map(String), { stdio: "inherit" });
|
|
339
|
-
if ((result.status ?? 0) === 0) console.log("AI Battery menu bar stopped.");
|
|
340
|
-
process.exit(result.status ?? 0);
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
const existingPids = macHudPids();
|
|
344
|
-
if (existingPids.length) {
|
|
345
|
-
spawnSync("kill", existingPids.map(String), { stdio: "ignore" });
|
|
346
|
-
sleepSync(400);
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
const osascriptArgs = [
|
|
350
|
-
macStatusPath,
|
|
351
|
-
commands.title,
|
|
352
|
-
commands.detailImage,
|
|
353
|
-
commands.detail,
|
|
354
|
-
String(options.interval)
|
|
355
|
-
];
|
|
356
|
-
|
|
357
|
-
if (options.foreground) {
|
|
358
|
-
const result = spawnSync("osascript", osascriptArgs, { stdio: "inherit" });
|
|
359
|
-
process.exit(result.status ?? 0);
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
const child = spawn("osascript", osascriptArgs, {
|
|
363
|
-
detached: true,
|
|
364
|
-
stdio: "ignore"
|
|
365
|
-
});
|
|
366
|
-
child.unref();
|
|
367
|
-
console.log(`${existingPids.length ? "AI Battery menu bar restarted" : "AI Battery menu bar started"}. Click the menu bar item for details; use "ai-battery hud stop" to close it.`);
|
|
368
|
-
process.exit(0);
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
if (process.platform === "darwin") {
|
|
372
|
-
runMacHud(process.argv.slice(2));
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
const useWsl = isWsl();
|
|
376
|
-
const powershell = "powershell.exe";
|
|
377
|
-
|
|
378
|
-
if (!useWsl && process.platform !== "win32") {
|
|
379
|
-
console.error("ai-battery-hud: desktop HUD needs Windows (native or WSL) or macOS.");
|
|
380
|
-
console.error("On Linux terminals use: ai-battery --watch");
|
|
381
|
-
process.exit(1);
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
if (!commandExists(powershell)) {
|
|
385
|
-
console.error("ai-battery-hud: powershell.exe is required for the Windows HUD.");
|
|
386
|
-
process.exit(1);
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
const filteredArgs = [];
|
|
390
|
-
let foreground = false;
|
|
391
|
-
let once = false;
|
|
392
|
-
let stop = false;
|
|
393
|
-
let subcommand = null;
|
|
394
|
-
let autostartAction = "status";
|
|
395
|
-
|
|
396
|
-
const cliArgs = process.argv.slice(2);
|
|
397
|
-
for (let i = 0; i < cliArgs.length; i += 1) {
|
|
398
|
-
const arg = cliArgs[i];
|
|
399
|
-
if (arg === "-Foreground" || arg === "--foreground") {
|
|
400
|
-
foreground = true;
|
|
401
|
-
} else if (arg === "-Movable" || arg === "--movable") {
|
|
402
|
-
filteredArgs.push("-Movable");
|
|
403
|
-
} else if (arg === "-Once" || arg === "--once") {
|
|
404
|
-
once = true;
|
|
405
|
-
filteredArgs.push("-Once");
|
|
406
|
-
} else if (arg === "-Stop" || arg === "--stop" || arg === "stop") {
|
|
407
|
-
stop = true;
|
|
408
|
-
filteredArgs.push("-StopExisting");
|
|
409
|
-
} else if (arg === "start") {
|
|
410
|
-
// Launching is the default action.
|
|
411
|
-
} else if (arg === "status") {
|
|
412
|
-
subcommand = "status";
|
|
413
|
-
} else if (arg === "autostart") {
|
|
414
|
-
subcommand = "autostart";
|
|
415
|
-
const next = cliArgs[i + 1];
|
|
416
|
-
if (next === "on" || next === "off" || next === "status") {
|
|
417
|
-
autostartAction = next;
|
|
418
|
-
i += 1;
|
|
419
|
-
}
|
|
420
|
-
} else {
|
|
421
|
-
filteredArgs.push(arg);
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
const hudScript = useWsl ? wslPath(ps1Path) : ps1Path;
|
|
426
|
-
const nodePath = process.execPath;
|
|
427
|
-
const batteryJs = path.join(scriptDir, "ai-battery.js");
|
|
428
|
-
const configuredCommand = process.env.AI_BATTERY_COMMAND || process.env.CLAUDEX_BATTERY_COMMAND;
|
|
2
|
+
|
|
3
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
|
|
9
|
+
const scriptPath = fs.realpathSync(fileURLToPath(import.meta.url));
|
|
10
|
+
const scriptDir = path.dirname(scriptPath);
|
|
11
|
+
const ps1Path = path.join(scriptDir, "ai-battery-hud.ps1");
|
|
12
|
+
const macStatusPath = path.join(scriptDir, "ai-battery-macos-status.applescript");
|
|
13
|
+
|
|
14
|
+
function isWsl() {
|
|
15
|
+
if (process.platform !== "linux") return false;
|
|
16
|
+
if (process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP) return true;
|
|
17
|
+
try {
|
|
18
|
+
return fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft");
|
|
19
|
+
} catch {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function commandExists(command) {
|
|
25
|
+
const result = spawnSync(command, ["-NoProfile", "-Command", "$PSVersionTable.PSVersion.Major"], {
|
|
26
|
+
encoding: "utf8",
|
|
27
|
+
stdio: "ignore",
|
|
28
|
+
windowsHide: true
|
|
29
|
+
});
|
|
30
|
+
return result.status === 0;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function wslPath(filePath) {
|
|
34
|
+
const result = spawnSync("wslpath", ["-w", filePath], {
|
|
35
|
+
encoding: "utf8",
|
|
36
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
37
|
+
});
|
|
38
|
+
if (result.status !== 0 || !result.stdout.trim()) {
|
|
39
|
+
throw new Error("wslpath failed while resolving the HUD PowerShell script path");
|
|
40
|
+
}
|
|
41
|
+
return result.stdout.trim();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function shellQuote(value) {
|
|
45
|
+
return `'${String(value).replace(/'/g, "'\\''")}'`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function wslEnvPrefix() {
|
|
49
|
+
const names = [
|
|
50
|
+
"AI_BATTERY_STATE_DIR",
|
|
51
|
+
"CLAUDEX_BATTERY_STATE_DIR",
|
|
52
|
+
"AI_BATTERY_COLUMNS",
|
|
53
|
+
"CLAUDEX_BATTERY_COLUMNS",
|
|
54
|
+
"AI_BATTERY_COLUMN_GUARD",
|
|
55
|
+
"CLAUDEX_BATTERY_COLUMN_GUARD",
|
|
56
|
+
"CODEX_HOME"
|
|
57
|
+
];
|
|
58
|
+
return names
|
|
59
|
+
.filter((name) => process.env[name])
|
|
60
|
+
.map((name) => `${name}=${shellQuote(process.env[name])}`)
|
|
61
|
+
.join(" ");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function psSingleQuote(value) {
|
|
65
|
+
return `'${String(value).replace(/'/g, "''")}'`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function winArgQuote(value) {
|
|
69
|
+
return `"${String(value).replace(/"/g, '\\"')}"`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function buildStartProcessCommand(filePath, args) {
|
|
73
|
+
const commandLine = args.map(winArgQuote).join(" ");
|
|
74
|
+
return `Start-Process -WindowStyle Hidden -FilePath ${psSingleQuote(filePath)} -ArgumentList ${psSingleQuote(commandLine)}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function psInvocationArg(value) {
|
|
78
|
+
const text = String(value);
|
|
79
|
+
if (/^-[A-Za-z][A-Za-z0-9]*$/.test(text)) return text;
|
|
80
|
+
return psSingleQuote(text);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function powerShellCommandArgs(scriptPath, scriptArgs) {
|
|
84
|
+
const invocation = `& ${psSingleQuote(scriptPath)} ${scriptArgs.map(psInvocationArg).join(" ")}`;
|
|
85
|
+
return [
|
|
86
|
+
"-NoProfile",
|
|
87
|
+
"-ExecutionPolicy",
|
|
88
|
+
"Bypass",
|
|
89
|
+
"-Command",
|
|
90
|
+
invocation
|
|
91
|
+
];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function sleepSync(ms) {
|
|
95
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function waitForFile(filePath, timeoutMs = 3500) {
|
|
99
|
+
const start = Date.now();
|
|
100
|
+
while (Date.now() - start < timeoutMs) {
|
|
101
|
+
if (fs.existsSync(filePath)) return true;
|
|
102
|
+
sleepSync(100);
|
|
103
|
+
}
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function snapshotHasWeekly(jsonText) {
|
|
108
|
+
try {
|
|
109
|
+
const snapshot = JSON.parse(jsonText);
|
|
110
|
+
if (!Array.isArray(snapshot.results)) return false;
|
|
111
|
+
const usageResults = snapshot.results.filter((result) => {
|
|
112
|
+
return result
|
|
113
|
+
&& result.ok
|
|
114
|
+
&& ["codex", "claude"].includes(result.provider)
|
|
115
|
+
&& typeof result.percentRemaining === "number";
|
|
116
|
+
});
|
|
117
|
+
return usageResults.length > 0 && usageResults.every((result) => result.secondary);
|
|
118
|
+
} catch {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function prefetchInitialJson(command, useWslCommand) {
|
|
124
|
+
if (process.env.AI_BATTERY_HUD_NO_PREFETCH) return null;
|
|
125
|
+
|
|
126
|
+
const attempts = 8;
|
|
127
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
128
|
+
const result = useWslCommand
|
|
129
|
+
? spawnSync("bash", ["-lc", command], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000 })
|
|
130
|
+
: spawnSync(process.execPath, [batteryJs, "--json"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000 });
|
|
131
|
+
|
|
132
|
+
const text = result.stdout?.trim();
|
|
133
|
+
if (result.status === 0 && text) {
|
|
134
|
+
if (snapshotHasWeekly(text) || attempt === attempts - 1) return text;
|
|
135
|
+
}
|
|
136
|
+
sleepSync(180);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function relevantEnvPrefix() {
|
|
143
|
+
const names = [
|
|
144
|
+
"AI_BATTERY_STATE_DIR",
|
|
145
|
+
"CLAUDEX_BATTERY_STATE_DIR",
|
|
146
|
+
"AI_BATTERY_COLUMNS",
|
|
147
|
+
"CLAUDEX_BATTERY_COLUMNS",
|
|
148
|
+
"AI_BATTERY_COLUMN_GUARD",
|
|
149
|
+
"CLAUDEX_BATTERY_COLUMN_GUARD",
|
|
150
|
+
"CODEX_HOME"
|
|
151
|
+
];
|
|
152
|
+
const pairs = [`HOME=${shellQuote(os.homedir())}`];
|
|
153
|
+
for (const name of names) {
|
|
154
|
+
if (process.env[name]) pairs.push(`${name}=${shellQuote(process.env[name])}`);
|
|
155
|
+
}
|
|
156
|
+
return pairs.join(" ");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function parseMacHudArgs(cliArgs) {
|
|
160
|
+
const options = {
|
|
161
|
+
foreground: false,
|
|
162
|
+
once: false,
|
|
163
|
+
stop: false,
|
|
164
|
+
subcommand: null,
|
|
165
|
+
autostartAction: "status",
|
|
166
|
+
interval: 10,
|
|
167
|
+
provider: "all"
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
for (let i = 0; i < cliArgs.length; i += 1) {
|
|
171
|
+
const arg = cliArgs[i];
|
|
172
|
+
if (arg === "-Foreground" || arg === "--foreground") {
|
|
173
|
+
options.foreground = true;
|
|
174
|
+
} else if (arg === "-Once" || arg === "--once") {
|
|
175
|
+
options.once = true;
|
|
176
|
+
} else if (arg === "-Stop" || arg === "--stop" || arg === "stop") {
|
|
177
|
+
options.stop = true;
|
|
178
|
+
} else if (arg === "start") {
|
|
179
|
+
// Starting is the default action.
|
|
180
|
+
} else if (arg === "status") {
|
|
181
|
+
options.subcommand = "status";
|
|
182
|
+
} else if (arg === "autostart") {
|
|
183
|
+
options.subcommand = "autostart";
|
|
184
|
+
const next = cliArgs[i + 1];
|
|
185
|
+
if (next === "on" || next === "off" || next === "status") {
|
|
186
|
+
options.autostartAction = next;
|
|
187
|
+
i += 1;
|
|
188
|
+
}
|
|
189
|
+
} else if (arg === "-Interval" || arg === "--interval") {
|
|
190
|
+
const next = cliArgs[i + 1];
|
|
191
|
+
if (next && !next.startsWith("-")) {
|
|
192
|
+
options.interval = Math.max(1, Number(next) || options.interval);
|
|
193
|
+
i += 1;
|
|
194
|
+
}
|
|
195
|
+
} else if (arg === "--provider" || arg === "-p") {
|
|
196
|
+
const next = cliArgs[i + 1];
|
|
197
|
+
if (["all", "codex", "claude"].includes(next)) {
|
|
198
|
+
options.provider = next;
|
|
199
|
+
i += 1;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return options;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function macProviderArgs(provider) {
|
|
208
|
+
return provider === "all" ? "" : ` --provider ${shellQuote(provider)}`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function macCommands(options) {
|
|
212
|
+
const node = shellQuote(process.execPath);
|
|
213
|
+
const batteryJs = shellQuote(path.join(scriptDir, "ai-battery.js"));
|
|
214
|
+
const providerArgs = macProviderArgs(options.provider);
|
|
215
|
+
const envPrefix = relevantEnvPrefix();
|
|
216
|
+
return {
|
|
217
|
+
title: `${envPrefix} ${node} ${batteryJs} --menu-bar-image${providerArgs} 2>/dev/null`,
|
|
218
|
+
detailImage: `${envPrefix} ${node} ${batteryJs} --menu-detail-image${providerArgs} 2>/dev/null`,
|
|
219
|
+
detail: `${envPrefix} ${node} ${batteryJs} --no-color${providerArgs} 2>/dev/null`
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function macHudPids() {
|
|
224
|
+
const result = spawnSync("pgrep", ["-f", macStatusPath], {
|
|
225
|
+
encoding: "utf8",
|
|
226
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
227
|
+
});
|
|
228
|
+
if (result.status !== 0) return [];
|
|
229
|
+
return (result.stdout || "")
|
|
230
|
+
.trim()
|
|
231
|
+
.split(/\s+/)
|
|
232
|
+
.map((pid) => Number(pid))
|
|
233
|
+
.filter((pid) => Number.isInteger(pid) && pid > 0 && pid !== process.pid);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function macLaunchAgentPath() {
|
|
237
|
+
return path.join(os.homedir(), "Library", "LaunchAgents", "com.ai-battery.hud.plist");
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function macLaunchctlDomain() {
|
|
241
|
+
return `gui/${typeof process.getuid === "function" ? process.getuid() : ""}`;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function xmlEscape(value) {
|
|
245
|
+
return String(value)
|
|
246
|
+
.replace(/&/g, "&")
|
|
247
|
+
.replace(/</g, "<")
|
|
248
|
+
.replace(/>/g, ">")
|
|
249
|
+
.replace(/"/g, """);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function plistString(value) {
|
|
253
|
+
return ` <string>${xmlEscape(value)}</string>`;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function macAutostartPlist(options) {
|
|
257
|
+
const args = [process.execPath, scriptPath, "start", "--interval", String(options.interval)];
|
|
258
|
+
if (options.provider !== "all") args.push("--provider", options.provider);
|
|
259
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
260
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
261
|
+
<plist version="1.0">
|
|
262
|
+
<dict>
|
|
263
|
+
<key>Label</key>
|
|
264
|
+
<string>com.ai-battery.hud</string>
|
|
265
|
+
<key>ProgramArguments</key>
|
|
266
|
+
<array>
|
|
267
|
+
${args.map(plistString).join("\n")}
|
|
268
|
+
</array>
|
|
269
|
+
<key>RunAtLoad</key>
|
|
270
|
+
<true/>
|
|
271
|
+
</dict>
|
|
272
|
+
</plist>
|
|
273
|
+
`;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function macAutostartStatus() {
|
|
277
|
+
const filePath = macLaunchAgentPath();
|
|
278
|
+
return { enabled: fs.existsSync(filePath), filePath };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function macAutostartEnable(options) {
|
|
282
|
+
const filePath = macLaunchAgentPath();
|
|
283
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
284
|
+
fs.writeFileSync(filePath, macAutostartPlist(options), "utf8");
|
|
285
|
+
spawnSync("launchctl", ["bootstrap", macLaunchctlDomain(), filePath], { stdio: "ignore" });
|
|
286
|
+
return filePath;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function macAutostartDisable() {
|
|
290
|
+
const filePath = macLaunchAgentPath();
|
|
291
|
+
spawnSync("launchctl", ["bootout", macLaunchctlDomain(), filePath], { stdio: "ignore" });
|
|
292
|
+
fs.rmSync(filePath, { force: true });
|
|
293
|
+
return filePath;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function runMacHud(cliArgs) {
|
|
297
|
+
const options = parseMacHudArgs(cliArgs);
|
|
298
|
+
const commands = macCommands(options);
|
|
299
|
+
|
|
300
|
+
if (options.once) {
|
|
301
|
+
const result = spawnSync(process.execPath, [
|
|
302
|
+
path.join(scriptDir, "ai-battery.js"),
|
|
303
|
+
"--menu-bar",
|
|
304
|
+
...(options.provider === "all" ? [] : ["--provider", options.provider])
|
|
305
|
+
], { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] });
|
|
306
|
+
if (result.stdout) process.stdout.write(result.stdout);
|
|
307
|
+
process.exit(result.status ?? 0);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
if (options.subcommand === "status") {
|
|
311
|
+
const pids = macHudPids();
|
|
312
|
+
const auto = macAutostartStatus();
|
|
313
|
+
console.log(`HUD: ${pids.length ? `running (PID ${pids[0]})` : "stopped"}`);
|
|
314
|
+
console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
|
|
315
|
+
if (auto.enabled) console.log(` ${auto.filePath}`);
|
|
316
|
+
process.exit(0);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (options.subcommand === "autostart") {
|
|
320
|
+
if (options.autostartAction === "on") {
|
|
321
|
+
console.log(`HUD autostart enabled: ${macAutostartEnable(options)}`);
|
|
322
|
+
} else if (options.autostartAction === "off") {
|
|
323
|
+
console.log(`HUD autostart disabled: ${macAutostartDisable()}`);
|
|
324
|
+
} else {
|
|
325
|
+
const auto = macAutostartStatus();
|
|
326
|
+
console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
|
|
327
|
+
if (auto.enabled) console.log(` ${auto.filePath}`);
|
|
328
|
+
}
|
|
329
|
+
process.exit(0);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (options.stop) {
|
|
333
|
+
const pids = macHudPids();
|
|
334
|
+
if (!pids.length) {
|
|
335
|
+
console.log("AI Battery menu bar is not running.");
|
|
336
|
+
process.exit(0);
|
|
337
|
+
}
|
|
338
|
+
const result = spawnSync("kill", pids.map(String), { stdio: "inherit" });
|
|
339
|
+
if ((result.status ?? 0) === 0) console.log("AI Battery menu bar stopped.");
|
|
340
|
+
process.exit(result.status ?? 0);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const existingPids = macHudPids();
|
|
344
|
+
if (existingPids.length) {
|
|
345
|
+
spawnSync("kill", existingPids.map(String), { stdio: "ignore" });
|
|
346
|
+
sleepSync(400);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const osascriptArgs = [
|
|
350
|
+
macStatusPath,
|
|
351
|
+
commands.title,
|
|
352
|
+
commands.detailImage,
|
|
353
|
+
commands.detail,
|
|
354
|
+
String(options.interval)
|
|
355
|
+
];
|
|
356
|
+
|
|
357
|
+
if (options.foreground) {
|
|
358
|
+
const result = spawnSync("osascript", osascriptArgs, { stdio: "inherit" });
|
|
359
|
+
process.exit(result.status ?? 0);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const child = spawn("osascript", osascriptArgs, {
|
|
363
|
+
detached: true,
|
|
364
|
+
stdio: "ignore"
|
|
365
|
+
});
|
|
366
|
+
child.unref();
|
|
367
|
+
console.log(`${existingPids.length ? "AI Battery menu bar restarted" : "AI Battery menu bar started"}. Click the menu bar item for details; use "ai-battery hud stop" to close it.`);
|
|
368
|
+
process.exit(0);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
if (process.platform === "darwin") {
|
|
372
|
+
runMacHud(process.argv.slice(2));
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const useWsl = isWsl();
|
|
376
|
+
const powershell = "powershell.exe";
|
|
377
|
+
|
|
378
|
+
if (!useWsl && process.platform !== "win32") {
|
|
379
|
+
console.error("ai-battery-hud: desktop HUD needs Windows (native or WSL) or macOS.");
|
|
380
|
+
console.error("On Linux terminals use: ai-battery --watch");
|
|
381
|
+
process.exit(1);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
if (!commandExists(powershell)) {
|
|
385
|
+
console.error("ai-battery-hud: powershell.exe is required for the Windows HUD.");
|
|
386
|
+
process.exit(1);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const filteredArgs = [];
|
|
390
|
+
let foreground = false;
|
|
391
|
+
let once = false;
|
|
392
|
+
let stop = false;
|
|
393
|
+
let subcommand = null;
|
|
394
|
+
let autostartAction = "status";
|
|
395
|
+
|
|
396
|
+
const cliArgs = process.argv.slice(2);
|
|
397
|
+
for (let i = 0; i < cliArgs.length; i += 1) {
|
|
398
|
+
const arg = cliArgs[i];
|
|
399
|
+
if (arg === "-Foreground" || arg === "--foreground") {
|
|
400
|
+
foreground = true;
|
|
401
|
+
} else if (arg === "-Movable" || arg === "--movable") {
|
|
402
|
+
filteredArgs.push("-Movable");
|
|
403
|
+
} else if (arg === "-Once" || arg === "--once") {
|
|
404
|
+
once = true;
|
|
405
|
+
filteredArgs.push("-Once");
|
|
406
|
+
} else if (arg === "-Stop" || arg === "--stop" || arg === "stop") {
|
|
407
|
+
stop = true;
|
|
408
|
+
filteredArgs.push("-StopExisting");
|
|
409
|
+
} else if (arg === "start") {
|
|
410
|
+
// Launching is the default action.
|
|
411
|
+
} else if (arg === "status") {
|
|
412
|
+
subcommand = "status";
|
|
413
|
+
} else if (arg === "autostart") {
|
|
414
|
+
subcommand = "autostart";
|
|
415
|
+
const next = cliArgs[i + 1];
|
|
416
|
+
if (next === "on" || next === "off" || next === "status") {
|
|
417
|
+
autostartAction = next;
|
|
418
|
+
i += 1;
|
|
419
|
+
}
|
|
420
|
+
} else {
|
|
421
|
+
filteredArgs.push(arg);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const hudScript = useWsl ? wslPath(ps1Path) : ps1Path;
|
|
426
|
+
const nodePath = process.execPath;
|
|
427
|
+
const batteryJs = path.join(scriptDir, "ai-battery.js");
|
|
428
|
+
const configuredCommand = process.env.AI_BATTERY_COMMAND || process.env.CLAUDEX_BATTERY_COMMAND;
|
|
429
429
|
const envPrefix = useWsl ? wslEnvPrefix() : "";
|
|
430
430
|
const batteryCommand = configuredCommand || (useWsl
|
|
431
431
|
? `${envPrefix ? `${envPrefix} ` : ""}HOME=${shellQuote(os.homedir())} ${shellQuote(nodePath)} ${shellQuote(batteryJs)} --json`
|
|
432
432
|
: `& ${winArgQuote(nodePath)} ${winArgQuote(batteryJs)} --json`);
|
|
433
|
-
const batteryCommandBase64 = Buffer.from(batteryCommand, "utf8").toString("base64");
|
|
434
|
-
|
|
435
|
-
const AUTOSTART_REG_PATH = "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
|
|
436
|
-
const AUTOSTART_REG_NAME = "AiBatteryHud";
|
|
437
|
-
|
|
438
|
-
function runPowerShell(command) {
|
|
439
|
-
return spawnSync(powershell, ["-NoProfile", "-Command", command], {
|
|
440
|
-
encoding: "utf8",
|
|
441
|
-
windowsHide: true
|
|
442
|
-
});
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
function hudProcessStatus() {
|
|
446
|
-
const query = "$hud = Get-CimInstance Win32_Process | Where-Object { "
|
|
447
|
-
+ "$_.ProcessId -ne $PID -and "
|
|
448
|
-
+ "$_.Name -match '^(powershell|pwsh)' -and "
|
|
449
|
-
+ "$_.CommandLine -like '*ai-battery-hud.ps1*' -and "
|
|
450
|
-
+ "$_.CommandLine -notlike '*Start-Process*' }; "
|
|
451
|
-
+ "if ($hud) { $p = @($hud)[0]; $source = if ($p.CommandLine -like '*-UseWsl*') { 'WSL' } else { 'Windows' }; 'running (' + $source + ', PID ' + $p.ProcessId + ')' } else { 'stopped' }";
|
|
452
|
-
const result = runPowerShell(query);
|
|
453
|
-
return (result.stdout || "").trim() || "unknown";
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
function autostartStatus() {
|
|
457
|
-
const result = runPowerShell(
|
|
458
|
-
`$v = (Get-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -ErrorAction SilentlyContinue).${AUTOSTART_REG_NAME}; `
|
|
459
|
-
+ "if ($v) { 'on'; $v } else { 'off' }"
|
|
460
|
-
);
|
|
461
|
-
const lines = (result.stdout || "").trim().split(/\r?\n/);
|
|
462
|
-
return { enabled: lines[0] === "on", command: lines.slice(1).join("\n") || null };
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
function autostartEnable() {
|
|
466
|
-
// autostart.ps1 refreshes the local copy of the HUD script when the source
|
|
467
|
-
// is reachable (the WSL share is not mounted until the distro starts), then
|
|
468
|
-
// launches the copy so sign-in start never depends on WSL being up. The HUD
|
|
469
|
-
// must run as a separate PowerShell process whose command line contains
|
|
470
|
-
// ai-battery-hud.ps1: stop/status and single-instance cleanup match it.
|
|
471
|
-
const autostartScript = [
|
|
472
|
-
"# Generated by: ai-battery hud autostart on",
|
|
473
|
-
`$src = ${psSingleQuote(hudScript)}`,
|
|
474
|
-
"$hud = Join-Path $PSScriptRoot 'ai-battery-hud.ps1'",
|
|
475
|
-
"try { Copy-Item $src $hud -Force -ErrorAction Stop } catch { }",
|
|
476
|
-
`$battery = ${psSingleQuote(batteryCommand)}`,
|
|
477
|
-
"$batteryB64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($battery))",
|
|
478
|
-
"$invoke = '& ' + \"'\" + ($hud -replace \"'\", \"''\") + \"'\" + ' -BatteryCommandBase64 ' + $batteryB64" + (useWsl ? " + ' -UseWsl'" : ""),
|
|
479
|
-
"$argList = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ('\"' + ($invoke -replace '\"', '\\\"') + '\"')) -join ' '",
|
|
480
|
-
"Start-Process -WindowStyle Hidden -FilePath 'powershell.exe' -ArgumentList $argList",
|
|
481
|
-
""
|
|
482
|
-
].join("\r\n");
|
|
483
|
-
const autostartB64 = Buffer.from(autostartScript, "utf8").toString("base64");
|
|
484
|
-
|
|
485
|
-
const script = [
|
|
486
|
-
"$dir = Join-Path $env:LOCALAPPDATA 'ai-battery'",
|
|
487
|
-
"New-Item -ItemType Directory -Force -Path $dir | Out-Null",
|
|
488
|
-
"$auto = Join-Path $dir 'autostart.ps1'",
|
|
489
|
-
`[System.IO.File]::WriteAllText($auto, [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${autostartB64}')))`,
|
|
490
|
-
`Copy-Item ${psSingleQuote(hudScript)} (Join-Path $dir 'ai-battery-hud.ps1') -Force`,
|
|
491
|
-
`Set-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -Value ('powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $auto + '"')`,
|
|
492
|
-
"Write-Output $auto"
|
|
493
|
-
].join("; ");
|
|
494
|
-
return runPowerShell(script);
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
function autostartDisable() {
|
|
498
|
-
return runPowerShell(
|
|
499
|
-
`Remove-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -ErrorAction SilentlyContinue`
|
|
500
|
-
);
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
if (subcommand === "status") {
|
|
504
|
-
const auto = autostartStatus();
|
|
505
|
-
console.log(`HUD: ${hudProcessStatus()}`);
|
|
506
|
-
console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
|
|
507
|
-
if (auto.command) console.log(` ${auto.command}`);
|
|
508
|
-
process.exit(0);
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
if (subcommand === "autostart") {
|
|
512
|
-
if (autostartAction === "on") {
|
|
513
|
-
const result = autostartEnable();
|
|
514
|
-
const output = (result.stdout || "").trim();
|
|
515
|
-
if (result.status !== 0 || !output) {
|
|
516
|
-
console.error("ai-battery-hud: failed to register autostart.");
|
|
517
|
-
if ((result.stderr || "").trim()) console.error((result.stderr || "").trim());
|
|
518
|
-
process.exit(1);
|
|
519
|
-
}
|
|
520
|
-
console.log("HUD autostart enabled: launches at Windows sign-in.");
|
|
521
|
-
console.log(`Launcher: ${output}`);
|
|
522
|
-
console.log("After updating ai-battery, run \"ai-battery hud autostart on\" again to refresh it.");
|
|
523
|
-
} else if (autostartAction === "off") {
|
|
524
|
-
autostartDisable();
|
|
525
|
-
console.log("HUD autostart disabled.");
|
|
526
|
-
} else {
|
|
527
|
-
const auto = autostartStatus();
|
|
528
|
-
console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
|
|
529
|
-
if (auto.command) console.log(` ${auto.command}`);
|
|
530
|
-
}
|
|
531
|
-
process.exit(0);
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
const initialJson = stop ? null : prefetchInitialJson(batteryCommand, useWsl);
|
|
535
|
-
const readyPath = (!useWsl && process.platform === "win32" && !foreground && !once && !stop)
|
|
536
|
-
? path.join(os.tmpdir(), `ai-battery-hud-ready-${process.pid}-${Date.now()}.json`)
|
|
537
|
-
: null;
|
|
538
|
-
|
|
539
|
-
const hudScriptArgs = [
|
|
540
|
-
"-BatteryCommandBase64",
|
|
541
|
-
batteryCommandBase64,
|
|
542
|
-
...filteredArgs
|
|
543
|
-
];
|
|
544
|
-
|
|
545
|
-
if (readyPath) {
|
|
546
|
-
hudScriptArgs.push("-ReadyPath", readyPath);
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
if (initialJson) {
|
|
550
|
-
hudScriptArgs.push("-InitialJsonBase64", Buffer.from(initialJson, "utf8").toString("base64"));
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
if (useWsl) {
|
|
554
|
-
hudScriptArgs.push("-UseWsl");
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
const psArgs = powerShellCommandArgs(hudScript, hudScriptArgs);
|
|
558
|
-
|
|
559
|
-
if (foreground || once || stop) {
|
|
560
|
-
const result = spawnSync(powershell, psArgs, { stdio: "inherit", windowsHide: true });
|
|
561
|
-
if (stop && (result.status ?? 0) === 0) {
|
|
562
|
-
console.log("AI Battery HUD stopped.");
|
|
563
|
-
}
|
|
564
|
-
process.exit(result.status ?? 0);
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
if (useWsl) {
|
|
568
|
-
const start = spawnSync(powershell, [
|
|
569
|
-
"-NoProfile",
|
|
570
|
-
"-ExecutionPolicy",
|
|
571
|
-
"Bypass",
|
|
572
|
-
"-Command",
|
|
573
|
-
buildStartProcessCommand("powershell.exe", psArgs)
|
|
574
|
-
], {
|
|
575
|
-
stdio: "ignore",
|
|
576
|
-
windowsHide: true
|
|
577
|
-
});
|
|
578
|
-
if (start.status !== 0) process.exit(start.status ?? 1);
|
|
579
|
-
} else {
|
|
580
|
-
const start = spawnSync(powershell, [
|
|
581
|
-
"-NoProfile",
|
|
582
|
-
"-ExecutionPolicy",
|
|
583
|
-
"Bypass",
|
|
584
|
-
"-Command",
|
|
585
|
-
buildStartProcessCommand("powershell.exe", psArgs)
|
|
586
|
-
], {
|
|
587
|
-
stdio: "ignore",
|
|
588
|
-
windowsHide: true
|
|
589
|
-
});
|
|
590
|
-
if (start.status !== 0) process.exit(start.status ?? 1);
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
if (readyPath && !waitForFile(readyPath)) {
|
|
594
|
-
console.log("AI Battery HUD start requested, but no visible window was confirmed. Run: ai-battery hud --foreground");
|
|
595
|
-
} else {
|
|
596
|
-
console.log("AI Battery HUD started. Drag it to place it; right-click and choose Exit to close.");
|
|
597
|
-
}
|
|
598
|
-
if (readyPath) fs.rmSync(readyPath, { force: true });
|
|
433
|
+
const batteryCommandBase64 = Buffer.from(batteryCommand, "utf8").toString("base64");
|
|
434
|
+
|
|
435
|
+
const AUTOSTART_REG_PATH = "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
|
|
436
|
+
const AUTOSTART_REG_NAME = "AiBatteryHud";
|
|
437
|
+
|
|
438
|
+
function runPowerShell(command) {
|
|
439
|
+
return spawnSync(powershell, ["-NoProfile", "-Command", command], {
|
|
440
|
+
encoding: "utf8",
|
|
441
|
+
windowsHide: true
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function hudProcessStatus() {
|
|
446
|
+
const query = "$hud = Get-CimInstance Win32_Process | Where-Object { "
|
|
447
|
+
+ "$_.ProcessId -ne $PID -and "
|
|
448
|
+
+ "$_.Name -match '^(powershell|pwsh)' -and "
|
|
449
|
+
+ "$_.CommandLine -like '*ai-battery-hud.ps1*' -and "
|
|
450
|
+
+ "$_.CommandLine -notlike '*Start-Process*' }; "
|
|
451
|
+
+ "if ($hud) { $p = @($hud)[0]; $source = if ($p.CommandLine -like '*-UseWsl*') { 'WSL' } else { 'Windows' }; 'running (' + $source + ', PID ' + $p.ProcessId + ')' } else { 'stopped' }";
|
|
452
|
+
const result = runPowerShell(query);
|
|
453
|
+
return (result.stdout || "").trim() || "unknown";
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function autostartStatus() {
|
|
457
|
+
const result = runPowerShell(
|
|
458
|
+
`$v = (Get-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -ErrorAction SilentlyContinue).${AUTOSTART_REG_NAME}; `
|
|
459
|
+
+ "if ($v) { 'on'; $v } else { 'off' }"
|
|
460
|
+
);
|
|
461
|
+
const lines = (result.stdout || "").trim().split(/\r?\n/);
|
|
462
|
+
return { enabled: lines[0] === "on", command: lines.slice(1).join("\n") || null };
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function autostartEnable() {
|
|
466
|
+
// autostart.ps1 refreshes the local copy of the HUD script when the source
|
|
467
|
+
// is reachable (the WSL share is not mounted until the distro starts), then
|
|
468
|
+
// launches the copy so sign-in start never depends on WSL being up. The HUD
|
|
469
|
+
// must run as a separate PowerShell process whose command line contains
|
|
470
|
+
// ai-battery-hud.ps1: stop/status and single-instance cleanup match it.
|
|
471
|
+
const autostartScript = [
|
|
472
|
+
"# Generated by: ai-battery hud autostart on",
|
|
473
|
+
`$src = ${psSingleQuote(hudScript)}`,
|
|
474
|
+
"$hud = Join-Path $PSScriptRoot 'ai-battery-hud.ps1'",
|
|
475
|
+
"try { Copy-Item $src $hud -Force -ErrorAction Stop } catch { }",
|
|
476
|
+
`$battery = ${psSingleQuote(batteryCommand)}`,
|
|
477
|
+
"$batteryB64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($battery))",
|
|
478
|
+
"$invoke = '& ' + \"'\" + ($hud -replace \"'\", \"''\") + \"'\" + ' -BatteryCommandBase64 ' + $batteryB64" + (useWsl ? " + ' -UseWsl'" : ""),
|
|
479
|
+
"$argList = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ('\"' + ($invoke -replace '\"', '\\\"') + '\"')) -join ' '",
|
|
480
|
+
"Start-Process -WindowStyle Hidden -FilePath 'powershell.exe' -ArgumentList $argList",
|
|
481
|
+
""
|
|
482
|
+
].join("\r\n");
|
|
483
|
+
const autostartB64 = Buffer.from(autostartScript, "utf8").toString("base64");
|
|
484
|
+
|
|
485
|
+
const script = [
|
|
486
|
+
"$dir = Join-Path $env:LOCALAPPDATA 'ai-battery'",
|
|
487
|
+
"New-Item -ItemType Directory -Force -Path $dir | Out-Null",
|
|
488
|
+
"$auto = Join-Path $dir 'autostart.ps1'",
|
|
489
|
+
`[System.IO.File]::WriteAllText($auto, [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${autostartB64}')))`,
|
|
490
|
+
`Copy-Item ${psSingleQuote(hudScript)} (Join-Path $dir 'ai-battery-hud.ps1') -Force`,
|
|
491
|
+
`Set-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -Value ('powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $auto + '"')`,
|
|
492
|
+
"Write-Output $auto"
|
|
493
|
+
].join("; ");
|
|
494
|
+
return runPowerShell(script);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function autostartDisable() {
|
|
498
|
+
return runPowerShell(
|
|
499
|
+
`Remove-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -ErrorAction SilentlyContinue`
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
if (subcommand === "status") {
|
|
504
|
+
const auto = autostartStatus();
|
|
505
|
+
console.log(`HUD: ${hudProcessStatus()}`);
|
|
506
|
+
console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
|
|
507
|
+
if (auto.command) console.log(` ${auto.command}`);
|
|
508
|
+
process.exit(0);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
if (subcommand === "autostart") {
|
|
512
|
+
if (autostartAction === "on") {
|
|
513
|
+
const result = autostartEnable();
|
|
514
|
+
const output = (result.stdout || "").trim();
|
|
515
|
+
if (result.status !== 0 || !output) {
|
|
516
|
+
console.error("ai-battery-hud: failed to register autostart.");
|
|
517
|
+
if ((result.stderr || "").trim()) console.error((result.stderr || "").trim());
|
|
518
|
+
process.exit(1);
|
|
519
|
+
}
|
|
520
|
+
console.log("HUD autostart enabled: launches at Windows sign-in.");
|
|
521
|
+
console.log(`Launcher: ${output}`);
|
|
522
|
+
console.log("After updating ai-battery, run \"ai-battery hud autostart on\" again to refresh it.");
|
|
523
|
+
} else if (autostartAction === "off") {
|
|
524
|
+
autostartDisable();
|
|
525
|
+
console.log("HUD autostart disabled.");
|
|
526
|
+
} else {
|
|
527
|
+
const auto = autostartStatus();
|
|
528
|
+
console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
|
|
529
|
+
if (auto.command) console.log(` ${auto.command}`);
|
|
530
|
+
}
|
|
531
|
+
process.exit(0);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const initialJson = stop ? null : prefetchInitialJson(batteryCommand, useWsl);
|
|
535
|
+
const readyPath = (!useWsl && process.platform === "win32" && !foreground && !once && !stop)
|
|
536
|
+
? path.join(os.tmpdir(), `ai-battery-hud-ready-${process.pid}-${Date.now()}.json`)
|
|
537
|
+
: null;
|
|
538
|
+
|
|
539
|
+
const hudScriptArgs = [
|
|
540
|
+
"-BatteryCommandBase64",
|
|
541
|
+
batteryCommandBase64,
|
|
542
|
+
...filteredArgs
|
|
543
|
+
];
|
|
544
|
+
|
|
545
|
+
if (readyPath) {
|
|
546
|
+
hudScriptArgs.push("-ReadyPath", readyPath);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
if (initialJson) {
|
|
550
|
+
hudScriptArgs.push("-InitialJsonBase64", Buffer.from(initialJson, "utf8").toString("base64"));
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
if (useWsl) {
|
|
554
|
+
hudScriptArgs.push("-UseWsl");
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const psArgs = powerShellCommandArgs(hudScript, hudScriptArgs);
|
|
558
|
+
|
|
559
|
+
if (foreground || once || stop) {
|
|
560
|
+
const result = spawnSync(powershell, psArgs, { stdio: "inherit", windowsHide: true });
|
|
561
|
+
if (stop && (result.status ?? 0) === 0) {
|
|
562
|
+
console.log("AI Battery HUD stopped.");
|
|
563
|
+
}
|
|
564
|
+
process.exit(result.status ?? 0);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
if (useWsl) {
|
|
568
|
+
const start = spawnSync(powershell, [
|
|
569
|
+
"-NoProfile",
|
|
570
|
+
"-ExecutionPolicy",
|
|
571
|
+
"Bypass",
|
|
572
|
+
"-Command",
|
|
573
|
+
buildStartProcessCommand("powershell.exe", psArgs)
|
|
574
|
+
], {
|
|
575
|
+
stdio: "ignore",
|
|
576
|
+
windowsHide: true
|
|
577
|
+
});
|
|
578
|
+
if (start.status !== 0) process.exit(start.status ?? 1);
|
|
579
|
+
} else {
|
|
580
|
+
const start = spawnSync(powershell, [
|
|
581
|
+
"-NoProfile",
|
|
582
|
+
"-ExecutionPolicy",
|
|
583
|
+
"Bypass",
|
|
584
|
+
"-Command",
|
|
585
|
+
buildStartProcessCommand("powershell.exe", psArgs)
|
|
586
|
+
], {
|
|
587
|
+
stdio: "ignore",
|
|
588
|
+
windowsHide: true
|
|
589
|
+
});
|
|
590
|
+
if (start.status !== 0) process.exit(start.status ?? 1);
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (readyPath && !waitForFile(readyPath)) {
|
|
594
|
+
console.log("AI Battery HUD start requested, but no visible window was confirmed. Run: ai-battery hud --foreground");
|
|
595
|
+
} else {
|
|
596
|
+
console.log("AI Battery HUD started. Drag it to place it; right-click and choose Exit to close.");
|
|
597
|
+
}
|
|
598
|
+
if (readyPath) fs.rmSync(readyPath, { force: true });
|