ai-battery 0.1.29 → 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 (50) hide show
  1. package/README.md +92 -319
  2. package/bin/ai-battery-macos-status.applescript +5 -12
  3. package/bin/ai-battery-run +708 -36
  4. package/bin/ai-battery-tmux.js +17 -0
  5. package/bin/terminal-compositor.js +111 -0
  6. package/docs/REFERENCE.md +98 -0
  7. package/docs/RELEASING.md +35 -7
  8. package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
  9. package/docs/antigravity-icon.svg +76 -0
  10. package/docs/claude-statusline-preview.svg +1 -2
  11. package/docs/hud-preview.svg +167 -0
  12. package/docs/terminal-preview.svg +54 -44
  13. package/docs/terminal-vertical-preview.svg +73 -0
  14. package/lib/cli.js +1105 -269
  15. package/lib/core/atomic-rename.js +18 -0
  16. package/lib/core/cli-help.js +69 -27
  17. package/lib/core/cli-messages.js +45 -1
  18. package/lib/core/cli-output.js +293 -68
  19. package/lib/core/cli-wrappers.js +410 -0
  20. package/lib/core/config-editor.js +283 -0
  21. package/lib/core/display-config.js +74 -0
  22. package/lib/core/integration-files.js +32 -3
  23. package/lib/core/shared-bar.js +603 -0
  24. package/lib/core/statusline-git.js +211 -0
  25. package/lib/core/terminal.js +25 -7
  26. package/lib/core/tmux-status.js +172 -0
  27. package/lib/core/uninstall.js +22 -9
  28. package/lib/core/usage-store.js +85 -0
  29. package/lib/hud/launcher.js +29 -31
  30. package/lib/platforms/linux/hud.js +4 -3
  31. package/lib/platforms/linux/panel.js +1 -1
  32. package/lib/platforms/macos/hud.js +8 -7
  33. package/lib/platforms/process-scanner.js +79 -30
  34. package/lib/platforms/ui-language.js +41 -0
  35. package/lib/platforms/windows/autostart-cleanup.js +1 -1
  36. package/lib/platforms/windows/codex-runner.js +184 -26
  37. package/lib/platforms/windows/hud/controls.ps1 +137 -81
  38. package/lib/platforms/windows/hud/main.ps1 +423 -97
  39. package/lib/platforms/windows/hud/rendering.ps1 +1232 -1
  40. package/lib/platforms/windows/hud/snapshot.ps1 +47 -44
  41. package/lib/platforms/windows/hud-launcher.js +153 -79
  42. package/lib/platforms/windows/shared-bar-platform.js +972 -0
  43. package/lib/platforms/windows/terminal-compositor.js +210 -25
  44. package/lib/platforms/windows/wt-bar.js +729 -0
  45. package/lib/platforms/windows/wt-fragment.js +665 -0
  46. package/lib/platforms/windows/wt-keybinding.js +300 -0
  47. package/lib/providers/antigravity.js +314 -0
  48. package/package.json +8 -3
  49. package/vendor/PaneContext.cs +875 -0
  50. package/lib/README.md +0 -23
@@ -0,0 +1,410 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ export const CLI_WRAPPER_MARKER = "AI_BATTERY_MANAGED_CLI_WRAPPER";
7
+ export const WRAPPED_CLI_NAMES = ["claude", "agy"];
8
+ const positionReader = fileURLToPath(new URL("../../bin/terminal-compositor.js", import.meta.url));
9
+
10
+ function shQuote(value) {
11
+ return `'${String(value).replace(/'/g, "'\\''")}'`;
12
+ }
13
+
14
+ export function isManagedCliWrapper(filePath) {
15
+ let fd;
16
+ try {
17
+ fd = fs.openSync(filePath, "r");
18
+ const buf = Buffer.alloc(512);
19
+ const len = fs.readSync(fd, buf, 0, buf.length, 0);
20
+ return buf.toString("utf8", 0, len).includes(CLI_WRAPPER_MARKER);
21
+ } catch {
22
+ return false;
23
+ } finally {
24
+ if (fd !== undefined) fs.closeSync(fd);
25
+ }
26
+ }
27
+
28
+ export function posixCliWrapperDir(homeDir = os.homedir()) {
29
+ return path.join(homeDir, ".local", "share", "ai-battery", "bin");
30
+ }
31
+
32
+ export function windowsCliWrapperDir(homeDir = os.homedir(), env = process.env) {
33
+ if (env.AI_BATTERY_DATA_DIR) return path.join(env.AI_BATTERY_DATA_DIR, "bin");
34
+ if (env.CLAUDEX_BATTERY_DATA_DIR) return path.join(env.CLAUDEX_BATTERY_DATA_DIR, "bin");
35
+ if (env.LOCALAPPDATA) return path.join(env.LOCALAPPDATA, "ai-battery", "bin");
36
+ return path.join(homeDir, ".local", "bin");
37
+ }
38
+
39
+ function buildPosixCliWrapperScript(commandName, runnerPath) {
40
+ return `#!/bin/sh
41
+ # ${CLI_WRAPPER_MARKER}=1
42
+ ai_battery_cmd_name=${shQuote(commandName)}
43
+ ai_battery_configured_runner=${shQuote(runnerPath)}
44
+ ai_battery_position_reader=${shQuote(positionReader)}
45
+ ai_battery_head=$(command -v head) || ai_battery_head=/usr/bin/head
46
+
47
+ ai_battery_is_cli_wrapper() {
48
+ ai_battery_hdr=$("$ai_battery_head" -c 256 "$1" 2>/dev/null) || return 1
49
+ case "$ai_battery_hdr" in
50
+ *${CLI_WRAPPER_MARKER}*) return 0 ;;
51
+ esac
52
+ return 1
53
+ }
54
+
55
+ ai_battery_find_real() {
56
+ ai_battery_rem=$PATH
57
+ while :; do
58
+ case "$ai_battery_rem" in
59
+ *:*)
60
+ ai_battery_dir=\${ai_battery_rem%%:*}
61
+ ai_battery_rem=\${ai_battery_rem#*:}
62
+ ai_battery_more=1 ;;
63
+ *) ai_battery_dir=$ai_battery_rem; ai_battery_more=0 ;;
64
+ esac
65
+ ai_battery_cand=\${ai_battery_dir:-.}/$1
66
+ if [ -f "$ai_battery_cand" ] && [ -x "$ai_battery_cand" ]; then
67
+ if ! ai_battery_is_cli_wrapper "$ai_battery_cand"; then
68
+ printf '%s\\n' "$ai_battery_cand"
69
+ return 0
70
+ fi
71
+ fi
72
+ [ "$ai_battery_more" = 1 ] || break
73
+ done
74
+ return 1
75
+ }
76
+
77
+ ai_battery_read_pos() {
78
+ ai_battery_node=$(command -v node 2>/dev/null) || ai_battery_node=
79
+ if [ -n "$ai_battery_node" ] && [ -f "$ai_battery_position_reader" ]; then
80
+ ai_battery_node_pos=$("$ai_battery_node" "$ai_battery_position_reader" --bar-position 2>/dev/null) || ai_battery_node_pos=
81
+ if [ -n "$ai_battery_node_pos" ]; then
82
+ printf '%s\\n' "$ai_battery_node_pos"
83
+ return 0
84
+ fi
85
+ fi
86
+ if [ -n "\${AI_BATTERY_BAR_POSITION:-}" ]; then
87
+ printf '%s\\n' "$AI_BATTERY_BAR_POSITION"
88
+ return 0
89
+ fi
90
+ ai_battery_win_dir=
91
+ if [ -f "$HOME/.local/state/ai-battery/windows-state-dir" ]; then
92
+ ai_battery_win_dir=$(cat "$HOME/.local/state/ai-battery/windows-state-dir" 2>/dev/null | tr -d '\\r\\n')
93
+ fi
94
+ for ai_battery_cfg in \\
95
+ "\${AI_BATTERY_SHARED_USAGE_STATE_DIR:+$AI_BATTERY_SHARED_USAGE_STATE_DIR/display-config.json}" \\
96
+ "\${AI_BATTERY_WINDOWS_STATE_DIR:+$AI_BATTERY_WINDOWS_STATE_DIR/display-config.json}" \\
97
+ "\${AI_BATTERY_STATE_DIR:+$AI_BATTERY_STATE_DIR/display-config.json}" \\
98
+ "\${CLAUDEX_BATTERY_STATE_DIR:+$CLAUDEX_BATTERY_STATE_DIR/display-config.json}" \\
99
+ "\${XDG_STATE_HOME:+$XDG_STATE_HOME/ai-battery/display-config.json}" \\
100
+ "\${ai_battery_win_dir:+$ai_battery_win_dir/display-config.json}" \\
101
+ "$HOME/.local/state/ai-battery/display-config.json"; do
102
+ if [ -n "$ai_battery_cfg" ] && [ -f "$ai_battery_cfg" ]; then
103
+ ai_battery_found=$(sed -n 's/.*"barPosition"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/p' "$ai_battery_cfg" 2>/dev/null | "$ai_battery_head" -n 1)
104
+ if [ -n "$ai_battery_found" ]; then
105
+ printf '%s\\n' "$ai_battery_found"
106
+ return 0
107
+ fi
108
+ fi
109
+ done
110
+ printf 'bottom\\n'
111
+ }
112
+
113
+ ai_battery_real=$(ai_battery_find_real "$ai_battery_cmd_name") || ai_battery_real=
114
+ if [ -z "$ai_battery_real" ]; then
115
+ printf '%s: command not found on PATH\\n' "$ai_battery_cmd_name" >&2
116
+ exit 127
117
+ fi
118
+
119
+ ai_battery_pos=$(ai_battery_read_pos | tr '[:upper:]' '[:lower:]')
120
+ ai_battery_runner=$ai_battery_configured_runner
121
+ if [ ! -x "$ai_battery_runner" ]; then
122
+ ai_battery_runner=$(command -v ai-battery-run 2>/dev/null) || ai_battery_runner=
123
+ fi
124
+ ai_battery_python=$(command -v python3 2>/dev/null) || ai_battery_python=
125
+
126
+ ai_battery_noninteractive=0
127
+ for ai_battery_arg in "$@"; do
128
+ case "$ai_battery_arg" in
129
+ -h|--help|-v|-V|--version|-p|--print) ai_battery_noninteractive=1; break ;;
130
+ esac
131
+ done
132
+
133
+ case "$ai_battery_pos" in
134
+ top|up|t|left|l|right|r)
135
+ if [ "$ai_battery_noninteractive" = 0 ] && [ -t 0 ] && [ -t 1 ] && [ "\${AI_BATTERY_WRAPPED_CLI:-}" != 1 ] && [ -x "$ai_battery_runner" ] && [ -n "$ai_battery_python" ]; then
136
+ ai_battery_node_bin=$(command -v node 2>/dev/null) || ai_battery_node_bin=
137
+ if [ -n "$ai_battery_node_bin" ] && [ -z "\${AI_BATTERY_NODE:-}" ]; then
138
+ export AI_BATTERY_NODE="$ai_battery_node_bin"
139
+ fi
140
+ export AI_BATTERY_WRAPPED_CLI=1
141
+ exec "$ai_battery_runner" --provider all -- "$ai_battery_real" "$@"
142
+ fi
143
+ ;;
144
+ esac
145
+
146
+ exec "$ai_battery_real" "$@"
147
+ `;
148
+ }
149
+
150
+ function buildWindowsCliCmd(nodePath) {
151
+ return [
152
+ "@echo off",
153
+ `rem ${CLI_WRAPPER_MARKER}=1`,
154
+ "setlocal EnableExtensions DisableDelayedExpansion",
155
+ `set "_ai_battery_node=${nodePath}"`,
156
+ 'if not exist "%_ai_battery_node%" set "_ai_battery_node=node"',
157
+ '"%_ai_battery_node%" "%~f0.ai-battery.cjs" %*',
158
+ "exit /b %ERRORLEVEL%"
159
+ ].join("\r\n") + "\r\n";
160
+ }
161
+
162
+ function buildWindowsCliBridge(commandName, runnerPath) {
163
+ return `// ${CLI_WRAPPER_MARKER}=1
164
+ const fs = require("node:fs");
165
+ const os = require("node:os");
166
+ const path = require("node:path");
167
+ const { spawn } = require("node:child_process");
168
+ const { spawnSync } = require("node:child_process");
169
+
170
+ const CMD_NAME = ${JSON.stringify(commandName)};
171
+ const RUNNER = ${JSON.stringify(runnerPath)};
172
+ const POSITION_READER = ${JSON.stringify(positionReader)};
173
+ const MARKER = ${JSON.stringify(CLI_WRAPPER_MARKER)};
174
+
175
+ function windowsCommandNames(command, env = process.env) {
176
+ const extensions = (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
177
+ return [...extensions.map((ext) => command + ext.toLowerCase()), command];
178
+ }
179
+
180
+ function isManaged(file) {
181
+ let fd;
182
+ try {
183
+ fd = fs.openSync(file, "r");
184
+ const header = Buffer.alloc(512);
185
+ const count = fs.readSync(fd, header, 0, header.length, 0);
186
+ return header.toString("utf8", 0, count).includes(MARKER);
187
+ } catch {
188
+ return false;
189
+ } finally {
190
+ if (fd !== undefined) fs.closeSync(fd);
191
+ }
192
+ }
193
+
194
+ function findRealCommand(command, env = process.env) {
195
+ for (const entry of (env.PATH || "").split(path.delimiter)) {
196
+ const dir = entry.replace(/^"(.*)"$/, "$1");
197
+ if (!dir) continue;
198
+ for (const name of windowsCommandNames(command, env)) {
199
+ const candidate = path.resolve(dir, name);
200
+ try {
201
+ if (!fs.statSync(candidate).isFile()) continue;
202
+ if (isManaged(candidate)) continue;
203
+ return candidate;
204
+ } catch {}
205
+ }
206
+ }
207
+ return null;
208
+ }
209
+
210
+ function readBarPosition(env = process.env) {
211
+ if (fs.existsSync(POSITION_READER)) {
212
+ const result = spawnSync(process.execPath, [POSITION_READER, "--bar-position"], {
213
+ env, encoding: "utf8", windowsHide: true, timeout: 5000
214
+ });
215
+ if (result.status === 0 && result.stdout.trim()) return result.stdout.trim();
216
+ }
217
+ const override = String(env.AI_BATTERY_BAR_POSITION || "").trim().toLowerCase();
218
+ if (override) return override;
219
+ const dirs = [
220
+ env.AI_BATTERY_SHARED_USAGE_STATE_DIR,
221
+ env.AI_BATTERY_STATE_DIR,
222
+ env.CLAUDEX_BATTERY_STATE_DIR,
223
+ env.XDG_STATE_HOME ? path.join(env.XDG_STATE_HOME, "ai-battery") : "",
224
+ path.join(os.homedir(), ".local", "state", "ai-battery")
225
+ ].filter(Boolean);
226
+ for (const dir of dirs) {
227
+ try {
228
+ const text = fs.readFileSync(path.join(dir, "display-config.json"), "utf8").replace(/^\\uFEFF/, "");
229
+ const parsed = JSON.parse(text);
230
+ const pos = String(parsed?.barPosition || "").trim().toLowerCase();
231
+ if (pos) return pos;
232
+ } catch {}
233
+ }
234
+ return "bottom";
235
+ }
236
+
237
+ function resolveNpmCmdShim(commandPath) {
238
+ if (!/\\.cmd$/i.test(commandPath)) return null;
239
+ let source;
240
+ try { source = fs.readFileSync(commandPath, "utf8"); } catch { return null; }
241
+ if (!source.includes("%dp0%") || !source.includes("%*")) return null;
242
+ const match = source.match(/%dp0%[\\\\/]([^"\\r\\n]+?\\.(?:cjs|mjs|js))"?\\s+%\\*/i);
243
+ if (!match) return null;
244
+ const scriptPath = path.resolve(path.dirname(commandPath), match[1].replace(/[\\\\/]+/g, path.sep));
245
+ if (!fs.existsSync(scriptPath)) return null;
246
+ const localNode = path.join(path.dirname(commandPath), "node.exe");
247
+ return { file: fs.existsSync(localNode) ? localNode : process.execPath, scriptPath };
248
+ }
249
+
250
+ const UNSAFE_CMD_ARGUMENT_RE = /[\\r\\n&|<>^%!()]/;
251
+ const UNSAFE_CMD_PATH_RE = /[\\r\\n&|<>^%!]/;
252
+
253
+ function directLaunch(exe, rest) {
254
+ if (/\\.(cmd|bat)$/i.test(exe)) {
255
+ const shim = resolveNpmCmdShim(exe);
256
+ if (shim) return { file: shim.file, args: [shim.scriptPath, ...rest] };
257
+ if (UNSAFE_CMD_PATH_RE.test(String(exe)) || rest.some((arg) => UNSAFE_CMD_ARGUMENT_RE.test(String(arg)))) {
258
+ throw new Error("Cannot safely pass shell metacharacters through batch command " + exe);
259
+ }
260
+ return { file: "cmd.exe", args: ["/d", "/s", "/c", "call", exe, ...rest] };
261
+ }
262
+ if (/\\.ps1$/i.test(exe)) {
263
+ return { file: "powershell.exe", args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", exe, ...rest] };
264
+ }
265
+ if (/\\.(js|mjs|cjs)$/i.test(exe)) {
266
+ return { file: process.execPath, args: [exe, ...rest] };
267
+ }
268
+ return { file: exe, args: rest };
269
+ }
270
+
271
+ const real = findRealCommand(CMD_NAME);
272
+ if (!real) {
273
+ console.error(CMD_NAME + ": command not found on PATH");
274
+ process.exit(127);
275
+ }
276
+
277
+ const pos = readBarPosition();
278
+ const wantsSideOrTop = ["top", "up", "t", "left", "l", "right", "r"].includes(pos);
279
+ const cliArgs = process.argv.slice(2);
280
+ const nonInteractive = cliArgs.some((arg) => ["-h", "--help", "-v", "-V", "--version", "-p", "--print"].includes(arg));
281
+ const env = { ...process.env };
282
+ let launch;
283
+ if (wantsSideOrTop && !nonInteractive && process.stdin.isTTY && process.stdout.isTTY && env.AI_BATTERY_WRAPPED_CLI !== "1" && fs.existsSync(RUNNER)) {
284
+ env.AI_BATTERY_WRAPPED_CLI = "1";
285
+ launch = { file: process.execPath, args: [RUNNER, "--provider", "all", "--left-padding", "2", "--", real, ...cliArgs] };
286
+ } else {
287
+ launch = directLaunch(real, cliArgs);
288
+ }
289
+
290
+ const child = spawn(launch.file, launch.args, { stdio: "inherit", env });
291
+ child.on("error", (error) => {
292
+ console.error(CMD_NAME + ": " + error.message);
293
+ process.exit(1);
294
+ });
295
+ child.on("exit", (code, signal) => {
296
+ if (signal) process.kill(process.pid, signal);
297
+ process.exit(code ?? 0);
298
+ });
299
+ `;
300
+ }
301
+
302
+ function writeManagedFile(filePath, content, executable = false) {
303
+ if (fs.existsSync(filePath) && !isManagedCliWrapper(filePath)) {
304
+ return { skipped: true, path: filePath };
305
+ }
306
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
307
+ const tmp = `${filePath}.${process.pid}.tmp`;
308
+ fs.writeFileSync(tmp, content, "utf8");
309
+ if (executable && process.platform !== "win32") {
310
+ fs.chmodSync(tmp, 0o755);
311
+ }
312
+ fs.renameSync(tmp, filePath);
313
+ return { installed: true, path: filePath };
314
+ }
315
+
316
+ export function installCliPositionWrappers({
317
+ names = WRAPPED_CLI_NAMES,
318
+ runnerPath,
319
+ homeDir = os.homedir(),
320
+ platform = process.platform,
321
+ nodePath = process.execPath,
322
+ windowsDir = null,
323
+ env = process.env
324
+ } = {}) {
325
+ if (!runnerPath) return { installed: [], skipped: [] };
326
+ const installed = [];
327
+ const skipped = [];
328
+
329
+ if (platform === "win32") {
330
+ const dir = windowsDir || windowsCliWrapperDir(homeDir, env);
331
+ const legacyDir = path.join(homeDir, ".local", "bin");
332
+ const sameAsLegacy = path.resolve(dir).toLowerCase() === path.resolve(legacyDir).toLowerCase();
333
+ for (const name of names) {
334
+ const cmdPath = path.join(dir, `${name}.cmd`);
335
+ const bridgePath = `${cmdPath}.ai-battery.cjs`;
336
+ const cmdRes = writeManagedFile(cmdPath, buildWindowsCliCmd(nodePath), false);
337
+ if (cmdRes.skipped) {
338
+ skipped.push(cmdPath);
339
+ continue;
340
+ }
341
+ writeManagedFile(bridgePath, buildWindowsCliBridge(name, runnerPath), false);
342
+ installed.push(cmdPath);
343
+ // Clean up legacy managed wrappers in ~/.local/bin after migrating to dedicated bin dir
344
+ // so old shims cannot shadow or conflict with native ~/.local/bin/claude.exe.
345
+ if (!sameAsLegacy) {
346
+ for (const oldFile of [path.join(legacyDir, `${name}.cmd`), path.join(legacyDir, `${name}.cmd.ai-battery.cjs`)]) {
347
+ if (fs.existsSync(oldFile) && isManagedCliWrapper(oldFile)) {
348
+ try { fs.unlinkSync(oldFile); } catch {}
349
+ }
350
+ }
351
+ }
352
+ }
353
+ return { dir, installed, skipped };
354
+ }
355
+
356
+ const dedicatedDir = posixCliWrapperDir(homeDir);
357
+ const localBinDir = path.join(homeDir, ".local", "bin");
358
+ for (const name of names) {
359
+ const content = buildPosixCliWrapperScript(name, runnerPath);
360
+ const primary = writeManagedFile(path.join(dedicatedDir, name), content, true);
361
+ if (primary.installed) installed.push(primary.path);
362
+ else skipped.push(primary.path);
363
+ // Also place in ~/.local/bin if unoccupied (e.g. claude) so already-open shells pick it up immediately.
364
+ const secondaryPath = path.join(localBinDir, name);
365
+ if (!fs.existsSync(secondaryPath) || isManagedCliWrapper(secondaryPath)) {
366
+ const secondary = writeManagedFile(secondaryPath, content, true);
367
+ if (secondary.installed) installed.push(secondary.path);
368
+ }
369
+ }
370
+ return { dir: dedicatedDir, installed, skipped };
371
+ }
372
+
373
+ export function uninstallCliPositionWrappers({
374
+ names = WRAPPED_CLI_NAMES,
375
+ homeDir = os.homedir(),
376
+ platform = process.platform,
377
+ windowsDir = null,
378
+ env = process.env
379
+ } = {}) {
380
+ const removed = [];
381
+ const removeIfManaged = (filePath) => {
382
+ if (fs.existsSync(filePath) && isManagedCliWrapper(filePath)) {
383
+ try {
384
+ fs.unlinkSync(filePath);
385
+ removed.push(filePath);
386
+ } catch {}
387
+ }
388
+ };
389
+ if (platform === "win32") {
390
+ const dirs = [...new Set([
391
+ windowsDir,
392
+ windowsCliWrapperDir(homeDir, env),
393
+ path.join(homeDir, ".local", "bin")
394
+ ].filter(Boolean).map(d => path.resolve(d)))];
395
+ for (const dir of dirs) {
396
+ for (const name of names) {
397
+ const cmdPath = path.join(dir, `${name}.cmd`);
398
+ removeIfManaged(cmdPath);
399
+ removeIfManaged(`${cmdPath}.ai-battery.cjs`);
400
+ }
401
+ }
402
+ return { removed };
403
+ }
404
+ for (const dir of [posixCliWrapperDir(homeDir), path.join(homeDir, ".local", "bin")]) {
405
+ for (const name of names) {
406
+ removeIfManaged(path.join(dir, name));
407
+ }
408
+ }
409
+ return { removed };
410
+ }