@sejuneoh/aitop 0.25.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/pricing.mjs CHANGED
@@ -79,17 +79,46 @@ function priceOf(model) {
79
79
  return lookup(PRICES, model);
80
80
  }
81
81
 
82
+ // 사용량 벡터: [입력(캐시 제외), 출력, 캐시 읽기, 캐시 쓰기 5분, 캐시 쓰기 1시간]. 월별 보관함(monthly.mjs)이
83
+ // 이 벡터를 남겨 두었다가 가격표가 바뀌면 지금 가격으로 다시 계산한다.
84
+ export const VEC = 5;
85
+ export const zeroVec = () => [0, 0, 0, 0, 0];
86
+
87
+ // Claude usage 한 건의 벡터.
88
+ export function claudeVec(u) {
89
+ if (!u) return zeroVec();
90
+ const write1h = u.cache_creation?.ephemeral_1h_input_tokens ?? 0;
91
+ const write5m = u.cache_creation ? (u.cache_creation.ephemeral_5m_input_tokens ?? 0) : (u.cache_creation_input_tokens ?? 0);
92
+ return [u.input_tokens ?? 0, u.output_tokens ?? 0, u.cache_read_input_tokens ?? 0, write5m, write1h];
93
+ }
94
+
95
+ // Claude 벡터 하나의 비용 (m: fast 배수).
96
+ function claudeVecCost(p, v, m) {
97
+ const input = p.input * m;
98
+ const base = v[0] * input + v[1] * p.output * m;
99
+ const cache = v[2] * (p.cacheRead ?? p.input * 0.1) * m + v[3] * input * 1.25 + v[4] * input * 2;
100
+ return { total: (base + cache) / 1e6, noCache: base / 1e6 };
101
+ }
102
+
82
103
  // Claude 메시지 usage 한 건의 환산 비용. total 은 캐시 포함, noCache 는 입력·출력만. 가격표에 없는 모델이면 null.
83
104
  export function claudeCost(model, u) {
84
105
  const p = priceOf(model);
85
106
  if (!p || !u) return null;
86
- const m = u.speed === 'fast' && p.fast ? p.fast : 1;
87
- const input = p.input * m;
88
- const write1h = u.cache_creation?.ephemeral_1h_input_tokens ?? 0;
89
- const write5m = u.cache_creation ? (u.cache_creation.ephemeral_5m_input_tokens ?? 0) : (u.cache_creation_input_tokens ?? 0);
90
- const base = (u.input_tokens ?? 0) * input + (u.output_tokens ?? 0) * p.output * m;
91
- const cache = (u.cache_read_input_tokens ?? 0) * (p.cacheRead ?? p.input * 0.1) * m + write5m * input * 1.25 + write1h * input * 2;
92
- return { total: (base + cache) / 1e6, noCache: base / 1e6 };
107
+ return claudeVecCost(p, claudeVec(u), u.speed === 'fast' && p.fast ? p.fast : 1);
108
+ }
109
+
110
+ // 보관된 벡터(v: 보통, f: fast 모드)를 지금 가격표로 환산한 비용(USD). 가격표에 없는 모델이면 null.
111
+ // agy(Gemini)는 날짜별 가격이라 at(그 달 가운데) 시각의 가격을 쓴다.
112
+ export function vecCost(tool, model, v, f, at = Date.now()) {
113
+ const u = v ?? zeroVec();
114
+ if (tool === 'claude') {
115
+ const p = priceOf(model);
116
+ if (!p) return null;
117
+ return claudeVecCost(p, u, 1).total + (f ? claudeVecCost(p, f, p.fast ?? 1).total : 0);
118
+ }
119
+ const p = tool === 'codex' ? openaiPrice(model) : tool === 'agy' ? geminiPrice(model, at) : null;
120
+ if (!p) return null;
121
+ return (u[0] * p.input + u[1] * p.output + u[2] * (p.cacheRead ?? 0)) / 1e6;
93
122
  }
94
123
 
95
124
  // Codex(OpenAI) API 정가 기준 환산 비용 (USD / 100만 토큰). Claude 와 같이 "API 로 썼다면" 기준이다.
package/src/report.mjs CHANGED
@@ -2,15 +2,25 @@
2
2
  // 값은 날짜별 사용량 장부(claude-ledger.mjs 의 collectDaily)에서 오고, 비용은 화면 헤더와 같은 API 정가 환산이다.
3
3
  // 줄은 최근 날짜가 위(오늘부터 거꾸로)이고, 맨 아래 합계 줄은 위 날짜 줄을 더한 값이다. --json 도 같은 값을 숫자로만 낸다.
4
4
  // 처음 읽는 동안 stderr 가 터미널이면 진행률을 보이고, 시간 상한을 넘으면 읽은 만큼으로 표를 내고 덜 읽었다고 알린다.
5
+ // --report monthly: 최근 N달(기본·최대 12)의 달별 표. 지난 날은 월별 보관함(monthly.mjs), 접기 전의 날은 장부에서 센다.
5
6
  import { t } from './i18n.mjs';
6
- import { fmtTokens, pad, stripControl, width } from './text.mjs';
7
+ import { fmtTokens, pad, stripControl, truncate, width } from './text.mjs';
7
8
  import { money } from './line.mjs';
8
9
  import { KEEP_DAYS, lastDays } from './sources/common.mjs';
10
+ import { projectLabels } from './sources/projects.mjs';
11
+ import { KEEP_MONTHS, lastMonths, monthOf, monthEnd } from './monthly.mjs';
9
12
 
10
- export const KINDS = ['daily'];
11
- export const BY = ['tool', 'model'];
13
+ export const KINDS = ['daily', 'monthly'];
14
+ export const BY = ['tool', 'model', 'project'];
15
+ // --by project 의 특별한 열: 프로젝트를 못 찾은 기록, 열 수 상한을 넘어 합친 나머지. --json 에도 이 이름 그대로 나간다.
16
+ export const UNKNOWN = '(unknown)';
17
+ export const OTHERS = '(others)';
18
+ // 표 머리글 한 칸의 최대 폭 (긴 프로젝트·모델 이름은 줄인다).
19
+ const HEAD_MAX = 24;
12
20
  export const MAX_DAYS = KEEP_DAYS;
13
21
  export const DEFAULT_DAYS = KEEP_DAYS;
22
+ export const MAX_MONTHS = KEEP_MONTHS;
23
+ export const DEFAULT_MONTHS = KEEP_MONTHS;
14
24
  // 전체 시간 상한. 넘으면 읽은 만큼으로 표를 낸다 (캐시에 남은 만큼은 다음 실행이 이어 읽는다).
15
25
  export const MAX_MS = 120_000;
16
26
  // 한 번에 읽는 시간. 이만큼마다 진행률을 고치고 캐시를 저장한다.
@@ -20,19 +30,22 @@ const PROGRESS_AFTER_MS = 400;
20
30
  const FLUSH_MS = 3000;
21
31
  const TOOLS = ['claude', 'codex', 'agy'];
22
32
 
23
- // --report <kind>, --report=<kind>, --by <tool|model>, --by=..., --days <N>, --days=<N> 를 꺼낸다.
24
- // kind 는 --report 를 주지 않았으면 null. --by·--days 는 --report 와 함께일 때만 받는다. capped: --days 를 30으로 줄였는지.
33
+ // --report <kind>, --report=<kind>, --by <tool|model|project>, --by=..., --days <N>, --months <N> (= 꼴도) 를 꺼낸다.
34
+ // kind 는 --report 를 주지 않았으면 null. --by·--days·--months 는 --report 와 함께일 때만 받는다.
35
+ // --days 는 daily, --months 는 monthly 와만 쓴다. capped: --days 를 30으로(--months 를 12로) 줄였는지.
25
36
  export function reportOption(argv) {
26
37
  let kind = null;
27
38
  let by = 'tool';
28
39
  let days = DEFAULT_DAYS;
40
+ let months = DEFAULT_MONTHS;
29
41
  let capped = false;
42
+ let gave = null;
30
43
  let error = null;
31
44
  let extra = false;
32
45
  const rest = [];
33
46
  for (let i = 0; i < argv.length; i++) {
34
47
  const a = argv[i];
35
- const m = /^--(report|by|days)(?:=(.*))?$/.exec(a);
48
+ const m = /^--(report|by|days|months)(?:=(.*))?$/.exec(a);
36
49
  if (!m) {
37
50
  rest.push(a);
38
51
  continue;
@@ -48,15 +61,19 @@ export function reportOption(argv) {
48
61
  else error ??= raw === '' ? t('opt.byMissing') : t('opt.byBad', { value: JSON.stringify(raw) });
49
62
  } else {
50
63
  extra = true;
64
+ gave = name;
65
+ const max = name === 'days' ? MAX_DAYS : MAX_MONTHS;
51
66
  const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
52
67
  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) });
68
+ capped = n > max;
69
+ if (name === 'days') days = Math.min(n, max);
70
+ else months = Math.min(n, max);
71
+ } else error ??= raw === '' ? t(`opt.${name}Missing`) : t(`opt.${name}Bad`, { value: JSON.stringify(raw) });
56
72
  }
57
73
  }
58
74
  if (!error && extra && !kind) error = t('opt.reportOnly');
59
- return { kind, by, days, capped, rest, error };
75
+ if (!error && gave && kind && (gave === 'days') !== (kind === 'daily')) error = t(gave === 'days' ? 'opt.daysDaily' : 'opt.monthsMonthly');
76
+ return { kind, by, days, months, capped, rest, error };
60
77
  }
61
78
 
62
79
  const zero = () => ({ tokens: 0, cost: 0, unpriced: false });
@@ -67,21 +84,29 @@ const add = (a, tokens, cost, unpriced) => {
67
84
  if (unpriced) a.unpriced = true;
68
85
  };
69
86
 
70
- // books: collectDaily 의 [{ tool, days }]. 최근 days 일의 날짜 줄(오늘부터 거꾸로)과 열(도구 또는 모델), 합계를 만든다.
71
- // 열은 기간 합계 비용이 큰 순서(같으면 토큰, 이름 순)이고, 기간 안에 토큰이 하나도 없는 열은 뺀다.
87
+ // 폭을 모를 때(파이프) --by project 표의 열 수 상한.
88
+ export const PIPE_COLUMNS = 8;
89
+
90
+ // books: collectDaily 의 [{ tool, days }] (--by project 면 project 도). 최근 days 일의 날짜 줄(오늘부터 거꾸로)과
91
+ // 열(도구, 모델 또는 프로젝트), 합계를 만든다. 열은 기간 합계 비용이 큰 순서(같으면 토큰, 이름 순)이고, 기간 안에 토큰이 하나도 없는 열은 뺀다.
92
+ // maxColumns: 열이 이보다 많으면 앞의 maxColumns-1 개만 두고 나머지를 OTHERS 로 합친다 (--by project 표만).
72
93
  // unpriced: 가격표에 없는 모델이 끼어 비용이 실제보다 적게 잡혔을 수 있는지.
73
- export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Date.now() } = {}) {
94
+ export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Date.now(), maxColumns = Infinity } = {}) {
74
95
  const dates = lastDays(days, now);
96
+ // 프로젝트 경로 → 짧은 이름. paths 는 거꾸로 (--json 에 이름별 경로를 둔다).
97
+ const labels = by === 'project' ? projectLabels(new Set(books.map((b) => b.project).filter(Boolean))) : new Map();
98
+ const paths = {};
75
99
  const rows = dates.map((date) => ({ date, tokens: 0, cost: 0, unpriced: false, items: {} }));
76
100
  const at = new Map(rows.map((r) => [r.date, r]));
77
101
  const total = { tokens: 0, cost: 0, unpriced: false, items: {} };
78
102
  let unpriced = false;
79
- for (const { tool, days: book } of books) {
103
+ for (const { tool, project, days: book } of books) {
80
104
  for (const [date, d] of Object.entries(book ?? {})) {
81
105
  const row = at.get(date);
82
106
  if (!row) continue;
83
107
  if (d.unknown) unpriced = true;
84
- const parts = by === 'model' ? Object.entries(d.models ?? {}) : [[tool, d]];
108
+ const parts = by === 'model' ? Object.entries(d.models ?? {}) : by === 'project' ? [[labels.get(project) ?? UNKNOWN, d]] : [[tool, d]];
109
+ if (by === 'project' && project) paths[labels.get(project)] = project;
85
110
  for (const [name, x] of parts) {
86
111
  add((row.items[name] ??= zero()), x.tokens, x.cost, x.unknown);
87
112
  add((total.items[name] ??= zero()), x.tokens, x.cost, x.unknown);
@@ -90,30 +115,140 @@ export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Dat
90
115
  add(total, d.tokens, d.cost, d.unknown);
91
116
  }
92
117
  }
118
+ const columns = columnsOf(total, rows, by, maxColumns);
119
+ const out = { report: 'daily', by, days, from: dates.at(-1), to: dates[0], columns, rows, total, unpriced };
120
+ if (by === 'project') out.paths = Object.fromEntries(columns.filter((c) => paths[c]).map((c) => [c, paths[c]]));
121
+ return out;
122
+ }
123
+
124
+ // 열: 기간 합계 비용이 큰 순서(같으면 토큰, 이름 순). 토큰이 하나도 없는 열은 빼고, maxColumns 를 넘으면 OTHERS 로 접는다.
125
+ function columnsOf(total, rows, by, maxColumns) {
93
126
  const rank = (name) => (by === 'tool' ? TOOLS.indexOf(name) : 0);
94
127
  const columns = Object.entries(total.items)
95
128
  .filter(([, x]) => x.tokens > 0 || x.cost > 0)
96
129
  .sort(([a, x], [b, y]) => y.cost - x.cost || y.tokens - x.tokens || rank(a) - rank(b) || a.localeCompare(b))
97
130
  .map(([name]) => name);
98
- return { report: 'daily', by, days, from: dates.at(-1), to: dates[0], columns, rows, total, unpriced };
131
+ if (columns.length > maxColumns) foldOthers(columns, Math.max(1, maxColumns - 1), [...rows, total]);
132
+ return columns;
133
+ }
134
+
135
+ const nextDay = (key) => {
136
+ const [y, m, d] = key.split('-').map(Number);
137
+ return lastDays(1, new Date(y, m - 1, d + 1, 12).getTime())[0];
138
+ };
139
+
140
+ // 월별 표. archive: 월별 보관함(없으면 null), books: 장부 [{ tool, project, days }].
141
+ // 보관함은 through 까지의 날을, 장부는 viewLo(다 읽은 창의 첫날) 이후이면서 through 다음 날부터를 센다 (한 날은 한쪽에서만).
142
+ // liveLo: 장부 쪽에서 원본 기록이 빠짐없이 남은 첫날 (기본 viewLo).
143
+ // 달마다 status: complete(빠짐없이 셌다), partial(일부 날만 셌다), missing(센 날도 값도 없다: 0 이 아니라 모름). current: 이번 달.
144
+ // partial: 장부를 시간 상한 때문에 덜 읽었으면, 장부 쪽 날은 센 날로 치지 않는다 (그 달은 complete 가 되지 않는다).
145
+ export function buildMonthly(books, archive, { by = 'tool', months = DEFAULT_MONTHS, now = Date.now(), viewLo, liveLo, partial = false, maxColumns = Infinity } = {}) {
146
+ const keys = lastMonths(months, now);
147
+ const shown = new Set(keys);
148
+ const today = lastDays(1, now)[0];
149
+ const through = archive?.through ?? null;
150
+ const from = archive?.from ?? null;
151
+ const holes = archive?.holes ?? [];
152
+ viewLo ??= lastDays(KEEP_DAYS, now).at(-1);
153
+ liveLo ??= viewLo;
154
+ const parts = [];
155
+ for (const k of keys) for (const e of archive?.months?.[k] ?? []) parts.push({ month: k, tool: e.t, model: e.m, project: e.p ?? null, tokens: e.n, cost: e.c, unknown: Boolean(e.x) });
156
+ for (const { tool, project, days } of books)
157
+ for (const [d, day] of Object.entries(days ?? {})) {
158
+ if (d < viewLo || d > today || (through && d <= through) || !shown.has(monthOf(d))) continue;
159
+ const models = day.models && Object.keys(day.models).length ? day.models : { unknown: day };
160
+ for (const [model, x] of Object.entries(models)) parts.push({ month: monthOf(d), tool, model, project: project ?? null, tokens: x.tokens, cost: x.cost, unknown: Boolean(x.unknown) });
161
+ }
162
+ const labels = by === 'project' ? projectLabels(new Set(parts.map((p) => p.project).filter(Boolean))) : new Map();
163
+ const paths = {};
164
+ // 센 날인지: 보관함 [from, through] (빈 날 제외) 또는 장부 [liveLo, 오늘].
165
+ const counted = (d) => (!partial && d >= liveLo) || (through && d >= from && d <= through && !holes.some(([a, b]) => d >= a && d <= b));
166
+ const rows = keys.map((month) => {
167
+ let all = 0;
168
+ let got = 0;
169
+ for (let d = `${month}-01`, end = monthEnd(month); d <= end && d <= today; d = nextDay(d)) {
170
+ all++;
171
+ if (counted(d)) got++;
172
+ }
173
+ return { date: month, month, current: month === keys[0], status: got === 0 ? 'missing' : got < all ? 'partial' : 'complete', tokens: 0, cost: 0, unpriced: false, items: {} };
174
+ });
175
+ const at = new Map(rows.map((r) => [r.month, r]));
176
+ const total = { tokens: 0, cost: 0, unpriced: false, items: {} };
177
+ let unpriced = false;
178
+ for (const p of parts) {
179
+ if (!(p.tokens > 0) && !(p.cost > 0)) continue;
180
+ const row = at.get(p.month);
181
+ const name = by === 'model' ? p.model : by === 'project' ? (labels.get(p.project) ?? UNKNOWN) : p.tool;
182
+ if (by === 'project' && p.project) paths[labels.get(p.project)] = p.project;
183
+ if (p.unknown) unpriced = true;
184
+ for (const o of [row, total]) {
185
+ add((o.items[name] ??= zero()), p.tokens, p.cost, p.unknown);
186
+ add(o, p.tokens, p.cost, p.unknown);
187
+ }
188
+ }
189
+ // 센 날이 없어도 값이 있으면(예: Claude 기록은 지워졌지만 Codex 기록은 남은 달) '일부' 로 값을 보인다.
190
+ for (const r of rows) if (r.status === 'missing' && (r.tokens > 0 || r.cost > 0)) r.status = 'partial';
191
+ const columns = columnsOf(total, rows, by, maxColumns);
192
+ const out = { report: 'monthly', by, months, from: keys.at(-1), to: keys[0], columns, rows, total, unpriced };
193
+ if (by === 'project') out.paths = Object.fromEntries(columns.filter((c) => paths[c]).map((c) => [c, paths[c]]));
194
+ return out;
195
+ }
196
+
197
+ // 표 r 을 열 keep 개 + OTHERS 로 접은 복사본 (r 은 그대로).
198
+ function folded(r, keep) {
199
+ const copy = (o) => ({ ...o, items: { ...o.items } });
200
+ const out = { ...r, columns: [...r.columns], rows: r.rows.map(copy), total: copy(r.total) };
201
+ foldOthers(out.columns, keep, [...out.rows, out.total]);
202
+ if (r.paths) out.paths = Object.fromEntries(Object.entries(r.paths).filter(([c]) => out.columns.includes(c)));
203
+ return out;
204
+ }
205
+
206
+ // 표 줄이 터미널 폭 cols 안에 들어가도록, 실제 칸 폭(머리글과 값 중 긴 쪽)을 재어 들어가는 만큼만 열을 남기고 나머지를 OTHERS 로 접는다.
207
+ // 한 열도 안 들어가면 열 1개 + OTHERS 로 낸다.
208
+ export function fitReport(r, cols) {
209
+ // 열이 1개 이하면 접어도 좁아지지 않는다 (빈 OTHERS 만 붙는다).
210
+ if (!(cols > 0) || r.columns.length <= 1 || tableWidth(r) <= cols) return r;
211
+ for (let keep = r.columns.length - 1; keep >= 1; keep--) {
212
+ const f = folded(r, keep);
213
+ if (tableWidth(f) <= cols) return f;
214
+ }
215
+ return folded(r, 1);
216
+ }
217
+
218
+ // 앞의 keep 개 뒤 열들을 OTHERS 한 열로 합친다 (columns 와 각 줄의 items 를 고친다).
219
+ function foldOthers(columns, keep, lines) {
220
+ const rest = columns.splice(keep);
221
+ columns.push(OTHERS);
222
+ for (const o of lines) {
223
+ let sum = null;
224
+ for (const c of rest) {
225
+ const x = o.items[c];
226
+ delete o.items[c];
227
+ if (x) add((sum ??= zero()), x.tokens, x.cost, x.unpriced);
228
+ }
229
+ if (sum) o.items[OTHERS] = sum;
230
+ }
99
231
  }
100
232
 
101
233
  // --json 모양: 키는 영어, 값은 숫자만 (날짜·이름은 문자열). partial: 시간 상한 때문에 덜 읽었는지.
102
234
  // 칸마다 unpriced(가격표에 없는 모델이 끼었는지)를 참·거짓으로 둔다. 화면의 ? 와 같은 뜻이다.
103
235
  export function reportJson(r, version, { partial = false } = {}) {
104
236
  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) }]));
237
+ const monthly = r.report === 'monthly';
238
+ const row = (x) => (monthly ? { month: x.month, current: x.current, status: x.status } : { date: x.date });
105
239
  return {
106
240
  version,
107
241
  report: r.report,
108
242
  by: r.by,
109
- days: r.days,
243
+ ...(monthly ? { months: r.months } : { days: r.days }),
110
244
  from: r.from,
111
245
  to: r.to,
112
246
  basis: 'api',
113
247
  partial,
114
248
  unpriced: r.unpriced,
115
249
  columns: r.columns,
116
- rows: r.rows.map((x) => ({ date: x.date, tokens: x.tokens, cost: x.cost, unpriced: x.unpriced, items: items(x) })),
250
+ ...(r.paths ? { paths: r.paths } : {}),
251
+ rows: r.rows.map((x) => ({ ...row(x), tokens: x.tokens, cost: x.cost, unpriced: x.unpriced, items: items(x) })),
117
252
  total: { tokens: r.total.tokens, cost: r.total.cost, unpriced: r.total.unpriced, items: items(r.total) },
118
253
  };
119
254
  }
@@ -121,19 +256,43 @@ export function reportJson(r, version, { partial = false } = {}) {
121
256
  // 칸 하나: '1.2M $3.40'. 토큰이 없으면 '-'. 가격표에 없는 모델이 끼었으면 화면 헤더처럼 비용 뒤에 ? 를 붙인다 ('$12.30?').
122
257
  const cell = (x) => (x && (x.tokens > 0 || x.cost > 0) ? `${fmtTokens(Math.round(x.tokens))} ${money(x.cost)}${x.unpriced ? '?' : ''}` : '-');
123
258
 
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));
259
+ // 사람이 읽는 표. 머리글·합계 줄 문구는 화면 언어(t)를 따른다. 도구·모델·프로젝트 이름은 그대로 쓴다.
260
+ const colName = (c) => (c === UNKNOWN ? t('report.unknown') : c === OTHERS ? t('report.others') : truncate(stripControl(c), HEAD_MAX));
261
+ // 표의 머리글·날짜 줄·합계 줄 글과 칸 폭 w.
262
+ function table(r) {
263
+ // 모델·프로젝트 이름은 기록에서 온 글이라 제어문자를 지운다.
264
+ const head = [t(r.report === 'monthly' ? 'report.month' : 'report.date'), ...r.columns.map(colName), t('report.total')];
265
+ const line = (label, o) => (o.status === 'missing' ? [label, ...r.columns.map(() => ''), t('report.missing')] : [label, ...r.columns.map((c) => cell(o.items[c])), cell(o)]);
266
+ // 달 표시: 이번 달 *, 일부만 센 달 ~.
267
+ const mark = (x) => (x.month ? `${x.month}${x.current ? ' *' : ''}${x.status === 'partial' ? ' ~' : ''}` : x.date);
268
+ const body = r.rows.map((x) => line(mark(x), x));
130
269
  const foot = line(t('report.total'), r.total);
131
270
  const all = [head, ...body, foot];
132
271
  const w = head.map((_, i) => Math.max(...all.map((row) => width(row[i]))));
272
+ return { head, body, foot, w };
273
+ }
274
+
275
+ // 표 한 줄의 폭 (칸 사이는 두 칸).
276
+ const tableWidth = (r) => {
277
+ const { w } = table(r);
278
+ return w.reduce((a, n) => a + n, 0) + 2 * (w.length - 1);
279
+ };
280
+
281
+ export function formatReport(r, { partial = false } = {}) {
282
+ const { head, body, foot, w } = table(r);
133
283
  const fmt = (row) => row.map((s, i) => pad(s, w[i], i === 0 ? 'left' : 'right')).join(' ').trimEnd();
134
284
  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)];
285
+ const monthly = r.report === 'monthly';
286
+ const title = monthly ? t('report.titleMonthly', { n: r.months, by: t(`report.by.${r.by}`), from: r.from, to: r.to }) : t('report.title', { n: r.days, by: t(`report.by.${r.by}`), from: r.from, to: r.to });
287
+ const out = [title, '', fmt(head), rule, ...body.map(fmt), rule, fmt(foot)];
136
288
  if (!r.columns.length) out.push('', t('report.empty'));
289
+ if (monthly) {
290
+ const notes = [];
291
+ if (r.rows.some((x) => x.current)) notes.push(t('report.noteCurrent'));
292
+ if (r.rows.some((x) => x.status === 'partial')) notes.push(t('report.notePartial'));
293
+ if (r.rows.some((x) => x.status === 'missing')) notes.push(t('report.noteMissing'));
294
+ if (notes.length) out.push('', ...notes);
295
+ }
137
296
  if (r.unpriced) out.push('', t('report.unpriced'));
138
297
  if (partial) out.push('', t('report.partial'));
139
298
  return out.join('\n');
@@ -141,28 +300,74 @@ export function formatReport(r, { partial = false } = {}) {
141
300
 
142
301
  // 장부를 끝까지(또는 시간 상한까지) 읽는다. 짧게 나눠 읽으며 진행률을 onProgress(0~1, 지난 ms)로 알리고 캐시를 저장한다.
143
302
  // 돌려주는 값: { books, partial }. partial 이면 시간 상한 때문에 덜 읽은 기록이 있다.
144
- export async function collectReport({ days = DEFAULT_DAYS, maxMs = MAX_MS, now = Date.now(), onProgress = () => {} } = {}) {
303
+ // by 가 'project' 면 장부마다 project(작업 폴더)를 붙인다.
304
+ // span: 주면 days 대신 최근 span 일(상한 없음) 안에 바뀐 기록을 읽는다 (월별 리포트). 이때는 접지 않는다 (collectMonthly 가 접는다).
305
+ // stepMs: 한 번에 읽는 시간 (테스트가 시간 상한을 흉내 낼 때 줄인다).
306
+ export async function collectReport({ days = DEFAULT_DAYS, span = null, maxMs = MAX_MS, now = Date.now(), by = 'tool', onProgress = () => {}, stepMs = STEP_MS } = {}) {
145
307
  const { createBudget } = await import('./tail.mjs');
146
- const { collectDaily } = await import('./sources/claude-ledger.mjs');
308
+ const { collectDaily, collectSpan } = await import('./sources/claude-ledger.mjs');
147
309
  const { flushCache } = await import('./cache.mjs');
310
+ const { attachProjects } = await import('./sources/projects.mjs');
311
+ const done = (books, partial) => ({ books: by === 'project' ? attachProjects(books) : books, partial });
148
312
  const start = Date.now();
149
313
  let lastFlush = start;
150
314
  for (;;) {
151
- const budget = createBudget(Infinity, STEP_MS);
152
- const r = collectDaily({ budget, now, days });
315
+ const budget = createBudget(Infinity, stepMs);
316
+ const r = span ? collectSpan({ budget, now, days: span }) : collectDaily({ budget, now, days });
153
317
  const spent = Date.now() - start;
154
- if (!budget.exhausted) return { books: r.books, partial: false };
318
+ // 다 읽었으면 지난 날을 월별 보관함에 접는다 (화면을 띄우지 않고 리포트만 쓰는 사용자도 보관함이 이어지게).
319
+ if (!budget.exhausted) {
320
+ const out = done(r.books, false);
321
+ if (!span) await foldDaily(out.books, now, days, by === 'project');
322
+ return out;
323
+ }
155
324
  onProgress(r.size ? 1 - r.pending / r.size : 0, spent);
156
325
  if (Date.now() - lastFlush > FLUSH_MS) {
157
326
  flushCache();
158
327
  lastFlush = Date.now();
159
328
  }
160
- if (spent >= maxMs) return { books: r.books, partial: true };
329
+ if (spent >= maxMs) return done(r.books, true);
161
330
  // 다른 일(신호 처리 등)이 돌 틈을 준다.
162
331
  await new Promise((resolve) => setImmediate(resolve));
163
332
  }
164
333
  }
165
334
 
335
+ // --report daily 가 다 읽은 장부(최근 days 일)를 보관함에 접는다. 접을 날이 없으면 파일만 읽고 끝난다.
336
+ async function foldDaily(books, now, days, attached) {
337
+ const { foldArchive, foldHi } = await import('./monthly.mjs');
338
+ const { attachProjects } = await import('./sources/projects.mjs');
339
+ foldArchive(books, { lo: lastDays(Math.max(7, Math.min(KEEP_DAYS, days)), now).at(-1), hi: foldHi(now), now, attach: attached ? (b) => b : attachProjects });
340
+ }
341
+
342
+ // --report monthly 용 장부 읽기와 접기. 보관함을 아직 1년치로 채운 적이 없거나(backfilled) 마지막으로 접은 날이 30일 창보다 오래됐으면,
343
+ // 12개월 전 달 1일부터 바뀐 기록을 모두 읽어(시간 상한·진행률은 daily 와 같다) 한 번 채운다. 아니면 30일 창만 읽는다.
344
+ // 다 읽었을 때만 접는다. 돌려주는 값: { books, archive, viewLo, liveLo, partial, state } (buildMonthly 참고).
345
+ export async function collectMonthly({ maxMs = MAX_MS, now = Date.now(), onProgress = () => {}, stepMs = STEP_MS } = {}) {
346
+ const m = await import('./monthly.mjs');
347
+ const { archive, state } = m.readArchive();
348
+ const lo30 = lastDays(KEEP_DAYS, now).at(-1);
349
+ const backfill = Boolean(archive) && (!archive.backfilled || archive.through == null || archive.through < m.addDays(lo30, -1));
350
+ const lo = backfill ? m.keepFrom(now) : lo30;
351
+ const [y, mo, d] = lo.split('-').map(Number);
352
+ const span = Math.ceil((now - new Date(y, mo - 1, d).getTime()) / 86400_000) + 1;
353
+ const got = await collectReport({ span, maxMs, now, by: 'project', onProgress, stepMs });
354
+ // 30일 창만 읽을 때도, 보관함이 아는 '빠짐없는 첫날(from)' 보다 앞은 일부로 둔다 (지워진 기록은 창 안에서도 돌아오지 않는다).
355
+ let liveLo = !backfill && archive?.from > lo ? archive.from : lo;
356
+ if (backfill) {
357
+ // Claude Code 는 수정 시각이 오래된 기록부터 지운다 (cleanupPeriodDays, 기본 30일). 남은 Claude 기록 중 가장 오래된
358
+ // 수정 시각이 든 날까지는 지워진 기록이 있었을 수 있어 '일부' 로 두고, 그다음 날부터 빠짐없다고 본다.
359
+ // (오래 이어 쓴 기록 하나에 옛날 날짜가 있어도 경계는 수정 시각이다.) Codex·agy 는 기록을 지우지 않는다.
360
+ const { oldestClaudeMtime } = await import('./sources/claude-ledger.mjs');
361
+ const oldest = oldestClaudeMtime();
362
+ const next = oldest == null ? lo : m.addDays(lastDays(1, oldest)[0], 1);
363
+ liveLo = next > lo ? next : lo;
364
+ }
365
+ if (!got.partial && archive) m.foldArchive(got.books, { lo, hi: m.foldHi(now), complete: liveLo, now, gap: backfill ? 'hole' : 'refuse', backfilled: backfill });
366
+ // 다른 aitop 이 먼저 썼을 수도 있으니 다시 읽는다 (그 경우도 파일 안은 늘 from~through 의 합이다).
367
+ const after = archive ? m.readArchive().archive : null;
368
+ return { books: got.books, archive: after, viewLo: lo, liveLo, partial: got.partial, state };
369
+ }
370
+
166
371
  // stderr 진행률. 터미널일 때만, 처음 PROGRESS_AFTER_MS 가 지난 뒤부터 같은 줄을 고쳐 쓴다. done() 은 그 줄을 지운다.
167
372
  export function progressWriter(stream = process.stderr) {
168
373
  let shown = false;
@@ -7,16 +7,17 @@ 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, addModel, KEEP_DAYS } from './common.mjs';
10
+ import { dayKey, addSlot, addModel, recentDays } from './common.mjs';
11
11
  import { debugIo } from '../log.mjs';
12
12
 
13
- const KIND = 'agy-ledger';
13
+ // 2: 사용량 벡터, 날짜 400일 보관 (#164).
14
+ const KIND = 'agy-ledger2';
14
15
  const DAYS = 7;
15
16
  const LIST_TTL_MS = 30_000;
16
17
 
17
18
  const outOf = (budget) => budget.left <= 0 || (budget.read > 0 && Date.now() >= (budget.deadline ?? Infinity));
18
19
  // 하루 합계 안의 모델별 몫도 따로 복사해, 읽다가 버릴 때 원래 장부가 바뀌지 않게 한다.
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
+ 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, ...(x.u ? { u: [...x.u] } : {}), ...(x.f ? { f: [...x.f] } : {}) }])) } : { ...v }]));
20
21
 
21
22
  export class AgyBook {
22
23
  constructor(path) {
@@ -29,16 +30,39 @@ export class AgyBook {
29
30
  this.slots = {};
30
31
  // 한 번이라도 끝까지 읽었는지. 처음 읽는 동안만 '집계 중' 진행률에 들어간다.
31
32
  this.complete = false;
33
+ // 마지막 갱신이 실패했는지 (열지 못함, 읽는 중 agy 가 씀, 예외). 캐시에서 불러온 값이 낡았을 수 있어
34
+ // 월별 보관함은 이 기록이 쓰였을 수 있는 날(staleFrom 부터)을 접지 않는다 (monthly.mjs staleCut).
35
+ this.stale = false;
36
+ // 실패한 때의 sig. 파일이 바뀌기 전까지는 매 갱신마다 다시 열지 않는다.
37
+ this.failSig = null;
38
+ // 마지막으로 끝까지 읽었을 때의 파일 수정 시각 (그 뒤에 쓴 호출만 빠졌을 수 있다).
39
+ this.okAt = null;
32
40
  const c = loadCache(path, KIND);
33
41
  if (c) {
34
42
  this.idx = c.idx ?? -1;
35
43
  this.model = c.model ?? null;
36
44
  this.days = c.days ?? {};
37
45
  this.slots = c.slots ?? {};
46
+ this.okAt = c.okAt ?? null;
38
47
  this.complete = true;
39
48
  }
40
49
  }
41
50
 
51
+ // 빠졌을 수 있는 첫날. 끝까지 읽은 적이 있으면 그때의 날, 없으면 파일이 생긴 날, 그것도 모르면 맨 처음부터.
52
+ get staleFrom() {
53
+ if (this.okAt != null) return dayKey(this.okAt);
54
+ try {
55
+ const born = statSync(this.path).birthtimeMs;
56
+ if (born > 0) return dayKey(born);
57
+ } catch {}
58
+ return '0000-00-00';
59
+ }
60
+
61
+ fail(sig) {
62
+ this.stale = true;
63
+ this.failSig = sig;
64
+ }
65
+
42
66
  get size() {
43
67
  try {
44
68
  return statSync(this.path).size;
@@ -49,7 +73,7 @@ export class AgyBook {
49
73
 
50
74
  update(budget) {
51
75
  const sig = sigOf(this.path);
52
- if (sig === null || sig === this.sig) return;
76
+ if (sig === null || sig === this.sig || sig === this.failSig) return;
53
77
  if (outOf(budget)) {
54
78
  budget.exhausted = true;
55
79
  return;
@@ -60,8 +84,12 @@ export class AgyBook {
60
84
  let db;
61
85
  let result = null;
62
86
  try {
87
+ opens++;
63
88
  db = openReadOnly(this.path);
64
- if (!db) return;
89
+ if (!db) {
90
+ this.fail(sig);
91
+ return;
92
+ }
65
93
  const has = db.prepare("select 1 from sqlite_master where type = 'table' and name = 'gen_metadata'").get();
66
94
  const last = has ? maxIdx(db, 'gen_metadata') : -1;
67
95
  // 마지막 줄 번호가 줄었으면 기록이 새로 쓰인 것이니 처음부터 다시 센다.
@@ -73,7 +101,7 @@ export class AgyBook {
73
101
  day.tokens += tokens;
74
102
  day.cost += cost?.total ?? 0;
75
103
  day.costNoCache += cost?.noCache ?? 0;
76
- addModel(day, model, tokens, cost?.total ?? 0, !cost && tokens > 0);
104
+ addModel(day, model, tokens, cost?.total ?? 0, !cost && tokens > 0, [u.input, u.output, u.cacheRead, u.cacheWrite, 0]);
77
105
  if (!cost && tokens > 0) day.unknown = true;
78
106
  addSlot(n.slots, at, cost?.total ?? 0, cost?.noCache ?? 0, !cost && tokens > 0);
79
107
  })
@@ -86,21 +114,27 @@ export class AgyBook {
86
114
  } finally {
87
115
  db?.close();
88
116
  }
89
- if (!result) return;
117
+ if (!result) {
118
+ this.fail(sig);
119
+ return;
120
+ }
90
121
  const changed = n.idx !== this.idx;
91
122
  Object.assign(this, n);
92
123
  if (result === 'done') {
93
124
  this.sig = sig;
94
125
  this.complete = true;
126
+ this.stale = false;
127
+ this.failSig = null;
128
+ this.okAt = mtime;
95
129
  }
96
130
  if (result === 'exhausted') budget.exhausted = true;
131
+ // 덜 쓰인 줄(torn)에서 멈췄으면 그 뒤가 빠졌을 수 있다. 파일이 바뀌면(마저 쓰이면) 다시 읽는다.
132
+ if (result === 'torn') this.fail(sig);
97
133
  if (changed) markDirty(this.path, () => this.snapshot(), KIND);
98
134
  }
99
135
 
100
136
  snapshot() {
101
- const keep = new Set(lastDays(KEEP_DAYS));
102
- const days = Object.fromEntries(Object.entries(this.days).filter(([k]) => keep.has(k)));
103
- return { offset: 0, idx: this.idx, model: this.model, days, slots: this.slots };
137
+ return { offset: 0, idx: this.idx, model: this.model, days: recentDays(this.days), slots: this.slots, okAt: this.okAt };
104
138
  }
105
139
  }
106
140
 
@@ -131,10 +165,11 @@ function recentFiles(days = DAYS) {
131
165
 
132
166
  const books = new Map();
133
167
 
134
- // 대화마다 날짜별 합계(days)와 5분 칸(slots), 처음 읽기가 덜 끝난 기록의 크기(pending)·전체 크기(size).
168
+ // 대화마다 날짜별 합계(days)와 5분 칸(slots), 처음 읽기가 덜 끝난 기록의 크기(pending)·전체 크기(size),
169
+ // 기록마다 마지막 갱신이 실패했으면 빠졌을 수 있는 첫날(stale, 아니면 null).
135
170
  // node:sqlite 를 못 쓰는 Node 에서는 비어 있다 (agy 는 프로세스만 보인다).
136
171
  export function collectAgyLedger({ budget, days = DAYS } = {}) {
137
- const out = { days: [], slots: [], pending: 0, size: 0 };
172
+ const out = { days: [], slots: [], paths: [], stale: [], pending: 0, size: 0 };
138
173
  if (!loadSqlite() || !existsSync(join(AGY_ROOT, 'conversations'))) return out;
139
174
  const files = recentFiles(days);
140
175
  const keep = new Set(files);
@@ -146,10 +181,15 @@ export function collectAgyLedger({ budget, days = DAYS } = {}) {
146
181
  const size = b.size;
147
182
  out.size += size;
148
183
  if (!b.complete) out.pending += size;
184
+ // 실패한 기록은 빠졌을 수 있는 첫날, 아니면 null.
185
+ out.stale.push(b.stale ? b.staleFrom : null);
149
186
  out.days.push(b.days);
187
+ out.paths.push(p);
150
188
  out.slots.push(b.slots);
151
189
  }
152
190
  return out;
153
191
  }
154
192
 
155
- export const _test = { reset: () => ((listed = { at: 0, files: [], days: 0 }), books.clear()) };
193
+ // 테스트용: 기록을 연 횟수.
194
+ let opens = 0;
195
+ export const _test = { reset: () => ((listed = { at: 0, files: [], days: 0 }), books.clear()), opens: () => opens };