@sejuneoh/aitop 0.41.1 → 0.42.1

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.
@@ -32,6 +32,29 @@ export function emptyTokens() {
32
32
  return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
33
33
  }
34
34
 
35
+ // 프롬프트 캐시 적중률 (#334): 캐시 읽기 / (입력 + 캐시 읽기 + 캐시 쓰기), 0~1. 모델에 보낸 프롬프트 중 캐시에서 읽은 몫이다.
36
+ // 입력은 캐시를 뺀 몫이어야 한다 (Claude usage 의 input_tokens, Codex 는 수집기가 cached 를 뺀 값, agy 도 따로 센다).
37
+ // 분모가 0 이면(토큰을 모르는 도구, 아직 호출이 없는 세션) null.
38
+ export function cacheHitRate(t) {
39
+ const read = t?.cacheRead ?? 0;
40
+ const all = (t?.input ?? 0) + read + (t?.cacheWrite ?? 0);
41
+ return all > 0 ? read / all : null;
42
+ }
43
+
44
+ // 장부 벡터([입력, 출력, 캐시 읽기, 캐시 쓰기 5분, 캐시 쓰기 1시간], addModel 의 u·f)를 적중률 계산용 토큰 모양으로.
45
+ export const vecTokens = (v) => ({ input: v?.[0] ?? 0, cacheRead: v?.[2] ?? 0, cacheWrite: (v?.[3] ?? 0) + (v?.[4] ?? 0) });
46
+
47
+ // 적중률 글: 87%. 0 보다 크지만 반올림하면 0% 인 값은 <1%, 1 보다 작지만 100% 로 오르는 값은 99% 로 (다 맞은 것처럼 보이지 않게).
48
+ export function hitText(r) {
49
+ if (r == null) return null;
50
+ if (r > 0 && r < 0.005) return '<1%';
51
+ const n = Math.round(r * 100);
52
+ return `${n === 100 && r < 1 ? 99 : n}%`;
53
+ }
54
+
55
+ // --json 용: 소수 셋째 자리까지.
56
+ export const hitJson = (r) => (r == null ? null : Math.round(r * 1000) / 1000);
57
+
35
58
  const two = (n) => String(n).padStart(2, '0');
36
59
  // 사용자가 보는 날짜(로컬 시간대) 기준 날짜 키.
37
60
  export function dayKey(ms) {
@@ -66,14 +89,15 @@ export function recentDays(days, n = STORE_DAYS, now = Date.now()) {
66
89
 
67
90
  // 하루 합계(day)에 모델별 몫 { tokens, cost, u } 를 더한다. 모델 이름을 모르면 'unknown' 으로 센다.
68
91
  // unknown: 가격표에 없는 모델이라 비용을 0 으로 셌을 때. 그 모델 몫에 unknown 을 남겨 리포트가 ? 를 붙인다.
69
- // vec: 사용량 벡터(pricing.mjs VEC). fast 면 f 에 따로 더한다 (Claude fast 모드는 단가가 다르다).
70
- export function addModel(day, model, tokens, cost, unknown = false, vec = null, fast = false) {
92
+ // vec: 사용량 벡터(pricing.mjs VEC). fast 면 f 에, long 이면 l 에 따로 더한다 (Claude fast 모드와 긴 프롬프트 요청은 단가가 다르다).
93
+ // long 이 fast 보다 먼저다: 긴 프롬프트 단가가 있는 모델(Haiku 5.5)은 fast 가 없다.
94
+ export function addModel(day, model, tokens, cost, unknown = false, vec = null, fast = false, long = false) {
71
95
  const m = ((day.models ??= {})[String(model || 'unknown')] ??= { tokens: 0, cost: 0 });
72
96
  m.tokens += tokens;
73
97
  m.cost += cost;
74
98
  if (unknown) m.unknown = true;
75
99
  if (vec) {
76
- const to = fast ? (m.f ??= [0, 0, 0, 0, 0]) : (m.u ??= [0, 0, 0, 0, 0]);
100
+ const to = long ? (m.l ??= [0, 0, 0, 0, 0]) : fast ? (m.f ??= [0, 0, 0, 0, 0]) : (m.u ??= [0, 0, 0, 0, 0]);
77
101
  for (let i = 0; i < to.length; i++) to[i] += vec[i] ?? 0;
78
102
  }
79
103
  }
@@ -10,6 +10,7 @@ import { openReadOnly } from '../sqlite.mjs';
10
10
  import { debugIo } from '../log.mjs';
11
11
  import { claudeProjectRoots } from './dirs.mjs';
12
12
  import { coworkProjectOf } from './cowork.mjs';
13
+ import { isZst, inflateZst } from '../zstd.mjs';
13
14
 
14
15
  // 앞부분에서 cwd 를 찾을 때 읽는 최대 크기. Codex 의 첫 줄(session_meta)은 지침 글이 들어 있어 길 수 있다.
15
16
  const HEAD_BYTES = 256 * 1024;
@@ -21,6 +22,23 @@ const BUF = Buffer.allocUnsafe(HEAD_BYTES);
21
22
  // 대개 첫 몇 줄에 있으므로 CHUNK 씩 읽고, 찾으면 더 읽지 않는다.
22
23
  const CHUNK = 16 * 1024;
23
24
  function scanHead(path, pick) {
25
+ // Codex 압축 기록(.jsonl.zst)은 앞부분만 풀 수 없어 통째로 풀고 앞 HEAD_BYTES 안의 줄만 본다 (장부가 cwd 를 주지 못했을 때만).
26
+ if (isZst(path)) {
27
+ const got = inflateZst(path);
28
+ if (!got.data) return;
29
+ const head = got.data.subarray(0, HEAD_BYTES);
30
+ const end = head.length < HEAD_BYTES ? head.length : head.lastIndexOf(10);
31
+ for (const line of head.toString('utf8', 0, Math.max(0, end)).split('\n')) {
32
+ let x;
33
+ try {
34
+ x = JSON.parse(line);
35
+ } catch {
36
+ continue;
37
+ }
38
+ if (pick(x)) return;
39
+ }
40
+ return;
41
+ }
24
42
  let fd;
25
43
  try {
26
44
  fd = openSync(path, 'r');
@@ -164,8 +182,10 @@ export function attachProjects(books, root) {
164
182
  // Claude Desktop Cowork 기록은 기록 안의 cwd(VM·outputs 폴더) 대신 cowork 또는 사용자가 고른 폴더로 묶는다 (#313).
165
183
  project = coworkProjectOf(b.path) ?? claudeProject(b.path);
166
184
  if (!project) fallback = claudeFolder(b.path, root);
167
- } else if (b.tool === 'codex') project = codexProject(b.path);
168
- else if (b.tool === 'agy') project = (agy ??= agyWorkspaces()).get(basename(b.path, '.db')) ?? null;
185
+ } else if (b.tool === 'codex') {
186
+ // 압축 기록은 장부가 읽으면서 기억한 작업 폴더(b.cwd)를 먼저 쓴다 (다시 풀지 않게).
187
+ project = (isZst(b.path) ? b.cwd : null) ?? codexProject(b.path);
188
+ } else if (b.tool === 'agy') project = (agy ??= agyWorkspaces()).get(basename(b.path, '.db')) ?? null;
169
189
  }
170
190
  project = projectRoot(project);
171
191
  // 한 폴더 이름에 서로 다른 경로가 둘 이상 모이면(/a/b-c 와 /a/b/c, 한글 이름 등) 어느 쪽인지 모르니 묶지 않는다 (false).
@@ -0,0 +1,241 @@
1
+ // aitop --statusline [-- <사용자 상태줄 명령> [인자...]] (#332).
2
+ // Claude Code settings.json 의 statusLine.command 에 사용자가 직접 넣는다. 하는 일:
3
+ // 1. stdin(Claude Code 가 주는 JSON)을 끝까지 읽는다. 1MB 를 넘으면 거기까지, 1초 안에 안 끝나면 있는 만큼.
4
+ // 2. rate_limits 의 숫자·시각만 꺼내 claude-limits.json 에 저장한다 (limits.mjs). 값이 없으면 파일을 그대로 둔다.
5
+ // 3. `--` 뒤 명령이 있으면 같은 stdin 바이트를 그 명령에 넘기고, 그 stdout 을 그대로 내고 종료 코드도 따른다 (2초 제한).
6
+ // 없으면 짧은 기본 줄(limits.mjs statusText)을 낸다.
7
+ // 명령 실행 규칙:
8
+ // - `--` 뒤가 인자 하나이고 그 안에 공백이 있으면 셸 문자열로 보고 플랫폼 셸(Linux·macOS /bin/sh, Windows cmd.exe)로 실행한다.
9
+ // 예) aitop --statusline -- "npx -y ccstatusline"
10
+ // - 그 밖에는 인자 배열 그대로 셸 없이 실행한다 (shell:false). 예) aitop --statusline -- npx -y ccstatusline
11
+ // Windows 에서 셸 없이 찾을 수 없는 명령(npx.cmd 같은 .cmd·.bat)은 cmd.exe 로 한 번 더 해 본다.
12
+ // 화면 모듈·수집기·설정·i18n 은 불러오지 않는다 (상태줄은 응답마다 불리므로 빨리 끝나야 한다).
13
+ import { spawn, spawnSync } from 'node:child_process';
14
+ import { existsSync } from 'node:fs';
15
+ import { win32 } from 'node:path';
16
+ import { freshLimits, parseLimits, saveLimits, statusText } from './limits.mjs';
17
+
18
+ export const STDIN_MAX = 1024 * 1024;
19
+ export const STDIN_MS = 1000;
20
+ export const CHILD_MS = 2000;
21
+
22
+ // stdin 을 Buffer 로. 상한을 넘거나 시간이 지나면 있는 만큼 돌려준다.
23
+ export function readInput(stream = process.stdin, { max = STDIN_MAX, ms = STDIN_MS } = {}) {
24
+ return new Promise((resolve) => {
25
+ const chunks = [];
26
+ let size = 0;
27
+ let done = false;
28
+ const finish = () => {
29
+ if (done) return;
30
+ done = true;
31
+ clearTimeout(timer);
32
+ stream.off('data', onData);
33
+ stream.off('end', finish);
34
+ stream.off('error', finish);
35
+ stream.pause();
36
+ resolve(Buffer.concat(chunks).subarray(0, max));
37
+ };
38
+ const onData = (c) => {
39
+ const b = Buffer.isBuffer(c) ? c : Buffer.from(c);
40
+ chunks.push(b);
41
+ size += b.length;
42
+ if (size >= max) finish();
43
+ };
44
+ const timer = setTimeout(finish, ms);
45
+ stream.on('data', onData);
46
+ stream.once('end', finish);
47
+ stream.once('error', finish);
48
+ stream.resume();
49
+ });
50
+ }
51
+
52
+ // Windows cmd.exe 에 넘길 인자 하나를 따옴표로 감싼다 (공백·특수 문자가 있을 때만). 명령은 사용자 자신의 설정에서 온다.
53
+ const winQuote = (a) => (/^[\w.:\\/=@+-]+$/.test(a) ? a : `"${a.replaceAll('"', '""')}"`);
54
+
55
+ // 실행 방법을 고른다. 돌려주는 값: { file, args, shell }.
56
+ export function commandPlan(cmd) {
57
+ if (cmd.length === 1 && /\s/.test(cmd[0])) return { file: cmd[0], args: [], shell: true };
58
+ return { file: cmd[0], args: cmd.slice(1), shell: false };
59
+ }
60
+
61
+ // 자식 stdout 상한. 상태줄은 몇 줄이면 되므로 넘는 부분은 버린다.
62
+ export const STDOUT_MAX = 64 * 1024;
63
+ // 그룹에 SIGTERM 을 보낸 뒤 SIGKILL 까지 기다리는 시간.
64
+ export const KILL_GRACE_MS = 200;
65
+
66
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
67
+ // 프로세스 그룹에 아직 살아 있는 프로세스가 있는지 (신호 0).
68
+ const groupAlive = (pid) => {
69
+ try {
70
+ process.kill(-pid, 0);
71
+ return true;
72
+ } catch {
73
+ return false;
74
+ }
75
+ };
76
+
77
+ // 자식을 손자까지 끈다. 시간 초과와 aitop 이 신호를 받았을 때 쓴다.
78
+ // - POSIX: detached 로 띄워 자식이 자기 프로세스 그룹의 우두머리다. 그룹째 SIGTERM, KILL_GRACE_MS 뒤에도 남아 있으면 SIGKILL.
79
+ // 셸 문자열(`sleep 30; echo hi`)의 sleep 이나 TERM 을 무시하는 자식도 남지 않는다.
80
+ // - Windows: 프로세스 그룹이 없으므로 taskkill /T /F 로 자식 트리를 끈다 (notify.mjs 와 같은 방법.
81
+ // 그 모듈은 i18n 을 불러오므로 여기서는 따로 둔다). taskkill 을 부르지 못하면 자식 하나라도 끈다.
82
+ // sync 이면 기다리지 않는다 (신호 처리 중에는 SIGKILL 을 바로 보낸다).
83
+ export async function stopTree(child, { platform = process.platform, spawnFn = spawn, grace = KILL_GRACE_MS, sync = false } = {}) {
84
+ const pid = child?.pid;
85
+ if (!pid) return;
86
+ if (platform === 'win32') {
87
+ try {
88
+ const root = process.env.SystemRoot;
89
+ const tk = root ? win32.join(root, 'System32', 'taskkill.exe') : 'taskkill.exe';
90
+ const args = ['/pid', String(pid), '/T', '/F'];
91
+ // 신호 처리 중에는 곧 process.exit 하므로 taskkill 이 끝날 때까지(2초까지) 기다린다.
92
+ if (sync) spawnSync(tk, args, { stdio: 'ignore', windowsHide: true, timeout: 2000 });
93
+ else spawnFn(tk, args, { stdio: 'ignore', windowsHide: true }).on?.('error', () => child.kill());
94
+ } catch {
95
+ try {
96
+ child.kill();
97
+ } catch {}
98
+ }
99
+ return;
100
+ }
101
+ try {
102
+ process.kill(-pid, sync ? 'SIGKILL' : 'SIGTERM');
103
+ } catch {
104
+ try {
105
+ child.kill(sync ? 'SIGKILL' : 'SIGTERM');
106
+ } catch {}
107
+ }
108
+ if (sync) return;
109
+ await sleep(grace);
110
+ if (groupAlive(pid)) {
111
+ try {
112
+ process.kill(-pid, 'SIGKILL');
113
+ } catch {}
114
+ }
115
+ }
116
+
117
+ // 지금 돌고 있는 사용자 명령. aitop 이 신호를 받으면 이것들을 그룹째 끈다.
118
+ const running = new Set();
119
+
120
+ // 명령 하나를 실행해 { code, stdout, error } 를 돌려준다. input 을 stdin 으로 넘긴다. deadline(ms 시각)을 넘으면 끈다.
121
+ function runOnce({ file, args, shell }, input, deadline, { platform = process.platform, spawnFn = spawn } = {}) {
122
+ return new Promise((resolve) => {
123
+ let child;
124
+ // POSIX 는 detached 로 새 프로세스 그룹을 만든다 (stdin·stdout 파이프는 그대로). Windows 의 detached 는 콘솔 창을 새로 열므로 쓰지 않는다.
125
+ const opts = { stdio: ['pipe', 'pipe', 'inherit'], windowsHide: true, detached: platform !== 'win32' };
126
+ try {
127
+ // shell:true 일 때는 인자 배열을 넘기지 않는다 (Node 가 따옴표 없이 이어 붙이므로 문자열 하나로만 쓴다).
128
+ child = shell ? spawnFn(file, { ...opts, shell: true }) : spawnFn(file, args, { ...opts, shell: false });
129
+ } catch (e) {
130
+ resolve({ code: null, stdout: Buffer.alloc(0), error: e });
131
+ return;
132
+ }
133
+ running.add(child);
134
+ const out = [];
135
+ let size = 0;
136
+ let settled = false;
137
+ // 시간을 넘겨 끄는 중이면 그 사이 자식이 끝나도(close) 기다리지 않고, 그룹 끄기(SIGKILL 까지)가 끝난 뒤 시간 초과로 끝낸다.
138
+ // 먼저 끝내면 bin 이 process.exit 해서 TERM 을 무시한 손자에게 SIGKILL 을 보내지 못한다.
139
+ let timedOut = false;
140
+ const end = (r) => {
141
+ if (settled || (timedOut && !r.timedOut)) return;
142
+ settled = true;
143
+ clearTimeout(timer);
144
+ running.delete(child);
145
+ resolve({ stdout: Buffer.concat(out).subarray(0, STDOUT_MAX), ...r });
146
+ };
147
+ const timer = setTimeout(async () => {
148
+ timedOut = true;
149
+ await stopTree(child, { platform, spawnFn });
150
+ end({ code: null, timedOut: true });
151
+ }, Math.max(0, deadline - Date.now()));
152
+ child.stdout.on('data', (c) => {
153
+ if (size >= STDOUT_MAX) return;
154
+ out.push(c);
155
+ size += c.length;
156
+ });
157
+ child.on('error', (e) => end({ code: null, error: e }));
158
+ child.on('close', (code, signal) => end({ code: code ?? (signal ? 1 : 0) }));
159
+ // 명령이 stdin 을 읽지 않고 끝나도 EPIPE 로 죽지 않게 한다.
160
+ child.stdin.on('error', () => {});
161
+ child.stdin.end(input);
162
+ });
163
+ }
164
+
165
+ // aitop 이 SIGTERM·SIGHUP·SIGINT 를 받으면(Claude Code 가 상태줄 실행을 취소할 때 등) 자식 그룹을 끄고 끝낸다.
166
+ const SIGNALS = ['SIGTERM', 'SIGHUP', 'SIGINT'];
167
+ function onSignal(sig) {
168
+ for (const c of running) stopTree(c, { sync: true });
169
+ process.exit(128 + ({ SIGHUP: 1, SIGINT: 2, SIGTERM: 15 }[sig] ?? 0));
170
+ }
171
+
172
+ // 명령이 경로로 적혔는지 (구분자가 있거나 . 으로 시작). 이름만 적은 명령(npx)은 PATH 에서 찾는다.
173
+ const isPathLike = (f, platform) => (platform === 'win32' ? /[\\/]/.test(f) || /^[a-z]:/i.test(f) : f.includes('/')) || f.startsWith('.');
174
+ // Windows 에서 경로로 적은 명령이 있는지. 확장자 없이 적었으면 PATHEXT 의 흔한 확장자도 본다.
175
+ function winPathExists(f, exists) {
176
+ if (exists(f)) return true;
177
+ return ['.exe', '.cmd', '.bat', '.com'].some((ext) => exists(f + ext));
178
+ }
179
+ // cmd.exe 가 명령을 찾지 못했을 때의 종료 코드.
180
+ const CMD_NOT_FOUND = 9009;
181
+
182
+ // 사용자 상태줄 명령을 실행한다. Windows 에서 셸 없이 못 찾은 명령은 cmd.exe 로 한 번 더 해 본다.
183
+ // 없는 명령은 플랫폼과 상관없이 error(ENOENT)로 돌려주어 127 로 끝나게 한다:
184
+ // - 경로로 적은 명령이 아예 없으면 cmd 로 다시 해 보지 않는다 (cmd 는 못 찾으면 9009 나 1 로 끝나 원인이 흐려진다).
185
+ // - cmd 로 다시 해 본 결과가 9009(명령을 찾지 못함)이면 처음 오류를 그대로 돌려준다.
186
+ // platform·spawnFn·exists 는 테스트에서 바꿔 끼운다.
187
+ export async function runCommand(cmd, input, { ms = CHILD_MS, platform = process.platform, spawnFn = spawn, exists = existsSync } = {}) {
188
+ const deadline = Date.now() + ms;
189
+ const plan = commandPlan(cmd);
190
+ const env = { platform, spawnFn };
191
+ let r = await runOnce(plan, input, deadline, env);
192
+ if (platform === 'win32' && !plan.shell && ['ENOENT', 'EINVAL'].includes(r.error?.code)) {
193
+ if (isPathLike(cmd[0], platform) && !winPathExists(cmd[0], exists)) return r;
194
+ const first = r;
195
+ r = await runOnce({ file: cmd.map(winQuote).join(' '), args: [], shell: true }, input, deadline, env);
196
+ if (r.code === CMD_NOT_FOUND) return { ...first, stdout: r.stdout };
197
+ }
198
+ return r;
199
+ }
200
+
201
+ const write = (stream, data) => new Promise((resolve) => (data.length ? stream.write(data, resolve) : resolve()));
202
+
203
+ // 본체. argv 는 `--statusline` 뒤의 인자들 (`--` 포함). 돌려주는 값은 종료 코드.
204
+ export async function statusline(argv, { stdin = process.stdin, stdout = process.stdout, stderr = process.stderr, file, now = Date.now } = {}) {
205
+ const sep = argv.indexOf('--');
206
+ const extra = sep < 0 ? argv : argv.slice(0, sep);
207
+ const cmd = sep < 0 ? [] : argv.slice(sep + 1);
208
+ if (extra.length || (sep >= 0 && !cmd.length)) {
209
+ stderr.write(`aitop: usage: aitop --statusline [-- <command> [args...]]\n`);
210
+ return 2;
211
+ }
212
+ const input = await readInput(stdin);
213
+ let limits = null;
214
+ try {
215
+ limits = parseLimits(JSON.parse(input.toString('utf8')), now());
216
+ } catch {}
217
+ // 저장이 실패해도 상태줄 출력은 막지 않는다.
218
+ if (limits) saveLimits(limits, { ...(file ? { file } : {}), now: now() });
219
+ if (!cmd.length) {
220
+ // 초기화 시각이 이미 지난 창은 뺀다 (Claude Code 가 빼 주지만 시계가 어긋날 수 있다).
221
+ await write(stdout, Buffer.from(statusText(freshLimits(limits && { at: now(), ...limits }, now()), now()) + '\n'));
222
+ return 0;
223
+ }
224
+ for (const sig of SIGNALS) process.on(sig, onSignal);
225
+ let r;
226
+ try {
227
+ r = await runCommand(cmd, input);
228
+ } finally {
229
+ for (const sig of SIGNALS) process.off(sig, onSignal);
230
+ }
231
+ await write(stdout, r.stdout);
232
+ if (r.error) {
233
+ stderr.write(`aitop: --statusline: ${cmd[0]}: ${r.error.code ?? r.error.message}\n`);
234
+ return 127;
235
+ }
236
+ if (r.timedOut) {
237
+ stderr.write(`aitop: --statusline: ${cmd[0]}: timed out after ${CHILD_MS / 1000}s\n`);
238
+ return 124;
239
+ }
240
+ return r.code;
241
+ }
package/src/tail.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  // 화면 갱신과 키 입력이 멈추지 않게 한다. 원본은 읽기 전용으로만 연다.
3
3
  import { openSync, readSync, closeSync, statSync } from 'node:fs';
4
4
  import { debug, debugIo } from './log.mjs';
5
+ import { isZst, inflateZst } from './zstd.mjs';
5
6
 
6
7
  const CHUNK = 1 << 20;
7
8
  const NL = 0x0a;
@@ -25,6 +26,13 @@ export class JsonlTail {
25
26
  this.restLength = 0;
26
27
  this.mtimeMs = 0;
27
28
  this.size = 0;
29
+ // Codex 압축 기록(.jsonl.zst, zstd.mjs): 통째로 풀어 한 번에 읽는다. offset 은 압축 파일 크기까지 읽었는지만 뜻한다.
30
+ this.zst = isZst(path);
31
+ // 압축 기록을 다 읽었을 때의 수정 시각 (같은 크기로 바뀐 것을 알아채려고). 캐시에서 이어 읽으면 모른다(null).
32
+ this.zstMtime = null;
33
+ // 압축 기록을 읽지 못한 까닭 ('nozstd' | 'toolarge' | 'error') 과 그때의 크기·수정 시각. 바뀌기 전에는 다시 풀지 않는다.
34
+ this.skipped = null;
35
+ this.skipSig = null;
28
36
  }
29
37
 
30
38
  // 완성된 줄까지 읽은 위치. 캐시에 저장해 두고 다음 실행에서 여기서부터 읽는다.
@@ -51,6 +59,7 @@ export class JsonlTail {
51
59
  }
52
60
  this.mtimeMs = st.mtimeMs;
53
61
  this.size = st.size;
62
+ if (this.zst) return this.readZst(onLine, budget, st);
54
63
  // 파일이 줄었으면(새로 쓰임) 처음부터 다시 읽는다. 누적값을 들고 있는 쪽은 onReset 에서 비워야 두 번 더하지 않는다.
55
64
  if (st.size < this.offset) {
56
65
  this.offset = 0;
@@ -114,4 +123,64 @@ export class JsonlTail {
114
123
  }
115
124
  return count;
116
125
  }
126
+
127
+ // 압축 기록은 뒤에 붙지 않으므로 크기·수정 시각이 바뀌면 처음부터 다시 읽는다. 해제는 나눌 수 없어 통째로 한다.
128
+ // 한도가 있는 갱신(실시간 화면)에서는 한 budget 에 압축 기록 하나만 풀어 갱신이 오래 멈추지 않게 한다. 한도가 없으면 다 푼다.
129
+ readZst(onLine, budget, st) {
130
+ const sig = `${st.size}:${st.mtimeMs}`;
131
+ if (this.offset === st.size && (this.zstMtime === null || this.zstMtime === st.mtimeMs)) return 0;
132
+ if (this.skipSig === sig) {
133
+ // 읽지 못한 기록은 읽을 것이 없는 것으로 보인다 (진행률·남은 크기가 멈춰 있지 않게).
134
+ this.size = this.offset;
135
+ return 0;
136
+ }
137
+ if (this.offset > 0) {
138
+ this.offset = 0;
139
+ this.zstMtime = null;
140
+ this.onReset?.();
141
+ }
142
+ const limited = Number.isFinite(budget.left) || Number.isFinite(budget.deadline ?? Infinity);
143
+ if (outOf(budget) || (limited && budget.zst)) {
144
+ budget.exhausted = true;
145
+ return 0;
146
+ }
147
+ if (limited) budget.zst = true;
148
+ const got = inflateZst(this.path);
149
+ if (!got.data) {
150
+ this.skipped = got.skip;
151
+ this.skipSig = sig;
152
+ this.size = this.offset;
153
+ return 0;
154
+ }
155
+ this.skipped = null;
156
+ this.skipSig = null;
157
+ const data = got.data;
158
+ budget.left -= data.length;
159
+ budget.read = (budget.read ?? 0) + data.length;
160
+ let count = 0;
161
+ for (let s = 0; s < data.length; ) {
162
+ let e = data.indexOf(NL, s);
163
+ if (e < 0) e = data.length;
164
+ if (e > s) {
165
+ let x;
166
+ try {
167
+ x = JSON.parse(data.toString('utf8', s, e));
168
+ } catch (err) {
169
+ debug('jsonl', 'line parse failed', err, this.path);
170
+ x = null;
171
+ }
172
+ if (x) {
173
+ onLine(x, s, e - s);
174
+ count++;
175
+ }
176
+ }
177
+ s = e + 1;
178
+ }
179
+ this.offset = st.size;
180
+ this.rest = [];
181
+ this.restLength = 0;
182
+ this.zstMtime = st.mtimeMs;
183
+ // 줄이 하나도 없어도 다 읽었다는 것을 캐시에 남기도록 1 이상을 돌려준다.
184
+ return Math.max(count, 1);
185
+ }
117
186
  }
package/src/trace.mjs CHANGED
@@ -13,6 +13,7 @@ import { fmtElapsed, fmtTokens, mask, maskStrict, oneLine, pad, stripControl, tr
13
13
  import { money } from './line.mjs';
14
14
  import { glyphs } from './ui/glyphs.mjs';
15
15
  import { isNoisePrompt, sessionName, toolDetail } from './sources/common.mjs';
16
+ import { plainName, rolloutNames } from './zstd.mjs';
16
17
 
17
18
  // 노드 수 상한 (묶고 접은 뒤). 넘으면 오래된 지시부터 뺀다.
18
19
  export const MAX_NODES = 300;
@@ -392,11 +393,12 @@ export async function findTrace(query, { claudeRoots, codexRoots, agyRoot } = {}
392
393
  // agy 기록 폴더: CLI 폴더와 앱 폴더 (#303). agyRoot 는 폴더 하나 또는 목록.
393
394
  const agyDirs = agyRoot == null ? (await import('./sources/antigravity.mjs')).agyRoots().map((r) => r.dir) : [agyRoot].flat();
394
395
  // 1) 파일 경로
395
- if (/\.(jsonl|db)$/i.test(q) && existsSync(q)) {
396
+ if (/\.(jsonl|db|jsonl\.zst)$/i.test(q) && existsSync(q)) {
396
397
  const p = resolve(q);
397
398
  const name = basename(p);
398
399
  if (/\.db$/i.test(name)) return { tool: 'agy', path: p, id: name.slice(0, -3), name: null };
399
- if (/^rollout-/.test(name)) return { tool: 'codex', path: p, id: name.slice(0, -6), name: null };
400
+ // Codex 압축 기록(.jsonl.zst)도 같은 id (zstd.mjs).
401
+ if (/^rollout-/.test(name)) return { tool: 'codex', path: p, id: plainName(name).slice(0, -6), name: null };
400
402
  return { tool: 'claude', path: p, id: name.slice(0, -6), name: claudeNames(p).name };
401
403
  }
402
404
  const low = q.toLowerCase();
@@ -419,14 +421,14 @@ export async function findTrace(query, { claudeRoots, codexRoots, agyRoot } = {}
419
421
  if (!prev || c.mtime > prev.mtime) byId.set(c.id, c);
420
422
  }
421
423
  found.push(...byId.values());
422
- // Codex: sessions/YYYY/MM/DD/rollout-...-<uuid>.jsonl
424
+ // Codex: sessions/YYYY/MM/DD/rollout-...-<uuid>.jsonl (7일 넘게 쉰 기록은 .jsonl.zst, 둘 다 있으면 .jsonl)
423
425
  const digits = (p) => list(p).filter((n) => /^\d+$/.test(n)).map((n) => join(p, n));
424
426
  for (const root of codexRoots) {
425
427
  for (const y of digits(root))
426
428
  for (const m of digits(y))
427
429
  for (const d of digits(m))
428
- for (const f of list(d)) {
429
- const u = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(f)?.[1];
430
+ for (const f of rolloutNames(list(d))) {
431
+ const u = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl(?:\.zst)?$/i.exec(f)?.[1];
430
432
  if (u && u.toLowerCase().startsWith(low)) found.push({ tool: 'codex', id: u, path: join(d, f), mtime: mtimeOf(join(d, f)) });
431
433
  }
432
434
  }
package/src/ui/chrome.mjs CHANGED
@@ -65,7 +65,8 @@ export function helpSections(view = {}, open = false) {
65
65
  const keys = [...here.map((n) => VIEWS[n]), COMMON].map((v) => viewText(v)).flatMap((v, i) => [...(i ? [['', '']] : []), [`${v.title}${i ? '' : t('help.here')}`, null], ...v.keys]);
66
66
  const others = Object.keys(VIEWS).filter((n) => !here.includes(n));
67
67
  const rest = [['', ''], [t('help.others'), null], ...others.map((n) => [viewText(VIEWS[n]).title, keysLine(n), 'dim'])];
68
- const now = settingsLine(view.settings);
68
+ // Claude 한도의 마지막 갱신은 화면 데이터(collect 의 limits)에서 가져온다 (#332).
69
+ const now = settingsLine(view.settings && view.data ? { ...view.settings, limitsAt: view.data.limits?.at ?? null, now: view.data.at } : view.settings);
69
70
  const opts = [
70
71
  [t('help.options'), null],
71
72
  ...options(),
package/src/ui/detail.mjs CHANGED
@@ -4,7 +4,7 @@ import { currentTab, filesForTab, turnTabs } from '../turns.mjs';
4
4
  import { isAbsolute, relative } from 'node:path';
5
5
  import { PALETTE, PHASE_COLOR } from './theme.mjs';
6
6
  import { NOW, box, cacheState, clock, fill, gauge, glyph, hhmm, levelBar, money, rule, segsWidth, tilde } from './draw.mjs';
7
- import { activitySeries } from '../sources/common.mjs';
7
+ import { activitySeries, cacheHitRate, hitText } from '../sources/common.mjs';
8
8
  import { glyphs } from './glyphs.mjs';
9
9
  import { STRINGS, phaseText, t as tr } from '../i18n.mjs';
10
10
  import { resumeCmd } from '../resume.mjs';
@@ -377,7 +377,8 @@ function fitGroups(groups, w) {
377
377
 
378
378
  // 좁은 화면의 요약 두 줄.
379
379
  // 1줄: 상태 · 폴더 · 브랜치 · 종류 · 시작.
380
- // 2줄: 571k +서브2 (입력 90.3k·출력 18.4k·캐시 463k) · $0.17 · ctx 5% · pid 218093. 캐시는 읽기와 쓰기를 더한 값이다.
380
+ // 2줄: 571k +서브2 (입력 90.3k·출력 18.4k·캐시 463k·적중 80%) · $0.17 · ctx 5% · pid 218093. 캐시는 읽기와 쓰기를 더한 값이다.
381
+ // 적중은 프롬프트 캐시 적중률(#334)로, 80칸에서도 보이게 토큰 내역 괄호 안에 짧게 둔다.
381
382
  // 폭이 모자라면 pid → 토큰 내역 → 서브에이전트 수 → ctx 순으로 뺀다.
382
383
  export function summaryLines(s, w, frame, view) {
383
384
  const g = glyph(s, frame);
@@ -404,7 +405,10 @@ export function summaryLines(s, w, frame, view) {
404
405
  const t = s.tokens ?? {};
405
406
  const net = view?.costMode === 'net';
406
407
  const total = { segs: [{ t: fmtTokens(t.total), fg: PALETTE.text, bold: true }] };
407
- const parts = { segs: [{ t: ' (', fg: PALETTE.info }, { t: tr('detail.tokenParts', { i: fmtTokens(t.input), o: fmtTokens(t.output), c: fmtTokens((t.cacheRead ?? 0) + (t.cacheWrite ?? 0)) }), fg: PALETTE.info }, { t: ')', fg: PALETTE.info }], drop: 3 };
408
+ // 프롬프트 캐시 적중률 (#334). 토큰 내역을 모르는 도구(분모 0)는 붙이지 않는다.
409
+ const rate = hitText(cacheHitRate(t));
410
+ const hit = rate ? `·${tr('detail.cacheHitShort', { r: rate })}` : '';
411
+ const parts = { segs: [{ t: ' (', fg: PALETTE.info }, { t: tr('detail.tokenParts', { i: fmtTokens(t.input), o: fmtTokens(t.output), c: fmtTokens((t.cacheRead ?? 0) + (t.cacheWrite ?? 0)) }) + hit, fg: PALETTE.info }, { t: ')', fg: PALETTE.info }], drop: 3 };
408
412
  const sub = t.subCount ? { segs: [{ t: tr('detail.sub', { n: t.subCount }), fg: PALETTE.muted }], drop: 2 } : null;
409
413
  const cost = s.cost != null ? { segs: [sep, ...(net ? [{ t: tr('detail.netTag'), fg: PALETTE.muted }] : []), { t: money(net ? s.costNoCache : s.cost, s.costUnknown), fg: PALETTE.money, bold: true }] } : null;
410
414
  let ctx = null;
@@ -564,7 +568,11 @@ export function detail(s, W, H, frame, view) {
564
568
  // 합계 = 메인 + 서브 = 입력 + 출력 + 캐시 읽기 + 캐시 쓰기 가 화면에서 그대로 맞아떨어지게 보인다.
565
569
  const t = s.tokens ?? {};
566
570
  section(tr('detail.tokens'));
567
- kv(tr('detail.total'), fmtTokens(t.total));
571
+ // 프롬프트 캐시 적중률 (#334): 메인과 서브에이전트를 더한 토큰에서. 숫자만 보이고 높낮이는 따지지 않는다.
572
+ // 줄을 늘리면 낮은 화면에서 비용 줄이 밀려나므로 합계 줄 끝에 붙인다 (왼쪽 칸은 100칸 화면에서도 36칸이라 들어간다).
573
+ const rate = hitText(cacheHitRate(t));
574
+ if (rate) L.push([INDENT, { t: pad(tr('detail.total'), 9), fg: PALETTE.muted }, { t: fmtTokens(t.total), fg: PALETTE.text }, { t: ` · ${tr('detail.cacheHit', { r: rate })}`, fg: PALETTE.info }]);
575
+ else kv(tr('detail.total'), fmtTokens(t.total));
568
576
  if (t.subCount) more([{ t: tr('detail.mainSub', { m: fmtTokens(t.main), n: t.subCount, s: fmtTokens(t.sub) }), fg: PALETTE.info }]);
569
577
  more([{ t: tr('detail.inOut', { i: fmtTokens(t.input), o: fmtTokens(t.output) }), fg: PALETTE.info }]);
570
578
  more([{ t: tr('detail.cache', { r: fmtTokens(t.cacheRead), w: fmtTokens(t.cacheWrite) }), fg: PALETTE.info }]);
package/src/ui/table.mjs CHANGED
@@ -10,6 +10,7 @@ import { glyphs } from './glyphs.mjs';
10
10
  import { phaseText, t } from '../i18n.mjs';
11
11
  import { NO_FOLDER } from '../order.mjs';
12
12
  import { callsYou, isStopped } from '../attention.mjs';
13
+ import { freshLimits, pctLevel, pctText } from '../limits.mjs';
13
14
 
14
15
  // 검색어가 세션 이름·폴더·모델 중 하나에 들어 있으면 남긴다 (대소문자 무시).
15
16
  export function filterSessions(sessions, query) {
@@ -213,19 +214,28 @@ export function progressSegs(r, bg) {
213
214
  // 폭이 모자랄 때 도구 이름 대신 쓰는 짧은 이름.
214
215
  export const TOOL_SHORT = { claude: 'cla', cowork: 'cwk', codex: 'cdx', gemini: 'gem' };
215
216
 
216
- // 도구 하나의 조각. level 0 은 다 보이고, 2 부터 토큰 수·미설치 글을 빼고, 3 은 이름을 줄인다.
217
+ // Claude 한도 조각 (#332): ' · 5h 23% · 7d 41%'. 80% 이상은 예산과 같은 주의색, 95% 이상은 경고색.
218
+ function limitSegs(limits) {
219
+ if (!limits) return [];
220
+ const one = (label, w) => (w ? [{ t: ' · ', fg: PALETTE.muted }, { t: `${label} `, fg: PALETTE.muted }, { t: pctText(w.pct), fg: BUDGET_COLOR[pctLevel(w.pct)] ?? PALETTE.text, bold: pctLevel(w.pct) !== 'ok' }] : []);
221
+ return [...one('5h', limits.fiveHour), ...one('7d', limits.sevenDay)];
222
+ }
223
+
224
+ // 도구 하나의 조각. level 0 은 다 보이고, 1 은 토큰 수를 빼고(한도가 있을 때만 쓰는 단계), 2 부터 미설치 글·한도를 빼고, 3 은 이름을 줄인다.
217
225
  function toolPart(p, level, showEnded) {
218
226
  const name = level >= 3 ? TOOL_SHORT[p.tool] : p.tool;
219
227
  const extra = level < 2;
228
+ const tok = level < 1;
229
+ const lim = extra ? limitSegs(p.limits) : [];
220
230
  // 세션이 없는 도구는 이름만 흐리게 둔다.
221
231
  if (!p.live) {
222
232
  // 종료 세션을 함께 볼 때는 그 도구의 누적 토큰을 흐리게 남긴다. 기록 폴더가 없으면 미설치로 보인다.
223
- const more = !extra ? [] : p.missing ? [{ t: ` ${t('tools.missing')}`, fg: PALETTE.info, italic: true }] : showEnded && p.count ? [{ t: ` · ${fmtTokens(p.tok)}`, fg: PALETTE.info }] : [];
233
+ const more = !extra ? [] : p.missing ? [{ t: ` ${t('tools.missing')}`, fg: PALETTE.info, italic: true }] : showEnded && p.count && tok ? [{ t: ` · ${fmtTokens(p.tok)}`, fg: PALETTE.info }] : [];
224
234
  // 실행 중 표시(▍) 자리를 비우지 않아 조각 사이가 고르게 2칸이다.
225
- return [{ t: name, fg: PALETTE.info }, ...more];
235
+ return [{ t: name, fg: PALETTE.info }, ...more, ...lim];
226
236
  }
227
237
  const tc = PALETTE.tools[p.tool];
228
- return [{ t: glyphs().tool, fg: tc }, { t: name, fg: tc, bold: true }, { t: ` ${p.live}`, fg: PALETTE.text }, ...(extra ? [{ t: ` · ${fmtTokens(p.tok)}`, fg: PALETTE.muted }] : [])];
238
+ return [{ t: glyphs().tool, fg: tc }, { t: name, fg: tc, bold: true }, { t: ` ${p.live}`, fg: PALETTE.text }, ...(tok ? [{ t: ` · ${fmtTokens(p.tok)}`, fg: PALETTE.muted }] : []), ...lim];
229
239
  }
230
240
 
231
241
  // 이 기간 동안 세션이 없는 도구는 도구 줄에서 숨긴다 (설정 파일 hideIdleTools 로 끈다).
@@ -256,6 +266,8 @@ export function toolStrip(view, W) {
256
266
  const list = view.data.sessions.filter((s) => s.tool === tool);
257
267
  const live = list.filter((s) => s.live).length;
258
268
  const last = toolLastUsed(view.data, tool, now);
269
+ // Claude 한도 (#332): --statusline 이 저장한 값 중 아직 유효한 것. 한도가 있으면 쉬는 Claude 도 숨기지 않는다.
270
+ const limits = tool === 'claude' ? freshLimits(view.data.limits, now) : null;
259
271
  return {
260
272
  tool,
261
273
  count: list.length,
@@ -263,7 +275,8 @@ export function toolStrip(view, W) {
263
275
  tok: list.reduce((a, s) => a + (s.tokens?.total ?? 0), 0),
264
276
  missing: view.data.tools?.tools?.[tool]?.state === 'missing',
265
277
  // 실행 중 세션이 있는 도구는 늘 보인다. 마지막 사용을 모르면(점검 전) 숨기지 않는다.
266
- idle: view.hideIdleTools !== false && !live && last != null && now - last >= IDLE_TOOL_MS,
278
+ idle: view.hideIdleTools !== false && !live && !limits && last != null && now - last >= IDLE_TOOL_MS,
279
+ limits,
267
280
  };
268
281
  });
269
282
  const visible = all.filter((p) => !p.idle);
@@ -281,7 +294,8 @@ export function toolStrip(view, W) {
281
294
  };
282
295
  const fits = (x) => segsWidth(x) <= W;
283
296
  let segs = null;
284
- for (const level of [0, 2, 3]) {
297
+ // 한도가 있을 때만 토큰 수를 먼저 빼는 단계(1)를 넣는다. 없으면 예전과 같다.
298
+ for (const level of all.some((p) => p.limits) ? [0, 1, 2, 3] : [0, 2, 3]) {
285
299
  for (const note of notes) {
286
300
  const s = build(parts, level, note);
287
301
  if (fits(s)) {
package/src/zstd.mjs ADDED
@@ -0,0 +1,51 @@
1
+ // Codex 압축 rollout(rollout-*.jsonl.zst) 을 읽는 데 쓰는 이름 규칙과 zstd 해제 (#330).
2
+ //
3
+ // Codex CLI(openai/codex codex-rs/rollout/src/compression.rs, 2026-11-27 확인)는 시작할 때(그리고 RPC 로) 백그라운드 작업을
4
+ // 띄워 sessions/ 와 archived_sessions/ 아래의 '식은' rollout 을 zstd(레벨 3)로 압축해 같은 이름 + ".zst" 로 바꿔 둔다.
5
+ // - 식은 기록: 수정 시각이 7일(MIN_ROLLOUT_AGE) 넘게 지난 rollout-*.jsonl. 압축 중에 바뀌면 건너뛴다.
6
+ // - 실행 표지 파일(rollout-compression.lock)로 너무 잦은 실행을 막고(6시간), 한 번에 최대 5시간·동시 2개까지 돈다.
7
+ // - 압축본에는 원본의 권한과 수정 시각을 그대로 옮긴 뒤 원본 .jsonl 을 지운다. 그래서 .zst 의 수정 시각도 7일 넘게 지난 값이다.
8
+ // - 세션을 다시 이어 쓰면(resume) .jsonl 로 풀어 놓고(materialize) .zst 를 지운다. 둘이 함께 있으면 Codex 도 .jsonl 을 읽는다.
9
+ // 그래서 압축 기록은 끝난 기록이다. 실행 중 판정에는 쓰지 않고, 한 번 다 읽으면 바뀔 때(크기·수정 시각)까지 다시 풀지 않는다.
10
+ //
11
+ // node:zlib 의 zstd(zstdDecompressSync 등)는 Node v23.8.0 과 v22.15.0 에 들어왔다 (nodejs.org/api/zlib.html, Stability 1 Experimental).
12
+ // 그보다 낮은 Node(예: 22.13)에서는 압축 기록을 건너뛰고 --doctor 에 알린다.
13
+ import * as zlib from 'node:zlib';
14
+ import { readFileSync } from 'node:fs';
15
+ import { debugIo } from './log.mjs';
16
+
17
+ export const ZST_SUFFIX = '.zst';
18
+ // 풀었을 때의 크기 상한. 넘는 기록은 건너뛴다 (한 번에 메모리에 올려 읽으므로).
19
+ export const ZST_MAX_BYTES = 256 * 1024 * 1024;
20
+
21
+ let decompress = typeof zlib.zstdDecompressSync === 'function' ? zlib.zstdDecompressSync : null;
22
+
23
+ export const zstdAvailable = () => typeof decompress === 'function';
24
+ export const isZst = (p) => String(p).endsWith('.jsonl' + ZST_SUFFIX);
25
+ // rollout-*.jsonl 또는 rollout-*.jsonl.zst 이름인지.
26
+ export const isRolloutName = (n) => n.startsWith('rollout-') && (n.endsWith('.jsonl') || n.endsWith('.jsonl' + ZST_SUFFIX));
27
+ // 압축 이름이면 .zst 를 뗀 이름 (같은 기록을 하나로 셀 때 쓰는 키).
28
+ export const plainName = (n) => (isZst(n) ? n.slice(0, -ZST_SUFFIX.length) : n);
29
+
30
+ // 한 폴더의 이름 목록에서 rollout 만 고르고, 같은 이름의 .jsonl 이 있는 .jsonl.zst 는 뺀다 (살아 있는 .jsonl 쪽을 읽는다).
31
+ export function rolloutNames(names) {
32
+ const set = new Set(names);
33
+ return names.filter((n) => isRolloutName(n) && !(isZst(n) && set.has(plainName(n))));
34
+ }
35
+
36
+ // 압축 기록을 풀어 Buffer 로. zstd 가 없으면 { skip: 'nozstd' }, 상한을 넘으면 { skip: 'toolarge' }, 읽기·해제 실패는 { skip: 'error' }.
37
+ export function inflateZst(path, max = ZST_MAX_BYTES) {
38
+ if (!zstdAvailable()) return { skip: 'nozstd' };
39
+ try {
40
+ return { data: decompress(readFileSync(path), { maxOutputLength: max }) };
41
+ } catch (e) {
42
+ debugIo('zstd', 'rollout decompress failed', e, path);
43
+ return { skip: e?.code === 'ERR_BUFFER_TOO_LARGE' || e instanceof RangeError ? 'toolarge' : 'error' };
44
+ }
45
+ }
46
+
47
+ // 테스트용: zstd 해제 함수를 바꿔 끼운다 (null 이면 zstd 없는 Node 처럼).
48
+ export const _test = {
49
+ setDecompress: (fn) => (decompress = fn),
50
+ reset: () => (decompress = typeof zlib.zstdDecompressSync === 'function' ? zlib.zstdDecompressSync : null),
51
+ };