@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/src/limits.mjs ADDED
@@ -0,0 +1,149 @@
1
+ // Claude 남은 사용 한도(5시간·7일, 게이트웨이 지출 한도) (#332).
2
+ // Claude Code 는 상태줄 명령의 stdin JSON 에만 rate_limits 를 넣고 기록 파일에는 남기지 않는다.
3
+ // 그래서 사용자가 settings.json 의 statusLine.command 에 `aitop --statusline` 을 넣으면, 그 입력에서 숫자·시각만 꺼내
4
+ // 캐시 루트의 claude-limits.json 에 저장하고, 실시간 화면·--json·--line 이 그 파일을 읽는다. 네트워크는 쓰지 않는다.
5
+ // 이 모듈은 상태줄이 자주(응답마다) 부르는 가벼운 경로라 paths.mjs·rename.mjs 만 불러온다 (화면 모듈·수집기·i18n 없음).
6
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { homedir } from 'node:os';
8
+ import { dirname, join } from 'node:path';
9
+ import { appDir } from './paths.mjs';
10
+ import { renameSync } from './rename.mjs';
11
+
12
+ // cache.mjs 의 CACHE_ROOT 와 같은 곳 (summary.json 옆). 버전 폴더 밖이라 aitop 버전이 바뀌어도 그대로 읽힌다.
13
+ export const LIMITS_NAME = 'claude-limits.json';
14
+ export const LIMITS_FILE = join(appDir('cache', { home: homedir() }), LIMITS_NAME);
15
+ // 이보다 오래된 저장값은 보이지 않는다 (7일 창보다 오래됐으면 어느 값도 믿을 수 없다).
16
+ export const MAX_AGE_MS = 7 * 86_400_000;
17
+ // 시계가 조금 어긋난 것은 봐준다. 이보다 미래 시각이면 잘못된 파일로 본다.
18
+ const SKEW_MS = 5_000;
19
+ // 같은 값이면 이 간격보다 자주 다시 쓰지 않는다 (상태줄은 응답마다 불린다). 마지막 갱신 시각이 이만큼 늦을 수 있다.
20
+ export const REWRITE_MS = 30_000;
21
+ // 5시간·7일 한도는 0~100 이다 (문서). 지출 한도(spend_limit)는 한도를 넘으면 100 을 넘을 수 있어 상한을 넉넉히 둔다.
22
+ const PCT_MAX = { fiveHour: 100, sevenDay: 100, spend: 1000 };
23
+ // resets_at 은 초 단위 epoch. 2001~2286년 밖이면 단위가 틀렸거나 깨진 값으로 본다.
24
+ const SEC_MIN = 1e9;
25
+ const SEC_MAX = 1e10;
26
+ // 창마다 resets_at 이 지금보다 이만큼 넘게 먼 미래면 버린다 (5시간 창은 6시간, 7일 창은 8일). 지출 한도는 기간(일·주·달)이 달라 SEC_MAX 만 본다.
27
+ const AHEAD_MS = { fiveHour: 6 * 3600_000, sevenDay: 8 * 86_400_000, spend: Infinity };
28
+ // 화면·--line 에서 주의색·경고색을 쓰는 기준 (예산 색 규칙과 같은 단계 이름).
29
+ export const CAUTION_PCT = 80;
30
+ export const WARN_PCT = 95;
31
+
32
+ const KEYS = [
33
+ ['fiveHour', 'five_hour'],
34
+ ['sevenDay', 'seven_day'],
35
+ ['spend', 'spend_limit'],
36
+ ];
37
+
38
+ // 창 하나: used_percentage(숫자, 0~max)와 resets_at(초 epoch)이 둘 다 맞아야 { pct, resetsAt(ms) }. 아니면 null.
39
+ // 문자열 숫자·음수·상한 넘는 값·NaN 은 받지 않는다.
40
+ function windowOf(w, max, maxAt = Infinity) {
41
+ if (!w || typeof w !== 'object') return null;
42
+ const pct = w.used_percentage;
43
+ const sec = w.resets_at;
44
+ if (typeof pct !== 'number' || !Number.isFinite(pct) || pct < 0 || pct > max) return null;
45
+ if (typeof sec !== 'number' || !Number.isFinite(sec) || sec < SEC_MIN || sec > SEC_MAX) return null;
46
+ if (sec * 1000 > maxAt) return null;
47
+ return { pct: Math.round(pct * 10) / 10, resetsAt: Math.round(sec * 1000) };
48
+ }
49
+
50
+ // 상태줄 입력(JSON 객체)에서 한도만 꺼낸다. 맞는 창이 하나도 없으면 null. now 는 초기화 시각 상한(AHEAD_MS)의 기준.
51
+ // 모델명·경로·세션 id·비용 같은 다른 필드는 보지도 담지도 않는다. 지출 한도의 used_usd·limit_usd·period 도 담지 않는다.
52
+ export function parseLimits(input, now = Date.now()) {
53
+ const r = input && typeof input === 'object' ? input.rate_limits : null;
54
+ if (!r || typeof r !== 'object') return null;
55
+ const out = {};
56
+ for (const [key, src] of KEYS) {
57
+ const w = windowOf(r[src], PCT_MAX[key], now + AHEAD_MS[key]);
58
+ if (w) out[key] = w;
59
+ }
60
+ return Object.keys(out).length ? out : null;
61
+ }
62
+
63
+ // 파일에서 읽은 창 하나를 다시 검사한다 (손으로 고친 파일·다른 버전이 쓴 파일).
64
+ function storedWindow(w, max) {
65
+ if (!w || typeof w !== 'object') return null;
66
+ if (typeof w.pct !== 'number' || !Number.isFinite(w.pct) || w.pct < 0 || w.pct > max) return null;
67
+ if (typeof w.resetsAt !== 'number' || !Number.isFinite(w.resetsAt) || w.resetsAt < SEC_MIN * 1000 || w.resetsAt > SEC_MAX * 1000) return null;
68
+ return { pct: w.pct, resetsAt: w.resetsAt };
69
+ }
70
+
71
+ // 저장 파일을 그대로 읽는다 (만료 검사 없음). 없거나 깨졌으면 null. --doctor 의 '마지막 갱신' 은 이 값의 at 이다.
72
+ export function loadLimits({ file = LIMITS_FILE } = {}) {
73
+ let s;
74
+ try {
75
+ s = JSON.parse(readFileSync(file, 'utf8'));
76
+ } catch {
77
+ return null;
78
+ }
79
+ if (!s || typeof s !== 'object' || typeof s.at !== 'number' || !Number.isFinite(s.at) || s.at <= 0) return null;
80
+ const out = { at: s.at };
81
+ for (const [key] of KEYS) {
82
+ const w = storedWindow(s[key], PCT_MAX[key]);
83
+ if (w) out[key] = w;
84
+ }
85
+ return out;
86
+ }
87
+
88
+ // 보여도 되는 값만 남긴다: 저장한 지 7일이 넘었거나 미래 시각이면 null, 초기화 시각이 지난 창은 뺀다. 남는 창이 없으면 null.
89
+ export function freshLimits(rec, now = Date.now()) {
90
+ if (!rec || !Number.isFinite(rec.at)) return null;
91
+ if (now - rec.at > MAX_AGE_MS || rec.at - now > SKEW_MS) return null;
92
+ const out = { at: rec.at };
93
+ for (const [key] of KEYS) if (rec[key] && rec[key].resetsAt > now) out[key] = rec[key];
94
+ return Object.keys(out).length > 1 ? out : null;
95
+ }
96
+
97
+ const sameWindows = (a, b) => KEYS.every(([k]) => (a?.[k]?.pct ?? null) === (b?.[k]?.pct ?? null) && (a?.[k]?.resetsAt ?? null) === (b?.[k]?.resetsAt ?? null));
98
+
99
+ // 원자적으로 저장한다: pid 별 임시 파일에 쓰고 rename (여러 Claude 세션의 상태줄이 함께 써도 섞이지 않고 마지막 쪽이 남는다).
100
+ // 값이 지난번과 같고 REWRITE_MS 안이면 쓰지 않는다. 쓴 경우 true.
101
+ export function saveLimits(limits, { file = LIMITS_FILE, now = Date.now() } = {}) {
102
+ if (!limits) return false;
103
+ const prev = loadLimits({ file });
104
+ if (prev && sameWindows(prev, limits) && now - prev.at >= 0 && now - prev.at < REWRITE_MS) return false;
105
+ const tmp = `${file}.${process.pid}.tmp`;
106
+ try {
107
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
108
+ writeFileSync(tmp, JSON.stringify({ at: now, ...limits }), { mode: 0o600 });
109
+ renameSync(tmp, file);
110
+ return true;
111
+ } catch {
112
+ try {
113
+ rmSync(tmp, { force: true });
114
+ } catch {}
115
+ return false;
116
+ }
117
+ }
118
+
119
+ // 남은 시간을 짧게: 2h10m, 45m, 3d4h.
120
+ export function fmtLeft(ms) {
121
+ const m = Math.max(0, Math.floor(ms / 60_000));
122
+ if (m < 60) return `${m}m`;
123
+ if (m < 1440) return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`;
124
+ return `${Math.floor(m / 1440)}d${Math.floor((m % 1440) / 60)}h`;
125
+ }
126
+
127
+ export const pctText = (p) => `${Math.round(p)}%`;
128
+ // 'caution' | 'warn' | 'ok'. 예산 단계와 같은 이름이라 BUDGET_COLOR 를 그대로 쓴다.
129
+ export const pctLevel = (p) => (p >= WARN_PCT ? 'warn' : p >= CAUTION_PCT ? 'caution' : 'ok');
130
+
131
+ // --statusline 기본 줄 (사용자 상태줄 명령이 없을 때). ASCII 만 쓴다: 5h 23% (2h10m) | 7d 41% | spend 63%
132
+ // 값이 하나도 없으면 빈 글.
133
+ export function statusText(limits, now = Date.now()) {
134
+ if (!limits) return '';
135
+ const parts = [];
136
+ if (limits.fiveHour) parts.push(`5h ${pctText(limits.fiveHour.pct)} (${fmtLeft(limits.fiveHour.resetsAt - now)})`);
137
+ if (limits.sevenDay) parts.push(`7d ${pctText(limits.sevenDay.pct)}`);
138
+ if (limits.spend) parts.push(`spend ${pctText(limits.spend.pct)}`);
139
+ return parts.join(' | ');
140
+ }
141
+
142
+ // --doctor 용 점검: 상태줄이 한 번이라도 저장했는지와 마지막 갱신 시각(ISO), 아직 유효한 값.
143
+ // 파일을 읽기만 한다 (사용자 Claude Code 설정은 열지 않는다).
144
+ export function limitsCheck({ file = LIMITS_FILE, now = Date.now() } = {}) {
145
+ const rec = loadLimits({ file });
146
+ const f = freshLimits(rec, now);
147
+ const pct = (w) => (w ? w.pct : null);
148
+ return { connected: Boolean(rec), at: rec ? new Date(rec.at).toISOString() : null, file, fiveHour: pct(f?.fiveHour), sevenDay: pct(f?.sevenDay) };
149
+ }
package/src/line.mjs CHANGED
@@ -5,6 +5,7 @@
5
5
  // 옵션 오류 문구만 i18n 으로 지금 언어를 따른다.
6
6
  import { t } from './i18n.mjs';
7
7
  import { fmtAgo, stripControl, truncate, width } from './text.mjs';
8
+ import { freshLimits, loadLimits, pctLevel, pctText } from './limits.mjs';
8
9
 
9
10
  export const MODES = ['plain', 'tmux'];
10
11
  export const DEFAULT_WIDTH = 40;
@@ -26,6 +27,17 @@ const CUT = '~';
26
27
  // 멈춤(오류로 멈춘 세션)은 화면의 경고색과 같은 빨강, 색약용은 주홍. 색이 없어도 'stop' 글자로 갈린다.
27
28
  // 쉬는 중(aitop idle)은 작업 중보다 더 흐린 회색.
28
29
  const COLOURS = { normal: { waiting: 'colour214', stopped: 'colour203', money: 'colour154', running: 'colour250', idle: 'colour242' }, colorBlind: { waiting: 'colour226', stopped: 'colour209', money: 'colour75', running: 'colour250', idle: 'colour242' } };
30
+ // Claude 한도 칸의 색: 80% 이상은 대기와 같은 주의색, 95% 이상은 멈춤과 같은 경고색, 그 아래는 작업 중과 같은 회색.
31
+ const limitFg = (c, pct) => ({ warn: c.stopped, caution: c.waiting, ok: c.running })[pctLevel(pct)];
32
+
33
+ // Claude 한도 칸 (#332): 5h23% 7d41%, 폭이 모자라면 5h23% (5시간 값이 없으면 7d41% 만). 색은 둘 중 높은 값으로 정한다.
34
+ function limitPart(limits, c) {
35
+ const five = limits?.fiveHour ? `5h${pctText(limits.fiveHour.pct)}` : null;
36
+ const week = limits?.sevenDay ? `7d${pctText(limits.sevenDay.pct)}` : null;
37
+ if (!five && !week) return null;
38
+ const texts = five && week ? [`${five} ${week}`, five] : [five ?? week];
39
+ return { texts, fg: limitFg(c, Math.max(limits.fiveHour?.pct ?? 0, limits.sevenDay?.pct ?? 0)) };
40
+ }
29
41
 
30
42
  // --line, --line=plain|tmux, --line-width <N>, --line-width=<N> 를 꺼낸다. line 은 켜지 않았으면 null.
31
43
  export function lineOption(argv) {
@@ -88,10 +100,11 @@ function waitTexts(waiting, longest, now) {
88
100
 
89
101
  // 값: today(오늘 비용, API 정가 환산), budgetDay(하루 예산, 없으면 null), waiting(응답 대기 수),
90
102
  // longest(가장 오래 기다린 세션 { name, since }, 모르면 null), stopped(오류로 멈춘 세션 수, 시간 안에 다 세지 못했으면 null), running(작업 중 수, 요약이 없거나 오래됐으면 null), perHour(최근 1시간 지출).
103
+ // limits(freshLimits 결과, 없으면 null)가 있으면 맨 끝에 Claude 한도 칸을 붙인다 (폭이 모자라면 가장 먼저 줄이고 뺀다).
91
104
  // 0 인 항목은 뺀다. 오늘 비용이 0 이어도 예산이 있으면 $0.00/$50 으로 보인다.
92
105
  // width 를 넘으면 뒤 항목부터 줄인다: 시간당 지출, 작업 중, 멈춤 수, 대기 세션 이름, 대기 수, 오늘 비용 차례.
93
106
  // mode 가 tmux 이고 noColor 가 아니면 항목마다 tmux 서식을 씌운다. tmux 모드에서는 이름 속 # 을 ## 로 바꿔 서식으로 읽히지 않게 한다.
94
- export function formatLine({ today = 0, budgetDay = null, waiting = 0, longest = null, stopped = 0, running = null, perHour = 0 } = {}, { mode = 'plain', noColor = false, width: max = DEFAULT_WIDTH, colorBlind = false, now = Date.now() } = {}) {
107
+ export function formatLine({ today = 0, budgetDay = null, waiting = 0, longest = null, stopped = 0, running = null, perHour = 0, limits = null } = {}, { mode = 'plain', noColor = false, width: max = DEFAULT_WIDTH, colorBlind = false, now = Date.now() } = {}) {
95
108
  const c = COLOURS[colorBlind ? 'colorBlind' : 'normal'];
96
109
  // texts: 긴 글부터. 폭이 모자라면 다음 글로 줄이고, 마지막 글도 넘으면 항목을 뺀다.
97
110
  const parts = [];
@@ -103,6 +116,9 @@ export function formatLine({ today = 0, budgetDay = null, waiting = 0, longest =
103
116
  if (!zero(perHour)) parts.push({ texts: [`${rate(perHour)}/h`], fg: c.money });
104
117
  // 보일 항목이 하나도 없으면 빈 줄 대신 IDLE 을 낸다 (고장과 구분되게). 폭이 모자라면 짧은 글, 그래도 모자라면 - (#292).
105
118
  if (!parts.length) parts.push({ texts: [IDLE, 'idle', '-'], fg: c.idle });
119
+ // 한도 칸은 IDLE 판단 뒤에 붙인다 (한도만 있으면 aitop idle 5h23% 처럼 보인다).
120
+ const lim = limitPart(limits, c);
121
+ if (lim) parts.push(lim);
106
122
  while (parts.length && width(parts.map((p) => p.texts[0]).join(' ')) > max) {
107
123
  if (parts.at(-1).texts.length > 1) parts.at(-1).texts.shift();
108
124
  else parts.pop();
@@ -144,5 +160,5 @@ export async function collectLine({ capMs = CAP_MS, now = Date.now() } = {}) {
144
160
  // 기록 끝 읽기도 장부와 같은 시간 상한 안에 둔다. 장부가 상한을 거의 다 쓴 경우에도 세어 볼 수 있게 최소 STOP_MIN_MS 는 준다.
145
161
  // 그래도 다 세지 못하면 stopped 는 null 이고 줄에서 멈춤 칸만 빠진다.
146
162
  const { waiting, stopped } = claudeLineCounts({ deadline: Math.max(budget.deadline, Date.now() + STOP_MIN_MS) });
147
- return { today: usage.today.cost, ...pickCounts(readSummary({ now }), waiting), stopped, perHour: usage.lastHour.cost };
163
+ return { today: usage.today.cost, ...pickCounts(readSummary({ now }), waiting), stopped, perHour: usage.lastHour.cost, limits: freshLimits(loadLimits(), now) };
148
164
  }
package/src/monthly.mjs CHANGED
@@ -10,7 +10,7 @@
10
10
  // 여러 aitop 이 함께 써도 파일 하나에는 늘 "since~through 의 합" 만 들어 있다: 쓰기 전에 다시 읽어 rev 가 바뀌었으면 쓰지 않고
11
11
  // (다음 기회에 다시 접는다), pid 별 임시 파일에 쓴 뒤 rename 한다.
12
12
  //
13
- // 값마다 사용량 벡터(입력·출력·캐시 읽기·캐시 쓰기 5분·1시간, fast 모드는 따로)를 남겨, 가격표가 바뀌면 지금 가격으로 다시 계산한다.
13
+ // 값마다 사용량 벡터(입력·출력·캐시 읽기·캐시 쓰기 5분·1시간, fast 모드와 긴 프롬프트 요청은 따로)를 남겨, 가격표가 바뀌면 지금 가격으로 다시 계산한다.
14
14
  import { readFileSync, writeFileSync, mkdirSync, rmSync } from 'node:fs';
15
15
  import { renameSync } from './rename.mjs';
16
16
  import { dirname, join } from 'node:path';
@@ -68,7 +68,7 @@ export const emptyArchive = () => ({ v: V, rev: 0, price: PRICE_TAG, since: null
68
68
 
69
69
  const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
70
70
  const isVec = (x) => Array.isArray(x) && x.every(isNum);
71
- const validEntry = (e) => e && typeof e.t === 'string' && typeof e.m === 'string' && (e.p == null || typeof e.p === 'string') && isNum(e.n) && isNum(e.c) && (e.u == null || isVec(e.u)) && (e.f == null || isVec(e.f));
71
+ const validEntry = (e) => e && typeof e.t === 'string' && typeof e.m === 'string' && (e.p == null || typeof e.p === 'string') && isNum(e.n) && isNum(e.c) && (e.u == null || isVec(e.u)) && (e.f == null || isVec(e.f)) && (e.l == null || isVec(e.l));
72
72
  function valid(a) {
73
73
  if (!a || typeof a !== 'object' || !Number.isInteger(a.rev)) return false;
74
74
  for (const k of ['since', 'from', 'through', 'backfilled']) if (a[k] != null && !(typeof a[k] === 'string' && DAY.test(a[k]))) return false;
@@ -85,8 +85,8 @@ function reprice(a) {
85
85
  for (const [month, list] of Object.entries(a.months)) {
86
86
  const at = Date.parse(`${month}-15T12:00:00Z`);
87
87
  for (const e of list) {
88
- if (!e.u && !e.f) continue;
89
- const c = vecCost(e.t, e.m, e.u, e.f, at);
88
+ if (!e.u && !e.f && !e.l) continue;
89
+ const c = vecCost(e.t, e.m, e.u, e.f, at, e.l);
90
90
  if (c == null) continue;
91
91
  e.c = c;
92
92
  delete e.x;
@@ -201,7 +201,7 @@ export function foldInto(a, books, { lo, hi, complete = lo, now = Date.now(), ga
201
201
  e.n += x.tokens;
202
202
  e.c += x.cost;
203
203
  if (x.unknown) e.x = 1;
204
- for (const k of ['u', 'f']) if (x[k]) e[k] = (e[k] ?? [0, 0, 0, 0, 0]).map((v, i) => v + (x[k][i] ?? 0));
204
+ for (const k of ['u', 'f', 'l']) if (x[k]) e[k] = (e[k] ?? [0, 0, 0, 0, 0]).map((v, i) => v + (x[k][i] ?? 0));
205
205
  }
206
206
  }
207
207
  if (a.through == null) {
package/src/pricing.mjs CHANGED
@@ -1,8 +1,10 @@
1
1
  // Claude API 정가 기준 환산 비용 (USD / 100만 토큰). 구독 요금제 사용분도 "API 로 썼다면" 기준으로 계산한다.
2
- // 출처: Anthropic 공식 가격표 https://platform.claude.com/docs/en/about-claude/pricing (2026-11-18 확인).
2
+ // 출처: Anthropic 공식 가격표 https://platform.claude.com/docs/en/about-claude/pricing (2026-11-27 확인).
3
3
  // 캐시 읽기는 기본 입력가의 0.1배이고 표에 cacheRead 가 있는 모델만 다르다 (Fable·Mythos 5.1/5.2 는 0.025배, Opus·Sonnet 5.5 는 0.05배).
4
- // 캐시 쓰기는 5분 1.25배·1시간 2배. Haiku 5.5 의 10만 토큰 초과 요청 단가(5배)는 반영하지 않는다:
5
- // 보관 벡터(monthly.mjs)에는 요청별 크기가 남지 않아서, 모두 기본 단가로 계산한다.
4
+ // 캐시 쓰기는 5분 1.25배·1시간 2배.
5
+ // long: 프롬프트가 over 토큰을 넘는 요청 전체에 쓰는 단가 (Haiku 5.5 는 10만 토큰 초과면 입력·출력·캐시 모두 5배).
6
+ // 프롬프트 길이는 그 요청(usage 한 건)의 입력 + 캐시 읽기 + 캐시 쓰기 합이고, 요청마다 따로 판정한다.
7
+ // 보관 벡터(monthly.mjs)에는 요청별 크기가 남지 않으므로, 긴 요청의 벡터는 장부에서 l 로 따로 모은다.
6
8
  import { createHash } from 'node:crypto';
7
9
 
8
10
  const PRICES = {
@@ -25,12 +27,12 @@ const PRICES = {
25
27
  'claude-sonnet-4-6': { input: 3, output: 15 },
26
28
  'claude-sonnet-4-5': { input: 3, output: 15 },
27
29
  'claude-sonnet-4': { input: 3, output: 15 },
28
- 'claude-haiku-5-5': { input: 0.1, output: 0.5 },
30
+ 'claude-haiku-5-5': { input: 0.1, output: 0.5, long: { over: 100_000, input: 0.5, output: 2.5, cacheRead: 0.05 } },
29
31
  'claude-haiku-4-5': { input: 1, output: 5 },
30
32
  };
31
33
 
32
34
  // Gemini API 정가 (USD / 100만 토큰, 유료 등급 standard). Antigravity CLI(agy) 사용분을 "API 로 썼다면" 기준으로 계산한다.
33
- // 출처: Google 공식 가격표 https://aistudio.google.com/docs/pricing (2026-11-18 확인). 긴 컨텍스트 구간은 따로 없다.
35
+ // 출처: Google 공식 가격표 https://ai.google.dev/gemini-api/docs/pricing (2026-11-27 확인). 긴 컨텍스트 구간은 따로 없다.
34
36
  // 출력에는 생각 토큰이 들어 있고, cacheRead 는 context caching 가격이다. 가격이 바뀌는 모델은 날짜순 목록이며,
35
37
  // from 은 그 가격이 시작되는 날(UTC 0시)이다.
36
38
  const GEMINI_PRICES = {
@@ -39,6 +41,11 @@ const GEMINI_PRICES = {
39
41
  { input: 2, output: 10, cacheRead: 0.1 },
40
42
  { from: '2026-12-01', input: 4, output: 20, cacheRead: 0.2 },
41
43
  ],
44
+ 'gemini-4-carbon': [
45
+ { input: 2, output: 10, cacheRead: 0.1 },
46
+ { from: '2026-12-01', input: 4, output: 20, cacheRead: 0.2 },
47
+ ],
48
+ 'gemini-4-neon': [{ input: 3, output: 15, cacheRead: 0.15 }],
42
49
  'gemini-3.8-flash': [
43
50
  { input: 0.75, output: 3.75, cacheRead: 0.075 },
44
51
  { from: '2027-01-01', input: 1.5, output: 7.5, cacheRead: 0.15 },
@@ -133,6 +140,7 @@ function priceOf(model) {
133
140
 
134
141
  // 사용량 벡터: [입력(캐시 제외), 출력, 캐시 읽기, 캐시 쓰기 5분, 캐시 쓰기 1시간]. 월별 보관함(monthly.mjs)이
135
142
  // 이 벡터를 남겨 두었다가 가격표가 바뀌면 지금 가격으로 다시 계산한다.
143
+ // 벡터는 세 갈래다: u(보통), f(fast 모드), l(긴 프롬프트 요청: 표에 long 이 있는 모델만).
136
144
  export const VEC = 5;
137
145
  export const zeroVec = () => [0, 0, 0, 0, 0];
138
146
 
@@ -144,7 +152,16 @@ export function claudeVec(u) {
144
152
  return [u.input_tokens ?? 0, u.output_tokens ?? 0, u.cache_read_input_tokens ?? 0, write5m, write1h];
145
153
  }
146
154
 
147
- // Claude 벡터 하나의 비용 (m: fast 배수).
155
+ // 요청 하나(usage 한 건)가 긴 프롬프트 단가를 받는지. 입력 + 캐시 읽기 + 캐시 쓰기 합이 long.over 를 넘을 때만이다 (같으면 기본 단가).
156
+ // 장부(claude-ledger.mjs)가 이 값으로 벡터를 l 에 모은다. 표에 long 이 없는 모델은 늘 false.
157
+ export function claudeLong(model, u) {
158
+ const over = priceOf(model)?.long?.over;
159
+ if (!over || !u) return false;
160
+ const v = claudeVec(u);
161
+ return v[0] + v[2] + v[3] + v[4] > over;
162
+ }
163
+
164
+ // Claude 벡터 하나의 비용 (m: fast 배수). 긴 요청은 p 대신 p.long 을 넘긴다 (캐시 읽기가 없으면 입력의 0.1배, 쓰기는 1.25배·2배로 같다).
148
165
  function claudeVecCost(p, v, m) {
149
166
  const input = p.input * m;
150
167
  const base = v[0] * input + v[1] * p.output * m;
@@ -156,17 +173,19 @@ function claudeVecCost(p, v, m) {
156
173
  export function claudeCost(model, u) {
157
174
  const p = priceOf(model);
158
175
  if (!p || !u) return null;
159
- return claudeVecCost(p, claudeVec(u), u.speed === 'fast' && p.fast ? p.fast : 1);
176
+ return claudeVecCost(claudeLong(model, u) ? p.long : p, claudeVec(u), u.speed === 'fast' && p.fast ? p.fast : 1);
160
177
  }
161
178
 
162
- // 보관된 벡터(v: 보통, f: fast 모드)를 지금 가격표로 환산한 비용(USD). 가격표에 없는 모델이면 null.
179
+ // 보관된 벡터(v: 보통, f: fast 모드, l: 긴 프롬프트 요청)를 지금 가격표로 환산한 비용(USD). 가격표에 없는 모델이면 null.
163
180
  // agy(Gemini)는 날짜별 가격이라 at(그 달 가운데) 시각의 가격을 쓴다.
164
- export function vecCost(tool, model, v, f, at = Date.now()) {
181
+ // l 은 long 단가로 계산한다. 지금 표에서 long 이 있는 모델(Haiku 5.5)은 fast 가 없어 배수는 1 이다.
182
+ // 표에서 long 이 사라졌으면 l 도 기본 단가로 계산한다.
183
+ export function vecCost(tool, model, v, f, at = Date.now(), l = null) {
165
184
  const u = v ?? zeroVec();
166
185
  if (tool === 'claude') {
167
186
  const p = priceOf(model);
168
187
  if (!p) return null;
169
- return claudeVecCost(p, u, 1).total + (f ? claudeVecCost(p, f, p.fast ?? 1).total : 0);
188
+ return claudeVecCost(p, u, 1).total + (f ? claudeVecCost(p, f, p.fast ?? 1).total : 0) + (l ? claudeVecCost(p.long ?? p, l, 1).total : 0);
170
189
  }
171
190
  const p = tool === 'codex' ? openaiPrice(model) : tool === 'agy' ? geminiPrice(model, at) : null;
172
191
  if (!p) return null;
package/src/resume.mjs CHANGED
@@ -15,8 +15,8 @@ export function shellQuote(s) {
15
15
  return `'${v.replace(/'/g, `'\\''`)}'`;
16
16
  }
17
17
 
18
- // Codex 기록 파일 이름(rollout-2025-...-<uuid>.jsonl)에서 세션 UUID 를 꺼낸다. `codex resume <UUID>` 가 받는 값이다.
19
- const UUID = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:\.jsonl)?$/i;
18
+ // Codex 기록 파일 이름(rollout-2025-...-<uuid>.jsonl, 압축본은 .jsonl.zst)에서 세션 UUID 를 꺼낸다. `codex resume <UUID>` 가 받는 값이다.
19
+ const UUID = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:\.jsonl(?:\.zst)?)?$/i;
20
20
  export const codexId = (id) => UUID.exec(String(id ?? ''))?.[1] ?? null;
21
21
  // Claude 세션 id 는 UUID 다. 그 밖의 값(예: --dangerously-skip-permissions)은 옵션으로 읽힐 수 있어 받지 않는다.
22
22
  const isUuid = (id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);
@@ -11,7 +11,7 @@ import { t } from './i18n.mjs';
11
11
  import { fmtElapsed, fmtTokens, mask, oneLine, pad, stripControl, truncate, width } from './text.mjs';
12
12
  import { money } from './line.mjs';
13
13
  import { tildeIn } from './paths.mjs';
14
- import { dayKey } from './sources/common.mjs';
14
+ import { cacheHitRate, dayKey, hitJson, hitText, vecTokens } from './sources/common.mjs';
15
15
  import { projectLabels } from './sources/projects.mjs';
16
16
  import { MAX_MS, UNKNOWN, collectReport } from './report.mjs';
17
17
 
@@ -144,6 +144,9 @@ export function buildSessions(books, { since, now = Date.now(), extra = new Map(
144
144
  let tokens = 0;
145
145
  let cost = 0;
146
146
  let unpriced = false;
147
+ // 프롬프트 캐시 적중률용 (#334): 장부 모델별 벡터(u·f)의 입력·캐시 읽기·캐시 쓰기 합. 벡터 없이 토큰만 있는 칸이 섞이면 모름.
148
+ const hit = { input: 0, cacheRead: 0, cacheWrite: 0 };
149
+ let hitKnown = true;
147
150
  let a = null;
148
151
  let z = null;
149
152
  const files = new Set();
@@ -165,6 +168,14 @@ export function buildSessions(books, { since, now = Date.now(), extra = new Map(
165
168
  const o = (models[m] ??= { tokens: 0, cost: 0 });
166
169
  o.tokens += x.tokens;
167
170
  o.cost += x.cost;
171
+ if (!x.u && !x.f) {
172
+ if (x.tokens > 0) hitKnown = false;
173
+ continue;
174
+ }
175
+ for (const v of [x.u, x.f]) {
176
+ const p = vecTokens(v);
177
+ for (const k of Object.keys(hit)) hit[k] += p[k];
178
+ }
168
179
  }
169
180
  if (g.tool === 'agy') time(d);
170
181
  }
@@ -208,6 +219,8 @@ export function buildSessions(books, { since, now = Date.now(), extra = new Map(
208
219
  tokens,
209
220
  cost,
210
221
  unpriced,
222
+ // 메인과 서브에이전트(agy 는 하위 대화)를 합친 프롬프트 캐시 적중률 0~1. 모르면 null.
223
+ cacheHitRate: hitKnown ? cacheHitRate(hit) : null,
211
224
  files: filesKnown ? files.size : null,
212
225
  filesMore: filesKnown && more,
213
226
  prompt,
@@ -283,6 +296,8 @@ export function sessionsJson(r, version, { partial = false, prompts = false } =
283
296
  tokens: x.tokens,
284
297
  cost: x.cost,
285
298
  unpriced: x.unpriced,
299
+ // 프롬프트 캐시 적중률 0~1 (소수 셋째 자리). 모르면 null.
300
+ cacheHitRate: hitJson(x.cacheHitRate),
286
301
  files: x.files,
287
302
  // 기다린 시간 (ms, 추정). agy 처럼 모르면 null.
288
303
  waitedMs: x.waited,
@@ -333,9 +348,10 @@ function titleOf(r) {
333
348
  }
334
349
 
335
350
  // 기다림 칸은 시작·끝 옆에 둔다 (시간끼리). 좁은 터미널에서는 다른 칸처럼 그대로 두고 세션 이름 칸이 줄어든다.
336
- const HEAD_KEYS = ['tool', 'model', 'project', 'name', 'start', 'end', 'waited', 'tokens', 'cost', 'files'];
337
- const rowCells = (x) => [x.tool, clean(modelText(x)), clean(projectText(x)), clean(x.name), startText(x), endText(x), waitedText(x.waited), used(x) ? fmtTokens(Math.round(x.tokens)) : '-', costText(x), filesText(x)];
338
- const RIGHT = new Set([6, 7, 8, 9]);
351
+ // 캐시(프롬프트 캐시 적중률, #334)는 토큰 옆에 둔다.
352
+ const HEAD_KEYS = ['tool', 'model', 'project', 'name', 'start', 'end', 'waited', 'tokens', 'cache', 'cost', 'files'];
353
+ const rowCells = (x) => [x.tool, clean(modelText(x)), clean(projectText(x)), clean(x.name), startText(x), endText(x), waitedText(x.waited), used(x) ? fmtTokens(Math.round(x.tokens)) : '-', hitText(x.cacheHitRate) ?? '-', costText(x), filesText(x)];
354
+ const RIGHT = new Set([6, 7, 8, 9, 10]);
339
355
  // 칸 폭 상한 (세션 이름은 터미널 폭에 맞춘다).
340
356
  const MAX_W = { 1: 24, 2: 20 };
341
357
  const NAME_MIN = 12;
@@ -6,7 +6,7 @@ import { readdirSync, statSync, existsSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { JsonlTail } from '../tail.mjs';
8
8
  import { loadCache, markDirty } from '../cache.mjs';
9
- import { claudeCost, claudeVec } from '../pricing.mjs';
9
+ import { claudeCost, claudeLong, claudeVec } from '../pricing.mjs';
10
10
  import { dayKey, lastDays, addSlot, addModel, lastHourOf, recentTodayOf, recentDays, KEEP_DAYS } from './common.mjs';
11
11
  import { collectAgyLedger } from './agy-ledger.mjs';
12
12
  import { collectCodexLedger } from './codex-ledger.mjs';
@@ -79,7 +79,12 @@ export class UsageTracker {
79
79
  day.cost += dCost;
80
80
  const vec = claudeVec(u);
81
81
  const was = claudeVec(prev?.u);
82
- addModel(day, m.model, dTokens, dCost, !cost && tokensOf(u) > 0, vec.map((x, i) => x - was[i]), u.speed === 'fast');
82
+ const long = claudeLong(m.model, u);
83
+ // 같은 응답의 직전 줄이 다른 갈래(보통·긴 요청)에 들어갔으면 그 몫을 빼고 이번 값을 통째로 새 갈래에 더한다.
84
+ if (prev && claudeLong(m.model, prev.u) !== long) {
85
+ addModel(day, m.model, 0, 0, false, was.map((x) => -x), prev.u.speed === 'fast', !long);
86
+ addModel(day, m.model, dTokens, dCost, unknown, vec, u.speed === 'fast', long);
87
+ } else addModel(day, m.model, dTokens, dCost, unknown, vec.map((x, i) => x - was[i]), u.speed === 'fast', long);
83
88
  day.costNoCache = (day.costNoCache ?? 0) + (cost?.noCache ?? 0) - (prev?.costNoCache ?? 0);
84
89
  if (unknown) day.unknown = true;
85
90
  addSlot(this.slots, at, dCost, dNoCache, unknown);
@@ -167,7 +172,8 @@ function gather({ budget, now, days = DAYS }) {
167
172
  for (const [tool, o] of others) {
168
173
  pending += o.pending;
169
174
  size += o.size;
170
- books.push(...o.days.map((d, i) => ({ tool, path: o.paths[i], days: d, ...(o.stale?.[i] ? { staleFrom: o.stale[i] } : {}) })));
175
+ // cwd: 장부가 읽으면서 기억한 작업 폴더 (Codex 압축 기록의 프로젝트를 찾을 때 쓴다, projects.mjs).
176
+ books.push(...o.days.map((d, i) => ({ tool, path: o.paths[i], days: d, ...(o.stale?.[i] ? { staleFrom: o.stale[i] } : {}), ...(o.cwds?.[i] ? { cwd: o.cwds[i] } : {}) })));
171
177
  slots.push(...o.slots);
172
178
  }
173
179
  return { books, slots, pending, size };
@@ -2,6 +2,7 @@
2
2
  // token_count 는 세션 누적값(total_token_usage)이라, 같은 파일의 직전 누적값과의 차이만 그 줄의 시각에 더한다.
3
3
  // 같은 누적값이 되풀이되면 차이가 0 이라 두 번 세지 않고, 누적값이 줄었으면 새 카운터가 시작된 것으로 보고 새 누적값을 그대로 더한다.
4
4
  // 가격은 그 줄 앞의 마지막 turn_context 모델로 매긴다. 기록은 읽기만 하고, 어디까지 읽었는지는 캐시에 둔다.
5
+ // 7일 넘게 쉬어 Codex 가 압축한 rollout-*.jsonl.zst 도 같은 기록으로 센다 (zstd.mjs). 한 번 다 풀어 읽으면 바뀔 때까지 다시 풀지 않는다.
5
6
  import { readdirSync, statSync } from 'node:fs';
6
7
  import { join } from 'node:path';
7
8
  import { JsonlTail } from '../tail.mjs';
@@ -11,6 +12,7 @@ import { allDayDirs } from './codex.mjs';
11
12
  import { dedupeBy } from './dirs.mjs';
12
13
  import { dayKey, addSlot, addModel, recentDays } from './common.mjs';
13
14
  import { debugIo } from '../log.mjs';
15
+ import { plainName, rolloutNames } from '../zstd.mjs';
14
16
 
15
17
  // 2: 사용량 벡터, 날짜 400일 보관 (#164).
16
18
  const KIND = 'codex-ledger2';
@@ -41,6 +43,8 @@ export class CodexBook {
41
43
  this.last = c.last ?? null;
42
44
  this.days = c.days ?? {};
43
45
  this.slots = c.slots ?? {};
46
+ this.cwd = c.cwd ?? null;
47
+ this.metaCwd = c.metaCwd ?? null;
44
48
  }
45
49
  }
46
50
 
@@ -50,6 +54,10 @@ export class CodexBook {
50
54
  this.days = {};
51
55
  // 지출 속도용 5분 칸 (common.mjs addSlot).
52
56
  this.slots = {};
57
+ // 리포트 --by project 용 작업 폴더: 첫 turn_context.cwd, 없으면 session_meta.cwd (projects.mjs codexProject 와 같은 규칙).
58
+ // 압축 기록은 앞부분만 읽을 수 없어 장부가 읽으면서 기억해 둔다.
59
+ this.cwd = null;
60
+ this.metaCwd = null;
53
61
  }
54
62
 
55
63
  get pending() {
@@ -63,13 +71,15 @@ export class CodexBook {
63
71
  }
64
72
 
65
73
  snapshot() {
66
- return { offset: this.tail.lineOffset, model: this.model, last: this.last, days: recentDays(this.days), slots: this.slots };
74
+ return { offset: this.tail.lineOffset, model: this.model, last: this.last, days: recentDays(this.days), slots: this.slots, cwd: this.cwd, metaCwd: this.metaCwd };
67
75
  }
68
76
 
69
77
  apply(x) {
70
78
  const p = x.payload ?? {};
79
+ if (x.type === 'session_meta' && typeof p.cwd === 'string') this.metaCwd ??= p.cwd;
71
80
  if (x.type === 'turn_context') {
72
81
  this.model = p.model ?? this.model;
82
+ if (typeof p.cwd === 'string') this.cwd ??= p.cwd;
73
83
  return;
74
84
  }
75
85
  if (x.type !== 'event_msg' || p.type !== 'token_count' || !p.info?.total_token_usage) return;
@@ -105,12 +115,12 @@ function recentFiles(days = DAYS) {
105
115
  } catch (e) {
106
116
  debugIo('ledger', 'codex day folder read failed', e, dir);
107
117
  }
108
- for (const n of names) {
109
- if (!n.startsWith('rollout-') || !n.endsWith('.jsonl')) continue;
118
+ // 같은 이름의 .jsonl 과 .jsonl.zst 가 함께 있으면 .jsonl 만, 홈끼리는 .zst 를 뗀 이름으로 하나로 센다.
119
+ for (const n of rolloutNames(names)) {
110
120
  const p = join(dir, n);
111
121
  try {
112
122
  const mtime = statSync(p).mtimeMs;
113
- if (mtime >= cutoff) found.push({ key: n, path: p, mtime });
123
+ if (mtime >= cutoff) found.push({ key: plainName(n), path: p, mtime });
114
124
  } catch {}
115
125
  }
116
126
  }
@@ -125,7 +135,7 @@ const books = new Map();
125
135
  // 기록마다 날짜별 합계(days)와 5분 칸(slots), 아직 읽지 않은 크기(pending)·전체 크기(size).
126
136
  // days: 최근 며칠 안에 바뀐 기록을 볼지 (평소 7일, 리포트는 더 길게).
127
137
  export function collectCodexLedger({ budget, days = DAYS } = {}) {
128
- const out = { days: [], slots: [], paths: [], pending: 0, size: 0 };
138
+ const out = { days: [], slots: [], paths: [], cwds: [], pending: 0, size: 0 };
129
139
  const files = recentFiles(days);
130
140
  const keep = new Set(files);
131
141
  for (const p of books.keys()) if (!keep.has(p)) books.delete(p);
@@ -137,6 +147,7 @@ export function collectCodexLedger({ budget, days = DAYS } = {}) {
137
147
  out.size += b.tail.size;
138
148
  out.days.push(b.days);
139
149
  out.paths.push(p);
150
+ out.cwds.push(b.cwd ?? b.metaCwd ?? null);
140
151
  out.slots.push(b.slots);
141
152
  }
142
153
  return out;
@@ -1,5 +1,6 @@
1
1
  // Codex CLI: 실행 중인 codex 프로세스의 작업 폴더와 ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl 을 짝지어 읽는다.
2
2
  // Codex 홈이 여럿이면(dirs.mjs) 모두 보고, 같은 rollout 파일 이름은 하나로 센다.
3
+ // 7일 넘게 쉰 rollout 은 Codex 가 .jsonl.zst 로 압축해 둔다 (zstd.mjs). 끝난 기록으로 읽고, 실행 중 짝짓기에는 쓰지 않는다.
3
4
  import { readdirSync, statSync, existsSync, realpathSync, openSync, readSync, closeSync } from 'node:fs';
4
5
  import { join, basename } from 'node:path';
5
6
  import { JsonlTail } from '../tail.mjs';
@@ -12,6 +13,7 @@ import { parsePatch, extractPatch, patchSucceeded } from './patch.mjs';
12
13
  import { debug, debugIo } from '../log.mjs';
13
14
  import { lastName } from '../paths.mjs';
14
15
  import { codexHomes, codexSessionRoots, dedupeBy, homeOf } from './dirs.mjs';
16
+ import { isZst, plainName, rolloutNames } from '../zstd.mjs';
15
17
 
16
18
  // 지시 탭에 쓰는 지시 목록은 최근 것만 남긴다.
17
19
  const MAX_TURNS = 50;
@@ -62,7 +64,8 @@ function recentFiles() {
62
64
  const paths = [];
63
65
  for (const dir of dayDirs()) {
64
66
  try {
65
- for (const n of readdirSync(dir)) if (n.endsWith('.jsonl')) paths.push(join(dir, n));
67
+ // 같은 이름의 .jsonl 과 .jsonl.zst 가 함께 있으면 .jsonl 만 (rolloutNames).
68
+ for (const n of rolloutNames(readdirSync(dir))) paths.push(join(dir, n));
66
69
  } catch (e) {
67
70
  debugIo('codex', 'day folder read failed', e, dir);
68
71
  }
@@ -77,7 +80,7 @@ function recentFiles() {
77
80
  } catch {
78
81
  continue;
79
82
  }
80
- if (Date.now() - m < RECENT_MS) out.push({ key: basename(p), path: p, mtime: m });
83
+ if (Date.now() - m < RECENT_MS) out.push({ key: plainName(basename(p)), path: p, mtime: m });
81
84
  }
82
85
  // 같은 rollout 이 두 홈에 있으면 더 최근 쪽 하나만.
83
86
  return dedupeBy(out).sort((a, b) => b.mtime - a.mtime);
@@ -157,6 +160,7 @@ function latestFor(dirs, cwd, since, taken) {
157
160
  }
158
161
  for (const n of names) {
159
162
  const p = join(dir, n);
163
+ // 압축 기록(.jsonl.zst)은 7일 넘게 쉰 끝난 기록이라 실행 중인 프로세스에 붙이지 않는다. 이어 쓰면 Codex 가 .jsonl 로 풀어 놓는다.
160
164
  if (!n.endsWith('.jsonl')) continue;
161
165
  listed.add(p);
162
166
  if (taken.has(p)) continue;
@@ -405,7 +409,8 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
405
409
  const procs = blind ? [] : procsOf();
406
410
  if (!procs.length && !showEnded && !blind) return [];
407
411
 
408
- const fresh = (f) => Date.now() - f.mtime <= NO_PROC_LIVE_MS;
412
+ // 압축 기록은 끝난 기록이라 실행 중으로 보지 않는다 (zstd.mjs).
413
+ const fresh = (f) => !isZst(f.path) && Date.now() - f.mtime <= NO_PROC_LIVE_MS;
409
414
  const files = blind && !showEnded ? recentFiles().filter(fresh) : recentFiles();
410
415
  const read = (path) => {
411
416
  let st = states.get(path);
@@ -445,7 +450,7 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
445
450
  else slots.set(p.cwd, [...(slots.get(p.cwd) ?? []), p.pid]);
446
451
  }
447
452
  for (const f of files) {
448
- if (liveByPath.has(f.path)) continue;
453
+ if (liveByPath.has(f.path) || isZst(f.path)) continue;
449
454
  const free = slots.get(states.get(f.path).cwd);
450
455
  const i = free?.findIndex((pid) => {
451
456
  const since = startOf(pid);
@@ -455,7 +460,7 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
455
460
  }
456
461
  // 작업 폴더를 모르는 프로세스(Windows)는 폴더와 상관없이 시작 시각으로만 짝짓는다 (pairByStart).
457
462
  if (anyCwd.length) {
458
- const free = files.filter((f) => !liveByPath.has(f.path));
463
+ const free = files.filter((f) => !liveByPath.has(f.path) && !isZst(f.path));
459
464
  for (const [path, pid] of pairByStart(anyCwd, free, (p) => states.get(p)?.startedAt, startOf)) liveByPath.set(path, pid);
460
465
  }
461
466