@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/README.md CHANGED
@@ -17,7 +17,9 @@
17
17
 
18
18
  ## Install
19
19
 
20
- Requires Node.js 22+ on Linux, macOS or WSL.
20
+ Requires Node.js 22+ on Linux, macOS, WSL or Windows.
21
+
22
+ Native Windows support is early (Windows Terminal recommended): Claude Code and Codex sessions, `--once`, `--json`, `--report` and `--doctor` work, but process detection, desktop notifications and `--on-waiting` are not there yet ([#195](https://github.com/SejuneOh/aitop/issues/195)-[#197](https://github.com/SejuneOh/aitop/issues/197)). Until then a Codex session counts as running while its log was written in the last 10 minutes, so it drops out during a long step that writes nothing for over 10 minutes, and a crashed session can stay up to 10 minutes. Cache, log and config live in `%LOCALAPPDATA%\aitop\cache`, `%LOCALAPPDATA%\aitop\state` and `%APPDATA%\aitop` unless `XDG_*` is set.
21
23
 
22
24
  ```bash
23
25
  npm install -g @sejuneoh/aitop
@@ -33,6 +35,7 @@ aitop --json print a snapshot as JSON and exit
33
35
  aitop --doctor check which tools and logs aitop can see
34
36
  aitop --line print one short status line and exit (for tmux, e.g. $54.13/$50 wait 2 run 3 $3.1/h)
35
37
  aitop --report daily daily cost table and exit
38
+ aitop --report monthly monthly cost table (last 12 months) and exit
36
39
  aitop --help all options
37
40
  aitop --lang ko Korean screen, help, doctor and error messages (also AITOP_LANG=ko or "lang": "ko" in the config file)
38
41
  ```
@@ -50,6 +53,12 @@ aitop --report daily --by model --days 14
50
53
  aitop --report daily --by project --days 7
51
54
  ```
52
55
 
56
+ `aitop --report monthly [--by tool|model|project] [--months N] [--json]` prints the same per month, newest first, for up to 12 months. Past days are folded into `monthly.json` in the cache folder (`~/.cache/aitop`, outside the versioned cache) about two days later, so monthly totals survive cache rebuilds and Claude Code deleting old transcripts. The first run reads up to a year of remaining logs once. `*` marks this month, `~` a month only partly counted (for example before the oldest remaining Claude log), and `no data` a month with neither logs nor archive (unknown, not zero). The archive keeps token counts per type, so costs are recomputed when the price table changes. In `--json`, rows have `month`, `current` and `status` (`complete`, `partial` or `missing`).
57
+
58
+ ```
59
+ aitop --report monthly --by model --months 6
60
+ ```
61
+
53
62
  ### tmux status line
54
63
 
55
64
  `aitop --line` prints today's cost (API list price, `/$<budget>` when a daily budget is set), the number of sessions waiting for you (`wait 2`, Claude Code counted live), the number of sessions running (`run 3`), and spend over the last hour. Items that are 0 are left out, and `--line-width N` (default 40) drops items from the end. It reads only aitop's cache, so it is fast once `aitop` has run before; with no cache yet it prints `...` after about 1.5 seconds. The running count (and waiting Antigravity sessions) come from a small summary that the live screen, `--once` and `--json` write to the cache; when no summary is newer than 60 seconds, `run` is left out rather than shown wrong. `--line=tmux` adds tmux colors, `NO_COLOR` turns them off.
@@ -61,7 +70,7 @@ set -g status-interval 15
61
70
 
62
71
  Keys: `↑↓` select · `n` next session to check · `/` search · `s` sort · `g` group · `p` pin · `f` changed files · `?` help · `q` quit
63
72
 
64
- Settings can also go in `~/.config/aitop/config.json`. See `aitop --help` or the [detailed manual (Korean)](https://github.com/SejuneOh/aitop/blob/main/docs/README.ko.md).
73
+ Settings can also go in `~/.config/aitop/config.json` (`%APPDATA%\aitop\config.json` on Windows). See `aitop --help` or the [detailed manual (Korean)](https://github.com/SejuneOh/aitop/blob/main/docs/README.ko.md).
65
74
 
66
75
  ## License
67
76
 
package/bin/aitop.mjs CHANGED
@@ -41,7 +41,7 @@ if (line.error) {
41
41
  process.stderr.write(`aitop: ${line.error}\n`);
42
42
  process.exit(2);
43
43
  }
44
- // --report daily, --by tool|model|project, --days <N> 은 reportOption 이 꺼낸다.
44
+ // --report daily|monthly, --by tool|model|project, --days <N>, --months <N> 은 reportOption 이 꺼낸다.
45
45
  const report = reportOption(line.rest);
46
46
  if (report.error) {
47
47
  process.stderr.write(`aitop: ${report.error}\n`);
@@ -147,22 +147,26 @@ if (line.mode) {
147
147
  }
148
148
 
149
149
  // --report: 날짜별 사용량 표(또는 --json)를 내고 끝낸다. 실시간 화면·세션 목록은 읽지 않고 장부만 읽는다.
150
- // 처음 실행은 30일치 기록을 읽으므로 stderr 가 터미널이면 진행률을 보이고, 시간 상한(AITOP_REPORT_MS, 기본 120초)을 넘으면 읽은 만큼 낸다.
150
+ // --report monthly 는 월별 보관함(monthly.mjs)과 장부를 합친다.
151
+ // 처음 실행은 30일치(monthly 는 1년치) 기록을 읽으므로 stderr 가 터미널이면 진행률을 보이고, 시간 상한(AITOP_REPORT_MS, 기본 120초)을 넘으면 읽은 만큼 낸다.
151
152
  if (report.kind) {
152
- const { buildReport, collectReport, fitReport, formatReport, PIPE_COLUMNS, progressWriter, reportJson, MAX_DAYS } = await import('../src/report.mjs');
153
+ const { buildMonthly, buildReport, collectMonthly, collectReport, fitReport, formatReport, PIPE_COLUMNS, progressWriter, reportJson, MAX_DAYS, MAX_MONTHS } = await import('../src/report.mjs');
153
154
  const { flushCache } = await import('../src/cache.mjs');
154
- if (report.capped) process.stderr.write(`aitop: ${t('report.capped', { n: MAX_DAYS })}\n`);
155
+ const monthly = report.kind === 'monthly';
156
+ if (report.capped) process.stderr.write(`aitop: ${monthly ? t('report.cappedMonths', { n: MAX_MONTHS }) : t('report.capped', { n: MAX_DAYS })}\n`);
155
157
  const progress = progressWriter();
156
158
  const maxMs = Number(process.env.AITOP_REPORT_MS) > 0 ? Number(process.env.AITOP_REPORT_MS) : undefined;
157
159
  const now = Date.now();
158
- const got = await collectReport({ days: report.days, maxMs, now, by: report.by, onProgress: progress.update });
160
+ // monthly: 보관함(monthly.json)과 장부를 합친다. 처음이면 1년치 기록을 한 번 읽어 보관함을 채운다.
161
+ const got = monthly ? await collectMonthly({ maxMs, now, onProgress: progress.update }) : await collectReport({ days: report.days, maxMs, now, by: report.by, onProgress: progress.update });
159
162
  progress.done();
160
163
  flushCache();
161
164
  if (got.partial && args.has('--json')) process.stderr.write(`aitop: ${t('report.partial')}\n`);
162
165
  // --by project 표는 터미널 폭(터미널이 아니면 COLUMNS 를 export 한 경우에만 그 폭, 아니면 열 8개)에 맞춰 열을 줄이고 나머지를 하나로 합친다 (--json 은 다 낸다).
163
166
  const fit = report.by === 'project' && !args.has('--json');
164
167
  const cols = process.stdout.isTTY ? process.stdout.columns : Number(process.env.COLUMNS) || 0;
165
- let r = buildReport(got.books, { by: report.by, days: report.days, now, maxColumns: fit && !cols ? PIPE_COLUMNS : Infinity });
168
+ const maxColumns = fit && !cols ? PIPE_COLUMNS : Infinity;
169
+ let r = monthly ? buildMonthly(got.books, got.archive, { by: report.by, months: report.months, now, viewLo: got.viewLo, liveLo: got.liveLo, partial: got.partial, maxColumns }) : buildReport(got.books, { by: report.by, days: report.days, now, maxColumns });
166
170
  if (fit && cols) r = fitReport(r, cols);
167
171
  const text = args.has('--json') ? JSON.stringify(reportJson(r, VERSION, { partial: got.partial }), null, 2) : formatReport(r, { partial: got.partial });
168
172
  process.stdout.on('error', (err) => process.exit(err.code === 'EPIPE' ? 0 : 1));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.26.0",
3
+ "version": "0.28.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -18,7 +18,8 @@
18
18
  },
19
19
  "os": [
20
20
  "linux",
21
- "darwin"
21
+ "darwin",
22
+ "win32"
22
23
  ],
23
24
  "homepage": "https://github.com/SejuneOh/aitop#readme",
24
25
  "bugs": "https://github.com/SejuneOh/aitop/issues",
@@ -32,7 +33,7 @@
32
33
  },
33
34
  "scripts": {
34
35
  "start": "node bin/aitop.mjs",
35
- "test": "AITOP_LANG=ko node --test test/*.test.mjs",
36
- "test:e2e": "AITOP_LANG=ko node --test test/e2e/*.e2e.mjs"
36
+ "test": "node --import ./test/lang-ko.mjs --test test/*.test.mjs",
37
+ "test:e2e": "node --import ./test/lang-ko.mjs --test test/e2e/*.e2e.mjs"
37
38
  }
38
39
  }
package/src/cache.mjs CHANGED
@@ -3,14 +3,17 @@
3
3
  import { readFileSync, writeFileSync, mkdirSync, renameSync, statSync, readdirSync, rmSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
5
  import { homedir } from 'node:os';
6
+ import { appDir } from './paths.mjs';
6
7
  import { createHash } from 'node:crypto';
7
8
  import { PRICE_TAG } from './pricing.mjs';
8
9
  import { debug, debugIo } from './log.mjs';
9
10
 
10
11
  // 캐시 형식이 바뀌면 VERSION 을, 가격표가 바뀌면 PRICE_TAG 가 폴더 이름을 바꿔서 예전 캐시를 버린다.
11
12
  // 14: 장부의 하루 합계에 모델별 몫(models)을 더하고, 날짜를 10일이 아니라 30일 남긴다 (#128).
13
+ // 장부(ledger)만 형식이 바뀔 때는 VERSION 대신 장부의 kind 이름을 바꿔 장부만 다시 센다 (세션 화면 캐시는 그대로).
12
14
  const VERSION = 14;
13
- const ROOT = join(process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'aitop');
15
+ // Windows 는 XDG_CACHE_HOME 이 없으면 %LOCALAPPDATA%\aitop\cache (paths.mjs).
16
+ const ROOT = appDir('cache', { home: homedir() });
14
17
  export const CACHE_ROOT = ROOT;
15
18
  const NAME = `v${VERSION}-${PRICE_TAG}`;
16
19
  const DIR = join(ROOT, NAME);
@@ -26,7 +29,8 @@ function removeOldDirs() {
26
29
  try {
27
30
  for (const d of readdirSync(ROOT)) {
28
31
  // summary.json(--line 용 요약, summary.mjs)은 버전 폴더 밖에 두고 여기서 지우지 않는다. 남은 임시 파일은 일주일 뒤 지운다.
29
- if (d === NAME || d === 'summary.json') continue;
32
+ // monthly.json(월별 보관함, monthly.mjs)과 깨져서 옆으로 옮긴 monthly.json.bad-* 도 사용자 기록이라 지우지 않는다.
33
+ if (d === NAME || d === 'summary.json' || d === 'monthly.json' || d.startsWith('monthly.json.bad-')) continue;
30
34
  const p = join(ROOT, d);
31
35
  // 이 버전보다 낮은 형식(v2, v6-… 등)은 더 이상 어떤 버전도 쓰지 않으므로 바로 지운다.
32
36
  const ver = Number(/^v(\d+)(?:-|$)/.exec(d)?.[1]);
package/src/config.mjs CHANGED
@@ -4,7 +4,8 @@
4
4
  // 화면 모듈은 불러올 때 테마·아이콘을 고르므로, 이 모듈은 다른 aitop 모듈을 불러오지 않는다.
5
5
  import { closeSync, constants, fstatSync, openSync, readSync, statSync } from 'node:fs';
6
6
  import { homedir } from 'node:os';
7
- import { isAbsolute, join } from 'node:path';
7
+ import { posix, win32 } from 'node:path';
8
+ import { appDir } from './paths.mjs';
8
9
  import { stripControl } from './text.mjs';
9
10
  import { langValue, localeLang, t } from './i18n.mjs';
10
11
 
@@ -71,9 +72,9 @@ export const KEYS = {
71
72
  lang: { ok: oneOf('ko', 'en'), expect: ['ko', 'en'], def: localeLang, env: ['AITOP_LANG', langValue], envProblem: true },
72
73
  };
73
74
 
74
- export function configPath(env = process.env, home = homedir()) {
75
- const xdg = env.XDG_CONFIG_HOME;
76
- return join(xdg && isAbsolute(xdg) ? xdg : join(home, '.config'), 'aitop', 'config.json');
75
+ // Windows 는 XDG_CONFIG_HOME 이 없으면 %APPDATA%\aitop\config.json.
76
+ export function configPath(env = process.env, home = homedir(), platform = process.platform) {
77
+ return (platform === 'win32' ? win32 : posix).join(appDir('config', { env, home, platform }), 'config.json');
77
78
  }
78
79
 
79
80
  // 설정 파일은 작다. 이보다 크면 읽지 않는다.
package/src/doctor.mjs CHANGED
@@ -9,6 +9,7 @@ import { AGY_ROOT } from './sources/antigravity.mjs';
9
9
  import { loadSqlite, openReadOnly } from './sqlite.mjs';
10
10
  import { fmtAgo, pad, stripControl } from './text.mjs';
11
11
  import { BRAND } from './brand.mjs';
12
+ import { tildeIn } from './paths.mjs';
12
13
  import { findNotifier, isWsl } from './notify.mjs';
13
14
  import { getLang, t as tr } from './i18n.mjs';
14
15
 
@@ -20,7 +21,8 @@ const CLAUDE = process.env.CLAUDE_CONFIG_DIR ?? join(HOME, '.claude');
20
21
  const CODEX = join(process.env.CODEX_HOME ?? join(HOME, '.codex'), 'sessions');
21
22
  const GEMINI = join(process.env.GEMINI_HOME ?? join(HOME, '.gemini'), 'tmp');
22
23
 
23
- const tilde = (p) => (p.startsWith(HOME + '/') ? '~' + p.slice(HOME.length) : p);
24
+ // Windows 는 \ 와 대소문자를 무시하고 줄인다 (paths.mjs).
25
+ const tilde = (p) => tildeIn(p, HOME);
24
26
  const ls = (dir) => {
25
27
  try {
26
28
  return readdirSync(dir, { withFileTypes: true });
package/src/i18n.mjs CHANGED
@@ -69,6 +69,8 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
69
69
  aitop --report daily [--by tool|model|project] [--days N] [--json] 최근 N일(기본·최대 30)의 날짜별 토큰·비용(API 정가 환산)을
70
70
  도구별·모델별·프로젝트별 표로 내고 끝낸다. 최근 날짜가 위, 맨 아래는 합계. 처음 실행은 30일치 기록을 읽느라 오래 걸릴 수 있다
71
71
  프로젝트는 작업 폴더의 마지막 이름이고, 열이 터미널 폭을 넘으면 비용이 작은 쪽을 (그 외) 로 합친다
72
+ aitop --report monthly [--by tool|model|project] [--months N] [--json] 최근 N달(기본·최대 12)의 달별 표. 지난 날은 캐시 폴더의
73
+ monthly.json 에 달별로 남겨 기록이 지워져도 남는다. 처음 실행은 1년치 기록을 한 번 읽는다. * 이번 달, ~ 일부만 센 달
72
74
  aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
73
75
  aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
74
76
  aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (notify-send · osascript, 없으면 건너뜀)
@@ -111,6 +113,9 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
111
113
  aitop --report daily [--by tool|model|project] [--days N] [--json] print daily tokens and cost (API list price) for the last N days
112
114
  (default and max 30) by tool, model or project, then exit. Newest day first, total at the bottom. The first run reads 30 days of logs and may take a while
113
115
  A project is the last folder name of the working directory. Columns beyond the terminal width are merged into (others)
116
+ aitop --report monthly [--by tool|model|project] [--months N] [--json] the same per month for the last N months (default and max 12).
117
+ Past days are kept per month in monthly.json in the cache folder, so they survive log cleanup. The first run reads up to a year of logs once.
118
+ * marks this month, ~ a month only partly counted
114
119
  aitop --doctor check Claude, Codex, Antigravity and Gemini logs, running processes and the config file (works with --json)
115
120
  aitop --bell ring the terminal bell when a session starts waiting for you
116
121
  aitop --notify show a desktop notification when a session starts waiting (notify-send or osascript, skipped if missing)
@@ -195,13 +200,17 @@ export const STRINGS = {
195
200
  'opt.lineBad': '--line 값 {value} 이 잘못되었습니다 (plain 또는 tmux)',
196
201
  'opt.lineWidthMissing': '--line-width 값이 없습니다 (글자 수)',
197
202
  'opt.lineWidthBad': '--line-width 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
198
- 'opt.reportMissing': '--report 값이 없습니다 (daily)',
199
- 'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily)',
203
+ 'opt.reportMissing': '--report 값이 없습니다 (daily 또는 monthly)',
204
+ 'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily 또는 monthly)',
200
205
  'opt.byMissing': '--by 값이 없습니다 (tool, model 또는 project)',
201
206
  'opt.byBad': '--by 값 {value} 이 잘못되었습니다 (tool, model 또는 project)',
202
207
  'opt.daysMissing': '--days 값이 없습니다 (일 수)',
203
208
  'opt.daysBad': '--days 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
204
- 'opt.reportOnly': '--by, --days 는 --report 와 함께 쓴다',
209
+ 'opt.monthsMissing': '--months 값이 없습니다 (달 수)',
210
+ 'opt.monthsBad': '--months 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
211
+ 'opt.daysDaily': '--days 는 --report daily 와 함께 쓴다 (monthly 는 --months)',
212
+ 'opt.monthsMonthly': '--months 는 --report monthly 와 함께 쓴다 (daily 는 --days)',
213
+ 'opt.reportOnly': '--by, --days, --months 는 --report 와 함께 쓴다',
205
214
 
206
215
  // 기간 리포트 (--report daily). 도구·모델 이름은 번역하지 않는다.
207
216
  'report.title': '날짜별 사용량 · 최근 {n}일 ({from} ~ {to}) · {by} · API 정가 환산',
@@ -217,6 +226,13 @@ export const STRINGS = {
217
226
  'report.partial': '시간 상한 안에 기록을 다 읽지 못해 일부만 셌습니다. 다시 실행하면 이어 읽습니다',
218
227
  'report.progress': '사용량 장부 읽는 중 {pct}% ({s}초)',
219
228
  'report.capped': '--days 는 장부가 남기는 {n}일까지만 볼 수 있어 {n}일로 줄입니다',
229
+ 'report.cappedMonths': '--months 는 보관함이 남기는 {n}달까지만 볼 수 있어 {n}달로 줄입니다',
230
+ 'report.titleMonthly': '달별 사용량 · 최근 {n}달 ({from} ~ {to}) · {by} · API 정가 환산',
231
+ 'report.month': '달',
232
+ 'report.missing': '기록 없음',
233
+ 'report.noteCurrent': '* 이번 달 (아직 진행 중)',
234
+ 'report.notePartial': '~ 일부 날만 셌습니다 (그 전 기록이 지워졌거나 보관함이 비어 있던 때)',
235
+ 'report.noteMissing': '기록 없음: 남은 기록도 보관함도 없는 달입니다 (0 이 아니라 모름)',
220
236
 
221
237
  'cfg.notFile': '설정 파일이 일반 파일이 아니라 읽지 않습니다',
222
238
  'cfg.tooBig': '설정 파일이 {kb}KB 를 넘어 읽지 않습니다',
@@ -541,13 +557,17 @@ export const STRINGS = {
541
557
  'opt.lineBad': 'bad --line value {value} (plain or tmux)',
542
558
  'opt.lineWidthMissing': '--line-width needs a value (characters)',
543
559
  'opt.lineWidthBad': 'bad --line-width value {value} (a whole number above 0)',
544
- 'opt.reportMissing': '--report needs a value (daily)',
545
- 'opt.reportBad': 'bad --report value {value} (daily)',
560
+ 'opt.reportMissing': '--report needs a value (daily or monthly)',
561
+ 'opt.reportBad': 'bad --report value {value} (daily or monthly)',
546
562
  'opt.byMissing': '--by needs a value (tool, model or project)',
547
563
  'opt.byBad': 'bad --by value {value} (tool, model or project)',
548
564
  'opt.daysMissing': '--days needs a value (number of days)',
549
565
  'opt.daysBad': 'bad --days value {value} (a whole number above 0)',
550
- 'opt.reportOnly': '--by and --days only work with --report',
566
+ 'opt.monthsMissing': '--months needs a value (number of months)',
567
+ 'opt.monthsBad': 'bad --months value {value} (a whole number above 0)',
568
+ 'opt.daysDaily': '--days only works with --report daily (use --months for monthly)',
569
+ 'opt.monthsMonthly': '--months only works with --report monthly (use --days for daily)',
570
+ 'opt.reportOnly': '--by, --days and --months only work with --report',
551
571
 
552
572
  'report.title': 'Daily usage, last {n} days ({from} to {to}), {by}, API list price',
553
573
  'report.by.tool': 'by tool',
@@ -562,6 +582,13 @@ export const STRINGS = {
562
582
  'report.partial': 'Could not read all logs within the time limit, so this is partial. Run again to continue',
563
583
  'report.progress': 'Reading usage logs {pct}% ({s}s)',
564
584
  'report.capped': '--days is limited to the {n} days the ledger keeps, using {n}',
585
+ 'report.cappedMonths': '--months is limited to the {n} months the archive keeps, using {n}',
586
+ 'report.titleMonthly': 'Monthly usage, last {n} months ({from} to {to}), {by}, API list price',
587
+ 'report.month': 'Month',
588
+ 'report.missing': 'no data',
589
+ 'report.noteCurrent': '* this month (still in progress)',
590
+ 'report.notePartial': '~ only some days were counted (older logs were deleted or the archive was empty then)',
591
+ 'report.noteMissing': 'no data: neither logs nor the archive cover this month (unknown, not zero)',
565
592
 
566
593
  'cfg.notFile': 'config file is not a regular file, not reading it',
567
594
  'cfg.tooBig': 'config file is over {kb}KB, not reading it',
package/src/log.mjs CHANGED
@@ -4,7 +4,8 @@
4
4
  // 꺼져 있으면 파일을 만들지 않고 debug() 는 바로 돌아간다.
5
5
  import { closeSync, constants, fchmodSync, fstatSync, mkdirSync, openSync, renameSync, statSync, writeSync } from 'node:fs';
6
6
  import { homedir } from 'node:os';
7
- import { basename, dirname, isAbsolute, join } from 'node:path';
7
+ import { basename, dirname, posix, win32 } from 'node:path';
8
+ import { appDir } from './paths.mjs';
8
9
  import { mask, stripControl } from './text.mjs';
9
10
 
10
11
  // 이 크기를 넘으면 aitop.log.1 로 옮기고 새로 쓴다 (이전 것 하나만 남긴다).
@@ -14,9 +15,9 @@ export const MAX_BYTES = 1024 * 1024;
14
15
  export const REPEAT_MS = 60_000;
15
16
  const MAX_KEYS = 1000;
16
17
 
17
- export function logPath(env = process.env, home = homedir()) {
18
- const xdg = env.XDG_STATE_HOME;
19
- return join(xdg && isAbsolute(xdg) ? xdg : join(home, '.local', 'state'), 'aitop', 'aitop.log');
18
+ // Windows 는 XDG_STATE_HOME 이 없으면 %LOCALAPPDATA%\aitop\state\aitop.log.
19
+ export function logPath(env = process.env, home = homedir(), platform = process.platform) {
20
+ return (platform === 'win32' ? win32 : posix).join(appDir('state', { env, home, platform }), 'aitop.log');
20
21
  }
21
22
 
22
23
  let state = { on: false, path: null };
@@ -0,0 +1,273 @@
1
+ // 월별 보관함 (--report monthly, #164). 장부(캐시)는 버전·가격표가 바뀌면 통째로 버려지고, 원본 기록도 도구가 오래되면 지운다.
2
+ // 그래서 지난 날의 합계를 캐시 루트의 monthly.json 에 달(YYYY-MM)별로 접어 12개월 남긴다 (버전 폴더 밖, summary.json 과 같은 자리).
3
+ //
4
+ // 한 번만 세기: since~through 의 날은 모두 보관함에 접혀 있다. 리포트는 through 까지는 보관함에서, through 다음 날부터는
5
+ // 살아 있는 장부에서 센다. 장부를 처음부터 다시 세도(버전·가격 변경) through 이전 날은 보관함 값만 쓰므로 두 번 더해지지 않는다.
6
+ // 접을 때는 [lo, hi] 를 빠짐없이 읽은 장부만 받고, 이미 [since, through] 에 든 날은 건너뛴다.
7
+ // 새 범위가 [since, through] 와 이어지지 않으면(사이가 빈다) 접지 않는다 (1년치를 다시 읽은 때만 빈 날을 holes 에 적고 접는다).
8
+ // from: 이 날부터는 빠짐없이 셌다 (그 앞은 기록이 지워졌을 수 있어 '일부' 로 보인다). holes 의 날도 '일부' 다.
9
+ //
10
+ // 여러 aitop 이 함께 써도 파일 하나에는 늘 "since~through 의 합" 만 들어 있다: 쓰기 전에 다시 읽어 rev 가 바뀌었으면 쓰지 않고
11
+ // (다음 기회에 다시 접는다), pid 별 임시 파일에 쓴 뒤 rename 한다.
12
+ //
13
+ // 값마다 사용량 벡터(입력·출력·캐시 읽기·캐시 쓰기 5분·1시간, fast 모드는 따로)를 남겨, 가격표가 바뀌면 지금 가격으로 다시 계산한다.
14
+ import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'node:fs';
15
+ import { dirname, join } from 'node:path';
16
+ import { CACHE_ROOT } from './cache.mjs';
17
+ import { PRICE_TAG, vecCost } from './pricing.mjs';
18
+ import { dayKey } from './sources/common.mjs';
19
+ import { debug, debugIo } from './log.mjs';
20
+
21
+ export const V = 1;
22
+ export const ARCHIVE_FILE = join(CACHE_ROOT, 'monthly.json');
23
+ // 남기는 달 수 (이번 달 포함).
24
+ export const KEEP_MONTHS = 12;
25
+ // 갱신이 실패한 agy 기록 때문에 접기가 이만큼 넘게 밀리면, 그 기록을 빼고 접고 그 날들을 '일부' 로 적는다.
26
+ export const STALE_MAX_DAYS = 7;
27
+ // 오늘·어제는 아직 늦게 쓰이는 줄(자정을 넘긴 응답, agy 의 늦은 기록)이 있을 수 있어 그제까지만 접는다.
28
+ export const LAG_DAYS = 2;
29
+
30
+ const DAY = /^\d{4}-\d\d-\d\d$/;
31
+ const MONTH = /^\d{4}-\d\d$/;
32
+
33
+ // 날짜 키 산술 (로컬 정오 기준이라 서머타임에도 하루씩 움직인다).
34
+ const atNoon = (key) => {
35
+ const [y, m, d] = key.split('-').map(Number);
36
+ return new Date(y, m - 1, d, 12);
37
+ };
38
+ export const addDays = (key, n) => {
39
+ const d = atNoon(key);
40
+ d.setDate(d.getDate() + n);
41
+ return dayKey(d.getTime());
42
+ };
43
+ export const monthOf = (key) => key.slice(0, 7);
44
+
45
+ // 이번 달부터 거꾸로 n 달 (YYYY-MM).
46
+ export function lastMonths(n, now = Date.now()) {
47
+ const d = new Date(now);
48
+ const out = [];
49
+ for (let i = 0; i < n; i++) {
50
+ const x = new Date(d.getFullYear(), d.getMonth() - i, 1, 12);
51
+ out.push(dayKey(x.getTime()).slice(0, 7));
52
+ }
53
+ return out;
54
+ }
55
+
56
+ // 보관함이 남기는 가장 오래된 날 (12개월 전 달의 1일).
57
+ export const keepFrom = (now = Date.now()) => `${lastMonths(KEEP_MONTHS, now).at(-1)}-01`;
58
+ // 접을 수 있는 가장 최근 날.
59
+ export const foldHi = (now = Date.now()) => dayKey(now - LAG_DAYS * 86400_000);
60
+ // 그 달의 마지막 날.
61
+ export const monthEnd = (month) => {
62
+ const [y, m] = month.split('-').map(Number);
63
+ return dayKey(new Date(y, m, 0, 12).getTime());
64
+ };
65
+
66
+ export const emptyArchive = () => ({ v: V, rev: 0, price: PRICE_TAG, since: null, from: null, through: null, backfilled: null, holes: [], months: {} });
67
+
68
+ const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
69
+ const isVec = (x) => Array.isArray(x) && x.every(isNum);
70
+ const validEntry = (e) => e && typeof e.t === 'string' && typeof e.m === 'string' && (e.p == null || typeof e.p === 'string') && isNum(e.n) && isNum(e.c) && (e.u == null || isVec(e.u)) && (e.f == null || isVec(e.f));
71
+ function valid(a) {
72
+ if (!a || typeof a !== 'object' || !Number.isInteger(a.rev)) return false;
73
+ for (const k of ['since', 'from', 'through', 'backfilled']) if (a[k] != null && !(typeof a[k] === 'string' && DAY.test(a[k]))) return false;
74
+ if ((a.since == null) !== (a.through == null) || (a.from == null) !== (a.through == null)) return false;
75
+ // holes: [첫날, 끝날] 또는 [첫날, 끝날, 빠진 도구]. 남는 칸은 무시한다.
76
+ if (!Array.isArray(a.holes) || !a.holes.every((h) => Array.isArray(h) && h.length >= 2 && DAY.test(h[0]) && DAY.test(h[1]))) return false;
77
+ if (!a.months || typeof a.months !== 'object') return false;
78
+ return Object.entries(a.months).every(([k, list]) => MONTH.test(k) && Array.isArray(list) && list.every(validEntry));
79
+ }
80
+
81
+ // 가격표가 바뀌었으면 벡터로 지금 가격을 다시 매긴다. 가격표에서 모델이 사라졌으면 예전 비용을 그대로 둔다.
82
+ function reprice(a) {
83
+ if (a.price === PRICE_TAG) return a;
84
+ for (const [month, list] of Object.entries(a.months)) {
85
+ const at = Date.parse(`${month}-15T12:00:00Z`);
86
+ for (const e of list) {
87
+ if (!e.u && !e.f) continue;
88
+ const c = vecCost(e.t, e.m, e.u, e.f, at);
89
+ if (c == null) continue;
90
+ e.c = c;
91
+ delete e.x;
92
+ }
93
+ }
94
+ a.price = PRICE_TAG;
95
+ return a;
96
+ }
97
+
98
+ // { archive, state }. state: ok, missing(없음), corrupt(깨짐, 옆으로 옮기고 빈 보관함), newer(더 새 형식: 읽지도 쓰지도 않는다, archive null).
99
+ export function readArchive(file = ARCHIVE_FILE) {
100
+ let raw;
101
+ try {
102
+ raw = readFileSync(file, 'utf8');
103
+ } catch (e) {
104
+ if (e.code !== 'ENOENT') debugIo('monthly', 'archive read failed', e);
105
+ return { archive: emptyArchive(), state: 'missing' };
106
+ }
107
+ let a = null;
108
+ try {
109
+ a = JSON.parse(raw);
110
+ } catch {}
111
+ if (a && Number.isInteger(a.v) && a.v > V) return { archive: null, state: 'newer' };
112
+ if (a?.v === V && valid(a)) return { archive: reprice(a), state: 'ok' };
113
+ // 지우지 않고 옆으로 옮겨 둔다 (사용자 기록이라 손으로 살릴 수 있게).
114
+ try {
115
+ renameSync(file, `${file}.bad-${Date.now()}`);
116
+ } catch (e) {
117
+ debugIo('monthly', 'archive move aside failed', e);
118
+ }
119
+ return { archive: emptyArchive(), state: 'corrupt' };
120
+ }
121
+
122
+ // 지금 파일의 rev (없으면 0, 읽을 수 없으면 null).
123
+ function revOf(file) {
124
+ try {
125
+ const a = JSON.parse(readFileSync(file, 'utf8'));
126
+ return a?.v === V && Number.isInteger(a.rev) ? a.rev : null;
127
+ } catch (e) {
128
+ return e.code === 'ENOENT' ? 0 : null;
129
+ }
130
+ }
131
+
132
+ // 읽은 뒤(rev = base) 아무도 쓰지 않았을 때만 쓴다. 썼으면 true.
133
+ export function writeArchive(a, base, file = ARCHIVE_FILE) {
134
+ if (revOf(file) !== base) return false;
135
+ const tmp = `${file}.${process.pid}.tmp`;
136
+ try {
137
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
138
+ writeFileSync(tmp, JSON.stringify({ ...a, v: V, rev: base + 1, price: PRICE_TAG }), { mode: 0o600 });
139
+ // 임시 파일을 쓰는 사이에 다른 쪽이 썼으면 버린다. 이 확인과 rename 사이에 다른 쪽이 rename 하면 그쪽 접기가
140
+ // 덮여 사라질 수 있다 (lost update). 그래도 남는 파일은 이쪽의 since~through 합이라 두 번 세지 않고, 사라진 날은
141
+ // 아직 장부 창 안(그제 근처)이라 다음 접기 때 다시 접힌다.
142
+ if (revOf(file) !== base) {
143
+ rmSync(tmp, { force: true });
144
+ return false;
145
+ }
146
+ renameSync(tmp, file);
147
+ a.rev = base + 1;
148
+ return true;
149
+ } catch (e) {
150
+ debugIo('monthly', 'archive write failed', e);
151
+ try {
152
+ rmSync(tmp, { force: true });
153
+ } catch {}
154
+ return false;
155
+ }
156
+ }
157
+
158
+ // books 의 날짜별 장부를 [lo, hi] 안의 날만 보관함 a 에 접는다 (a 를 고친다). books: [{ tool, project, days }].
159
+ // 부르는 쪽은 [lo, hi] 의 날을 빠짐없이 읽은 장부만 넘긴다. 이미 [since, through] 에 든 날은 건너뛴다.
160
+ // complete: 이 날부터는 원본 기록이 다 남아 있다 (기본 lo). 1년치를 다시 읽을 때 Claude 기록이 지워진 앞쪽을 가른다.
161
+ // gap: 사이가 비면 'hole'(빈 날을 holes 에 적고 접는다) 또는 'refuse'(접지 않는다).
162
+ // 돌려주는 값: 'folded', 'none'(더 접을 날 없음), 'gap'.
163
+ // extraHoles: 이번에 접는 날 중 일부만 센 범위 (staleCut 이 뺀 agy 기록 등).
164
+ export function foldInto(a, books, { lo, hi, complete = lo, now = Date.now(), gap = 'refuse', extraHoles = [] }) {
165
+ const keep = keepFrom(now);
166
+ if (lo < keep) lo = keep;
167
+ if (complete < lo) complete = lo;
168
+ if (hi < lo) return 'none';
169
+ const holes = [];
170
+ // 이번에 새로 접는 범위 (이미 접은 [since, through] 밖).
171
+ const fresh = a.through == null ? [[lo, hi]] : [[lo, addDays(a.since, -1)], [addDays(a.through, 1), hi]];
172
+ if (a.through != null) {
173
+ if (lo >= a.since && hi <= a.through) return 'none';
174
+ const after = addDays(a.through, 1);
175
+ if (hi < addDays(a.since, -1) || (lo > after && gap !== 'hole')) return 'gap';
176
+ // 빈 날, 그리고 원본 기록이 덜 남은 앞쪽과 원래 빠짐없던 날 사이는 '일부' 다.
177
+ const end = lo > complete ? lo : complete;
178
+ if (end > after) holes.push([after, addDays(end, -1)]);
179
+ }
180
+ const has = (d) => a.through != null && d >= a.since && d <= a.through;
181
+ const index = new Map();
182
+ const slot = (month, t, m, p) => {
183
+ const key = `${month}\t${t}\t${m}\t${p ?? ''}`;
184
+ let e = index.get(key);
185
+ if (!e) {
186
+ const list = (a.months[month] ??= []);
187
+ e = list.find((x) => x.t === t && x.m === m && (x.p ?? null) === (p ?? null));
188
+ if (!e) list.push((e = { t, m, p: p ?? null, n: 0, c: 0 }));
189
+ index.set(key, e);
190
+ }
191
+ return e;
192
+ };
193
+ for (const { tool, project, days } of books)
194
+ for (const [d, day] of Object.entries(days ?? {})) {
195
+ if (d < lo || d > hi || has(d)) continue;
196
+ const models = day.models && Object.keys(day.models).length ? day.models : { unknown: { tokens: day.tokens, cost: day.cost, unknown: day.unknown } };
197
+ for (const [model, x] of Object.entries(models)) {
198
+ if (!(x.tokens > 0) && !(x.cost > 0)) continue;
199
+ const e = slot(monthOf(d), tool, model, project);
200
+ e.n += x.tokens;
201
+ e.c += x.cost;
202
+ if (x.unknown) e.x = 1;
203
+ for (const k of ['u', 'f']) if (x[k]) e[k] = (e[k] ?? [0, 0, 0, 0, 0]).map((v, i) => v + (x[k][i] ?? 0));
204
+ }
205
+ }
206
+ if (a.through == null) {
207
+ a.since = lo;
208
+ a.from = complete;
209
+ a.through = hi;
210
+ } else {
211
+ // 앞으로 넓혔으면 from 도 앞당긴다 (complete 가 원래 from 보다 늦으면 그 사이는 위에서 holes 로 적었다).
212
+ if (lo < a.since && complete < a.from) a.from = complete;
213
+ if (lo < a.since) a.since = lo;
214
+ if (hi > a.through) a.through = hi;
215
+ }
216
+ // 이번에 새로 접은 날만 적는다 (이미 접은 날에 겹쳐 쌓이지 않게).
217
+ for (const [x, y, tool] of extraHoles)
218
+ for (const [p, q] of fresh) {
219
+ const from = x > p ? x : p;
220
+ const to = y < q ? y : q;
221
+ if (from <= to) holes.push(tool ? [from, to, tool] : [from, to]);
222
+ }
223
+ a.holes.push(...holes.filter(([x, y]) => x <= y));
224
+ // 12개월보다 오래된 달은 버린다.
225
+ const keepMonth = monthOf(keep);
226
+ for (const k of Object.keys(a.months)) if (k < keepMonth) delete a.months[k];
227
+ a.holes = a.holes.filter(([, to]) => to >= keep);
228
+ if (a.since < keep) a.since = keep;
229
+ if (a.from < keep) a.from = keep;
230
+ if (a.from > a.through) a.from = addDays(a.through, 1);
231
+ return 'folded';
232
+ }
233
+
234
+ // 갱신이 실패한 agy 기록(book.staleFrom)이 있을 때 접을 범위. 그 기록이 쓰였을 수 있는 첫날 전날까지만 접는다.
235
+ // 그렇게 STALE_MAX_DAYS 넘게 밀리면, 그 기록은 staleFrom 앞의 날(마지막으로 다 읽은 정상 값)만 남겨 hi 까지 접고
236
+ // 빠졌을 수 있는 범위를 holes 로 남긴다 (Claude·Codex 몫이 지워지기 전에).
237
+ export function staleCut(books, hi) {
238
+ const stale = books.filter((b) => b.staleFrom && b.staleFrom <= hi);
239
+ if (!stale.length) return { books, hi, holes: [] };
240
+ const first = stale.reduce((x, b) => (b.staleFrom < x ? b.staleFrom : x), hi);
241
+ const cut = addDays(first, -1);
242
+ if (cut >= addDays(hi, -STALE_MAX_DAYS)) {
243
+ debug('monthly', 'fold held back: an agy log failed to update', null, `${first}`);
244
+ return { books, hi: cut, holes: [] };
245
+ }
246
+ debug('monthly', 'fold skipped failing agy logs, days marked partial', null, `${first}`);
247
+ const trim = (b) => ({ ...b, days: Object.fromEntries(Object.entries(b.days ?? {}).filter(([k]) => k < b.staleFrom)) });
248
+ return { books: books.map((b) => (stale.includes(b) ? trim(b) : b)), hi, holes: [[first, hi, 'agy']] };
249
+ }
250
+
251
+ // 읽고, 접고, 쓴다. attach: 장부에 project 를 붙이는 함수 (projects.mjs attachProjects).
252
+ // 돌려주는 값: 'folded', 'none', 'gap', 'newer', 'busy'(다른 aitop 이 먼저 썼다), 'error'.
253
+ export function foldArchive(books, { lo, hi, complete = lo, now = Date.now(), gap = 'refuse', backfilled = false, attach = (b) => b, file = ARCHIVE_FILE } = {}) {
254
+ const { archive: a, state } = readArchive(file);
255
+ if (state === 'newer') return 'newer';
256
+ const cut = staleCut(books, hi);
257
+ books = cut.books;
258
+ hi = cut.hi;
259
+ // 접을 날이 없으면 프로젝트를 찾지도 않는다 (평소 화면은 대개 여기서 끝난다).
260
+ if (a.through != null && lo >= a.since && hi <= a.through && !backfilled) return 'none';
261
+ const base = a.rev;
262
+ let r;
263
+ try {
264
+ r = foldInto(a, attach(books), { lo, hi, complete, now, gap, extraHoles: cut.holes });
265
+ } catch (e) {
266
+ debugIo('monthly', 'archive fold failed', e);
267
+ return 'error';
268
+ }
269
+ if (r === 'gap') return r;
270
+ if (backfilled) a.backfilled = dayKey(now);
271
+ else if (r === 'none') return r;
272
+ return writeArchive(a, base, file) ? r : 'busy';
273
+ }
package/src/order.mjs CHANGED
@@ -5,6 +5,7 @@
5
5
  // 고정(p)한 세션은 응답 대기 바로 아래에 고정한 순서대로 둔다. 정렬을 바꿔도 그 순서는 바뀌지 않고, 묶을 때는 '고정' 묶음 하나로 모은다.
6
6
  // 응답 대기를 고정보다 위에 두는 것은 사람이 할 일이 고정 목록에 가려지지 않게 하려는 것이다. 고정한 세션이 응답 대기가 되면 대기 쪽으로 올라간다.
7
7
  import { costOf } from './ui/draw.mjs';
8
+ import { lastName } from './paths.mjs';
8
9
 
9
10
  export const SORTS = ['default', 'cost', 'context', 'recent'];
10
11
  export const GROUPS = ['none', 'project', 'tool'];
@@ -41,7 +42,7 @@ export function compare(sort, costMode = 'api', ready = true) {
41
42
  return (a, b) => ended(a) - ended(b) || key(b, costMode) - key(a, costMode);
42
43
  }
43
44
 
44
- const projectOf = (s) => s.project || String(s.cwd ?? '').split('/').filter(Boolean).at(-1) || NO_FOLDER;
45
+ const projectOf = (s) => s.project || lastName(s.cwd) || NO_FOLDER;
45
46
  const GROUP_KEY = { project: projectOf, tool: (s) => s.tool ?? '?' };
46
47
 
47
48
  // 돌려주는 sessions 는 화면에 그리는 순서 그대로다 (↑↓·n 도 이 순서를 따른다).