@sejuneoh/aitop 0.26.0 → 0.28.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/paths.mjs ADDED
@@ -0,0 +1,61 @@
1
+ // OS 마다 다른 경로 규칙을 한곳에 모은다. platform 과 env 를 받아서 테스트가 win32 를 흉내 낼 수 있다.
2
+ import path from 'node:path';
3
+ import { homedir } from 'node:os';
4
+
5
+ const pathFor = (plat) => (plat === 'win32' ? path.win32 : path.posix);
6
+
7
+ // 경로의 마지막 이름. win32 는 / 와 \ 를 모두 나누고, 그 밖의 OS 는 예전처럼 / 만 나눈다.
8
+ export const lastName = (p, plat = process.platform) =>
9
+ String(p ?? '')
10
+ .split(plat === 'win32' ? /[\\/]+/ : '/')
11
+ .filter(Boolean)
12
+ .at(-1) ?? '';
13
+
14
+ // 실행 파일 이름. win32 는 마지막 이름에서 .exe·.cmd·.bat·.ps1 을 떼고, 그 밖의 OS 는 예전처럼 마지막 / 뒤 그대로.
15
+ export const exeName = (p, plat = process.platform) =>
16
+ plat === 'win32' ? lastName(p, plat).replace(/\.(exe|cmd|bat|ps1)$/i, '') : String(p).split('/').pop();
17
+
18
+ // home 아래 경로를 ~ 로 줄인다. win32 는 드라이브 문자·대소문자를 무시하고 \ 와 / 를 같게 본다.
19
+ export function tildeIn(p, home = homedir(), plat = process.platform) {
20
+ const s = String(p ?? '');
21
+ const win = plat === 'win32';
22
+ const norm = (x) => (win ? x.replace(/\//g, '\\').toLowerCase() : x);
23
+ const h = String(home ?? '').replace(win ? /[\\/]+$/ : /\/+$/, '');
24
+ if (!h || s.length < h.length) return s;
25
+ if (norm(s.slice(0, h.length)) !== norm(h)) return s;
26
+ const rest = s.slice(h.length);
27
+ if (rest === '') return '~';
28
+ const sepOk = win ? /^[\\/]/.test(rest) : rest.startsWith('/');
29
+ return sepOk ? '~' + rest : s;
30
+ }
31
+
32
+ // 절대 경로인 환경 변수 값만 쓴다.
33
+ const absEnv = (env, key, plat) => {
34
+ const v = env[key];
35
+ return v && pathFor(plat).isAbsolute(v) ? v : null;
36
+ };
37
+
38
+ // aitop 이 쓰는 폴더(끝이 aitop 또는 aitop\<종류>). XDG_* 가 있으면 어느 OS 든 그것을 쓴다.
39
+ // Linux·macOS: ~/.cache/aitop, ~/.local/state/aitop, ~/.config/aitop
40
+ // Windows: %LOCALAPPDATA%\aitop\cache, %LOCALAPPDATA%\aitop\state, %APPDATA%\aitop
41
+ export function appDir(kind, { env = process.env, home = homedir(), platform = process.platform } = {}) {
42
+ const { join } = pathFor(platform);
43
+ const win = platform === 'win32';
44
+ const local = () => absEnv(env, 'LOCALAPPDATA', platform) ?? join(home, 'AppData', 'Local');
45
+ if (kind === 'cache') {
46
+ // 캐시는 예전부터 XDG_CACHE_HOME 을 절대 경로인지 보지 않고 썼다. 그대로 둔다.
47
+ if (env.XDG_CACHE_HOME != null) return join(env.XDG_CACHE_HOME, 'aitop');
48
+ return win ? join(local(), 'aitop', 'cache') : join(home, '.cache', 'aitop');
49
+ }
50
+ if (kind === 'state') {
51
+ const xdg = absEnv(env, 'XDG_STATE_HOME', platform);
52
+ if (xdg) return join(xdg, 'aitop');
53
+ return win ? join(local(), 'aitop', 'state') : join(home, '.local', 'state', 'aitop');
54
+ }
55
+ if (kind === 'config') {
56
+ const xdg = absEnv(env, 'XDG_CONFIG_HOME', platform);
57
+ if (xdg) return join(xdg, 'aitop');
58
+ return win ? join(absEnv(env, 'APPDATA', platform) ?? join(home, 'AppData', 'Roaming'), 'aitop') : join(home, '.config', 'aitop');
59
+ }
60
+ throw new Error(`unknown dir kind: ${kind}`);
61
+ }
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/procs.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  import { readdirSync, readFileSync, readlinkSync, existsSync } from 'node:fs';
4
4
  import { execFileSync } from 'node:child_process';
5
5
  import { platform } from 'node:os';
6
+ import { exeName } from './paths.mjs';
6
7
 
7
8
  const OS = platform();
8
9
  const HAS_PROC = existsSync('/proc/self');
@@ -24,12 +25,15 @@ export function isAlive(pid) {
24
25
 
25
26
  // ps 는 인자를 공백으로만 이어 보여 준다. 앞 두 칸(실행 파일, node 스크립트)이 없는 절대 경로면
26
27
  // 실제로 있는 경로가 될 때까지 뒤 토큰을 이어 붙인다 (예: ~/Library/Application Support/…/codex.js).
28
+ // 절대 경로: /… 또는 드라이브 문자(C:\…, C:/…).
29
+ const isAbs = (p) => p.startsWith('/') || /^[A-Za-z]:[\\/]/.test(p);
30
+
27
31
  export function joinPaths(tokens, exists = existsSync) {
28
32
  const out = [];
29
33
  let i = 0;
30
34
  while (i < tokens.length) {
31
35
  let cur = tokens[i++];
32
- if (out.length < 2 && cur.startsWith('/') && !exists(cur)) {
36
+ if (out.length < 2 && isAbs(cur) && !exists(cur)) {
33
37
  let j = i;
34
38
  let joined = cur;
35
39
  while (j < tokens.length && j - i < 8) {
@@ -133,7 +137,8 @@ export function findProcesses(match) {
133
137
  return found.map((p) => ({ ...p, cwd: cwdOf(p.pid) }));
134
138
  }
135
139
 
136
- const base = (p) => p.split('/').pop();
140
+ // 실행 파일 이름 (paths.mjs exeName). Windows 에서만 \ 도 나누고 .exe·.cmd 등을 뗀다 (codex.cmd, agy.exe).
141
+ const base = (p) => exeName(p);
137
142
 
138
143
  // `codex` 는 node 스크립트(…/bin/codex.js)이거나 네이티브 바이너리(codex-*)로 뜬다.
139
144
  export function isCodex(argv) {
package/src/report.mjs CHANGED
@@ -2,13 +2,15 @@
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
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';
9
10
  import { projectLabels } from './sources/projects.mjs';
11
+ import { KEEP_MONTHS, lastMonths, monthOf, monthEnd } from './monthly.mjs';
10
12
 
11
- export const KINDS = ['daily'];
13
+ export const KINDS = ['daily', 'monthly'];
12
14
  export const BY = ['tool', 'model', 'project'];
13
15
  // --by project 의 특별한 열: 프로젝트를 못 찾은 기록, 열 수 상한을 넘어 합친 나머지. --json 에도 이 이름 그대로 나간다.
14
16
  export const UNKNOWN = '(unknown)';
@@ -17,6 +19,8 @@ export const OTHERS = '(others)';
17
19
  const HEAD_MAX = 24;
18
20
  export const MAX_DAYS = KEEP_DAYS;
19
21
  export const DEFAULT_DAYS = KEEP_DAYS;
22
+ export const MAX_MONTHS = KEEP_MONTHS;
23
+ export const DEFAULT_MONTHS = KEEP_MONTHS;
20
24
  // 전체 시간 상한. 넘으면 읽은 만큼으로 표를 낸다 (캐시에 남은 만큼은 다음 실행이 이어 읽는다).
21
25
  export const MAX_MS = 120_000;
22
26
  // 한 번에 읽는 시간. 이만큼마다 진행률을 고치고 캐시를 저장한다.
@@ -26,19 +30,22 @@ const PROGRESS_AFTER_MS = 400;
26
30
  const FLUSH_MS = 3000;
27
31
  const TOOLS = ['claude', 'codex', 'agy'];
28
32
 
29
- // --report <kind>, --report=<kind>, --by <tool|model|project>, --by=..., --days <N>, --days=<N> 를 꺼낸다.
30
- // 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로) 줄였는지.
31
36
  export function reportOption(argv) {
32
37
  let kind = null;
33
38
  let by = 'tool';
34
39
  let days = DEFAULT_DAYS;
40
+ let months = DEFAULT_MONTHS;
35
41
  let capped = false;
42
+ let gave = null;
36
43
  let error = null;
37
44
  let extra = false;
38
45
  const rest = [];
39
46
  for (let i = 0; i < argv.length; i++) {
40
47
  const a = argv[i];
41
- const m = /^--(report|by|days)(?:=(.*))?$/.exec(a);
48
+ const m = /^--(report|by|days|months)(?:=(.*))?$/.exec(a);
42
49
  if (!m) {
43
50
  rest.push(a);
44
51
  continue;
@@ -54,15 +61,19 @@ export function reportOption(argv) {
54
61
  else error ??= raw === '' ? t('opt.byMissing') : t('opt.byBad', { value: JSON.stringify(raw) });
55
62
  } else {
56
63
  extra = true;
64
+ gave = name;
65
+ const max = name === 'days' ? MAX_DAYS : MAX_MONTHS;
57
66
  const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
58
67
  if (n > 0) {
59
- capped = n > MAX_DAYS;
60
- days = Math.min(n, MAX_DAYS);
61
- } 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) });
62
72
  }
63
73
  }
64
74
  if (!error && extra && !kind) error = t('opt.reportOnly');
65
- 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 };
66
77
  }
67
78
 
68
79
  const zero = () => ({ tokens: 0, cost: 0, unpriced: false });
@@ -104,13 +115,81 @@ export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Dat
104
115
  add(total, d.tokens, d.cost, d.unknown);
105
116
  }
106
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) {
107
126
  const rank = (name) => (by === 'tool' ? TOOLS.indexOf(name) : 0);
108
127
  const columns = Object.entries(total.items)
109
128
  .filter(([, x]) => x.tokens > 0 || x.cost > 0)
110
129
  .sort(([a, x], [b, y]) => y.cost - x.cost || y.tokens - x.tokens || rank(a) - rank(b) || a.localeCompare(b))
111
130
  .map(([name]) => name);
112
131
  if (columns.length > maxColumns) foldOthers(columns, Math.max(1, maxColumns - 1), [...rows, total]);
113
- const out = { report: 'daily', by, days, from: dates.at(-1), to: dates[0], columns, rows, total, unpriced };
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 };
114
193
  if (by === 'project') out.paths = Object.fromEntries(columns.filter((c) => paths[c]).map((c) => [c, paths[c]]));
115
194
  return out;
116
195
  }
@@ -155,11 +234,13 @@ function foldOthers(columns, keep, lines) {
155
234
  // 칸마다 unpriced(가격표에 없는 모델이 끼었는지)를 참·거짓으로 둔다. 화면의 ? 와 같은 뜻이다.
156
235
  export function reportJson(r, version, { partial = false } = {}) {
157
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 });
158
239
  return {
159
240
  version,
160
241
  report: r.report,
161
242
  by: r.by,
162
- days: r.days,
243
+ ...(monthly ? { months: r.months } : { days: r.days }),
163
244
  from: r.from,
164
245
  to: r.to,
165
246
  basis: 'api',
@@ -167,7 +248,7 @@ export function reportJson(r, version, { partial = false } = {}) {
167
248
  unpriced: r.unpriced,
168
249
  columns: r.columns,
169
250
  ...(r.paths ? { paths: r.paths } : {}),
170
- rows: r.rows.map((x) => ({ date: x.date, tokens: x.tokens, cost: x.cost, unpriced: x.unpriced, items: items(x) })),
251
+ rows: r.rows.map((x) => ({ ...row(x), tokens: x.tokens, cost: x.cost, unpriced: x.unpriced, items: items(x) })),
171
252
  total: { tokens: r.total.tokens, cost: r.total.cost, unpriced: r.total.unpriced, items: items(r.total) },
172
253
  };
173
254
  }
@@ -180,9 +261,11 @@ const colName = (c) => (c === UNKNOWN ? t('report.unknown') : c === OTHERS ? t('
180
261
  // 표의 머리글·날짜 줄·합계 줄 글과 칸 폭 w.
181
262
  function table(r) {
182
263
  // 모델·프로젝트 이름은 기록에서 온 글이라 제어문자를 지운다.
183
- const head = [t('report.date'), ...r.columns.map(colName), t('report.total')];
184
- const line = (label, o) => [label, ...r.columns.map((c) => cell(o.items[c])), cell(o)];
185
- const body = r.rows.map((x) => line(x.date, x));
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));
186
269
  const foot = line(t('report.total'), r.total);
187
270
  const all = [head, ...body, foot];
188
271
  const w = head.map((_, i) => Math.max(...all.map((row) => width(row[i]))));
@@ -199,8 +282,17 @@ export function formatReport(r, { partial = false } = {}) {
199
282
  const { head, body, foot, w } = table(r);
200
283
  const fmt = (row) => row.map((s, i) => pad(s, w[i], i === 0 ? 'left' : 'right')).join(' ').trimEnd();
201
284
  const rule = w.map((n) => '-'.repeat(n)).join(' ');
202
- 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)];
203
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
+ }
204
296
  if (r.unpriced) out.push('', t('report.unpriced'));
205
297
  if (partial) out.push('', t('report.partial'));
206
298
  return out.join('\n');
@@ -209,19 +301,26 @@ export function formatReport(r, { partial = false } = {}) {
209
301
  // 장부를 끝까지(또는 시간 상한까지) 읽는다. 짧게 나눠 읽으며 진행률을 onProgress(0~1, 지난 ms)로 알리고 캐시를 저장한다.
210
302
  // 돌려주는 값: { books, partial }. partial 이면 시간 상한 때문에 덜 읽은 기록이 있다.
211
303
  // by 가 'project' 면 장부마다 project(작업 폴더)를 붙인다.
212
- export async function collectReport({ days = DEFAULT_DAYS, maxMs = MAX_MS, now = Date.now(), by = 'tool', onProgress = () => {} } = {}) {
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 } = {}) {
213
307
  const { createBudget } = await import('./tail.mjs');
214
- const { collectDaily } = await import('./sources/claude-ledger.mjs');
308
+ const { collectDaily, collectSpan } = await import('./sources/claude-ledger.mjs');
215
309
  const { flushCache } = await import('./cache.mjs');
216
310
  const { attachProjects } = await import('./sources/projects.mjs');
217
311
  const done = (books, partial) => ({ books: by === 'project' ? attachProjects(books) : books, partial });
218
312
  const start = Date.now();
219
313
  let lastFlush = start;
220
314
  for (;;) {
221
- const budget = createBudget(Infinity, STEP_MS);
222
- 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 });
223
317
  const spent = Date.now() - start;
224
- if (!budget.exhausted) return done(r.books, 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
+ }
225
324
  onProgress(r.size ? 1 - r.pending / r.size : 0, spent);
226
325
  if (Date.now() - lastFlush > FLUSH_MS) {
227
326
  flushCache();
@@ -233,6 +332,42 @@ export async function collectReport({ days = DEFAULT_DAYS, maxMs = MAX_MS, now =
233
332
  }
234
333
  }
235
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
+
236
371
  // stderr 진행률. 터미널일 때만, 처음 PROGRESS_AFTER_MS 가 지난 뒤부터 같은 줄을 고쳐 쓴다. done() 은 그 줄을 지운다.
237
372
  export function progressWriter(stream = process.stderr) {
238
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: [], paths: [], 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,6 +181,8 @@ 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);
150
187
  out.paths.push(p);
151
188
  out.slots.push(b.slots);
@@ -153,4 +190,6 @@ export function collectAgyLedger({ budget, days = DAYS } = {}) {
153
190
  return out;
154
191
  }
155
192
 
156
- 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 };
@@ -522,7 +522,9 @@ export function cwdOf(workspaceUris) {
522
522
  try {
523
523
  const first = JSON.parse(workspaceUris || '[]')[0];
524
524
  if (!first) return null;
525
- return first.startsWith('file:') ? fileURLToPath(first) : first;
525
+ const p = first.startsWith('file:') ? fileURLToPath(first) : first;
526
+ // Windows 의 file:///c%3A/… 는 c:\… 가 되므로 드라이브 문자를 대문자로 맞춘다 (Claude·Codex 의 C:\ 와 같은 프로젝트로 묶이게).
527
+ return process.platform === 'win32' ? p.replace(/^[a-z](?=:)/, (d) => d.toUpperCase()) : p;
526
528
  } catch (e) {
527
529
  debug('agy', 'workspace_uris parse failed', e);
528
530
  return null;