@sejuneoh/aitop 0.41.1 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![npm](https://img.shields.io/npm/v/@sejuneoh/aitop)](https://www.npmjs.com/package/@sejuneoh/aitop)
4
4
  [![license: MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/SejuneOh/aitop/blob/main/LICENSE)
5
5
 
6
- **`top` for your AI coding agents.** One live terminal screen for every Claude Code, Codex CLI and Antigravity CLI session on your machine. No hooks, read-only.
6
+ **`top` for your AI coding agents.** One live terminal screen for every Claude Code, Codex CLI, Antigravity and Claude Desktop Cowork session on your machine (Gemini CLI by process). No setup step, no hooks, no telemetry.
7
7
 
8
8
  > `npx @sejuneoh/aitop`
9
9
  >
@@ -20,9 +20,12 @@
20
20
  - **Know which session is which.**
21
21
  - Every row shows the session name (your `/rename` or the tool's title).
22
22
  - `y` copies a resume command, and `--report sessions` prints yesterday's sessions with cost for your standup.
23
- - **No hooks, nothing sent.**
24
- - Claude Code, Codex CLI and Antigravity CLI side by side, from [several history folders](#several-claude-or-codex-profiles) (`~/.claude`, `~/.claude-work`, ...).
25
- - aitop only reads the logs they already write. It changes no settings and needs no network, ports or dependencies. The one exception is the opt-in [`--remote`](#remote-hosts-and-wsl-distros), which runs your own `ssh` or `wsl.exe`.
23
+ - **No setup, no hooks, no telemetry.**
24
+ - aitop only reads the logs the tools already write. It changes no settings and needs no network, ports or dependencies. The one exception is the opt-in [`--remote`](#remote-hosts-and-wsl-distros), which runs your own `ssh` or `wsl.exe`.
25
+ - **Several vendors on one screen.**
26
+ - Claude Code, Codex CLI, Antigravity (CLI and app), Gemini CLI and [Claude Desktop Cowork](#claude-desktop-cowork) side by side, from [several history folders](#several-claude-or-codex-profiles) (`~/.claude`, `~/.claude-work`, ...).
27
+ - The tools now have their own session screens too (Claude Code `claude agents`, Codex `codex agents`, Antigravity `/usage`), each showing only its own sessions.
28
+ - [`--remote`](#remote-hosts-and-wsl-distros) adds SSH hosts and WSL distros to the same screen, with no daemon.
26
29
 
27
30
  **Contents**
28
31
 
@@ -31,7 +34,7 @@
31
34
  - [Subagents](#subagents) · [Daily and monthly reports](#daily-and-monthly-reports) · [Session report](#session-report) · [Call tree](#call-tree)
32
35
  - [Notifications](#notifications) · [tmux status line](#tmux-status-line) · [Several Claude or Codex profiles](#several-claude-or-codex-profiles)
33
36
  - [Resume a session elsewhere](#resume-a-session-elsewhere) · [Remote hosts and WSL distros](#remote-hosts-and-wsl-distros) · [JSON output](#json-output) · [Language](#language)
34
- - [How it differs from similar tools](#how-it-differs-from-similar-tools) · [Install](#install) · [License](#license)
37
+ - [What aitop can't see](#what-aitop-cant-see) · [How it differs from similar tools](#how-it-differs-from-similar-tools) · [Install](#install) · [License](#license)
35
38
 
36
39
  ## Quick start
37
40
 
@@ -241,6 +244,8 @@ Every session that used tokens in the period, highest cost first, for standups.
241
244
  - Start and end of activity within the period.
242
245
  - Time the agent waited for you (see below).
243
246
  - Tokens.
247
+ - Cache: prompt cache hit rate, cache reads / (input + cache reads + cache writes), subagents included (`-` when unknown). The detail panel shows the same number next to the token total, and `--json` has `cacheHitRate` (0 to 1, `null` when unknown) per session in both `aitop --json` and the session report.
248
+ - Codex does not log cache write tokens (always 0), so its rate means slightly more than Claude's.
244
249
  - Cost (API list price). Unpriced models are left out, not guessed, and `--json` marks them with `unpriced`.
245
250
  - Files changed (`-` when unknown, always for agy).
246
251
  - Claude subagents are counted in their parent session.
@@ -377,6 +382,7 @@ set -g status-interval 15
377
382
  - The Claude Code sessions stopped by an API error (`stop 1`, read live).
378
383
  - The number of sessions running (`run 3`).
379
384
  - Spend over the last hour.
385
+ - Claude usage limits at the end (`5h23% 7d41%`) once [`--statusline`](#claude-usage-limits) has saved them.
380
386
  - `aitop idle` when there is nothing to show (`idle` or `-` in a very narrow `--line-width`), so an empty line never looks like a broken setup.
381
387
 
382
388
  **Options**
@@ -409,6 +415,42 @@ set -g status-interval 15
409
415
 
410
416
  </details>
411
417
 
418
+ ## Claude usage limits
419
+
420
+ See how much of your Claude 5-hour and 7-day limits you have used, without any network call.
421
+
422
+ Claude Code sends these numbers only to its status line command, and does not write them to its logs. So add `aitop --statusline` to the status line yourself, in `~/.claude/settings.json`:
423
+
424
+ ```json
425
+ { "statusLine": { "type": "command", "command": "aitop --statusline" } }
426
+ ```
427
+
428
+ That prints a short line such as `5h 24% (2h10m) | 7d 41%`. To keep the status line you already have, put its command after `--`:
429
+
430
+ ```json
431
+ { "statusLine": { "type": "command", "command": "aitop --statusline -- npx -y ccstatusline" } }
432
+ ```
433
+
434
+ - aitop passes the same input to that command and prints its output and exit code as they are (2-second limit).
435
+ - The words after `--` run as an argument list, without a shell. A single argument with spaces (`aitop --statusline -- "my-status --short"`) runs through the shell (`/bin/sh`, or `cmd.exe` on Windows). On Windows, a command it cannot start directly (such as `npx.cmd`) is retried through `cmd.exe`.
436
+ - So a single path with spaces is read as a shell string: quote it inside, as in `aitop --statusline -- "'/opt/my tools/status'"` (or `"\"C:\Program Files\st\st.exe\""` on Windows).
437
+ - When the command runs over 2 seconds, or aitop itself is stopped, the command is stopped with everything it started (its process group, or `taskkill /T` on Windows). Output over 64 KB is cut.
438
+ - The command runs in its own session with no controlling terminal, so a script that reads `/dev/tty` (`tput cols`, `stty size </dev/tty`) may print something else. Read `COLUMNS` and other environment variables instead.
439
+
440
+ **Where it shows**
441
+
442
+ - The header, next to `claude`: `5h 23% · 7d 41%`. 80% and over in the caution color, 95% and over in the warning color. Folded away first on a narrow screen.
443
+ - `--json`: `limits.claude` (below), `--line`: `5h23% 7d41%` at the end.
444
+ - `--doctor` and the `?` help: whether the status line is connected and when it last saved.
445
+
446
+ **What it saves**
447
+
448
+ - Only `rate_limits.five_hour`, `seven_day` and `spend_limit`: the used percentage and reset time. Model, folders, session id and cost are not saved.
449
+ - The file is `claude-limits.json` in aitop's cache folder (next to `summary.json`, mode 0600). It is replaced on each change, never sent anywhere.
450
+ - A window is hidden after its reset time, and everything is hidden when nothing was saved for 7 days.
451
+ - With several Claude config folders or accounts, the one that saved last is shown. Limits on [`--remote`](#remote-hosts-and-wsl-distros) hosts are not merged in.
452
+ - Values come only on claude.ai Pro, Max and Ultra plans (or behind a Claude apps gateway with a spend limit), and only after the first reply in a session. Before that, the file is left as it was.
453
+
412
454
  ## Several Claude or Codex profiles
413
455
 
414
456
  aitop reads `~/.claude` and `~/.codex` by default. List more profiles to read them too.
@@ -590,6 +632,7 @@ See sessions on machines you manage (a VM, a dev server, another WSL distro) on
590
632
  - For scripts, use `phaseKind`, a stable state name: `think`, `write`, `tool`, `team`, `waiting`, `idle`, `stopped`, `done`, `ended` (or `null`).
591
633
  - `stopReason` says why a session is `stopped`: `{ "kind": "auth" }` login needed, `network` connection lost, `api` any other API error. `null` otherwise.
592
634
  - `schema` (top level) is the JSON shape version, now `1`. It goes up only when an existing field changes meaning or shape.
635
+ - `limits.claude`: Claude usage limits saved by [`--statusline`](#claude-usage-limits), `{ fiveHour: { usedPercent, resetsAt }, sevenDay, spend?, at }` with ISO times, or `null`. `--doctor --json` has `limits: { connected, at, file, fiveHour, sevenDay }`.
593
636
  - With [`--remote`](#remote-hosts-and-wsl-distros): each session has `host` (`null` for local) and `remoteId` (its id on that host; `id` is `<host>:<id>`), and `remotes` lists each remote as `{ name, kind, ok, error, version, schema, at }` (`[]` when off). `usage` stays local.
594
637
 
595
638
  <details>
@@ -636,25 +679,28 @@ The UI follows your locale: English by default, Korean when the locale starts wi
636
679
 
637
680
  </details>
638
681
 
682
+ ## What aitop can't see
683
+
684
+ - Sessions that run in the cloud or on another host (Claude Code on the web/`--cloud`, Cowork cloud tasks, Codex cloud tasks, Antigravity `--remote-agent`, SSH hosts) leave no history on this machine, so aitop can't show them.
685
+ - SSH hosts you can reach show up with [`--remote`](#remote-hosts-and-wsl-distros), if aitop is installed there.
686
+ - Remote Control sessions run locally and do show up.
687
+
639
688
  ## How it differs from similar tools
640
689
 
641
- - [ccusage](https://github.com/ryoppippi/ccusage)
642
- - Reports token usage and cost from local logs (daily, monthly, session, 5-hour blocks).
643
- - aitop is a live session monitor first, with smaller cost reports on the side.
644
- - [abtop](https://github.com/graykode/abtop)
645
- - A Rust live dashboard for Claude Code, Codex CLI and OpenCode, with rate limits, ports and keys to kill sessions.
646
- - aitop installs with npm, also covers Antigravity, and only watches.
647
- - [claude-code-monitor](https://github.com/onikan27/claude-code-monitor)
648
- - Watches Claude Code on macOS through hooks it adds to `~/.claude/settings.json`, with a phone web view.
649
- - aitop adds no hooks and only reads existing logs, on Linux, macOS, WSL and Windows.
650
- - [Agents Stack](https://marketplace.visualstudio.com/items?itemName=MykD.agents-stack)
651
- - A VS Code extension for Claude Code, Antigravity, Codex and Gemini CLI.
652
- - It adds hooks to each agent's config. Antigravity has no hook for approval waits, so those do not show.
653
- - aitop runs in any terminal, adds no hooks and shows Antigravity sessions waiting for approval.
690
+ | Tool | What it is | Agents | Setup |
691
+ |---|---|---|---|
692
+ | [ccusage](https://github.com/ryoppippi/ccusage) (★19.6k) | Cost reports from local logs | Claude Code and others | npm. Since v20.1.0 (2026-11-23) sends telemetry once a day by default |
693
+ | [abtop](https://github.com/graykode/abtop) (★3.9k) | Rust live dashboard | Claude Code, Codex CLI, OpenCode | Rate limits need a hook it installs |
694
+ | [agent-deck](https://github.com/asheshgoplani/agent-deck) | tmux session manager, remote and web UI | Claude Code, Codex, Gemini, Antigravity | Starts and manages the sessions itself |
695
+ | [claude-code-trace](https://github.com/delexw/claude-code-trace) | History viewer with a call tree | Claude Code, plus Antigravity and Codex plugins | Separate app |
696
+ | Built-in screens | `claude agents`, `codex agents`, Antigravity `/usage` | Their own tool only | None |
697
+ | aitop | Live monitor of local logs, with cost reports | Claude Code, Codex, Antigravity, Gemini CLI (process), Cowork | None: no hooks, no telemetry |
698
+
699
+ As of 2026-11-27.
654
700
 
655
701
  ## Install
656
702
 
657
- Requires Node.js 22+ on Linux, macOS, WSL or Windows.
703
+ Requires Node.js 22+ on Linux, macOS, WSL or Windows. Antigravity details and Codex logs compressed after 7 idle days (`rollout-*.jsonl.zst`) need Node 22.15+; on older Node they are skipped and `--doctor` says how many.
658
704
 
659
705
  > `npx @sejuneoh/aitop`
660
706
  >
package/bin/aitop.mjs CHANGED
@@ -1,17 +1,28 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from 'node:fs';
3
- import { budgetDayOption, configJson, configPath, configText, parseRemote, readConfigFile, remoteOption, resolveConfig } from '../src/config.mjs';
4
- import { langOption, pickLang, setLang, t } from '../src/i18n.mjs';
5
- import { notifyOptions } from '../src/notify.mjs';
6
- import { lineOption } from '../src/line.mjs';
7
- import { reportOption } from '../src/report.mjs';
8
- import { suggest } from '../src/suggest.mjs';
9
- import { mask, setAmbiguous, stripControl } from '../src/text.mjs';
2
+ // --statusline (#332): Claude Code 상태줄이 응답마다 부르는 경로다. 설정·i18n·화면 모듈을 불러오기 전에 갈라 빨리 끝낸다.
3
+ // `--` 앞에는 --statusline 만 둔다 (다른 옵션은 statusline.mjs 가 사용법 오류로 알린다).
4
+ const rawArgs = process.argv.slice(2);
5
+ const slAt = rawArgs.indexOf('--statusline');
6
+ const dashAt = rawArgs.indexOf('--');
7
+ if (slAt >= 0 && (dashAt < 0 || slAt < dashAt)) {
8
+ const { statusline } = await import('../src/statusline.mjs');
9
+ process.stdout.on('error', () => process.exit(0));
10
+ process.exit(await statusline(rawArgs.filter((_, i) => i !== slAt)));
11
+ }
12
+
13
+ const { readFileSync } = await import('node:fs');
14
+ const { budgetDayOption, configJson, configPath, configText, parseRemote, readConfigFile, remoteOption, resolveConfig } = await import('../src/config.mjs');
15
+ const { langOption, pickLang, setLang, t } = await import('../src/i18n.mjs');
16
+ const { notifyOptions } = await import('../src/notify.mjs');
17
+ const { lineOption } = await import('../src/line.mjs');
18
+ const { reportOption } = await import('../src/report.mjs');
19
+ const { suggest } = await import('../src/suggest.mjs');
20
+ const { mask, setAmbiguous, stripControl } = await import('../src/text.mjs');
10
21
 
11
22
  const KNOWN = new Set(['-h', '--help', '-v', '--version', '--once', '--all', '--json', '--doctor', '--bell', '--show-requests', '--print-config', '--no-bell', '--no-all', '--no-show-requests', '--debug', '--no-debug', '--color-blind', '--no-color-blind']);
12
23
  const THEMES = ['light', 'dark'];
13
24
  // 잘못 친 옵션에 제안할 후보. KNOWN 의 긴 옵션과, 다른 모듈이 먼저 꺼내는 값 옵션을 합친다.
14
- const OPTIONS = [...[...KNOWN].filter((o) => o.startsWith('--')), '--theme', '--lang', '--notify', '--no-notify', '--on-waiting', '--no-on-waiting', '--budget-day', '--no-budget-day', '--line', '--line-width', '--report', '--by', '--days', '--months', '--since', '--plan', '--md', '--show-prompts', '--remote', '--no-remote'];
25
+ const OPTIONS = [...[...KNOWN].filter((o) => o.startsWith('--')), '--theme', '--lang', '--notify', '--no-notify', '--on-waiting', '--no-on-waiting', '--budget-day', '--no-budget-day', '--line', '--line-width', '--report', '--by', '--days', '--months', '--since', '--plan', '--md', '--show-prompts', '--remote', '--no-remote', '--statusline'];
15
26
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
16
27
 
17
28
  // 언어는 다른 옵션의 오류 문구보다 먼저 정한다: --lang > AITOP_LANG > 설정 파일 lang > LC_ALL > LC_MESSAGES > LANG.
@@ -276,7 +287,8 @@ if (args.has('--doctor')) {
276
287
  // 진단은 한 번 돌고 끝나므로 Windows 의 첫 PowerShell CIM 호출을 더 오래 기다린다 (procs.mjs WIN_DOCTOR_TIMEOUT_MS).
277
288
  const { setFirstScanTimeout, WIN_DOCTOR_TIMEOUT_MS } = await import('../src/procs.mjs');
278
289
  setFirstScanTimeout(WIN_DOCTOR_TIMEOUT_MS);
279
- const result = { ...checkTools(), config: configJson(config), log: { on: log.on, path: log.path }, remotes: (opt.remotes ?? []).map((n) => parseRemote(n)?.name).filter(Boolean) };
290
+ const { limitsCheck } = await import('../src/limits.mjs');
291
+ const result = { ...checkTools(), config: configJson(config), log: { on: log.on, path: log.path }, remotes: (opt.remotes ?? []).map((n) => parseRemote(n)?.name).filter(Boolean), limits: limitsCheck() };
280
292
  await printAndExit(args.has('--json') ? JSON.stringify({ version: VERSION, ...result, tools: toolsJson(result.tools) }, null, 2) : doctorText(result, VERSION));
281
293
  }
282
294
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.41.1",
3
+ "version": "0.42.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/cache.mjs CHANGED
@@ -8,6 +8,7 @@ import { appDir } from './paths.mjs';
8
8
  import { createHash } from 'node:crypto';
9
9
  import { PRICE_TAG } from './pricing.mjs';
10
10
  import { debug, debugIo } from './log.mjs';
11
+ import { isZst } from './zstd.mjs';
11
12
 
12
13
  // 캐시 형식이 바뀌면 VERSION 을, 가격표가 바뀌면 PRICE_TAG 가 폴더 이름을 바꿔서 예전 캐시를 버린다.
13
14
  // 14: 장부의 하루 합계에 모델별 몫(models)을 더하고, 날짜를 10일이 아니라 30일 남긴다 (#128).
@@ -36,7 +37,8 @@ function removeOldDirs() {
36
37
  // summary.json(--line 용 요약, summary.mjs)은 버전 폴더 밖에 두고 여기서 지우지 않는다. 남은 임시 파일은 일주일 뒤 지운다.
37
38
  // monthly.json(월별 보관함, monthly.mjs)과 깨져서 옆으로 옮긴 monthly.json.bad-* 도 사용자 기록이라 지우지 않는다.
38
39
  // sdk-parents.json(claude -p 실행의 기억된 부모)도 형식 버전과 상관없이 남긴다.
39
- if (d === NAME || d === 'summary.json' || d === 'monthly.json' || d === PARENTS_FILE || d.startsWith('monthly.json.bad-')) continue;
40
+ // claude-limits.json(--statusline 이 저장한 Claude 한도, limits.mjs)도 남긴다. 오래된 값은 읽는 쪽이 숨긴다.
41
+ if (d === NAME || d === 'summary.json' || d === 'claude-limits.json' || d === 'monthly.json' || d === PARENTS_FILE || d.startsWith('monthly.json.bad-')) continue;
40
42
  const p = join(ROOT, d);
41
43
  // 이 버전보다 낮은 형식(v2, v6-… 등)은 더 이상 어떤 버전도 쓰지 않으므로 바로 지운다.
42
44
  const ver = Number(/^v(\d+)(?:-|$)/.exec(d)?.[1]);
@@ -51,11 +53,13 @@ function removeOldDirs() {
51
53
  const keyOf = (path, kind) => createHash('sha1').update(`${kind}\0${path}`).digest('hex');
52
54
 
53
55
  // 파일이 바뀌지 않고 뒤에만 붙었을 때(크기가 같거나 커졌고 inode 가 같을 때)만 캐시를 쓴다.
56
+ // Codex 압축 기록(.jsonl.zst)은 뒤에 붙지 않으므로 크기와 수정 시각까지 같을 때만 쓴다 (zstd.mjs).
54
57
  export function loadCache(path, kind = '') {
55
58
  try {
56
59
  const c = JSON.parse(readFileSync(join(DIR, keyOf(path, kind) + '.json'), 'utf8'));
57
60
  const st = statSync(path);
58
61
  if (c.path !== path || c.ino !== st.ino || st.size < c.offset) return null;
62
+ if (isZst(path) && (c.size !== st.size || c.mtime !== st.mtimeMs)) return null;
59
63
  return c;
60
64
  } catch (e) {
61
65
  debugIo('cache', 'cache load failed', e);
@@ -84,7 +88,9 @@ export function flushCache() {
84
88
  const data = build();
85
89
  if (!data) continue;
86
90
  const file = join(DIR, key + '.json');
87
- writeFileSync(file + '.tmp', JSON.stringify({ ...data, path, ino: statSync(path).ino }), { mode: 0o600 });
91
+ const st = statSync(path);
92
+ // 압축 기록은 크기·수정 시각도 남겨 바뀌었는지 본다 (loadCache).
93
+ writeFileSync(file + '.tmp', JSON.stringify({ ...data, path, ino: st.ino, ...(isZst(path) ? { size: st.size, mtime: st.mtimeMs } : {}) }), { mode: 0o600 });
88
94
  try {
89
95
  renameSync(file + '.tmp', file, { retries });
90
96
  } catch (e) {
package/src/collect.mjs CHANGED
@@ -5,6 +5,7 @@ import { collectAgy } from './sources/antigravity.mjs';
5
5
  import { collectCowork } from './sources/cowork.mjs';
6
6
  import { collectLedger } from './sources/claude-ledger.mjs';
7
7
  import { createBudget } from './tail.mjs';
8
+ import { loadLimits } from './limits.mjs';
8
9
 
9
10
  const RANK = { waiting: 0, busy: 1, shell: 2, live: 3, idle: 4, ended: 5 };
10
11
 
@@ -45,6 +46,8 @@ export function collect({ budgetBytes = Infinity, budgetMs = Infinity, ...opts }
45
46
  errors.push(`usage: ${err.message}`);
46
47
  }
47
48
  sessions.sort(bySession);
49
+ // --statusline 이 저장한 Claude 한도 (#332). 작은 파일 하나라 갱신마다 읽는다. 만료 검사는 보이는 쪽(freshLimits)이 한다.
50
+ const limits = loadLimits();
48
51
  // sessionsMore: 세션 기록(장부 빼고)만 덜 읽었는지. 시작할 때의 준비 완료는 이 값으로 정한다 (7일 장부는 헤더 진행 줄로만 보인다).
49
- return { sessions, usage, errors, at: Date.now(), more: Object.values(budgets).some((b) => b.exhausted), sessionsMore: Object.entries(budgets).some(([name, b]) => name !== 'usage' && b.exhausted) };
52
+ return { sessions, usage, limits, errors, at: Date.now(), more: Object.values(budgets).some((b) => b.exhausted), sessionsMore: Object.entries(budgets).some(([name, b]) => name !== 'usage' && b.exhausted) };
50
53
  }
package/src/doctor.mjs CHANGED
@@ -14,6 +14,7 @@ import { tildeIn } from './paths.mjs';
14
14
  import { busProblem, findNotifier, isWsl } from './notify.mjs';
15
15
  import { getLang, t as tr } from './i18n.mjs';
16
16
  import { candidateDirs, claudeDirs, codexHomes } from './sources/dirs.mjs';
17
+ import { inflateZst, isRolloutName, isZst, plainName, zstdAvailable } from './zstd.mjs';
17
18
 
18
19
  const UNIT = { s: '초', m: '분', h: '시간', d: '일' };
19
20
  const ago = (ms) => fmtAgo(ms).replace(/[smhd]$/, (u) => UNIT[u]);
@@ -54,6 +55,20 @@ function newest(files) {
54
55
 
55
56
  // 파일 첫 줄이 JSON 으로 읽히면 true, 아니면 false. 비어 있거나 첫 줄이 64KB 를 넘으면 판정하지 않는다(null).
56
57
  function firstLineIsJson(path) {
58
+ // Codex 압축 기록(.jsonl.zst)은 풀어서 본다. zstd 가 없거나 상한을 넘으면 판정하지 않는다.
59
+ if (isZst(path)) {
60
+ const got = inflateZst(path);
61
+ if (!got.data) return got.skip === 'error' ? false : null;
62
+ const text = got.data.subarray(0, 65536).toString('utf8');
63
+ const end = text.indexOf('\n');
64
+ if (!got.data.length || (end < 0 && got.data.length > 65536)) return null;
65
+ try {
66
+ JSON.parse(end < 0 ? text : text.slice(0, end));
67
+ return true;
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
57
72
  let fd;
58
73
  try {
59
74
  fd = openSync(path, 'r');
@@ -125,11 +140,16 @@ function gatherDirs(roots, list) {
125
140
  const found = dirs.some((d) => d.found);
126
141
  const files = [...byKey.values()];
127
142
  const last = found ? newest(files) : null;
128
- return { found, path: dirs[0]?.path ?? '', dirs, records: files.length, lastAt: last?.mtime ?? null, readable: last ? firstLineIsJson(last.path) : null };
143
+ return { found, path: dirs[0]?.path ?? '', dirs, files, records: files.length, lastAt: last?.mtime ?? null, readable: last ? firstLineIsJson(last.path) : null };
129
144
  }
130
145
 
131
146
  const claudeFiles = (dir) => walk(dir, 1, (n) => n.endsWith('.jsonl')).map((p) => ({ key: p.slice(dir.length), path: p }));
132
- const codexFiles = (dir) => walk(dir, 3, (n) => n.startsWith('rollout-') && n.endsWith('.jsonl')).map((p) => ({ key: basename(p), path: p }));
147
+ // Codex 는 압축 기록(rollout-*.jsonl.zst, zstd.mjs)도 기록으로 센다. 같은 이름의 .jsonl 이 있으면 .jsonl 하나만.
148
+ const codexFiles = (dir) => {
149
+ const paths = walk(dir, 3, isRolloutName);
150
+ const set = new Set(paths);
151
+ return paths.filter((p) => !(isZst(p) && set.has(plainName(p)))).map((p) => ({ key: plainName(basename(p)), path: p }));
152
+ };
133
153
 
134
154
  // 읽지 않는 폴더 중 기록이 있는 것 (dirs.mjs candidateDirs). 기록 수만 센다.
135
155
  function candidatesOf(paths, sub, list) {
@@ -149,12 +169,14 @@ function claude(cand) {
149
169
  return { tool: 'claude', state: 'ok', path: g.path, dirs: g.dirs, candidates, records: g.records, lastAt: g.lastAt, running, readable: g.readable, hint: null };
150
170
  }
151
171
 
172
+ // zstd 가 없는 Node(22.15 미만)에서는 압축 기록을 읽지 못하므로 그 수(zstUnread)를 남기고 안내한다.
152
173
  function codex(cand) {
153
174
  const g = gatherDirs(codexHomes().map((h) => join(h, 'sessions')), codexFiles);
154
175
  const running = canListProcesses() ? findProcesses(isCodex).length : null;
155
176
  const candidates = candidatesOf(cand, 'sessions', codexFiles);
156
177
  if (!g.found) return { tool: 'codex', state: 'missing', path: g.path, dirs: g.dirs, candidates, records: 0, lastAt: null, running, readable: null, hint: null };
157
- return { tool: 'codex', state: 'ok', path: g.path, dirs: g.dirs, candidates, records: g.records, lastAt: g.lastAt, running, readable: g.readable, hint: null };
178
+ const zstUnread = zstdAvailable() ? 0 : g.files.filter(isZst).length;
179
+ return { tool: 'codex', state: 'ok', path: g.path, dirs: g.dirs, candidates, records: g.records, lastAt: g.lastAt, running, readable: g.readable, ...(zstUnread ? { zstUnread } : {}), hint: null };
158
180
  }
159
181
 
160
182
  // Gemini 는 세션 기록 형식을 아직 모른다. 프로세스만 세고, 기록 폴더가 있으면 형식 확인용 키 이름을 남긴다.
@@ -244,6 +266,7 @@ export function hintOf(r, lang = 'ko') {
244
266
  if (r.tool === 'cowork') return r.readable === false ? tr('doctor.hint.coworkUnread', null, o) : null;
245
267
  if (r.state === 'missing') return r.tool === 'agy' ? tr('doctor.hint.agyMissing', null, o) : tr('doctor.hint.missing', { tool: r.tool }, o);
246
268
  if (r.tool === 'agy' && r.state === 'limited') return tr('doctor.hint.agyNode', { node: process.versions.node }, o);
269
+ if (r.tool === 'codex' && r.zstUnread) return tr('doctor.hint.codexZst', { n: r.zstUnread, node: process.versions.node }, o);
247
270
  return null;
248
271
  }
249
272
 
@@ -374,5 +397,14 @@ export function doctorText(result, version, now = Date.now(), lang = getLang())
374
397
  }
375
398
  // --remote(#308)로 정한 원격 목록. 점검은 접속하지 않는다 (네트워크를 쓰지 않음).
376
399
  if (result.remotes?.length) out.push('', tr('doctor.remotes', { mark: '○', list: result.remotes.join(', ') }, o));
400
+ // Claude 한도 (#332): aitop --statusline 이 저장한 파일이 있는지와 마지막 갱신. 없으면 넣는 방법을 알린다.
401
+ const lim = result.limits;
402
+ if (lim) {
403
+ const at = Date.parse(lim.at);
404
+ const pctOr = (p) => (p == null ? '-' : `${Math.round(p)}%`);
405
+ const tail = lim.fiveHour != null || lim.sevenDay != null ? tr('doctor.limitsNow', { five: pctOr(lim.fiveHour), week: pctOr(lim.sevenDay) }, o) : '';
406
+ if (lim.connected && Number.isFinite(at)) out.push('', tr('doctor.limitsOn', { ago: lang === 'ko' ? ago(now - at) : fmtAgo(now - at), tail }, o));
407
+ else out.push('', tr('doctor.limitsOff', null, o), ` → ${tr('doctor.limitsHint', null, o)}`);
408
+ }
377
409
  return stripControl(out.join('\n'));
378
410
  }
package/src/help.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  // 화면 모듈을 불러오지 않는다 (bin 이 색·테마를 정하기 전에 불러도 되게).
3
3
  // 화면 이름, 키 설명, 키 짧은 이름은 i18n.mjs 표에 있다. 표(VIEWS)에는 ko 값을 두고, 화면 안 도움말과 --help 는 지금 언어로 바꾼다.
4
4
  import { STRINGS, getLang, t } from './i18n.mjs';
5
+ import { fmtAgo } from './text.mjs';
5
6
 
6
7
  const ko = (key) => STRINGS.ko[key];
7
8
 
@@ -120,6 +121,7 @@ const OPTION_IDS = [
120
121
  ['--color-blind', 'hopt.colorBlind'],
121
122
  ['--debug', 'hopt.debug'],
122
123
  ['--line[=tmux]', 'hopt.line'],
124
+ ['--statusline', 'hopt.statusline'],
123
125
  ['--print-config', 'hopt.printConfig'],
124
126
  ['AITOP_AMBIGUOUS=wide', 'hopt.ambiguous'],
125
127
  ];
@@ -154,6 +156,10 @@ export function keysText(lang = getLang()) {
154
156
  return [`${t('help.keys', null, { lang })}: ${keysLine('table', lang)} · ${keysLine('common', lang)}`, ...['detail', 'files', 'diff', 'artifacts', 'artifact', 'filtered', 'search'].map((n) => ` ${title(n)}: ${keysLine(n, lang)}`)].join('\n');
155
157
  }
156
158
 
159
+ // 지난 시간 짧게: 한국어는 3분, 그 밖은 3m.
160
+ const KO_UNIT = { s: '초', m: '분', h: '시간', d: '일' };
161
+ const agoText = (ms, lang) => (lang === 'ko' ? fmtAgo(ms).replace(/[smhd]$/, (u) => KO_UNIT[u]) : fmtAgo(ms));
162
+
157
163
  // 지금 설정 값 한 줄 (예: 예산 $50 · 알림 켜짐 · 디버그 꺼짐). settings 가 없으면 null.
158
164
  export function settingsLine(s, lang = getLang()) {
159
165
  if (!s) return null;
@@ -162,5 +168,7 @@ export function settingsLine(s, lang = getLang()) {
162
168
  const usd = (x) => (Number.isInteger(x) ? `$${x}` : `$${x.toFixed(2)}`);
163
169
  // 알림이 켜져 있고 종류를 기본(waiting)과 다르게 정했으면 함께 보인다. 예: 알림 켜짐 (waiting,done)
164
170
  const kinds = s.notify && s.events && s.events.join(',') !== 'waiting' ? ` (${s.events.join(',')})` : '';
165
- return [t('set.budget', { v: s.budgetDay > 0 ? usd(s.budgetDay) : t('set.none', null, o) }, o), t('set.notify', { v: onOff(s.notify) + kinds }, o), ...(s.onWaiting ? [t('set.onWaiting', null, o)] : []), t('set.debug', { v: onOff(s.debug) }, o)].join(' · ');
171
+ // Claude 한도 (#332): 상태줄(aitop --statusline)이 저장한 적이 있으면 마지막 갱신, 없으면 연결 안 됨. limitsAt 을 줬을 때만 넣는다.
172
+ const lim = 'limitsAt' in s ? [t('set.limits', { v: Number.isFinite(s.limitsAt) ? t('set.limitsOn', { ago: agoText((s.now ?? Date.now()) - s.limitsAt, lang) }, o) : t('set.limitsOff', null, o) }, o)] : [];
173
+ return [t('set.budget', { v: s.budgetDay > 0 ? usd(s.budgetDay) : t('set.none', null, o) }, o), t('set.notify', { v: onOff(s.notify) + kinds }, o), ...(s.onWaiting ? [t('set.onWaiting', null, o)] : []), t('set.debug', { v: onOff(s.debug) }, o), ...lim].join(' · ');
166
174
  }
package/src/i18n.mjs CHANGED
@@ -66,6 +66,11 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
66
66
  --line=tmux 는 tmux 색 서식(#[fg=...])을 넣는다. --line-width <N> 폭 상한(기본 40, 넘으면 뒤 항목부터 빼고 대기 세션 이름은 대기 수보다 먼저 뺀다)
67
67
  캐시만 읽는다. 캐시가 없어 1.5초 안에 못 읽으면 ... 을 낸다. 작업 중 수와 Antigravity 의 대기 수는
68
68
  1분 안에 aitop 화면·--once·--json 이 남긴 요약이 있을 때만 보인다
69
+ Claude 한도(--statusline)가 저장돼 있으면 끝에 5h23% 7d41% 를 붙인다
70
+ aitop --statusline [-- <명령> [인자...]]
71
+ Claude Code 상태줄(settings.json 의 statusLine.command)에 넣는다. 입력 JSON 에서 5시간·7일 한도(%·초기화 시각)만
72
+ 캐시 폴더의 claude-limits.json 에 저장하고, 화면 헤더·--json·--line 이 보인다 (Pro·Max·Ultra 만 값이 온다)
73
+ -- 뒤 명령이 있으면 같은 입력을 넘겨 그 출력을 그대로 낸다 (2초 제한). 인자 하나에 공백이 있으면 셸로 실행한다
69
74
  aitop --json 세션 목록과 사용량 합계를 JSON 으로 한 번 출력한다 (--all 과 함께 쓸 수 있다)
70
75
  세션마다 resumeCmd 에 그 세션을 이어 여는 명령을 넣는다 (예: cd /repo && claude --resume <id>, 없으면 null)
71
76
  aitop --remote dev,me@vm2,wsl:Ubuntu-22.04 SSH 원격과 WSL 배포판의 세션을 함께 본다. 각 원격에서 aitop --json --no-remote 를
@@ -131,6 +136,12 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
131
136
  --line=tmux adds tmux colors (#[fg=...]). --line-width <N> sets the max width (default 40, drops items from the end, the waiting name before its count)
132
137
  Reads only the cache. With no cache it prints ... after 1.5 seconds. The running count and waiting Antigravity sessions
133
138
  show only when the live screen, --once or --json left a summary in the last minute
139
+ With Claude limits saved by --statusline, appends 5h23% 7d41% at the end
140
+ aitop --statusline [-- <command> [args...]]
141
+ for the Claude Code status line (statusLine.command in settings.json). Saves only the 5-hour and 7-day limits
142
+ (percent and reset time) from its JSON input to claude-limits.json in the cache folder, shown in the header, --json and --line
143
+ (values come only on Pro, Max and Ultra). With a command after --, passes it the same input and prints its output (2s limit).
144
+ A single argument with spaces runs through the shell
134
145
  aitop --json print the session list and usage totals as JSON once (works with --all)
135
146
  Each session has resumeCmd, the command that reopens it (e.g. cd /repo && claude --resume <id>, null if none)
136
147
  aitop --remote dev,me@vm2,wsl:Ubuntu-22.04 also show sessions on SSH hosts and WSL distros. Runs aitop --json --no-remote on each one
@@ -317,11 +328,12 @@ export const STRINGS = {
317
328
  'sessions.col.end': '끝',
318
329
  'sessions.col.waited': '기다림',
319
330
  'sessions.col.tokens': '토큰',
331
+ 'sessions.col.cache': '캐시',
320
332
  'sessions.col.cost': '비용',
321
333
  'sessions.col.files': '파일',
322
334
  'sessions.col.prompt': '첫 지시',
323
335
  'sessions.empty': '이 기간에 사용량이 있는 세션이 없습니다',
324
- 'sessions.noteBasis': '비용은 API 정가 환산이며 실제 청구액이 아닙니다. 시작·끝은 기간 안의 활동 시각, 파일은 고친 파일 수 (- 는 모름). 기다림은 응답을 끝낸 뒤 다음 입력·허락까지의 추정 (간격 하나당 2시간까지, 자리 비움과 구분하지 못함)',
336
+ 'sessions.noteBasis': '비용은 API 정가 환산이며 실제 청구액이 아닙니다. 시작·끝은 기간 안의 활동 시각, 파일은 고친 파일 수 (- 는 모름). 캐시는 프롬프트 캐시 적중률 (입력 중 캐시에서 읽은 몫). 기다림은 응답을 끝낸 뒤 다음 입력·허락까지의 추정 (간격 하나당 2시간까지, 자리 비움과 구분하지 못함)',
325
337
  'sessions.capped': '--since 는 장부가 남기는 {n}일 전까지만 볼 수 있어 {n}일 전으로 줄입니다',
326
338
  'trace.title': '호출 트리 · {name} · {id}',
327
339
  'trace.summary': '{span} · 지시 {prompts} · 도구 호출 {tools} (서브에이전트 {agents}) · 토큰 {tokens} · {cost}',
@@ -397,6 +409,7 @@ export const STRINGS = {
397
409
  'doctor.hint.agyMissing': 'agy 를 한 번 실행하면 생깁니다 (Gemini 탭에 보입니다)',
398
410
  'doctor.hint.gemini': '프로세스만 감지합니다 (세션·토큰은 아직 지원하지 않음)',
399
411
  'doctor.hint.agyNode': 'Node {node} 에서는 기록을 읽기 전용으로 열 수 없어 프로세스만 감지합니다 (Node 22.15 이상 필요)',
412
+ 'doctor.hint.codexZst': '압축 기록 {n}개 읽지 못함 (Node {node} 에 zstd 없음, Node 22.15 이상 필요)',
400
413
  'doctor.notifier': '✓ 알림 {kind} ({path}) · --notify 로 켬 (끝남·context 경고는 --notify=waiting,done,context)',
401
414
  'doctor.noNotifier': '○ 알림 {want} 없음 · --notify 를 켜도 알림을 건너뜀',
402
415
  'doctor.noNotifierWsl': '! 알림 powershell.exe·notify-send 없음 · --notify 를 켜도 알림을 건너뜀',
@@ -415,6 +428,10 @@ export const STRINGS = {
415
428
  'doctor.debugOff': '꺼짐',
416
429
  'doctor.debugTail': ' · --debug 로 켬',
417
430
  'doctor.remotes': '{mark} 원격 {list} (점검에서는 접속하지 않는다)',
431
+ 'doctor.limitsOn': '✓ Claude 한도 상태줄 연결됨 · 마지막 갱신 {ago} 전{tail}',
432
+ 'doctor.limitsOff': '○ Claude 한도 상태줄 연결 안 됨',
433
+ 'doctor.limitsHint': 'Claude Code settings.json 의 statusLine.command 에 aitop --statusline 을 넣으면 5시간·7일 한도가 보인다 (Pro·Max·Ultra, README)',
434
+ 'doctor.limitsNow': ' · 5시간 {five} · 7일 {week}',
418
435
 
419
436
  // 상태 문구 (phaseText 가 phase.msg ?? phase.kind 로 고른다). --json 의 phase 는 늘 이 한국어 표로 만든다.
420
437
  'phase.ended': '종료',
@@ -649,6 +666,7 @@ export const STRINGS = {
649
666
  'hopt.colorBlind': '적록 색약용 색 (대기·돈·경고를 노랑·파랑 계열로)',
650
667
  'hopt.debug': '디버그 로그를 남긴다',
651
668
  'hopt.line': '오늘 비용·대기·작업 중 수·시간당 지출 한 줄 (tmux 상태줄용)',
669
+ 'hopt.statusline': 'Claude Code 상태줄에 넣어 5시간·7일 한도를 저장',
652
670
  'hopt.printConfig': '설정 값과 출처, 설정 파일 위치',
653
671
  'hopt.ambiguous': '·→─● 를 2칸으로 그리는 터미널용 (1칸 기호로)',
654
672
  'set.budget': '예산 {v}',
@@ -656,6 +674,9 @@ export const STRINGS = {
656
674
  'set.notify': '알림 {v}',
657
675
  'set.onWaiting': '대기 명령 있음',
658
676
  'set.debug': '디버그 {v}',
677
+ 'set.limits': 'Claude 한도 {v}',
678
+ 'set.limitsOn': '상태줄 연결됨 ({ago} 전 갱신)',
679
+ 'set.limitsOff': '상태줄 연결 안 됨',
659
680
  'set.on': '켜짐',
660
681
  'set.off': '꺼짐',
661
682
 
@@ -721,6 +742,8 @@ export const STRINGS = {
721
742
  'detail.mainSub': '메인 {m} + 서브 {n}개 {s}',
722
743
  'detail.inOut': '입력 {i} · 출력 {o}',
723
744
  'detail.cache': '캐시 읽기 {r} · 쓰기 {w}',
745
+ 'detail.cacheHit': '캐시 적중 {r}',
746
+ 'detail.cacheHitShort': '적중 {r}',
724
747
  'detail.cost': '비용',
725
748
  'detail.context': '컨텍스트',
726
749
  'detail.apiLabel': 'API 환산',
@@ -867,11 +890,12 @@ export const STRINGS = {
867
890
  'sessions.col.end': 'End',
868
891
  'sessions.col.waited': 'Waited',
869
892
  'sessions.col.tokens': 'Tokens',
893
+ 'sessions.col.cache': 'Cache',
870
894
  'sessions.col.cost': 'Cost',
871
895
  'sessions.col.files': 'Files',
872
896
  'sessions.col.prompt': 'First prompt',
873
897
  'sessions.empty': 'No session used tokens in this period',
874
- 'sessions.noteBasis': 'Cost is the API list price, not your actual bill. Start and end are activity times within the period; Files is the number of files changed (- means unknown). Waited estimates the time from a finished reply to your next prompt or approval (up to 2 hours per gap; time away is counted too)',
898
+ 'sessions.noteBasis': 'Cost is the API list price, not your actual bill. Start and end are activity times within the period; Files is the number of files changed (- means unknown). Cache is the prompt cache hit rate (share of input read from cache). Waited estimates the time from a finished reply to your next prompt or approval (up to 2 hours per gap; time away is counted too)',
875
899
  'sessions.capped': '--since is limited to {n} days back, which the ledger keeps, using {n} days',
876
900
  'trace.title': 'Call tree · {name} · {id}',
877
901
  'trace.summary': '{span} · prompts {prompts} · tool calls {tools} (subagents {agents}) · tokens {tokens} · {cost}',
@@ -947,6 +971,7 @@ export const STRINGS = {
947
971
  'doctor.hint.agyMissing': 'created after you run agy once (shown in the Gemini tab)',
948
972
  'doctor.hint.gemini': 'detects processes only (sessions and tokens not supported yet)',
949
973
  'doctor.hint.agyNode': 'Node {node} cannot open the logs read-only, so only processes are detected (needs Node 22.15 or later)',
974
+ 'doctor.hint.codexZst': { one: '{n} compressed log not read (Node {node} has no zstd, needs Node 22.15 or later)', other: '{n} compressed logs not read (Node {node} has no zstd, needs Node 22.15 or later)' },
950
975
  'doctor.notifier': '✓ notify {kind} ({path}) · turn on with --notify (done and context alerts: --notify=waiting,done,context)',
951
976
  'doctor.noNotifier': '○ notify {want} not found · --notify will skip notifications',
952
977
  'doctor.noNotifierWsl': '! notify powershell.exe and notify-send not found · --notify will skip notifications',
@@ -965,6 +990,10 @@ export const STRINGS = {
965
990
  'doctor.debugOff': 'off',
966
991
  'doctor.debugTail': ' · turn on with --debug',
967
992
  'doctor.remotes': '{mark} remote {list} (not contacted by the check)',
993
+ 'doctor.limitsOn': '✓ Claude limits status line connected · last update {ago} ago{tail}',
994
+ 'doctor.limitsOff': '○ Claude limits status line not connected',
995
+ 'doctor.limitsHint': 'put aitop --statusline in statusLine.command of Claude Code settings.json to see 5-hour and 7-day limits (Pro, Max, Ultra; see README)',
996
+ 'doctor.limitsNow': ' · 5h {five} · 7d {week}',
968
997
 
969
998
  'phase.ended': 'Ended',
970
999
  'phase.done': 'Done',
@@ -1189,6 +1218,7 @@ export const STRINGS = {
1189
1218
  'hopt.colorBlind': 'Red-green color blind palette',
1190
1219
  'hopt.debug': 'Write a debug log',
1191
1220
  'hopt.line': 'One line for the tmux status bar',
1221
+ 'hopt.statusline': 'In the Claude Code status line, saves 5-hour and 7-day limits',
1192
1222
  'hopt.printConfig': 'Settings, sources, config path',
1193
1223
  'hopt.ambiguous': 'For 2 column ·→─● terminals',
1194
1224
  'set.budget': 'budget {v}',
@@ -1196,6 +1226,9 @@ export const STRINGS = {
1196
1226
  'set.notify': 'notify {v}',
1197
1227
  'set.onWaiting': 'on-waiting set',
1198
1228
  'set.debug': 'debug {v}',
1229
+ 'set.limits': 'Claude limits {v}',
1230
+ 'set.limitsOn': 'status line connected (updated {ago} ago)',
1231
+ 'set.limitsOff': 'status line not connected',
1199
1232
  'set.on': 'on',
1200
1233
  'set.off': 'off',
1201
1234
 
@@ -1260,6 +1293,8 @@ export const STRINGS = {
1260
1293
  'detail.mainSub': { one: 'main {m} + {n} subagent {s}', other: 'main {m} + {n} subagents {s}' },
1261
1294
  'detail.inOut': 'in {i} · out {o}',
1262
1295
  'detail.cache': 'cache read {r} · write {w}',
1296
+ 'detail.cacheHit': 'cache hit {r}',
1297
+ 'detail.cacheHitShort': 'hit {r}',
1263
1298
  'detail.cost': 'Cost',
1264
1299
  'detail.context': 'Context',
1265
1300
  'detail.apiLabel': 'API cost',
package/src/json.mjs CHANGED
@@ -2,8 +2,9 @@ import { projectBudget } from './budget.mjs';
2
2
  import { toolsJson } from './doctor.mjs';
3
3
  import { phaseText } from './i18n.mjs';
4
4
  import { resumeCmd } from './resume.mjs';
5
- import { memberStalled } from './sources/common.mjs';
5
+ import { cacheHitRate, hitJson, memberStalled } from './sources/common.mjs';
6
6
  import { artifactLink } from './sources/artifacts.mjs';
7
+ import { freshLimits } from './limits.mjs';
7
8
 
8
9
  // aitop --json 출력. 다른 스크립트나 AI 가 읽기 쉬운 모양으로 세션 목록과 사용량 합계를 담는다.
9
10
  // 텍스트는 수집 단계에서 이미 비밀값 가림이 적용돼 있다.
@@ -31,6 +32,15 @@ const koPhase = (p) => (p?.kind ? phaseText(p, { lang: 'ko' }) : null);
31
32
  export const SCHEMA = 1;
32
33
  const remoteOf = (r) => ({ name: r.name, kind: r.kind, ok: Boolean(r.ok), error: r.error ?? null, version: r.version ?? null, schema: r.schema ?? null, at: iso(r.at) });
33
34
 
35
+ // Claude 한도 (#332): --statusline 이 저장한 값 중 아직 유효한 창만. 값이 없거나 오래됐으면 null.
36
+ // usedPercent 는 0~100 (spend 는 한도를 넘으면 100 초과), resetsAt·at 은 ISO 시각.
37
+ const winJson = (w) => (w ? { usedPercent: w.pct, resetsAt: iso(w.resetsAt) } : null);
38
+ export function limitsJson(rec, now = Date.now()) {
39
+ const f = freshLimits(rec, now);
40
+ if (!f) return null;
41
+ return { fiveHour: winJson(f.fiveHour), sevenDay: winJson(f.sevenDay), ...(f.spend ? { spend: winJson(f.spend) } : {}), at: iso(f.at) };
42
+ }
43
+
34
44
  export function toJson(data, version = null, opts = {}) {
35
45
  const b = data.usage ? projectBudget(data.usage, opts.budgetDay, { now: data.at ?? Date.now() }) : null;
36
46
  return {
@@ -39,6 +49,8 @@ export function toJson(data, version = null, opts = {}) {
39
49
  at: iso(data.at),
40
50
  tools: toolsJson(data.tools?.tools),
41
51
  usage: data.usage ? { today: usageOf(data.usage.today), last7days: { ...usageOf(data.usage.week), ...dailyOf(data.usage.days7) }, lastHour: lastHourOf(data.usage.lastHour), complete: data.usage.loading == null, ...(b ? { budget: { day: b.day, projected: money(b.projected), unknown: b.unknown, level: b.level } } : {}) } : null,
52
+ // 이 기기의 Claude 남은 사용 한도 (aitop --statusline 을 Claude Code 상태줄에 넣었을 때만 값이 있다).
53
+ limits: { claude: limitsJson(data.limits, data.at ?? Date.now()) },
42
54
  // --remote 로 모은 원격마다 마지막 결과 (#308). 원격을 켜지 않으면 빈 배열. at 은 마지막으로 성공한 시각.
43
55
  remotes: (data.remotes ?? []).map(remoteOf),
44
56
  sessions: data.sessions.map((s) => ({
@@ -80,6 +92,8 @@ export function toJson(data, version = null, opts = {}) {
80
92
  startedAt: iso(s.startedAt),
81
93
  updatedAt: iso(s.updatedAt),
82
94
  tokens: pickTokens(s.tokens),
95
+ // 프롬프트 캐시 적중률 (#334): 캐시 읽기 / (입력 + 캐시 읽기 + 캐시 쓰기), 메인과 서브에이전트 합. 0~1, 소수 셋째 자리. 토큰 내역을 모르면 null.
96
+ cacheHitRate: hitJson(cacheHitRate(s.tokens)),
83
97
  cost: money(s.cost),
84
98
  costNoCache: money(s.costNoCache),
85
99
  costUnknown: Boolean(s.costUnknown),