@sejuneoh/aitop 0.23.0 → 0.25.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 +52 -8
- package/package.json +1 -1
- package/src/cache.mjs +2 -1
- package/src/collect.mjs +7 -9
- package/src/i18n.mjs +45 -4
- package/src/loading.mjs +45 -0
- package/src/order.mjs +9 -3
- 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/claude.mjs +8 -3
- package/src/sources/codex-ledger.mjs +13 -12
- package/src/sources/common.mjs +13 -0
- package/src/ui/glyphs.mjs +3 -0
- package/src/ui/table.mjs +32 -9
- package/src/ui.mjs +6 -2
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';
|
|
@@ -171,6 +198,7 @@ const { toJson } = await import('../src/json.mjs');
|
|
|
171
198
|
const { createAttention, updateAttention, markSeen, nextAttention, windowTitle, createWaitWatch, takeNewlyWaiting, attentionCounts } = await import('../src/attention.mjs');
|
|
172
199
|
const { createNotifier } = await import('../src/notify.mjs');
|
|
173
200
|
const { onKey, fixFocus } = await import('../src/keys.mjs');
|
|
201
|
+
const { admit, createLoading, latchReady } = await import('../src/loading.mjs');
|
|
174
202
|
|
|
175
203
|
// 요청 전체 보기는 기본으로 꺼 둔다. 켜지 않으면 상세 패널에도 --json 에도 나가지 않는다.
|
|
176
204
|
const showRequests = opt.showRequests;
|
|
@@ -178,8 +206,12 @@ const showRequests = opt.showRequests;
|
|
|
178
206
|
const settings = { budgetDay: opt.budgetDay, notify: Boolean(alerts.notify), onWaiting: Boolean(alerts.onWaiting), debug: log.on, configPath: config.path };
|
|
179
207
|
const view = { showRequests, budgetDay: opt.budgetDay, hideIdleTools: opt.hideIdleTools, settings, data: null, selectedId: null, showDetail: 'auto', showEnded: opt.all, frame: 0, filter: '', searching: false, help: false, focus: null, filePath: null, diffScroll: 0, tab: 'now', costMode: 'api', sort: 'default', group: 'none', pins: [] };
|
|
180
208
|
const once = args.has('--once') || args.has('--json') || !process.stdout.isTTY;
|
|
209
|
+
// ready: 시작할 때 세션 기록을 다 읽었는지 (loading.mjs). 그 전에는 비용·컨텍스트 정렬과 ▲ 를 고정한다. 한 번에 다 읽는 --once·--json 은 처음부터 준비 완료다.
|
|
210
|
+
view.ready = once;
|
|
211
|
+
const loading = createLoading();
|
|
181
212
|
// 실시간 화면에서 한 번 갱신할 때 읽는 기록 양과 시간. 큰 기록은 여러 번에 나눠 읽어서 키 입력이 막히지 않게 한다.
|
|
182
|
-
|
|
213
|
+
// AITOP_TICK_BYTES: 테스트에서 캐시 없는 긴 로딩을 흉내 낼 때 쓴다.
|
|
214
|
+
const TICK_BUDGET = Number(process.env.AITOP_TICK_BYTES) > 0 ? Number(process.env.AITOP_TICK_BYTES) : 24 * 1024 * 1024;
|
|
183
215
|
const TICK_MS = 60;
|
|
184
216
|
// 덜 읽은 기록이 있으면 1초를 기다리지 않고 이만큼 쉰 뒤 이어 읽는다 (그 사이 키 입력과 그리기가 돈다).
|
|
185
217
|
const CATCH_UP_MS = 15;
|
|
@@ -193,10 +225,14 @@ const bell = opt.bell;
|
|
|
193
225
|
const waitWatch = createWaitWatch();
|
|
194
226
|
const notifier = !once && (alerts.notify || alerts.onWaiting) ? createNotifier(alerts) : null;
|
|
195
227
|
|
|
196
|
-
|
|
228
|
+
// throttle: 주기 갱신(tick)에서만 참이다. 로딩 중에는 loading.mjs 의 admit 이 허락할 때만 화면 데이터를 바꾼다.
|
|
229
|
+
// 알림(벨·--notify·--on-waiting)은 화면에 올리지 않은 갱신에서도 그대로 돈다. 돌려주는 값은 화면 데이터를 바꿨는지.
|
|
230
|
+
function refresh({ throttle = false } = {}) {
|
|
197
231
|
const data = collect({ showEnded: view.showEnded, selectedId: view.selectedId, budgetBytes: once ? Infinity : TICK_BUDGET, budgetMs: once ? Infinity : TICK_MS });
|
|
232
|
+
// 준비 완료를 먼저 정해, 처음 고르는 세션도 이번 갱신의 정렬을 따르게 한다.
|
|
233
|
+
if (!once) latchReady(loading, data.sessionsMore);
|
|
198
234
|
if (!data.sessions.some((s) => s.id === view.selectedId)) {
|
|
199
|
-
view.selectedId = arrange(data.sessions, view).sessions[0]?.id ?? null;
|
|
235
|
+
view.selectedId = arrange(data.sessions, { ...view, ready: once || loading.ready }).sessions[0]?.id ?? null;
|
|
200
236
|
view.focus = null;
|
|
201
237
|
view.tab = 'now';
|
|
202
238
|
}
|
|
@@ -205,15 +241,23 @@ function refresh() {
|
|
|
205
241
|
// 도구별 점검은 기록 폴더를 훑으므로 30초에 한 번만 한다.
|
|
206
242
|
if (!tools || Date.now() - tools.at > 30_000) tools = { at: Date.now(), result: checkTools() };
|
|
207
243
|
data.tools = tools.result;
|
|
208
|
-
view.data = data;
|
|
209
244
|
if (!once && (bell || notifier)) {
|
|
210
245
|
const fresh = takeNewlyWaiting(waitWatch, data.sessions);
|
|
211
246
|
if (fresh.length && bell) process.stdout.write('\x07');
|
|
212
247
|
notifier?.fire(fresh);
|
|
213
248
|
}
|
|
249
|
+
lastMore = data.more;
|
|
250
|
+
if (!once) {
|
|
251
|
+
const shown = admit(loading, data);
|
|
252
|
+
if (throttle && !shown) return false;
|
|
253
|
+
view.ready = loading.ready;
|
|
254
|
+
}
|
|
255
|
+
view.data = data;
|
|
214
256
|
if (view.filter) keepSelectionVisible();
|
|
215
257
|
fixFocus(view);
|
|
258
|
+
return true;
|
|
216
259
|
}
|
|
260
|
+
let lastMore = false;
|
|
217
261
|
|
|
218
262
|
function select(id) {
|
|
219
263
|
if (id !== view.selectedId) {
|
|
@@ -355,13 +399,13 @@ stdin.on('data', (key) => {
|
|
|
355
399
|
|
|
356
400
|
let lastFlush = 0;
|
|
357
401
|
function tick() {
|
|
358
|
-
refresh();
|
|
359
|
-
const more =
|
|
402
|
+
const shown = refresh({ throttle: true });
|
|
403
|
+
const more = lastMore;
|
|
360
404
|
if (more ? Date.now() - lastFlush > LOADING_FLUSH_MS : Date.now() - lastFlush > 15_000) {
|
|
361
405
|
flushCache();
|
|
362
406
|
lastFlush = Date.now();
|
|
363
407
|
}
|
|
364
|
-
draw();
|
|
408
|
+
if (shown) draw();
|
|
365
409
|
setTimeout(tick, more ? CATCH_UP_MS : 1000);
|
|
366
410
|
}
|
|
367
411
|
|
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/collect.mjs
CHANGED
|
@@ -24,17 +24,14 @@ export function bySession(a, b) {
|
|
|
24
24
|
// 돌려주는 more 가 true 면 한도 때문에 덜 읽은 기록이 있다.
|
|
25
25
|
// 도구마다, 그리고 날짜별 사용량 장부에 한도를 따로 줘서 서로의 읽기를 막지 않게 한다.
|
|
26
26
|
export function collect({ budgetBytes = Infinity, budgetMs = Infinity, ...opts } = {}) {
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
budgets.push(b);
|
|
31
|
-
return b;
|
|
32
|
-
};
|
|
27
|
+
// 이름별 읽기 한도. 'usage' 는 장부, 나머지는 도구별 세션 기록이다.
|
|
28
|
+
const budgets = {};
|
|
29
|
+
const budgetOf = (name, bytes, ms) => (budgets[name] = createBudget(bytes, ms));
|
|
33
30
|
const sessions = [];
|
|
34
31
|
const errors = [];
|
|
35
32
|
for (const [tool, fn] of [['claude', collectClaude], ['codex', collectCodex], ['gemini', collectGemini], ['agy', collectAgy]]) {
|
|
36
33
|
try {
|
|
37
|
-
sessions.push(...fn({ ...opts, budget: budgetOf(budgetBytes, budgetMs) }));
|
|
34
|
+
sessions.push(...fn({ ...opts, budget: budgetOf(tool, budgetBytes, budgetMs) }));
|
|
38
35
|
} catch (err) {
|
|
39
36
|
errors.push(`${tool}: ${err.message}`);
|
|
40
37
|
}
|
|
@@ -42,10 +39,11 @@ export function collect({ budgetBytes = Infinity, budgetMs = Infinity, ...opts }
|
|
|
42
39
|
// 장부는 세션 화면보다 덜 급하니 한 번 갱신에 세션 한도의 1/3 만 읽는다 (처음 한 번 다 읽은 뒤에는 캐시와 새 줄만 읽는다).
|
|
43
40
|
let usage = null;
|
|
44
41
|
try {
|
|
45
|
-
usage = collectLedger({ budget: budgetOf(budgetBytes / 3, budgetMs / 2) });
|
|
42
|
+
usage = collectLedger({ budget: budgetOf('usage', budgetBytes / 3, budgetMs / 2) });
|
|
46
43
|
} catch (err) {
|
|
47
44
|
errors.push(`usage: ${err.message}`);
|
|
48
45
|
}
|
|
49
46
|
sessions.sort(bySession);
|
|
50
|
-
|
|
47
|
+
// sessionsMore: 세션 기록(장부 빼고)만 덜 읽었는지. 시작할 때의 준비 완료는 이 값으로 정한다 (7일 장부는 헤더 진행 줄로만 보인다).
|
|
48
|
+
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) };
|
|
51
49
|
}
|
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 를 넘어 읽지 않습니다',
|
|
@@ -253,7 +276,7 @@ export const STRINGS = {
|
|
|
253
276
|
'phase.think': '생각 중',
|
|
254
277
|
'phase.working': '작업 중',
|
|
255
278
|
'phase.steps': '작업 중 · {n}단계',
|
|
256
|
-
'phase.loading': '
|
|
279
|
+
'phase.loading': '…',
|
|
257
280
|
'phase.write': '답변 작성 중',
|
|
258
281
|
'phase.agents': '에이전트 {n}개 실행 중',
|
|
259
282
|
|
|
@@ -273,7 +296,7 @@ export const STRINGS = {
|
|
|
273
296
|
'hdr.budget': '예산',
|
|
274
297
|
'hdr.today': '오늘',
|
|
275
298
|
'hdr.week': '7일',
|
|
276
|
-
'hdr.
|
|
299
|
+
'hdr.loading': '집계 중',
|
|
277
300
|
'hdr.apiLong': 'API 환산',
|
|
278
301
|
'hdr.apiShort': 'API',
|
|
279
302
|
'hdr.netLong': '캐시 제외',
|
|
@@ -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',
|
|
@@ -576,7 +617,7 @@ export const STRINGS = {
|
|
|
576
617
|
'phase.think': 'Thinking',
|
|
577
618
|
'phase.working': 'Working',
|
|
578
619
|
'phase.steps': { long: 'Working · step {n}', short: 'Step {n}' },
|
|
579
|
-
'phase.loading':
|
|
620
|
+
'phase.loading': '…',
|
|
580
621
|
'phase.write': { long: 'Writing reply', short: 'Writing' },
|
|
581
622
|
'phase.agents': { long: { one: '{n} agent running', other: '{n} agents running' }, short: { one: '{n} agent', other: '{n} agents' } },
|
|
582
623
|
|
|
@@ -595,7 +636,7 @@ export const STRINGS = {
|
|
|
595
636
|
'hdr.budget': 'budget',
|
|
596
637
|
'hdr.today': 'today',
|
|
597
638
|
'hdr.week': '7d',
|
|
598
|
-
'hdr.
|
|
639
|
+
'hdr.loading': 'Loading',
|
|
599
640
|
'hdr.apiLong': 'API cost',
|
|
600
641
|
'hdr.apiShort': 'API',
|
|
601
642
|
'hdr.netLong': 'no cache',
|
package/src/loading.mjs
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// 시작할 때의 로딩을 차분하게: 준비 완료 래치와, 로딩 중 다시 그리기 속도 제한.
|
|
2
|
+
// 캐시가 없으면 세션 기록과 7일 장부를 여러 갱신에 나눠 읽는데, 갱신마다 그리면 숫자·순서·진행률이 쉬지 않고 바뀐다.
|
|
3
|
+
|
|
4
|
+
// 준비 완료를 기다리는 최대 시간. 디스크가 느려 읽기 한도(바이트·시간)에 계속 걸려도 이만큼 지나면 준비 완료로 본다.
|
|
5
|
+
export const READY_CAP_MS = 60_000;
|
|
6
|
+
// 로딩 중에는 중요한 변화가 없으면 이 간격보다 자주 화면에 올리지 않는다.
|
|
7
|
+
export const LOADING_DRAW_MS = 1000;
|
|
8
|
+
|
|
9
|
+
// now: 시계 (테스트에서 바꿔 넣는다).
|
|
10
|
+
export function createLoading({ now = Date.now, capMs = READY_CAP_MS, drawMs = LOADING_DRAW_MS } = {}) {
|
|
11
|
+
return { now, capMs, drawMs, startedAt: now(), ready: false, shownAt: -Infinity, shown: null };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// 준비 완료 = 처음으로 more(세션 기록만, collect 의 sessionsMore)가 거짓인 갱신, 또는 시작 후 capMs. 한 번 켜지면 되돌리지 않는다 (more 는 한도가 시간이기도 해서 다시 참이 될 수 있다).
|
|
15
|
+
// 7일 장부(usage.loading)는 준비 완료 조건에 넣지 않고 헤더 진행 줄로만 보인다.
|
|
16
|
+
export function latchReady(L, more) {
|
|
17
|
+
if (!L.ready && (more === false || L.now() - L.startedAt >= L.capMs)) L.ready = true;
|
|
18
|
+
return L.ready;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// 바로 그려야 하는 변화를 가리는 데 쓰는 값: 세션 목록과 응답 대기 세션.
|
|
22
|
+
const signature = (data) => {
|
|
23
|
+
const list = data?.sessions ?? [];
|
|
24
|
+
return `${list.map((s) => s.id).join(',')}|${list.filter((s) => s.status === 'waiting').map((s) => s.id).join(',')}`;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// 이번 갱신 결과를 화면에 올릴지 정한다. 준비 완료 전이나 7일 집계 중에는 drawMs 에 한 번만 올리고,
|
|
28
|
+
// 첫 화면, 준비 완료 순간, 집계가 끝난 순간, 세션 목록·응답 대기가 바뀐 갱신은 바로 올린다. 로딩이 끝난 뒤에는 늘 올린다.
|
|
29
|
+
// 준비 완료 순간은 화면에 마지막으로 올린 값과 견준다 (부르는 쪽이 admit 전에 latchReady 를 먼저 불러도 바로 올린다).
|
|
30
|
+
export function admit(L, data) {
|
|
31
|
+
const ready = latchReady(L, data.sessionsMore ?? data.more);
|
|
32
|
+
const loading = data.usage?.loading != null;
|
|
33
|
+
const prev = L.shown;
|
|
34
|
+
const sig = signature(data);
|
|
35
|
+
const urgent =
|
|
36
|
+
!prev ||
|
|
37
|
+
(ready && !prev.ready) ||
|
|
38
|
+
(!loading && prev.loading) ||
|
|
39
|
+
sig !== prev.sig;
|
|
40
|
+
const now = L.now();
|
|
41
|
+
if (!urgent && (!ready || loading) && now - L.shownAt < L.drawMs) return false;
|
|
42
|
+
L.shown = { sig, loading, ready };
|
|
43
|
+
L.shownAt = now;
|
|
44
|
+
return true;
|
|
45
|
+
}
|
package/src/order.mjs
CHANGED
|
@@ -28,11 +28,16 @@ const KEYS = {
|
|
|
28
28
|
recent: (s) => s.updatedAt ?? -Infinity,
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
+
// 기록을 읽는 동안 계속 커지는 값. 준비 완료 전에는 이 값으로 줄 세우지 않는다.
|
|
32
|
+
const GROWING = new Set(['cost', 'context']);
|
|
33
|
+
|
|
31
34
|
// 종료 세션은 어떤 정렬에서도 (묶음 안에서도) 아래에 둔다. 그다음 큰 값이 위. 값이 같으면 받은 순서(기본 순서)를 지켜 갱신마다 자리가 흔들리지 않게 한다 (Array.prototype.sort 는 안정 정렬).
|
|
32
|
-
|
|
35
|
+
// ready 가 false 면(시작할 때 기록을 아직 읽는 중) 비용·컨텍스트 정렬은 기본 순서에 고정했다가, 준비 완료 때 한 번만 다시 줄 세운다.
|
|
36
|
+
export function compare(sort, costMode = 'api', ready = true) {
|
|
33
37
|
const key = KEYS[sort];
|
|
34
38
|
if (!key) return () => 0;
|
|
35
39
|
const ended = (s) => (s.status === 'ended' ? 1 : 0);
|
|
40
|
+
if (ready === false && GROWING.has(sort)) return (a, b) => ended(a) - ended(b);
|
|
36
41
|
return (a, b) => ended(a) - ended(b) || key(b, costMode) - key(a, costMode);
|
|
37
42
|
}
|
|
38
43
|
|
|
@@ -42,8 +47,9 @@ const GROUP_KEY = { project: projectOf, tool: (s) => s.tool ?? '?' };
|
|
|
42
47
|
// 돌려주는 sessions 는 화면에 그리는 순서 그대로다 (↑↓·n 도 이 순서를 따른다).
|
|
43
48
|
// groups 는 묶을 때만 있다: { name, count, cost, unknown, waiting, pinned, sessions }. 묶음은 그 안의 첫 세션이 정렬에서 앞선 순으로 놓인다.
|
|
44
49
|
// pins: 고정한 세션 id (고정한 순서). 화면에 없는 id 는 건너뛴다.
|
|
45
|
-
|
|
46
|
-
|
|
50
|
+
// ready: false 면 준비 완료 전이다 (compare 참고). 응답 대기 세션은 그동안에도 맨 위로 올린다.
|
|
51
|
+
export function arrange(sessions, { sort = 'default', group = 'none', costMode = 'api', pins = [], ready = true } = {}) {
|
|
52
|
+
const cmp = compare(sort, costMode, ready);
|
|
47
53
|
const rank = new Map((pins ?? []).map((id, i) => [id, i]));
|
|
48
54
|
const waiting = sessions.filter((s) => s.status === 'waiting').sort(cmp);
|
|
49
55
|
const pinned = sessions.filter((s) => s.status !== 'waiting' && rank.has(s.id)).sort((a, b) => rank.get(a.id) - rank.get(b.id));
|
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)
|
package/src/sources/claude.mjs
CHANGED
|
@@ -69,13 +69,14 @@ export function _stats() {
|
|
|
69
69
|
return { trackers: trackers.size, subTrackers: subTrackers.size };
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
// 기록을 아직 다 읽지 못한 세션의 상태. 읽다 만 기록의 진행 단계는 틀릴 수 있어 화면에는 … 로만 보인다 (진행률은 헤더 한 줄로 모은다).
|
|
72
73
|
function loadingPhase(t) {
|
|
73
|
-
return t?.loading != null ? { kind: 'think', msg: 'loading'
|
|
74
|
+
return t?.loading != null ? { kind: 'think', msg: 'loading' } : null;
|
|
74
75
|
}
|
|
75
76
|
|
|
76
77
|
// 서브에이전트 전체(끝난 것 포함)의 토큰·비용 합계. 메인 세션 합계에 더해 화면에 보인다.
|
|
77
78
|
function emptySub() {
|
|
78
|
-
return { count: 0, tokens: emptyTokens(), cost: 0, costNoCache: 0, costUnknown: false, files: [], activity: [] };
|
|
79
|
+
return { count: 0, tokens: emptyTokens(), cost: 0, costNoCache: 0, costUnknown: false, loading: false, files: [], activity: [] };
|
|
79
80
|
}
|
|
80
81
|
|
|
81
82
|
// 메인 tracker 와 서브에이전트 합계를 화면에 보일 세션 숫자로 합친다. 기록을 아직 읽지 않았으면(t 없음) 비용은 null.
|
|
@@ -89,6 +90,8 @@ function sessionTotals(t, sub) {
|
|
|
89
90
|
cost: t ? t.cost + sub.cost : null,
|
|
90
91
|
costNoCache: t ? t.costNoCache + sub.costNoCache : null,
|
|
91
92
|
costUnknown: Boolean(t?.costUnknown || sub.costUnknown),
|
|
93
|
+
// 메인이나 서브에이전트 기록을 아직 다 읽지 못해 숫자가 덜 찬 상태. 표는 이 동안 숫자 대신 … 를 보인다.
|
|
94
|
+
loading: Boolean(t?.loading != null || sub.loading),
|
|
92
95
|
context: { used, window: contextWindow(t?.model, used) },
|
|
93
96
|
files: t ? mergeFiles([{ agent: '메인', files: t.files }, ...sub.files]) : [],
|
|
94
97
|
turns: t?.turns ?? [],
|
|
@@ -112,6 +115,7 @@ function readMembers(transcript, parent, budget) {
|
|
|
112
115
|
sub.cost += t.cost;
|
|
113
116
|
sub.costNoCache += t.costNoCache;
|
|
114
117
|
sub.costUnknown ||= t.costUnknown;
|
|
118
|
+
sub.loading ||= t.loading != null;
|
|
115
119
|
sub.activity.push(t.activity);
|
|
116
120
|
if (t.files.length) sub.files.push({ agent: meta.agentType ?? 'agent', files: t.files, startedAt: t.firstAt ?? undefined });
|
|
117
121
|
const age = Date.now() - t.mtimeMs;
|
|
@@ -134,6 +138,7 @@ function readMembers(transcript, parent, budget) {
|
|
|
134
138
|
cost: t.cost,
|
|
135
139
|
costNoCache: t.costNoCache,
|
|
136
140
|
costUnknown: t.costUnknown,
|
|
141
|
+
loading: t.loading != null,
|
|
137
142
|
startedAt: t.events[0]?.at,
|
|
138
143
|
});
|
|
139
144
|
}
|
|
@@ -276,7 +281,7 @@ function endedFromTranscripts(known, selectedId, budget) {
|
|
|
276
281
|
live: false,
|
|
277
282
|
lazy: !t,
|
|
278
283
|
status: 'ended',
|
|
279
|
-
phase:
|
|
284
|
+
phase: { kind: 'ended' },
|
|
280
285
|
waitingFor: null,
|
|
281
286
|
now: '',
|
|
282
287
|
startedAt: head.startedAt,
|
|
@@ -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;
|
package/src/ui/glyphs.mjs
CHANGED
|
@@ -10,6 +10,8 @@ const NORMAL = {
|
|
|
10
10
|
rule: '─',
|
|
11
11
|
bar: { fill: '▃', empty: NO_COLOR ? '▁' : '▃' },
|
|
12
12
|
week: '▁▂▃▄▅▆▇█',
|
|
13
|
+
// 시작할 때 헤더의 집계 진행 막대. 색이 없으면 채운 칸과 빈칸이 모양으로 갈리도록 ASCII 로 그린다.
|
|
14
|
+
progress: NO_COLOR ? { l: '[', r: ']', fill: '#', empty: '.' } : { l: '▕', r: '▏', fill: '█', empty: '░' },
|
|
13
15
|
waiting: '◆',
|
|
14
16
|
waitingBlink: '◇',
|
|
15
17
|
unseen: '●',
|
|
@@ -35,6 +37,7 @@ const SAFE = {
|
|
|
35
37
|
// 색이 없어도 채운 칸과 빈칸이 모양으로 갈리게 한다.
|
|
36
38
|
bar: { fill: '#', empty: NO_COLOR ? '.' : '#' },
|
|
37
39
|
week: '_.:-=+*#',
|
|
40
|
+
progress: { l: '[', r: ']', fill: '#', empty: '.' },
|
|
38
41
|
waiting: '!',
|
|
39
42
|
waitingBlink: '.',
|
|
40
43
|
unseen: '*',
|
package/src/ui/table.mjs
CHANGED
|
@@ -132,7 +132,7 @@ export function header(view, W) {
|
|
|
132
132
|
const rate = rateText ? [{ t: ` (${rateText}/h)`, fg: PALETTE.muted, bg: B }] : null;
|
|
133
133
|
// bar: 7일 금액 뒤의 날짜별 막대. 집계 중이거나 날짜별 값이 없으면 넣지 않는다.
|
|
134
134
|
const bar = u?.loading == null && u?.days7?.length ? [{ t: ' ', bg: B }, ...weekBar(u.days7, view.costMode).map((x) => ({ ...x, bg: B }))] : null;
|
|
135
|
-
const week = (tok, withBar = false) =>
|
|
135
|
+
const week = (tok, withBar = false) => period(t('hdr.week'), u.week, tok, [], withBar && bar ? bar : []);
|
|
136
136
|
// 장부를 못 읽었으면 화면에 있는 세션(모든 도구)의 누적 토큰이라도 보인다.
|
|
137
137
|
const fallback = [{ t: `Σ ${fmtTokens(sessions.reduce((a, s) => a + (s.tokens?.total ?? 0), 0))} tok`, fg: PALETTE.muted, bg: B }];
|
|
138
138
|
const clockSeg = { t: clock(view.data.at), fg: PALETTE.muted, bg: B };
|
|
@@ -164,7 +164,9 @@ export function header(view, W) {
|
|
|
164
164
|
// 캐시 제외 화면에서도 'API 예상' 은 기준이 드러나므로 캐시 제외 표시 없이 남길 수 있다.
|
|
165
165
|
...(projSeg ? [{ api: 'short', budget: 'only' }, { budget: 'only' }] : []),
|
|
166
166
|
];
|
|
167
|
-
|
|
167
|
+
// 7일 장부를 처음 읽는 동안은 오늘·7일·1시간·막대 자리를 진행 줄 하나로 둔다 (집계 중 ▕███░░░░░░░▏ 30%). 좁으면 막대를 뺀다.
|
|
168
|
+
const loading = u?.loading != null ? progressSegs(u.loading, B) : null;
|
|
169
|
+
const rights = loading ? [[...loading.full, dot, clockSeg], [...loading.short, dot, clockSeg], [clockSeg]] : u ? [...shapes.filter((o) => !net || o.api || o.budget === 'only').map(right), [clockSeg]] : [[...fallback, dot, clockSeg], [clockSeg]];
|
|
168
170
|
// 사용량 숫자가 상태 이름보다 중요하므로, 이름을 먼저 줄이고 그래도 모자라면 오른쪽을 줄인다.
|
|
169
171
|
// 시각만 남기 전에는 live 수와 ○ 대기를 먼저 빼서 오늘 비용을 지킨다.
|
|
170
172
|
const fit = (r, narrow, drop) => {
|
|
@@ -174,7 +176,7 @@ export function header(view, W) {
|
|
|
174
176
|
};
|
|
175
177
|
const kept = rights.slice(0, -1);
|
|
176
178
|
// 캐시 제외 기준은 '캐시제외' 표시 때문에 9칸이 더 든다. 시각만 남기기 전에 시각을 빼고 '캐시제외 오늘 $5.20' 을 남긴다.
|
|
177
|
-
const bare = u && net ? [right({ api: 'short', clock: false })] : [];
|
|
179
|
+
const bare = u && net && !loading ? [right({ api: 'short', clock: false })] : [];
|
|
178
180
|
const tries = [
|
|
179
181
|
...kept.flatMap((r) => [[r, false, 0], [r, true, 0]]),
|
|
180
182
|
...[1, 2].flatMap((drop) => kept.map((r) => [r, true, drop])),
|
|
@@ -188,6 +190,22 @@ export function header(view, W) {
|
|
|
188
190
|
return line(leftOf(true, 2), W, B);
|
|
189
191
|
}
|
|
190
192
|
|
|
193
|
+
// 집계 진행률은 10% 단위로만 올린다 (다시 그리는 횟수를 줄인다). 막대는 10칸이라 한 칸이 10% 다.
|
|
194
|
+
export const progressStep = (r) => Math.min(100, Math.max(0, Math.floor((Number(r) || 0) * 10) * 10));
|
|
195
|
+
|
|
196
|
+
// 헤더 진행 줄의 조각. full: 글·막대·%, short: 글·% 만.
|
|
197
|
+
export function progressSegs(r, bg) {
|
|
198
|
+
const pct = progressStep(r);
|
|
199
|
+
const P = glyphs().progress;
|
|
200
|
+
const filled = pct / 10;
|
|
201
|
+
const label = { t: `${t('hdr.loading')} `, fg: PALETTE.info, bg };
|
|
202
|
+
const num = { t: `${pct}%`, fg: PALETTE.muted, bg };
|
|
203
|
+
return {
|
|
204
|
+
full: [label, { t: P.l, fg: PALETTE.faint, bg }, { t: P.fill.repeat(filled), fg: PALETTE.brand, bg }, { t: P.empty.repeat(10 - filled), fg: PALETTE.faint, bg }, { t: P.r + ' ', fg: PALETTE.faint, bg }, num],
|
|
205
|
+
short: [label, num],
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
191
209
|
// 폭이 모자랄 때 도구 이름 대신 쓰는 짧은 이름.
|
|
192
210
|
export const TOOL_SHORT = { claude: 'cla', codex: 'cdx', gemini: 'gem' };
|
|
193
211
|
|
|
@@ -317,7 +335,9 @@ export function sessionRow(s, c, W, selected, frame, hot, costMode = 'api', pinn
|
|
|
317
335
|
const pc = s.phase?.kind === 'idle' ? PALETTE.info : PHASE_COLOR[s.phase?.kind] ?? PALETTE.muted;
|
|
318
336
|
// 아직 토큰을 하나도 쓰지 않은 세션은 숫자 칸을 비운다. 기다리는 중이면 '아직 지시 없음'.
|
|
319
337
|
const blank = s.lazy || !(s.tokens?.total > 0);
|
|
320
|
-
|
|
338
|
+
// 기록을 아직 다 읽지 못한 세션은 덜 찬 숫자 대신 … 를 둔다 (다 읽은 뒤의 0 은 그대로 0).
|
|
339
|
+
const partial = Boolean(s.loading);
|
|
340
|
+
const status = blank && !partial && s.tool !== 'gemini' && (s.status === 'idle' || s.status === 'live') ? t('phase.noPrompt') : statusText(s.phase);
|
|
321
341
|
const segs = [
|
|
322
342
|
{ t: selected ? glyphs().select : ' ', fg: PALETTE.brand, bold: true },
|
|
323
343
|
{ ...g, t: g.t + ' ' },
|
|
@@ -331,14 +351,17 @@ export function sessionRow(s, c, W, selected, frame, hot, costMode = 'api', pinn
|
|
|
331
351
|
if (c.showProject) segs.push({ t: pad(s.project ?? '', c.project) + ' ', fg: ended ? PALETTE.ended : PALETTE.muted });
|
|
332
352
|
segs.push(
|
|
333
353
|
{ t: pad(status, c.status) + ' ', fg: pc, bold: s.status === 'waiting' },
|
|
334
|
-
{ t: pad(blank ? '' : fmtTokens(s.tokens.total), c.tokens, 'right') + ' ', fg: ended ? PALETTE.ended : PALETTE.muted },
|
|
354
|
+
{ t: pad(partial ? '…' : blank ? '' : fmtTokens(s.tokens.total), c.tokens, 'right') + ' ', fg: ended ? PALETTE.ended : partial ? PALETTE.info : PALETTE.muted },
|
|
335
355
|
);
|
|
336
|
-
if (c.showCost) segs.push({ t: pad(blank ? '' : (hot?.has(s.id) ? glyphs().hot : '') + money(costOf(s, costMode), s.costUnknown), c.cost, 'right') + ' ', fg: s.cost == null || ended ? PALETTE.info : hot?.has(s.id) ? PALETTE.money : PALETTE.muted, bold: Boolean(hot?.has(s.id)) });
|
|
337
|
-
segs.push(...gauge(s.context?.used ?? 0, s.context?.window ?? 0, c.cells), { t: ' ' }, { t: pad(idle, c.age, 'right'), fg: waiting ? PALETTE.waiting : PALETTE.info });
|
|
356
|
+
if (c.showCost) segs.push(partial ? { t: pad('…', c.cost, 'right') + ' ', fg: PALETTE.info } : { t: pad(blank ? '' : (hot?.has(s.id) ? glyphs().hot : '') + money(costOf(s, costMode), s.costUnknown), c.cost, 'right') + ' ', fg: s.cost == null || ended ? PALETTE.info : hot?.has(s.id) ? PALETTE.money : PALETTE.muted, bold: Boolean(hot?.has(s.id)) });
|
|
357
|
+
segs.push(...(partial ? pendingGauge(c.cells) : gauge(s.context?.used ?? 0, s.context?.window ?? 0, c.cells)), { t: ' ' }, { t: pad(idle, c.age, 'right'), fg: waiting ? PALETTE.waiting : PALETTE.info });
|
|
338
358
|
// 종료 행은 밝기 말고도 기울임꼴로 구분한다 (색이 없으면 · 글리프와 '종료' 글자로 구분된다).
|
|
339
359
|
return line(ended ? segs.map((x) => ({ ...x, italic: true })) : segs, W, bg);
|
|
340
360
|
}
|
|
341
361
|
|
|
362
|
+
// 기록을 읽는 중인 세션의 CONTEXT 칸: 빈 막대와 … (gauge 와 같은 폭).
|
|
363
|
+
const pendingGauge = (cells) => [{ t: glyphs().bar.empty.repeat(cells), fg: PALETTE.faint }, { t: pad('…', 5, 'right'), fg: PALETTE.info }];
|
|
364
|
+
|
|
342
365
|
// 표의 STATUS 칸 글. 응답 대기는 ◆ 와 행 색으로 이미 보이므로 무엇을 허락해 달라는지만 적고, 요청 내용이 없으면 '응답 대기' 를 남긴다.
|
|
343
366
|
// 상세 창은 phaseText 의 긴 문구 전체를 보인다.
|
|
344
367
|
export const statusText = (phase) => phaseText(phase, { short: true });
|
|
@@ -369,9 +392,9 @@ export function memberRow(m, last, c, W, frame, parentModel, costMode = 'api') {
|
|
|
369
392
|
);
|
|
370
393
|
segs.push(
|
|
371
394
|
{ t: pad(statusText(m.phase), c.status) + ' ', fg: done ? PALETTE.info : PHASE_COLOR[m.phase?.kind] ?? PALETTE.muted },
|
|
372
|
-
{ t: pad(started ? fmtTokens(m.tokens ?? 0) : '', c.tokens, 'right') + ' ', fg: done ? PALETTE.info : PALETTE.muted },
|
|
395
|
+
{ t: pad(m.loading ? '…' : started ? fmtTokens(m.tokens ?? 0) : '', c.tokens, 'right') + ' ', fg: done || m.loading ? PALETTE.info : PALETTE.muted },
|
|
373
396
|
);
|
|
374
|
-
if (c.showCost) segs.push({ t: pad(started ? money(costOf(m, costMode), m.costUnknown) : '', c.cost, 'right') + ' ', fg: done ? PALETTE.info : PALETTE.muted });
|
|
397
|
+
if (c.showCost) segs.push({ t: pad(m.loading ? '…' : started ? money(costOf(m, costMode), m.costUnknown) : '', c.cost, 'right') + ' ', fg: done || m.loading ? PALETTE.info : PALETTE.muted });
|
|
375
398
|
// 끝난 팀원은 종료 행처럼 기울임꼴로 둔다.
|
|
376
399
|
return line(done ? segs.map((x) => ({ ...x, italic: true })) : segs, W);
|
|
377
400
|
}
|
package/src/ui.mjs
CHANGED
|
@@ -21,8 +21,11 @@ export function animating(view) {
|
|
|
21
21
|
return filterSessions(view.data.sessions, view.filter).some((s) => glyphMoves(s) || (s.members ?? []).some((m) => m.status !== 'done'));
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
// 로딩 중(준비 완료 전이거나 7일 집계 중)에는 경과 시간(IDLE 등)을 데이터를 받은 시각에 맞춰, 스피너 프레임마다 숫자가 따로 바뀌지 않게 한다.
|
|
25
|
+
const settling = (view) => view.data && (view.ready === false || view.data.usage?.loading != null);
|
|
26
|
+
|
|
24
27
|
export function render(view, W, H) {
|
|
25
|
-
setNow(Date.now());
|
|
28
|
+
setNow(settling(view) && view.data.at ? view.data.at : Date.now());
|
|
26
29
|
const lines = [];
|
|
27
30
|
if (!view.data) {
|
|
28
31
|
// 첫 수집은 동기로 돌아 이 화면이 다시 그려지지 않으므로 움직이지 않는 로고를 둔다.
|
|
@@ -78,7 +81,8 @@ export function render(view, W, H) {
|
|
|
78
81
|
if (start === selRow && rows[start - 1]?.g && lastOfSel - start + 2 <= shown) start--;
|
|
79
82
|
const isSession = (r) => r.s && !r.m;
|
|
80
83
|
const visible = rows.slice(start, start + shown);
|
|
81
|
-
|
|
84
|
+
// 준비 완료 전에는 값이 커지는 대로 ▲ 가 옮겨 다니므로 붙이지 않는다.
|
|
85
|
+
const hot = view.ready === false ? null : topCost(visible.filter(isSession).map((r) => r.s), view.costMode);
|
|
82
86
|
if (!sessions.length) table.push(...(view.filter ? [line([{ t: ` ${t('ui.noMatch', { q: view.filter })}`, fg: PALETTE.muted, italic: true }], TW)] : emptyLines(view, TW)));
|
|
83
87
|
for (const r of visible) table.push(r.g ? groupRow(r.g, TW) : r.m ? memberRow(r.m, r.last, c, TW, view.frame, r.s.model, view.costMode) : sessionRow(r.s, c, TW, r.s === sel, view.frame, hot, view.costMode, Boolean(view.pins?.includes(r.s.id))));
|
|
84
88
|
if (clipped) {
|