ai-battery 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +30 -14
  2. package/bin/ai-battery-macos-rail.applescript +227 -0
  3. package/bin/ai-battery-macos-status.applescript +5 -12
  4. package/bin/ai-battery-run +701 -31
  5. package/bin/ai-battery-tmux.js +17 -0
  6. package/bin/terminal-compositor.js +111 -0
  7. package/docs/REFERENCE.md +23 -3
  8. package/docs/RELEASING.md +30 -7
  9. package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
  10. package/docs/hud-preview.svg +75 -20
  11. package/docs/terminal-vertical-preview.svg +73 -0
  12. package/lib/cli.js +1148 -240
  13. package/lib/core/atomic-rename.js +18 -0
  14. package/lib/core/cli-help.js +57 -12
  15. package/lib/core/cli-messages.js +45 -1
  16. package/lib/core/cli-output.js +277 -72
  17. package/lib/core/cli-wrappers.js +410 -0
  18. package/lib/core/config-editor.js +194 -29
  19. package/lib/core/display-config.js +45 -0
  20. package/lib/core/integration-files.js +32 -3
  21. package/lib/core/shared-bar.js +603 -0
  22. package/lib/core/statusline-git.js +179 -15
  23. package/lib/core/terminal.js +25 -7
  24. package/lib/core/tmux-status.js +172 -0
  25. package/lib/core/uninstall.js +20 -7
  26. package/lib/core/usage-store.js +85 -0
  27. package/lib/hud/launcher.js +32 -33
  28. package/lib/platforms/linux/gnome-extension/extension.js +7 -6
  29. package/lib/platforms/linux/hud.js +157 -42
  30. package/lib/platforms/linux/panel.js +16 -3
  31. package/lib/platforms/linux/rail.js +412 -0
  32. package/lib/platforms/macos/hud.js +152 -44
  33. package/lib/platforms/process-scanner.js +77 -29
  34. package/lib/platforms/windows/autostart-cleanup.js +1 -1
  35. package/lib/platforms/windows/codex-runner.js +178 -21
  36. package/lib/platforms/windows/hud/controls.ps1 +65 -15
  37. package/lib/platforms/windows/hud/main.ps1 +715 -54
  38. package/lib/platforms/windows/hud/rendering.ps1 +1284 -2
  39. package/lib/platforms/windows/hud/snapshot.ps1 +26 -46
  40. package/lib/platforms/windows/hud-launcher.js +234 -81
  41. package/lib/platforms/windows/shared-bar-platform.js +972 -0
  42. package/lib/platforms/windows/terminal-compositor.js +210 -25
  43. package/lib/platforms/windows/wt-bar.js +729 -0
  44. package/lib/platforms/windows/wt-fragment.js +665 -0
  45. package/lib/platforms/windows/wt-keybinding.js +300 -0
  46. package/lib/providers/antigravity.js +155 -8
  47. package/package.json +6 -2
  48. package/vendor/PaneContext.cs +875 -0
@@ -0,0 +1,300 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import crypto from "node:crypto";
4
+ import { atomicRename } from "../../core/atomic-rename.js";
5
+
6
+ export const TRIGGER_KEY_CANDIDATES = [24, 23, 22, 21].map(number => ({ key: `f${number}`, vk: 0x6f + number }));
7
+ const digest = text => crypto.createHash("sha256").update(text).digest("hex");
8
+
9
+ // Keep JSONC offsets so installing one key does not reformat profiles or comments.
10
+ function parseSettings(text) {
11
+ let position = text.charCodeAt(0) === 0xfeff ? 1 : 0;
12
+ const skip = () => {
13
+ for (;;) {
14
+ while (/\s/.test(text[position] || "") && position < text.length) position += 1;
15
+ if (text.slice(position, position + 2) === "//") {
16
+ while (position < text.length && text[position] !== "\n") position += 1;
17
+ } else if (text.slice(position, position + 2) === "/*") {
18
+ const end = text.indexOf("*/", position + 2);
19
+ if (end < 0) throw new Error("Unclosed settings comment");
20
+ position = end + 2;
21
+ } else return;
22
+ }
23
+ };
24
+ const value = (depth = 0) => {
25
+ if (depth > 100) throw new Error("Settings nesting limit");
26
+ skip();
27
+ const start = position;
28
+ const first = text[position++];
29
+ if (first === "{" || first === "[") {
30
+ const object = first === "{";
31
+ const closeChar = object ? "}" : "]";
32
+ const items = [];
33
+ const result = object ? {} : [];
34
+ skip();
35
+ while (text[position] !== closeChar) {
36
+ const key = object ? value(depth + 1) : null;
37
+ if (object) { skip(); if (typeof key.value !== "string" || text[position++] !== ":") throw new Error("Invalid settings property"); }
38
+ const node = value(depth + 1);
39
+ const item = object ? { ...node, start: key.start, key: key.value, node } : node;
40
+ items.push(item);
41
+ if (object) Object.defineProperty(result, key.value, { value: node.value, enumerable: true, configurable: true, writable: true });
42
+ else result.push(node.value);
43
+ skip();
44
+ if (text[position] !== ",") break;
45
+ item.comma = position++;
46
+ skip();
47
+ }
48
+ const close = position;
49
+ if (text[position++] !== closeChar) throw new Error("Invalid settings container");
50
+ return { start, end: position, close, items, value: result, type: object ? "object" : "array" };
51
+ }
52
+ if (first === '"') {
53
+ while (position < text.length) {
54
+ const ch = text[position++];
55
+ if (ch === "\\") position += 1;
56
+ else if (ch === '"') return { start, end: position, value: JSON.parse(text.slice(start, position)) };
57
+ }
58
+ throw new Error("Unclosed settings string");
59
+ }
60
+ while (position < text.length && !/[\s,\]}\/]/.test(text[position])) position += 1;
61
+ return { start, end: position, value: JSON.parse(text.slice(start, position)) };
62
+ };
63
+ const root = value();
64
+ skip();
65
+ if (root.type !== "object" || position !== text.length) throw new Error("Invalid Terminal settings");
66
+ return root;
67
+ }
68
+
69
+ function load(file) {
70
+ if (!file) return null;
71
+ try { const raw = fs.readFileSync(file, "utf8"); return { raw, root: parseSettings(raw) }; } catch { return null; }
72
+ }
73
+ function recordPath(file) { return file + ".ai-battery-trigger.json"; }
74
+ function readRecord(file) { try { return JSON.parse(fs.readFileSync(recordPath(file), "utf8")); } catch { return null; } }
75
+ function writeAtomic(file, text) {
76
+ const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
77
+ try { fs.writeFileSync(temp, text, { mode: 0o600 }); atomicRename(temp, file); }
78
+ finally { try { fs.unlinkSync(temp); } catch {} }
79
+ }
80
+ function keys(entry) { return (Array.isArray(entry?.keys) ? entry.keys : [entry?.keys]).filter(value => typeof value === "string").map(value => value.trim().toLowerCase()); }
81
+ function allBindings(value) { return [value.keybindings, value.actions].flatMap(list => Array.isArray(list) ? list : []); }
82
+ function sameValue(left, right) {
83
+ if (left === right) return true;
84
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
85
+ if (Array.isArray(left) || Array.isArray(right)) {
86
+ return Array.isArray(left) && Array.isArray(right)
87
+ && left.length === right.length
88
+ && left.every((item, index) => sameValue(item, right[index]));
89
+ }
90
+ const leftKeys = Object.keys(left).sort();
91
+ const rightKeys = Object.keys(right).sort();
92
+ return leftKeys.length === rightKeys.length
93
+ && leftKeys.every((key, index) => key === rightKeys[index] && sameValue(left[key], right[key]));
94
+ }
95
+ function sameEntry(left, right) { return sameValue(left, right); }
96
+
97
+ function isOwnedBackupPath(file, backupPath) {
98
+ if (typeof backupPath !== "string" || !backupPath) return false;
99
+ const resolvedFile = path.resolve(file);
100
+ const resolvedBackup = path.resolve(backupPath);
101
+ if (path.dirname(resolvedBackup) !== path.dirname(resolvedFile)) return false;
102
+ const prefix = `${path.basename(resolvedFile)}.ai-battery-backup-`;
103
+ const name = path.basename(resolvedBackup);
104
+ if (!name.startsWith(prefix)) return false;
105
+ const suffix = name.slice(prefix.length);
106
+ if (!/^\d+-\d+(?:-[a-f0-9]+)?$/.test(suffix)) return false;
107
+ try {
108
+ const stat = fs.lstatSync(resolvedBackup);
109
+ return stat.isFile() && !stat.isSymbolicLink();
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+
115
+ function readVerifiedBackup(file, record) {
116
+ if (!record?.backupPath || !record?.originalHash) return null;
117
+ if (!isOwnedBackupPath(file, record.backupPath)) return null;
118
+ try {
119
+ const content = fs.readFileSync(record.backupPath, "utf8");
120
+ return digest(content) === record.originalHash ? content : null;
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+
126
+ function cleanupVerifiedBackup(file, record) {
127
+ if (readVerifiedBackup(file, record) === null) return false;
128
+ try {
129
+ fs.unlinkSync(record.backupPath);
130
+ return true;
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ function findTriggerBinding(rootValue, actionId, file) {
137
+ const bindings = allBindings(rootValue);
138
+ for (const entry of bindings.filter(item => item?.id === actionId)) {
139
+ const chosen = TRIGGER_KEY_CANDIDATES.find(candidate => keys(entry).includes(candidate.key));
140
+ if (chosen && !bindings.some(other => other?.id !== actionId && keys(other).includes(chosen.key))) return { ...chosen, settingsPath: file };
141
+ }
142
+ return null;
143
+ }
144
+
145
+ export function readTriggerBinding(file, actionId) {
146
+ const loaded = load(file);
147
+ if (!loaded) return null;
148
+ return findTriggerBinding(loaded.root.value, actionId, file);
149
+ }
150
+
151
+ function arrayProperty(root) {
152
+ const properties = root.items.filter(item => item.key === "keybindings");
153
+ if (properties.length > 1 || (properties.length && properties[0].type !== "array")) throw new Error("Ambiguous Terminal keybindings; preserved");
154
+ return properties[0]?.node;
155
+ }
156
+ function applyEdits(raw, edits) {
157
+ for (const edit of [...edits].sort((a, b) => b.start - a.start)) raw = raw.slice(0, edit.start) + edit.text + raw.slice(edit.end ?? edit.start);
158
+ parseSettings(raw);
159
+ return raw;
160
+ }
161
+ function appendBinding(loaded, binding) {
162
+ const { raw, root } = loaded;
163
+ const array = arrayProperty(root);
164
+ const container = array || root;
165
+ const last = container.items.at(-1);
166
+ const addedComma = Boolean(last && last.comma === undefined);
167
+ const createdKeybindings = !array;
168
+ const newline = raw.includes("\r\n") ? "\r\n" : "\n";
169
+ const indent = raw.slice(0, container.close).match(/(?:^|\n)([ \t]*)[^\n]*$/)?.[1] || "";
170
+ const content = array ? JSON.stringify(binding) : `"keybindings": [${JSON.stringify(binding)}]`;
171
+ const edits = [{ start: container.close, text: ` ${content}${newline}${indent}` }];
172
+ if (addedComma) edits.push({ start: last.end, text: "," });
173
+ return { next: applyEdits(raw, edits), addedComma, createdKeybindings };
174
+ }
175
+
176
+ function removeContainerItem(container, index, { removePrevCommaIfLast = false } = {}) {
177
+ const item = container.items[index];
178
+ const edits = [{ start: item.start, end: item.end, text: "" }];
179
+ if (item.comma !== undefined) {
180
+ edits.push({ start: item.comma, end: item.comma + 1, text: "" });
181
+ } else if (index > 0 && removePrevCommaIfLast) {
182
+ const previous = container.items[index - 1];
183
+ if (previous.comma !== undefined) {
184
+ edits.push({ start: previous.comma, end: previous.comma + 1, text: "" });
185
+ }
186
+ }
187
+ return edits;
188
+ }
189
+
190
+ function inferRecordOrigin(file, record) {
191
+ if (typeof record.addedComma === "boolean") {
192
+ return { addedComma: record.addedComma, createdKeybindings: Boolean(record.createdKeybindings) };
193
+ }
194
+ const original = readVerifiedBackup(file, record);
195
+ if (original !== null) {
196
+ try {
197
+ const backupRoot = parseSettings(original);
198
+ const backupArray = arrayProperty(backupRoot);
199
+ const container = backupArray || backupRoot;
200
+ const last = container.items.at(-1);
201
+ return {
202
+ addedComma: Boolean(last && last.comma === undefined),
203
+ createdKeybindings: !backupArray
204
+ };
205
+ } catch { /* Fall through to conservative default. */ }
206
+ }
207
+ return { addedComma: false, createdKeybindings: false };
208
+ }
209
+
210
+ export function ensureTriggerBinding(file, actionId) {
211
+ const loaded = load(file);
212
+ if (!loaded) return { ok: false, skipped: true, reason: "Terminal settings unavailable; manual shared bar remains available." };
213
+ let backupPath = null;
214
+ let backupCreated = false;
215
+ let recordWritten = false;
216
+ let settingsWritten = false;
217
+ try {
218
+ const { raw, root } = loaded;
219
+ arrayProperty(root);
220
+ const record = readRecord(file);
221
+ const existing = allBindings(root.value).filter(entry => entry?.id === actionId);
222
+ if (record && !existing.some(entry => sameEntry(entry, record.binding)) && digest(raw) !== record.originalHash) {
223
+ return { ok: false, skipped: true, reason: "Edited shared-bar keybinding preserved; automatic attachment disabled." };
224
+ }
225
+ const binding = findTriggerBinding(root.value, actionId, file);
226
+ if (binding) return { ok: true, changed: false, ...binding };
227
+ if (existing.length) return { ok: false, skipped: true, reason: "Existing shared-bar shortcut preserved; no unused automatic trigger." };
228
+ const used = new Set(allBindings(root.value).flatMap(keys));
229
+ const chosen = TRIGGER_KEY_CANDIDATES.find(candidate => !used.has(candidate.key));
230
+ if (!chosen) return { ok: false, skipped: true, reason: "F21–F24 already bound; manual shared bar remains available." };
231
+ const entry = { id: actionId, keys: chosen.key };
232
+ const { next, addedComma, createdKeybindings } = appendBinding(loaded, entry);
233
+ backupPath = `${file}.ai-battery-backup-${Date.now()}-${process.pid}-${crypto.randomBytes(3).toString("hex")}`;
234
+ fs.copyFileSync(file, backupPath, fs.constants.COPYFILE_EXCL);
235
+ backupCreated = true;
236
+ if (fs.readFileSync(file, "utf8") !== raw) throw new Error("Terminal settings changed during setup; preserved");
237
+ writeAtomic(recordPath(file), JSON.stringify({
238
+ version: 1,
239
+ binding: entry,
240
+ backupPath,
241
+ originalHash: digest(raw),
242
+ installedHash: digest(next),
243
+ addedComma,
244
+ createdKeybindings
245
+ }));
246
+ recordWritten = true;
247
+ if (fs.readFileSync(file, "utf8") !== raw) throw new Error("Terminal settings changed during setup; preserved");
248
+ writeAtomic(file, next);
249
+ settingsWritten = true;
250
+ return { ok: true, changed: true, ...chosen };
251
+ } catch (error) {
252
+ if (!settingsWritten) {
253
+ if (recordWritten) { try { fs.unlinkSync(recordPath(file)); } catch {} }
254
+ if (backupCreated && backupPath) { try { fs.unlinkSync(backupPath); } catch {} }
255
+ }
256
+ return { ok: false, skipped: true, reason: error.message };
257
+ }
258
+ }
259
+
260
+ export function removeTriggerBinding(file, actionId) {
261
+ if (!file) return { ok: true, removed: false };
262
+ const record = readRecord(file);
263
+ if (!record || record.version !== 1 || record.binding?.id !== actionId) return { ok: true, removed: false };
264
+ const loaded = load(file);
265
+ if (!loaded) return { ok: false, retained: true, reason: "Terminal settings unavailable; shared-bar recovery record preserved." };
266
+ try {
267
+ const { raw, root } = loaded;
268
+ let next;
269
+ if (digest(raw) === record.installedHash) {
270
+ if (!isOwnedBackupPath(file, record.backupPath)) throw new Error("Shared-bar settings backup invalid; preserved");
271
+ const original = fs.readFileSync(record.backupPath, "utf8");
272
+ if (digest(original) !== record.originalHash) throw new Error("Shared-bar settings backup changed; preserved");
273
+ next = original;
274
+ } else {
275
+ const array = arrayProperty(root);
276
+ const ownedIndex = array ? array.items.findIndex(item => sameEntry(item.value, record.binding)) : -1;
277
+ if (ownedIndex < 0) {
278
+ if (allBindings(root.value).some(entry => entry?.id === actionId)) return { ok: false, retained: true, reason: "Edited shared-bar shortcut preserved." };
279
+ cleanupVerifiedBackup(file, record);
280
+ fs.unlinkSync(recordPath(file));
281
+ return { ok: true, removed: false };
282
+ }
283
+ const origin = inferRecordOrigin(file, record);
284
+ let edits;
285
+ if (origin.createdKeybindings && array.items.length === 1 && !/\/[/*]/.test(raw.slice(array.start, array.end))) {
286
+ const propIndex = root.items.findIndex(item => item.key === "keybindings");
287
+ edits = removeContainerItem(root, propIndex, { removePrevCommaIfLast: origin.addedComma });
288
+ } else {
289
+ const removePrevCommaIfLast = origin.createdKeybindings ? true : origin.addedComma;
290
+ edits = removeContainerItem(array, ownedIndex, { removePrevCommaIfLast });
291
+ }
292
+ next = applyEdits(raw, edits);
293
+ }
294
+ if (fs.readFileSync(file, "utf8") !== raw) throw new Error("Terminal settings changed during reset; preserved");
295
+ writeAtomic(file, next);
296
+ cleanupVerifiedBackup(file, record);
297
+ fs.unlinkSync(recordPath(file));
298
+ return { ok: true, removed: true };
299
+ } catch (error) { return { ok: false, retained: true, reason: error.message }; }
300
+ }
@@ -2,6 +2,15 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  import { clamp, resetEpochSeconds } from "../core/limits.js";
5
+ import { withFileLock } from "../core/usage-store.js";
6
+
7
+ function sameStatusLine(left, right) {
8
+ const normalize = value => value && typeof value === "object" && !Array.isArray(value)
9
+ ? { type: "command", padding: 0, enabled: true, stack_with_default: false, ...value } : value;
10
+ // agy omits default-valued fields when saving settings. These are the
11
+ // documented defaults; commands, nondefaults and unknown fields stay exact.
12
+ return isDeepStrictEqual(normalize(left), normalize(right));
13
+ }
5
14
 
6
15
  function selectAntigravityLimits(quotas, model, now) {
7
16
  const modelName = typeof model === "string" ? model : model?.id || model?.display_name || "";
@@ -75,9 +84,10 @@ export function antigravityStatuslineCommand(scriptPath, flags, shellArg, platfo
75
84
  return [shellArg(process.execPath), shellArg(scriptPath), "capture-antigravity", ...flags].join(" ");
76
85
  }
77
86
 
78
- export function createAntigravityIntegration({ homePath, stateDir, readJson, readUserJsonObject, readConfig, writeConfig, writeJsonAtomic, samePath, shellArg, scriptDir, isProviderRunning }) {
87
+ export function createAntigravityIntegration({ homePath, stateDir, usageStateDir = stateDir, readJson, readUserJsonObject, readConfig, writeConfig, writeJsonAtomic, samePath, shellArg, scriptDir, isProviderRunning, providerVisible = provider => readConfig().providers?.[provider] !== false }) {
79
88
  const settingsPath = () => homePath(".gemini", "antigravity-cli", "settings.json");
80
89
  const cachePath = () => path.join(stateDir(), "antigravity-statusline.json");
90
+ const usageCachePath = () => path.join(usageStateDir(), "antigravity-account-usage.json");
81
91
  const backupKey = "antigravityStatusLineBackup";
82
92
  const managed = value => typeof value?.command === "string" && value.command.includes("ai-battery.js") && value.command.includes("capture-antigravity");
83
93
 
@@ -127,7 +137,7 @@ export function createAntigravityIntegration({ homePath, stateDir, readJson, rea
127
137
  config[backupKey] = null; writeConfig(config);
128
138
  return { settingsPath: target, changed: false, alreadyRestored: true };
129
139
  }
130
- const owned = backup ? backup.managedStatusLines.some(value => isDeepStrictEqual(value, existing)) : managed(existing);
140
+ const owned = backup ? backup.managedStatusLines.some(value => sameStatusLine(value, existing)) : managed(existing);
131
141
  if (!owned) return { settingsPath: target, changed: false, skipped: Boolean(backup), retainedBackup: Boolean(backup), reason: "Gemini settings changed; settings and recovery record preserved" };
132
142
  if (backup?.settingsExisted === false && Object.keys(settings.value).length === 1) fs.rmSync(target, { force: true });
133
143
  else {
@@ -140,28 +150,165 @@ export function createAntigravityIntegration({ homePath, stateDir, readJson, rea
140
150
  return { settingsPath: target, changed: true, restored: Boolean(backup?.hadStatusLine || backup?.settingsExisted) };
141
151
  }
142
152
 
153
+ function quotaFingerprint(quotas) {
154
+ return [...(quotas || [])]
155
+ .sort((a, b) => String(a.id || "").localeCompare(String(b.id || "")))
156
+ .map(q => {
157
+ const resetSec = resetEpochSeconds(q.resetsAt);
158
+ // Bucket resetsAt to 10s intervals so +/-1s reset_in_seconds jitter never looks like new quota data.
159
+ const resetBucket = resetSec > 0 ? Math.round(resetSec / 10) : 0;
160
+ return {
161
+ id: q.id,
162
+ remainingPercent: q.remainingPercent ?? null,
163
+ remainingAmount: q.remainingAmount ?? null,
164
+ windowMinutes: q.windowMinutes ?? null,
165
+ resetBucket
166
+ };
167
+ });
168
+ }
169
+
170
+ function mergeCanonicalQuotas(existingQuotas, incomingQuotas) {
171
+ const byId = new Map();
172
+ for (const q of existingQuotas || []) {
173
+ if (q?.id) byId.set(q.id, q);
174
+ }
175
+ for (const incoming of incomingQuotas || []) {
176
+ if (!incoming?.id) continue;
177
+ const prev = byId.get(incoming.id);
178
+ if (!prev) {
179
+ byId.set(incoming.id, incoming);
180
+ continue;
181
+ }
182
+ const prevReset = resetEpochSeconds(prev.resetsAt);
183
+ const nextReset = resetEpochSeconds(incoming.resetsAt);
184
+ const nowSec = Date.now() / 1000;
185
+ const prevExpired = prevReset > 0 && prevReset <= nowSec;
186
+ const nextExpired = nextReset > 0 && nextReset <= nowSec;
187
+ const prevUnused = prev.remainingPercent === 100;
188
+ const nextUnused = incoming.remainingPercent === 100;
189
+ if (prevExpired && !nextExpired) {
190
+ byId.set(incoming.id, incoming);
191
+ } else if (!prevExpired && nextExpired) {
192
+ continue;
193
+ } else if (prevReset > 0 && nextReset > 0) {
194
+ if (Math.abs(nextReset - prevReset) > 60) {
195
+ // An unused 100% bucket carries a rolling (now + window) reset timestamp
196
+ // that is always later than an active draining window's fixed resetsAt.
197
+ // Never let a rolling 100% clobber an unexpired draining bucket, and let
198
+ // an actively draining bucket replace a rolling 100%.
199
+ if (prevUnused && !nextUnused) {
200
+ byId.set(incoming.id, incoming);
201
+ } else if (!prevUnused && nextUnused) {
202
+ continue;
203
+ } else if (nextReset > prevReset) {
204
+ byId.set(incoming.id, incoming);
205
+ }
206
+ } else if (typeof prev.remainingPercent === "number" && typeof incoming.remainingPercent === "number") {
207
+ // Same bounded reset window: usage drains monotonically, so an idle stale pane
208
+ // with a higher remainingPercent cannot clobber a fresher lower reading.
209
+ if (incoming.remainingPercent <= prev.remainingPercent) {
210
+ byId.set(incoming.id, incoming);
211
+ }
212
+ } else if (typeof incoming.remainingPercent === "number") {
213
+ byId.set(incoming.id, incoming);
214
+ }
215
+ } else {
216
+ // Without a bounded reset window on both sides, accept the incoming reading
217
+ // so buckets without resetsAt never latch permanently at their lowest value.
218
+ byId.set(incoming.id, incoming);
219
+ }
220
+ }
221
+ return [...byId.values()].sort((a, b) => String(a.id).localeCompare(String(b.id)));
222
+ }
223
+
143
224
  function capture(input) {
144
225
  const snapshot = normalizeAntigravityPayload(input);
226
+ const receivedQuotas = snapshot.quotas.length > 0;
227
+ const previous = readJson(cachePath());
228
+ const previousShared = readJson(usageCachePath());
229
+ if (!snapshot.quotas.length && Array.isArray(previous?.quotas) && previous.quotas.length) Object.assign(snapshot, selectAntigravityLimits(previous.quotas, snapshot.model, Date.now()));
230
+ const family = model => /claude|opus|sonnet|haiku|gpt|codex|openai/i.test(typeof model === "string" ? model : model?.id || model?.display_name || "") ? "third-party" : "gemini";
231
+ const incomingFp = quotaFingerprint(snapshot.quotas);
232
+ const sameAsLocal = family(snapshot.model) === family(previous?.model) && isDeepStrictEqual(incomingFp, quotaFingerprint(previous?.quotas));
233
+ const sameAsShared = family(snapshot.model) === family(previousShared?.model) && isDeepStrictEqual(incomingFp, quotaFingerprint(previousShared?.quotas));
234
+ if (sameAsLocal) {
235
+ snapshot.quotaObservedAt = previous?.quotaObservedAt || previous?.timestamp || snapshot.timestamp;
236
+ } else if (sameAsShared) {
237
+ snapshot.quotaObservedAt = previousShared?.timestamp || snapshot.timestamp;
238
+ } else {
239
+ snapshot.quotaObservedAt = snapshot.timestamp;
240
+ }
241
+ if (receivedQuotas) {
242
+ const sharedPath = usageCachePath();
243
+ const modelStr = typeof snapshot.model === "string" ? snapshot.model : snapshot.model?.id || snapshot.model?.display_name || "";
244
+ try {
245
+ withFileLock(`${sharedPath}.lock`, () => {
246
+ const current = readJson(sharedPath);
247
+ const mergedQuotas = current?.provider === "antigravity" && Array.isArray(current.quotas)
248
+ ? mergeCanonicalQuotas(current.quotas, snapshot.quotas)
249
+ : snapshot.quotas;
250
+ const modelFamilyChanged = Boolean(modelStr && current?.model && family(modelStr) !== family(current.model));
251
+ const changed = !current
252
+ || modelFamilyChanged
253
+ || !isDeepStrictEqual(quotaFingerprint(mergedQuotas), quotaFingerprint(current.quotas));
254
+ const prevTs = Date.parse(current?.timestamp || "") || 0;
255
+ const nextTs = changed || !current?.timestamp
256
+ ? Math.max(prevTs, Date.parse(snapshot.quotaObservedAt || snapshot.timestamp || "") || Date.now())
257
+ : prevTs;
258
+ const canonicalTs = new Date(nextTs).toISOString();
259
+ if (changed || !current?.timestamp) {
260
+ writeJsonAtomic(sharedPath, {
261
+ provider: "antigravity",
262
+ version: 1,
263
+ timestamp: canonicalTs,
264
+ model: modelStr || current?.model || "",
265
+ quotas: mergedQuotas
266
+ });
267
+ }
268
+ // Keep the local snapshot aligned with canonical quotas so an idle pane
269
+ // cannot retain stale higher quotas above the shared canonical record.
270
+ if (!isDeepStrictEqual(quotaFingerprint(mergedQuotas), incomingFp)) {
271
+ snapshot.quotas = mergedQuotas;
272
+ Object.assign(snapshot, selectAntigravityLimits(mergedQuotas, snapshot.model, Date.now()));
273
+ snapshot.quotaObservedAt = canonicalTs;
274
+ }
275
+ }, { timeoutMs: 1000 });
276
+ } catch { /* Best-effort shared publish. */ }
277
+ }
145
278
  // Deliberately exclude account email and transcript contents from the cache.
146
279
  writeJsonAtomic(cachePath(), snapshot);
147
280
  return snapshot;
148
281
  }
149
282
 
150
283
  function read(options = {}) {
151
- const cached = readJson(cachePath());
152
- const running = options.runningOverride ?? isProviderRunning("antigravity");
284
+ // Backfill old installations too, so the first WSL/HUD reader can see an
285
+ // existing native Windows hook without waiting for another agent event.
286
+ const localRecord = readJson(cachePath());
287
+ const records = [...new Set([cachePath(), path.join(usageStateDir(), "antigravity-statusline.json"), usageCachePath()])]
288
+ .map(file => ({ file, value: readJson(file) }))
289
+ .filter(({ value }) => value?.provider === "antigravity" && Array.isArray(value.quotas) && value.quotas.length)
290
+ .sort((a, b) => (Date.parse(b.value.quotaObservedAt || b.value.timestamp || "") || 0) - (Date.parse(a.value.quotaObservedAt || a.value.timestamp || "") || 0));
291
+ const cached = records[0]?.value;
292
+ const localAgeMs = localRecord?.timestamp ? Date.now() - (Date.parse(localRecord.timestamp) || 0) : Infinity;
293
+ const recentStatuslineActive = Number.isFinite(localAgeMs) && localAgeMs >= 0 && localAgeMs <= 20000 && localRecord?.agentState !== "exited";
294
+ const running = typeof options.runningOverride === "boolean"
295
+ ? options.runningOverride
296
+ : (isProviderRunning("antigravity", options.processOptions) || recentStatuslineActive);
153
297
  if (cached?.provider !== "antigravity") return { provider: "antigravity", ok: false, running, error: "Waiting for Gemini statusLine payload", source: cachePath() };
154
- const limits = Array.isArray(cached.quotas) ? selectAntigravityLimits(cached.quotas, cached.model, Date.now()) : {};
155
- const snapshot = { ...cached, ...limits, running, source: cachePath(), ageSeconds: Math.max(0, (Date.now() - Date.parse(cached.timestamp)) / 1000) };
298
+ const preferredModel = localRecord?.model && localAgeMs <= 15 * 60 * 1000 ? localRecord.model : cached.model;
299
+ const limits = Array.isArray(cached.quotas) ? selectAntigravityLimits(cached.quotas, preferredModel, Date.now()) : {};
300
+ const timestamp = cached.quotaObservedAt || cached.timestamp;
301
+ const snapshot = { ...cached, ...limits, model: preferredModel, timestamp, running, source: records[0].file, ageSeconds: Math.max(0, (Date.now() - (Date.parse(timestamp) || Date.now())) / 1000) };
156
302
  return snapshot;
157
303
  }
158
304
 
159
305
  function diagnose() {
160
306
  const settings = readUserJsonObject(settingsPath(), "Gemini settings");
161
307
  const statusLine = settings.value?.statusLine;
162
- return { providerEnabled: readConfig().providers.antigravity !== false, settingsPath: settingsPath(),
308
+ return { providerEnabled: providerVisible("antigravity"), settingsPath: settingsPath(),
163
309
  configured: Boolean(statusLine), managed: managed(statusLine), enabled: statusLine?.enabled !== false,
164
310
  cachePath: cachePath(), statuslineCache: readJson(cachePath())?.provider === "antigravity", error: settings.error || null };
165
311
  }
166
- return { install, uninstall, capture, read, diagnose, cachePath, settingsPath };
312
+ const available = () => [cachePath(), usageCachePath(), path.join(usageStateDir(), "antigravity-statusline.json"), settingsPath()].some(file => fs.existsSync(file));
313
+ return { install, uninstall, capture, read, diagnose, cachePath, usageCachePath, settingsPath, available };
167
314
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-battery",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Tiny terminal battery meter for local Codex, Claude Code and Gemini CLI usage.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -29,9 +29,11 @@
29
29
  "bin/ai-battery-run",
30
30
  "bin/ai-battery-run-win.js",
31
31
  "bin/terminal-compositor.js",
32
+ "bin/ai-battery-tmux.js",
32
33
  "bin/ai-battery-hud",
33
34
  "bin/ai-battery-hud.js",
34
35
  "bin/ai-battery-macos-status.applescript",
36
+ "bin/ai-battery-macos-rail.applescript",
35
37
  "bin/ai-battery-hud.ps1",
36
38
  "lib/**/*.js",
37
39
  "lib/**/*.ps1",
@@ -42,9 +44,11 @@
42
44
  "scripts/linux-gnome-menu-check.mjs",
43
45
  "scripts/linux-gnome-menu-smoke.js",
44
46
  "vendor/rowpty/RowPty.cs",
47
+ "vendor/PaneContext.cs",
45
48
  "docs/*.svg",
46
49
  "docs/RELEASING.md",
47
50
  "docs/REFERENCE.md",
51
+ "docs/WINDOWS-TERMINAL-SHARED-BAR.md",
48
52
  "docs/SETUP-REGRESSION.md",
49
53
  "README.md"
50
54
  ],
@@ -57,7 +61,7 @@
57
61
  "smoke:codex-fullscreen-win": "node ./scripts/windows-codex-fullscreen-check.mjs",
58
62
  "smoke:wsl-win": "bash ./scripts/wsl-windows-rowpty-smoke.sh",
59
63
  "smoke:linux": "node ./scripts/linux-gnome-menu-check.mjs",
60
- "check": "node --check ./bin/ai-battery.js && node --check ./bin/ai-battery-hud.js && node --check ./bin/ai-battery-run-win.js && node --check ./lib/hud/launcher.js && node --check ./lib/platforms/windows/codex-runner.js && node --check ./lib/platforms/linux/hud.js && node --check ./lib/platforms/linux/panel.js && node --check ./lib/platforms/linux/panel-snapshot.js && node --check ./lib/platforms/linux/gnome.js && node --check ./lib/platforms/linux/gnome-control.js && node --check ./lib/platforms/linux/gnome-extension/extension.js && node --test",
64
+ "check": "node --check ./bin/ai-battery.js && node --check ./bin/ai-battery-hud.js && node --check ./bin/ai-battery-run-win.js && node --check ./bin/ai-battery-tmux.js && node --check ./bin/terminal-compositor.js && node --check ./lib/cli.js && node --check ./lib/core/atomic-rename.js && node --check ./lib/core/cli-help.js && node --check ./lib/core/cli-messages.js && node --check ./lib/core/cli-output.js && node --check ./lib/core/cli-wrappers.js && node --check ./lib/core/config-editor.js && node --check ./lib/core/diagnostics.js && node --check ./lib/core/display-config.js && node --check ./lib/core/integration-files.js && node --check ./lib/core/shared-bar.js && node --check ./lib/core/terminal.js && node --check ./lib/core/tmux-status.js && node --check ./lib/core/uninstall.js && node --check ./lib/core/usage-store.js && node --check ./lib/providers/antigravity.js && node --check ./lib/hud/launcher.js && node --check ./lib/platforms/process-scanner.js && node --check ./lib/platforms/windows/codex-runner.js && node --check ./lib/platforms/windows/hud-launcher.js && node --check ./lib/platforms/windows/shared-bar-platform.js && node --check ./lib/platforms/windows/wt-bar.js && node --check ./lib/platforms/windows/wt-fragment.js && node --check ./lib/platforms/windows/wt-keybinding.js && node --check ./lib/platforms/linux/hud.js && node --check ./lib/platforms/linux/panel.js && node --check ./lib/platforms/linux/rail.js && node --check ./lib/platforms/linux/panel-snapshot.js && node --check ./lib/platforms/linux/gnome.js && node --check ./lib/platforms/linux/gnome-control.js && node --check ./lib/platforms/linux/gnome-extension/extension.js && node --test",
61
65
  "test": "node --test"
62
66
  },
63
67
  "engines": {