ai-battery 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +30 -14
  2. package/bin/ai-battery-macos-status.applescript +5 -12
  3. package/bin/ai-battery-run +701 -31
  4. package/bin/ai-battery-tmux.js +17 -0
  5. package/bin/terminal-compositor.js +111 -0
  6. package/docs/REFERENCE.md +23 -3
  7. package/docs/RELEASING.md +24 -7
  8. package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
  9. package/docs/hud-preview.svg +43 -20
  10. package/docs/terminal-vertical-preview.svg +73 -0
  11. package/lib/cli.js +945 -219
  12. package/lib/core/atomic-rename.js +18 -0
  13. package/lib/core/cli-help.js +35 -7
  14. package/lib/core/cli-messages.js +45 -1
  15. package/lib/core/cli-output.js +277 -72
  16. package/lib/core/cli-wrappers.js +410 -0
  17. package/lib/core/config-editor.js +177 -29
  18. package/lib/core/display-config.js +45 -0
  19. package/lib/core/integration-files.js +32 -3
  20. package/lib/core/shared-bar.js +603 -0
  21. package/lib/core/statusline-git.js +179 -15
  22. package/lib/core/terminal.js +25 -7
  23. package/lib/core/tmux-status.js +172 -0
  24. package/lib/core/uninstall.js +20 -7
  25. package/lib/core/usage-store.js +85 -0
  26. package/lib/hud/launcher.js +29 -31
  27. package/lib/platforms/linux/hud.js +1 -1
  28. package/lib/platforms/linux/panel.js +1 -1
  29. package/lib/platforms/macos/hud.js +5 -5
  30. package/lib/platforms/process-scanner.js +77 -29
  31. package/lib/platforms/windows/autostart-cleanup.js +1 -1
  32. package/lib/platforms/windows/codex-runner.js +178 -21
  33. package/lib/platforms/windows/hud/controls.ps1 +44 -10
  34. package/lib/platforms/windows/hud/main.ps1 +350 -43
  35. package/lib/platforms/windows/hud/rendering.ps1 +1227 -1
  36. package/lib/platforms/windows/hud/snapshot.ps1 +26 -46
  37. package/lib/platforms/windows/hud-launcher.js +153 -79
  38. package/lib/platforms/windows/shared-bar-platform.js +972 -0
  39. package/lib/platforms/windows/terminal-compositor.js +210 -25
  40. package/lib/platforms/windows/wt-bar.js +729 -0
  41. package/lib/platforms/windows/wt-fragment.js +665 -0
  42. package/lib/platforms/windows/wt-keybinding.js +300 -0
  43. package/lib/providers/antigravity.js +155 -8
  44. package/package.json +5 -2
  45. package/vendor/PaneContext.cs +875 -0
@@ -0,0 +1,665 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import crypto from "node:crypto";
5
+ import { spawnSync } from "node:child_process";
6
+ import { atomicRename } from "../../core/atomic-rename.js";
7
+ import { DEFAULT_SIDEBAR_WIDTH, normalizeBarPosition, normalizeSidebarWidth } from "../../core/display-config.js";
8
+ import { isWsl } from "../runtime.js";
9
+ import { ensureTriggerBinding, readTriggerBinding, removeTriggerBinding } from "./wt-keybinding.js";
10
+ export { TRIGGER_KEY_CANDIDATES } from "./wt-keybinding.js";
11
+
12
+ export const WT_BAR_PROFILE_NAME = "AI Battery Bar";
13
+ export const WT_BAR_PROFILE_GUID = "{a1b277e4-ba77-4e91-8c3d-a1ba77e40001}";
14
+ export const WT_ATTACH_ACTION_ID = "AiBattery.AttachBar";
15
+ export const WT_FRAGMENT_DIR_NAME = "ai-battery";
16
+ export const WT_FRAGMENT_FILE_NAME = "bar.json";
17
+
18
+ let wslLocalAppDataMemo;
19
+
20
+ function wslLocalStateDir(env = process.env) {
21
+ if (env.AI_BATTERY_STATE_DIR) return env.AI_BATTERY_STATE_DIR;
22
+ if (env.CLAUDEX_BATTERY_STATE_DIR) return env.CLAUDEX_BATTERY_STATE_DIR;
23
+ if (env.XDG_STATE_HOME) return path.join(env.XDG_STATE_HOME, "ai-battery");
24
+ const home = String(env.HOME || "").trim() || os.homedir();
25
+ return path.join(home, ".local", "state", "ai-battery");
26
+ }
27
+
28
+ function hasCustomXdgStateHome(env = process.env) {
29
+ const xdg = String(env.XDG_STATE_HOME || "").trim();
30
+ if (!xdg) return false;
31
+ const home = String(env.HOME || "").trim() || os.homedir();
32
+ return path.resolve(xdg) !== path.resolve(home, ".local", "state");
33
+ }
34
+
35
+ function normalizeWslWindowsPath(rawPath, platform = process.platform) {
36
+ const text = String(rawPath || "").trim();
37
+ if (!text) return "";
38
+ if (platform === "win32" || !isWsl()) return text;
39
+ if (/^[A-Za-z]:[\\/]/.test(text)) {
40
+ const conv = spawnSync("wslpath", ["-u", text], {
41
+ encoding: "utf8",
42
+ stdio: ["ignore", "pipe", "ignore"],
43
+ timeout: 2000
44
+ });
45
+ const unixPath = String(conv.stdout || "").trim();
46
+ if (conv.status === 0 && unixPath.startsWith("/")) return unixPath;
47
+ const drive = text[0].toLowerCase();
48
+ return `/mnt/${drive}/${text.slice(3).replace(/\\/g, "/")}`;
49
+ }
50
+ return text;
51
+ }
52
+
53
+ export function resolveWindowsLocalAppData(env = process.env, { platform = process.platform } = {}) {
54
+ const direct = normalizeWslWindowsPath(env.LOCALAPPDATA, platform);
55
+ if (direct) return direct;
56
+ if (platform === "win32" || !isWsl()) return null;
57
+ const override = normalizeWslWindowsPath(env.AI_BATTERY_WINDOWS_LOCALAPPDATA, platform);
58
+ if (override) return override;
59
+ if (env.AI_BATTERY_STATE_DIR || env.CLAUDEX_BATTERY_STATE_DIR || env.AI_BATTERY_DATA_DIR || hasCustomXdgStateHome(env)) return null;
60
+ if (wslLocalAppDataMemo !== undefined) return wslLocalAppDataMemo;
61
+
62
+ const cacheFile = path.join(wslLocalStateDir(env), "windows-localappdata");
63
+ try {
64
+ const cached = fs.readFileSync(cacheFile, "utf8").trim();
65
+ if (cached && fs.existsSync(cached)) {
66
+ wslLocalAppDataMemo = cached;
67
+ return cached;
68
+ }
69
+ } catch { /* Cache miss. */ }
70
+
71
+ let resolved = null;
72
+ try {
73
+ const cmdExe = fs.existsSync("/mnt/c/Windows/System32/cmd.exe") ? "/mnt/c/Windows/System32/cmd.exe" : "cmd.exe";
74
+ const out = spawnSync(cmdExe, ["/c", "echo %LOCALAPPDATA%"], {
75
+ encoding: "utf8",
76
+ stdio: ["ignore", "pipe", "ignore"],
77
+ timeout: 2000
78
+ });
79
+ const winPath = String(out.stdout || "").trim();
80
+ if (out.status === 0 && /^[A-Za-z]:\\/.test(winPath)) {
81
+ const conv = spawnSync("wslpath", ["-u", winPath], {
82
+ encoding: "utf8",
83
+ stdio: ["ignore", "pipe", "ignore"],
84
+ timeout: 2000
85
+ });
86
+ const unixPath = String(conv.stdout || "").trim();
87
+ if (conv.status === 0 && unixPath.startsWith("/")) resolved = unixPath;
88
+ }
89
+ } catch { /* WSL interop unavailable. */ }
90
+
91
+ if (resolved) {
92
+ try {
93
+ fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
94
+ fs.writeFileSync(cacheFile, `${resolved}\n`);
95
+ } catch { /* Best-effort cache write. */ }
96
+ }
97
+ wslLocalAppDataMemo = resolved;
98
+ return resolved;
99
+ }
100
+
101
+ export function wtFragmentPath(env = process.env) {
102
+ const localAppData = resolveWindowsLocalAppData(env);
103
+ if (!localAppData) return null;
104
+ return path.join(
105
+ localAppData,
106
+ "Microsoft",
107
+ "Windows Terminal",
108
+ "Fragments",
109
+ WT_FRAGMENT_DIR_NAME,
110
+ WT_FRAGMENT_FILE_NAME
111
+ );
112
+ }
113
+
114
+ export function candidateWtSettingsPaths(env = process.env) {
115
+ const localAppData = resolveWindowsLocalAppData(env);
116
+ if (!localAppData) return [];
117
+ return [
118
+ path.join(localAppData, "Packages", "Microsoft.WindowsTerminal_8wekyb3d8bbwe", "LocalState", "settings.json"),
119
+ path.join(localAppData, "Packages", "Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe", "LocalState", "settings.json"),
120
+ path.join(localAppData, "Microsoft", "Windows Terminal", "settings.json")
121
+ ];
122
+ }
123
+
124
+ export function findWtSettingsPath(env = process.env) {
125
+ for (const candidate of candidateWtSettingsPaths(env)) {
126
+ try {
127
+ if (fs.existsSync(candidate)) return candidate;
128
+ } catch { /* Continue checking other WT channels. */ }
129
+ }
130
+ return null;
131
+ }
132
+
133
+ export function ensureWtTriggerKeybinding(settingsPath) { return ensureTriggerBinding(settingsPath, WT_ATTACH_ACTION_ID); }
134
+ export function removeWtTriggerKeybinding(settingsPath) { return removeTriggerBinding(settingsPath, WT_ATTACH_ACTION_ID); }
135
+ export function readWtTriggerKeybinding(env = process.env) { return readTriggerBinding(findWtSettingsPath(env), WT_ATTACH_ACTION_ID); }
136
+
137
+ function stripJsonComments(text) {
138
+ let result = "";
139
+ let inString = false;
140
+ let escaped = false;
141
+ for (let i = 0; i < text.length; i += 1) {
142
+ const ch = text[i];
143
+ const next = text[i + 1];
144
+ if (inString) {
145
+ result += ch;
146
+ if (escaped) escaped = false;
147
+ else if (ch === "\\") escaped = true;
148
+ else if (ch === "\"") inString = false;
149
+ continue;
150
+ }
151
+ if (ch === "\"") {
152
+ inString = true;
153
+ result += ch;
154
+ } else if (ch === "/" && next === "/") {
155
+ while (i < text.length && text[i] !== "\n") i += 1;
156
+ if (i < text.length) result += "\n";
157
+ } else if (ch === "/" && next === "*") {
158
+ i += 2;
159
+ while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) i += 1;
160
+ i += 1;
161
+ } else {
162
+ result += ch;
163
+ }
164
+ }
165
+ // Remove trailing commas only outside strings (paths may contain ",}").
166
+ let clean = "";
167
+ inString = false; escaped = false;
168
+ for (let i = 0; i < result.length; i += 1) {
169
+ const ch = result[i];
170
+ if (inString) {
171
+ clean += ch;
172
+ if (escaped) escaped = false;
173
+ else if (ch === "\\") escaped = true;
174
+ else if (ch === '\"') inString = false;
175
+ } else {
176
+ if (ch === '\"') inString = true;
177
+ if (ch === "," && /^\s*[}\]]/.test(result.slice(i + 1))) continue;
178
+ clean += ch;
179
+ }
180
+ }
181
+ return clean;
182
+ }
183
+
184
+ const BUILTIN_WT_SCHEMES = {
185
+ "campbell": { background: "#0C0C0C", foreground: "#CCCCCC" },
186
+ "campbell powershell": { background: "#012456", foreground: "#CCCCCC" },
187
+ "dark+": { background: "#1E1E1E", foreground: "#CCCCCC" },
188
+ "ubuntu": { background: "#300A24", foreground: "#FFFFFF" },
189
+ "one half dark": { background: "#282C34", foreground: "#DCDFE4" },
190
+ "one half light": { background: "#FAFAFA", foreground: "#383A42" },
191
+ "tango dark": { background: "#000000", foreground: "#D3D7CF" },
192
+ "tango light": { background: "#FFFFFF", foreground: "#555753" },
193
+ "solarized dark": { background: "#002B36", foreground: "#839496" },
194
+ "solarized light": { background: "#FDF6E3", foreground: "#657B83" },
195
+ "vintage": { background: "#000000", foreground: "#C0C0C0" },
196
+ "frost": { background: "#FFFFFF", foreground: "#000000" }
197
+ };
198
+
199
+ function normalizeHexColor(value) {
200
+ const text = String(value || "").trim();
201
+ if (/^#[0-9a-f]{6}$/i.test(text)) return text.toUpperCase();
202
+ if (/^#[0-9a-f]{3}$/i.test(text)) {
203
+ const [r, g, b] = text.slice(1).toUpperCase().split("");
204
+ return `#${r}${r}${g}${g}${b}${b}`;
205
+ }
206
+ if (/^#[0-9a-f]{8}$/i.test(text)) {
207
+ return `#${text.slice(3).toUpperCase()}`;
208
+ }
209
+ return null;
210
+ }
211
+
212
+ function resolveProfileColorPair(profile, schemes) {
213
+ if (!profile || typeof profile !== "object") return null;
214
+ const schemeName = typeof profile.colorScheme === "string"
215
+ ? profile.colorScheme
216
+ : (typeof profile.colorScheme?.dark === "string"
217
+ ? profile.colorScheme.dark
218
+ : (typeof profile.colorScheme?.light === "string" ? profile.colorScheme.light : ""));
219
+ const scheme = schemeName ? schemes.get(schemeName.toLowerCase()) : null;
220
+ const background = normalizeHexColor(profile.background) || normalizeHexColor(scheme?.background);
221
+ const foreground = normalizeHexColor(profile.foreground) || normalizeHexColor(scheme?.foreground);
222
+ if (!background && !foreground) return null;
223
+ return { background, foreground };
224
+ }
225
+
226
+ // Read all WT profile + fragment color schemes (including Microsoft.WSL Ubuntu
227
+ // purple #300A24) so the shared bar can dynamically match the active tab theme.
228
+ export function readWtProfileColorMap(env = process.env) {
229
+ const schemes = new Map(Object.entries(BUILTIN_WT_SCHEMES));
230
+ const rawProfilesByGuid = new Map();
231
+ const byDistro = new Map();
232
+
233
+ const ingestFile = (filePath) => {
234
+ try {
235
+ const raw = fs.readFileSync(filePath, "utf8").replace(/^\uFEFF/, "");
236
+ const parsed = JSON.parse(stripJsonComments(raw));
237
+ if (Array.isArray(parsed?.schemes)) {
238
+ for (const scheme of parsed.schemes) {
239
+ if (scheme?.name) {
240
+ schemes.set(String(scheme.name).toLowerCase(), {
241
+ background: normalizeHexColor(scheme.background),
242
+ foreground: normalizeHexColor(scheme.foreground)
243
+ });
244
+ }
245
+ }
246
+ }
247
+ const list = Array.isArray(parsed?.profiles)
248
+ ? parsed.profiles
249
+ : (Array.isArray(parsed?.profiles?.list) ? parsed.profiles.list : []);
250
+ for (const item of list) {
251
+ if (!item || typeof item !== "object") continue;
252
+ const guid = String(item.guid || "").toLowerCase();
253
+ if (guid) {
254
+ rawProfilesByGuid.set(guid, { ...(rawProfilesByGuid.get(guid) || {}), ...item });
255
+ }
256
+ }
257
+ return parsed;
258
+ } catch {
259
+ return null;
260
+ }
261
+ };
262
+
263
+ const fragmentRoots = [];
264
+ const localAppData = resolveWindowsLocalAppData(env);
265
+ if (localAppData) {
266
+ fragmentRoots.push(path.join(localAppData, "Microsoft", "Windows Terminal", "Fragments"));
267
+ }
268
+ const programData = process.platform === "win32"
269
+ ? String(env.PROGRAMDATA || "C:\\ProgramData").trim()
270
+ : (isWsl() && !env.LOCALAPPDATA && fs.existsSync("/mnt/c/ProgramData") ? "/mnt/c/ProgramData" : "");
271
+ if (programData) {
272
+ fragmentRoots.push(path.join(programData, "Microsoft", "Windows Terminal", "Fragments"));
273
+ }
274
+ for (const fragmentsRoot of fragmentRoots) {
275
+ try {
276
+ for (const dirEntry of fs.readdirSync(fragmentsRoot, { withFileTypes: true })) {
277
+ if (!dirEntry.isDirectory() || dirEntry.name === WT_FRAGMENT_DIR_NAME) continue;
278
+ const subDir = path.join(fragmentsRoot, dirEntry.name);
279
+ try {
280
+ for (const fileEntry of fs.readdirSync(subDir, { withFileTypes: true })) {
281
+ if (fileEntry.isFile() && fileEntry.name.toLowerCase().endsWith(".json")) {
282
+ ingestFile(path.join(subDir, fileEntry.name));
283
+ }
284
+ }
285
+ } catch { /* Skip unreadable fragment subfolder. */ }
286
+ }
287
+ } catch { /* No fragments directory. */ }
288
+ }
289
+
290
+ const settingsPath = findWtSettingsPath(env);
291
+ const settings = settingsPath ? ingestFile(settingsPath) : null;
292
+ const inherited = settings?.profiles?.defaults || {};
293
+ const fallbackColors = resolveProfileColorPair(inherited, schemes) || BUILTIN_WT_SCHEMES.campbell;
294
+ const byGuid = new Map();
295
+
296
+ for (const [guid, item] of rawProfilesByGuid.entries()) {
297
+ const merged = { ...inherited, ...item };
298
+ const explicitColors = resolveProfileColorPair(merged, schemes);
299
+ const colors = explicitColors || fallbackColors;
300
+ byGuid.set(guid, colors);
301
+ if (explicitColors) {
302
+ const nameKey = String(merged.name || "").trim().toLowerCase();
303
+ if (nameKey) byDistro.set(nameKey, explicitColors);
304
+ const distroType = String(merged["wsl.distribution-type"] || "").trim().toLowerCase();
305
+ if (distroType && !byDistro.has(distroType)) byDistro.set(distroType, explicitColors);
306
+ }
307
+ }
308
+
309
+ const defaultGuid = String(settings?.defaultProfile || "").toLowerCase();
310
+ const defaultColors = (defaultGuid && byGuid.get(defaultGuid)) || fallbackColors;
311
+
312
+ return { byGuid, byDistro, defaultColors };
313
+ }
314
+
315
+ // Read-only appearance mirror from the user's default WT profile so the hidden
316
+ // bar pane matches their exact terminal theme, font face, opacity and acrylic.
317
+ export function readDefaultProfileAppearance(settingsPath) {
318
+ if (!settingsPath) return {};
319
+ try {
320
+ const raw = fs.readFileSync(settingsPath, "utf8").replace(/^\uFEFF/, "");
321
+ const parsed = JSON.parse(stripJsonComments(raw));
322
+ const list = Array.isArray(parsed?.profiles?.list) ? parsed.profiles.list : [];
323
+ const defaultGuid = String(parsed?.defaultProfile || "").toLowerCase();
324
+ const target = list.find(item => String(item?.guid || "").toLowerCase() === defaultGuid);
325
+ const inherited = parsed?.profiles?.defaults || {};
326
+ const profile = { ...inherited, ...target, font: { ...inherited.font, ...target?.font } };
327
+ const mirrored = {};
328
+ for (const key of ["colorScheme", "background", "foreground", "opacity", "useAcrylic"]) {
329
+ if (profile[key] !== undefined) mirrored[key] = profile[key];
330
+ }
331
+ if (profile.font && typeof profile.font === "object") {
332
+ if (typeof profile.font.face === "string") mirrored.fontFace = profile.font.face;
333
+ if (typeof profile.font.size === "number") mirrored.fontSize = profile.font.size;
334
+ }
335
+ return mirrored;
336
+ } catch {
337
+ return {};
338
+ }
339
+ }
340
+
341
+ function quoteWinArg(value) {
342
+ const text = String(value ?? "");
343
+ if (text.length && !/[ \t"]/.test(text)) return text;
344
+ return `"${text.replace(/(\\*)"/g, "$1$1\\\"").replace(/(\\+)$/, "$1$1")}"`;
345
+ }
346
+
347
+ export function buildWtFragment({
348
+ nodePath,
349
+ cliPath,
350
+ appearance = {},
351
+ barFontSize = null,
352
+ position = "bottom",
353
+ sidebarWidth = DEFAULT_SIDEBAR_WIDTH,
354
+ windowClientWidth = null,
355
+ windowDpi = 96,
356
+ splitSize = null,
357
+ resizeSteps = null
358
+ }) {
359
+ const normalizedPos = normalizeBarPosition(position, "bottom");
360
+ const normalizedSidebarWidth = normalizeSidebarWidth(sidebarWidth, DEFAULT_SIDEBAR_WIDTH);
361
+ const splitDirection = normalizedPos === "top" ? "up"
362
+ : normalizedPos === "left" ? "left"
363
+ : normalizedPos === "right" ? "right"
364
+ : "down";
365
+ const returnFocusDirection = normalizedPos === "top" ? "down"
366
+ : normalizedPos === "left" ? "right"
367
+ : normalizedPos === "right" ? "left"
368
+ : "up";
369
+ const isVertical = normalizedPos === "left" || normalizedPos === "right";
370
+ const isFirstChild = normalizedPos === "top" || normalizedPos === "left";
371
+
372
+ const font = {};
373
+ if (appearance.fontFace) font.face = appearance.fontFace;
374
+ if (typeof barFontSize === "number") font.size = barFontSize;
375
+ else if (typeof appearance.fontSize === "number") font.size = appearance.fontSize;
376
+
377
+ // Windows Terminal's splitPane `size` always sets the SECOND child's fraction:
378
+ // - down/right (bar is second child): size = barFraction.
379
+ // - up/left (bar is first child): size = 1 - barFraction.
380
+ // Each resizePane step shrinks the bar by exactly 0.05 (5% of root container):
381
+ // - bottom/top: start at 0.20 so WT Pane::CanSplit never rejects 2x2 / stacked
382
+ // grids, then 3 resizePane steps shrink it to 0.05 (~35 DIPs = clean 1 row,
383
+ // no text clipping at 100%-200% DPI).
384
+ // - left/right: target ~73 DIPs scaled by exact window DPI (5 full cols + safe
385
+ // cell pitch buffer, 2 DIP horizontal padding) so 1100-1440 DIP windows never
386
+ // clip "18:43" at 100%-200% DPI and wide/maximized windows stay slim.
387
+ const round3 = (n) => Math.round(n * 1000) / 1000;
388
+ let defaultVerticalBarFraction = 0.11;
389
+ if (isVertical && Number.isFinite(Number(windowClientWidth)) && Number(windowClientWidth) >= 400) {
390
+ const dpi = Number.isFinite(Number(windowDpi)) && Number(windowDpi) >= 72 ? Number(windowDpi) : 96;
391
+ const scale = dpi / 96;
392
+ const fontSize = typeof font.size === "number" && font.size > 0 ? font.size : 12;
393
+ const charPx = Math.max(11, Math.round(fontSize * 0.92)) * scale;
394
+ const targetBarPx = Math.ceil((normalizedSidebarWidth * charPx) + (18 * scale));
395
+ const desiredFinalFraction = Math.max(0.026, Math.min(0.105, targetBarPx / Number(windowClientWidth)));
396
+ defaultVerticalBarFraction = round3(Math.max(0.076, Math.min(0.160, desiredFinalFraction + 0.05)));
397
+ }
398
+ const effectiveSplitSize = typeof splitSize === "number"
399
+ ? splitSize
400
+ : (isVertical
401
+ ? (isFirstChild ? round3(1 - defaultVerticalBarFraction) : defaultVerticalBarFraction)
402
+ : (isFirstChild ? 0.80 : 0.20));
403
+ const effectiveResizeSteps = typeof resizeSteps === "number"
404
+ ? resizeSteps
405
+ : (isVertical ? 1 : 3);
406
+
407
+ const profile = {
408
+ guid: WT_BAR_PROFILE_GUID,
409
+ name: WT_BAR_PROFILE_NAME,
410
+ hidden: true,
411
+ scrollbarState: "hidden",
412
+ padding: isVertical ? "2, 4, 2, 4" : "16, 4, 12, 4",
413
+ suppressApplicationTitle: true,
414
+ closeOnExit: "always",
415
+ ...(Object.keys(font).length ? { font } : {}),
416
+ commandline: `${quoteWinArg(nodePath)} ${quoteWinArg(cliPath)} bar`
417
+ };
418
+ for (const key of ["colorScheme", "background", "foreground", "opacity", "useAcrylic"]) {
419
+ if (appearance[key] !== undefined) profile[key] = appearance[key];
420
+ }
421
+
422
+ // Climb to the tab's root container via moveFocus("parent") so splitPane
423
+ // wraps ANY existing split tree ([A|B], top/bottom, 2x2) untouched as the
424
+ // sibling and places AI Battery Bar along the configured edge (bottom/top/left/right).
425
+ // Windows Terminal rejects splitSize < ~0.20 on stacked/compact layouts, so we
426
+ // split at 0.20 and shrink the root-level bar cleanly without altering upper split ratios.
427
+ const climbToRoot = Array.from({ length: 16 }, () => ({ action: "moveFocus", direction: "parent" }));
428
+ const shrinkBar = Array.from({ length: Math.max(0, Number(effectiveResizeSteps) || 0) }, () => ({ action: "resizePane", direction: splitDirection }));
429
+
430
+ return {
431
+ profiles: [profile],
432
+ actions: [
433
+ {
434
+ id: WT_ATTACH_ACTION_ID,
435
+ name: "AI Battery: Attach shared status bar",
436
+ command: {
437
+ action: "multipleActions",
438
+ actions: [
439
+ ...climbToRoot,
440
+ {
441
+ action: "splitPane",
442
+ split: splitDirection,
443
+ size: effectiveSplitSize,
444
+ profile: WT_BAR_PROFILE_NAME
445
+ },
446
+ ...shrinkBar,
447
+ { action: "moveFocus", direction: returnFocusDirection }
448
+ ]
449
+ }
450
+ }
451
+ ]
452
+ };
453
+ }
454
+
455
+ function managedFragment(content) {
456
+ const digest = crypto.createHash("sha256").update(JSON.stringify(content)).digest("hex");
457
+ return { ...content, _aiBattery: { version: 1, digest } };
458
+ }
459
+
460
+ function ownedFragment(file) {
461
+ try {
462
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
463
+ const { _aiBattery, ...content } = parsed;
464
+ return _aiBattery?.version === 1 && managedFragment(content)._aiBattery.digest === _aiBattery.digest;
465
+ } catch { return false; }
466
+ }
467
+
468
+ function legacyFragment(file) {
469
+ try {
470
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
471
+ const actions = Array.isArray(value.actions) ? value.actions : [];
472
+ const allowedIds = new Set([WT_ATTACH_ACTION_ID, "AiBattery.NewTabWithBar"]);
473
+ return !value._aiBattery && value.profiles?.length === 1
474
+ && value.profiles[0].guid === WT_BAR_PROFILE_GUID
475
+ && /ai-battery(?:-shared-bar)?[\\/].*ai-battery\.js.* bar$/.test(value.profiles[0].commandline || "")
476
+ && actions.length >= 1 && actions.length <= 2
477
+ && actions.some(action => action?.id === WT_ATTACH_ACTION_ID)
478
+ && actions.every(action => allowedIds.has(action?.id));
479
+ } catch { return false; }
480
+ }
481
+
482
+ function touchWtSettings(settingsPath) {
483
+ if (!settingsPath) return;
484
+ try {
485
+ const now = new Date();
486
+ fs.utimesSync(settingsPath, now, now);
487
+ } catch { /* Best-effort WT hot reload trigger without modifying file bytes. */ }
488
+ }
489
+
490
+ export function installWtFragment({ env = process.env, nodePath = process.execPath, cliPath, bindAutoTrigger = true, position = "bottom", sidebarWidth = DEFAULT_SIDEBAR_WIDTH } = {}) {
491
+ const target = wtFragmentPath(env);
492
+ if (!target) {
493
+ return { ok: false, skipped: true, reason: "LOCALAPPDATA is not set" };
494
+ }
495
+ const settingsPath = findWtSettingsPath(env);
496
+ const appearance = readDefaultProfileAppearance(settingsPath);
497
+ const effectivePosition = normalizeBarPosition(position, "bottom");
498
+ const effectiveWidth = normalizeSidebarWidth(sidebarWidth, DEFAULT_SIDEBAR_WIDTH);
499
+ const fragment = managedFragment(buildWtFragment({ nodePath, cliPath, appearance, position: effectivePosition, sidebarWidth: effectiveWidth }));
500
+ let backupPath = null;
501
+ if (fs.existsSync(target) && !ownedFragment(target)) {
502
+ if (!legacyFragment(target)) {
503
+ return { ok: false, skipped: true, reason: "Existing Windows Terminal bar fragment was edited; preserved.", fragmentPath: target };
504
+ }
505
+ backupPath = `${target}.ai-battery-backup-${Date.now()}`;
506
+ fs.copyFileSync(target, backupPath, fs.constants.COPYFILE_EXCL);
507
+ }
508
+ const content = `${JSON.stringify(fragment, null, 2)}\n`;
509
+
510
+ const changed = !fs.existsSync(target) || fs.readFileSync(target, "utf8") !== content;
511
+ if (changed) {
512
+ fs.mkdirSync(path.dirname(target), { recursive: true });
513
+ const temp = `${target}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
514
+ try {
515
+ fs.writeFileSync(temp, content, "utf8");
516
+ atomicRename(temp, target);
517
+ } finally {
518
+ try { fs.unlinkSync(temp); } catch { /* Already renamed. */ }
519
+ }
520
+ }
521
+ const trigger = bindAutoTrigger ? ensureWtTriggerKeybinding(settingsPath) : { ok: false };
522
+ if (changed && !trigger.changed) touchWtSettings(settingsPath);
523
+ return {
524
+ ok: true,
525
+ changed: changed || Boolean(trigger.changed),
526
+ autoAttach: trigger.ok,
527
+ autoTriggerKey: trigger.key || null,
528
+ autoAttachNote: trigger.reason || null,
529
+ backupPath,
530
+ fragmentPath: target,
531
+ wtSettingsPath: settingsPath,
532
+ profileName: WT_BAR_PROFILE_NAME,
533
+ actionIds: [WT_ATTACH_ACTION_ID]
534
+ };
535
+ }
536
+
537
+ export function removeWtFragment({ env = process.env } = {}) {
538
+ const target = wtFragmentPath(env);
539
+ if (!target) return { ok: true, removed: false, fragmentPath: null };
540
+ const existed = fs.existsSync(target);
541
+ if (existed && !ownedFragment(target)) {
542
+ return { ok: true, removed: false, retained: true, fragmentPath: target, reason: "Edited Windows Terminal bar fragment preserved." };
543
+ }
544
+ const keyRemoved = removeWtTriggerKeybinding(findWtSettingsPath(env));
545
+ if (keyRemoved.retained) return { ok: false, retained: true, fragmentPath: target, error: keyRemoved.reason };
546
+ if (existed) {
547
+ fs.rmSync(target, { force: true });
548
+ try {
549
+ const folder = path.dirname(target);
550
+ if (fs.readdirSync(folder).length === 0) fs.rmdirSync(folder);
551
+ } catch { /* Keep non-empty directory. */ }
552
+ touchWtSettings(findWtSettingsPath(env));
553
+ }
554
+ return { ok: true, removed: existed || keyRemoved.removed, fragmentPath: target, keybindingRemoved: keyRemoved.removed };
555
+ }
556
+
557
+ export function updateWtFragmentPosition({ env = process.env, position = "bottom", sidebarWidth = DEFAULT_SIDEBAR_WIDTH, windowClientWidth = null, windowDpi = 96 } = {}) {
558
+ const target = wtFragmentPath(env);
559
+ if (!target || !fs.existsSync(target) || !ownedFragment(target)) {
560
+ return { ok: false, updated: false, reason: "Fragment not managed or missing." };
561
+ }
562
+ try {
563
+ const existing = JSON.parse(fs.readFileSync(target, "utf8"));
564
+ const profile = existing?.profiles?.[0];
565
+ const cmd = String(profile?.commandline || "");
566
+ const match = cmd.match(/^("(?:[^"\\]|\\.)*"|\S+)\s+("(?:[^"\\]|\\.)*"|\S+)\s+bar$/);
567
+ if (!match) return { ok: false, updated: false, reason: "Could not parse bar commandline." };
568
+ const unquote = (token) => token.startsWith("\"") && token.endsWith("\"")
569
+ ? token.slice(1, -1).replace(/\\"/g, "\"").replace(/\\\\/g, "\\")
570
+ : token;
571
+ const nodePath = unquote(match[1]);
572
+ const cliPath = unquote(match[2]);
573
+ const settingsPath = findWtSettingsPath(env);
574
+ const appearance = readDefaultProfileAppearance(settingsPath);
575
+ const nextPos = normalizeBarPosition(position, "bottom");
576
+ const nextWidth = normalizeSidebarWidth(sidebarWidth, DEFAULT_SIDEBAR_WIDTH);
577
+ const built = buildWtFragment({ nodePath, cliPath, appearance, position: nextPos, sidebarWidth: nextWidth, windowClientWidth, windowDpi });
578
+ // Avoid triggering a WT settings reload right before F24 when the existing
579
+ // fragment already matches the direction, padding, and within 0.4% size.
580
+ if (windowClientWidth !== null) {
581
+ const prevActions = existing?.actions?.[0]?.command?.actions || [];
582
+ const nextActions = built?.actions?.[0]?.command?.actions || [];
583
+ const prevSplit = prevActions.find(a => a?.action === "splitPane");
584
+ const nextSplit = nextActions.find(a => a?.action === "splitPane");
585
+ const prevResizes = prevActions.filter(a => a?.action === "resizePane").length;
586
+ const nextResizes = nextActions.filter(a => a?.action === "resizePane").length;
587
+ if (
588
+ prevSplit && nextSplit
589
+ && prevSplit.split === nextSplit.split
590
+ && prevResizes === nextResizes
591
+ && profile?.padding === built.profiles?.[0]?.padding
592
+ && Math.abs(Number(prevSplit.size) - Number(nextSplit.size)) <= 0.004
593
+ ) {
594
+ return { ok: true, updated: false, position: nextPos, fragmentPath: target };
595
+ }
596
+ }
597
+ const fragment = managedFragment(built);
598
+ const content = `${JSON.stringify(fragment, null, 2)}\n`;
599
+ const changed = fs.readFileSync(target, "utf8") !== content;
600
+ if (changed) {
601
+ const temp = `${target}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
602
+ try {
603
+ fs.writeFileSync(temp, content, "utf8");
604
+ atomicRename(temp, target);
605
+ } finally {
606
+ try { fs.unlinkSync(temp); } catch {}
607
+ }
608
+ touchWtSettings(settingsPath);
609
+ }
610
+ return { ok: true, updated: changed, position: nextPos, fragmentPath: target };
611
+ } catch (error) {
612
+ return { ok: false, updated: false, reason: error?.message || "Failed to update fragment." };
613
+ }
614
+ }
615
+
616
+ export function isWtFragmentValid({ env = process.env } = {}) {
617
+ const fragmentPath = wtFragmentPath(env);
618
+ if (!fragmentPath || !fs.existsSync(fragmentPath)) return false;
619
+ try {
620
+ const parsed = JSON.parse(fs.readFileSync(fragmentPath, "utf8"));
621
+ return Boolean(
622
+ Array.isArray(parsed?.profiles)
623
+ && parsed.profiles.some(p => p?.name === WT_BAR_PROFILE_NAME)
624
+ && Array.isArray(parsed?.actions)
625
+ && parsed.actions.some(a => a?.id === WT_ATTACH_ACTION_ID)
626
+ );
627
+ } catch {
628
+ return false;
629
+ }
630
+ }
631
+
632
+ export function diagnoseWtFragment({ env = process.env } = {}) {
633
+ const fragmentPath = wtFragmentPath(env);
634
+ const wtSettingsPath = findWtSettingsPath(env);
635
+ const trigger = readWtTriggerKeybinding(env);
636
+ let installed = false;
637
+ let valid = false;
638
+ let error = null;
639
+ if (fragmentPath && fs.existsSync(fragmentPath)) {
640
+ installed = true;
641
+ try {
642
+ const parsed = JSON.parse(fs.readFileSync(fragmentPath, "utf8"));
643
+ valid = Boolean(
644
+ Array.isArray(parsed?.profiles)
645
+ && parsed.profiles.some(p => p?.name === WT_BAR_PROFILE_NAME)
646
+ && Array.isArray(parsed?.actions)
647
+ && parsed.actions.some(a => a?.id === WT_ATTACH_ACTION_ID)
648
+ );
649
+ } catch (err) {
650
+ error = err.message;
651
+ }
652
+ }
653
+ return {
654
+ available: Boolean(wtSettingsPath || fragmentPath),
655
+ installed,
656
+ valid,
657
+ autoAttach: Boolean(valid && trigger),
658
+ autoTriggerKey: trigger?.key || null,
659
+ fragmentPath,
660
+ wtSettingsPath,
661
+ profileName: WT_BAR_PROFILE_NAME,
662
+ actionIds: [WT_ATTACH_ACTION_ID],
663
+ error
664
+ };
665
+ }