ai-battery 0.1.26 → 0.1.28

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
@@ -1,5 +1,9 @@
1
1
  # AI Battery
2
2
 
3
+ 0.1.28: `setup`만으로 Codex TUI가 연결되던 0.1.24의 기본 동작을 복원했습니다. 신규 설치·업데이트·reset 후 setup을 동일하게 처리합니다. `doctor`는 표시 설정(Visibility), TUI 연동 상태, 현재 세션을 구분하고 누락된 연동·PATH·의존성에 맞는 조치를 안내합니다. [회귀 원인과 검증](docs/SETUP-REGRESSION.md).
4
+
5
+ 0.1.27: 한글 오류 메시지가 포함된 하단 사용량 줄이 갱신될 때 Codex 화면에 여러 줄로 누적되던 문제를 수정했습니다. 화면 칸 수를 기준으로 너비를 제한하고 불필요한 공백 채우기를 제거했습니다. 하단 바의 데이터 없음 표시는 `Claude --%`처럼 간결하게 표시합니다.
6
+
3
7
  0.1.26: `setup`이 기존 Codex 연동을 해제하던 문제를 수정했습니다. 기존 wrapper·PATH·Codex 상태줄과 tmux 연동을 유지·갱신하며, 실행 중인 셸이 기억하는 경로를 제거하지 않습니다. tmux 미실행 상태를 구분하고 HUD 메뉴의 밝은 테두리를 제거했습니다. 기본 예시는 `ai-battery setup tmux`입니다.
4
8
 
5
9
  0.1.25: Ubuntu/Linux 패널 HUD를 추가했습니다. macOS와 같은 로고·배터리 바·퍼센트를 표시합니다. 도움말·진단·설정 결과·오류 안내는 간결한 한국어/영어로 표시합니다. 명령 없이 실행하면 도움말을 표시하며 `show` 명령은 제거했습니다. 설정 복원은 `ai-battery reset`으로 실행하고, 이전 `reset settings`·`reset config`도 계속 지원합니다.
@@ -106,7 +110,7 @@ npx ai-battery
106
110
  tmux
107
111
  ```
108
112
 
109
- 일반 터미널에서 `codex`를 실행할 때도 사용량 행을 표시하려면 한 번 `ai-battery setup codex --wrap-codex`를 실행하고 안내된 `source` 명령을 현재 셸에 적용하세요. 이후 `setup`과 npm 업데이트에서도 이 선택을 유지합니다. 새로 열린 터미널에는 자동 적용됩니다. 데스크톱 표시는 `ai-battery hud`를 사용합니다.
113
+ `ai-battery setup`은 일반 터미널의 `codex`에도 사용량 행을 연결합니다. 기존 셸에서는 안내된 `source` 명령을 적용하고, 새 터미널에서는 `codex`를 실행하세요. 업데이트 후 setup과 reset 후 setup도 같은 방식으로 연결합니다. 데스크톱 표시는 `ai-battery hud`를 사용합니다.
110
114
 
111
115
  ## CLI
112
116
 
@@ -170,7 +174,7 @@ CLI는 npm 제거를 자동 실행하지 않습니다. `teardown`과 `uninstall`
170
174
 
171
175
  ## Setup
172
176
 
173
- `setup`은 기존 Codex wrapper·PATH·상태줄과 tmux 연동을 유지·갱신하고 Claude statusLine을 설정합니다. 실행 중인 터미널의 경로와 복구용 백업을 제거하지 않습니다. 새 설치에는 Codex wrapper나 Codex 설정을 자동으로 추가하지 않습니다. 연동 해제는 `reset`으로 실행합니다.
177
+ `setup`은 기존 Codex wrapper·PATH·상태줄과 tmux 연동을 유지·갱신하고 Claude statusLine을 설정합니다. 실행 중인 터미널의 경로와 복구용 백업을 제거하지 않습니다. 새 설치와 reset 후에도 Codex PATH wrapper를 연결합니다. 원본 Codex 실행 파일·설정·세션 기록은 유지합니다. 연동 해제는 `reset`으로 실행합니다.
174
178
 
175
179
  ```bash
176
180
  ai-battery setup
@@ -183,7 +187,7 @@ ai-battery setup tmux
183
187
  ai-battery setup codex
184
188
  ```
185
189
 
186
- 기존처럼 `codex` 명령에 wrapper를 연결하려는 경우에만 `ai-battery setup codex --wrap-codex`를 사용합니다. Codex `[tui].status_line` 변경도 별도 옵션인 `--configure-codex-statusline`이 필요합니다. 두 옵션은 실행 경로나 사용자 설정을 변경하므로 기본값에서 제외되어 있습니다. 관리형 변경은 복구 기록을 먼저 저장하고, `reset`에서 해당 변경만 복원합니다.
190
+ `setup`과 `setup codex`는 Codex wrapper를 기본으로 연결합니다. `--wrap-codex`는 호환 옵션이며, `--no-wrap-codex`는 wrapper 설정만 생략합니다. 기존 연동을 해제하려면 `reset codex`를 사용합니다. Codex `[tui].status_line` 변경은 별도 옵션인 `--configure-codex-statusline`을 지정한 경우에만 적용합니다. 관리형 변경은 복구 기록을 먼저 저장하고, `reset`에서 해당 변경만 복원합니다.
187
191
 
188
192
  tmux에서는 pane마다 하단 행을 예약하면 같은 전역 배터리가 pane 수만큼 중복 표시됩니다. 대신 tmux의 status bar에 세션당 한 번만 표시할 수 있습니다.
189
193
 
@@ -214,7 +218,7 @@ ai-battery on all
214
218
 
215
219
  ## Codex Terminal Row
216
220
 
217
- 기본 `codex`는 AI Battery를 거치지 않고 실행됩니다. 사용량을 독립적으로 보려면 `ai-battery --watch 2` 또는 지원 플랫폼에서 `ai-battery hud`를 실행하세요.
221
+ `ai-battery setup` 이후 새 터미널에서 `codex`를 실행하면 사용량 행이 표시됩니다. `doctor`의 `Visibility`는 표시 허용 설정이고, `TUI`는 다음 실행의 연동 준비 상태, `Session`은 현재 Codex의 연결 여부입니다. `on`만으로 연동을 설치하지는 않습니다. 사용량을 별도로 보려면 `ai-battery --watch 2` 또는 지원 플랫폼에서 `ai-battery hud`를 실행하세요.
218
222
 
219
223
  세션 하나에 하단 행을 추가하려면 명시적으로 실행합니다.
220
224
 
@@ -6,6 +6,7 @@ import signal
6
6
  import subprocess
7
7
  import sys
8
8
  import time
9
+ import unicodedata
9
10
 
10
11
  if os.name == "nt":
11
12
  print(
@@ -25,7 +26,12 @@ import tty
25
26
 
26
27
  SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
27
28
  BATTERY_BIN = os.environ.get("AI_BATTERY_BIN") or os.environ.get("CLAUDEX_BATTERY_BIN", os.path.join(SCRIPT_DIR, "ai-battery.js"))
28
- ANSI_RE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
29
+ ANSI_RE = re.compile(
30
+ r"(\x1b(?:\[[0-?]*[ -/]*[@-~]"
31
+ r"|\][^\x07\x1b]*(?:\x07|\x1b\\|$)"
32
+ r"|[PX^_][\s\S]*?(?:\x1b\\|$)|[ -/]*[@-~]))"
33
+ )
34
+ SGR_RE = re.compile(r"\x1b\[[0-9:;]*m")
29
35
 
30
36
 
31
37
  def battery_command_base():
@@ -164,12 +170,31 @@ def column_guard():
164
170
  return DEFAULT_COLUMN_GUARD
165
171
 
166
172
 
167
- def fit_ansi(text, width, pad=True):
168
- plain = strip_ansi(text)
169
- if len(plain) <= width:
170
- return text + (" " * (width - len(plain)) if pad else "")
171
- suffix = " " if pad else ""
172
- return plain[: max(0, width - len(suffix))] + suffix
173
+ def fit_ansi(text, width):
174
+ # Python len() counts code points, not terminal cells. Padding a Korean
175
+ # line using len() can wrap at the bottom and scroll a copy into the TUI
176
+ # on every refresh. EL clears the tail, so no padding is necessary.
177
+ output = []
178
+ cells = 0
179
+ for token in ANSI_RE.split(text):
180
+ if token.startswith("\x1b"):
181
+ # Status output may style text, but must never move the cursor,
182
+ # erase the child's screen or introduce another physical row.
183
+ if SGR_RE.fullmatch(token):
184
+ output.append(token)
185
+ continue
186
+ for char in token:
187
+ category = unicodedata.category(char)
188
+ if category in ("Cc", "Cs"):
189
+ continue
190
+ char_width = 0 if category in ("Mn", "Me", "Cf") else (
191
+ 2 if unicodedata.east_asian_width(char) in ("W", "F") else 1
192
+ )
193
+ if cells + char_width > width:
194
+ return "".join(output)
195
+ output.append(char)
196
+ cells += char_width
197
+ return "".join(output)
173
198
 
174
199
 
175
200
  class StatusLine:
@@ -308,7 +333,7 @@ class StatusLine:
308
333
  def draw_cached(self):
309
334
  """Repaint cached text at the new terminal size without starting a poll."""
310
335
  paint_width = max(1, self.cols - 1)
311
- line = fit_ansi(self.text, paint_width, pad=True)
336
+ line = fit_ansi(self.text, paint_width)
312
337
  self.last_draw = time.monotonic()
313
338
  self.last_line = line
314
339
  self._write_row(line)
@@ -319,7 +344,7 @@ class StatusLine:
319
344
  return
320
345
  self.refresh(force)
321
346
  paint_width = max(1, self.cols - 1)
322
- line = fit_ansi(self.text, paint_width, pad=True)
347
+ line = fit_ansi(self.text, paint_width)
323
348
  if not force and not dirty and line == self.last_line:
324
349
  return
325
350
  self.last_draw = now
@@ -376,7 +401,7 @@ def main():
376
401
 
377
402
  set_winsize(master_fd, child_rows, cols)
378
403
  old_term = termios.tcgetattr(sys.stdin.fileno())
379
- child_exit = 0
404
+ child_exit = None
380
405
 
381
406
  def on_resize(_signum, _frame):
382
407
  status.resize()
@@ -451,6 +476,14 @@ def main():
451
476
  termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old_term)
452
477
  status.clear()
453
478
 
479
+ # PTY EOF/EIO may precede the nonblocking wait above. Preserve the
480
+ # command's exit code in that case as well (restored from 0.1.24).
481
+ if child_exit is None:
482
+ _, wait_status = os.waitpid(pid, 0)
483
+ if os.WIFEXITED(wait_status):
484
+ child_exit = os.WEXITSTATUS(wait_status)
485
+ elif os.WIFSIGNALED(wait_status):
486
+ child_exit = 128 + os.WTERMSIG(wait_status)
454
487
  raise SystemExit(child_exit)
455
488
 
456
489
 
package/docs/RELEASING.md CHANGED
@@ -1,6 +1,18 @@
1
1
  # npm release
2
2
 
3
- The prepared version is **0.1.26**, following the published 0.1.25. Preparing or pushing this release does not publish it to npm.
3
+ The prepared version is **0.1.28**, following the published 0.1.27. Preparing or pushing this release does not publish it to npm.
4
+
5
+ ## Fixes in 0.1.28
6
+
7
+ - Restore the 0.1.24 automatic Codex wrapper default, including after reset. Keep the 0.1.26 non-destructive refresh behavior. Explicit opt-out skips setup without removing existing integrations.
8
+ - Diagnose visibility, TUI readiness and current-session attachment separately; report incomplete setup for missing prerequisites. Restore the 0.1.24 PTY EOF exit-status fix.
9
+ - See [the published-package regression audit](SETUP-REGRESSION.md). Test upgrades from the last working 0.1.24 and the current 0.1.27.
10
+
11
+ ## Fixes in 0.1.27
12
+
13
+ - POSIX terminal rows measure Korean/full-width text in screen cells, retain colors while clipping, and clear the old tail without space padding. Repeated refreshes no longer wrap the bottom row and accumulate meter copies in the Codex screen or scrollback. Bounded rows show unavailable providers as `Codex --%` / `Claude --%`; detailed diagnostics retain localized errors.
14
+
15
+ The active runner keeps its Python code until the next launch. Updating the CLI formatter also mitigates the reported Korean-error overflow in already-running sessions, since each status poll loads the formatter again. Existing Codex processes need not be terminated.
4
16
 
5
17
  ## Fixes in 0.1.26
6
18
 
@@ -16,14 +28,16 @@ The prepared version is **0.1.26**, following the published 0.1.25. Preparing or
16
28
  ```text
17
29
  npm run check
18
30
  npm run smoke:linux
19
- mkdir -p .cache/releases/0.1.26
31
+ mkdir -p .cache/releases/0.1.28
20
32
  npm pack --dry-run --json
21
- npm pack --pack-destination .cache/releases/0.1.26 --json
33
+ npm pack --pack-destination .cache/releases/0.1.28 --json
22
34
  ```
23
35
 
24
36
  The regression suite includes real PTYs: an already-running wrapped Codex remains interactive during setup, the same Bash command cache launches it again, a fresh shell displays the usage row, and an attached tmux client displays the bar after live setup. An open wrapper reader retains its old bytes, compatibility command paths and recovery backups survive, and user Codex/shell/tmux settings are compared exactly.
25
37
 
26
- Also install 0.1.25 into an isolated npm prefix, open the PTY fixture, upgrade that prefix to the exact 0.1.26 tarball, and run default setup while the original terminal remains open. Save the lifecycle report, package manifest, SHA256 checksum, installed-package smoke report and publish dry-run under `.cache/releases/0.1.26/`.
38
+ POSIX screen regressions replay actual output into a terminal emulator and inspect the rendered rows, cursor and scrollback. They cover repeated Korean error rows, narrow widths, wide/combining characters, control sequences, shorter replacement text, resize and keyboard input through a live PTY.
39
+
40
+ Also install each of 0.1.24 and 0.1.27 into an isolated npm prefix, open the PTY fixture, upgrade that prefix to the exact 0.1.28 tarball, and run default setup while the original terminal remains open. Save the lifecycle report, package manifest, SHA256 checksum, installed-package smoke report and publish dry-run under `.cache/releases/0.1.28/`.
27
41
 
28
42
  The Linux GUI smoke test opens the actual popup in an isolated GNOME 50.1 Wayland session, verifies zero border width for the content and box pointer, and saves a screenshot. It also checks shared macOS SVG size, provider visibility, extension fallback/reconnect and shutdown. Native Windows/macOS runtime tests require their respective environments; platform-neutral regressions still run here.
29
43
 
@@ -33,22 +47,22 @@ Inspect the tarball for runtime modules, stable bin entrypoints and required pla
33
47
 
34
48
  ```text
35
49
  npm whoami
36
- npm publish .cache/releases/0.1.26/ai-battery-0.1.26.tgz --access public --tag latest
50
+ npm publish .cache/releases/0.1.28/ai-battery-0.1.28.tgz --access public --tag latest
37
51
  npm view ai-battery version dist-tags --json
38
52
  ```
39
53
 
40
- Authenticate with `npm login` if required, and complete npm 2FA when requested. If 0.1.26 is already published, increment the version and repeat verification. Tag the tested commit `v0.1.26` after publication.
54
+ Authenticate with `npm login` if required, and complete npm 2FA when requested. If 0.1.28 is already published, increment the version and repeat verification. Tag the tested commit `v0.1.28` after publication.
41
55
 
42
56
  ## Update and enable terminal display
43
57
 
44
58
  ```text
45
- npm install -g ai-battery@0.1.26
59
+ npm install -g ai-battery@0.1.28
46
60
  ai-battery setup
47
61
  ai-battery setup tmux
48
62
  tmux
49
63
  ```
50
64
 
51
- For a Codex usage row outside tmux, enable it once with `ai-battery setup codex --wrap-codex` and run the printed source command in existing shells. New shells load it automatically. Subsequent setup calls preserve that choice. Re-running setup does not require closing running Codex sessions.
65
+ Plain setup enables the Codex usage row outside tmux. Run the printed source command in existing shells. New shells load it automatically. Subsequent setup calls preserve that choice. Re-running setup does not require closing running Codex sessions.
52
66
 
53
67
  GNOME caches loaded extension JavaScript. After its display code changes, sign out and back in when convenient, then start the HUD again. The terminal integration does not require a desktop restart.
54
68
 
@@ -0,0 +1,63 @@
1
+ # Codex setup regression: 0.1.24 to 0.1.27
2
+
3
+ The Linux HUD feature did not require a change to Codex terminal setup. The
4
+ 0.1.25 release nevertheless lost the default setup behavior shipped in 0.1.24.
5
+ This was a release regression, not a Linux limitation or a user configuration
6
+ requirement.
7
+
8
+ ## Evidence
9
+
10
+ The published npm tarballs for all four versions were inspected, including
11
+ `lib/cli.js` and `bin/ai-battery-run`:
12
+
13
+ | Version | Default Codex wrapper | Setup can remove an existing wrapper | PTY EOF preserves child exit status |
14
+ | --- | --- | --- | --- |
15
+ | 0.1.24 | enabled | yes, with explicit opt-out | yes |
16
+ | 0.1.25 | disabled | yes, during default setup | no |
17
+ | 0.1.26 | disabled | no | no |
18
+ | 0.1.27 | disabled | no | no |
19
+ | 0.1.28 | enabled | no; removal uses reset | yes |
20
+
21
+ Commit `869683e` restored automatic display, the `--no-wrap-codex` option and
22
+ PTY exit handling for 0.1.24 on `fix/setup-codex-defaults`. That branch was not
23
+ merged into main before the 0.1.25 Linux HUD release. Main continued from
24
+ `98ae375` (0.1.23); the published 0.1.25 package also has `wrapCodex: false`.
25
+
26
+ 0.1.26 (`2307c89`) stopped setup from consuming recovery records and deleting
27
+ wrapper paths. It preserved an existing integration but did not restore the
28
+ 0.1.24 default. Therefore a reset, which correctly removes the integration,
29
+ followed by plain setup still produced a standalone Codex command. 0.1.27
30
+ fixed Korean row wrapping but retained that setup regression.
31
+
32
+ ## Why diagnosis and testing missed it
33
+
34
+ `providerEnabled` is an on/off visibility preference. It defaults to true even
35
+ without an installed integration. The concise doctor formatter displayed it
36
+ as `Codex: on`, while suppressing the missing-wrapper note. That made a display
37
+ preference look like a successful installation.
38
+
39
+ Most live setup tests explicitly passed `--wrap-codex`. Another test asserted
40
+ that default setup should leave Codex standalone. They tested the regressed
41
+ behavior rather than the setup contract of the last working release.
42
+
43
+ ## Restored contract
44
+
45
+ - Plain setup and setup codex install or refresh the managed PATH wrapper.
46
+ The original Codex executable, Codex configuration and session history are
47
+ preserved. New tmux integration remains explicit.
48
+ - Setup never detaches an existing integration. `--no-wrap-codex` skips wrapper
49
+ setup and preserves existing files; reset is the removal operation.
50
+ - Reset followed by plain setup restores the terminal row for new sessions.
51
+ An already-running Codex keeps running through both operations.
52
+ - Missing Codex, Python or runner prerequisites produce incomplete setup and a
53
+ failing exit status, with a cause and next step.
54
+ - Doctor reports visibility, integration readiness and current-session
55
+ attachment separately. Missing integration, PATH mismatch, missing runner,
56
+ missing Python and missing original Codex each have their own state and
57
+ action. A missing optional Codex built-in status line is not a wrapper error.
58
+ - Claude diagnosis distinguishes an installed hook waiting for first-use data
59
+ from missing, external, outdated or invalid settings.
60
+
61
+ Release checks now cover default setup without opt-in flags, reset/setup,
62
+ fresh shells, live terminals and upgrades from both 0.1.24 and 0.1.27. Package
63
+ validation uses the exact npm tarball, in addition to source tests.
package/lib/cli.js CHANGED
@@ -20,6 +20,7 @@ import { createIntegrationFiles } from "./core/integration-files.js";
20
20
  import { cliError, cliText, helpText, invalidChoice, requiredValue } from "./core/cli-help.js";
21
21
  import { errorText, messageText as cliMessageText } from "./core/cli-messages.js";
22
22
  import { formatClaudeResult, formatDoctorResult, formatResetResult, formatSetupResult, formatVisibilityResult } from "./core/cli-output.js";
23
+ import { codexTerminalDisplay, claudeTerminalDisplay } from "./core/diagnostics.js";
23
24
  import {
24
25
  cacheAgeSeconds,
25
26
  clamp,
@@ -114,7 +115,7 @@ function parseArgs(argv) {
114
115
  hudState: false,
115
116
  silent: false,
116
117
  force: false,
117
- wrapCodex: false,
118
+ wrapCodex: true,
118
119
  configureCodexStatusLine: false,
119
120
  attachHud: false,
120
121
  header: true,
@@ -167,6 +168,8 @@ function parseArgs(argv) {
167
168
  args.force = true;
168
169
  } else if (arg === "--wrap-codex") {
169
170
  args.wrapCodex = true;
171
+ } else if (arg === "--no-wrap-codex") {
172
+ args.wrapCodex = false;
170
173
  } else if (arg === "--configure-codex-statusline") {
171
174
  args.configureCodexStatusLine = true;
172
175
  } else if (arg === "--attach-hud") {
@@ -468,7 +471,7 @@ function runningInsideCodex() {
468
471
  }
469
472
 
470
473
  function runningInsideAiBatteryCodexWrapper() {
471
- return Boolean(process.env.AI_BATTERY_WRAPPED_CODEX || process.env.AI_BATTERY_ORIGINAL_CODEX);
474
+ return process.env.AI_BATTERY_WRAPPED_CODEX === "1";
472
475
  }
473
476
 
474
477
  function scriptDir() {
@@ -1904,9 +1907,6 @@ function diagnoseCodex() {
1904
1907
  if (!wrapperInstalled) {
1905
1908
  notes.push("Codex wrapper is not installed. Run: ai-battery setup codex");
1906
1909
  }
1907
- if (!statusLine.configured) {
1908
- notes.push("Codex status_line is not configured. Run: ai-battery setup codex");
1909
- }
1910
1910
  if (activeIsWrapper && !wrapperInstalled) {
1911
1911
  notes.push("Plain \"codex\" still resolves to an AI Battery wrapper outside the configured shim. Run: ai-battery reset codex");
1912
1912
  }
@@ -1964,7 +1964,7 @@ function diagnoseCodex() {
1964
1964
  const restartNote = codexRestartNote();
1965
1965
  if (restartNote) notes.push(restartNote);
1966
1966
 
1967
- return {
1967
+ const diagnostic = {
1968
1968
  providerEnabled,
1969
1969
  runtimeHome,
1970
1970
  sessionsPath,
@@ -1991,6 +1991,8 @@ function diagnoseCodex() {
1991
1991
  currentCodexWrapped: runningInsideAiBatteryCodexWrapper(),
1992
1992
  notes
1993
1993
  };
1994
+ diagnostic.terminalDisplay = codexTerminalDisplay(diagnostic, { layout: windowsLayout });
1995
+ return diagnostic;
1994
1996
  }
1995
1997
 
1996
1998
  function diagnoseClaudeStatusLine() {
@@ -2025,9 +2027,10 @@ function diagnoseClaudeStatusLine() {
2025
2027
  }
2026
2028
 
2027
2029
  async function runDoctor() {
2030
+ const recoveryConfig = readConfig({ strict: true });
2028
2031
  const version = await checkPackageVersion();
2029
2032
  const claudeStatusLine = diagnoseClaudeStatusLine();
2030
- const recoveryConfig = readConfig();
2033
+ const claudeReading = Boolean(readClaudeStatuslineCache());
2031
2034
  return {
2032
2035
  generatedAt: new Date().toISOString(),
2033
2036
  aiBattery: {
@@ -2057,8 +2060,9 @@ async function runDoctor() {
2057
2060
  claude: {
2058
2061
  providerEnabled: providerVisible("claude"),
2059
2062
  cachePath: claudeCachePath(),
2060
- statuslineCache: Boolean(readClaudeStatuslineCache()),
2063
+ statuslineCache: claudeReading,
2061
2064
  statusLine: claudeStatusLine,
2065
+ terminalDisplay: claudeTerminalDisplay(claudeStatusLine, claudeReading),
2062
2066
  notes: [
2063
2067
  !claudeStatusLine.configured ? "Claude statusLine is not configured. Run: ai-battery setup claude" : null,
2064
2068
  claudeStatusLine.configured && !claudeStatusLine.managed
@@ -2278,19 +2282,22 @@ function runSetup(args) {
2278
2282
  results.tmux = installTmuxStatus(tmuxRefreshPath ? { confPath: tmuxRefreshPath } : {});
2279
2283
  }
2280
2284
  if (targets.includes("codex")) {
2281
- const wrapCodex = args.wrapCodex || Boolean(previous.codexWrapper)
2282
- || codexWrapperCandidates(previous).some(file => managedCodexWrapper(file));
2285
+ const wrapCodex = args.wrapCodex;
2283
2286
  const statusLine = args.configureCodexStatusLine ? installCodexStatusLine(args) : null;
2284
2287
  if (wrapCodex) {
2285
- results.codex = { ...installCodexWrapper(args), statusLine };
2288
+ const prerequisite = !codexRunnerExists() ? "AI Battery runner is missing. Reinstall: npm install -g ai-battery@latest"
2289
+ : process.platform !== "win32" && !findCommand("python3") ? "Python 3 is required for the Codex terminal row. Install Python 3, then run ai-battery setup codex." : null;
2290
+ results.codex = prerequisite ? { ok: false, skipped: true, reason: prerequisite, statusLine }
2291
+ : { ...installCodexWrapper(args), statusLine };
2286
2292
  } else {
2287
2293
  results.codex = {
2288
2294
  ok: true,
2289
- standalone: true,
2290
- reason: "Codex command and configuration are left under Codex's control.",
2295
+ wrapperSetupSkipped: true,
2296
+ reason: "Codex wrapper setup skipped (--no-wrap-codex). Existing integrations are preserved; remove them with ai-battery reset codex.",
2291
2297
  statusLine
2292
2298
  };
2293
2299
  }
2300
+ results.codex.providerEnabled = providerVisible("codex");
2294
2301
  if (process.platform === "win32" && wrapCodex) {
2295
2302
  results.codex.rowpty = windowsSetupNeedsRowPty()
2296
2303
  ? (windowsClaudeLauncher || installRowPtyHost())
@@ -2312,6 +2319,8 @@ function setupResultFailed(result) {
2312
2319
  || result.claude?.launcher?.error
2313
2320
  || (result.claude?.launcher && result.claude.launcher.ok === false)
2314
2321
  || (result.codex && result.codex.ok === false)
2322
+ || result.codex?.path?.ok === false
2323
+ || result.codex?.path?.error
2315
2324
  || result.codex?.statusLine?.error
2316
2325
  || result.codex?.rowpty?.error
2317
2326
  || (result.codex?.rowpty && result.codex.rowpty.ok === false)
@@ -4378,7 +4387,8 @@ function weekText(secondary) {
4378
4387
  }
4379
4388
 
4380
4389
  function formatCodex(data, args) {
4381
- if (!data.ok) return statusColorize(data, `Codex ? (${cliMessageText(data.error)})`, args);
4390
+ if (!data.ok) return statusColorize(data, args.maxWidth && !args.showPaths
4391
+ ? "Codex --%" : `Codex ? (${cliMessageText(data.error)})`, args);
4382
4392
 
4383
4393
  const batteryColor = remainingColor(data.percentRemaining);
4384
4394
  const primary = data.primary;
@@ -4413,7 +4423,8 @@ function formatCodex(data, args) {
4413
4423
  }
4414
4424
 
4415
4425
  function formatClaude(data, args) {
4416
- if (!data.ok) return statusColorize(data, `Claude ? (${cliMessageText(data.error)})`, args);
4426
+ if (!data.ok) return statusColorize(data, args.maxWidth && !args.showPaths
4427
+ ? "Claude --%" : `Claude ? (${cliMessageText(data.error)})`, args);
4417
4428
 
4418
4429
  if (data.sourceType === "statusline") {
4419
4430
  const batteryColor = remainingColor(data.percentRemaining);
@@ -4977,7 +4988,7 @@ function render(snapshot, args) {
4977
4988
  }
4978
4989
  // A split pane can be too narrow even for the minimum bars. Retain both
4979
4990
  // names and readings rather than letting the one-row terminal wrap away
4980
- // a provider. Error detail and bars remain available in wider panes.
4991
+ // a provider. Detailed errors remain available in diagnostics.
4981
4992
  const readings = snapshot.results.map((result) => {
4982
4993
  const percent = typeof result.percentRemaining === "number" ? `${result.percentRemaining}%` : "--%";
4983
4994
  const name = result.provider === "codex" ? "Codex" : result.provider === "claude" ? "Claude" : result.provider;
@@ -5016,7 +5027,7 @@ async function main() {
5016
5027
  console.log(formatSetupResult(result, {
5017
5028
  failed,
5018
5029
  reloadCommand: sourcePathCommand(result.codex?.path?.rcPath),
5019
- restartNote: result.codex && !result.codex.standalone ? codexRestartNote() : null
5030
+ restartNote: result.codex?.ok && !result.codex.wrapperSetupSkipped ? codexRestartNote() : null
5020
5031
  }));
5021
5032
  }
5022
5033
  if (failed) process.exitCode = 1;
@@ -82,17 +82,18 @@ export function helpText(command = "", { env = process.env, platform = process.p
82
82
  return [
83
83
  usage(legacy ? `${command} [--force]` : "setup [codex|claude|tmux|all] [options]"),
84
84
  legacy ? t("Configure Claude Code's usage status line.", "Claude Code 상태 표시줄에 사용량을 연결합니다.")
85
- : t("Configure usage display. Existing integrations are preserved and refreshed; new tmux integration is opt-in.", "사용량 표시를 연동합니다. 기존 연동은 유지·갱신하며 새 tmux 연동은 별도로 지정합니다."),
85
+ : t("Enable Codex and Claude Code terminal usage display. Specify tmux separately.", "Codex와 Claude Code의 터미널 사용량 표시를 연결합니다. tmux는 별도로 지정합니다."),
86
86
  options([
87
87
  ["--force", "Replace an existing Claude statusLine", "기존 Claude 상태 표시줄 교체"],
88
88
  ...(!legacy ? [
89
- ["--wrap-codex", "Route the codex command through AI Battery", "codex 명령에 AI Battery 연결"],
89
+ ["--wrap-codex", "Enable Codex terminal display (default)", "Codex 터미널 표시 연결 (기본)"],
90
+ ["--no-wrap-codex", "Skip Codex wrapper setup", "Codex wrapper 설정 생략"],
90
91
  ["--configure-codex-statusline", "Configure Codex's built-in status line", "Codex 내장 상태 표시줄 설정"]
91
92
  ] : []),
92
93
  json
93
94
  ]),
94
95
  legacy ? t("Restore settings: ai-battery reset claude", "설정 복원: ai-battery reset claude")
95
- : t("By default, Codex keeps its command, PATH and settings.\nRestore settings: ai-battery reset", "기본 Codex 설치는 실행 명령·PATH·설정을 유지합니다.\n설정 복원: ai-battery reset"),
96
+ : t("The original Codex executable and settings are preserved.\nRestore settings: ai-battery reset", "Codex 원본 실행 파일과 설정은 유지합니다.\n설정 복원: ai-battery reset"),
96
97
  examples(legacy ? [`ai-battery ${command}`] : ["ai-battery setup tmux"])
97
98
  ].join("\n\n");
98
99
  }
@@ -110,7 +111,7 @@ export function helpText(command = "", { env = process.env, platform = process.p
110
111
  return [usage(`${command} [codex|claude|all]`), command === "on"
111
112
  ? t("Show the selected tools (default: all).", "선택한 도구의 사용량을 표시합니다. 기본 대상은 all입니다.")
112
113
  : t("Hide the selected tools (default: all).", "선택한 도구의 사용량을 숨깁니다. 기본 대상은 all입니다."),
113
- options([json]), examples([`ai-battery ${command} codex`])].join("\n\n");
114
+ options([json]), t("Changes visibility only. Configure terminal integration with ai-battery setup.", "표시 설정만 변경합니다. 터미널 연결: ai-battery setup"), examples([`ai-battery ${command} codex`])].join("\n\n");
114
115
  }
115
116
  if (command === "doctor") {
116
117
  return [usage("doctor [--json]"), t("Check installation, integrations and available updates.", "설치 상태, 연동 설정, 업데이트를 확인합니다."), options([json])].join("\n\n");
@@ -72,6 +72,14 @@ const messages = [
72
72
  ["CODEX_HOME contains a comma and the literal path does not exist. Multiple homes are not supported; correct CODEX_HOME before using /resume.", "CODEX_HOME에 존재하는 경로 하나를 지정하세요. 쉼표로 여러 경로를 지정할 수 없습니다.", "Set CODEX_HOME to one existing directory; comma-separated paths are unsupported."],
73
73
  ["Codex session directory was not found: {path}", "Codex 로그를 찾을 수 없습니다: {path}", "Codex logs not found: {path}"],
74
74
  ["Codex provider is hidden. Run: ai-battery on codex", "Codex 사용량 표시 켜기: ai-battery on codex", "Show Codex usage: ai-battery on codex"],
75
+ ["Open a new terminal to apply PATH changes.", "새 터미널에서 PATH 변경을 적용하세요."],
76
+ ["Load the shell configuration or open a new terminal, then run hash -r (zsh: rehash).", "셸 설정을 불러오거나 새 터미널을 연 뒤 hash -r(zsh: rehash)을 실행하세요."],
77
+ ["Install Python 3, then run codex again.", "Python 3 설치 후 codex를 다시 실행하세요."],
78
+ ["Install Codex or restore its original command on PATH, then run ai-battery setup codex.", "PATH에 원본 Codex 명령을 설치·복구한 뒤 ai-battery setup codex를 실행하세요."],
79
+ ["Set AI_BATTERY_WIN_LAYOUT=composite, then run codex again.", "AI_BATTERY_WIN_LAYOUT=composite로 설정한 뒤 codex를 다시 실행하세요."],
80
+ ["Start Claude Code to receive usage data.", "Claude Code를 실행하면 사용량이 수집됩니다."],
81
+ ["AI Battery runner is missing. Reinstall: npm install -g ai-battery@latest", "AI Battery runner가 없습니다. 재설치: npm install -g ai-battery@latest"],
82
+ ["Python 3 is required for the Codex terminal row. Install Python 3, then run ai-battery setup codex.", "Codex 터미널 표시에 Python 3가 필요합니다. 설치 후 ai-battery setup codex를 실행하세요."],
75
83
  ["Plain \"codex\" still resolves to an AI Battery wrapper outside the configured shim. Run: ai-battery reset codex", "이전 Codex wrapper가 남아 있습니다. 복원: ai-battery reset codex", "Legacy Codex wrapper detected. Restore: ai-battery reset codex"],
76
84
  ["A Codex backup is available for restore: {path}", "Codex 복구 파일: {path}", "Codex restore backup: {path}"],
77
85
  ["Plain \"codex\" does not resolve to the AI Battery wrapper in this shell. Ensure {path} is before the original codex on PATH, then {action}.", "PATH에서 원본 codex보다 앞에 배치하세요: {path}\n{action}", "Place before the original codex on PATH: {path}\n{action}"],
@@ -1,5 +1,6 @@
1
1
  import { cliLanguage } from "./cli-help.js";
2
2
  import { errorText, messageText } from "./cli-messages.js";
3
+ import { codexTerminalDisplay, claudeTerminalDisplay } from "./diagnostics.js";
3
4
 
4
5
  function output(env) {
5
6
  const lines = [];
@@ -31,8 +32,9 @@ export function formatSetupResult(result, { failed = false, platform = process.p
31
32
  else if (claude.launcher?.ok === false) o.note(claude.launcher.reason);
32
33
  }
33
34
  if (codex) {
34
- if (codex.standalone) {
35
- o.add("Codex: standalone");
35
+ if (codex.wrapperSetupSkipped) {
36
+ o.add("Codex wrapper: skipped (--no-wrap-codex)");
37
+ o.add(o.t("Existing integrations are preserved. Remove: ai-battery reset codex", "기존 연동은 유지됩니다. 해제: ai-battery reset codex"));
36
38
  } else if (codex.ok) {
37
39
  o.add(`Codex wrapper: ready · ${codex.wrapperPath}`);
38
40
  o.add(`Original: ${codex.originalCommand}`);
@@ -43,11 +45,11 @@ export function formatSetupResult(result, { failed = false, platform = process.p
43
45
  o.error("PATH", codex.path.error || o.t("Could not update PATH.", "PATH를 갱신하지 못했습니다."));
44
46
  }
45
47
  if (/^(Could not|Skipped)/.test(codex.path?.note || "")) o.note(codex.path.note);
48
+ if (codex.providerEnabled === false) o.add("Visibility: off · ai-battery on codex");
46
49
  } else {
47
50
  o.add("Codex: skipped");
48
51
  o.note(codex.reason);
49
52
  }
50
- if (codex.standalone && platform !== "win32" && !tmux) o.add(o.t("Terminal usage: ai-battery setup tmux", "터미널 사용량 표시: ai-battery setup tmux"));
51
53
  if (codex.statusLine) {
52
54
  const status = codex.statusLine;
53
55
  o.add(`Codex status_line: ${status.error ? "error" : status.alreadyConfigured ? "already configured" : "configured"} · ${status.configPath}`);
@@ -86,8 +88,15 @@ export function formatDoctorResult(result, { env = process.env } = {}) {
86
88
  if (battery.updateCheck.error !== "disabled") o.error("npm", battery.updateCheck.error);
87
89
  }
88
90
  o.lines.push("");
89
- o.add(`Codex: ${codex.providerEnabled ? "on" : "off"} · ${codex.activeIsWrapper ? "wrapper" : "standalone"}`);
90
- o.add(` Command: ${codex.activeCodex || "not found"}`);
91
+ const codexDisplay = codex.terminalDisplay || codexTerminalDisplay(codex);
92
+ o.add("Codex:");
93
+ o.add(` Visibility: ${codex.providerEnabled ? "on" : "off"}`);
94
+ if (!codex.providerEnabled) o.add(" Show: ai-battery on codex");
95
+ o.add(` TUI: ${codexDisplay.status}`);
96
+ o.add(` Session: ${codexDisplay.currentSession}`);
97
+ if (codexDisplay.action) o.add(` ${o.t("Fix", "해결")}: ${messageText(codexDisplay.action, env)}`);
98
+ if (codexDisplay.currentSession === "unwrapped") o.add(o.t(" Start a new Codex session after setup to attach the usage row.", " setup 후 새 Codex 세션부터 사용량 줄이 연결됩니다."));
99
+ o.add(` PATH command: ${codex.activeCodex || "not found"}`);
91
100
  o.add(` status_line: ${codex.statusLine.error ? "error" : codex.statusLine.configured ? "configured" : "optional"}`);
92
101
  o.error(" Error", codex.statusLine.error);
93
102
  o.add(` Logs: ${codex.sessionsExists ? "ready" : "not found"}`);
@@ -96,10 +105,14 @@ export function formatDoctorResult(result, { env = process.env } = {}) {
96
105
  if (codex.compositor) o.add(` Compositor: ${codex.compositor.available ? "ready" : "dependencies missing"}`);
97
106
  if (codex.rowpty?.layoutRequested) o.add(` rowpty: ${codex.rowpty.installed ? "ready" : "not found"} · ConPTY: ${codex.rowpty.bundledConpty ? "bundled" : "OS"}`);
98
107
  o.lines.push("");
99
- o.add(`Claude: ${claude.providerEnabled ? "on" : "off"}`);
108
+ const claudeDisplay = claude.terminalDisplay || claudeTerminalDisplay(claude.statusLine, claude.statuslineCache);
109
+ o.add("Claude:");
110
+ o.add(` Visibility: ${claude.providerEnabled ? "on" : "off"}`);
111
+ if (!claude.providerEnabled) o.add(" Show: ai-battery on claude");
112
+ o.add(` TUI: ${claudeDisplay.status}`);
113
+ if (claudeDisplay.action) o.add(` ${o.t("Next", "다음")}: ${messageText(claudeDisplay.action, env)}`);
100
114
  o.add(` statusLine: ${claude.statusLine.error ? "error" : claude.statusLine.managed ? "ready" : claude.statusLine.configured ? "external" : "not configured"}`);
101
115
  o.add(` Cache: ${claude.statuslineCache ? "ready" : "waiting"}`);
102
- if (claude.statusLine.managed && !claude.statuslineCache) o.add(o.t(" Start Claude Code to receive usage data.", " Claude Code를 실행하면 사용량이 수집됩니다."));
103
116
  if (result.tmux) {
104
117
  o.lines.push("");
105
118
  o.add(`tmux: ${result.tmux.error ? "error" : result.tmux.configured ? result.tmux.insideTmux ? "configured · in session" : "configured · outside session" : "not configured"}`);
@@ -0,0 +1,45 @@
1
+ // Installation readiness is independent of the on/off visibility preference.
2
+ // These states describe the next command; an existing session is separate.
3
+ export function codexTerminalDisplay(data, { platform = process.platform, layout = "" } = {}) {
4
+ let status = "ready";
5
+ let action = null;
6
+ if (!data.wrapperInstalled) {
7
+ status = "not configured";
8
+ action = "ai-battery setup codex";
9
+ } else if (!data.activeIsWrapper) {
10
+ status = "PATH mismatch";
11
+ action = platform === "win32" ? "Open a new terminal to apply PATH changes."
12
+ : "Load the shell configuration or open a new terminal, then run hash -r (zsh: rehash).";
13
+ } else if (!data.runnerExists) {
14
+ status = "runner missing";
15
+ action = "npm install -g ai-battery@latest";
16
+ } else if (platform !== "win32" && !data.python3) {
17
+ status = "python3 missing";
18
+ action = "Install Python 3, then run codex again.";
19
+ } else if (!(data.followsPath ? data.resolvedOriginalCommand : data.originalExists)) {
20
+ status = "Codex missing";
21
+ action = "Install Codex or restore its original command on PATH, then run ai-battery setup codex.";
22
+ } else if (platform === "win32" && layout === "plain") {
23
+ status = "disabled by layout";
24
+ action = "Set AI_BATTERY_WIN_LAYOUT=composite, then run codex again.";
25
+ }
26
+ return {
27
+ status,
28
+ ready: status === "ready",
29
+ action,
30
+ currentSession: !data.insideCodex ? "not checked" : data.currentCodexWrapped ? "wrapped" : "unwrapped"
31
+ };
32
+ }
33
+
34
+ export function claudeTerminalDisplay(statusLine, hasReading) {
35
+ const status = statusLine.error ? "settings error" : !statusLine.configured ? "not configured"
36
+ : !statusLine.managed ? "external statusLine" : statusLine.needsRefresh ? "update required"
37
+ : hasReading ? "ready" : "waiting for data";
38
+ return {
39
+ status,
40
+ ready: ["ready", "waiting for data"].includes(status),
41
+ action: status === "not configured" || status === "update required" ? "ai-battery setup claude"
42
+ : status === "external statusLine" ? "ai-battery setup claude --force"
43
+ : status === "waiting for data" ? "Start Claude Code to receive usage data." : null
44
+ };
45
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-battery",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
4
4
  "description": "Tiny terminal battery meter for local Codex and Claude Code usage.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -43,6 +43,7 @@
43
43
  "vendor/rowpty/RowPty.cs",
44
44
  "docs/*.svg",
45
45
  "docs/RELEASING.md",
46
+ "docs/SETUP-REGRESSION.md",
46
47
  "README.md"
47
48
  ],
48
49
  "scripts": {