ai-battery 0.1.9 → 0.1.10

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.
package/README.md CHANGED
@@ -50,7 +50,7 @@ Codex 86% │ 5h 18:09 │ 7d 82% ┃ Claude 4% │ 5h 18:10 │ 7d 71%
50
50
  | `ai-battery` | 지원 | 지원 | 지원 | 지원 | Node.js 18 이상이 필요합니다. |
51
51
  | `ai-battery --watch` | 지원 | 지원 | 지원 | 지원 | 터미널 안에서 주기적으로 갱신합니다. |
52
52
  | Claude statusLine | 지원 | 지원 | 지원 | 지원 | Claude Code `statusLine`에 `node <script>` 명령을 저장합니다. |
53
- | Codex terminal row | 지원 | 지원 | 지원 | 지원 | Windows는 `node-pty`/ConPTY가 있으면 reserved row, 없으면 overlay fallback을 사용합니다. WSL/Linux/macOS는 POSIX PTY와 `python3`를 사용합니다. |
53
+ | Codex terminal row | 지원 | 지원 | 지원 | 지원 | Windows는 `rowpty.exe`(전용 ConPTY host)가 있으면 하단 row를 예약하고, 없으면 같은 콘솔에 덧그리는 overlay row로 동작합니다. WSL/Linux/macOS는 POSIX PTY와 `python3`를 사용합니다. |
54
54
  | `ai-battery setup codex` | 지원 | 지원 | 지원 | 지원 | Codex `[tui].status_line`을 맞추고, Windows는 `codex.cmd` wrapper, WSL/Linux/macOS는 POSIX shell wrapper를 설치합니다. |
55
55
  | `ai-battery hud` | 지원 | 지원 | 미지원 | 지원 | Windows/WSL은 PowerShell/WinForms HUD, macOS는 menu bar status item입니다. |
56
56
 
@@ -169,7 +169,15 @@ ai-battery setup codex
169
169
 
170
170
  Codex setup은 `~/.codex/config.toml`의 `[tui]`에 `model-with-reasoning`, `current-dir`, `git-branch` status line을 설정합니다. 기존 값이 있으면 uninstall 복구용으로 백업합니다. Codex wrapper는 기존 `codex` 명령을 직접 덮어쓰지 않습니다. `~/.local/bin`이 이미 PATH에서 원본 `codex`보다 앞에 있고 `~/.local/bin/codex`가 비어 있거나 AI Battery 관리 파일이면 그 위치에 wrapper를 둬서 바로 잡히게 합니다. 그렇지 않으면 `~/.local/share/ai-battery/bin/codex`에 관리형 wrapper를 만들고, 필요한 경우 셸 설정에 이 디렉터리를 PATH 앞쪽으로 추가합니다. `~/.local/bin/codex` 같은 공용 위치에 이미 다른 파일이 있으면 덮어쓰지 않습니다. 새 터미널부터 `codex`가 자동으로 AI Battery 하단 행과 함께 실행됩니다. 같은 터미널에서 이미 `codex`를 실행한 적이 있으면 셸 캐시 때문에 `hash -r`이 한 번 필요할 수 있고, PATH 추가가 필요한 경우에는 `setup` 출력에 표시되는 `source ...` 명령을 실행하세요.
171
171
 
172
- Windows native `cmd`/PowerShell에서는 `codex.cmd` wrapper가 Windows runner를 실행합니다. `node-pty`가 설치되어 있으면 ConPTY로 Codex 화면을 한 줄 짧게 띄워 하단 row를 예약하고, `node-pty`가 없거나 로드되지 않으면 같은 콘솔의 하단에 overlay row를 다시 그리는 fallback을 사용합니다. Claude statusLine은 일반 `cmd`/PowerShell 프롬프트가 아니라 Claude Code 안에서만 표시됩니다.
172
+ Windows native `cmd`/PowerShell에서는 `codex.cmd` wrapper가 Windows runner를 실행합니다. runner는 `rowpty.exe`(별도 rowpty 프로젝트의 전용 ConPTY host)가 있으면 WSL과 같은 방식으로 하단 row를 예약합니다: 자식 프로그램은 한 줄 짧은 화면을 쓰고, 상태줄은 출력이 잠잠해진 시점에만 그려져 깜빡임 없이 하단에 고정됩니다. `rowpty.exe`는 바이너리로 배포되지 않습니다 — `ai-battery setup`이 패키지에 동봉된 소스(`vendor/rowpty/RowPty.cs`)를 Windows 내장 .NET Framework `csc.exe`로 사용자 머신에서 직접 컴파일해 `%LOCALAPPDATA%\ai-battery\bin`에 설치하고, 그 옆에 Microsoft 서명된 최신 ConPTY(`conpty.dll`/`OpenConsole.exe`, node-pty 패키지에서 복사)를 배치합니다. 서명 없는 다운로드 바이너리가 없으므로 SmartScreen/Defender류 평판 경고를 원천적으로 피하고, 소스가 텍스트로 열려 있어 감사할 수 있습니다. 직접 빌드한 exe를 쓰려면 `AI_BATTERY_ROWPTY` 환경변수로 지정합니다. rowpty가 없으면 같은 콘솔에 덧그리는 overlay layout으로 동작하며(`AI_BATTERY_WIN_LAYOUT=overlay`로 강제 가능), legacy `node-pty` reserve는 `AI_BATTERY_WIN_LAYOUT=reserve`이면서 rowpty가 없을 때만 사용됩니다. Claude statusLine은 일반 `cmd`/PowerShell 프롬프트가 아니라 Claude Code 안에서만 표시됩니다.
173
+
174
+ tmux에서는 pane마다 하단 행을 예약하면 같은 전역 배터리가 pane 수만큼 중복 표시됩니다. 대신 tmux의 status bar에 세션당 한 번만 표시할 수 있습니다.
175
+
176
+ ```bash
177
+ ai-battery setup tmux
178
+ ```
179
+
180
+ `~/.tmux.conf`에 관리 블록을 추가해 status-right에 배터리를 표시하고(10초 간격 갱신), 이 tmux 안에서 실행되는 `codex`는 pane별 배터리 행을 생략하고 pane 전체를 사용합니다. 적용하려면 `tmux source-file ~/.tmux.conf` 후 새 pane을 여세요. 이 블록은 기존 `status-right` 설정을 덮어쓰므로 `setup all`에 포함되지 않는 opt-in입니다. 해제는 `ai-battery uninstall tmux`, tmux 안에서도 pane별 행을 유지하려면 `AI_BATTERY_TMUX=row`를 설정합니다. Claude statusLine은 Claude Code 내부 UI라 tmux 여부와 무관하게 그대로 표시됩니다.
173
181
 
174
182
  Codex 하단 행이 보이지 않으면 진단을 실행합니다.
175
183
 
@@ -305,7 +313,7 @@ Codex는 최근 세션 로그에서 `rate_limits` 이벤트를 찾습니다. Cla
305
313
 
306
314
  ## Source Environment
307
315
 
308
- 기본 CLI는 Node.js 18 이상이 있으면 Windows native, WSL, Linux, macOS에서 실행됩니다. Windows native의 Codex terminal row는 Node runner를 사용하며, optional `node-pty`가 있으면 ConPTY reserved row를 사용하고 없으면 overlay fallback을 사용합니다. WSL/Linux/macOS의 `ai-battery-run`은 Python 3와 POSIX PTY를 사용합니다. HUD는 Windows/WSL에서는 PowerShell/WinForms, macOS에서는 내장 `osascript`와 AppleScriptObjC를 사용합니다.
316
+ 기본 CLI는 Node.js 18 이상이 있으면 Windows native, WSL, Linux, macOS에서 실행됩니다. Windows native의 Codex terminal row는 `rowpty.exe`(전용 ConPTY host, .NET Framework 4.8 내장 csc.exe로 빌드)가 있으면 reserved row를 사용하고, 없으면 Node runner의 same-console overlay row로 동작합니다. WSL/Linux/macOS의 `ai-battery-run`은 Python 3와 POSIX PTY를 사용합니다. HUD는 Windows/WSL에서는 PowerShell/WinForms, macOS에서는 내장 `osascript`와 AppleScriptObjC를 사용합니다.
309
317
 
310
318
  Codex 데이터는 기본적으로 `~/.codex/sessions`를 읽습니다. 다른 위치를 쓰고 있다면 `CODEX_HOME`을 설정하세요.
311
319
 
@@ -429,7 +429,7 @@ const configuredCommand = process.env.AI_BATTERY_COMMAND || process.env.CLAUDEX_
429
429
  const envPrefix = useWsl ? wslEnvPrefix() : "";
430
430
  const batteryCommand = configuredCommand || (useWsl
431
431
  ? `${envPrefix ? `${envPrefix} ` : ""}HOME=${shellQuote(os.homedir())} ${shellQuote(nodePath)} ${shellQuote(batteryJs)} --json`
432
- : `${winArgQuote(nodePath)} ${winArgQuote(batteryJs)} --json`);
432
+ : `& ${winArgQuote(nodePath)} ${winArgQuote(batteryJs)} --json`);
433
433
  const batteryCommandBase64 = Buffer.from(batteryCommand, "utf8").toString("base64");
434
434
 
435
435
  const AUTOSTART_REG_PATH = "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
@@ -350,13 +350,23 @@ function Invoke-AiBatteryJson {
350
350
  if ($UseWsl) {
351
351
  $output = & wsl.exe bash -lc "$BatteryCommand 2>/dev/null"
352
352
  } else {
353
- $output = Invoke-Expression "$BatteryCommand 2>`$null"
353
+ $output = Invoke-LocalBatteryCommandOutput $BatteryCommand
354
354
  }
355
355
  $text = ($output -join "`n").Trim()
356
356
  if (-not $text) { throw "ai-battery produced no output" }
357
357
  return $text | ConvertFrom-Json
358
358
  }
359
359
 
360
+ function Invoke-LocalBatteryCommandOutput([string]$Command) {
361
+ try {
362
+ return Invoke-Expression "$Command 2>`$null"
363
+ } catch {
364
+ $trimmed = $Command.TrimStart()
365
+ if ($trimmed.StartsWith("&")) { throw }
366
+ return Invoke-Expression "& $Command 2>`$null"
367
+ }
368
+ }
369
+
360
370
  function Get-DurationText([Nullable[int]]$Seconds) {
361
371
  if ($null -eq $Seconds) { return "?" }
362
372
  if ($Seconds -le 0) { return "now" }
@@ -621,7 +631,13 @@ function Start-SnapshotFetch {
621
631
  if ($UseWslShell) {
622
632
  $output = & wsl.exe bash -lc "$Command 2>/dev/null"
623
633
  } else {
624
- $output = Invoke-Expression "$Command 2>`$null"
634
+ try {
635
+ $output = Invoke-Expression "$Command 2>`$null"
636
+ } catch {
637
+ $trimmed = $Command.TrimStart()
638
+ if ($trimmed.StartsWith("&")) { throw }
639
+ $output = Invoke-Expression "& $Command 2>`$null"
640
+ }
625
641
  }
626
642
  ($output -join "`n").Trim()
627
643
  } catch {
@@ -251,6 +251,18 @@ class StatusLine:
251
251
  os.write(sys.stdout.fileno(), payload.encode("ascii"))
252
252
 
253
253
 
254
+ def tmux_status_bar_active():
255
+ if not os.environ.get("TMUX"):
256
+ return False
257
+ override = (os.environ.get("AI_BATTERY_TMUX") or os.environ.get("CLAUDEX_BATTERY_TMUX") or "").lower()
258
+ if override == "row":
259
+ return False
260
+ if override in ("status", "plain", "off"):
261
+ return True
262
+ flag = os.environ.get("AI_BATTERY_TMUX_STATUS") or os.environ.get("CLAUDEX_BATTERY_TMUX_STATUS")
263
+ return flag == "1"
264
+
265
+
254
266
  def main():
255
267
  interval, bar_width, provider, layout, left_padding, command = parse_args(sys.argv[1:])
256
268
  command_provider = infer_provider(command)
@@ -258,6 +270,12 @@ def main():
258
270
  provider = command_provider
259
271
  layout = resolve_layout(layout, command_provider)
260
272
 
273
+ # Inside tmux with the status-bar integration, the battery already shows
274
+ # once per session in tmux's own bar; skip the per-pane reserved row and
275
+ # hand the pane to the child untouched.
276
+ if tmux_status_bar_active():
277
+ os.execvp(command[0], command)
278
+
261
279
  if not os.isatty(sys.stdin.fileno()) or not os.isatty(sys.stdout.fileno()):
262
280
  print(
263
281
  "ai-battery-run: stdin/stdout is not a real terminal.\n"
@@ -13,12 +13,15 @@ const ANSI_RE = /\u001b\[[0-?]*[ -/]*[@-~]/g;
13
13
  const DEBUG_LOG = process.env.AI_BATTERY_DEBUG_LOG || process.env.CLAUDEX_BATTERY_DEBUG_LOG || "";
14
14
  const DEFAULT_COLUMN_GUARD = 4;
15
15
  const DEFAULT_LEFT_PADDING = 2;
16
+ const DEFAULT_CODEX_OVERLAY_BOTTOM_OFFSET = 1;
16
17
 
17
18
  function usage() {
18
19
  console.log(`Usage: ai-battery-run-win [--interval SECONDS] [--bar-width N] [--provider auto|all|codex|claude] [--layout auto|reserve|overlay] [--left-padding N] -- COMMAND [ARGS...]
19
20
 
20
21
  Runs COMMAND and keeps AI Battery on the terminal bottom row.
21
- On Windows, node-pty enables ConPTY row reservation when available; otherwise AI Battery falls back to a same-console overlay row.`);
22
+ On Windows, the rowpty host (a native ConPTY host with a reserved bottom row) is preferred when its executable
23
+ is available; otherwise AI Battery falls back to a same-console overlay row.
24
+ --layout reserve additionally allows the legacy node-pty/ConPTY path when rowpty is missing.`);
22
25
  }
23
26
 
24
27
  function debugLog(event, details = {}) {
@@ -111,6 +114,18 @@ function columnGuard() {
111
114
  return Number.isFinite(value) ? Math.max(0, Math.min(20, Math.floor(value))) : DEFAULT_COLUMN_GUARD;
112
115
  }
113
116
 
117
+ function overlayBottomOffset(activeProvider) {
118
+ const raw = Number(process.env.AI_BATTERY_OVERLAY_BOTTOM_OFFSET || process.env.CLAUDEX_BATTERY_OVERLAY_BOTTOM_OFFSET);
119
+ if (Number.isFinite(raw)) return Math.max(0, Math.min(5, Math.floor(raw)));
120
+ return activeProvider === "codex" ? DEFAULT_CODEX_OVERLAY_BOTTOM_OFFSET : 0;
121
+ }
122
+
123
+ function statusRow(rows, bottomOffset = 0) {
124
+ const safeRows = Math.max(1, Number(rows) || 1);
125
+ const safeOffset = Math.max(0, Math.min(5, Math.floor(Number(bottomOffset) || 0)));
126
+ return Math.max(1, safeRows - safeOffset);
127
+ }
128
+
114
129
  function stripAnsi(text) {
115
130
  return String(text).replace(ANSI_RE, "");
116
131
  }
@@ -147,10 +162,121 @@ function statusOutputText(stdout) {
147
162
  return String(stdout || "").replace(/[\r\n]+$/g, "");
148
163
  }
149
164
 
165
+ function rowptyExePath() {
166
+ const explicit = process.env.AI_BATTERY_ROWPTY || process.env.CLAUDEX_BATTERY_ROWPTY;
167
+ if (explicit) return fs.existsSync(explicit) ? explicit : null;
168
+ const candidates = [];
169
+ if (process.env.LOCALAPPDATA) {
170
+ candidates.push(path.join(process.env.LOCALAPPDATA, "ai-battery", "bin", "rowpty.exe"));
171
+ }
172
+ candidates.push(path.join(SCRIPT_DIR, "..", "..", "rowpty", "bin", "rowpty.exe"));
173
+ for (const candidate of candidates) {
174
+ if (fs.existsSync(candidate)) return candidate;
175
+ }
176
+ return null;
177
+ }
178
+
179
+ function quoteWindowsCommandLineArg(value) {
180
+ const text = String(value ?? "");
181
+ if (text.length && !/[ \t"]/.test(text)) return text;
182
+ let quoted = "\"";
183
+ let backslashes = 0;
184
+ for (const ch of text) {
185
+ if (ch === "\\") {
186
+ backslashes += 1;
187
+ } else if (ch === "\"") {
188
+ quoted += "\\".repeat(backslashes * 2 + 1) + "\"";
189
+ backslashes = 0;
190
+ } else {
191
+ quoted += "\\".repeat(backslashes) + ch;
192
+ backslashes = 0;
193
+ }
194
+ }
195
+ return quoted + "\\".repeat(backslashes * 2) + "\"";
196
+ }
197
+
198
+ function rowptyStatusCommand(args, activeProvider) {
199
+ // rowpty substitutes {MAXWIDTH} with (cols - 4) before each status run.
200
+ return batteryCommand(args, activeProvider, "{MAXWIDTH}")
201
+ .map(quoteWindowsCommandLineArg)
202
+ .join(" ");
203
+ }
204
+
205
+ function runRowPty(args, activeProvider) {
206
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return Promise.resolve(null);
207
+ const exe = rowptyExePath();
208
+ if (!exe) {
209
+ debugLog("rowpty:missing");
210
+ return Promise.resolve(null);
211
+ }
212
+
213
+ const command = windowsCommand(args.command);
214
+ const hostArgs = [
215
+ "--interval", String(Math.max(0.5, args.interval)),
216
+ "--reserve", "1",
217
+ "--status-cmd", rowptyStatusCommand(args, activeProvider),
218
+ "--", command.file, ...command.args
219
+ ];
220
+ debugLog("rowpty:start", { exe, hostArgs, size: termSize() });
221
+ const child = spawn(exe, hostArgs, {
222
+ stdio: "inherit",
223
+ cwd: process.cwd(),
224
+ env: process.env,
225
+ windowsHide: false
226
+ });
227
+
228
+ return new Promise((resolve) => {
229
+ child.on("exit", (code, signal) => {
230
+ debugLog("rowpty:exit", { code, signal });
231
+ resolve(code ?? (signal ? 1 : 0));
232
+ });
233
+ child.on("error", (error) => {
234
+ debugLog("rowpty:error", { error: error.message });
235
+ resolve(null);
236
+ });
237
+ });
238
+ }
239
+
240
+ function conPtyBackspaceMode() {
241
+ // Windows Terminal sends 0x7f for Backspace and 0x08 for Ctrl+Backspace.
242
+ // Rewriting DEL to BS makes TUIs (Codex, Claude Code) treat every
243
+ // Backspace as delete-word, so keys pass through untouched by default.
244
+ const mode = String(process.env.AI_BATTERY_CONPTY_BACKSPACE || process.env.CLAUDEX_BATTERY_CONPTY_BACKSPACE || "passthrough").toLowerCase();
245
+ return ["bs", "del", "passthrough"].includes(mode) ? mode : "passthrough";
246
+ }
247
+
248
+ function normalizeConPtyInput(data, mode = conPtyBackspaceMode()) {
249
+ const text = Buffer.isBuffer(data) ? data.toString("utf8") : String(data || "");
250
+ if (mode === "passthrough" || mode === "del") return text;
251
+ return text.replace(/\x7f/g, "\x08");
252
+ }
253
+
254
+ function conPtyRepaintIntervalMs() {
255
+ const raw = Number(process.env.AI_BATTERY_CONPTY_REPAINT_MS || process.env.CLAUDEX_BATTERY_CONPTY_REPAINT_MS);
256
+ if (Number.isFinite(raw)) return Math.max(250, Math.min(5000, Math.floor(raw)));
257
+ return 1000;
258
+ }
259
+
260
+ function outputMayClearDisplay(data) {
261
+ const text = Buffer.isBuffer(data) ? data.toString("utf8") : String(data || "");
262
+ return /\x1bc|\x1b\[[0-?]*[23]J|\x1b\[\?1049[hl]/.test(text);
263
+ }
264
+
265
+ function scheduleRepaintBurst(status, timers) {
266
+ for (const delayMs of [0, 80, 250, 700, 1400]) {
267
+ const timer = setTimeout(() => {
268
+ timers.delete(timer);
269
+ status.paint(true);
270
+ }, delayMs);
271
+ timers.add(timer);
272
+ }
273
+ }
274
+
150
275
  class StatusLine {
151
- constructor(args, activeProvider) {
276
+ constructor(args, activeProvider, options = {}) {
152
277
  this.args = args;
153
278
  this.activeProvider = activeProvider;
279
+ this.bottomOffset = options.bottomOffset ?? 0;
154
280
  this.text = "AI Battery starting...";
155
281
  this.nextFetch = 0;
156
282
  this.lastLine = "";
@@ -226,11 +352,12 @@ class StatusLine {
226
352
  const now = Date.now();
227
353
  if (!force && now - this.lastDraw < 150) return;
228
354
  const width = Math.max(1, this.cols - 1);
355
+ const row = statusRow(this.rows, this.bottomOffset);
229
356
  const line = fitAnsi(this.text, width, true);
230
357
  if (!force && line === this.lastLine) return;
231
358
  this.lastLine = line;
232
359
  this.lastDraw = now;
233
- process.stdout.write(`\x1b7\x1b[0m\x1b[${this.rows};1H\r\x1b[1G${line}\x1b[K\x1b[0m\x1b8`);
360
+ process.stdout.write(`\x1b7\x1b[0m\x1b[${row};1H\r\x1b[1G${line}\x1b[K\x1b[0m\x1b8`);
234
361
  }
235
362
 
236
363
  draw(force = false) {
@@ -240,7 +367,8 @@ class StatusLine {
240
367
 
241
368
  clear() {
242
369
  this.disposed = true;
243
- process.stdout.write(`\x1b7\x1b[0m\x1b[${this.rows};1H\r\x1b[1G\x1b[2K\x1b8`);
370
+ const row = statusRow(this.rows, this.bottomOffset);
371
+ process.stdout.write(`\x1b7\x1b[0m\x1b[${row};1H\r\x1b[1G\x1b[2K\x1b8`);
244
372
  }
245
373
  }
246
374
 
@@ -306,8 +434,10 @@ async function loadNodePty() {
306
434
  }
307
435
 
308
436
  async function runConPty(args, activeProvider) {
309
- if (args.layout === "overlay") {
310
- debugLog("conpty:skipped", { reason: "layout overlay" });
437
+ // Nested ConPTY (node-pty) breaks host-terminal scrollback and can stall
438
+ // child output until the next keypress, so it is opt-in via --layout reserve.
439
+ if (args.layout !== "reserve") {
440
+ debugLog("conpty:skipped", { reason: `layout ${args.layout}` });
311
441
  return null;
312
442
  }
313
443
 
@@ -318,11 +448,9 @@ async function runConPty(args, activeProvider) {
318
448
  stdinTty: Boolean(process.stdin.isTTY),
319
449
  stdoutTty: Boolean(process.stdout.isTTY)
320
450
  });
321
- if (args.layout === "reserve") {
322
- console.error("ai-battery-run-win: ConPTY reserve layout is unavailable in this terminal.");
323
- return 2;
324
- }
325
- return null;
451
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return null;
452
+ console.error("ai-battery-run-win: ConPTY reserve layout is unavailable in this terminal.");
453
+ return 2;
326
454
  }
327
455
 
328
456
  const status = new StatusLine(args, activeProvider);
@@ -349,7 +477,7 @@ async function runConPty(args, activeProvider) {
349
477
  const oldRaw = process.stdin.isRaw;
350
478
  process.stdin.setRawMode?.(true);
351
479
  process.stdin.resume();
352
- const onInput = (data) => term.write(data.toString());
480
+ const onInput = (data) => term.write(normalizeConPtyInput(data));
353
481
  process.stdin.on("data", onInput);
354
482
 
355
483
  let drawTimer = null;
@@ -366,23 +494,34 @@ async function runConPty(args, activeProvider) {
366
494
  };
367
495
  status.onRefresh = () => scheduleDraw(true, 45);
368
496
 
497
+ const timers = new Set();
369
498
  const timer = setInterval(() => scheduleDraw(false), Math.max(500, args.interval * 1000));
499
+ const repaintTimer = setInterval(() => status.paint(true), conPtyRepaintIntervalMs());
370
500
  const onResize = () => {
371
501
  status.resize();
372
502
  term.resize(status.cols, Math.max(1, status.rows - 1));
373
503
  scheduleDraw(true, 0);
504
+ scheduleRepaintBurst(status, timers);
374
505
  };
375
506
  process.stdout.on("resize", onResize);
376
507
 
508
+ const clearConPtyTimers = () => {
509
+ clearInterval(timer);
510
+ clearInterval(repaintTimer);
511
+ if (drawTimer) clearTimeout(drawTimer);
512
+ for (const timer of timers) clearTimeout(timer);
513
+ timers.clear();
514
+ };
515
+
377
516
  return await new Promise((resolve) => {
378
517
  term.onData((data) => {
379
518
  process.stdout.write(data);
519
+ if (outputMayClearDisplay(data)) scheduleRepaintBurst(status, timers);
380
520
  scheduleDraw(false);
381
521
  });
382
522
  term.onExit(({ exitCode }) => {
383
523
  debugLog("conpty:exit", { exitCode });
384
- clearInterval(timer);
385
- if (drawTimer) clearTimeout(drawTimer);
524
+ clearConPtyTimers();
386
525
  process.stdout.off("resize", onResize);
387
526
  process.stdin.off("data", onInput);
388
527
  process.stdin.setRawMode?.(oldRaw);
@@ -390,6 +529,7 @@ async function runConPty(args, activeProvider) {
390
529
  resolve(exitCode ?? 0);
391
530
  });
392
531
  scheduleDraw(true, 0);
532
+ scheduleRepaintBurst(status, timers);
393
533
  });
394
534
  }
395
535
 
@@ -399,6 +539,16 @@ function overlayInitialDelayMs() {
399
539
  return 1200;
400
540
  }
401
541
 
542
+ function overlayRepaintIntervalMs() {
543
+ const raw = Number(process.env.AI_BATTERY_OVERLAY_REPAINT_MS || process.env.CLAUDEX_BATTERY_OVERLAY_REPAINT_MS);
544
+ if (Number.isFinite(raw)) return Math.max(250, Math.min(5000, Math.floor(raw)));
545
+ return 1000;
546
+ }
547
+
548
+ function scheduleOverlayRepaintBurst(status, timers) {
549
+ scheduleRepaintBurst(status, timers);
550
+ }
551
+
402
552
  function runOverlay(args, activeProvider) {
403
553
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
404
554
  debugLog("overlay:unavailable", {
@@ -409,11 +559,14 @@ function runOverlay(args, activeProvider) {
409
559
  return 2;
410
560
  }
411
561
 
412
- const status = new StatusLine(args, activeProvider);
562
+ const status = new StatusLine(args, activeProvider, {
563
+ bottomOffset: overlayBottomOffset(activeProvider)
564
+ });
413
565
  const command = windowsCommand(args.command);
414
566
  debugLog("overlay:start", {
415
567
  size: termSize(),
416
568
  command,
569
+ bottomOffset: status.bottomOffset,
417
570
  initialDelayMs: overlayInitialDelayMs(),
418
571
  stdoutColumns: process.stdout.columns,
419
572
  stdoutRows: process.stdout.rows,
@@ -427,27 +580,39 @@ function runOverlay(args, activeProvider) {
427
580
  windowsHide: false
428
581
  });
429
582
 
430
- const timer = setInterval(() => status.draw(false), Math.max(1000, args.interval * 1000));
583
+ const timers = new Set();
584
+ const refreshTimer = setInterval(() => status.draw(false), Math.max(1000, args.interval * 1000));
585
+ const repaintTimer = setInterval(() => status.paint(true), overlayRepaintIntervalMs());
431
586
  const onResize = () => {
432
587
  status.resize();
433
588
  status.draw(true);
589
+ scheduleOverlayRepaintBurst(status, timers);
434
590
  };
435
591
  process.stdout.on("resize", onResize);
436
- const firstDraw = setTimeout(() => status.draw(true), overlayInitialDelayMs());
592
+ const firstDraw = setTimeout(() => {
593
+ status.draw(true);
594
+ scheduleOverlayRepaintBurst(status, timers);
595
+ }, overlayInitialDelayMs());
596
+ timers.add(firstDraw);
597
+
598
+ const clearOverlayTimers = () => {
599
+ clearInterval(refreshTimer);
600
+ clearInterval(repaintTimer);
601
+ for (const timer of timers) clearTimeout(timer);
602
+ timers.clear();
603
+ };
437
604
 
438
605
  return new Promise((resolve) => {
439
606
  child.on("exit", (code, signal) => {
440
607
  debugLog("overlay:exit", { code, signal });
441
- clearInterval(timer);
442
- clearTimeout(firstDraw);
608
+ clearOverlayTimers();
443
609
  process.stdout.off("resize", onResize);
444
610
  status.clear();
445
611
  resolve(code ?? (signal ? 1 : 0));
446
612
  });
447
613
  child.on("error", (error) => {
448
614
  debugLog("overlay:error", { error: error.message });
449
- clearInterval(timer);
450
- clearTimeout(firstDraw);
615
+ clearOverlayTimers();
451
616
  process.stdout.off("resize", onResize);
452
617
  status.clear();
453
618
  console.error(`ai-battery-run-win: ${error.message}`);
@@ -499,16 +664,32 @@ async function main() {
499
664
  stdoutTty: Boolean(process.stdout.isTTY)
500
665
  });
501
666
 
502
- const ptyExit = await runConPty(args, activeProvider);
503
- const exitCode = ptyExit === null
504
- ? (process.stdin.isTTY && process.stdout.isTTY ? await runOverlay(args, activeProvider) : await runPlain(args))
505
- : ptyExit;
667
+ let exitCode = null;
668
+ if (args.layout !== "overlay") {
669
+ exitCode = await runRowPty(args, activeProvider);
670
+ if (exitCode === null) exitCode = await runConPty(args, activeProvider);
671
+ }
672
+ if (exitCode === null) {
673
+ exitCode = process.stdin.isTTY && process.stdout.isTTY
674
+ ? await runOverlay(args, activeProvider)
675
+ : await runPlain(args);
676
+ }
506
677
  process.exit(exitCode);
507
678
  }
508
679
 
509
680
  export {
681
+ conPtyBackspaceMode,
682
+ conPtyRepaintIntervalMs,
683
+ normalizeConPtyInput,
684
+ outputMayClearDisplay,
685
+ overlayBottomOffset,
686
+ overlayRepaintIntervalMs,
510
687
  parseArgs,
688
+ quoteWindowsCommandLineArg,
511
689
  resolveWindowsCommandFile,
690
+ rowptyExePath,
691
+ rowptyStatusCommand,
692
+ statusRow,
512
693
  statusOutputText,
513
694
  windowsCommand
514
695
  };