ai-battery 0.1.28 → 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.
@@ -1,12 +1,19 @@
1
- // Follow the same locale order as Tidy; untranslated languages use English.
2
- export function cliLanguage(env = process.env, defaultLocale = Intl.DateTimeFormat().resolvedOptions().locale) {
3
- const languages = env.LANGUAGE?.trim()
1
+ import { systemUiLocale } from "../platforms/ui-language.js";
2
+
3
+ // Honor language preferences; neutral C/POSIX locales defer to the system UI language.
4
+ export function cliLanguage(env = process.env, defaultLocale) {
5
+ const explicitLanguage = Boolean(env.LANGUAGE?.trim());
6
+ const languages = explicitLanguage
4
7
  ? env.LANGUAGE.split(":")
5
- : [env.LC_ALL || env.LC_MESSAGES || env.LANG || defaultLocale];
8
+ : [env.LC_ALL || env.LC_MESSAGES || env.LANG || defaultLocale || systemUiLocale()];
6
9
  for (const language of languages) {
7
10
  const base = language.trim().toLowerCase().split(/[_@.\-]/)[0];
8
11
  if (base === "ko") return "ko";
9
- if (["en", "c", "posix"].includes(base)) return "en";
12
+ if (base === "en") return "en";
13
+ if (["c", "posix"].includes(base)) {
14
+ const locale = explicitLanguage ? "en" : defaultLocale || systemUiLocale();
15
+ return /^ko(?:[_@.\-]|$)/i.test(locale) ? "ko" : "en";
16
+ }
10
17
  }
11
18
  return "en";
12
19
  }
@@ -44,7 +51,7 @@ export function helpText(command = "", { env = process.env, platform = process.p
44
51
  const options = (items) => `${t("Options", "옵션")}:\n${rows(items)}`;
45
52
  const examples = (lines) => `${t("Examples", "예시")}:\n${lines.map((line) => ` ${line}`).join("\n")}`;
46
53
  const json = ["--json", "Print JSON", "JSON으로 출력"];
47
- const providers = ["-p, --provider all|codex|claude", "Provider to show (default: all)", "표시할 도구 (기본: all)"];
54
+ const providers = ["-p, --provider all|codex|claude|gemini", "Provider to show (default: all)", "표시할 도구 (기본: all)"];
48
55
  const colorOptions = [
49
56
  ["--ansi", "Use ANSI colors", "ANSI 색상 사용"],
50
57
  ["--muted", "Use muted colors", "차분한 색상 사용"],
@@ -61,12 +68,12 @@ export function helpText(command = "", { env = process.env, platform = process.p
61
68
  barWidth,
62
69
  ["--max-width N", "Limit output width to N columns", "출력 너비를 N칸으로 제한"],
63
70
  leftPadding,
64
- ["--active-provider codex|claude", "Highlight the active tool", "사용 중인 도구 강조"],
71
+ ["--active-provider codex|claude|gemini", "Highlight the active tool", "사용 중인 도구 강조"],
65
72
  showPaths,
66
73
  ["--tmux", "Use tmux status bar colors", "tmux 상태 표시줄 색상 사용"]
67
74
  ];
68
75
  const headerOptions = [
69
- ["--no-header", "Hide Claude's extra header", "Claude 추가 헤더 숨기기"],
76
+ ["--no-header", "Hide the statusline header", "상태 표시줄 헤더 숨기기"],
70
77
  ["--usage-row", "Always show the usage row", "사용량 행 항상 표시"],
71
78
  ["--no-usage-row", "Hide the duplicate usage row", "중복 사용량 행 숨기기"]
72
79
  ];
@@ -80,21 +87,22 @@ export function helpText(command = "", { env = process.env, platform = process.p
80
87
  if (command === "setup" || command === "install-claude-statusline") {
81
88
  const legacy = command === "install-claude-statusline";
82
89
  return [
83
- usage(legacy ? `${command} [--force]` : "setup [codex|claude|tmux|all] [options]"),
90
+ usage(legacy ? `${command} [--force]` : "setup [codex|claude|gemini|tmux|all] [options]"),
84
91
  legacy ? t("Configure Claude Code's usage status line.", "Claude Code 상태 표시줄에 사용량을 연결합니다.")
85
- : t("Enable Codex and Claude Code terminal usage display. Specify tmux separately.", "Codex와 Claude Code의 터미널 사용량 표시를 연결합니다. tmux는 별도로 지정합니다."),
92
+ : t("Configure all tools, including Codex's built-in first row. Specify a tool for individual setup; tmux is separate.", "기본적으로 모든 도구와 Codex 내장 첫 행을 설정합니다. 도구를 지정하면 해당 도구만 설정하며 tmux는 별도로 지정합니다."),
86
93
  options([
87
- ["--force", "Replace an existing Claude statusLine", "기존 Claude 상태 표시줄 교체"],
94
+ ["--force", "Replace an existing hook with a restorable backup", "기존 상태 표시줄을 백업 후 교체"],
88
95
  ...(!legacy ? [
89
96
  ["--wrap-codex", "Enable Codex terminal display (default)", "Codex 터미널 표시 연결 (기본)"],
90
- ["--no-wrap-codex", "Skip Codex wrapper setup", "Codex wrapper 설정 생략"],
91
- ["--configure-codex-statusline", "Configure Codex's built-in status line", "Codex 내장 상태 표시줄 설정"]
97
+ ["--no-wrap-codex", "Skip only the Codex wrapper, keeping first-row setup", "Codex wrapper만 생략 (첫 행은 설정)"]
92
98
  ] : []),
99
+ ...headerOptions,
100
+ ["--provider-order LIST", "Tool order, comma separated", "도구 표시 순서 (쉼표로 구분)"],
93
101
  json
94
102
  ]),
95
103
  legacy ? t("Restore settings: ai-battery reset claude", "설정 복원: ai-battery reset claude")
96
- : t("The original Codex executable and settings are preserved.\nRestore settings: ai-battery reset", "Codex 원본 실행 파일과 설정은 유지합니다.\n설정 복원: ai-battery reset"),
97
- examples(legacy ? [`ai-battery ${command}`] : ["ai-battery setup tmux"])
104
+ : t("Previous settings are saved for restore. Gemini aliases: antigravity, agy.\nRestore settings: ai-battery reset", "이전 설정은 복구용으로 저장합니다. gemini 호환 명령: antigravity, agy.\n설정 복원: ai-battery reset"),
105
+ examples(legacy ? [`ai-battery ${command}`] : ["ai-battery setup", "ai-battery setup gemini", "ai-battery setup tmux"])
98
106
  ].join("\n\n");
99
107
  }
100
108
  if (command === "uninstall-claude-statusline") {
@@ -102,24 +110,30 @@ export function helpText(command = "", { env = process.env, platform = process.p
102
110
  options([json]), t("Also available as: ai-battery reset claude", "같은 작업: ai-battery reset claude")].join("\n\n");
103
111
  }
104
112
  if (["reset", "teardown", "uninstall"].includes(command)) {
105
- const syntax = `${command} [codex|claude|hud|tmux|all]`;
113
+ const syntax = `${command} [codex|claude|gemini|hud|tmux|all]`;
106
114
  return [usage(syntax), resetNote, options([json, ["--silent", "Hide completion messages", "완료 메시지 숨기기"]]),
107
115
  t("Compatibility aliases: reset settings, reset config, teardown, uninstall", "호환 명령: reset settings, reset config, teardown, uninstall"),
108
116
  examples(["ai-battery reset", "ai-battery reset claude"])].join("\n\n");
109
117
  }
110
118
  if (command === "on" || command === "off") {
111
- return [usage(`${command} [codex|claude|all]`), command === "on"
119
+ return [usage(`${command} [codex|claude|gemini|all]`), command === "on"
112
120
  ? t("Show the selected tools (default: all).", "선택한 도구의 사용량을 표시합니다. 기본 대상은 all입니다.")
113
121
  : t("Hide the selected tools (default: all).", "선택한 도구의 사용량을 숨깁니다. 기본 대상은 all입니다."),
114
122
  options([json]), t("Changes visibility only. Configure terminal integration with ai-battery setup.", "표시 설정만 변경합니다. 터미널 연결: ai-battery setup"), examples([`ai-battery ${command} codex`])].join("\n\n");
115
123
  }
124
+ if (command === "config") {
125
+ return [usage("config [options]"), t("Choose visible tools and their order in the inline editor shared by TUI and HUD.", "인라인 설정창에서 TUI와 HUD에 표시할 도구와 순서를 함께 설정합니다."),
126
+ t("↑↓ select · ←→ reorder · Space show/hide · Enter save · Esc cancel", "↑↓ 선택 · ←→ 순서 이동 · Space 표시/숨김 · Enter 저장 · Esc 취소"),
127
+ options([["--provider-order LIST", "Set order directly, comma separated", "순서를 명령으로 지정 (쉼표로 구분)"], json]),
128
+ examples(["ai-battery config", "ai-battery config --provider-order antigravity,codex,claude"])].join("\n\n");
129
+ }
116
130
  if (command === "doctor") {
117
131
  return [usage("doctor [--json]"), t("Check installation, integrations and available updates.", "설치 상태, 연동 설정, 업데이트를 확인합니다."), options([json])].join("\n\n");
118
132
  }
119
- if (command === "capture-claude") {
120
- return [usage("capture-claude [options]"), t("Read Claude statusLine JSON from stdin and update the usage cache.", "표준 입력으로 Claude 상태 표시줄 JSON을 받아 사용량 캐시를 갱신합니다."),
133
+ if (command === "capture-claude" || command === "capture-antigravity") {
134
+ return [usage(`${command} [options]`), t("Read statusLine JSON from stdin and update the usage cache.", "표준 입력으로 상태 표시줄 JSON을 받아 사용량 캐시를 갱신합니다."),
121
135
  options([providers, ...colorOptions, barWidth, leftPadding, showPaths, ...headerOptions,
122
- ...(platform === "win32" ? [["--attach-hud", "Attach the Windows terminal HUD", "Windows 터미널에 HUD 연결"]] : []),
136
+ ...(platform === "win32" && command === "capture-claude" ? [["--attach-hud", "Attach the Windows terminal HUD", "Windows 터미널에 HUD 연결"]] : []),
123
137
  ["--silent", "Update the cache without output", "출력 없이 캐시 갱신"]])].join("\n\n");
124
138
  }
125
139
  if (command === "hud") {
@@ -147,18 +161,18 @@ export function helpText(command = "", { env = process.env, platform = process.p
147
161
  ].join("\n\n");
148
162
  }
149
163
  return [
150
- t("AI Battery · Codex and Claude Code usage", "AI Battery · Codex와 Claude Code 사용량"),
164
+ t("AI Battery · Codex, Claude Code and Gemini usage", "AI Battery · Codex·Claude Code·Gemini 사용량"),
151
165
  usage("[command] [options]"),
152
166
  `${t("Commands", "명령")}:\n${rows([
153
- ["setup", "Configure usage display", "사용량 표시 연동"],
167
+ ["setup", "Configure all tools", "모든 도구 설정"],
154
168
  ["hud", "Manage the desktop usage display", "데스크톱 사용량 표시 관리"],
155
- ["on / off", "Show or hide a tool", "도구별 사용량 표시 켜기·끄기"],
169
+ ["config", "Choose visible tools and display order", "표시할 도구와 순서 설정"],
156
170
  ["reset", "Restore settings and clean generated files", "설정 복원 및 생성 파일 정리"],
157
171
  ["doctor", "Check installation and integrations", "설치 및 연동 상태 진단"]
158
172
  ])}`,
159
173
  options([["-w, --watch [seconds]", "Refresh periodically (default: 10s)", "주기적으로 갱신 (기본: 10초)"],
160
174
  ["-v, --version", "Show version", "버전 확인"], ["-h, --help", "Show help", "도움말 보기"]]),
161
- examples(["ai-battery setup tmux", "ai-battery hud", "ai-battery on codex"]),
175
+ examples(["ai-battery setup", "ai-battery setup tmux", "ai-battery hud", "ai-battery config"]),
162
176
  t("More help: ai-battery <command> --help", "상세 도움말: ai-battery <명령> --help")
163
177
  ].join("\n\n");
164
178
  }
@@ -24,7 +24,13 @@ export function formatClaudeResult(result, { removing = false, env = process.env
24
24
 
25
25
  export function formatSetupResult(result, { failed = false, platform = process.platform, reloadCommand, restartNote, env = process.env } = {}) {
26
26
  const o = output(env);
27
- const { codex, claude, tmux } = result;
27
+ const { codex, claude, antigravity, tmux } = result;
28
+ if (antigravity) {
29
+ o.add(`Gemini statusLine: ${antigravity.error ? "error" : antigravity.skipped ? "unchanged" : "ready"} · ${antigravity.settingsPath}`);
30
+ o.error("Error", antigravity.error);
31
+ o.note(antigravity.reason);
32
+ if (!antigravity.error && !antigravity.skipped) o.add(o.t("Restart agy to apply.", "agy를 다시 실행하면 적용됩니다."));
33
+ }
28
34
  if (claude) {
29
35
  o.add(formatClaudeResult(claude, { env }));
30
36
  if (!claude.skipped && !claude.error) o.add(o.t("Restart Claude Code to apply.", "Claude Code를 다시 실행하면 적용됩니다."));
@@ -113,6 +119,16 @@ export function formatDoctorResult(result, { env = process.env } = {}) {
113
119
  if (claudeDisplay.action) o.add(` ${o.t("Next", "다음")}: ${messageText(claudeDisplay.action, env)}`);
114
120
  o.add(` statusLine: ${claude.statusLine.error ? "error" : claude.statusLine.managed ? "ready" : claude.statusLine.configured ? "external" : "not configured"}`);
115
121
  o.add(` Cache: ${claude.statuslineCache ? "ready" : "waiting"}`);
122
+ if (result.antigravity) {
123
+ const agy = result.antigravity;
124
+ o.lines.push("");
125
+ o.add("Gemini:");
126
+ o.add(` Visibility: ${agy.providerEnabled ? "on" : "off"}`);
127
+ o.add(` statusLine: ${agy.error ? "error" : agy.managed ? agy.enabled ? "ready" : "disabled" : agy.configured ? "external" : "not configured"}`);
128
+ o.add(` Cache: ${agy.statuslineCache ? "ready" : "waiting"}`);
129
+ o.error(" Error", agy.error);
130
+ if (!agy.managed) o.add(" Setup: ai-battery setup antigravity");
131
+ }
116
132
  if (result.tmux) {
117
133
  o.lines.push("");
118
134
  o.add(`tmux: ${result.tmux.error ? "error" : result.tmux.configured ? result.tmux.insideTmux ? "configured · in session" : "configured · outside session" : "not configured"}`);
@@ -121,7 +137,7 @@ export function formatDoctorResult(result, { env = process.env } = {}) {
121
137
  else if (!result.tmux.configured && !codex.wrapperInstalled) o.add(o.t(" Terminal usage: ai-battery setup tmux", " 터미널 사용량 표시: ai-battery setup tmux"));
122
138
  }
123
139
  const recovery = battery.recovery;
124
- const backups = [recovery.codexWrapper && "Codex wrapper", recovery.codexStatusLine && "Codex status_line", recovery.claudeStatusLine && "Claude statusLine"].filter(Boolean);
140
+ const backups = [recovery.codexWrapper && "Codex wrapper", recovery.codexStatusLine && "Codex status_line", recovery.claudeStatusLine && "Claude statusLine", recovery.antigravityStatusLine && "Gemini statusLine"].filter(Boolean);
125
141
  if (backups.length) o.add(`Recovery: ${backups.join(", ")}`);
126
142
  const notes = [...codex.notes, ...claude.notes].filter((note) =>
127
143
  ![
@@ -140,7 +156,7 @@ export function formatDoctorResult(result, { env = process.env } = {}) {
140
156
 
141
157
  export function formatResetResult(result, { failed = false, wrapped = false, platform = process.platform, env = process.env } = {}) {
142
158
  const o = output(env);
143
- const { codex, claude, hud, artifacts } = result.results;
159
+ const { codex, claude, antigravity, hud, artifacts } = result.results;
144
160
  if (codex) {
145
161
  const restored = codex.restoredWrappers || [];
146
162
  const removed = codex.removedWrappers || [];
@@ -160,6 +176,10 @@ export function formatResetResult(result, { failed = false, wrapped = false, pla
160
176
  }
161
177
  }
162
178
  if (claude) o.add(formatClaudeResult(claude, { removing: true, env }));
179
+ if (antigravity) {
180
+ o.add(`Gemini statusLine: ${antigravity.error ? "error" : antigravity.retainedBackup ? "preserved" : antigravity.changed ? antigravity.restored ? "restored" : "removed" : "unchanged"}`);
181
+ o.error("Error", antigravity.error); o.note(antigravity.reason);
182
+ }
163
183
  if (hud) {
164
184
  if (hud.error) o.error("HUD", hud.error);
165
185
  else if (hud.skipped) o.add("HUD: skipped");
@@ -172,7 +192,7 @@ export function formatResetResult(result, { failed = false, wrapped = false, pla
172
192
  }
173
193
  }
174
194
  for (const [name, item] of Object.entries(result.results)) {
175
- if (["codex", "claude", "hud", "artifacts"].includes(name)) continue;
195
+ if (["codex", "claude", "antigravity", "hud", "artifacts"].includes(name)) continue;
176
196
  if (!item.error && !item.errors?.length && item.changed) o.add(`${name}: restored`);
177
197
  o.error(name, item.error);
178
198
  for (const error of item.errors || []) o.error(`${name} · ${error.path}`, error.error);
@@ -0,0 +1,135 @@
1
+ import { clearScreenDown, cursorTo, emitKeypressEvents, moveCursor } from "node:readline";
2
+ import { PROVIDERS, normalizeOrder, providerLabel } from "./display-config.js";
3
+ import { cliLanguage } from "./cli-help.js";
4
+ import { truncateMiddleVisible, visibleWidth } from "./terminal.js";
5
+
6
+ export function canEditConfig(input = process.stdin, output = process.stdout) {
7
+ return Boolean(input.isTTY && output.isTTY && typeof input.setRawMode === "function");
8
+ }
9
+
10
+ export function editDisplayConfig(initialConfig, { input = process.stdin, output = process.stdout, language = cliLanguage(), color = !Object.hasOwn(process.env, "NO_COLOR") } = {}) {
11
+ const order = normalizeOrder(initialConfig.providerOrder, PROVIDERS);
12
+ const providers = Object.fromEntries(PROVIDERS.map(provider => [provider, initialConfig.providers?.[provider] !== false]));
13
+ const changedProviders = new Set();
14
+ const t = (english, korean) => language === "ko" ? korean : english;
15
+ const wasRaw = Boolean(input.isRaw);
16
+ const wasFlowing = input.readableFlowing;
17
+ let selected = 0;
18
+ let drawnWidths = [];
19
+ let finished = false;
20
+
21
+ return new Promise((resolve, reject) => {
22
+ const erase = () => {
23
+ if (!drawnWidths.length) return;
24
+ // Resizing reflows the previous frame before Node receives `resize`.
25
+ // The cursor stays at column zero of its last logical line, so count
26
+ // every physical row above it using the terminal's current width.
27
+ const columns = Math.max(1, Number(output.columns) || 80);
28
+ const rowsAbove = drawnWidths.slice(0, -1).reduce((rows, width) => rows + Math.max(1, Math.ceil(width / columns)), 0);
29
+ cursorTo(output, 0);
30
+ moveCursor(output, 0, -rowsAbove);
31
+ clearScreenDown(output);
32
+ drawnWidths = [];
33
+ };
34
+
35
+ const draw = () => {
36
+ const availableWidth = Math.max(1, (Number(output.columns) || 80) - 1);
37
+ const width = Math.min(64, availableWidth);
38
+ const height = Number(output.rows) || 24;
39
+ const fit = text => truncateMiddleVisible(text, width);
40
+ const arrows = t("↑↓ select · ←→ move", "↑↓ 선택 · ←→ 순서 이동");
41
+ const toggle = t("Space show/hide", "Space 표시/숨김");
42
+ const confirm = t("Enter save · Esc cancel", "Enter 저장 · Esc 취소");
43
+ const fullHelp = `${arrows} · ${toggle} · ${confirm}`;
44
+ const compactHelp = t("↑↓ select · ←→ move · Space toggle · Enter save · Esc cancel", "↑↓ 선택 · ←→ 순서 · Space 표시 · Enter 저장 · Esc 취소");
45
+ const help = [fullHelp, compactHelp, "↑↓ · ←→ · Space · Enter · Esc"].find(text => visibleWidth(text) <= availableWidth)
46
+ || truncateMiddleVisible("↑↓ ←→ Space Enter Esc", availableWidth);
47
+ const items = order.map((provider, index) => {
48
+ const text = `${index === selected ? "›" : " "} ${index + 1}. [${providers[provider] ? "x" : " "}] ${providerLabel(provider)}`;
49
+ const inside = truncateMiddleVisible(text, Math.max(1, width - 4));
50
+ const padded = inside + " ".repeat(Math.max(0, width - 4 - visibleWidth(inside)));
51
+ const line = width >= 24 && height >= 10 ? `│ ${padded} │` : text;
52
+ return index === selected && color ? `\x1b[36m${line}\x1b[0m` : line;
53
+ });
54
+ let lines;
55
+ const preview = order.filter(provider => providers[provider]).map(providerLabel).join(" → ") || t("All hidden", "모두 숨김");
56
+ if (width >= 24 && height >= 10) {
57
+ const title = truncateMiddleVisible(` ${t("Tools & display order", "표시 도구·순서")} `, width - 3);
58
+ lines = [
59
+ `╭─${title}${"─".repeat(Math.max(0, width - 3 - visibleWidth(title)))}╮`,
60
+ ...items,
61
+ `╰${"─".repeat(width - 2)}╯`,
62
+ fit(`${t("Preview", "미리보기")}: ${preview}`),
63
+ help
64
+ ];
65
+ } else if (height >= 8) {
66
+ lines = [fit(t("Tools & display order", "표시 도구·순서")), ...items.map(fit), help];
67
+ } else {
68
+ lines = [fit(`${selected + 1}/${order.length} [${providers[order[selected]] ? "x" : " "}] ${providerLabel(order[selected])}`), help].slice(0, Math.max(1, height));
69
+ }
70
+ erase();
71
+ output.write(`${lines.join("\r\n")}\r`);
72
+ drawnWidths = lines.map(visibleWidth);
73
+ };
74
+
75
+ const finish = (value, error) => {
76
+ if (finished) return;
77
+ finished = true;
78
+ input.removeListener("keypress", onKey);
79
+ input.removeListener("end", onEnd);
80
+ input.removeListener("error", onError);
81
+ output.removeListener("resize", onResize);
82
+ process.removeListener("SIGINT", onInterrupt);
83
+ process.removeListener("SIGTERM", onTerminate);
84
+ process.removeListener("SIGHUP", onHangup);
85
+ try { input.setRawMode(wasRaw); } catch { /* The terminal may have closed. */ }
86
+ if (!wasFlowing) input.pause();
87
+ try { erase(); output.write("\x1b[?25h"); } catch { /* Restore input even after output failure. */ }
88
+ if (error) reject(error);
89
+ else resolve(value);
90
+ };
91
+ const onEnd = () => finish(null);
92
+ const onError = error => finish(null, error);
93
+ const onResize = () => { try { draw(); } catch (error) { finish(null, error); } };
94
+ const onInterrupt = () => { process.exitCode = 130; finish(null); };
95
+ const onTerminate = () => { process.exitCode = 143; finish(null); };
96
+ const onHangup = () => { process.exitCode = 129; finish(null); };
97
+ const onKey = (_text, key = {}) => {
98
+ if (key.name === "escape") return finish(null);
99
+ if (key.ctrl && key.name === "c") return onInterrupt();
100
+ if (key.name === "return" || key.name === "enter") return finish({
101
+ providerOrder: [...order],
102
+ providerChanges: Object.fromEntries([...changedProviders].map(provider => [provider, providers[provider]]))
103
+ });
104
+ if ((key.name === "space" || _text === " ") && !key.ctrl && !key.meta) {
105
+ const provider = order[selected];
106
+ providers[provider] = !providers[provider];
107
+ changedProviders.add(provider);
108
+ }
109
+ else if (key.name === "up") selected = Math.max(0, selected - 1);
110
+ else if (key.name === "down") selected = Math.min(order.length - 1, selected + 1);
111
+ else if (key.name === "left" || key.name === "right") {
112
+ const target = selected + (key.name === "left" ? -1 : 1);
113
+ if (target < 0 || target >= order.length) return;
114
+ [order[selected], order[target]] = [order[target], order[selected]];
115
+ selected = target;
116
+ } else return;
117
+ onResize();
118
+ };
119
+
120
+ try {
121
+ emitKeypressEvents(input);
122
+ input.on("keypress", onKey);
123
+ input.once("end", onEnd);
124
+ input.once("error", onError);
125
+ output.on("resize", onResize);
126
+ process.on("SIGINT", onInterrupt);
127
+ process.on("SIGTERM", onTerminate);
128
+ process.on("SIGHUP", onHangup);
129
+ input.setRawMode(true);
130
+ input.resume();
131
+ output.write("\x1b[?25l");
132
+ draw();
133
+ } catch (error) { finish(null, error); }
134
+ });
135
+ }
@@ -0,0 +1,29 @@
1
+ export const PROVIDERS = ["codex", "claude", "antigravity"];
2
+ export const STATUS_LINE_ITEMS = ["model-with-reasoning", "current-dir", "git-branch", "branch-changes", "context-remaining"];
3
+
4
+ export function providerId(value) {
5
+ return value === "gemini" || value === "agy" ? "antigravity" : value;
6
+ }
7
+
8
+ export function normalizeOrder(value, defaults) {
9
+ if (!Array.isArray(value)) return [...defaults];
10
+ const selected = [...new Set(value.map(providerId).filter(item => defaults.includes(item)))];
11
+ return [...selected, ...defaults.filter(item => !selected.includes(item))];
12
+ }
13
+
14
+ export function parseOrder(value, choices, label) {
15
+ const items = String(value).split(",").map(item => providerId(item.trim()));
16
+ if (!items.length || items.some(item => !choices.includes(item)) || new Set(items).size !== items.length) {
17
+ throw new Error(`${label}: use unique comma-separated values from ${choices.join(", ")}`);
18
+ }
19
+ return normalizeOrder(items, choices);
20
+ }
21
+
22
+ export function orderResults(results, order) {
23
+ const providers = normalizeOrder(order, PROVIDERS);
24
+ return [...results].sort((a, b) => providers.indexOf(a.provider) - providers.indexOf(b.provider));
25
+ }
26
+
27
+ export function providerLabel(provider) {
28
+ return { codex: "Codex", claude: "Claude", antigravity: "Gemini", ai: "AI" }[provider] || provider;
29
+ }
@@ -0,0 +1,47 @@
1
+ import { execFileSync } from "node:child_process";
2
+
3
+ // Match Codex's committed branch diff against the default branch merge base.
4
+ // Only inspect local refs: status hooks must not block on network/auth prompts.
5
+ export function branchChanges(dir) {
6
+ if (!dir) return null;
7
+ const deadline = Date.now() + 900;
8
+ const git = args => {
9
+ const remaining = deadline - Date.now();
10
+ if (remaining <= 0) return null;
11
+ try {
12
+ return execFileSync("git", ["-C", dir, ...args], {
13
+ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"],
14
+ timeout: Math.min(250, remaining), maxBuffer: 4 * 1024 * 1024,
15
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" }
16
+ }).trim();
17
+ } catch { return null; }
18
+ };
19
+ const remotes = (git(["remote"]) || "").split(/\r?\n/).filter(Boolean);
20
+ remotes.sort((a, b) => (a === "origin" ? -1 : b === "origin" ? 1 : 0));
21
+ let base = null;
22
+ for (const remote of remotes) {
23
+ const ref = git(["symbolic-ref", "--quiet", `refs/remotes/${remote}/HEAD`]);
24
+ if (ref?.startsWith(`refs/remotes/${remote}/`) && git(["rev-parse", "--verify", "--quiet", ref])) {
25
+ base = ref;
26
+ break;
27
+ }
28
+ }
29
+ if (!base) {
30
+ for (const candidate of ["main", "master"]) {
31
+ const ref = `refs/heads/${candidate}`;
32
+ if (git(["rev-parse", "--verify", "--quiet", ref])) { base = ref; break; }
33
+ }
34
+ }
35
+ if (!base) return null;
36
+ const mergeBase = git(["merge-base", "HEAD", base]);
37
+ if (!mergeBase) return null;
38
+ const numstat = git(["diff", "--no-ext-diff", "--numstat", `${mergeBase}..HEAD`, "--"]);
39
+ if (numstat === null) return null;
40
+ let additions = 0, deletions = 0;
41
+ for (const line of numstat.split(/\r?\n/)) {
42
+ const [added, removed] = line.split("\t");
43
+ if (/^\d+$/.test(added)) additions += Number(added);
44
+ if (/^\d+$/.test(removed)) deletions += Number(removed);
45
+ }
46
+ return `+${additions} -${deletions}`;
47
+ }
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
 
5
- const STATE_FILES = /^(?:(?:codex-status|windows-processes|wsl-windows-processes|claude-rate-limit-hit)-scan-cache\.json|claude-statusline\.json|codex-account-usage\.json|windows-state-dir|hud-position\.json|hud-snapshot-[\w-]+\.json|linux-hud\.log|(?:tui|hud)-dock-(?:request|host)(?:-\d+)?\.json|macos-menu-(?:bar|detail)\.svg|codex-menu-bar-transparent\.png)(?:\.\d+(?:\.\d+)?(?:\.[a-z0-9]+)?\.tmp)?$/;
5
+ const STATE_FILES = /^(?:(?:codex-status|windows-processes|wsl-windows-processes|claude-rate-limit-hit)-scan-cache\.json|(?:claude|antigravity)-statusline\.json|codex-account-usage\.json|windows-state-dir|hud-position\.json|hud-snapshot-[\w-]+\.json|linux-hud\.log|(?:tui|hud)-dock-(?:request|host)(?:-\d+)?\.json|macos-menu-(?:bar|detail)\.svg|codex-menu-bar-transparent\.png)(?:\.\d+(?:\.\d+)?(?:\.[a-z0-9]+)?\.tmp)?$/;
6
6
  const HUD_FILES = new Set(["main.ps1", "controls.ps1", "dock.ps1", "native.ps1", "rendering.ps1", "snapshot.ps1", "windowing.ps1", "ai-battery-hud.ps1"]);
7
7
 
8
8
  function lstat(file) {
@@ -15,7 +15,7 @@ function readJson(file) {
15
15
 
16
16
  export function isBatteryConfig(value) {
17
17
  return Boolean(value && !Array.isArray(value) && value.version === 1
18
- && ["providers", "codexWrapper", "codexStatusLineBackup", "claudeStatusLineBackup"].some(key => Object.hasOwn(value, key)));
18
+ && ["providers", "codexWrapper", "codexStatusLineBackup", "claudeStatusLineBackup", "antigravityStatusLineBackup"].some(key => Object.hasOwn(value, key)));
19
19
  }
20
20
 
21
21
  function inside(file, root) {
@@ -53,7 +53,7 @@ export function cleanupBatteryArtifacts({ roots, home = os.homedir(), protectedR
53
53
  let owned = kind === "root" && STATE_FILES.test(entry.name);
54
54
  if (kind === "root" && entry.name === "config.json") {
55
55
  const config = readJson(file);
56
- owned = isBatteryConfig(config) && !config.codexWrapper && !config.codexStatusLineBackup && !config.claudeStatusLineBackup && !Object.keys(config.integrationFiles || {}).length;
56
+ owned = isBatteryConfig(config) && !config.codexWrapper && !config.codexStatusLineBackup && !config.claudeStatusLineBackup && !config.antigravityStatusLineBackup && !Object.keys(config.integrationFiles || {}).length;
57
57
  }
58
58
  if (["claude-statusline-sessions", "claude-hud-sessions"].includes(kind)) {
59
59
  owned = /^[\w-]+\.json(?:\.\d+\.tmp)?$/.test(entry.name)
@@ -1,7 +1,9 @@
1
1
  import Gio from "gi://Gio";
2
2
  import GLib from "gi://GLib";
3
+ import { gnomeHudUuid, legacyGnomeHudUuids } from "./gnome-uuid.js";
3
4
 
4
- const uuid = "ai-battery@hnode.dev";
5
+ const uuid = ARGV[1] || gnomeHudUuid;
6
+ if (![gnomeHudUuid, ...legacyGnomeHudUuids].includes(uuid)) throw new Error("Unsupported AI Battery extension UUID");
5
7
  const service = "org.gnome.Shell.Extensions";
6
8
  const object = "/org/gnome/Shell";
7
9
  function call(method, args = null, iface = service) {
@@ -22,9 +24,12 @@ if (info.available && ["enable", "disable"].includes(ARGV[0])) {
22
24
  const enable = ARGV[0] === "enable";
23
25
  if (!enable) info.accepted = call("DisableExtension", new GLib.Variant("(s)", [uuid]))[0];
24
26
  const settings = new Gio.Settings({ schema_id: "org.gnome.shell" });
27
+ // DisableExtension can leave the old UUID in disabled-extensions. Clean
28
+ // both identities when applying the new one, including after a partial move.
29
+ const identities = uuid === gnomeHudUuid ? [uuid, ...legacyGnomeHudUuids] : [uuid];
25
30
  for (const key of ["enabled-extensions", "disabled-extensions"]) {
26
31
  const previous = settings.get_strv(key);
27
- let next = previous.filter(value => value !== uuid);
32
+ let next = previous.filter(value => !identities.includes(value));
28
33
  if (enable && key === "enabled-extensions") next.push(uuid);
29
34
  if (next.join("\0") !== previous.join("\0") && !settings.set_strv(key, next)) throw new Error(`Could not update ${key}`);
30
35
  }
@@ -0,0 +1,3 @@
1
+ // Shared by Node and GJS; keep extension identity independent of either runtime.
2
+ export const gnomeHudUuid = "ai-battery@hnode";
3
+ export const legacyGnomeHudUuids = ["ai-battery@hnode.dev"];
@@ -3,9 +3,11 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { gnomeHudUuid, legacyGnomeHudUuids } from "./gnome-uuid.js";
7
+
8
+ export { gnomeHudUuid } from "./gnome-uuid.js";
6
9
 
7
10
  const directory = path.dirname(fileURLToPath(import.meta.url));
8
- export const gnomeHudUuid = "ai-battery@hnode.dev";
9
11
  export const gnomeHudMetadata = {
10
12
  uuid: gnomeHudUuid, name: "AI Battery", description: "Codex and Claude usage with the macOS detail menu",
11
13
  "shell-version": ["45", "46", "47", "48", "49", "50"], version: 1,
@@ -13,52 +15,73 @@ export const gnomeHudMetadata = {
13
15
  };
14
16
 
15
17
  export function createGnomeHudIntegration({ home = os.homedir(), env = process.env, run = spawnSync } = {}) {
16
- const target = path.join(env.XDG_DATA_HOME || path.join(home, ".local/share"), "gnome-shell/extensions", gnomeHudUuid);
18
+ const extensions = path.join(env.XDG_DATA_HOME || path.join(home, ".local/share"), "gnome-shell/extensions");
19
+ const target = path.join(extensions, gnomeHudUuid);
17
20
  const source = path.join(directory, "gnome-extension/extension.js");
18
21
  const gjs = env.AI_BATTERY_GJS || (fs.existsSync("/usr/bin/gjs") ? "/usr/bin/gjs" : "gjs");
19
- function control(action) {
20
- const result = run(gjs, ["-m", path.join(directory, "gnome-control.js"), action], { env, encoding: "utf8", timeout: 8000 });
22
+ function control(action, uuid = gnomeHudUuid) {
23
+ const result = run(gjs, ["-m", path.join(directory, "gnome-control.js"), action, uuid], { env, encoding: "utf8", timeout: 8000 });
21
24
  if (result.status !== 0 || result.error) throw new Error(result.error?.message || result.stderr?.trim() || "GNOME HUD integration failed");
22
25
  return JSON.parse(result.stdout);
23
26
  }
24
- function owned() {
25
- const stat = fs.lstatSync(target, { throwIfNoEntry: false });
27
+ function owned(directory = target, uuid = gnomeHudUuid) {
28
+ const stat = fs.lstatSync(directory, { throwIfNoEntry: false });
26
29
  if (!stat) return false;
30
+ // Removal may leave unrelated notes in the directory. Their presence is
31
+ // not an installed extension and must not block a later prepare/reset.
32
+ if (stat.isDirectory() && !stat.isSymbolicLink()
33
+ && !fs.lstatSync(path.join(directory, "metadata.json"), { throwIfNoEntry: false })
34
+ && !fs.lstatSync(path.join(directory, "extension.js"), { throwIfNoEntry: false })) return false;
27
35
  let metadata;
28
36
  try {
29
- const file = path.join(target, "metadata.json");
37
+ const file = path.join(directory, "metadata.json");
30
38
  const metaStat = fs.lstatSync(file);
31
- const codeStat = fs.lstatSync(path.join(target, "extension.js"));
39
+ const codeStat = fs.lstatSync(path.join(directory, "extension.js"));
32
40
  if (!stat.isDirectory() || stat.isSymbolicLink() || !metaStat.isFile() || metaStat.isSymbolicLink()
33
41
  || !codeStat.isFile() || codeStat.isSymbolicLink()) throw new Error("Unowned extension");
34
42
  metadata = JSON.parse(fs.readFileSync(file, "utf8"));
35
43
  } catch { /* Report one ownership error without modifying the directory. */ }
36
- if (metadata?.uuid !== gnomeHudUuid || metadata["ai-battery-managed"] !== true) {
37
- throw new Error(`GNOME HUD extension ownership could not be verified; left untouched: ${target}`);
44
+ if (metadata?.uuid !== uuid || metadata["ai-battery-managed"] !== true) {
45
+ throw new Error(`GNOME HUD extension ownership could not be verified; left untouched: ${directory}`);
38
46
  }
39
47
  return true;
40
48
  }
49
+ function legacyInstallations() {
50
+ return legacyGnomeHudUuids.map(uuid => ({ uuid, directory: path.join(extensions, uuid) }))
51
+ .filter(item => owned(item.directory, item.uuid));
52
+ }
53
+ function removeOwned(directory, uuid) {
54
+ control("disable", uuid);
55
+ for (const name of ["extension.js", "metadata.json"]) fs.unlinkSync(path.join(directory, name));
56
+ if (!fs.readdirSync(directory).length) fs.rmdirSync(directory);
57
+ }
41
58
  function prepare() {
42
59
  const info = control("info");
43
60
  if (!info.available || !gnomeHudMetadata["shell-version"].includes(String(info.version).split(".")[0])) return { supported: false };
44
61
  const exists = owned();
62
+ // Validate both identities before modifying files or desktop settings.
63
+ const legacy = legacyInstallations();
45
64
  const code = fs.readFileSync(source, "utf8");
46
- const changed = !exists || fs.readFileSync(path.join(target, "extension.js"), "utf8") !== code;
65
+ const metadata = `${JSON.stringify(gnomeHudMetadata, null, 2)}\n`;
66
+ const changed = !exists || fs.readFileSync(path.join(target, "extension.js"), "utf8") !== code
67
+ || fs.readFileSync(path.join(target, "metadata.json"), "utf8") !== metadata;
47
68
  if (changed) {
48
69
  fs.mkdirSync(target, { recursive: true, mode: 0o700 });
49
70
  fs.writeFileSync(path.join(target, "extension.js"), code, { mode: 0o600 });
50
- fs.writeFileSync(path.join(target, "metadata.json"), `${JSON.stringify(gnomeHudMetadata, null, 2)}\n`, { mode: 0o600 });
71
+ fs.writeFileSync(path.join(target, "metadata.json"), metadata, { mode: 0o600 });
51
72
  }
73
+ for (const item of legacy) removeOwned(item.directory, item.uuid);
52
74
  const enabled = control("enable");
53
- return { supported: true, pending: !enabled.accepted || changed, blocked: !info.allowed, path: target };
75
+ return { supported: true, pending: !enabled.accepted || changed, blocked: !info.allowed, path: target,
76
+ migrated: legacy.map(item => item.uuid) };
54
77
  }
55
78
  function remove() {
56
- if (!owned()) return { changed: false };
57
- // Validate all managed files before touching desktop settings or removing a file.
58
- control("disable");
59
- for (const name of ["extension.js", "metadata.json"]) fs.unlinkSync(path.join(target, name));
60
- if (!fs.readdirSync(target).length) fs.rmdirSync(target);
61
- return { changed: true, path: target };
79
+ const exists = owned();
80
+ const legacy = legacyInstallations();
81
+ if (!exists && !legacy.length) return { changed: false };
82
+ if (exists) removeOwned(target, gnomeHudUuid);
83
+ for (const item of legacy) removeOwned(item.directory, item.uuid);
84
+ return { changed: true, path: exists ? target : legacy[0].directory };
62
85
  }
63
86
  return { prepare, remove, target };
64
87
  }
@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";
7
7
  import { cliError, cliText, helpText, invalidChoice, requiredValue } from "../../core/cli-help.js";
8
8
  import { createGnomeHudIntegration } from "./gnome.js";
9
9
  import { errorText } from "../../core/cli-messages.js";
10
+ import { providerId } from "../../core/display-config.js";
10
11
 
11
12
  const directory = path.dirname(fileURLToPath(import.meta.url));
12
13
  const marker = "X-AI-Battery-Managed=true";
@@ -36,8 +37,8 @@ export function parseLinuxHudArgs(argv) {
36
37
  if (!Number.isFinite(options.interval) || options.interval < 1) throw cliError("--interval must be at least 1 second.", "--interval은 1초 이상이어야 합니다.", "hud");
37
38
  i += 1;
38
39
  } else if (arg === "--provider" || arg === "-p") {
39
- options.provider = requiredValue(argv, i, "hud");
40
- if (!["all", "codex", "claude"].includes(options.provider)) throw invalidChoice(arg, "all, codex, claude", "hud");
40
+ options.provider = providerId(requiredValue(argv, i, "hud"));
41
+ if (!["all", "codex", "claude", "antigravity"].includes(options.provider)) throw invalidChoice(arg, "all, codex, claude, gemini", "hud");
41
42
  i += 1;
42
43
  } else if (arg === "--foreground" || arg === "-Foreground") {
43
44
  options.foreground = true;
@@ -4,6 +4,7 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { cliError, cliText, helpText, invalidChoice, requiredValue } from "../../core/cli-help.js";
6
6
  import { errorText } from "../../core/cli-messages.js";
7
+ import { providerId } from "../../core/display-config.js";
7
8
 
8
9
  function sleepSync(ms) {
9
10
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
@@ -45,8 +46,8 @@ function parseMacHudArgs(cliArgs) {
45
46
  options.interval = Math.max(1, Number(requiredValue(cliArgs, i, "hud")) || options.interval);
46
47
  i += 1;
47
48
  } else if (arg === "--provider" || arg === "-p") {
48
- const next = requiredValue(cliArgs, i, "hud");
49
- if (!["all", "codex", "claude"].includes(next)) throw invalidChoice(arg, "all, codex, claude", "hud");
49
+ const next = providerId(requiredValue(cliArgs, i, "hud"));
50
+ if (!["all", "codex", "claude", "antigravity"].includes(next)) throw invalidChoice(arg, "all, codex, claude, gemini", "hud");
50
51
  options.provider = next;
51
52
  i += 1;
52
53
  } else {