@sejuneoh/aitop 0.23.0 → 0.24.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 +9 -0
- package/bin/aitop.mjs +28 -1
- package/package.json +1 -1
- package/src/cache.mjs +2 -1
- package/src/i18n.mjs +41 -0
- package/src/pricing.mjs +25 -3
- package/src/report.mjs +179 -0
- package/src/sources/agy-ledger.mjs +14 -12
- package/src/sources/claude-ledger.mjs +38 -17
- package/src/sources/codex-ledger.mjs +13 -12
- package/src/sources/common.mjs +13 -0
package/README.md
CHANGED
|
@@ -30,6 +30,7 @@ aitop --all include sessions that ended in the last 24 hours
|
|
|
30
30
|
aitop --json print a snapshot as JSON and exit
|
|
31
31
|
aitop --doctor check which tools and logs aitop can see
|
|
32
32
|
aitop --line print one short status line and exit (for tmux, e.g. $54.13/$50 wait 2 $3.1/h)
|
|
33
|
+
aitop --report daily daily cost table and exit
|
|
33
34
|
aitop --help all options
|
|
34
35
|
aitop --lang ko Korean screen, help, doctor and error messages (also AITOP_LANG=ko or "lang": "ko" in the config file)
|
|
35
36
|
```
|
|
@@ -38,6 +39,14 @@ The language is picked from `--lang`, then `AITOP_LANG`, then `lang` in the conf
|
|
|
38
39
|
|
|
39
40
|
In `--json`, `phase` stays the Korean status text in every language (as does `AITOP_WAITING_FOR` for `--on-waiting`). For scripts, use `phaseKind`, a stable state name: `think`, `write`, `tool`, `team`, `waiting`, `idle`, `done`, `ended` (or `null`). Other text fields follow their own rules: with English selected, `--doctor --json` has Korean `tools.*.hint` but English `config.problems`.
|
|
40
41
|
|
|
42
|
+
### Daily report
|
|
43
|
+
|
|
44
|
+
`aitop --report daily` prints tokens and cost (API list price, like the header) per day, newest first, with a total row, then exits. Columns are per tool by default or per model with `--by model`; `--days N` goes back up to 30 days, and `--json` gives the same numbers for scripts. The first run reads up to 30 days of logs, so it can take a while (progress shows on stderr); later runs use the cache.
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
aitop --report daily --by model --days 14
|
|
48
|
+
```
|
|
49
|
+
|
|
41
50
|
### tmux status line
|
|
42
51
|
|
|
43
52
|
`aitop --line` prints today's cost (API list price, `/$<budget>` when a daily budget is set), the number of Claude Code sessions waiting for you, and spend over the last hour. Items that are 0 are left out, and `--line-width N` (default 40) drops items from the end. It reads only aitop's cache, so it is fast once `aitop` has run before; with no cache yet it prints `...` after about 1.5 seconds. `--line=tmux` adds tmux colors, `NO_COLOR` turns them off.
|
package/bin/aitop.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { budgetDayOption, configJson, configPath, configText, readConfigFile, re
|
|
|
4
4
|
import { langOption, pickLang, setLang, t } from '../src/i18n.mjs';
|
|
5
5
|
import { notifyOptions } from '../src/notify.mjs';
|
|
6
6
|
import { lineOption } from '../src/line.mjs';
|
|
7
|
+
import { reportOption } from '../src/report.mjs';
|
|
7
8
|
import { mask, setAmbiguous, stripControl } from '../src/text.mjs';
|
|
8
9
|
|
|
9
10
|
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']);
|
|
@@ -40,10 +41,16 @@ if (line.error) {
|
|
|
40
41
|
process.stderr.write(`aitop: ${line.error}\n`);
|
|
41
42
|
process.exit(2);
|
|
42
43
|
}
|
|
44
|
+
// --report daily, --by tool|model, --days <N> 은 reportOption 이 꺼낸다.
|
|
45
|
+
const report = reportOption(line.rest);
|
|
46
|
+
if (report.error) {
|
|
47
|
+
process.stderr.write(`aitop: ${report.error}\n`);
|
|
48
|
+
process.exit(2);
|
|
49
|
+
}
|
|
43
50
|
// 사용자가 준 NO_COLOR. 아래에서 파이프 출력이면 NO_COLOR 를 켜므로 그 전에 읽어 둔다 (tmux 의 #() 는 TTY 가 아니다).
|
|
44
51
|
const userNoColor = Boolean(process.env.NO_COLOR);
|
|
45
52
|
// --theme light, --theme=light 처럼 값을 받는 옵션은 따로 꺼낸다.
|
|
46
|
-
const argv =
|
|
53
|
+
const argv = report.rest;
|
|
47
54
|
let theme = null;
|
|
48
55
|
const rest = [];
|
|
49
56
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -139,6 +146,26 @@ if (line.mode) {
|
|
|
139
146
|
process.exit(0);
|
|
140
147
|
}
|
|
141
148
|
|
|
149
|
+
// --report: 날짜별 사용량 표(또는 --json)를 내고 끝낸다. 실시간 화면·세션 목록은 읽지 않고 장부만 읽는다.
|
|
150
|
+
// 처음 실행은 30일치 기록을 읽으므로 stderr 가 터미널이면 진행률을 보이고, 시간 상한(AITOP_REPORT_MS, 기본 120초)을 넘으면 읽은 만큼 낸다.
|
|
151
|
+
if (report.kind) {
|
|
152
|
+
const { buildReport, collectReport, formatReport, progressWriter, reportJson, MAX_DAYS } = await import('../src/report.mjs');
|
|
153
|
+
const { flushCache } = await import('../src/cache.mjs');
|
|
154
|
+
if (report.capped) process.stderr.write(`aitop: ${t('report.capped', { n: MAX_DAYS })}\n`);
|
|
155
|
+
const progress = progressWriter();
|
|
156
|
+
const maxMs = Number(process.env.AITOP_REPORT_MS) > 0 ? Number(process.env.AITOP_REPORT_MS) : undefined;
|
|
157
|
+
const now = Date.now();
|
|
158
|
+
const got = await collectReport({ days: report.days, maxMs, now, onProgress: progress.update });
|
|
159
|
+
progress.done();
|
|
160
|
+
flushCache();
|
|
161
|
+
if (got.partial && args.has('--json')) process.stderr.write(`aitop: ${t('report.partial')}\n`);
|
|
162
|
+
const r = buildReport(got.books, { by: report.by, days: report.days, now });
|
|
163
|
+
const text = args.has('--json') ? JSON.stringify(reportJson(r, VERSION, { partial: got.partial }), null, 2) : formatReport(r, { partial: got.partial });
|
|
164
|
+
process.stdout.on('error', (err) => process.exit(err.code === 'EPIPE' ? 0 : 1));
|
|
165
|
+
await new Promise((resolve) => process.stdout.write(text + '\n', resolve));
|
|
166
|
+
process.exit(0);
|
|
167
|
+
}
|
|
168
|
+
|
|
142
169
|
// 파이프나 파일로 받을 때는 색 코드를 넣지 않는다. 화면 모듈이 불러올 때 NO_COLOR 를 읽으므로 그 전에 정한다.
|
|
143
170
|
const forced = process.env.FORCE_COLOR != null && !['', '0', 'false'].includes(process.env.FORCE_COLOR);
|
|
144
171
|
if (!process.stdout.isTTY && !forced && !process.env.NO_COLOR) process.env.NO_COLOR = '1';
|
package/package.json
CHANGED
package/src/cache.mjs
CHANGED
|
@@ -8,7 +8,8 @@ import { PRICE_TAG } from './pricing.mjs';
|
|
|
8
8
|
import { debug, debugIo } from './log.mjs';
|
|
9
9
|
|
|
10
10
|
// 캐시 형식이 바뀌면 VERSION 을, 가격표가 바뀌면 PRICE_TAG 가 폴더 이름을 바꿔서 예전 캐시를 버린다.
|
|
11
|
-
|
|
11
|
+
// 14: 장부의 하루 합계에 모델별 몫(models)을 더하고, 날짜를 10일이 아니라 30일 남긴다 (#128).
|
|
12
|
+
const VERSION = 14;
|
|
12
13
|
const ROOT = join(process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'aitop');
|
|
13
14
|
const NAME = `v${VERSION}-${PRICE_TAG}`;
|
|
14
15
|
const DIR = join(ROOT, NAME);
|
package/src/i18n.mjs
CHANGED
|
@@ -65,6 +65,8 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
|
|
|
65
65
|
--line=tmux 는 tmux 색 서식(#[fg=...])을 넣는다. --line-width <N> 폭 상한(기본 40, 넘으면 뒤 항목부터 뺀다)
|
|
66
66
|
장부 캐시만 읽는다. 캐시가 없어 1.5초 안에 못 읽으면 ... 을 낸다. 응답 대기 수는 Claude Code 세션만 센다
|
|
67
67
|
aitop --json 세션 목록과 사용량 합계를 JSON 으로 한 번 출력한다 (--all 과 함께 쓸 수 있다)
|
|
68
|
+
aitop --report daily [--by tool|model] [--days N] [--json] 최근 N일(기본·최대 30)의 날짜별 토큰·비용(API 정가 환산)을
|
|
69
|
+
도구별 또는 모델별 표로 내고 끝낸다. 최근 날짜가 위, 맨 아래는 합계. 처음 실행은 30일치 기록을 읽느라 오래 걸릴 수 있다
|
|
68
70
|
aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
|
|
69
71
|
aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
|
|
70
72
|
aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (notify-send · osascript, 없으면 건너뜀)
|
|
@@ -103,6 +105,8 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
|
|
|
103
105
|
--line=tmux adds tmux colors (#[fg=...]). --line-width <N> sets the max width (default 40, drops items from the end)
|
|
104
106
|
Reads only the cache. With no cache it prints ... after 1.5 seconds. The waiting count covers Claude Code sessions only
|
|
105
107
|
aitop --json print the session list and usage totals as JSON once (works with --all)
|
|
108
|
+
aitop --report daily [--by tool|model] [--days N] [--json] print daily tokens and cost (API list price) for the last N days
|
|
109
|
+
(default and max 30) by tool or by model, then exit. Newest day first, total at the bottom. The first run reads 30 days of logs and may take a while
|
|
106
110
|
aitop --doctor check Claude, Codex, Antigravity and Gemini logs, running processes and the config file (works with --json)
|
|
107
111
|
aitop --bell ring the terminal bell when a session starts waiting for you
|
|
108
112
|
aitop --notify show a desktop notification when a session starts waiting (notify-send or osascript, skipped if missing)
|
|
@@ -187,6 +191,25 @@ export const STRINGS = {
|
|
|
187
191
|
'opt.lineBad': '--line 값 {value} 이 잘못되었습니다 (plain 또는 tmux)',
|
|
188
192
|
'opt.lineWidthMissing': '--line-width 값이 없습니다 (글자 수)',
|
|
189
193
|
'opt.lineWidthBad': '--line-width 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
|
|
194
|
+
'opt.reportMissing': '--report 값이 없습니다 (daily)',
|
|
195
|
+
'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily)',
|
|
196
|
+
'opt.byMissing': '--by 값이 없습니다 (tool 또는 model)',
|
|
197
|
+
'opt.byBad': '--by 값 {value} 이 잘못되었습니다 (tool 또는 model)',
|
|
198
|
+
'opt.daysMissing': '--days 값이 없습니다 (일 수)',
|
|
199
|
+
'opt.daysBad': '--days 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
|
|
200
|
+
'opt.reportOnly': '--by, --days 는 --report 와 함께 쓴다',
|
|
201
|
+
|
|
202
|
+
// 기간 리포트 (--report daily). 도구·모델 이름은 번역하지 않는다.
|
|
203
|
+
'report.title': '날짜별 사용량 · 최근 {n}일 ({from} ~ {to}) · {by} · API 정가 환산',
|
|
204
|
+
'report.by.tool': '도구별',
|
|
205
|
+
'report.by.model': '모델별',
|
|
206
|
+
'report.date': '날짜',
|
|
207
|
+
'report.total': '합계',
|
|
208
|
+
'report.empty': '이 기간에 기록된 사용량이 없습니다',
|
|
209
|
+
'report.unpriced': '? 가격표에 없는 모델이 있어 비용이 실제보다 적게 잡혔을 수 있습니다',
|
|
210
|
+
'report.partial': '시간 상한 안에 기록을 다 읽지 못해 일부만 셌습니다. 다시 실행하면 이어 읽습니다',
|
|
211
|
+
'report.progress': '사용량 장부 읽는 중 {pct}% ({s}초)',
|
|
212
|
+
'report.capped': '--days 는 장부가 남기는 {n}일까지만 볼 수 있어 {n}일로 줄입니다',
|
|
190
213
|
|
|
191
214
|
'cfg.notFile': '설정 파일이 일반 파일이 아니라 읽지 않습니다',
|
|
192
215
|
'cfg.tooBig': '설정 파일이 {kb}KB 를 넘어 읽지 않습니다',
|
|
@@ -511,6 +534,24 @@ export const STRINGS = {
|
|
|
511
534
|
'opt.lineBad': 'bad --line value {value} (plain or tmux)',
|
|
512
535
|
'opt.lineWidthMissing': '--line-width needs a value (characters)',
|
|
513
536
|
'opt.lineWidthBad': 'bad --line-width value {value} (a whole number above 0)',
|
|
537
|
+
'opt.reportMissing': '--report needs a value (daily)',
|
|
538
|
+
'opt.reportBad': 'bad --report value {value} (daily)',
|
|
539
|
+
'opt.byMissing': '--by needs a value (tool or model)',
|
|
540
|
+
'opt.byBad': 'bad --by value {value} (tool or model)',
|
|
541
|
+
'opt.daysMissing': '--days needs a value (number of days)',
|
|
542
|
+
'opt.daysBad': 'bad --days value {value} (a whole number above 0)',
|
|
543
|
+
'opt.reportOnly': '--by and --days only work with --report',
|
|
544
|
+
|
|
545
|
+
'report.title': 'Daily usage, last {n} days ({from} to {to}), {by}, API list price',
|
|
546
|
+
'report.by.tool': 'by tool',
|
|
547
|
+
'report.by.model': 'by model',
|
|
548
|
+
'report.date': 'Date',
|
|
549
|
+
'report.total': 'Total',
|
|
550
|
+
'report.empty': 'No usage recorded in this period',
|
|
551
|
+
'report.unpriced': '? includes unpriced models, so the cost may be lower than actual',
|
|
552
|
+
'report.partial': 'Could not read all logs within the time limit, so this is partial. Run again to continue',
|
|
553
|
+
'report.progress': 'Reading usage logs {pct}% ({s}s)',
|
|
554
|
+
'report.capped': '--days is limited to the {n} days the ledger keeps, using {n}',
|
|
514
555
|
|
|
515
556
|
'cfg.notFile': 'config file is not a regular file, not reading it',
|
|
516
557
|
'cfg.tooBig': 'config file is over {kb}KB, not reading it',
|
package/src/pricing.mjs
CHANGED
|
@@ -94,23 +94,45 @@ export function claudeCost(model, u) {
|
|
|
94
94
|
|
|
95
95
|
// Codex(OpenAI) API 정가 기준 환산 비용 (USD / 100만 토큰). Claude 와 같이 "API 로 썼다면" 기준이다.
|
|
96
96
|
// 출처: OpenAI 공식 가격표 https://developers.openai.com/api/docs/pricing 와 모델별 문서
|
|
97
|
-
//
|
|
98
|
-
//
|
|
97
|
+
// https://developers.openai.com/api/docs/models/<모델 이름> (2026-11-11 확인, 표의 모든 모델이 공식 값과 같다).
|
|
98
|
+
// cacheRead 는 cached input 가격이다. gpt-5.1-codex, gpt-5.1-codex-max, gpt-5-codex 는 가격표에는 없고 모델별 문서에만 있다
|
|
99
|
+
// (세 모델 모두 지원 종료). gpt-5.6-sol 값은 2026-11-30 까지의 프로모션 가격이며, 그 뒤 가격은 아직 공개되지 않았다.
|
|
100
|
+
// 긴 컨텍스트 단가(입력 272K 초과 요청은 입력 2배·출력 1.5배, gpt-5.6-*, gpt-5.5, gpt-5.4)는 반영하지 않는다:
|
|
101
|
+
// 세션 누적 토큰만으로는 요청마다 272K 를 넘었는지 알 수 없어서, 모두 기본 단가로 계산한다.
|
|
102
|
+
// 컨텍스트 창은 Codex 기록의 model_context_window 를 그대로 쓰므로 WINDOWS 표에 넣지 않는다.
|
|
99
103
|
const OPENAI_PRICES = {
|
|
104
|
+
'gpt-5.6-sol': { input: 4, cacheRead: 0.4, output: 20 },
|
|
105
|
+
'gpt-5.6-terra': { input: 2, cacheRead: 0.2, output: 12 },
|
|
106
|
+
'gpt-5.6-luna': { input: 0.2, cacheRead: 0.02, output: 1.2 },
|
|
107
|
+
'gpt-5.5': { input: 5, cacheRead: 0.5, output: 30 },
|
|
108
|
+
'gpt-5.4': { input: 2.5, cacheRead: 0.25, output: 15 },
|
|
109
|
+
'gpt-5.4-mini': { input: 0.75, cacheRead: 0.075, output: 4.5 },
|
|
100
110
|
'gpt-5.3-codex': { input: 1.75, cacheRead: 0.175, output: 14 },
|
|
111
|
+
'gpt-5.2': { input: 1.75, cacheRead: 0.175, output: 14 },
|
|
112
|
+
'gpt-5.1-codex-max': { input: 1.25, cacheRead: 0.125, output: 10 },
|
|
101
113
|
'gpt-5.1-codex-mini': { input: 0.25, cacheRead: 0.025, output: 2 },
|
|
102
114
|
'gpt-5.1-codex': { input: 1.25, cacheRead: 0.125, output: 10 },
|
|
115
|
+
'gpt-5-codex': { input: 1.25, cacheRead: 0.125, output: 10 },
|
|
116
|
+
'gpt-5-mini': { input: 0.25, cacheRead: 0.025, output: 2 },
|
|
117
|
+
'gpt-5': { input: 1.25, cacheRead: 0.125, output: 10 },
|
|
103
118
|
'codex-mini': { input: 1.5, cacheRead: 0.375, output: 6 },
|
|
104
119
|
'gpt-4o-mini': { input: 0.15, cacheRead: 0.075, output: 0.6 },
|
|
105
120
|
};
|
|
106
121
|
|
|
122
|
+
// Codex 모델 가격. 이름이 표와 똑같을 때, 또는 끝의 -latest 나 날짜(-2025-08-07)만 뗐을 때 표와 똑같을 때만 찾는다.
|
|
123
|
+
// 앞부분만 같은 다른 모델(gpt-5.5-pro 와 gpt-5.5, gpt-5.4-nano 와 gpt-5.4 등)에 엉뚱한 가격을 매기지 않기 위해서다.
|
|
124
|
+
export function openaiPrice(model) {
|
|
125
|
+
if (!model) return null;
|
|
126
|
+
return OPENAI_PRICES[model] ?? OPENAI_PRICES[model.replace(/-(latest|\d{4}-\d{2}-\d{2})$/, '')] ?? null;
|
|
127
|
+
}
|
|
128
|
+
|
|
107
129
|
// 가격표가 바뀌면 이 값이 바뀌고, 캐시 폴더도 바뀌어 예전 비용이 다시 계산된다. 세 표(Claude, Gemini, Codex)를 모두 넣는다.
|
|
108
130
|
export const PRICE_TABLES = [PRICES, GEMINI_PRICES, OPENAI_PRICES];
|
|
109
131
|
export const PRICE_TAG = priceTag(PRICE_TABLES);
|
|
110
132
|
|
|
111
133
|
// Codex 세션 누적 토큰(tokens: input 은 캐시 제외, cacheRead, output)의 환산 비용. 가격표에 없는 모델이면 null.
|
|
112
134
|
export function codexCost(model, t) {
|
|
113
|
-
const p =
|
|
135
|
+
const p = openaiPrice(model);
|
|
114
136
|
if (!p || !t) return null;
|
|
115
137
|
const base = (t.input ?? 0) * p.input + (t.output ?? 0) * p.output;
|
|
116
138
|
return { total: (base + (t.cacheRead ?? 0) * p.cacheRead) / 1e6, noCache: base / 1e6 };
|
package/src/report.mjs
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// aitop --report daily: 최근 N일(기본 30, 최대 30)의 날짜별 토큰·비용을 도구별 또는 모델별 표로 내고 끝낸다 (실시간 화면 없음).
|
|
2
|
+
// 값은 날짜별 사용량 장부(claude-ledger.mjs 의 collectDaily)에서 오고, 비용은 화면 헤더와 같은 API 정가 환산이다.
|
|
3
|
+
// 줄은 최근 날짜가 위(오늘부터 거꾸로)이고, 맨 아래 합계 줄은 위 날짜 줄을 더한 값이다. --json 도 같은 값을 숫자로만 낸다.
|
|
4
|
+
// 처음 읽는 동안 stderr 가 터미널이면 진행률을 보이고, 시간 상한을 넘으면 읽은 만큼으로 표를 내고 덜 읽었다고 알린다.
|
|
5
|
+
import { t } from './i18n.mjs';
|
|
6
|
+
import { fmtTokens, pad, stripControl, width } from './text.mjs';
|
|
7
|
+
import { money } from './line.mjs';
|
|
8
|
+
import { KEEP_DAYS, lastDays } from './sources/common.mjs';
|
|
9
|
+
|
|
10
|
+
export const KINDS = ['daily'];
|
|
11
|
+
export const BY = ['tool', 'model'];
|
|
12
|
+
export const MAX_DAYS = KEEP_DAYS;
|
|
13
|
+
export const DEFAULT_DAYS = KEEP_DAYS;
|
|
14
|
+
// 전체 시간 상한. 넘으면 읽은 만큼으로 표를 낸다 (캐시에 남은 만큼은 다음 실행이 이어 읽는다).
|
|
15
|
+
export const MAX_MS = 120_000;
|
|
16
|
+
// 한 번에 읽는 시간. 이만큼마다 진행률을 고치고 캐시를 저장한다.
|
|
17
|
+
const STEP_MS = 250;
|
|
18
|
+
// 이보다 오래 걸릴 때만 진행률을 보인다 (캐시가 있는 실행에서 깜빡이지 않게).
|
|
19
|
+
const PROGRESS_AFTER_MS = 400;
|
|
20
|
+
const FLUSH_MS = 3000;
|
|
21
|
+
const TOOLS = ['claude', 'codex', 'agy'];
|
|
22
|
+
|
|
23
|
+
// --report <kind>, --report=<kind>, --by <tool|model>, --by=..., --days <N>, --days=<N> 를 꺼낸다.
|
|
24
|
+
// kind 는 --report 를 주지 않았으면 null. --by·--days 는 --report 와 함께일 때만 받는다. capped: --days 를 30으로 줄였는지.
|
|
25
|
+
export function reportOption(argv) {
|
|
26
|
+
let kind = null;
|
|
27
|
+
let by = 'tool';
|
|
28
|
+
let days = DEFAULT_DAYS;
|
|
29
|
+
let capped = false;
|
|
30
|
+
let error = null;
|
|
31
|
+
let extra = false;
|
|
32
|
+
const rest = [];
|
|
33
|
+
for (let i = 0; i < argv.length; i++) {
|
|
34
|
+
const a = argv[i];
|
|
35
|
+
const m = /^--(report|by|days)(?:=(.*))?$/.exec(a);
|
|
36
|
+
if (!m) {
|
|
37
|
+
rest.push(a);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
const name = m[1];
|
|
41
|
+
const raw = m[2] ?? (argv[i + 1] == null || argv[i + 1].startsWith('-') ? '' : argv[++i]);
|
|
42
|
+
if (name === 'report') {
|
|
43
|
+
if (KINDS.includes(raw)) kind = raw;
|
|
44
|
+
else error ??= raw === '' ? t('opt.reportMissing') : t('opt.reportBad', { value: JSON.stringify(raw) });
|
|
45
|
+
} else if (name === 'by') {
|
|
46
|
+
extra = true;
|
|
47
|
+
if (BY.includes(raw)) by = raw;
|
|
48
|
+
else error ??= raw === '' ? t('opt.byMissing') : t('opt.byBad', { value: JSON.stringify(raw) });
|
|
49
|
+
} else {
|
|
50
|
+
extra = true;
|
|
51
|
+
const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
|
|
52
|
+
if (n > 0) {
|
|
53
|
+
capped = n > MAX_DAYS;
|
|
54
|
+
days = Math.min(n, MAX_DAYS);
|
|
55
|
+
} else error ??= raw === '' ? t('opt.daysMissing') : t('opt.daysBad', { value: JSON.stringify(raw) });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (!error && extra && !kind) error = t('opt.reportOnly');
|
|
59
|
+
return { kind, by, days, capped, rest, error };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const zero = () => ({ tokens: 0, cost: 0, unpriced: false });
|
|
63
|
+
// unpriced: 가격표에 없는 모델이 끼어 이 칸의 비용이 실제보다 적을 수 있는지.
|
|
64
|
+
const add = (a, tokens, cost, unpriced) => {
|
|
65
|
+
a.tokens += tokens;
|
|
66
|
+
a.cost += cost;
|
|
67
|
+
if (unpriced) a.unpriced = true;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
// books: collectDaily 의 [{ tool, days }]. 최근 days 일의 날짜 줄(오늘부터 거꾸로)과 열(도구 또는 모델), 합계를 만든다.
|
|
71
|
+
// 열은 기간 합계 비용이 큰 순서(같으면 토큰, 이름 순)이고, 기간 안에 토큰이 하나도 없는 열은 뺀다.
|
|
72
|
+
// unpriced: 가격표에 없는 모델이 끼어 비용이 실제보다 적게 잡혔을 수 있는지.
|
|
73
|
+
export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Date.now() } = {}) {
|
|
74
|
+
const dates = lastDays(days, now);
|
|
75
|
+
const rows = dates.map((date) => ({ date, tokens: 0, cost: 0, unpriced: false, items: {} }));
|
|
76
|
+
const at = new Map(rows.map((r) => [r.date, r]));
|
|
77
|
+
const total = { tokens: 0, cost: 0, unpriced: false, items: {} };
|
|
78
|
+
let unpriced = false;
|
|
79
|
+
for (const { tool, days: book } of books) {
|
|
80
|
+
for (const [date, d] of Object.entries(book ?? {})) {
|
|
81
|
+
const row = at.get(date);
|
|
82
|
+
if (!row) continue;
|
|
83
|
+
if (d.unknown) unpriced = true;
|
|
84
|
+
const parts = by === 'model' ? Object.entries(d.models ?? {}) : [[tool, d]];
|
|
85
|
+
for (const [name, x] of parts) {
|
|
86
|
+
add((row.items[name] ??= zero()), x.tokens, x.cost, x.unknown);
|
|
87
|
+
add((total.items[name] ??= zero()), x.tokens, x.cost, x.unknown);
|
|
88
|
+
}
|
|
89
|
+
add(row, d.tokens, d.cost, d.unknown);
|
|
90
|
+
add(total, d.tokens, d.cost, d.unknown);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const rank = (name) => (by === 'tool' ? TOOLS.indexOf(name) : 0);
|
|
94
|
+
const columns = Object.entries(total.items)
|
|
95
|
+
.filter(([, x]) => x.tokens > 0 || x.cost > 0)
|
|
96
|
+
.sort(([a, x], [b, y]) => y.cost - x.cost || y.tokens - x.tokens || rank(a) - rank(b) || a.localeCompare(b))
|
|
97
|
+
.map(([name]) => name);
|
|
98
|
+
return { report: 'daily', by, days, from: dates.at(-1), to: dates[0], columns, rows, total, unpriced };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// --json 모양: 키는 영어, 값은 숫자만 (날짜·이름은 문자열). partial: 시간 상한 때문에 덜 읽었는지.
|
|
102
|
+
// 칸마다 unpriced(가격표에 없는 모델이 끼었는지)를 참·거짓으로 둔다. 화면의 ? 와 같은 뜻이다.
|
|
103
|
+
export function reportJson(r, version, { partial = false } = {}) {
|
|
104
|
+
const items = (o) => Object.fromEntries(r.columns.map((c) => [c, { tokens: o.items[c]?.tokens ?? 0, cost: o.items[c]?.cost ?? 0, unpriced: Boolean(o.items[c]?.unpriced) }]));
|
|
105
|
+
return {
|
|
106
|
+
version,
|
|
107
|
+
report: r.report,
|
|
108
|
+
by: r.by,
|
|
109
|
+
days: r.days,
|
|
110
|
+
from: r.from,
|
|
111
|
+
to: r.to,
|
|
112
|
+
basis: 'api',
|
|
113
|
+
partial,
|
|
114
|
+
unpriced: r.unpriced,
|
|
115
|
+
columns: r.columns,
|
|
116
|
+
rows: r.rows.map((x) => ({ date: x.date, tokens: x.tokens, cost: x.cost, unpriced: x.unpriced, items: items(x) })),
|
|
117
|
+
total: { tokens: r.total.tokens, cost: r.total.cost, unpriced: r.total.unpriced, items: items(r.total) },
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// 칸 하나: '1.2M $3.40'. 토큰이 없으면 '-'. 가격표에 없는 모델이 끼었으면 화면 헤더처럼 비용 뒤에 ? 를 붙인다 ('$12.30?').
|
|
122
|
+
const cell = (x) => (x && (x.tokens > 0 || x.cost > 0) ? `${fmtTokens(Math.round(x.tokens))} ${money(x.cost)}${x.unpriced ? '?' : ''}` : '-');
|
|
123
|
+
|
|
124
|
+
// 사람이 읽는 표. 머리글·합계 줄 문구는 화면 언어(t)를 따른다. 도구 이름과 모델 이름은 그대로 쓴다.
|
|
125
|
+
export function formatReport(r, { partial = false } = {}) {
|
|
126
|
+
// 모델 이름은 기록에서 온 글이라 제어문자를 지운다.
|
|
127
|
+
const head = [t('report.date'), ...r.columns.map((c) => stripControl(c)), t('report.total')];
|
|
128
|
+
const line = (label, o) => [label, ...r.columns.map((c) => cell(o.items[c])), cell(o)];
|
|
129
|
+
const body = r.rows.map((x) => line(x.date, x));
|
|
130
|
+
const foot = line(t('report.total'), r.total);
|
|
131
|
+
const all = [head, ...body, foot];
|
|
132
|
+
const w = head.map((_, i) => Math.max(...all.map((row) => width(row[i]))));
|
|
133
|
+
const fmt = (row) => row.map((s, i) => pad(s, w[i], i === 0 ? 'left' : 'right')).join(' ').trimEnd();
|
|
134
|
+
const rule = w.map((n) => '-'.repeat(n)).join(' ');
|
|
135
|
+
const out = [t('report.title', { n: r.days, by: t(`report.by.${r.by}`), from: r.from, to: r.to }), '', fmt(head), rule, ...body.map(fmt), rule, fmt(foot)];
|
|
136
|
+
if (!r.columns.length) out.push('', t('report.empty'));
|
|
137
|
+
if (r.unpriced) out.push('', t('report.unpriced'));
|
|
138
|
+
if (partial) out.push('', t('report.partial'));
|
|
139
|
+
return out.join('\n');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// 장부를 끝까지(또는 시간 상한까지) 읽는다. 짧게 나눠 읽으며 진행률을 onProgress(0~1, 지난 ms)로 알리고 캐시를 저장한다.
|
|
143
|
+
// 돌려주는 값: { books, partial }. partial 이면 시간 상한 때문에 덜 읽은 기록이 있다.
|
|
144
|
+
export async function collectReport({ days = DEFAULT_DAYS, maxMs = MAX_MS, now = Date.now(), onProgress = () => {} } = {}) {
|
|
145
|
+
const { createBudget } = await import('./tail.mjs');
|
|
146
|
+
const { collectDaily } = await import('./sources/claude-ledger.mjs');
|
|
147
|
+
const { flushCache } = await import('./cache.mjs');
|
|
148
|
+
const start = Date.now();
|
|
149
|
+
let lastFlush = start;
|
|
150
|
+
for (;;) {
|
|
151
|
+
const budget = createBudget(Infinity, STEP_MS);
|
|
152
|
+
const r = collectDaily({ budget, now, days });
|
|
153
|
+
const spent = Date.now() - start;
|
|
154
|
+
if (!budget.exhausted) return { books: r.books, partial: false };
|
|
155
|
+
onProgress(r.size ? 1 - r.pending / r.size : 0, spent);
|
|
156
|
+
if (Date.now() - lastFlush > FLUSH_MS) {
|
|
157
|
+
flushCache();
|
|
158
|
+
lastFlush = Date.now();
|
|
159
|
+
}
|
|
160
|
+
if (spent >= maxMs) return { books: r.books, partial: true };
|
|
161
|
+
// 다른 일(신호 처리 등)이 돌 틈을 준다.
|
|
162
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// stderr 진행률. 터미널일 때만, 처음 PROGRESS_AFTER_MS 가 지난 뒤부터 같은 줄을 고쳐 쓴다. done() 은 그 줄을 지운다.
|
|
167
|
+
export function progressWriter(stream = process.stderr) {
|
|
168
|
+
let shown = false;
|
|
169
|
+
return {
|
|
170
|
+
update(ratio, ms) {
|
|
171
|
+
if (!stream.isTTY || ms < PROGRESS_AFTER_MS) return;
|
|
172
|
+
shown = true;
|
|
173
|
+
stream.write(`\r\x1b[2K${t('report.progress', { pct: Math.floor(Math.max(0, Math.min(1, ratio)) * 100), s: Math.round(ms / 1000) })}`);
|
|
174
|
+
},
|
|
175
|
+
done() {
|
|
176
|
+
if (shown) stream.write('\r\x1b[2K');
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
}
|
|
@@ -7,16 +7,16 @@ import { join } from 'node:path';
|
|
|
7
7
|
import { AGY_ROOT, readCalls, sigOf, maxIdx } from './antigravity.mjs';
|
|
8
8
|
import { openReadOnly, loadSqlite } from '../sqlite.mjs';
|
|
9
9
|
import { loadCache, markDirty } from '../cache.mjs';
|
|
10
|
-
import { dayKey, lastDays, addSlot } from './common.mjs';
|
|
10
|
+
import { dayKey, lastDays, addSlot, addModel, KEEP_DAYS } from './common.mjs';
|
|
11
11
|
import { debugIo } from '../log.mjs';
|
|
12
12
|
|
|
13
13
|
const KIND = 'agy-ledger';
|
|
14
14
|
const DAYS = 7;
|
|
15
|
-
const KEEP_DAYS = 10;
|
|
16
15
|
const LIST_TTL_MS = 30_000;
|
|
17
16
|
|
|
18
17
|
const outOf = (budget) => budget.left <= 0 || (budget.read > 0 && Date.now() >= (budget.deadline ?? Infinity));
|
|
19
|
-
|
|
18
|
+
// 하루 합계 안의 모델별 몫도 따로 복사해, 읽다가 버릴 때 원래 장부가 바뀌지 않게 한다.
|
|
19
|
+
const copyDays = (days) => Object.fromEntries(Object.entries(days).map(([k, v]) => [k, v.models ? { ...v, models: Object.fromEntries(Object.entries(v.models).map(([m, x]) => [m, { ...x }])) } : { ...v }]));
|
|
20
20
|
|
|
21
21
|
export class AgyBook {
|
|
22
22
|
constructor(path) {
|
|
@@ -67,12 +67,13 @@ export class AgyBook {
|
|
|
67
67
|
// 마지막 줄 번호가 줄었으면 기록이 새로 쓰인 것이니 처음부터 다시 센다.
|
|
68
68
|
if (last < n.idx) n = { idx: -1, model: null, days: {}, slots: {} };
|
|
69
69
|
result = has
|
|
70
|
-
? readCalls(db, n, last, budget, mtime, ({ usage: u, cost, at }) => {
|
|
70
|
+
? readCalls(db, n, last, budget, mtime, ({ model, usage: u, cost, at }) => {
|
|
71
71
|
const day = (n.days[dayKey(at)] ??= { tokens: 0, cost: 0, costNoCache: 0, unknown: false });
|
|
72
72
|
const tokens = u.input + u.output + u.cacheRead + u.cacheWrite;
|
|
73
73
|
day.tokens += tokens;
|
|
74
74
|
day.cost += cost?.total ?? 0;
|
|
75
75
|
day.costNoCache += cost?.noCache ?? 0;
|
|
76
|
+
addModel(day, model, tokens, cost?.total ?? 0, !cost && tokens > 0);
|
|
76
77
|
if (!cost && tokens > 0) day.unknown = true;
|
|
77
78
|
addSlot(n.slots, at, cost?.total ?? 0, cost?.noCache ?? 0, !cost && tokens > 0);
|
|
78
79
|
})
|
|
@@ -103,12 +104,13 @@ export class AgyBook {
|
|
|
103
104
|
}
|
|
104
105
|
}
|
|
105
106
|
|
|
106
|
-
let listed = { at: 0, files: [] };
|
|
107
|
+
let listed = { at: 0, files: [], days: 0 };
|
|
107
108
|
|
|
108
|
-
|
|
109
|
-
|
|
109
|
+
// 최근 days 일(평소 7일, 리포트는 더 길게) 안에 바뀐 대화 기록.
|
|
110
|
+
function recentFiles(days = DAYS) {
|
|
111
|
+
if (listed.days === days && Date.now() - listed.at < LIST_TTL_MS) return listed.files;
|
|
110
112
|
const dir = join(AGY_ROOT, 'conversations');
|
|
111
|
-
const cutoff = Date.now() -
|
|
113
|
+
const cutoff = Date.now() - days * 86400_000;
|
|
112
114
|
const files = [];
|
|
113
115
|
let names = [];
|
|
114
116
|
try {
|
|
@@ -123,7 +125,7 @@ function recentFiles() {
|
|
|
123
125
|
if (statSync(p).mtimeMs >= cutoff) files.push(p);
|
|
124
126
|
} catch {}
|
|
125
127
|
}
|
|
126
|
-
listed = { at: Date.now(), files };
|
|
128
|
+
listed = { at: Date.now(), files, days };
|
|
127
129
|
return files;
|
|
128
130
|
}
|
|
129
131
|
|
|
@@ -131,10 +133,10 @@ const books = new Map();
|
|
|
131
133
|
|
|
132
134
|
// 대화마다 날짜별 합계(days)와 5분 칸(slots), 처음 읽기가 덜 끝난 기록의 크기(pending)·전체 크기(size).
|
|
133
135
|
// node:sqlite 를 못 쓰는 Node 에서는 비어 있다 (agy 는 프로세스만 보인다).
|
|
134
|
-
export function collectAgyLedger({ budget } = {}) {
|
|
136
|
+
export function collectAgyLedger({ budget, days = DAYS } = {}) {
|
|
135
137
|
const out = { days: [], slots: [], pending: 0, size: 0 };
|
|
136
138
|
if (!loadSqlite() || !existsSync(join(AGY_ROOT, 'conversations'))) return out;
|
|
137
|
-
const files = recentFiles();
|
|
139
|
+
const files = recentFiles(days);
|
|
138
140
|
const keep = new Set(files);
|
|
139
141
|
for (const p of books.keys()) if (!keep.has(p)) books.delete(p);
|
|
140
142
|
for (const p of files) {
|
|
@@ -150,4 +152,4 @@ export function collectAgyLedger({ budget } = {}) {
|
|
|
150
152
|
return out;
|
|
151
153
|
}
|
|
152
154
|
|
|
153
|
-
export const _test = { reset: () => ((listed = { at: 0, files: [] }), books.clear()) };
|
|
155
|
+
export const _test = { reset: () => ((listed = { at: 0, files: [], days: 0 }), books.clear()) };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// 날짜별 사용량 장부: 최근 7일 안에 바뀐 Claude 기록(서브에이전트 포함)에서 사용량만
|
|
1
|
+
// 날짜별 사용량 장부: 최근 7일 안에 바뀐 Claude 기록(서브에이전트 포함)에서 사용량만 날짜별·모델별로 모은다.
|
|
2
|
+
// 기간 리포트(--report)는 같은 장부를 최근 N일(최대 30일) 안에 바뀐 기록까지 넓혀 읽는다 (collectDaily).
|
|
2
3
|
// Antigravity CLI(agy)·Codex CLI 사용량은 agy-ledger.mjs·codex-ledger.mjs 가 같은 모양으로 모으고, 여기서 함께 더한다.
|
|
3
4
|
// 세션 화면과 상관없이 끝난 세션까지 세야 해서, 세션 tracker 와 따로 가볍게 읽고 캐시도 따로 둔다.
|
|
4
5
|
import { readdirSync, statSync, existsSync } from 'node:fs';
|
|
@@ -7,7 +8,7 @@ import { homedir } from 'node:os';
|
|
|
7
8
|
import { JsonlTail } from '../tail.mjs';
|
|
8
9
|
import { loadCache, markDirty } from '../cache.mjs';
|
|
9
10
|
import { claudeCost } from '../pricing.mjs';
|
|
10
|
-
import { dayKey, lastDays, addSlot, lastHourOf, recentTodayOf } from './common.mjs';
|
|
11
|
+
import { dayKey, lastDays, addSlot, addModel, lastHourOf, recentTodayOf, KEEP_DAYS } from './common.mjs';
|
|
11
12
|
import { collectAgyLedger } from './agy-ledger.mjs';
|
|
12
13
|
import { collectCodexLedger } from './codex-ledger.mjs';
|
|
13
14
|
import { debugIo } from '../log.mjs';
|
|
@@ -18,7 +19,6 @@ const HOME = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
|
|
|
18
19
|
const PROJECTS = join(HOME, 'projects');
|
|
19
20
|
const KIND = 'ledger';
|
|
20
21
|
const DAYS = 7;
|
|
21
|
-
const KEEP_DAYS = 10;
|
|
22
22
|
const LIST_TTL_MS = 30_000;
|
|
23
23
|
const RECENT_IDS = 64;
|
|
24
24
|
const LOADING_MIN_BYTES = 4 * 1024 * 1024;
|
|
@@ -74,8 +74,10 @@ export class UsageTracker {
|
|
|
74
74
|
const dCost = (cost?.total ?? 0) - (prev?.cost ?? 0);
|
|
75
75
|
const dNoCache = (cost?.noCache ?? 0) - (prev?.costNoCache ?? 0);
|
|
76
76
|
const unknown = !cost && tokensOf(u) > 0;
|
|
77
|
-
|
|
77
|
+
const dTokens = tokensOf(u) - tokensOf(prev?.u);
|
|
78
|
+
day.tokens += dTokens;
|
|
78
79
|
day.cost += dCost;
|
|
80
|
+
addModel(day, m.model, dTokens, dCost, !cost && tokensOf(u) > 0);
|
|
79
81
|
day.costNoCache = (day.costNoCache ?? 0) + (cost?.noCache ?? 0) - (prev?.costNoCache ?? 0);
|
|
80
82
|
if (unknown) day.unknown = true;
|
|
81
83
|
addSlot(this.slots, at, dCost, dNoCache, unknown);
|
|
@@ -85,12 +87,12 @@ export class UsageTracker {
|
|
|
85
87
|
}
|
|
86
88
|
}
|
|
87
89
|
|
|
88
|
-
let listed = { at: 0, files: [] };
|
|
90
|
+
let listed = { at: 0, files: [], days: 0 };
|
|
89
91
|
|
|
90
|
-
// 최근 7일 안에 바뀐 메인 기록과 서브에이전트 기록.
|
|
91
|
-
function recentFiles() {
|
|
92
|
-
if (Date.now() - listed.at < LIST_TTL_MS) return listed.files;
|
|
93
|
-
const cutoff = Date.now() -
|
|
92
|
+
// 최근 days 일(평소 7일) 안에 바뀐 메인 기록과 서브에이전트 기록.
|
|
93
|
+
function recentFiles(days = DAYS) {
|
|
94
|
+
if (listed.days === days && Date.now() - listed.at < LIST_TTL_MS) return listed.files;
|
|
95
|
+
const cutoff = Date.now() - days * 86400_000;
|
|
94
96
|
const files = [];
|
|
95
97
|
const add = (p) => {
|
|
96
98
|
try {
|
|
@@ -121,15 +123,15 @@ function recentFiles() {
|
|
|
121
123
|
}
|
|
122
124
|
}
|
|
123
125
|
}
|
|
124
|
-
listed = { at: Date.now(), files };
|
|
126
|
+
listed = { at: Date.now(), files, days };
|
|
125
127
|
return files;
|
|
126
128
|
}
|
|
127
129
|
|
|
128
130
|
const trackers = new Map();
|
|
129
131
|
|
|
130
|
-
//
|
|
131
|
-
|
|
132
|
-
const files = recentFiles();
|
|
132
|
+
// 최근 days 일 안에 바뀐 기록(Claude + agy + Codex)을 읽는다. books 는 기록마다 { tool, days }.
|
|
133
|
+
function gather({ budget, now, days = DAYS }) {
|
|
134
|
+
const files = recentFiles(days);
|
|
133
135
|
const keep = new Set(files);
|
|
134
136
|
for (const p of trackers.keys()) if (!keep.has(p)) trackers.delete(p);
|
|
135
137
|
let pending = 0;
|
|
@@ -141,15 +143,34 @@ export function collectLedger({ budget, now = Date.now() } = {}) {
|
|
|
141
143
|
pending += t.pending;
|
|
142
144
|
size += t.tail.size;
|
|
143
145
|
}
|
|
144
|
-
const others = [
|
|
145
|
-
|
|
146
|
+
const others = [
|
|
147
|
+
['agy', collectAgyLedger({ budget, now, days })],
|
|
148
|
+
['codex', collectCodexLedger({ budget, days })],
|
|
149
|
+
];
|
|
150
|
+
const books = [...trackers.values()].map((t) => ({ tool: 'claude', days: t.days }));
|
|
146
151
|
const slots = [...trackers.values()].map((t) => t.slots);
|
|
147
|
-
for (const o of others) {
|
|
152
|
+
for (const [tool, o] of others) {
|
|
148
153
|
pending += o.pending;
|
|
149
154
|
size += o.size;
|
|
150
|
-
books.push(...o.days);
|
|
155
|
+
books.push(...o.days.map((d) => ({ tool, days: d })));
|
|
151
156
|
slots.push(...o.slots);
|
|
152
157
|
}
|
|
158
|
+
return { books, slots, pending, size };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// 기간 리포트용: 최근 days 일(최대 KEEP_DAYS) 안에 바뀐 기록의 날짜별·모델별 장부.
|
|
162
|
+
// 평소 화면(collectLedger)은 7일 안에 바뀐 기록만 보므로, 이 함수를 부를 때만 더 오래된 기록을 읽는다.
|
|
163
|
+
export function collectDaily({ budget, now = Date.now(), days = KEEP_DAYS } = {}) {
|
|
164
|
+
const { books, pending, size } = gather({ budget, now, days: Math.max(DAYS, Math.min(KEEP_DAYS, days)) });
|
|
165
|
+
return { books, pending, size };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// 오늘·최근 7일·최근 1시간 합계 (Claude + agy + Codex). 아직 다 읽지 못했으면 loading 에 진행률(0~1).
|
|
169
|
+
export function collectLedger({ budget, now = Date.now() } = {}) {
|
|
170
|
+
const g = gather({ budget, now });
|
|
171
|
+
const { pending, size } = g;
|
|
172
|
+
const books = g.books.map((b) => b.days);
|
|
173
|
+
const slots = g.slots;
|
|
153
174
|
const sum = (keys) => {
|
|
154
175
|
const out = { tokens: 0, cost: 0, costNoCache: 0, unknown: false };
|
|
155
176
|
for (const days of books)
|
|
@@ -8,12 +8,11 @@ import { JsonlTail } from '../tail.mjs';
|
|
|
8
8
|
import { loadCache, markDirty } from '../cache.mjs';
|
|
9
9
|
import { codexCost } from '../pricing.mjs';
|
|
10
10
|
import { dayDirs } from './codex.mjs';
|
|
11
|
-
import { dayKey, lastDays, addSlot } from './common.mjs';
|
|
11
|
+
import { dayKey, lastDays, addSlot, addModel, KEEP_DAYS } from './common.mjs';
|
|
12
12
|
import { debugIo } from '../log.mjs';
|
|
13
13
|
|
|
14
14
|
const KIND = 'codex-ledger';
|
|
15
15
|
const DAYS = 7;
|
|
16
|
-
const KEEP_DAYS = 10;
|
|
17
16
|
const LIST_TTL_MS = 30_000;
|
|
18
17
|
const SCAN_DAYS = 30;
|
|
19
18
|
|
|
@@ -86,20 +85,21 @@ export class CodexBook {
|
|
|
86
85
|
day.tokens += tokens;
|
|
87
86
|
day.cost += cost?.total ?? 0;
|
|
88
87
|
day.costNoCache += cost?.noCache ?? 0;
|
|
88
|
+
addModel(day, this.model, tokens, cost?.total ?? 0, !cost);
|
|
89
89
|
if (!cost) day.unknown = true;
|
|
90
90
|
addSlot(this.slots, at, cost?.total ?? 0, cost?.noCache ?? 0, !cost);
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
let listed = { at: 0, files: [] };
|
|
94
|
+
let listed = { at: 0, files: [], days: 0 };
|
|
95
95
|
|
|
96
96
|
// 며칠 전에 시작했거나 다시 이어 쓴 세션도 시작한 날짜 폴더에 쓰므로, 30일치 폴더에서 7일 안에 바뀐 기록을 고른다.
|
|
97
|
-
// 7일보다 오래된 줄은 날짜 키로 걸러진다.
|
|
98
|
-
function recentFiles() {
|
|
99
|
-
if (Date.now() - listed.at < LIST_TTL_MS) return listed.files;
|
|
100
|
-
const cutoff = Date.now() -
|
|
97
|
+
// 7일보다 오래된 줄은 날짜 키로 걸러진다. 리포트처럼 days 를 늘리면 폴더도 그만큼 더 거슬러 본다 (30일 리포트면 53일치).
|
|
98
|
+
function recentFiles(days = DAYS) {
|
|
99
|
+
if (listed.days === days && Date.now() - listed.at < LIST_TTL_MS) return listed.files;
|
|
100
|
+
const cutoff = Date.now() - days * 86400_000;
|
|
101
101
|
const files = [];
|
|
102
|
-
for (const dir of dayDirs(SCAN_DAYS)) {
|
|
102
|
+
for (const dir of dayDirs(SCAN_DAYS + days - DAYS)) {
|
|
103
103
|
let names = [];
|
|
104
104
|
try {
|
|
105
105
|
names = readdirSync(dir);
|
|
@@ -114,16 +114,17 @@ function recentFiles() {
|
|
|
114
114
|
} catch {}
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
|
-
listed = { at: Date.now(), files };
|
|
117
|
+
listed = { at: Date.now(), files, days };
|
|
118
118
|
return files;
|
|
119
119
|
}
|
|
120
120
|
|
|
121
121
|
const books = new Map();
|
|
122
122
|
|
|
123
123
|
// 기록마다 날짜별 합계(days)와 5분 칸(slots), 아직 읽지 않은 크기(pending)·전체 크기(size).
|
|
124
|
-
|
|
124
|
+
// days: 최근 며칠 안에 바뀐 기록을 볼지 (평소 7일, 리포트는 더 길게).
|
|
125
|
+
export function collectCodexLedger({ budget, days = DAYS } = {}) {
|
|
125
126
|
const out = { days: [], slots: [], pending: 0, size: 0 };
|
|
126
|
-
const files = recentFiles();
|
|
127
|
+
const files = recentFiles(days);
|
|
127
128
|
const keep = new Set(files);
|
|
128
129
|
for (const p of books.keys()) if (!keep.has(p)) books.delete(p);
|
|
129
130
|
for (const p of files) {
|
|
@@ -138,4 +139,4 @@ export function collectCodexLedger({ budget } = {}) {
|
|
|
138
139
|
return out;
|
|
139
140
|
}
|
|
140
141
|
|
|
141
|
-
export const _test = { reset: () => ((listed = { at: 0, files: [] }), books.clear()) };
|
|
142
|
+
export const _test = { reset: () => ((listed = { at: 0, files: [], days: 0 }), books.clear()) };
|
package/src/sources/common.mjs
CHANGED
|
@@ -27,6 +27,19 @@ export function lastDays(n, now = Date.now()) {
|
|
|
27
27
|
return keys;
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
// 장부가 날짜별로 남기는 일수. 기간 리포트(--report)가 볼 수 있는 가장 긴 기간이기도 하다.
|
|
31
|
+
// 평소 실행은 최근 7일 안에 바뀐 기록만 읽지만, 그 기록 안의 30일치 날짜 합계는 캐시에 남겨 리포트가 다시 읽지 않게 한다.
|
|
32
|
+
export const KEEP_DAYS = 30;
|
|
33
|
+
|
|
34
|
+
// 하루 합계(day)에 모델별 몫 { tokens, cost } 를 더한다. 모델 이름을 모르면 'unknown' 으로 센다.
|
|
35
|
+
// unknown: 가격표에 없는 모델이라 비용을 0 으로 셌을 때. 그 모델 몫에 unknown 을 남겨 리포트가 ? 를 붙인다.
|
|
36
|
+
export function addModel(day, model, tokens, cost, unknown = false) {
|
|
37
|
+
const m = ((day.models ??= {})[String(model || 'unknown')] ??= { tokens: 0, cost: 0 });
|
|
38
|
+
m.tokens += tokens;
|
|
39
|
+
m.cost += cost;
|
|
40
|
+
if (unknown) m.unknown = true;
|
|
41
|
+
}
|
|
42
|
+
|
|
30
43
|
// 지출 속도용 짧은 구간 장부. 비용을 5분 칸(키 = 칸 시작 시각 ms)에 모으고, 그 장부에서 가장 새 칸부터
|
|
31
44
|
// 2시간 안의 칸만 남긴다. 기준이 시계가 아니라 기록 안의 시각이라 처음 읽기 중에도 칸 수가 일정하다.
|
|
32
45
|
export const SLOT_MS = 5 * 60_000;
|