ai-battery 0.1.21 → 0.1.23

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,6 +1,6 @@
1
1
  # AI Battery
2
2
 
3
- 0.1.19: Codex wrapper는 현재 PATH를 따릅니다. nvm 등의 전환 후 새 Codex를 고정된 이전 경로 대신 실행합니다. Windows·WSL 사용량 공유 수정도 포함하므로 양쪽 설치를 업데이트하세요. Windows Terminal padding 변경은 로컬 표시 조정이며, 패키지는 사용자 터미널 설정을 자동 변경하지 않습니다.
3
+ 0.1.23: 기본 Codex 설치는 실행 명령·PATH·설정을 변경하지 않습니다. `reset settings`는 AI Battery의 설정 변경을 복원하고 생성 파일을 정리하며 npm 패키지는 유지합니다. 패키지 삭제는 `npm uninstall -g ai-battery`로 진행하세요. 기존 Bash 터미널에 삭제된 wrapper 경로가 남았다면 `hash -r`을 실행하세요.
4
4
 
5
5
  [한국어](README.md) · [English](docs/i18n/en/) · [日本語](docs/i18n/ja/) · [中文](docs/i18n/zh/) · [Español](docs/i18n/es/)
6
6
 
@@ -29,34 +29,34 @@ Markdown의 텍스트 fallback은 렌더러별 블록 문자 높이 차이를
29
29
  Codex 86% │ 5h 18:09 │ 7d 82% ┃ Claude 4% │ 5h 18:10 │ 7d 71%
30
30
  ```
31
31
 
32
- | Provider | Source | Shows |
33
- | --- | --- | --- |
34
- | Codex | `~/.codex/sessions/**/*.jsonl` | 5h 잔량, 5h 리셋 시각, 7d 잔량 |
35
- | Claude Code | Claude `statusLine` payload cache + 429 hit logs | 5h 잔량, 5h 리셋 시각, 7d 잔량 |
36
- | Claude fallback | `~/.claude/projects/**/*.jsonl` | 최근 턴 토큰 사용량 |
32
+ | Provider | Source | Shows |
33
+ | --------------- | ------------------------------------------------ | ------------------------------ |
34
+ | Codex | `~/.codex/sessions/**/*.jsonl` | 5h 잔량, 5h 리셋 시각, 7d 잔량 |
35
+ | Claude Code | Claude `statusLine` payload cache + 429 hit logs | 5h 잔량, 5h 리셋 시각, 7d 잔량 |
36
+ | Claude fallback | `~/.claude/projects/**/*.jsonl` | 최근 턴 토큰 사용량 |
37
37
 
38
38
  ## Features
39
39
 
40
- | Feature | Description |
41
- | --- | --- |
42
- | 공통 사용량 표시 | Codex와 Claude Code 사용량을 같은 형식으로 표시합니다. |
43
- | 리셋 시각 표시 | `5h`, `7d` 창 라벨과 값을 표시합니다. |
44
- | 색상 기준 | 40% 초과 초록, 21-40% 주황, 20% 이하 빨강으로 배터리만 강조합니다. |
45
- | Codex terminal row | Windows에서는 가상 터미널 화면과 배터리 행을 합성하고, WSL/Linux/macOS에서는 PTY wrapper로 별도 사용량 행을 고정합니다. |
46
- | Claude statusLine | Claude Code 내장 statusLine hook과 실제 429 hit 로그로 Claude rate limit 상태를 읽습니다. |
47
- | HUD / menu bar | Windows native에서는 terminal-docked/floating HUD, WSL에서는 floating HUD, macOS에서는 menu bar status item을 제공합니다. |
48
- | npm 실행 | `npm install -g` 또는 `npx`로 실행할 수 있습니다. |
40
+ | Feature | Description |
41
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------- |
42
+ | 공통 사용량 표시 | Codex와 Claude Code 사용량을 같은 형식으로 표시합니다. |
43
+ | 리셋 시각 표시 | `5h`, `7d` 창 라벨과 값을 표시합니다. |
44
+ | 색상 기준 | 40% 초과 초록, 21-40% 주황, 20% 이하 빨강으로 배터리만 강조합니다. |
45
+ | Codex terminal row | Windows에서는 가상 터미널 화면과 배터리 행을 합성하고, WSL/Linux/macOS에서는 PTY wrapper로 별도 사용량 행을 고정합니다. |
46
+ | Claude statusLine | Claude Code 내장 statusLine hook과 실제 429 hit 로그로 Claude rate limit 상태를 읽습니다. |
47
+ | HUD / menu bar | Windows native에서는 terminal-docked/floating HUD, WSL에서는 floating HUD, macOS에서는 menu bar status item을 제공합니다. |
48
+ | npm 실행 | `npm install -g` 또는 `npx`로 실행할 수 있습니다. |
49
49
 
50
50
  ## Platform Support
51
51
 
52
- | Mode | Windows native | WSL | Linux | macOS | Note |
53
- | --- | --- | --- | --- | --- | --- |
54
- | `ai-battery` | 지원 | 지원 | 지원 | 지원 | Node.js 18 이상이 필요합니다. |
55
- | `ai-battery --watch` | 지원 | 지원 | 지원 | 지원 | 터미널 안에서 주기적으로 갱신합니다. |
56
- | Claude statusLine | 지원 | 지원 | 지원 | 지원 | Claude Code `statusLine`에 `node <script>` 명령을 저장합니다. |
57
- | Codex fullscreen | 지원 | 지원 | 지원 | 지원 | Windows 기본값은 Fullscreen PTY 화면과 터미널 배터리 행을 합성합니다. WSL/Linux/macOS는 POSIX PTY와 `python3`를 사용합니다. |
58
- | `ai-battery setup codex` | 지원 | 지원 | 지원 | 지원 | Codex `[tui].status_line`을 맞추고, Windows는 `codex.cmd` wrapper, WSL/Linux/macOS는 POSIX shell wrapper를 설치합니다. |
59
- | `ai-battery hud` | 지원 | 지원 | 미지원 | 지원 | Windows/WSL은 PowerShell/WinForms HUD, macOS는 menu bar status item입니다. |
52
+ | Mode | Windows native | WSL | Linux | macOS | Note |
53
+ | ------------------------ | -------------- | ---- | ------ | ----- | --------------------------------------------------------------------------------------------------------------------------- |
54
+ | `ai-battery` | 지원 | 지원 | 지원 | 지원 | Node.js 18 이상이 필요합니다. |
55
+ | `ai-battery --watch` | 지원 | 지원 | 지원 | 지원 | 터미널 안에서 주기적으로 갱신합니다. |
56
+ | Claude statusLine | 지원 | 지원 | 지원 | 지원 | Claude Code `statusLine`에 `node <script>` 명령을 저장합니다. |
57
+ | Codex fullscreen | 지원 | 지원 | 지원 | 지원 | Windows 기본값은 Fullscreen PTY 화면과 터미널 배터리 행을 합성합니다. WSL/Linux/macOS는 POSIX PTY와 `python3`를 사용합니다. |
58
+ | `ai-battery setup codex` | 지원 | 지원 | 지원 | 지원 | 기존 AI Battery wrapper를 해제합니다. 새 wrapper나 Codex 설정 변경은 명시적 옵션이 필요합니다. |
59
+ | `ai-battery hud` | 지원 | 지원 | 미지원 | 지원 | Windows/WSL은 PowerShell/WinForms HUD, macOS는 menu bar status item입니다. |
60
60
 
61
61
  실행 중 감지는 Linux/WSL은 `/proc`, macOS는 `ps`, Windows는 PowerShell 프로세스 목록을 사용합니다. 텍스트 출력은 흰색/회색으로, macOS HUD는 실행 중인 항목만 색상 배터리바로 강조하고 비실행 항목은 흐린 회색 계열로 표시합니다.
62
62
 
@@ -82,7 +82,7 @@ npx ai-battery
82
82
  npm install -g ai-battery
83
83
  ```
84
84
 
85
- 2. Claude와 Codex 자동 표시를 설정합니다.
85
+ 2. Claude statusLine을 설정하고, 기존 Codex wrapper가 있으면 해제합니다.
86
86
 
87
87
  ```bash
88
88
  ai-battery setup
@@ -95,7 +95,7 @@ npx ai-battery
95
95
  codex
96
96
  ```
97
97
 
98
- 4. 데스크톱 HUD나 macOS menu bar 표시가 필요하면 실행합니다.
98
+ 4. Codex 사용량은 별도 터미널의 `ai-battery --watch 2`, 또는 Windows/WSL/macOS HUD로 확인합니다.
99
99
 
100
100
  ```bash
101
101
  ai-battery hud
@@ -111,56 +111,59 @@ ai-battery --version
111
111
  ai-battery --provider codex
112
112
  ai-battery --provider claude
113
113
  ai-battery setup
114
- ai-battery uninstall
114
+ ai-battery reset settings
115
115
  ai-battery doctor
116
116
  ai-battery hud
117
117
  ai-battery off codex
118
118
  ai-battery on codex
119
119
  ```
120
120
 
121
- | Option | Description |
122
- | --- | --- |
123
- | `--provider all\|codex\|claude` | 표시할 provider를 선택합니다. |
124
- | `--watch [seconds]` | 같은 줄에서 주기적으로 갱신합니다. |
125
- | `--json` | HUD나 다른 도구에서 쓰기 좋은 JSON을 출력합니다. |
126
- | `--bar-width N` | 터미널 배터리 바 길이를 조정합니다. |
127
- | `--show-paths` | 로그 파일 경로와 데이터 관측 시각을 함께 표시합니다. |
128
- | `-v`, `--version` | 설치된 `ai-battery` 버전을 출력합니다. |
121
+ | Option | Description |
122
+ | ------------------------------- | ---------------------------------------------------- |
123
+ | `--provider all\|codex\|claude` | 표시할 provider를 선택합니다. |
124
+ | `--watch [seconds]` | 같은 줄에서 주기적으로 갱신합니다. |
125
+ | `--json` | HUD나 다른 도구에서 쓰기 좋은 JSON을 출력합니다. |
126
+ | `--bar-width N` | 터미널 배터리 바 길이를 조정합니다. |
127
+ | `--show-paths` | 로그 파일 경로와 데이터 관측 시각을 함께 표시합니다. |
128
+ | `-v`, `--version` | 설치된 `ai-battery` 버전을 출력합니다. |
129
129
 
130
130
  `doctor`는 설치 상태와 함께 npm latest 버전을 확인합니다. 네트워크가 막혀 있으면 버전 확인만 건너뛰고 나머지 진단은 계속 표시합니다.
131
131
 
132
- ## Uninstall
132
+ <a id="uninstall"></a>
133
133
 
134
- `off`는 표시만 숨기는 설정이고, `uninstall`은 `setup`과 HUD autostart가 만든 통합 지점을 제거합니다.
134
+ ## Reset Settings
135
+
136
+ `ai-battery reset settings`는 AI Battery가 추가한 통합 설정을 원래 값으로 복원하고, 소유권을 확인한 AI Battery 캐시·전용 런타임·생성 파일을 정리합니다. Codex·Claude의 관련 없는 설정과 npm 패키지·실행 명령은 유지합니다. Codex나 Claude의 설정 전체를 기본값으로 초기화하는 명령은 아닙니다.
135
137
 
136
138
  ```bash
137
- ai-battery uninstall
139
+ ai-battery reset settings
138
140
  ```
139
141
 
140
- 일부만 제거할 수도 있습니다.
142
+ `ai-battery reset config`도 같은 동작입니다. 일부 통합만 복원하려면 대상을 지정합니다. 대상 지정 시 다른 통합과 공통 캐시는 유지합니다.
141
143
 
142
144
  ```bash
143
- ai-battery uninstall codex
144
- ai-battery uninstall claude
145
- ai-battery uninstall hud
145
+ ai-battery reset settings codex
146
+ ai-battery reset settings claude
147
+ ai-battery reset settings hud
148
+ ai-battery reset settings tmux
146
149
  ```
147
150
 
148
- 이 명령은 AI Battery가 관리 마커를 넣은 Codex wrapper, Codex `[tui].status_line`, Claude `statusLine`, HUD/menu bar autostart와 실행 중인 HUD를 정리합니다. 다른 도구가 만든 `codex` 파일이나 Claude `statusLine`은 건드리지 않습니다. setup 전에 복구 기록을 먼저 저장하며, 이후 사용자가 추가한 관련 없는 Codex/Claude 설정은 보존하고 AI Battery가 관리한 값만 원래 값으로 되돌립니다. 관리 중인 status line 자체나 wrapper 파일이 setup 이후 다른 값으로 바뀌었다면 덮어쓰거나 삭제하지 않고 복구 기록과 PATH를 유지한 채 종료 코드 1로 알립니다. 원본 command backup이 있는 wrapper는 현재 wrapper를 임시 보존한 뒤 원본 교체가 성공한 경우에만 삭제합니다. 현재 이미 AI Battery wrapper 안에서 실행 중인 Codex 세션의 terminal row는 그 세션을 종료해야 사라집니다.
149
-
150
- 복구 기록은 `ai-battery uninstall`이 해당 항목을 성공적으로 복원하거나 안전하게 제거한 뒤에만 지워집니다. Claude는 기존 `statusLine`과 파일 존재 여부·권한만 저장하며 `settings.json` 전체를 복제하지 않으므로 다른 설정이나 비밀값을 백업 파일에 중복 보관하지 않습니다. JSON 결과나 종료 코드를 확인하는 자동화에서는 0일 때만 완전한 정리로 간주하세요.
151
+ 관리 중인 status line이나 설정 블록이 사용자에 의해 변경됐다면 덮어쓰지 않고 복구 기록을 보존하며 종료 코드 1로 알립니다. 관련 없는 Codex·Claude 설정, 사용자 추가 파일, 확인할 수 없는 파일은 보존합니다. 셸·tmux의 사용자 수정도 관리 블록 밖의 내용은 유지합니다. 복구 기록은 해당 항목이 복원되거나 안전하게 제거된 뒤에만 지워집니다.
151
152
 
152
- 최신 npm은 패키지의 uninstall lifecycle을 실행하지 않기 때문에 `npm uninstall ai-battery` 또는 `npm uninstall -g ai-battery`만으로는 외부 통합 지점을 자동 정리할 수 없습니다. 완전히 제거하려면 npm 패키지를 지우기 전에 먼저 실행하세요.
153
+ 패키지까지 삭제하려면 설정 복원이 성공한 다음 npm으로 제거합니다. 로컬 설치는 `npm uninstall ai-battery`, 전역 설치는 아래 명령을 사용합니다. Windows와 WSL, Node 버전별 설치는 각각 진행하세요.
153
154
 
154
155
  ```bash
155
- ai-battery uninstall
156
- npm uninstall -g ai-battery
156
+ ai-battery reset settings && npm uninstall -g ai-battery
157
+ hash -r # Bash: 기존 터미널의 삭제된 wrapper 경로 캐시 해제 (zsh: rehash)
157
158
  ```
158
159
 
159
- 이미 npm 패키지를 먼저 지운 뒤라면, 다시 설치한 다음 `ai-battery uninstall`을 실행하거나 아래 항목을 직접 확인해 제거해야 합니다: AI Battery가 만든 Codex wrapper, shell rc의 `# >>> ai-battery setup >>>` block, Codex `~/.codex/config.toml`의 `[tui].status_line`, Claude `statusLine`, HUD/menu bar autostart.
160
+ CLI는 npm 제거를 자동 실행하지 않습니다. `teardown`과 `uninstall`은 호환용 별칭으로 남아 있으며, 동일하게 설정과 생성 파일만 정리합니다. `off`는 표시만 숨깁니다. 이미 npm 패키지를 먼저 지웠다면 다시 설치하고 `reset settings`로 통합부터 복원하세요.
161
+
162
+ 자식 프로세스인 CLI는 부모 셸의 명령 캐시를 지울 수 없습니다. 새 터미널을 열어도 캐시는 초기화됩니다. 이미 wrapper로 시작한 Codex 세션의 하단 행은 해당 세션을 종료해야 사라집니다.
160
163
 
161
164
  ## Setup
162
165
 
163
- `setup`은 한 번만 실행합니다. Claude Code에는 statusLine hook을 설치하고, Codex에는 기본 status line 구성과 platform wrapper를 설치해서 이후에는 추가 명령 없이 원래처럼 실행하게 합니다.
166
+ `setup`은 Claude Code의 statusLine hook을 설정합니다. Codex는 기본적으로 독립 실행을 유지하며, 이전 버전의 AI Battery wrapper와 변경된 설정만 복원합니다. 원래 `codex` 실행 파일·PATH·설정에 새 변경을 추가하지 않습니다.
164
167
 
165
168
  ```bash
166
169
  ai-battery setup
@@ -173,7 +176,11 @@ ai-battery setup claude
173
176
  ai-battery setup codex
174
177
  ```
175
178
 
176
- 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 ...` 명령을 실행하세요.
179
+ Codex 실행 경로를 그대로 유지하려면 `ai-battery --watch 2` 또는 `ai-battery hud`를 사용하세요. 하단 행을 실행 세션 하나에만 추가하려면 POSIX에서는 `ai-battery-run -- codex`, Windows에서는 `ai-battery-run-win -- codex`를 직접 실행합니다.
180
+
181
+ 기존처럼 `codex` 명령에 wrapper를 연결하려는 경우에만 `ai-battery setup codex --wrap-codex`를 사용합니다. Codex `[tui].status_line` 변경도 별도 옵션인 `--configure-codex-statusline`이 필요합니다. 두 옵션은 실행 경로나 사용자 설정을 변경하므로 기본값에서 제외되어 있습니다. 관리형 변경은 복구 기록을 먼저 저장하고, `reset settings`에서 해당 변경만 복원합니다.
182
+
183
+ 다음 Windows runner 설명은 직접 runner를 실행하거나 wrapper를 명시적으로 선택한 경우에 적용됩니다.
177
184
 
178
185
  Windows native `cmd`/PowerShell에서는 `codex.cmd` wrapper가 현재 PATH에서 원본 Codex를 매번 찾고, 기본 `composite` runner로 실행합니다. Codex Fullscreen 화면은 `node-pty`의 bundled ConPTY와 `@xterm/headless` 안에서 해석한 뒤, 터미널 최하단의 AI Battery 1행과 합성합니다. Codex의 기본 상태·단축키 행은 본문 스크롤 이동에서 제외하며, 바뀐 화면만 다시 그립니다. 시스템 Node와 Codex 설치는 변경하지 않습니다.
179
186
 
@@ -191,7 +198,7 @@ tmux에서는 pane마다 하단 행을 예약하면 같은 전역 배터리가 p
191
198
  ai-battery setup tmux
192
199
  ```
193
200
 
194
- `~/.tmux.conf`에 관리 블록을 추가해 status-right에 배터리를 표시하고(10초 간격 갱신), 이 tmux 안에서 실행되는 `codex`는 pane별 배터리 행을 생략하고 pane 전체를 사용합니다. Claude statusLine도 같은 환경에서는 배터리 행을 접고 header(모델·디렉터리·브랜치) 1행만 표시합니다 — 배터리는 tmux bar에 이미 있기 때문입니다. 적용하려면 `tmux source-file ~/.tmux.conf` 후 새 pane을 여세요. 이 블록은 기존 `status-right` 설정을 덮어쓰므로 `setup all`에 포함되지 않는 opt-in입니다. 해제는 `ai-battery uninstall tmux`, tmux 안에서도 pane별 행을 유지하려면 `AI_BATTERY_TMUX=row`를 설정합니다.
201
+ `~/.tmux.conf`에 관리 블록을 추가해 status-right에 배터리를 표시하고(10초 간격 갱신), 이 tmux 안에서 실행되는 `codex`는 pane별 배터리 행을 생략하고 pane 전체를 사용합니다. Claude statusLine도 같은 환경에서는 배터리 행을 접고 header(모델·디렉터리·브랜치) 1행만 표시합니다 — 배터리는 tmux bar에 이미 있기 때문입니다. 적용하려면 `tmux source-file ~/.tmux.conf` 후 새 pane을 여세요. 이 블록은 기존 `status-right` 설정을 덮어쓰므로 `setup all`에 포함되지 않는 opt-in입니다. 해제는 `ai-battery reset settings tmux`, tmux 안에서도 pane별 행을 유지하려면 `AI_BATTERY_TMUX=row`를 설정합니다.
195
202
 
196
203
  Codex 하단 행이 보이지 않으면 진단을 실행합니다.
197
204
 
@@ -214,16 +221,13 @@ ai-battery on all
214
221
 
215
222
  ## Codex Terminal Row
216
223
 
217
- `ai-battery setup`은 Codex 자체 status line을 `모델/추론강도 · 워크스페이스 · git branch` 구성으로 맞춥니다. 사용량 표시는 별도의 `codex` wrapper가 담당하므로, 사용자는 원래처럼 `codex`만 입력하면 `ai-battery-run`이 내부에서 Codex를 한 줄 짧은 PTY 안에서 실행합니다.
218
-
219
- ```bash
220
- codex
221
- ```
224
+ 기본 `codex`는 AI Battery를 거치지 않고 실행됩니다. 사용량을 독립적으로 보려면 `ai-battery --watch 2` 또는 지원 플랫폼에서 `ai-battery hud`를 실행하세요.
222
225
 
223
- 직접 wrapper를 실행해야 하는 고급 사용자는 아래 명령을 사용할 수 있습니다.
226
+ 세션 하나에 하단 행을 추가하려면 명시적으로 실행합니다.
224
227
 
225
228
  ```bash
226
- ai-battery-run --provider all codex
229
+ ai-battery-run --provider all -- codex # WSL/Linux/macOS
230
+ ai-battery-run-win --provider all -- codex # Windows cmd/PowerShell
227
231
  ```
228
232
 
229
233
  갱신 주기를 줄이려면 `--interval`을 사용합니다.
@@ -270,7 +274,7 @@ ai-battery hud -Mode statusline -Position bottomcenter
270
274
  제거:
271
275
 
272
276
  ```bash
273
- ai-battery uninstall-claude-statusline
277
+ ai-battery reset settings claude
274
278
  ```
275
279
 
276
280
  Claude가 한 번 이상 statusLine payload를 전달해야 Claude의 사용량 캐시가 생성됩니다. 그 전에는 Claude 로컬 로그 기반 fallback이 표시됩니다.
@@ -290,21 +294,21 @@ Codex [battery:88] │ 5h 00:47 │ 7d 93%
290
294
  Claude [battery:76] │ 5h 00:47 │ 7d 59%
291
295
  ```
292
296
 
293
- | Command | Role |
294
- | --- | --- |
295
- | `ai-battery hud` / `ai-battery hud start` | Windows floating HUD 또는 macOS menu bar item을 시작합니다. |
296
- | `ai-battery hud stop` | 실행 중인 HUD/menu bar item을 종료합니다. (`--stop`도 동일) |
297
- | `ai-battery hud status` | HUD/menu bar 실행 여부와 autostart 등록 상태를 보여줍니다. |
298
- | `ai-battery hud autostart on` | Windows 로그인 또는 macOS 로그인 시 자동 실행을 등록합니다. |
299
- | `ai-battery hud autostart off` | 자동 실행 등록을 해제합니다. |
300
- | `ai-battery hud autostart status` | 자동 실행 등록 상태만 보여줍니다. |
301
- | `ai-battery hud -Foreground` | 디버깅용으로 터미널에 붙여 실행합니다. |
302
- | `ai-battery hud -Once` | 콘솔에서 한 번만 출력합니다. |
303
- | `ai-battery hud -Interval 2` | 갱신 주기를 바꿉니다. |
304
- | `ai-battery hud -Mode tray` | Windows tray icon 모드로 실행합니다. macOS에서는 menu bar item이 기본입니다. |
305
- | `ai-battery hud light` / `ai-battery hud dark` | Windows floating HUD를 밝은 작업표시줄용 검은 글자 또는 어두운 작업표시줄용 흰 글자로 바꿉니다. |
306
- | `ai-battery hud black` / `ai-battery hud white` | 글자색을 직접 검은색 또는 흰색으로 바꿉니다. |
307
- | `ai-battery hud --backdrop` / `ai-battery hud --no-backdrop` | Windows floating HUD 글자 뒤 어두운 backing을 켜거나 끕니다. |
297
+ | Command | Role |
298
+ | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------- |
299
+ | `ai-battery hud` / `ai-battery hud start` | Windows floating HUD 또는 macOS menu bar item을 시작합니다. |
300
+ | `ai-battery hud stop` | 실행 중인 HUD/menu bar item을 종료합니다. (`--stop`도 동일) |
301
+ | `ai-battery hud status` | HUD/menu bar 실행 여부와 autostart 등록 상태를 보여줍니다. |
302
+ | `ai-battery hud autostart on` | Windows 로그인 또는 macOS 로그인 시 자동 실행을 등록합니다. |
303
+ | `ai-battery hud autostart off` | 자동 실행 등록을 해제합니다. |
304
+ | `ai-battery hud autostart status` | 자동 실행 등록 상태만 보여줍니다. |
305
+ | `ai-battery hud -Foreground` | 디버깅용으로 터미널에 붙여 실행합니다. |
306
+ | `ai-battery hud -Once` | 콘솔에서 한 번만 출력합니다. |
307
+ | `ai-battery hud -Interval 2` | 갱신 주기를 바꿉니다. |
308
+ | `ai-battery hud -Mode tray` | Windows tray icon 모드로 실행합니다. macOS에서는 menu bar item이 기본입니다. |
309
+ | `ai-battery hud light` / `ai-battery hud dark` | Windows floating HUD를 밝은 작업표시줄용 검은 글자 또는 어두운 작업표시줄용 흰 글자로 바꿉니다. |
310
+ | `ai-battery hud black` / `ai-battery hud white` | 글자색을 직접 검은색 또는 흰색으로 바꿉니다. |
311
+ | `ai-battery hud --backdrop` / `ai-battery hud --no-backdrop` | Windows floating HUD 글자 뒤 어두운 backing을 켜거나 끕니다. |
308
312
 
309
313
  Windows floating HUD는 기본적으로 투명 배경에 밝은 글자로 표시합니다. 밝은 작업표시줄에서는 `ai-battery hud light`, 어두운 작업표시줄에서는 `ai-battery hud dark`를 쓰면 됩니다. 글자색으로 직접 고르려면 `ai-battery hud black` 또는 `ai-battery hud white`를 쓰세요. 로그인 자동 실행에도 같은 모드를 저장하려면 `ai-battery hud autostart on light`처럼 붙이면 됩니다.
310
314
 
@@ -338,13 +342,13 @@ Codex는 최근 세션 로그에서 `rate_limits` 이벤트를 찾습니다. Cla
338
342
 
339
343
  ## Tech Stack
340
344
 
341
- | Layer | Technology | Role |
342
- | --- | --- | --- |
343
- | CLI | Node.js | 로그 파싱, Claude cache, ANSI/statusLine 출력 |
344
- | PTY row | Python 3 | Codex 실행용 reserved terminal row |
345
- | HUD launcher | Node.js / Bash compatibility wrapper | Windows native/WSL PowerShell HUD와 macOS menu bar 실행 |
346
- | HUD UI | PowerShell WinForms / AppleScriptObjC | Windows floating overlay, tray icon, macOS menu bar item |
347
- | Data | JSONL logs, statusLine JSON | Codex/Claude 사용량 소스 |
345
+ | Layer | Technology | Role |
346
+ | ------------ | ------------------------------------- | -------------------------------------------------------- |
347
+ | CLI | Node.js | 로그 파싱, Claude cache, ANSI/statusLine 출력 |
348
+ | PTY row | Python 3 | Codex 실행용 reserved terminal row |
349
+ | HUD launcher | Node.js / Bash compatibility wrapper | Windows native/WSL PowerShell HUD와 macOS menu bar 실행 |
350
+ | HUD UI | PowerShell WinForms / AppleScriptObjC | Windows floating overlay, tray icon, macOS menu bar item |
351
+ | Data | JSONL logs, statusLine JSON | Codex/Claude 사용량 소스 |
348
352
 
349
353
  ## Source Environment
350
354
 
@@ -77,6 +77,10 @@ ai_battery_find_command() {
77
77
  ai_battery_usable_runner() {
78
78
  [ -f "$1" ] && [ -x "$1" ] || return 1
79
79
  ai_battery_runner_target=$(ai_battery_realpath "$1") || return 1
80
+ ai_battery_runner_header=$("$ai_battery_head" -c 64 "$ai_battery_runner_target" 2>/dev/null) || return 1
81
+ case "$ai_battery_runner_header" in
82
+ '#!/usr/bin/env python3'*) command -v python3 >/dev/null 2>&1 || return 1 ;;
83
+ esac
80
84
  case "$ai_battery_runner_target" in
81
85
  */versions/node/*) ai_battery_nvm_node "$ai_battery_runner_target" >/dev/null ;;
82
86
  *) return 0 ;;
package/docs/RELEASING.md CHANGED
@@ -1,64 +1,66 @@
1
1
  # npm release
2
2
 
3
- The current release candidate is **0.1.21**, prepared from the 0.1.20 main branch. npm `latest` was checked as **0.1.20** on 2026-10-15. This preparation does not publish to npm or create a release tag.
3
+ The current release candidate is **0.1.22**. It includes the 0.1.21 usage-refresh fixes and changes the default Codex integration to preserve independent execution. Preparing a tarball does not publish it to npm.
4
4
 
5
- ## Changes in 0.1.21
5
+ ## Changes in 0.1.22
6
6
 
7
- - Windows default PTY composition and POSIX terminal rows poll every 2 seconds by default. POSIX polling runs asynchronously so usage scans do not block terminal input or output.
8
- - Polls allow up to 10 seconds by default. Failed updates retry after 1 second, with backoff for repeated failures. A retained reading is marked `[stale]`; an initial failure displays `AI Battery unavailable`.
9
- - New and changed Codex session logs invalidate the parsing cache before its normal expiry. Account usage sharing between Windows and WSL, separate session stores, and existing runtime selection are preserved.
10
- - WSL reuses a brief Windows process scan cache. A known active Codex does not require another process scan just to fetch its usage.
11
- - The package no longer depends on an older copy of `ai-battery` itself.
12
-
13
- Values remain the latest usage reported by local Codex logs and Claude statusLine. They are not direct live server measurements; delayed source updates can delay the display.
7
+ - Default `setup codex` restores legacy AI Battery integrations without creating a Codex wrapper, adding PATH entries or configuring Codex's status line. Use an independent watcher/HUD, or explicitly launch a runner for one session. `--wrap-codex` and `--configure-codex-statusline` are separate opt-ins.
8
+ - `ai-battery reset settings` restores integrations and selectively removes verified caches, private runtimes and generated files. `reset config` is an alias. The CLI never invokes npm uninstall; all npm packages, package commands and local project manifests/lockfiles are preserved. `teardown` and `uninstall` remain compatibility aliases. Targeted reset restores only the selected integration.
9
+ - Shell and tmux recovery records preserve exact original content, permissions and file absence. User edits outside managed blocks survive repeated setup and reset. Edited blocks, retargeted symlinks and unresolved recovery records prevent unsafe removal.
10
+ - Windows PATH cleanup preserves unrelated whitespace and separators and reports failed writes. HUD cleanup verifies its Run value and launcher ownership and preserves unknown files. macOS LaunchAgent cleanup refuses foreign files and symlinks.
11
+ - Existing Bash terminals can cache a deleted legacy Codex wrapper. Run `hash -r` (zsh: `rehash`) or open a new terminal. A child CLI cannot clear its parent shell's command cache. A POSIX wrapper whose Python runner cannot start because Python is absent now runs the original Codex directly.
14
12
 
15
13
  ## Validation
16
14
 
17
- The integrated candidate passed the following checks on 2026-10-15:
15
+ Checked on 2026-10-15:
18
16
 
19
- | Check | Result |
17
+ | Environment | Result |
20
18
  | --- | --- |
21
- | WSL `npm run check` | 133 passed, 15 platform skips, 0 failures |
22
- | Windows native Node 22.23.2 `node --test` | 117 passed, 31 platform skips, 0 failures |
23
- | Focused polling and freshness tests | Slow polls, failed/empty/partial/oversized output, automatic recovery, zero remaining, new sessions, and cache invalidation |
19
+ | WSL `npm run check` | 156 passed, 16 platform skips, 0 failures |
20
+ | Windows native Node 22.23.2 full suite | 135 passed, 37 platform skips, 0 failures |
21
+
22
+ Validation results and tarball manifests are stored in `.cache/releases/0.1.22/`. The regression suite covers default command/config preservation, exact shell restoration, user edits, symlinks, custom integration paths, incomplete recovery, global/local package preservation, settings/config and compatibility aliases, HUD target parsing, invalid reset scopes, and Windows registry ownership. Desktop operations in the installed CLI fixture are stubbed; Windows autostart cleanup is separately exercised against a temporary registry key and profile.
24
23
 
25
- Tarball installation results, package contents, and checksums are saved with the local release artifacts under `.cache/releases/0.1.21/`. Windows ARM64 still requires a device check; native verification here uses x64.
24
+ Reset behavior is tested in isolated global and local installations, with provider settings and original launchers compared byte for byte. npm removal is a separate explicit operation in the installed-tarball checks.
25
+
26
+ Native Windows validation uses x64 Node 22.23.2. macOS LaunchAgent ownership and file handling are tested through an isolated fixture; native macOS and Windows ARM64 are not verified here.
26
27
 
27
28
  ## Prepare
28
29
 
29
30
  ```text
30
31
  npm run check
31
32
  npm pack --dry-run
32
- npm pack --pack-destination .cache/releases/0.1.21
33
+ npm pack --pack-destination .cache/releases/0.1.22
33
34
  ```
34
35
 
35
- Inspect the package file list. It must include `lib`, the bin entrypoints and required PowerShell modules. Screenshots, logs, credentials, local runtime binaries, tests and `.cache` must not be included. Test the exact tarball with a clean installation on Windows and POSIX. On Windows, also run `npm run smoke:composite` and `npm run smoke:codex-fullscreen-win` against the installed runner; the Codex fixture uses a local mock server and does not consume account quota.
36
+ Inspect the package file list. Include the core cleanup/recovery modules, platform modules, bin entrypoints and required PowerShell files. Exclude screenshots, logs, credentials, local runtime binaries, tests and `.cache`. Verify the exact tarball using an isolated npm prefix and provider homes. Release 0.1.21 fullscreen/compositor reports remain under `.cache/releases/0.1.21/`; this release changes setup/removal rather than terminal composition.
36
37
 
37
38
  ## Publish manually
38
39
 
39
40
  ```text
40
41
  npm login
41
42
  npm whoami
42
- npm publish .cache/releases/0.1.21/ai-battery-0.1.21.tgz --access public --tag latest
43
+ npm publish .cache/releases/0.1.22/ai-battery-0.1.22.tgz --access public --tag latest
43
44
  npm view ai-battery version dist-tags --json
44
45
  ```
45
46
 
46
- Use the exact tested tarball. Complete npm's authentication/2FA prompt when requested. Publishing the same name/version twice is not allowed. If 0.1.21 is already published when you release, increment the version and repeat preparation. Use `--tag next` instead of `--tag latest` for a preview release.
47
-
48
- After successful publication, tag the tested commit (`v0.1.21`) and push the release tag. Keep the remote release branch until the release commit is integrated into main.
47
+ Publish the exact tested tarball. Complete npm authentication/2FA when requested. If the version is already published, increment it and repeat preparation. After publication, tag the tested commit (`v0.1.22`) and integrate the release branch into main.
49
48
 
50
- ## Update installed integrations
49
+ ## Update or remove an installation
51
50
 
52
- Run separately in Windows and WSL:
51
+ Run separately for Windows and WSL:
53
52
 
54
53
  ```text
55
- npm install -g ai-battery@0.1.21
54
+ npm install -g ai-battery@0.1.22
56
55
  ai-battery setup codex
57
- ai-battery doctor
58
56
  ```
59
57
 
60
- Restart the terminal session after updating. A running PTY wrapper retains its loaded code. Existing managed wrappers must be regenerated by setup to adopt the current integration.
58
+ Default setup detaches a legacy wrapper. In an existing Bash terminal run `hash -r`; zsh uses `rehash`. Plain `codex` then runs independently. Display usage with `ai-battery --watch 2` or a supported desktop HUD. There is no built-in `ai-battery update` command.
61
59
 
62
- The private Windows runtime lives under `%LOCALAPPDATA%\ai-battery\runtimes` by default, or the selected AI Battery data directory. `AI_BATTERY_RUNTIME_DOWNLOAD=0` disables downloading. System Node, PATH and the original Codex installation are preserved.
60
+ Restore AI Battery settings first, then remove the package with npm only if restoration succeeded:
61
+
62
+ ```text
63
+ ai-battery reset settings && npm uninstall -g ai-battery
64
+ ```
63
65
 
64
- Official npm references: [publish](https://docs.npmjs.com/cli/v11/commands/npm-publish/), [login](https://docs.npmjs.com/cli/v11/commands/npm-login/).
66
+ Modified or unrecognized files are preserved and listed. A running wrapped session retains its loaded code until it exits. `reset config` is an alias for `reset settings`. The CLI never removes any npm installation. Use `npm uninstall ai-battery` for local installs; Windows/WSL and Node-version installations are managed separately.
package/lib/cli.js CHANGED
@@ -15,6 +15,8 @@ import { quoteWindowsCommandLineArg, rowptyExePath } from "./platforms/windows/c
15
15
  import { isWsl } from "./platforms/runtime.js";
16
16
  import { createProcessScanner } from "./platforms/process-scanner.js";
17
17
  import { createWindowsPathIntegration } from "./platforms/windows/path-integration.js";
18
+ import { cleanupBatteryArtifacts, isBatteryConfig } from "./core/uninstall.js";
19
+ import { createIntegrationFiles } from "./core/integration-files.js";
18
20
  import {
19
21
  cacheAgeSeconds,
20
22
  clamp,
@@ -58,6 +60,7 @@ const DEFAULT_STATUSLINE_COLUMN_GUARD = 4;
58
60
  const COMMANDS = new Set([
59
61
  "show",
60
62
  "setup",
63
+ "reset",
61
64
  "teardown",
62
65
  "uninstall",
63
66
  "doctor",
@@ -108,24 +111,32 @@ function parseArgs(argv) {
108
111
  hudState: false,
109
112
  silent: false,
110
113
  force: false,
114
+ wrapCodex: false,
115
+ configureCodexStatusLine: false,
111
116
  attachHud: false,
112
117
  header: true,
113
118
  usageRow: "auto",
114
119
  help: false,
115
120
  version: false,
121
+ resetScope: null,
116
122
  targets: [],
117
123
  rest: []
118
124
  };
119
125
 
126
+ let commandSeen = false;
120
127
  for (let i = 0; i < argv.length; i += 1) {
121
128
  const arg = argv[i];
122
- if (!arg.startsWith("-") && COMMANDS.has(arg)) {
129
+ if (!commandSeen && !arg.startsWith("-") && COMMANDS.has(arg)) {
123
130
  args.command = arg;
131
+ commandSeen = true;
124
132
  if (arg === "hud") {
125
133
  args.rest = argv.slice(i + 1);
126
134
  break;
127
135
  }
128
- } else if (!arg.startsWith("-") && ["setup", "teardown", "uninstall", "on", "off"].includes(args.command)) {
136
+ } else if (!arg.startsWith("-") && args.command === "reset" && !args.resetScope) {
137
+ if (!["settings", "config"].includes(arg)) throw new Error("Usage: ai-battery reset settings|config [codex|claude|hud|tmux|all]");
138
+ args.resetScope = "settings";
139
+ } else if (!arg.startsWith("-") && ["setup", "reset", "teardown", "uninstall", "on", "off"].includes(args.command)) {
129
140
  args.targets.push(arg);
130
141
  } else if (arg === "--provider" || arg === "-p") {
131
142
  args.provider = argv[++i] || "all";
@@ -148,6 +159,10 @@ function parseArgs(argv) {
148
159
  args.usageRow = false;
149
160
  } else if (arg === "--force") {
150
161
  args.force = true;
162
+ } else if (arg === "--wrap-codex") {
163
+ args.wrapCodex = true;
164
+ } else if (arg === "--configure-codex-statusline") {
165
+ args.configureCodexStatusLine = true;
151
166
  } else if (arg === "--attach-hud") {
152
167
  args.attachHud = true;
153
168
  } else if (arg === "--watch" || arg === "-w") {
@@ -190,6 +205,9 @@ function parseArgs(argv) {
190
205
  }
191
206
  }
192
207
 
208
+ if (args.command === "reset" && !args.resetScope && !args.help && !args.version) {
209
+ throw new Error("Usage: ai-battery reset settings|config [codex|claude|hud|tmux|all]");
210
+ }
193
211
  if (!["all", "codex", "claude"].includes(args.provider)) {
194
212
  throw new Error("--provider must be one of: all, codex, claude");
195
213
  }
@@ -205,8 +223,8 @@ function printHelp() {
205
223
 
206
224
  Usage:
207
225
  ai-battery [options]
208
- ai-battery setup [codex|claude] [--force]
209
- ai-battery uninstall [codex|claude|hud|all]
226
+ ai-battery setup [codex|claude] [--force] [--wrap-codex]
227
+ ai-battery reset settings [codex|claude|hud|tmux|all]
210
228
  ai-battery doctor
211
229
  ai-battery hud [start|stop|status] [hud options]
212
230
  ai-battery hud autostart on|off|status
@@ -215,6 +233,11 @@ Usage:
215
233
 
216
234
  Aliases:
217
235
  claudex-battery
236
+ ai-battery reset config [codex|claude|hud|tmux|all]
237
+
238
+ Setup leaves Codex's command, PATH and configuration unchanged by default.
239
+ Reset settings restores AI Battery's integrations and cleans its generated files.
240
+ The npm package stays installed. Remove it separately: npm uninstall -g ai-battery
218
241
 
219
242
  Options:
220
243
  -p, --provider all|codex|claude Provider to show (default: all)
@@ -232,6 +255,8 @@ Options:
232
255
  --menu-bar Print compact macOS menu bar text
233
256
  --tmux Emit tmux status-line color markup
234
257
  --force Replace an existing Claude statusLine
258
+ --wrap-codex Explicitly opt into intercepting codex on PATH
259
+ --configure-codex-statusline Explicitly configure Codex's own status line
235
260
  --no-color Disable ANSI colors
236
261
  -v, --version Show ai-battery version
237
262
  -h, --help Show this help
@@ -239,7 +264,8 @@ Options:
239
264
  Compatibility:
240
265
  ai-battery install-claude-statusline [--force]
241
266
  ai-battery uninstall-claude-statusline
242
- ai-battery teardown [codex|claude|hud|all]
267
+ ai-battery teardown [codex|claude|hud|tmux|all]
268
+ ai-battery uninstall [codex|claude|hud|tmux|all]
243
269
  `);
244
270
  }
245
271
 
@@ -388,6 +414,9 @@ function readConfig(options = {}) {
388
414
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
389
415
  throw new Error(`AI Battery config is invalid and was left untouched: ${target}`);
390
416
  }
417
+ if (!isBatteryConfig(parsed)) {
418
+ throw new Error(`AI Battery config ownership could not be verified; file was left untouched: ${target}`);
419
+ }
391
420
  if (parsed.providers !== undefined
392
421
  && (!parsed.providers || typeof parsed.providers !== "object" || Array.isArray(parsed.providers))) {
393
422
  throw new Error(`AI Battery config providers must be a JSON object: ${target}`);
@@ -409,6 +438,8 @@ function writeConfig(config) {
409
438
  writeJsonAtomic(configPath(), config);
410
439
  }
411
440
 
441
+ const { installManagedText, removeManagedText, stripOwnedBlock } = createIntegrationFiles({ readConfig, writeConfig, writeTextAtomic });
442
+
412
443
  function providerVisible(provider) {
413
444
  const config = readConfig();
414
445
  return config.providers?.[provider] !== false;
@@ -975,13 +1006,13 @@ function installTmuxStatus() {
975
1006
  try {
976
1007
  existing = fs.readFileSync(confPath, "utf8");
977
1008
  } catch {}
978
- const withoutBlock = removeAiBatteryTmuxBlock(existing);
1009
+ const withoutBlock = stripOwnedBlock(confPath, existing, removeAiBatteryTmuxBlock);
979
1010
  const existingStatusRight = extractExistingStatusRight(withoutBlock);
980
1011
  const next = `${withoutBlock}${tmuxStatusBlock(existingStatusRight)}`;
981
1012
  if (next === existing) {
982
1013
  return { ok: true, confPath, changed: false };
983
1014
  }
984
- fs.writeFileSync(confPath, next, "utf8");
1015
+ installManagedText(confPath, next, next.slice(withoutBlock.length));
985
1016
  return {
986
1017
  ok: true,
987
1018
  confPath,
@@ -994,16 +1025,10 @@ function installTmuxStatus() {
994
1025
  function uninstallTmuxStatus() {
995
1026
  if (process.platform === "win32") return { skipped: true };
996
1027
  const confPath = tmuxConfPath();
997
- let existing;
998
- try {
999
- existing = fs.readFileSync(confPath, "utf8");
1000
- } catch {
1001
- return { changed: false, confPath };
1002
- }
1003
- const next = removeAiBatteryTmuxBlock(existing);
1004
- if (next === existing) return { changed: false, confPath };
1005
- fs.writeFileSync(confPath, next, "utf8");
1006
- return { changed: true, confPath };
1028
+ const records = readConfig({ strict: true }).integrationFiles || {};
1029
+ const paths = uniquePaths([confPath, ...Object.keys(records).filter(file => records[file]?.block?.includes("# >>> ai-battery tmux >>>"))]);
1030
+ const changedPaths = paths.filter(file => removeManagedText(file, removeAiBatteryTmuxBlock));
1031
+ return { changed: changedPaths.length > 0, confPath, changedPaths };
1007
1032
  }
1008
1033
 
1009
1034
  function removeAiBatteryShellPathBlock(text) {
@@ -1043,13 +1068,10 @@ function removeShellPathBlocks(extraShimDirs = [], options = {}) {
1043
1068
  }
1044
1069
 
1045
1070
  const changed = [];
1046
- for (const rcPath of shellRcCandidates()) {
1047
- if (!fs.existsSync(rcPath)) continue;
1048
- const existing = fs.readFileSync(rcPath, "utf8");
1049
- const next = removeAiBatteryShellPathBlock(existing);
1050
- if (next === existing) continue;
1051
- fs.writeFileSync(rcPath, next, "utf8");
1052
- changed.push(rcPath);
1071
+ const records = readConfig({ strict: true }).integrationFiles || {};
1072
+ const paths = uniquePaths([...shellRcCandidates(), ...Object.keys(records).filter(file => records[file]?.block?.includes("# >>> ai-battery setup >>>"))]);
1073
+ for (const rcPath of paths) {
1074
+ if (removeManagedText(rcPath, removeAiBatteryShellPathBlock)) changed.push(rcPath);
1053
1075
  }
1054
1076
  return changed;
1055
1077
  }
@@ -1082,10 +1104,10 @@ function ensureShimPath(shimDir, originalCommand) {
1082
1104
  const rcPath = shellRcPath();
1083
1105
  fs.mkdirSync(path.dirname(rcPath), { recursive: true });
1084
1106
  const existing = fs.existsSync(rcPath) ? fs.readFileSync(rcPath, "utf8") : "";
1085
- const withoutAiBatteryBlock = removeAiBatteryShellPathBlock(existing);
1107
+ const withoutAiBatteryBlock = stripOwnedBlock(rcPath, existing, removeAiBatteryShellPathBlock);
1086
1108
  const separator = withoutAiBatteryBlock && !withoutAiBatteryBlock.endsWith("\n") ? "\n" : "";
1087
1109
  const next = `${withoutAiBatteryBlock}${separator}${shellPathBlock(shimDir)}`;
1088
- fs.writeFileSync(rcPath, next, "utf8");
1110
+ installManagedText(rcPath, next, next.slice(withoutAiBatteryBlock.length));
1089
1111
 
1090
1112
  return {
1091
1113
  changed: true,
@@ -1676,6 +1698,7 @@ function uninstallCodexWrapper() {
1676
1698
  candidates.map((wrapperPath) => path.dirname(wrapperPath)),
1677
1699
  { windowsOwnedShimDirs }
1678
1700
  );
1701
+ config.integrationFiles = readConfig({ strict: true }).integrationFiles;
1679
1702
  if (clearedWrapperConfig) {
1680
1703
  config.codexWrapper = null;
1681
1704
  }
@@ -1752,6 +1775,7 @@ function installCodexWrapper(args) {
1752
1775
  }
1753
1776
 
1754
1777
  const pathResult = ensureShimPath(shimDir, originalPathForPath || originalCommand);
1778
+ config.integrationFiles = readConfig({ strict: true }).integrationFiles;
1755
1779
  const previousOwnedPath = config.codexWrapper?.pathAddedByAiBattery;
1756
1780
  config.codexWrapper = {
1757
1781
  wrapperPath,
@@ -1826,7 +1850,9 @@ function windowsOwnedShimDirsForUninstall(config) {
1826
1850
  ? path.dirname(config.codexWrapper.wrapperPath)
1827
1851
  : null;
1828
1852
  const explicitlyAdded = config.codexWrapper?.pathAddedByAiBattery;
1829
- if (explicitlyAdded) return [explicitlyAdded];
1853
+ if (config.codexWrapper && Object.hasOwn(config.codexWrapper, "pathAddedByAiBattery")) {
1854
+ return explicitlyAdded ? [explicitlyAdded] : [];
1855
+ }
1830
1856
  if (configuredShimDir && samePath(configuredShimDir, defaultCodexShimDir())) {
1831
1857
  return [configuredShimDir];
1832
1858
  }
@@ -1894,7 +1920,7 @@ function diagnoseCodex() {
1894
1920
  notes.push("Codex status_line is not configured. Run: ai-battery setup codex");
1895
1921
  }
1896
1922
  if (activeIsWrapper && !wrapperInstalled) {
1897
- notes.push("Plain \"codex\" still resolves to an AI Battery wrapper outside the configured shim. Run: ai-battery uninstall codex");
1923
+ notes.push("Plain \"codex\" still resolves to an AI Battery wrapper outside the configured shim. Run: ai-battery reset settings codex");
1898
1924
  }
1899
1925
  if (activeWrapperBackup) {
1900
1926
  notes.push(`A Codex backup is available for restore: ${activeWrapperBackup}`);
@@ -2192,16 +2218,20 @@ function installRowPtyHost() {
2192
2218
  function uninstallRowPtyHost() {
2193
2219
  if (process.platform !== "win32") return { skipped: true };
2194
2220
  const binDir = path.join(dataDir(), "bin");
2221
+ try {
2222
+ if (fs.lstatSync(binDir).isSymbolicLink()) throw new Error(`Refusing to clean a symlinked runtime directory: ${binDir}`);
2223
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
2195
2224
  sweepParkedRowPtyFiles(binDir);
2196
2225
  const removed = [];
2226
+ const errors = [];
2197
2227
  for (const name of ["rowpty.exe", "conpty.dll", "OpenConsole.exe", "rowpty.src.sha256"]) {
2198
2228
  const target = path.join(binDir, name);
2199
2229
  try {
2200
2230
  fs.unlinkSync(target);
2201
2231
  removed.push(name);
2202
- } catch {}
2232
+ } catch (error) { if (error.code !== "ENOENT") errors.push({ path: target, error: error.message }); }
2203
2233
  }
2204
- return { removed };
2234
+ return { removed, errors };
2205
2235
  }
2206
2236
 
2207
2237
  function setupTargets(targets) {
@@ -2237,12 +2267,24 @@ function runSetup(args) {
2237
2267
  results.tmux = installTmuxStatus();
2238
2268
  }
2239
2269
  if (targets.includes("codex")) {
2240
- const statusLine = installCodexStatusLine(args);
2241
- results.codex = {
2242
- ...installCodexWrapper(args),
2243
- statusLine
2244
- };
2245
- if (process.platform === "win32") {
2270
+ const statusLine = args.wrapCodex && args.configureCodexStatusLine ? installCodexStatusLine(args) : null;
2271
+ if (args.wrapCodex) {
2272
+ results.codex = { ...installCodexWrapper(args), statusLine };
2273
+ } else {
2274
+ const legacyCleanup = uninstallCodexWrapper();
2275
+ const failed = teardownResultFailed({ results: { codex: legacyCleanup } });
2276
+ results.codex = {
2277
+ ok: !failed,
2278
+ standalone: !failed,
2279
+ skipped: failed,
2280
+ legacyCleanup,
2281
+ reason: failed ? "Could not safely detach the legacy Codex integration; kept recovery metadata. Run ai-battery reset settings codex for details."
2282
+ : "Codex command and configuration are left under Codex's control. Use ai-battery hud or ai-battery-run -- codex for usage display."
2283
+ };
2284
+ // An explicit status-line request is applied after legacy restoration.
2285
+ if (args.configureCodexStatusLine && !failed) results.codex.statusLine = installCodexStatusLine(args);
2286
+ }
2287
+ if (process.platform === "win32" && args.wrapCodex) {
2246
2288
  results.codex.rowpty = windowsSetupNeedsRowPty()
2247
2289
  ? (windowsClaudeLauncher || installRowPtyHost())
2248
2290
  : {
@@ -2297,7 +2339,7 @@ function runHudCommand(args) {
2297
2339
  return childResult(spawnSync(process.execPath, [hudPath, ...args], {
2298
2340
  encoding: "utf8",
2299
2341
  stdio: ["ignore", "pipe", "pipe"],
2300
- timeout: 5000,
2342
+ timeout: 15000,
2301
2343
  windowsHide: true
2302
2344
  }));
2303
2345
  }
@@ -2311,8 +2353,8 @@ function uninstallHud() {
2311
2353
  };
2312
2354
  }
2313
2355
 
2314
- const autostart = runHudCommand(["autostart", "off"]);
2315
2356
  const stop = runHudCommand(["stop"]);
2357
+ const autostart = runHudCommand(["autostart", "off"]);
2316
2358
  return {
2317
2359
  changed: autostart.ok || stop.ok,
2318
2360
  autostart,
@@ -2340,7 +2382,6 @@ function runTeardown(args) {
2340
2382
  }
2341
2383
  if (targets.includes("codex")) {
2342
2384
  runStep("codex", uninstallCodexWrapper);
2343
- runStep("rowpty", uninstallRowPtyHost);
2344
2385
  }
2345
2386
  if (targets.includes("tmux")) {
2346
2387
  runStep("tmux", uninstallTmuxStatus);
@@ -2348,8 +2389,25 @@ function runTeardown(args) {
2348
2389
  if (targets.includes("hud")) {
2349
2390
  runStep("hud", uninstallHud);
2350
2391
  }
2392
+ if (targets.includes("codex")) runStep("rowpty", uninstallRowPtyHost);
2393
+ const fullReset = !args.targets.length || args.targets.includes("all");
2394
+ if (fullReset && !teardownResultFailed({ results })) {
2395
+ const pending = Object.keys(readConfig({ strict: true }).integrationFiles || {});
2396
+ if (pending.length) {
2397
+ results.recovery = { error: "Unrestored integration files remain; kept recovery metadata", paths: pending };
2398
+ return { targets, fullReset, results };
2399
+ }
2400
+ const roots = [stateDir(), dataDir(), path.join(os.tmpdir(), "ai-battery")];
2401
+ if (process.platform === "win32" && process.env.LOCALAPPDATA) roots.push(path.join(process.env.LOCALAPPDATA, "ai-battery"));
2402
+ results.artifacts = cleanupBatteryArtifacts({
2403
+ roots,
2404
+ home: userHome(),
2405
+ protectedRoots: [codexRuntimeHome(), homePath(".claude"), path.resolve(scriptDir(), "..")]
2406
+ });
2407
+ }
2351
2408
  return {
2352
2409
  targets,
2410
+ fullReset,
2353
2411
  results
2354
2412
  };
2355
2413
  }
@@ -2570,6 +2628,7 @@ function readJson(filePath) {
2570
2628
  function teardownResultFailed(result) {
2571
2629
  return Object.values(result.results || {}).some((item) => Boolean(
2572
2630
  item?.error
2631
+ || item?.errors?.length
2573
2632
  || item?.retainedConfig
2574
2633
  || item?.retainedBackup
2575
2634
  || item?.skippedWrappers?.length
@@ -4974,6 +5033,27 @@ function printTeardownResult(result) {
4974
5033
  if (runningInsideAiBatteryCodexWrapper()) {
4975
5034
  console.log("Current Codex session was already started through AI Battery; exit this session to remove the terminal row.");
4976
5035
  }
5036
+ const artifacts = result.results.artifacts;
5037
+ for (const [name, item] of Object.entries(result.results)) {
5038
+ if (["codex", "claude", "hud", "artifacts"].includes(name)) continue;
5039
+ if (item.error) console.log(`${name} cleanup error: ${item.error}`);
5040
+ for (const error of item.errors || []) console.log(`${name} cleanup error: ${error.path}: ${error.error}`);
5041
+ for (const file of item.paths || []) console.log(`Recovery pending: ${file}`);
5042
+ }
5043
+ if (artifacts) {
5044
+ for (const file of artifacts.removed) console.log(`Removed AI Battery artifact: ${file}`);
5045
+ for (const file of artifacts.retained) console.log(`Preserved unrecognized or user-owned file: ${file}`);
5046
+ for (const item of artifacts.errors) console.log(`Cleanup error: ${item.path}: ${item.error}`);
5047
+ }
5048
+ if (teardownResultFailed(result)) {
5049
+ console.log("Settings reset incomplete; recovery metadata and npm package were preserved.");
5050
+ } else {
5051
+ console.log("AI Battery settings reset; npm package was left unchanged.");
5052
+ console.log("To remove the package: npm uninstall -g ai-battery");
5053
+ }
5054
+ if (result.targets.includes("codex") && process.platform !== "win32") {
5055
+ console.log("In this existing Bash terminal, run: hash -r (zsh: rehash). A child process cannot clear its parent shell's cached command paths.");
5056
+ }
4977
5057
  }
4978
5058
 
4979
5059
  async function main() {
@@ -5003,7 +5083,12 @@ async function main() {
5003
5083
  }
5004
5084
  }
5005
5085
  }
5006
- if (result.codex?.ok) {
5086
+ if (result.codex?.standalone) {
5087
+ console.log(result.codex.reason);
5088
+ if (result.codex.legacyCleanup.changed) {
5089
+ console.log("Removed legacy Codex integration. In this existing Bash terminal run: hash -r (zsh: rehash).");
5090
+ }
5091
+ } else if (result.codex?.ok) {
5007
5092
  console.log(`Codex wrapper installed: ${result.codex.wrapperPath}`);
5008
5093
  console.log(`Original codex: ${result.codex.originalCommand}`);
5009
5094
  if (result.codex.path?.note) console.log(result.codex.path.note);
@@ -5044,10 +5129,10 @@ async function main() {
5044
5129
  if (result.codex?.retainedConfig) {
5045
5130
  console.log("Kept the Codex recovery record because the configured wrapper could not be safely removed.");
5046
5131
  }
5047
- if (process.platform === "win32" && result.codex) {
5132
+ if (process.platform === "win32" && result.codex && !result.codex.standalone) {
5048
5133
  console.log("Windows terminal note: Codex uses fullscreen PTY composition by default, with a private VT-capable Node runtime when needed and a native HUD fallback. Open a new cmd/PowerShell after setup.");
5049
5134
  }
5050
- console.log("To remove AI Battery cleanly later, run: ai-battery uninstall");
5135
+ console.log("To restore settings later, run: ai-battery reset settings");
5051
5136
  const note = codexRestartNote();
5052
5137
  if (result.codex && note) console.log(note);
5053
5138
  }
@@ -5055,7 +5140,10 @@ async function main() {
5055
5140
  return;
5056
5141
  }
5057
5142
 
5058
- if (args.command === "teardown" || args.command === "uninstall") {
5143
+ if (["reset", "teardown", "uninstall"].includes(args.command)) {
5144
+ if (!args.silent && !args.json && args.command !== "reset") {
5145
+ console.log(`\"${args.command}\" is a compatibility alias for \"reset settings\"; npm package removal is separate.`);
5146
+ }
5059
5147
  const result = runTeardown(args);
5060
5148
  if (args.json) {
5061
5149
  console.log(JSON.stringify(result, null, 2));
@@ -0,0 +1,75 @@
1
+ import fs from "node:fs";
2
+
3
+ export function createIntegrationFiles({ readConfig, writeConfig, writeTextAtomic }) {
4
+ const key = file => file;
5
+ const recordFor = file => readConfig({ strict: true }).integrationFiles?.[key(file)];
6
+ const read = file => {
7
+ try { return fs.readFileSync(file, "utf8"); } catch (error) { if (error.code === "ENOENT") return null; throw error; }
8
+ };
9
+ function checkTarget(file, record) {
10
+ let stat;
11
+ try { stat = fs.lstatSync(file); } catch (error) { if (error.code === "ENOENT") return; throw error; }
12
+ if ((record?.target && fs.realpathSync(file) !== record.target) || (!record?.target && stat.isSymbolicLink())) {
13
+ throw new Error(`Integration symlink target changed; left untouched: ${file}`);
14
+ }
15
+ }
16
+ function stripRecorded(text, record, file) {
17
+ if (text === record.beforeText) return text;
18
+ const index = text.indexOf(record.block);
19
+ if (index < 0) throw new Error(`AI Battery integration block was edited; kept the file and recovery record: ${file}`);
20
+ const before = text.slice(0, index);
21
+ const after = text.slice(index + record.block.length);
22
+ const separator = before && after && !before.endsWith("\n") && !after.startsWith("\n") ? "\n" : "";
23
+ return before + separator + after;
24
+ }
25
+ function stripOwnedBlock(file, text, fallback) {
26
+ const record = recordFor(file);
27
+ if (!record) return fallback(text);
28
+ checkTarget(file, record);
29
+ return stripRecorded(text, record, file);
30
+ }
31
+ function installManagedText(file, next, block) {
32
+ const config = readConfig({ strict: true });
33
+ const previous = config.integrationFiles?.[key(file)];
34
+ if (previous) checkTarget(file, previous);
35
+ const current = read(file);
36
+ if (previous && current !== null) {
37
+ checkTarget(file, previous);
38
+ stripRecorded(current, previous, file);
39
+ }
40
+ if (!block) throw new Error(`Cannot record an empty integration block: ${file}`);
41
+ const mode = current === null ? 0o600 : fs.statSync(file).mode & 0o777;
42
+ const record = {
43
+ beforeText: previous && current !== null
44
+ ? current === previous.installedText ? previous.beforeText : stripRecorded(current, previous, file)
45
+ : current,
46
+ target: previous?.target || (current === null ? null : fs.realpathSync(file)),
47
+ installedText: next,
48
+ block
49
+ };
50
+ config.integrationFiles = { ...config.integrationFiles, [key(file)]: record };
51
+ writeConfig(config);
52
+ writeTextAtomic(file, next, mode);
53
+ }
54
+ function removeManagedText(file, fallback) {
55
+ const config = readConfig({ strict: true });
56
+ const record = config.integrationFiles?.[key(file)];
57
+ if (record) checkTarget(file, record);
58
+ const current = read(file);
59
+ if (current === null) {
60
+ if (record) { delete config.integrationFiles[key(file)]; writeConfig(config); }
61
+ return false;
62
+ }
63
+ const next = record
64
+ ? current === record.installedText ? record.beforeText : stripRecorded(current, record, file)
65
+ : fallback(current);
66
+ const changed = next !== current;
67
+ if (changed) {
68
+ if (next === null) fs.unlinkSync(file);
69
+ else writeTextAtomic(file, next, fs.statSync(file).mode & 0o777);
70
+ }
71
+ if (record) { delete config.integrationFiles[key(file)]; writeConfig(config); }
72
+ return changed;
73
+ }
74
+ return { installManagedText, removeManagedText, stripOwnedBlock };
75
+ }
@@ -0,0 +1,85 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
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|(?:tui|hud)-dock-(?:request|host)(?:-\d+)?\.json|macos-menu-(?:bar|detail)\.svg|codex-menu-bar-transparent\.png)(?:\.\d+(?:\.\d+)?(?:\.[a-z0-9]+)?\.tmp)?$/;
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
+
8
+ function lstat(file) {
9
+ try { return fs.lstatSync(file); } catch (error) { if (error.code === "ENOENT") return null; throw error; }
10
+ }
11
+
12
+ function readJson(file) {
13
+ try { return JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, "")); } catch { return null; }
14
+ }
15
+
16
+ export function isBatteryConfig(value) {
17
+ return Boolean(value && !Array.isArray(value) && value.version === 1
18
+ && ["providers", "codexWrapper", "codexStatusLineBackup", "claudeStatusLineBackup"].some(key => Object.hasOwn(value, key)));
19
+ }
20
+
21
+ function inside(file, root) {
22
+ const relative = path.relative(path.resolve(root), path.resolve(file));
23
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
24
+ }
25
+
26
+ export function cleanupBatteryArtifacts({ roots, home = os.homedir(), protectedRoots = [] }) {
27
+ const result = { removed: [], retained: [], errors: [] };
28
+ const protectedPaths = [home, path.parse(home).root, ...protectedRoots].map(file => {
29
+ try { return fs.realpathSync(file); } catch { return path.resolve(file); }
30
+ });
31
+ const removeFile = file => {
32
+ const stat = lstat(file);
33
+ if (!stat) return;
34
+ if (!stat.isFile() || stat.isSymbolicLink()) { result.retained.push(file); return; }
35
+ fs.unlinkSync(file);
36
+ result.removed.push(file);
37
+ };
38
+ const prune = directory => {
39
+ if (!fs.readdirSync(directory).length) { fs.rmdirSync(directory); result.removed.push(directory); }
40
+ };
41
+ const visit = (directory, kind) => {
42
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
43
+ const file = path.join(directory, entry.name);
44
+ if (entry.isSymbolicLink()) { result.retained.push(file); continue; }
45
+ if (entry.isDirectory()) {
46
+ const childKind = kind === "root" && ["bin", "hud", "runtimes", "claude-statusline-sessions", "claude-hud-sessions"].includes(entry.name)
47
+ ? entry.name
48
+ : kind === "runtimes" && /^(?:node-v\d+\.\d+\.\d+-win-(?:x64|arm64)|\.node-download-[\w-]+)$/.test(entry.name) ? "runtime" : null;
49
+ if (childKind) { visit(file, childKind); prune(file); }
50
+ else result.retained.push(file);
51
+ continue;
52
+ }
53
+ let owned = kind === "root" && STATE_FILES.test(entry.name);
54
+ if (kind === "root" && entry.name === "config.json") {
55
+ const config = readJson(file);
56
+ owned = isBatteryConfig(config) && !config.codexWrapper && !config.codexStatusLineBackup && !config.claudeStatusLineBackup && !Object.keys(config.integrationFiles || {}).length;
57
+ }
58
+ if (["claude-statusline-sessions", "claude-hud-sessions"].includes(kind)) {
59
+ owned = /^[\w-]+\.json(?:\.\d+\.tmp)?$/.test(entry.name)
60
+ && (entry.name.endsWith(".tmp") || readJson(file)?.provider === "claude" || kind === "claude-hud-sessions");
61
+ }
62
+ if (kind === "bin") owned = /^(?:rowpty\.exe|conpty\.dll|OpenConsole\.exe|rowpty\.src\.sha256)(?:\.old-[\w.-]+)?$/.test(entry.name);
63
+ if (kind === "hud") owned = HUD_FILES.has(entry.name);
64
+ if (kind === "runtimes") owned = /^\.node-\d+\.\d+\.\d+-(?:x64|arm64)\.lock$/.test(entry.name);
65
+ if (kind === "runtime") owned = /^(?:node\.exe|extract\.ps1|SHASUMS256\.txt|node-v\d+\.\d+\.\d+-win-(?:x64|arm64)\.zip)$/.test(entry.name);
66
+ if (owned) removeFile(file);
67
+ else result.retained.push(file);
68
+ }
69
+ };
70
+ for (const root of [...new Set(roots.filter(Boolean).map(file => path.resolve(file)))]) {
71
+ try {
72
+ const stat = lstat(root);
73
+ if (!stat) continue;
74
+ const resolved = fs.realpathSync(root);
75
+ if (!stat.isDirectory() || stat.isSymbolicLink()
76
+ || protectedPaths.some(file => inside(file, resolved) || (file !== path.resolve(home) && file !== path.parse(home).root && inside(resolved, file)))) {
77
+ result.errors.push({ path: root, error: "Refusing to clean a shared, protected, or symlinked directory" });
78
+ continue;
79
+ }
80
+ visit(root, "root");
81
+ prune(root);
82
+ } catch (error) { result.errors.push({ path: root, error: error.message }); }
83
+ }
84
+ return result;
85
+ }
@@ -7,7 +7,8 @@ function sleepSync(ms) {
7
7
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
8
8
  }
9
9
 
10
- export function createMacHudPlatform({ macStatusPath, relevantEnvPrefix, scriptDir, shellQuote }) {
10
+ export function createMacHudPlatform({ macStatusPath, relevantEnvPrefix, scriptDir, shellQuote,
11
+ home = os.homedir(), runLaunchctl = args => spawnSync("launchctl", args, { stdio: "ignore" }) }) {
11
12
  function parseMacHudArgs(cliArgs) {
12
13
  const options = {
13
14
  foreground: false,
@@ -106,7 +107,7 @@ function macHudPidsFromPsOutput(output, ownPid = process.pid) {
106
107
  }
107
108
 
108
109
  function macLaunchAgentPath() {
109
- return path.join(os.homedir(), "Library", "LaunchAgents", "com.ai-battery.hud.plist");
110
+ return path.join(home, "Library", "LaunchAgents", "com.ai-battery.hud.plist");
110
111
  }
111
112
 
112
113
  function macLaunchctlDomain() {
@@ -126,7 +127,7 @@ function plistString(value) {
126
127
  }
127
128
 
128
129
  function macAutostartPlist(options) {
129
- const args = [process.execPath, scriptPath, "start", "--interval", String(options.interval)];
130
+ const args = [process.execPath, path.join(scriptDir, "ai-battery-hud.js"), "start", "--interval", String(options.interval)];
130
131
  if (options.provider !== "all") args.push("--provider", options.provider);
131
132
  return `<?xml version="1.0" encoding="UTF-8"?>
132
133
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -150,17 +151,32 @@ function macAutostartStatus() {
150
151
  return { enabled: fs.existsSync(filePath), filePath };
151
152
  }
152
153
 
154
+ function verifyMacAutostartOwnership(filePath) {
155
+ let stat;
156
+ try { stat = fs.lstatSync(filePath); } catch (error) { if (error.code === "ENOENT") return false; throw error; }
157
+ const text = stat.isFile() && !stat.isSymbolicLink() ? fs.readFileSync(filePath, "utf8") : "";
158
+ const args = text.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1];
159
+ const values = [...(args || "").matchAll(/<string>([^<]*)<\/string>/g)].map(match => match[1]);
160
+ if (!/<key>Label<\/key>\s*<string>com\.ai-battery\.hud<\/string>/.test(text)
161
+ || !/[\\/]ai-battery-hud\.js$/.test(values[1] || "") || values[2] !== "start") {
162
+ throw new Error(`LaunchAgent ownership could not be verified; left untouched: ${filePath}`);
163
+ }
164
+ return true;
165
+ }
166
+
153
167
  function macAutostartEnable(options) {
154
168
  const filePath = macLaunchAgentPath();
169
+ verifyMacAutostartOwnership(filePath);
155
170
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
156
171
  fs.writeFileSync(filePath, macAutostartPlist(options), "utf8");
157
- spawnSync("launchctl", ["bootstrap", macLaunchctlDomain(), filePath], { stdio: "ignore" });
172
+ runLaunchctl(["bootstrap", macLaunchctlDomain(), filePath]);
158
173
  return filePath;
159
174
  }
160
175
 
161
176
  function macAutostartDisable() {
162
177
  const filePath = macLaunchAgentPath();
163
- spawnSync("launchctl", ["bootout", macLaunchctlDomain(), filePath], { stdio: "ignore" });
178
+ if (!verifyMacAutostartOwnership(filePath)) return filePath;
179
+ runLaunchctl(["bootout", macLaunchctlDomain(), filePath]);
164
180
  fs.rmSync(filePath, { force: true });
165
181
  return filePath;
166
182
  }
@@ -244,6 +260,8 @@ function runMacHud(cliArgs) {
244
260
  return {
245
261
  macHudCommandMatches,
246
262
  macHudPidsFromPsOutput,
263
+ macAutostartEnable,
264
+ macAutostartDisable,
247
265
  runMacHud
248
266
  };
249
267
  }
@@ -0,0 +1,35 @@
1
+ const quote = value => `'${String(value).replace(/'/g, "''")}'`;
2
+
3
+ // Parameters let the Windows regression test use its own temporary registry key.
4
+ export function windowsAutostartCleanupScript({ registryPath, registryName }) {
5
+ return [
6
+ "$ErrorActionPreference = 'Stop'",
7
+ "$dir = Join-Path $env:LOCALAPPDATA 'ai-battery'",
8
+ "$auto = Join-Path $dir 'autostart.ps1'",
9
+ "$hudDir = Join-Path $dir 'hud'",
10
+ "foreach ($p in @($dir, $auto, $hudDir)) { if ((Test-Path -LiteralPath $p) -and ((Get-Item -Force -LiteralPath $p).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw ('Refusing to follow an autostart symlink: ' + $p) } }",
11
+ `$v = (Get-ItemProperty -Path ${quote(registryPath)} -Name ${quote(registryName)} -ErrorAction SilentlyContinue).${registryName}`,
12
+ "$expected = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File \"' + $auto + '\"'",
13
+ "if ($v -and $v -ne $expected) { throw 'AiBatteryHud registry value changed; left it untouched.' }",
14
+ "$ownedFile = $false",
15
+ "if (Test-Path -LiteralPath $auto) {",
16
+ " $ownedFile = (Get-Content -Raw -LiteralPath $auto).StartsWith('# Generated by: ai-battery hud autostart on')",
17
+ " if (-not $ownedFile) { throw 'Autostart file changed; left it and its registry value untouched.' }",
18
+ "}",
19
+ `if ($v) { Remove-ItemProperty -Path ${quote(registryPath)} -Name ${quote(registryName)} }`,
20
+ "if ($ownedFile) {",
21
+ " Remove-Item -LiteralPath $auto -Force",
22
+ " if (Test-Path -LiteralPath $hudDir) {",
23
+ " foreach ($name in @('main.ps1', 'controls.ps1', 'dock.ps1', 'native.ps1', 'rendering.ps1', 'snapshot.ps1', 'windowing.ps1', 'ai-battery-hud.ps1')) {",
24
+ " $file = Join-Path $hudDir $name",
25
+ " if (Test-Path -LiteralPath $file -PathType Leaf) {",
26
+ " if ((Get-Item -Force -LiteralPath $file).Attributes -band [IO.FileAttributes]::ReparsePoint) { continue }",
27
+ " Remove-Item -LiteralPath $file -Force",
28
+ " }",
29
+ " }",
30
+ " if (-not (Get-ChildItem -Force -LiteralPath $hudDir | Select-Object -First 1)) { Remove-Item -LiteralPath $hudDir }",
31
+ " }",
32
+ "}",
33
+ "if ((Test-Path -LiteralPath $dir) -and -not (Get-ChildItem -Force -LiteralPath $dir | Select-Object -First 1)) { Remove-Item -LiteralPath $dir }"
34
+ ].join("\n");
35
+ }
@@ -2,6 +2,7 @@ import { spawnSync } from "node:child_process";
2
2
  import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import { windowsAutostartCleanupScript } from "./autostart-cleanup.js";
5
6
 
6
7
  export function createWindowsHudPlatform({
7
8
  buildStartProcessCommand,
@@ -748,20 +749,7 @@ function autostartEnable() {
748
749
  }
749
750
 
750
751
  function autostartDisable() {
751
- return runPowerShell([
752
- `$v = (Get-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -ErrorAction SilentlyContinue).${AUTOSTART_REG_NAME}`,
753
- "$dir = Join-Path $env:LOCALAPPDATA 'ai-battery'",
754
- "$auto = Join-Path $dir 'autostart.ps1'",
755
- "$ownedFile = $false",
756
- "if (Test-Path -LiteralPath $auto) { $ownedFile = (Get-Content -Raw -LiteralPath $auto) -like '*Generated by: ai-battery hud autostart on*' }",
757
- "if ($v -and ($v -notlike '*ai-battery*autostart.ps1*')) { Write-Error 'AiBatteryHud registry value is not managed by AI Battery; left it untouched.'; exit 2 }",
758
- `Remove-ItemProperty -Path '${AUTOSTART_REG_PATH}' -Name '${AUTOSTART_REG_NAME}' -ErrorAction SilentlyContinue`,
759
- "if ($ownedFile) {",
760
- " Remove-Item -LiteralPath $auto -Force -ErrorAction SilentlyContinue",
761
- " $hudDir = Join-Path $dir 'hud'",
762
- " if ((Split-Path -Parent $hudDir) -eq $dir -and (Test-Path -LiteralPath $hudDir)) { Remove-Item -LiteralPath $hudDir -Recurse -Force -ErrorAction SilentlyContinue }",
763
- "}"
764
- ].join("\n"));
752
+ return runPowerShell(windowsAutostartCleanupScript({ registryPath: AUTOSTART_REG_PATH, registryName: AUTOSTART_REG_NAME }));
765
753
  }
766
754
 
767
755
  if (subcommand === "status") {
@@ -786,7 +774,12 @@ if (subcommand === "autostart") {
786
774
  console.log("Windows and WSL use the same Run entry; enabling from the other side replaces this launcher.");
787
775
  console.log("After updating ai-battery, run \"ai-battery hud autostart on\" again to refresh it.");
788
776
  } else if (autostartAction === "off") {
789
- autostartDisable();
777
+ const result = autostartDisable();
778
+ if (result.status !== 0 || result.error) {
779
+ console.error("ai-battery-hud: autostart cleanup failed; preserved files that could not be verified.");
780
+ if (result.stderr) console.error(result.stderr.trim());
781
+ process.exit(1);
782
+ }
790
783
  console.log("HUD autostart disabled.");
791
784
  } else {
792
785
  const auto = autostartStatus();
@@ -27,15 +27,15 @@ function windowsUserPathParts() {
27
27
  const result = runWindowsPowerShell("[Environment]::GetEnvironmentVariable('Path', 'User')");
28
28
  if (result.status !== 0) throw new Error("Could not read Windows user PATH; leaving it unchanged");
29
29
  const text = result.stdout;
30
- return String(text || "")
31
- .trim()
32
- .split(";")
33
- .map((entry) => entry.trim())
34
- .filter(Boolean);
30
+ // PowerShell adds one output line ending. Preserve every other PATH byte,
31
+ // including whitespace, empty entries and trailing separators.
32
+ const raw = String(text || "").replace(/\r?\n$/, "");
33
+ return raw ? raw.split(";") : [];
35
34
  }
36
35
 
37
36
  function sameWindowsPath(left, right) {
38
- return path.resolve(left).toLowerCase() === path.resolve(right).toLowerCase();
37
+ if (!String(left).trim() || !String(right).trim()) return false;
38
+ return path.resolve(String(left).trim()).toLowerCase() === path.resolve(String(right).trim()).toLowerCase();
39
39
  }
40
40
 
41
41
  function staleWindowsAiBatteryTempPath(entry) {
@@ -105,7 +105,8 @@ function removeWindowsUserPathEntries(shimDirs) {
105
105
  if (nextParts.length === parts.length) return [];
106
106
 
107
107
  const result = runWindowsPowerShell(`[Environment]::SetEnvironmentVariable('Path', ${psQuote(nextParts.join(";"))}, 'User')`);
108
- return result.status === 0 ? ["Windows user PATH"] : [];
108
+ if (result.status !== 0 || result.error) throw new Error("Could not remove the AI Battery entry from Windows user PATH; kept the recovery record");
109
+ return ["Windows user PATH"];
109
110
  }
110
111
  return {
111
112
  ensureWindowsShimPath,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-battery",
3
- "version": "0.1.21",
3
+ "version": "0.1.23",
4
4
  "description": "Tiny terminal battery meter for local Codex and Claude Code usage.",
5
5
  "type": "module",
6
6
  "keywords": [