ai-battery 0.1.29 → 0.2.0

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.
@@ -0,0 +1,167 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { clamp, resetEpochSeconds } from "../core/limits.js";
5
+
6
+ function selectAntigravityLimits(quotas, model, now) {
7
+ const modelName = typeof model === "string" ? model : model?.id || model?.display_name || "";
8
+ const family = /claude|opus|sonnet|haiku|gpt|codex|openai/i.test(modelName)
9
+ ? /^(?:3p)(?:[-_]|$)|claude|gpt|openai/i : /gemini/i;
10
+ const normalized = quotas.map(quota => {
11
+ const seconds = resetEpochSeconds(quota.resetsAt);
12
+ const resetsAt = seconds > 0 ? new Date(seconds * 1000).toISOString() : null;
13
+ return { ...quota, resetsAt, resetPassed: resetsAt !== null && seconds <= now / 1000 };
14
+ });
15
+ const matching = normalized.filter(quota => family.test(quota.id));
16
+ // Unrecognized bucket names can be used, but never borrow another model family's quota.
17
+ const candidates = (matching.length ? matching : normalized.filter(quota => !/gemini|^3p(?:[-_]|$)|claude|gpt|openai/i.test(quota.id)))
18
+ .filter(quota => typeof quota.remainingPercent === "number")
19
+ .sort((a, b) => a.remainingPercent - b.remainingPercent || a.id.localeCompare(b.id));
20
+ // Periods have fixed meanings in every renderer: primary is 5h, secondary is 7d.
21
+ const primary = candidates.find(quota => quota.windowMinutes === 300)
22
+ ?? candidates.find(quota => !quota.windowMinutes) ?? null;
23
+ const secondary = candidates.find(quota => quota.windowMinutes === 10080 && !quota.resetPassed) ?? null;
24
+ const reading = primary ?? secondary;
25
+ const ok = Boolean(reading && !reading.resetPassed);
26
+ return { quotas: normalized, primary, secondary, ok,
27
+ percentRemaining: ok ? reading.remainingPercent : null,
28
+ percentUsed: ok ? reading.usedPercent : null,
29
+ error: ok ? null : reading?.resetPassed ? "Gemini quota reset; waiting for a fresh payload" : "Gemini quota percentage unavailable" };
30
+ }
31
+
32
+ // https://antigravity.google/docs/cli/statusline
33
+ // agy invokes a shell command, sends JSON on stdin, and accepts ANSI/multiline stdout.
34
+ export function normalizeAntigravityPayload(input, now = Date.now()) {
35
+ const quotas = Object.entries(input.quota || {}).flatMap(([id, value]) => {
36
+ if (!value || typeof value !== "object" || value.disabled === true) return [];
37
+ const fraction = value.remaining_fraction;
38
+ const remainingPercent = typeof fraction === "number" && Number.isFinite(fraction)
39
+ ? clamp(Math.round(fraction * 100), 0, 100) : null;
40
+ const resetTime = resetEpochSeconds(value.reset_time);
41
+ const resetSeconds = resetTime > 0 ? resetTime
42
+ : typeof value.reset_in_seconds === "number" && Number.isFinite(value.reset_in_seconds) && value.reset_in_seconds > 0
43
+ ? Math.floor(now / 1000 + value.reset_in_seconds) : null;
44
+ return [{ id, remainingPercent, remainingAmount: value.remaining_amount ?? null,
45
+ usedPercent: remainingPercent === null ? null : 100 - remainingPercent,
46
+ windowMinutes: /weekly|7d/i.test(id) ? 10080 : /5h|five.hour/i.test(id) ? 300 : null,
47
+ resetsAt: resetSeconds === null ? null : new Date(resetSeconds * 1000).toISOString(),
48
+ resetPassed: resetSeconds !== null && resetSeconds <= now / 1000 }];
49
+ });
50
+ return {
51
+ provider: "antigravity", sourceType: "statusline", timestamp: new Date(now).toISOString(),
52
+ sessionId: input.session_id || input.conversation_id || null,
53
+ model: typeof input.model === "object" && input.model ? { id: input.model.id, display_name: input.model.display_name, effort: input.model.effort } : input.model || "",
54
+ workspace: input.workspace ? { current_dir: input.workspace.current_dir, project_dir: input.workspace.project_dir } : null,
55
+ contextWindow: input.context_window ? {
56
+ remainingPercentage: input.context_window.remaining_percentage,
57
+ usedPercentage: input.context_window.used_percentage
58
+ } : null,
59
+ agentState: input.agent_state || null,
60
+ ...selectAntigravityLimits(quotas, input.model, now)
61
+ };
62
+ }
63
+
64
+ export function antigravityStatuslineCommand(scriptPath, flags, shellArg, platform = process.platform) {
65
+ if (platform === "win32") {
66
+ // agy's cmd /c invocation applies Windows argv escaping to the whole
67
+ // command. Embedded path quotes then reach Node as literal quotes. Keep
68
+ // the quoted script path out of the shell arguments and decode it inside
69
+ // Node instead. The plain marker
70
+ // preserves managed-hook detection and the normal CLI argv positions.
71
+ const loader = `process.argv[1]=${JSON.stringify(scriptPath)};import(require('node:url').pathToFileURL(process.argv[1]).href).catch(error=>{console.error(error);process.exitCode=1});`;
72
+ const encoded = Buffer.from(loader, "utf8").toString("base64");
73
+ return ["node", "-e", `eval(Buffer.from('${encoded}','base64').toString())`, "ai-battery.js", "capture-antigravity", ...flags].join(" ");
74
+ }
75
+ return [shellArg(process.execPath), shellArg(scriptPath), "capture-antigravity", ...flags].join(" ");
76
+ }
77
+
78
+ export function createAntigravityIntegration({ homePath, stateDir, readJson, readUserJsonObject, readConfig, writeConfig, writeJsonAtomic, samePath, shellArg, scriptDir, isProviderRunning }) {
79
+ const settingsPath = () => homePath(".gemini", "antigravity-cli", "settings.json");
80
+ const cachePath = () => path.join(stateDir(), "antigravity-statusline.json");
81
+ const backupKey = "antigravityStatusLineBackup";
82
+ const managed = value => typeof value?.command === "string" && value.command.includes("ai-battery.js") && value.command.includes("capture-antigravity");
83
+
84
+ function install(args = {}) {
85
+ const target = settingsPath();
86
+ const settings = readUserJsonObject(target, `Gemini settings at ${target}`);
87
+ if (!settings.ok) return { ok: false, settingsPath: target, error: settings.error };
88
+ const config = readConfig({ strict: true });
89
+ const backup = config[backupKey];
90
+ if (backup?.settingsPath && !samePath(backup.settingsPath, target)) {
91
+ return { ok: false, settingsPath: target, error: `Gemini recovery record belongs to ${backup.settingsPath}; settings preserved` };
92
+ }
93
+ const existing = settings.value.statusLine;
94
+ if (existing?.command && !managed(existing) && !args.force) {
95
+ return { settingsPath: target, skipped: true, reason: "Existing Gemini statusLine preserved. Replace: ai-battery setup gemini --force" };
96
+ }
97
+ const flags = ["--muted", "--left-padding", "1"];
98
+ if (args.header === false) flags.push("--no-header");
99
+ if (args.usageRow === false) flags.push("--no-usage-row");
100
+ if (args.usageRow === true) flags.push("--usage-row");
101
+ const command = antigravityStatuslineCommand(path.join(scriptDir(), "ai-battery.js"), flags, shellArg);
102
+ const next = { type: "command", command, padding: 0, enabled: true, stack_with_default: false };
103
+ if (!backup) config[backupKey] = {
104
+ settingsPath: target, settingsExisted: settings.exists, mode: settings.mode,
105
+ hadStatusLine: Boolean(Object.hasOwn(settings.value, "statusLine") && !managed(existing)),
106
+ statusLine: managed(existing) ? null : existing ?? null, managedStatusLines: []
107
+ };
108
+ const record = config[backupKey];
109
+ record.managedStatusLines ??= [];
110
+ if (!record.managedStatusLines.some(value => isDeepStrictEqual(value, next))) record.managedStatusLines.push(next);
111
+ // Save recovery before changing the settings file.
112
+ writeConfig(config);
113
+ writeJsonAtomic(target, { ...settings.value, statusLine: next }, settings.mode ?? 0o600);
114
+ return { ok: true, changed: !isDeepStrictEqual(existing, next), settingsPath: target, command: next.command, backedUp: !backup };
115
+ }
116
+
117
+ function uninstall() {
118
+ const target = settingsPath();
119
+ const settings = readUserJsonObject(target, `Gemini settings at ${target}`);
120
+ if (!settings.ok) return { settingsPath: target, error: settings.error };
121
+ const config = readConfig({ strict: true });
122
+ const backup = config[backupKey];
123
+ if (backup?.settingsPath && !samePath(backup.settingsPath, target)) return { settingsPath: target, retainedBackup: true, error: "Gemini recovery record belongs to a different HOME" };
124
+ const existing = settings.value.statusLine;
125
+ const restored = backup && (backup.hadStatusLine ? isDeepStrictEqual(existing, backup.statusLine) : !Object.hasOwn(settings.value, "statusLine"));
126
+ if (restored) {
127
+ config[backupKey] = null; writeConfig(config);
128
+ return { settingsPath: target, changed: false, alreadyRestored: true };
129
+ }
130
+ const owned = backup ? backup.managedStatusLines.some(value => isDeepStrictEqual(value, existing)) : managed(existing);
131
+ if (!owned) return { settingsPath: target, changed: false, skipped: Boolean(backup), retainedBackup: Boolean(backup), reason: "Gemini settings changed; settings and recovery record preserved" };
132
+ if (backup?.settingsExisted === false && Object.keys(settings.value).length === 1) fs.rmSync(target, { force: true });
133
+ else {
134
+ const next = { ...settings.value };
135
+ if (backup?.hadStatusLine) next.statusLine = backup.statusLine;
136
+ else delete next.statusLine;
137
+ writeJsonAtomic(target, next, backup?.mode ?? settings.mode ?? 0o600);
138
+ }
139
+ config[backupKey] = null; writeConfig(config);
140
+ return { settingsPath: target, changed: true, restored: Boolean(backup?.hadStatusLine || backup?.settingsExisted) };
141
+ }
142
+
143
+ function capture(input) {
144
+ const snapshot = normalizeAntigravityPayload(input);
145
+ // Deliberately exclude account email and transcript contents from the cache.
146
+ writeJsonAtomic(cachePath(), snapshot);
147
+ return snapshot;
148
+ }
149
+
150
+ function read(options = {}) {
151
+ const cached = readJson(cachePath());
152
+ const running = options.runningOverride ?? isProviderRunning("antigravity");
153
+ 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) };
156
+ return snapshot;
157
+ }
158
+
159
+ function diagnose() {
160
+ const settings = readUserJsonObject(settingsPath(), "Gemini settings");
161
+ const statusLine = settings.value?.statusLine;
162
+ return { providerEnabled: readConfig().providers.antigravity !== false, settingsPath: settingsPath(),
163
+ configured: Boolean(statusLine), managed: managed(statusLine), enabled: statusLine?.enabled !== false,
164
+ cachePath: cachePath(), statuslineCache: readJson(cachePath())?.provider === "antigravity", error: settings.error || null };
165
+ }
166
+ return { install, uninstall, capture, read, diagnose, cachePath, settingsPath };
167
+ }
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "ai-battery",
3
- "version": "0.1.29",
4
- "description": "Tiny terminal battery meter for local Codex and Claude Code usage.",
3
+ "version": "0.2.0",
4
+ "description": "Tiny terminal battery meter for local Codex, Claude Code and Gemini CLI usage.",
5
5
  "type": "module",
6
6
  "keywords": [
7
7
  "ai",
8
8
  "battery",
9
9
  "codex",
10
10
  "claude",
11
+ "antigravity",
11
12
  "statusline",
12
13
  "tui",
13
14
  "usage"
@@ -43,6 +44,7 @@
43
44
  "vendor/rowpty/RowPty.cs",
44
45
  "docs/*.svg",
45
46
  "docs/RELEASING.md",
47
+ "docs/REFERENCE.md",
46
48
  "docs/SETUP-REGRESSION.md",
47
49
  "README.md"
48
50
  ],
package/lib/README.md DELETED
@@ -1,23 +0,0 @@
1
- # Internal module layout
2
-
3
- The bin directory contains stable executable entrypoints only. Runtime
4
- implementation belongs under lib:
5
-
6
- - core: provider-independent usage normalization and terminal formatting.
7
- - hud: desktop HUD dispatch and shared snapshot prefetch.
8
- - platforms/runtime.js: cross-platform environment detection helpers.
9
- - platforms/process-scanner.js: Windows, WSL, macOS, and Linux process scans.
10
- - platforms/macos: macOS menu bar integration.
11
- - platforms/linux: GJS StatusNotifierItem and native detail menu, sharing the
12
- macOS panel artwork; GNOME display extension sharing the full-size macOS
13
- detail image, Node snapshot worker, and owned XDG/extension setup and cleanup.
14
- - platforms/windows: Windows Codex runner, compositor, PATH integration, and
15
- HUD launcher.
16
- - platforms/windows/hud: WinForms modules. dock.ps1 owns terminal attachment
17
- and AppBar behavior; windowing.ps1 owns desktop placement; snapshot.ps1 owns
18
- refresh; rendering.ps1 and controls.ps1 own UI drawing and updates;
19
- native.ps1 contains Win32 interop.
20
-
21
- Keep public command paths and test imports pointed at bin. Those entrypoints
22
- re-export implementation APIs so internal modules can move without breaking
23
- installed commands or downstream imports.