@sejuneoh/aitop 0.22.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 +16 -2
- package/bin/aitop.mjs +51 -46
- package/package.json +3 -3
- package/src/cache.mjs +2 -1
- package/src/config.mjs +33 -25
- package/src/doctor.mjs +45 -24
- package/src/help.mjs +87 -58
- package/src/i18n.mjs +850 -0
- package/src/json.mjs +8 -2
- package/src/line.mjs +4 -2
- package/src/notify.mjs +14 -8
- package/src/order.mjs +4 -3
- package/src/pricing.mjs +25 -3
- package/src/report.mjs +179 -0
- package/src/sources/agy-ledger.mjs +14 -12
- package/src/sources/antigravity.mjs +16 -15
- package/src/sources/claude-ledger.mjs +38 -17
- package/src/sources/claude-tracker.mjs +4 -4
- package/src/sources/claude.mjs +10 -10
- package/src/sources/codex-ledger.mjs +13 -12
- package/src/sources/codex.mjs +5 -5
- package/src/sources/common.mjs +13 -0
- package/src/sources/gemini.mjs +1 -1
- package/src/ui/chrome.mjs +62 -54
- package/src/ui/detail.mjs +49 -42
- package/src/ui/table.mjs +35 -33
- package/src/ui.mjs +4 -3
package/src/json.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { projectBudget } from './budget.mjs';
|
|
2
2
|
import { toolsJson } from './doctor.mjs';
|
|
3
|
+
import { phaseText } from './i18n.mjs';
|
|
3
4
|
|
|
4
5
|
// aitop --json 출력. 다른 스크립트나 AI 가 읽기 쉬운 모양으로 세션 목록과 사용량 합계를 담는다.
|
|
5
6
|
// 텍스트는 수집 단계에서 이미 비밀값 가림이 적용돼 있다.
|
|
@@ -18,6 +19,9 @@ const usageOf = (u) => (u ? { ...u, ...('cost' in u ? { cost: money(u.cost) } :
|
|
|
18
19
|
// version 은 aitop 버전, tools 는 aitop --doctor 와 같은 도구별 점검 결과다.
|
|
19
20
|
// opts.showRequests: 응답 대기 요청 전체(waitDetail)를 넣는다. 기본은 꺼져 있다.
|
|
20
21
|
// opts.budgetDay: 하루 예산. 있으면 usage.budget 에 예산, 오늘 끝 예상 비용(API 정가 환산, 화면과 같은 기준), 단계를 넣는다.
|
|
22
|
+
// --json 의 phase 문구. 한국어 표로 만든다 (영어 화면 1/3 의 계약).
|
|
23
|
+
const koPhase = (p) => (p?.kind ? phaseText(p, { lang: 'ko' }) : null);
|
|
24
|
+
|
|
21
25
|
export function toJson(data, version = null, opts = {}) {
|
|
22
26
|
const b = data.usage ? projectBudget(data.usage, opts.budgetDay, { now: data.at ?? Date.now() }) : null;
|
|
23
27
|
return {
|
|
@@ -37,7 +41,9 @@ export function toJson(data, version = null, opts = {}) {
|
|
|
37
41
|
pid: s.pid ?? null,
|
|
38
42
|
live: Boolean(s.live),
|
|
39
43
|
status: s.status,
|
|
40
|
-
|
|
44
|
+
// phase 는 화면 언어와 상관없이 늘 한국어 문구(예전과 같은 글)로 두고, 언어와 상관없는 상태 이름은 phaseKind 로 준다.
|
|
45
|
+
phase: koPhase(s.phase),
|
|
46
|
+
phaseKind: s.phase?.kind ?? null,
|
|
41
47
|
waitingFor: s.waitingFor ?? null,
|
|
42
48
|
// 허락을 기다리는 요청의 전체 내용 (Bash 명령, 파일 경로 등). --show-requests 를 켰을 때만 넣는다. 비밀값 가림은 최선을 다할 뿐이다.
|
|
43
49
|
...(opts.showRequests ? { waitDetail: s.waitDetail ?? null } : {}),
|
|
@@ -51,7 +57,7 @@ export function toJson(data, version = null, opts = {}) {
|
|
|
51
57
|
context: { used: s.context?.used ?? 0, window: s.context?.window ?? null },
|
|
52
58
|
// 변경 내용(diff)은 넣지 않고 파일별 통계만 넣는다. 줄 수는 편집마다 더한 누적값이다 (git diff 아님).
|
|
53
59
|
files: (s.files ?? []).map((f) => ({ path: f.path, created: Boolean(f.created), edits: f.edits, writtenLines: f.add, deletedLines: f.del, updatedAt: iso(f.at), agents: f.agents ?? [] })),
|
|
54
|
-
members: (s.members ?? []).map((m) => ({ name: m.name, task: m.task ?? null, model: m.model ?? null, status: m.status, phase: m.phase?.
|
|
60
|
+
members: (s.members ?? []).map((m) => ({ name: m.name, task: m.task ?? null, model: m.model ?? null, status: m.status, phase: koPhase(m.phase), phaseKind: m.phase?.kind ?? null, tokens: m.tokens ?? 0, cost: money(m.cost) })),
|
|
55
61
|
})),
|
|
56
62
|
};
|
|
57
63
|
}
|
package/src/line.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// aitop --line: tmux 상태줄 같은 곳에 넣을 한 줄 요약. 예) $54.13/$50 wait 2 $3.1/h
|
|
2
2
|
// 글자는 ASCII 만 쓴다 (이모지·폭이 모호한 기호는 tmux 에서 칸이 어긋난다). 표기는 짧은 영어 약어로 고정하고 번역하지 않는다.
|
|
3
3
|
// 색은 --line=tmux 일 때 tmux 서식(#[fg=colourN])으로만 넣고 ANSI 코드는 쓰지 않는다. NO_COLOR 면 서식도 넣지 않는다.
|
|
4
|
+
// 옵션 오류 문구만 i18n 으로 지금 언어를 따른다.
|
|
5
|
+
import { t } from './i18n.mjs';
|
|
4
6
|
|
|
5
7
|
export const MODES = ['plain', 'tmux'];
|
|
6
8
|
export const DEFAULT_WIDTH = 40;
|
|
@@ -24,7 +26,7 @@ export function lineOption(argv) {
|
|
|
24
26
|
if (m) {
|
|
25
27
|
const v = m[1] ?? 'plain';
|
|
26
28
|
if (MODES.includes(v)) mode = v;
|
|
27
|
-
else error ??=
|
|
29
|
+
else error ??= t('opt.lineBad', { value: JSON.stringify(v) });
|
|
28
30
|
continue;
|
|
29
31
|
}
|
|
30
32
|
const w = /^--line-width(?:=(.*))?$/.exec(a);
|
|
@@ -35,7 +37,7 @@ export function lineOption(argv) {
|
|
|
35
37
|
const raw = w[1] ?? (argv[i + 1]?.startsWith('-') ? '' : (argv[++i] ?? ''));
|
|
36
38
|
const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
|
|
37
39
|
if (n > 0) width = n;
|
|
38
|
-
else error ??= raw === '' ? '
|
|
40
|
+
else error ??= raw === '' ? t('opt.lineWidthMissing') : t('opt.lineWidthBad', { value: JSON.stringify(raw) });
|
|
39
41
|
}
|
|
40
42
|
return { mode, width, rest, error };
|
|
41
43
|
}
|
package/src/notify.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { spawn } from 'node:child_process';
|
|
|
4
4
|
import { accessSync, constants, readFileSync } from 'node:fs';
|
|
5
5
|
import { join, delimiter } from 'node:path';
|
|
6
6
|
import { mask, stripControl } from './text.mjs';
|
|
7
|
+
import { getLang, phaseText, t } from './i18n.mjs';
|
|
7
8
|
|
|
8
9
|
export const HOOK_TIMEOUT_MS = 10_000;
|
|
9
10
|
const LABEL_MAX = 120;
|
|
@@ -42,8 +43,8 @@ export function notifyOptions(argv, config = {}, valueOpts = VALUE_OPTS) {
|
|
|
42
43
|
continue;
|
|
43
44
|
}
|
|
44
45
|
const v = m[1] ?? (i + 1 < argv.length ? argv[++i] : '');
|
|
45
|
-
if (!v.trim()) error = '
|
|
46
|
-
else if (m[1] == null && v.startsWith('-')) error =
|
|
46
|
+
if (!v.trim()) error = t('opt.onWaitingMissing');
|
|
47
|
+
else if (m[1] == null && v.startsWith('-')) error = t('opt.onWaitingDash', { value: v });
|
|
47
48
|
else onWaiting = v;
|
|
48
49
|
}
|
|
49
50
|
return { notify, onWaiting, rest, error };
|
|
@@ -103,8 +104,11 @@ export function notifierCommand(notifier, title, body) {
|
|
|
103
104
|
const escapeMarkup = (t) => String(t).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
104
105
|
|
|
105
106
|
// 세션에서 짧은 대기 사유. "응답 대기 · Bash" → "Bash". 비밀값처럼 보이는 것은 가린다.
|
|
106
|
-
|
|
107
|
-
|
|
107
|
+
// AITOP_WAITING_FOR 로도 넘기는 값이라 기본은 화면 언어와 상관없이 예전과 같은 한국어 문구다. 알림 본문은 lang 으로 화면 언어를 준다.
|
|
108
|
+
// 요청도 에이전트도 없으면 빈 글.
|
|
109
|
+
export function waitingLabel(s, lang = 'ko') {
|
|
110
|
+
const a = s.phase?.args ?? {};
|
|
111
|
+
const text = s.phase?.kind === 'waiting' && (a.what || a.agents) ? phaseText(s.phase, { lang, short: true }) : '';
|
|
108
112
|
const one = stripControl(text).replace(/\s+/g, ' ').trim();
|
|
109
113
|
return mask(one.length > LABEL_MAX ? one.slice(0, LABEL_MAX - 1) + '…' : one);
|
|
110
114
|
}
|
|
@@ -120,13 +124,15 @@ export function waitingEnv(s) {
|
|
|
120
124
|
};
|
|
121
125
|
}
|
|
122
126
|
|
|
123
|
-
|
|
127
|
+
// 알림 제목·본문은 화면 언어를 따른다 (AITOP_WAITING_FOR 와 달리 사람이 읽는 글이라).
|
|
128
|
+
export function notifyText(sessions, lang = getLang()) {
|
|
129
|
+
const o = { lang };
|
|
124
130
|
if (sessions.length === 1) {
|
|
125
131
|
const s = sessions[0];
|
|
126
|
-
const label = waitingLabel(s);
|
|
127
|
-
return { title:
|
|
132
|
+
const label = waitingLabel(s, lang);
|
|
133
|
+
return { title: t('notify.one', { tool: s.tool ?? '?' }, o), body: stripControl(`${s.project ?? s.id ?? ''}${label ? ' · ' + label : ''}`) };
|
|
128
134
|
}
|
|
129
|
-
return { title: '
|
|
135
|
+
return { title: t('notify.title', null, o), body: t('notify.many', { n: sessions.length }, o) };
|
|
130
136
|
}
|
|
131
137
|
|
|
132
138
|
// 한 번에 하나만 실행하는 자식 프로세스 실행기.
|
package/src/order.mjs
CHANGED
|
@@ -8,10 +8,11 @@ import { costOf } from './ui/draw.mjs';
|
|
|
8
8
|
|
|
9
9
|
export const SORTS = ['default', 'cost', 'context', 'recent'];
|
|
10
10
|
export const GROUPS = ['none', 'project', 'tool'];
|
|
11
|
-
export const SORT_LABEL = { default: '기본', cost: '비용', context: '컨텍스트', recent: '최근' };
|
|
12
|
-
export const GROUP_LABEL = { none: '없음', project: '프로젝트', tool: '도구' };
|
|
13
11
|
export const WAITING_GROUP = '응답 대기';
|
|
14
12
|
export const PINNED_GROUP = '고정';
|
|
13
|
+
// 폴더를 모르는 세션의 프로젝트 묶음 이름. 응답 대기·고정·폴더 없음 이름은 묶음 키라 ko 로 두고 화면(ui/table.mjs groupRow)이 지금 언어로 바꾼다.
|
|
14
|
+
// 정렬·묶기 이름(s:비용 g:프로젝트)은 i18n.mjs 의 sort.*·groupBy.* 에 있다.
|
|
15
|
+
export const NO_FOLDER = '(폴더 없음)';
|
|
15
16
|
|
|
16
17
|
// pins 에 id 가 있으면 빼고, 없으면 끝에 붙인다 (고정한 순서를 지킨다). 새 배열을 돌려준다.
|
|
17
18
|
export const togglePin = (pins = [], id) => (pins.includes(id) ? pins.filter((x) => x !== id) : [...pins, id]);
|
|
@@ -35,7 +36,7 @@ export function compare(sort, costMode = 'api') {
|
|
|
35
36
|
return (a, b) => ended(a) - ended(b) || key(b, costMode) - key(a, costMode);
|
|
36
37
|
}
|
|
37
38
|
|
|
38
|
-
const projectOf = (s) => s.project || String(s.cwd ?? '').split('/').filter(Boolean).at(-1) ||
|
|
39
|
+
const projectOf = (s) => s.project || String(s.cwd ?? '').split('/').filter(Boolean).at(-1) || NO_FOLDER;
|
|
39
40
|
const GROUP_KEY = { project: projectOf, tool: (s) => s.tool ?? '?' };
|
|
40
41
|
|
|
41
42
|
// 돌려주는 sessions 는 화면에 그리는 순서 그대로다 (↑↓·n 도 이 순서를 따른다).
|
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()) };
|
|
@@ -605,7 +605,7 @@ function member(r, g) {
|
|
|
605
605
|
task: r.title ?? '',
|
|
606
606
|
status: r.running ? 'busy' : 'done',
|
|
607
607
|
started: g.tokens.total > 0,
|
|
608
|
-
phase: r.running ? { kind: 'think',
|
|
608
|
+
phase: r.running ? { kind: 'think', msg: 'steps', args: { n: r.steps } } : { kind: 'done' },
|
|
609
609
|
now: '',
|
|
610
610
|
tokens: g.tokens.total,
|
|
611
611
|
cost: g.cost,
|
|
@@ -639,24 +639,25 @@ export function waitingFor(g) {
|
|
|
639
639
|
// 실행 중일 때는 아직 바뀌는 중인 단계, 없으면 마지막으로 끝난 단계로 지금 할 일을 짐작한다.
|
|
640
640
|
// 끝난 답변이 도구 호출을 냈으면 그 도구를 실행할 차례이고, 끝난 도구 호출 뒤에는 모델이 결과를 읽고 생각한다.
|
|
641
641
|
export function phaseOf(live, r, g, runningMembers = 0) {
|
|
642
|
-
if (!live) return { kind: 'ended'
|
|
643
|
-
|
|
642
|
+
if (!live) return { kind: 'ended' };
|
|
643
|
+
// 같이 도는 에이전트 수는 args.agents 로 보내고, 화면이 문구 뒤에 붙인다.
|
|
644
|
+
const extra = runningMembers ? { agents: runningMembers } : {};
|
|
644
645
|
const wait = waitingFor(g);
|
|
645
|
-
if (wait) return { kind: 'waiting',
|
|
646
|
-
if (!r.running) return { kind: 'idle'
|
|
646
|
+
if (wait) return { kind: 'waiting', args: { what: wait, ...extra } };
|
|
647
|
+
if (!r.running) return { kind: 'idle' };
|
|
647
648
|
// 바뀌는 중인 단계와 끝난 단계 가운데 더 뒤의 것이 지금 하는 일이다 (앞의 명령이 오래 도는 동안 뒤 단계가 이어질 수 있다).
|
|
648
649
|
const open = g.open && (!g.last || (g.open.idx ?? Infinity) > (g.last.idx ?? -1));
|
|
649
650
|
const s = open ? g.open : (g.last ?? g.open);
|
|
650
651
|
let p;
|
|
651
|
-
if (!s) p = { kind: 'think',
|
|
652
|
-
else if (s.type === STEP.TOOL && open) p = { kind: 'tool',
|
|
653
|
-
else if (s.type === STEP.REPLY && !open && s.tool) p = { kind: 'tool',
|
|
654
|
-
else if (s.type === STEP.REPLY) p = { kind: 'write'
|
|
655
|
-
else p = { kind: 'think'
|
|
656
|
-
return { ...p,
|
|
652
|
+
if (!s) p = { kind: 'think', msg: 'steps', args: { n: r.steps } };
|
|
653
|
+
else if (s.type === STEP.TOOL && open) p = s.tool?.what ? { kind: 'tool', args: { what: s.tool.what } } : { kind: 'tool', msg: 'toolUnknown' };
|
|
654
|
+
else if (s.type === STEP.REPLY && !open && s.tool) p = { kind: 'tool', args: { what: s.tool.what } };
|
|
655
|
+
else if (s.type === STEP.REPLY) p = { kind: 'write' };
|
|
656
|
+
else p = { kind: 'think' };
|
|
657
|
+
return runningMembers ? { ...p, args: { ...p.args, ...extra } } : p;
|
|
657
658
|
}
|
|
658
659
|
|
|
659
|
-
function placeholder(p,
|
|
660
|
+
function placeholder(p, msg) {
|
|
660
661
|
return {
|
|
661
662
|
tool: 'gemini',
|
|
662
663
|
id: `agy-${p.pid}`,
|
|
@@ -668,7 +669,7 @@ function placeholder(p, text) {
|
|
|
668
669
|
model: null,
|
|
669
670
|
live: true,
|
|
670
671
|
status: 'idle',
|
|
671
|
-
phase: { kind: 'idle',
|
|
672
|
+
phase: { kind: 'idle', msg },
|
|
672
673
|
cost: null,
|
|
673
674
|
now: '',
|
|
674
675
|
updatedAt: Date.now(),
|
|
@@ -683,7 +684,7 @@ export function collectAgy({ showEnded, budget }) {
|
|
|
683
684
|
const procs = findProcesses(isAgy);
|
|
684
685
|
// 기록 폴더가 없으면 agy 를 실행한 적이 없는 것이다 (테스트에서 AITOP_AGY_HOME 으로 실제 기록과 떼어 놓을 때도 쓴다).
|
|
685
686
|
if (!existsSync(AGY_ROOT) || (!procs.length && !showEnded)) return [];
|
|
686
|
-
if (!loadSqlite()) return procs.map((p) => placeholder(p, '
|
|
687
|
+
if (!loadSqlite()) return procs.map((p) => placeholder(p, 'agyOldNode'));
|
|
687
688
|
|
|
688
689
|
const rows = readSummaries();
|
|
689
690
|
const { live, loose } = matchLive(procs, rows);
|
|
@@ -755,7 +756,7 @@ export function collectAgy({ showEnded, budget }) {
|
|
|
755
756
|
members: isLive ? members : [],
|
|
756
757
|
});
|
|
757
758
|
}
|
|
758
|
-
for (const p of loose) out.push(placeholder(p, '
|
|
759
|
+
for (const p of loose) out.push(placeholder(p, 'firstInput'));
|
|
759
760
|
|
|
760
761
|
const keep = new Set(rows.map((r) => r.id));
|
|
761
762
|
for (const id of convs.keys()) if (!keep.has(id)) convs.delete(id);
|
|
@@ -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)
|